问:
Why does PlaceAutocompleteFragment crashes with NoSuchMethodError?
I am trying to find place from Google map in my android
my code is

```<code>PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
            getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            // TODO: Get info about the selected place.
            Log.i(TAG, "Place: " + place.getName());

            String placeDetailsStr = place.getName() + "\n"
                    + place.getId() + "\n"
                    + place.getLatLng().toString() + "\n"
                    + place.getAddress() + "\n"
                    + place.getAttributions();
        }

        @Override
        public void onError(Status status) {
            // TODO: Handle the error.
            Log.i(TAG, "An error occurred: " + status);
        }
    });
</code>```

but when I try to enter something it crashes with error

```<code>FATAL EXCEPTION: main                                                    Process: com.example.asset.lab13_bonus, PID: 1192
                                                                         java.lang.NoSuchMethodError: No virtual method zzbo(Landroid/content/Context;)V in class Lcom/google/android/gms/common/GoogleApiAvailability; or its super classes (declaration of 'com.google.android.gms.common.GoogleApiAvailability' appears in /data/app/com.example.asset.lab13_bonus-bAk1S6P8t8HToIo1FR8JeA==/split_lib_dependencies_apk.apk:classes12.dex)
                                                                             at com.google.android.gms.location.places.ui.zza$zza.build(Unknown Source:79)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocomplete$IntentBuilder.build(Unknown Source:0)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocompleteFragment.zzboi(Unknown Source:42)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocompleteFragment.zza(Unknown Source:0)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocompleteFragment$1.onClick(Unknown Source:2)
                                                                             at android.view.View.performClick(View.java:6256)
                                                                             at android.view.View$PerformClick.run(View.java:24697)
                                                                             at android.os.Handler.handleCallback(Handler.java:789)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                             at android.os.Looper.loop(Looper.java:164)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

Gradle dependencies :

```<code>compile 'com.google.android.gms:play-services-maps:11.0.4'
compile 'com.google.android.gms:play-services-places:9.4.0'
compile "com.google.android.gms:play-services-base:9.4.0"
</code>```

what does this mean ?
Can someone help me?
May be it does not work because of device?

答:
try this,</p>

```<code>compile 'com.google.android.gms:play-services-maps:9.4.0'
compile 'com.google.android.gms:play-services-places:9.4.0'
compile "com.google.android.gms:play-services-base:9.4.0"
</code>```

Body:
I am trying to find place from Google map in my android
my code is

PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
            getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            // TODO: Get info about the selected place.
            Log.i(TAG, "Place: " + place.getName());

            String placeDetailsStr = place.getName() + "\n"
                    + place.getId() + "\n"
                    + place.getLatLng().toString() + "\n"
                    + place.getAddress() + "\n"
                    + place.getAttributions();
        }

        @Override
        public void onError(Status status) {
            // TODO: Handle the error.
            Log.i(TAG, "An error occurred: " + status);
        }
    });

but when I try to enter something it crashes with error

FATAL EXCEPTION: main                                                    Process: com.example.asset.lab13_bonus, PID: 1192
                                                                         java.lang.NoSuchMethodError: No virtual method zzbo(Landroid/content/Context;)V in class Lcom/google/android/gms/common/GoogleApiAvailability; or its super classes (declaration of 'com.google.android.gms.common.GoogleApiAvailability' appears in /data/app/com.example.asset.lab13_bonus-bAk1S6P8t8HToIo1FR8JeA==/split_lib_dependencies_apk.apk:classes12.dex)
                                                                             at com.google.android.gms.location.places.ui.zza$zza.build(Unknown Source:79)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocomplete$IntentBuilder.build(Unknown Source:0)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocompleteFragment.zzboi(Unknown Source:42)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocompleteFragment.zza(Unknown Source:0)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocompleteFragment$1.onClick(Unknown Source:2)
                                                                             at android.view.View.performClick(View.java:6256)
                                                                             at android.view.View$PerformClick.run(View.java:24697)
                                                                             at android.os.Handler.handleCallback(Handler.java:789)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                             at android.os.Looper.loop(Looper.java:164)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Gradle dependencies :

compile 'com.google.android.gms:play-services-maps:11.0.4'
compile 'com.google.android.gms:play-services-places:9.4.0'
compile "com.google.android.gms:play-services-base:9.4.0"

what does this mean ?
Can someone help me?
May be it does not work because of device?

Body:
try this,

compile 'com.google.android.gms:play-services-maps:9.4.0'
compile 'com.google.android.gms:play-services-places:9.4.0'
compile "com.google.android.gms:play-services-base:9.4.0"


来源: stackexchange

问:
AWS CloudFront and ELB: Is there a way to force connection using only CloudFront?
I have an ELB which balances some EC2 instances.
The ELB exposes the endpoints of the entire system.

Now I am creating a CloudFront distribution over this ELB.
Is there a way to allow users to connect ONLY using CloudFront endpoint and refuse direct connections to ELB?

Thanks

答:
You can set up a automated security group that only allows Cloudfront IP's and let a Lambda function to update it when Cloudfront IP ranges change. On my blog post, you can find a complete Cloudformation template that will set this up for you:

https://medium.com/cagataygurturk/restricting-elb-access-to-cloudfront-8b0990dea69f

ContentLicense: CC BY-SA 3.0


问:
Declaring variables and select statement in a procedure
I'm writing a SQL procedure which should use calculated date stored as a local variable in a select statement. I'm using Oracle SQL developer. My code is:

```<code>create or replace PROCEDURE
                                   my_procedure
AS
BEGIN
DECLARE
  l_max_dt  DATE;
BEGIN
 SELECT MAX(TRX_DT)
 INTO   l_max_dt
 FROM   TABLE
 WHERE 1=1;
end;
 select * from TABLE where trx_dt = l_max_dt;
end;
</code>```

This code gives me an error : " Error(14,48): PL/SQL: ORA-00904: "L_MAX_DT": invalid identifier" when select statement is present.
How can I store variables to use them in statements?

答:
Your issue is one of scope. In your procedure, you have a nested block, in which you declare the l_max_dt variable. Once the code has exited that block, the l_max_dt variable is no longer in scope - i.e. the outer block does not know anything about it.

There is no need to have a nested block in this instance - you can do it all in the same block, like so:

```<code>create or replace PROCEDURE my_procedure
AS
  l_max_dt  DATE;
BEGIN
  SELECT MAX(TRX_DT)
  INTO   l_max_dt
  FROM   TABLE
  WHERE 1=1;

--  commented out as this isn't valid syntax; there is a missing INTO clause
--  select *
--  from TABLE where trx_dt = l_max_dt;
END my_procedure;
</code>```

However, you could simply do the query in one fell swoop - e.g.:

```<code>select *
from   your_table
where  trx_dt = (select max(trx_dt) from your_table);
</code>```

A couple of points about your procedure:

In PL/SQL, if you use an implicit cursor (i.e. when you put a select statement directly in the body of the code) you need to have something to put the results into. You could bulk collect the results into an array, or you could ensure that you will receive exactly one row (or code error handling for NO_DATA_FOUND and TOO_MANY_ROWS) into a record or corresponding scalar variables.

You shouldn't use select * in your procedure - instead, you should explicitly state the columns being returned, because someone adding a column to that table could cause your procedure to error. There are exceptions to this "rule", but explicitly stating the columns is a good habit to get into.

Body:
I'm writing a SQL procedure which should use calculated date stored as a local variable in a select statement. I'm using Oracle SQL developer. My code is:

create or replace PROCEDURE
                                   my_procedure
AS
BEGIN
DECLARE
  l_max_dt  DATE;
BEGIN
 SELECT MAX(TRX_DT)
 INTO   l_max_dt
 FROM   TABLE
 WHERE 1=1;
end;
 select * from TABLE where trx_dt = l_max_dt;
end;

This code gives me an error : " Error(14,48): PL/SQL: ORA-00904: "L_MAX_DT": invalid identifier" when select statement is present.
How can I store variables to use them in statements?

Body:
Your issue is one of scope. In your procedure, you have a nested block, in which you declare the l_max_dt variable. Once the code has exited that block, the l_max_dt variable is no longer in scope - i.e. the outer block does not know anything about it.

There is no need to have a nested block in this instance - you can do it all in the same block, like so:

create or replace PROCEDURE my_procedure
AS
  l_max_dt  DATE;
BEGIN
  SELECT MAX(TRX_DT)
  INTO   l_max_dt
  FROM   TABLE
  WHERE 1=1;

--  commented out as this isn't valid syntax; there is a missing INTO clause
--  select *
--  from TABLE where trx_dt = l_max_dt;
END my_procedure;

However, you could simply do the query in one fell swoop - e.g.:

select *
from   your_table
where  trx_dt = (select max(trx_dt) from your_table);

A couple of points about your procedure:

In PL/SQL, if you use an implicit cursor (i.e. when you put a select statement directly in the body of the code) you need to have something to put the results into. You could bulk collect the results into an array, or you could ensure that you will receive exactly one row (or code error handling for NO_DATA_FOUND and TOO_MANY_ROWS) into a record or corresponding scalar variables.

You shouldn't use select * in your procedure - instead, you should explicitly state the columns being returned, because someone adding a column to that table could cause your procedure to error. There are exceptions to this "rule", but explicitly stating the columns is a good habit to get into.


问:
Kentor AuthServices/Owin - handling the response from the identity provider
I have a working configuration to authenticate against Azure AD using KentorAuthServices & Owin, but I need to know some basic information about the user that has just logged in.  When I used WSFed as the authentication service I could simply handle the SecurityTokenValidated notification as per below.  How do I do similarly with KentorAuthServices? I don't see an appropriate notification to pull this information.  All I need is the username/email address the user logged in with.

```<code>Notifications = new WsFederationAuthenticationNotifications
            {
                SecurityTokenValidated = context =>
                {
                    string username = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value;

                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(60), true, "");
                    String encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                    context.Response.Cookies.Append(FormsAuthentication.FormsCookieName, encryptedTicket);
                    return Task.FromResult(0);
                }
            }
</code>```

ETA: Doing some more digging I believe AcsCommandResultCreated is the notification that I want to hook into - but this never fires?

答:
All the information in the SAML Response is converted to claims in the resulting identity. If you are using the default template with ASP.Net Identity you can access the external identity in the ExternalLoginCallback action on the AccountController.

The AcsCommandResultCreated notification should definitely be fired on a sucessful login. Try enable the Katana logging and see if the login sequence is aborted due to an error.

Body:
I have a working configuration to authenticate against Azure AD using KentorAuthServices & Owin, but I need to know some basic information about the user that has just logged in.  When I used WSFed as the authentication service I could simply handle the SecurityTokenValidated notification as per below.  How do I do similarly with KentorAuthServices? I don't see an appropriate notification to pull this information.  All I need is the username/email address the user logged in with.

Notifications = new WsFederationAuthenticationNotifications
            {
                SecurityTokenValidated = context =>
                {
                    string username = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value;

                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(60), true, "");
                    String encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                    context.Response.Cookies.Append(FormsAuthentication.FormsCookieName, encryptedTicket);
                    return Task.FromResult(0);
                }
            }

ETA: Doing some more digging I believe AcsCommandResultCreated is the notification that I want to hook into - but this never fires?


问:
else if and elif not working for my python code
This is my first day of learning to code. I tried this code and do not know why did it fail. Any help is much appreciated:

```<code>a=int(input())

if a>10:
    print("your number is greater than 10")
    else:
</code>```

I get SyntaxError: invalid syntax

答:
You have an indentation error:

```<code>if condition:
    code...
elif condition:
    another code...
else:
    last code...
</code>```

Where the elif and else parts are optional, and elif means else: if condition:.

PS: Use int(input()) otherwise you would get an string but no an int.

Body:
This is my first day of learning to code. I tried this code and do not know why did it fail. Any help is much appreciated:

a=int(input())

if a>10:
    print("your number is greater than 10")
    else:

I get SyntaxError: invalid syntax

Body:
You have an indentation error:

if condition:
    code...
elif condition:
    another code...
else:
    last code...

Where the elif and else parts are optional, and elif means else: if condition:.

PS: Use int(input()) otherwise you would get an string but no an int.


问:
NSJSONSerialization adding \n to beginning and end of JSON string
I have an iOS application that needs to post some information to the server in json format. In particular, I need to pick up an NSArray of Strings and convert it into a NSString in json format. I am using the following code to create the string:

```<code>NSData *jsonData = [NSJSONSerialization dataWithJSONObject:_selectedStyles options:NSJSONReadingMutableContainers error:&error];
    if(error){
        //TODO: handle error
    }
NSString *selectedStylesInJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
</code>```

However, the string that comes out of that is the following:

```<code>@"[\n  \"schlager\",\n  \"volkstuemlicherSchlager\"\n]"
</code>```

As you can see, the NSJSONSerialization method is inserting a \n before and after every string in the array, which is incorrect.

How can I make iOS convert this array in the correct format? The format I am looking for is:

```<code>["object 1", "object 2"]
</code>```

答:
Use
[NSJSONSerialization dataWithJSONObject:self options:0 error:nil];
[NSJSONSerialization dataWithJSONObject:self options:kNilOptions
 error:nil];

If that option is not set, the most compact possible JSON will be generated. If an error occurs, the error parameter will be set and the return value will be nil. The resulting data is a encoded in UTF-8.

Come from Apple Document.

Body:
I have an iOS application that needs to post some information to the server in json format. In particular, I need to pick up an NSArray of Strings and convert it into a NSString in json format. I am using the following code to create the string:

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:_selectedStyles options:NSJSONReadingMutableContainers error:&error];
    if(error){
        //TODO: handle error
    }
NSString *selectedStylesInJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

However, the string that comes out of that is the following:

@"[\n  \"schlager\",\n  \"volkstuemlicherSchlager\"\n]"

As you can see, the NSJSONSerialization method is inserting a \n before and after every string in the array, which is incorrect.

How can I make iOS convert this array in the correct format? The format I am looking for is:

["object 1", "object 2"]


问:
File synchronization between c# application (.NET) and microsoft server
I am currently writing a c# application that includes file synchronization so that files can be provided for other clients and used offline. I thought of using the Microsoft File Sync Framework (.NET) to take care about the synchronization itself: https://msdn.microsoft.com/en-us/library/mt763483

We do have a MS server 2016 that could be used as a file server by creating a public share, but I am not sure if this is the correct way to do it (referring to security). I was also thinking about using (s)FTP or WebDAV to provide the files in order to have a secure connection. Is there a best practice how to do file synchronization in c# applications over the internet using a microsoft server without implementing your own server application?

Thanks in advance.

答: Using WebDAV finally worked great for me.</p>


问:
Uncaught TypeError: Cannot read property 'mountComponent' of undefined error when running create-react-app build version

Steps to Reproduce

My create-react-app works fine on development mode, but it is blank page when I run the built one using (npm run build) with this console error.

```<code>Uncaught TypeError: Cannot read property 'mountComponent' of undefined
    at r (patchUtils.js:51)
    at e.exports (reactPatches.js:41)
    at react.js:59
    at Object.ready (reactInternals.js:24)
    at r (react.js:58)
    at Object.<anonymous> (index.js:12)
    at t (bootstrap 3c1adc8fa04e423f7356:19)
    at Object.<anonymous> (main.448e9d91.js:66458)
    at t (bootstrap 3c1adc8fa04e423f7356:19)
    at bootstrap 3c1adc8fa04e423f7356:62
    at bootstrap 3c1adc8fa04e423f7356:62
</code>```

I didn't change any create-react-app config. One thing I'm suspecting is this part of code and the structure.

```<code>class SocialIntegrator extends React.Component {
  static propTypes = { children: PropTypes.node.isRequired };

  componentDidMount = () => {
    if (!initialized) {
      initialized = true;

      installFacebookSdk();
      installPinterest();
      installTwitter();
    }
  };

  render = () => React.Children.only(this.props.children);
}

export default SocialIntegrator;
</code>```

Here's App.js .

```<code>import React from "react";
import { Provider } from "react-redux";
import { BrowserRouter as Router, Switch } from "react-router-dom";
import PageLayoutRoute from "components/controls/PageLayoutRoute";
import { SocialIntegrator } from "components/Social";
import { createStore } from "store";
import routes from "components/routes";
import HomePage from "components/HomePage";
import StudioPage from "components/StudioPage";
import FramingPage from "components/FramingPage";
import OrderReviewPage from "components/OrderReviewPage";
import OrderConfirmationPage from "components/OrderConfirmationPage";
import { injectGlobal } from "styled-components";
injectGlobal`
  html {
    overflow-y: auto;
  }
`;
const store = createStore();

const App = () =>
  <SocialIntegrator>
    <Provider store={store}>
      <Router>
        <Switch>
          <PageLayoutRoute exact path={routes.home} component={HomePage} />
          <PageLayoutRoute path={routes.studio} component={StudioPage} />
          <PageLayoutRoute path={routes.framing} component={FramingPage} />
          {/* */}
          <PageLayoutRoute path="/checkout" component={OrderReviewPage} />
          <PageLayoutRoute path="/orderConfirmed" component={OrderConfirmationPage} />
        </Switch>
      </Router>
    </Provider>
  </SocialIntegrator>;

export default App;
</code>```

Here's createStore.js.

```<code>import { createOpbeatMiddleware } from "opbeat-react/redux";
import { applyMiddleware, createStore } from "redux";
import thunk from "redux-thunk";
import reducer from "./reducer";

export default () =>
  createStore(
    reducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ &&
      window.__REDUX_DEVTOOLS_EXTENSION__(),
    applyMiddleware(thunk, createOpbeatMiddleware())
  );
</code>```

Export/Import

So I'm using subfolders with index.js in each of them to export each component.
export: Social/index.js

```<code>export { default as SocialIntegrator } from "./controls/SocialIntegrator";
</code>```

import: index.js

```<code>import { SocialIntegrator } from "components/Social";
</code>```

Environment

node -v:  v8.4.0

npm -v: v4.6.1

yarn --version (if you use Yarn): 0.20.0

npm ls react-scripts (if you haven’t ejected): v1.0.14

答:
Please see my explanation here: Uncaught TypeError: Cannot read property 'mountComponent' of undefined error when running create-react-app build version

You are using a library that depends on private React APIs. Those APIs don't exist anymore. (And were never meant to be used directly.)

Body:
Steps to Reproduce

My create-react-app works fine on development mode, but it is blank page when I run the built one using (npm run build) with this console error.

Uncaught TypeError: Cannot read property 'mountComponent' of undefined
    at r (patchUtils.js:51)
    at e.exports (reactPatches.js:41)
    at react.js:59
    at Object.ready (reactInternals.js:24)
    at r (react.js:58)
    at Object.<anonymous> (index.js:12)
    at t (bootstrap 3c1adc8fa04e423f7356:19)
    at Object.<anonymous> (main.448e9d91.js:66458)
    at t (bootstrap 3c1adc8fa04e423f7356:19)
    at bootstrap 3c1adc8fa04e423f7356:62
    at bootstrap 3c1adc8fa04e423f7356:62

I didn't change any create-react-app config. One thing I'm suspecting is this part of code and the structure.

class SocialIntegrator extends React.Component {
  static propTypes = { children: PropTypes.node.isRequired };

  componentDidMount = () => {
    if (!initialized) {
      initialized = true;

      installFacebookSdk();
      installPinterest();
      installTwitter();
    }
  };

  render = () => React.Children.only(this.props.children);
}

export default SocialIntegrator;

Here's App.js .

import React from "react";
import { Provider } from "react-redux";
import { BrowserRouter as Router, Switch } from "react-router-dom";
import PageLayoutRoute from "components/controls/PageLayoutRoute";
import { SocialIntegrator } from "components/Social";
import { createStore } from "store";
import routes from "components/routes";
import HomePage from "components/HomePage";
import StudioPage from "components/StudioPage";
import FramingPage from "components/FramingPage";
import OrderReviewPage from "components/OrderReviewPage";
import OrderConfirmationPage from "components/OrderConfirmationPage";
import { injectGlobal } from "styled-components";
injectGlobal`
  html {
    overflow-y: auto;
  }
`;
const store = createStore();

const App = () =>
  <SocialIntegrator>
    <Provider store={store}>
      <Router>
        <Switch>
          <PageLayoutRoute exact path={routes.home} component={HomePage} />
          <PageLayoutRoute path={routes.studio} component={StudioPage} />
          <PageLayoutRoute path={routes.framing} component={FramingPage} />
          {/* */}
          <PageLayoutRoute path="/checkout" component={OrderReviewPage} />
          <PageLayoutRoute path="/orderConfirmed" component={OrderConfirmationPage} />
        </Switch>
      </Router>
    </Provider>
  </SocialIntegrator>;

export default App;

Here's createStore.js.

import { createOpbeatMiddleware } from "opbeat-react/redux";
import { applyMiddleware, createStore } from "redux";
import thunk from "redux-thunk";
import reducer from "./reducer";

export default () =>
  createStore(
    reducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ &&
      window.__REDUX_DEVTOOLS_EXTENSION__(),
    applyMiddleware(thunk, createOpbeatMiddleware())
  );

Export/Import

So I'm using subfolders with index.js in each of them to export each component.
export: Social/index.js

export { default as SocialIntegrator } from "./controls/SocialIntegrator";

import: index.js

import { SocialIntegrator } from "components/Social";

Environment

node -v:  v8.4.0

npm -v: v4.6.1

yarn --version (if you use Yarn): 0.20.0

npm ls react-scripts (if you haven’t ejected): v1.0.14

ContentLicense: CC BY-SA 4.0


问:
Jsoup doesn't extract all the expected elements
For some reason Jsoup extracts only 2207 elements although there are definitely more of them. For example, the URL of the class XmlPullParserFactory isn't read although it's inside an element with the class jd-linkcol.

Below is my code:

```<code>try {
    String url = "https://developer.android.com/reference/classes.html";
    Document document = Jsoup.connect(url).timeout(0).get();
    Elements classes = document.getElementsByClass("jd-linkcol");
    BufferedWriter fw = new BufferedWriter(new FileWriter(new File("/tmp/test.txt")));

    System.out.println(classes.size());

    for (int i = 0; i < classes.size(); i++) {
        Elements links = classes.get(i).getElementsByTag("a");
        String classUrl = links.attr("abs:href");

        if (classUrl.contains("XmlPullParserFactory")) {
            System.out.println(classUrl);
        }

        fw.write(classUrl + "\n");
    }
    fw.flush();
    fw.close();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
</code>```

I'm using Jsoup 1.7.3 which I didn't update since a while.

答:
The max body size is limited to 1MB by default. With the default settings you are getting only the first 2207 elements from AbsListView to MediaRouter.UserRouteInfo, which comply with the default size of 1MB. To get all elements you can simply change the default settings using:

```<code>Document document = Jsoup.connect(url).timeout(0).maxBodySize(1024*1024*10).get();
//for example to set the max body size to 10 MB
</code>```

or

```<code>//to set it to unlimited size
Document document = Jsoup.connect(url).timeout(0).maxBodySize(0).get();
</code>```

Body:
For some reason Jsoup extracts only 2207 elements although there are definitely more of them. For example, the URL of the class XmlPullParserFactory isn't read although it's inside an element with the class jd-linkcol.

Below is my code:

try {
    String url = "https://developer.android.com/reference/classes.html";
    Document document = Jsoup.connect(url).timeout(0).get();
    Elements classes = document.getElementsByClass("jd-linkcol");
    BufferedWriter fw = new BufferedWriter(new FileWriter(new File("/tmp/test.txt")));

    System.out.println(classes.size());

    for (int i = 0; i < classes.size(); i++) {
        Elements links = classes.get(i).getElementsByTag("a");
        String classUrl = links.attr("abs:href");

        if (classUrl.contains("XmlPullParserFactory")) {
            System.out.println(classUrl);
        }

        fw.write(classUrl + "\n");
    }
    fw.flush();
    fw.close();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

I'm using Jsoup 1.7.3 which I didn't update since a while.

Body:
The max body size is limited to 1MB by default. With the default settings you are getting only the first 2207 elements from AbsListView to MediaRouter.UserRouteInfo, which comply with the default size of 1MB. To get all elements you can simply change the default settings using:

Document document = Jsoup.connect(url).timeout(0).maxBodySize(1024*1024*10).get();
//for example to set the max body size to 10 MB

or

//to set it to unlimited size
Document document = Jsoup.connect(url).timeout(0).maxBodySize(0).get();


问:
What are 'service_args' for the selenium-python chrome webdriver?
I searched documentation for the argument service_args for the chrome webdriver, and I found the following pages: here and here, which unfortunately do not contain any useful content to answer my question.

So where can I find proper documentation on the service_args argument?

答:
The reason why this is not documented is unknown.

But most likely this option can be used to pass arguments to the chromedriver. The list of options can be seen by running

```<code>chromedriver --help
</code>```

For version 2.24 of chromdriver you get the following list:

```<code>Usage: chromedriver [OPTIONS]

Options
  --port=PORT                     port to listen on
  --adb-port=PORT                 adb server port
  --log-path=FILE                 write server log to file instead of stderr, increases log level to INFO
  --verbose                       log verbosely
  --version                       print the version number and exit
  --silent                        log nothing
  --url-base                      base URL path prefix for commands, e.g. wd/url
  --port-server                   address of server to contact for reserving a port
  --whitelisted-ips               comma-separated whitelist of remote IPv4 addresses which are allowed to connect to ChromeDriver
</code>```

Body:
The reason why this is not documented is unknown.

But most likely this option can be used to pass arguments to the chromedriver. The list of options can be seen by running

chromedriver --help

For version 2.24 of chromdriver you get the following list:

Usage: chromedriver [OPTIONS]

Options
  --port=PORT                     port to listen on
  --adb-port=PORT                 adb server port
  --log-path=FILE                 write server log to file instead of stderr, increases log level to INFO
  --verbose                       log verbosely
  --version                       print the version number and exit
  --silent                        log nothing
  --url-base                      base URL path prefix for commands, e.g. wd/url
  --port-server                   address of server to contact for reserving a port
  --whitelisted-ips               comma-separated whitelist of remote IPv4 addresses which are allowed to connect to ChromeDriver


问:
Mysql select where t4.name=x and t2 or t3 have a t1.user !? :)
To explain my problem lets imagine 4 tables.

```<code>users - (userid, user.data)

buy - (buyid, productid, userid, buy.conditions)

sell - (sellid, productid, userid, sell.conditions)
</code>```

product - (productid, product.data)

I want to do a select that returns all the users and product data when there is a user that have products with X on the name to buy or sell.

```<code>SELECT userid,
       USER.DATA,
       productid,
       product.DATA
FROM   users,
       buy,
       sell,
       products
WHERE  ( buy.userid = users.userid
          OR sell.userid = users.userid )
       AND ( buy.productid = product.productid
              OR buy.productid = product.productid )
       AND product.DATA LIKE '%x%'
</code>```

this doesnt work but I belive you get the idea of what I am tryng to do.

答:
Thanks a lot guys!

With the help from a friend end up making something like this:

```<code>
SELECT USER.DATA,
      product.DATA, origem
From
(
SELECT 'b' Origem,
   productid,
   userid
FROM buy
union all
SELECT 's' Origem,
   productid,
   userid
FROM sell
) tabelas
inner join users on users.userid=tabelas.userid
inner join products on products.productid=tabelas.productid
Where product.DATA LIKE '%x%'
</code>```

ContentLicense: CC BY-SA 2.5

Body:
To explain my problem lets imagine 4 tables.

users - (userid, user.data)

buy - (buyid, productid, userid, buy.conditions)

sell - (sellid, productid, userid, sell.conditions)

product - (productid, product.data)

I want to do a select that returns all the users and product data when there is a user that have products with X on the name to buy or sell.

SELECT userid,
       USER.DATA,
       productid,
       product.DATA
FROM   users,
       buy,
       sell,
       products
WHERE  ( buy.userid = users.userid
          OR sell.userid = users.userid )
       AND ( buy.productid = product.productid
              OR buy.productid = product.productid )
       AND product.DATA LIKE '%x%'

this doesnt work but I belive you get the idea of what I am tryng to do.

Body:
Thanks a lot guys!

With the help from a friend end up making something like this:

SELECT USER.DATA,
      product.DATA, origem
From
(
SELECT 'b' Origem,
   productid,
   userid
FROM buy
union all
SELECT 's' Origem,
   productid,
   userid
FROM sell
) tabelas
inner join users on users.userid=tabelas.userid
inner join products on products.productid=tabelas.productid
Where product.DATA LIKE '%x%'


问:
Having trouble with Linq list sorting
Good evening.

I have a list of a class that I would like to index for different reasons, one being that I would like to read the data in different orders at different times. The trouble I am having is that I cannot get my head around sorting with LINQ.

The class I have in my list is similar to this (this is a smaller version)

```<code>List<SalesRecord> Records = new List<SalesRecord>();
class SalesRecord
{
    public Int16 SalesID { get; set; }
    public Int32 Invoice { get; set; }
    public DateTime BookoutDate { get; set; }
}
</code>```

The count size of Records is roughly 500,000

My thoughts were to create a couple of lists that would reference each item in Records in a particular order

Eg:

```<code>List<int> BookoutDateIndex;
List<int> InvoiceIndex;

Records[BookoutDateIndex[0]].BookoutDate // Oldest date
Records[BookoutDateIndex[1]].BookoutDate // Second oldest date
                                         // etc
</code>```

Based on the information I have seen, the closest I have found that almost does what I want is this...

```<code>// Copy dates to new list
List<DateTime> BookoutDates = new List<DateTime>();

for (int salesRecordIndex = 0; salesRecordIndex < records.Count; salesRecordIndex++)
    BookoutDates.Add(Records[salesRecordIndex].BookoutDate);

// Sort list

var sorted = Indexes.BookoutDates
    .Select((x, i) => new KeyValuePair<DateTime, int>(x, i))
    .OrderBy(x => x.Key)
    .ToList();
</code>```

Although this works, I don't want the actual date in the Index and I don't want to have to copy the dates in a new list beforehand.

I realize this would be easier to do by loading the data into something like a Access database, but I prefer to do it without a database option.

Any assistance would be appreciated.

答:
Surely you just want:</p>

```<code>var sorted = Records
    .OrderBy(x => x.BookoutDate)
    .ToList();
</code>```

Title: Having trouble with Linq list sorting

Body:
Good evening.

I have a list of a class that I would like to index for different reasons, one being that I would like to read the data in different orders at different times. The trouble I am having is that I cannot get my head around sorting with LINQ.

The class I have in my list is similar to this (this is a smaller version)

List<SalesRecord> Records = new List<SalesRecord>();
class SalesRecord
{
    public Int16 SalesID { get; set; }
    public Int32 Invoice { get; set; }
    public DateTime BookoutDate { get; set; }
}

The count size of Records is roughly 500,000

My thoughts were to create a couple of lists that would reference each item in Records in a particular order

Eg:

List<int> BookoutDateIndex;
List<int> InvoiceIndex;

Records[BookoutDateIndex[0]].BookoutDate // Oldest date
Records[BookoutDateIndex[1]].BookoutDate // Second oldest date
                                         // etc

Based on the information I have seen, the closest I have found that almost does what I want is this...

// Copy dates to new list
List<DateTime> BookoutDates = new List<DateTime>();

for (int salesRecordIndex = 0; salesRecordIndex < records.Count; salesRecordIndex++)
    BookoutDates.Add(Records[salesRecordIndex].BookoutDate);

// Sort list

var sorted = Indexes.BookoutDates
    .Select((x, i) => new KeyValuePair<DateTime, int>(x, i))
    .OrderBy(x => x.Key)
    .ToList();

Although this works, I don't want the actual date in the Index and I don't want to have to copy the dates in a new list beforehand.

I realize this would be easier to do by loading the data into something like a Access database, but I prefer to do it without a database option.

Any assistance would be appreciated.

Body:
Surely you just want:

var sorted = Records
    .OrderBy(x => x.BookoutDate)
    .ToList();


问:
Unable to view form page in Codeigniter
Unable to view form page in Codeigniter, When I try to open.

form.php
This is my view file in Codeigniter. I am newbie in Codeigniter, I am unable to solve this problem.

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

<link href="<?php echo base_url().'assets/bootstrap.min.css'; ?>" rel="stylesheet" type='text/css'>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 <style>
 .error{color:red}
 </style>
</head>
<body>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-3">

<h1>Student Registraion</h1>

<?php
echo form_open();
  echo form_label('First Name');
  $data=[
  'name'=>'fname',
  'class'=>'form-control',
  'id'=>'fname',
  'value'=>isset($dta['fname'])?$dta['fname']:''
  ];
  echo form_input($data);
  echo form_error('fname');

  echo form_label('Last Name');
  $data=[
  'name'=>'lname',
  'class'=>'form-control',
  'id'=>'lname',
  'value'=>isset($dta['lname'])?$dta['lname']:''
  ];
  echo form_input($data);
  echo form_error('email');
   echo form_label('Email');

  $data=[
  'name'=>'email',
  'class'=>'form-control',
  'id'=>'email',
  'value'=>isset($dta['email'])?$dta['email']:''
  ];

  echo form_input($data);

  echo form_label('Mobile Number');

  $data=[
  'name'=>'mobile',
  'class'=>'form-control',
  'id'=>'mobile',
  'value'=>isset($dta['mobile'])?$dta['mobile']:''
  ];

  echo form_input($data);
   echo form_error('mobile');
    echo form_label('Message');
  $data=[
  'name'=>'message',
  'class'=>'form-control',
  'id'=>'message',
  'value'=>isset($dta['message'])?$dta['message']:''
  ];
  echo form_textarea($data).br(1);
  echo form_submit('submit','submit','class="btn btn-success"');
  echo form_close();
?>
</div>
<div class="col-md-3"></div>
</div>

</body>
</html>
</code>```

home.php

Unable to view form page in Codeigniter, When I try to open.

When I open my insert form It gives me error, I have attached error screenshot.

```<code><?php

class home extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->model('select');
        $this->load->helper(array('form','url','html'));
        $this->load->library(array('form_validation','session'));

    }

   function records()
   {

       $ytl['dta']=$this->users->datas();
       //$this->load->view('info',$ytl);
       //echo "```controller";print_r($ytl);
   }
   function primezone()
   {

           $ytl['dta']=$this->users->datas();
            echo "```controller";print_r($ytl);
   }

    function form($id)
    {
    //die($id);
    if($this->input->post())
    {
        //echo"```";print_r( $this->input->post());die;
        $this->form_validation->set_rules('fname','First Name','required|min_length[5]');
        $this->form_validation->set_rules('lname','Last Name','required|callback_check_picture[lname]');

        //$this->form_validation->set_rules('email','Email','required');

        $this->form_validation->set_rules('mobile','Mobile Number','required|callback_valid_phone_number[mobile]');

        $this->form_validation->set_error_delimiters('
', '
');
        if($this->form_validation->run()==True)
        {
        $data=[
        'fname'=>$this->input->post('fname'),
        'lname'=>$this->input->post('lname'),
        'email'=>$this->input->post('email'),
        'mobile'=>$this->input->post('mobile'),
        'message'=>$this->input->post('message'),
        ];
        $ytl=$this->select->insertdata($data);
        if($ytl)
        {
            $this->session->set_flashdata('message', 'Successfully Added.');
     redirect('home');
        }
        }else
        {
                //$this->load->view('form');
        }

    }
    $ytl['dta']=$this->select->getDataById($id);
    //echo "```";print_r($ytl);die;
    $this->load->view('form',$ytl);

}
public function check_picture($a){
   if(!is_numeric($a))
   {
       return true;
   }else{
     $this->form_validation->set_message('check_picture', 'Please enter only char value');
     return False;
}
}

function valid_phone_number($value)
{
    $value = strlen($value);
    //echo $value;die;
    if ($value == 10) {
        return true;
    }
    else
    {
        $this->form_validation->set_message('valid_phone_number', 'Mobile number not in range'); //{10}
    return false;
    }
}

    public function index()

     {
         //load the database
         //$this->load->database();
         //load the model
         $this->load->model('select');
         //load the method of model
         $data['h']=$this->select->select();
         //return the data in view
         $this->load->view('fetch_view', $data);
      }

}

?>
</code>```

select.php

This is my model. Unable to view form page in Codeigniter, When I try to open.

```<code><?php

class select extends CI_model

{
    function __construct()
      {
         // Call the Model constructor
         parent::__construct();
     $this->load->database();
      }

    function datas()
    {
        $pzi=[
        'name'=>'pratibha',
        'email'=>'pratibha@gmail.com',
        'mobile'=>998858585,
        'address'=>'noida'

        ];

        return $pzi;
    }

    function insertdata($data)
    {
        $this->load->database();
        return $this->db->insert('student',
        $data);
    }

    public function select()
      {
         //data is retrive from this query

         $query = $this->db->get('student');
         return $query;
      }

    function getDataById($id)
    {
        $this->db->select('*');
        $this->db->where('id',$id);
        $this->db->from('student');
      $query = $this->db->get()->row_array();
         return $query;
    }
}

?>
</code>```

答:
you are calling insert function from your controller. call an update function</p>

```<code>$this->db->where('id',$id);
$this->db->set($data);
$this->db->update('student');
</code>```

Title: Unable to view form page in Codeigniter

Body:
Unable to view form page in Codeigniter, When I try to open.

form.php
This is my view file in Codeigniter. I am newbie in Codeigniter, I am unable to solve this problem.

<!DOCTYPE html>

<link href="<?php echo base_url().'assets/bootstrap.min.css'; ?>" rel="stylesheet" type='text/css'>

Student Registraion

<?php
echo form_open();
  echo form_label('First Name');
  $data=[
  'name'=>'fname',
  'class'=>'form-control',
  'id'=>'fname',
  'value'=>isset($dta['fname'])?$dta['fname']:''
  ];
  echo form_input($data);
  echo form_error('fname');

  echo form_label('Last Name');
  $data=[
  'name'=>'lname',
  'class'=>'form-control',
  'id'=>'lname',
  'value'=>isset($dta['lname'])?$dta['lname']:''
  ];
  echo form_input($data);
  echo form_error('email');
   echo form_label('Email');

  $data=[
  'name'=>'email',
  'class'=>'form-control',
  'id'=>'email',
  'value'=>isset($dta['email'])?$dta['email']:''
  ];

  echo form_input($data);

  echo form_label('Mobile Number');

  $data=[
  'name'=>'mobile',
  'class'=>'form-control',
  'id'=>'mobile',
  'value'=>isset($dta['mobile'])?$dta['mobile']:''
  ];

  echo form_input($data);
   echo form_error('mobile');
    echo form_label('Message');
  $data=[
  'name'=>'message',
  'class'=>'form-control',
  'id'=>'message',
  'value'=>isset($dta['message'])?$dta['message']:''
  ];
  echo form_textarea($data).br(1);
  echo form_submit('submit','submit','class="btn btn-success"');
  echo form_close();
?>

home.php

Unable to view form page in Codeigniter, When I try to open.

When I open my insert form It gives me error, I have attached error screenshot.

<?php

class home extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->model('select');
        $this->load->helper(array('form','url','html'));
        $this->load->library(array('form_validation','session'));

    }

   function records()
   {

       $ytl['dta']=$this->users->datas();
       //$this->load->view('info',$ytl);
       //echo "
controller";print_r($ytl);
   }
   function primezone()
   {

           $ytl['dta']=$this->users->datas();
            echo "
controller";print_r($ytl);
   }

    function form($id)
    {
    //die($id);
    if($this->input->post())
    {
        //echo"
";print_r( $this->input->post());die;
        $this->form_validation->set_rules('fname','First Name','required|min_length[5]');
        $this->form_validation->set_rules('lname','Last Name','required|callback_check_picture[lname]');

        //$this->form_validation->set_rules('email','Email','required');

        $this->form_validation->set_rules('mobile','Mobile Number','required|callback_valid_phone_number[mobile]');

        $this->form_validation->set_error_delimiters('
', '
');
        if($this->form_validation->run()==True)
        {
        $data=[
        'fname'=>$this->input->post('fname'),
        'lname'=>$this->input->post('lname'),
        'email'=>$this->input->post('email'),
        'mobile'=>$this->input->post('mobile'),
        'message'=>$this->input->post('message'),
        ];
        $ytl=$this->select->insertdata($data);
        if($ytl)
        {
            $this->session->set_flashdata('message', 'Successfully Added.');
     redirect('home');
        }
        }else
        {
                //$this->load->view('form');
        }

    }
    $ytl['dta']=$this->select->getDataById($id);
    //echo "
";print_r($ytl);die;
    $this->load->view('form',$ytl);

}
public function check_picture($a){
   if(!is_numeric($a))
   {
       return true;
   }else{
     $this->form_validation->set_message('check_picture', 'Please enter only char value');
     return False;
}
}

function valid_phone_number($value)
{
    $value = strlen($value);
    //echo $value;die;
    if ($value == 10) {
        return true;
    }
    else
    {
        $this->form_validation->set_message('valid_phone_number', 'Mobile number not in range'); //{10}
    return false;
    }
}

    public function index()

     {
         //load the database
         //$this->load->database();
         //load the model
         $this->load->model('select');
         //load the method of model
         $data['h']=$this->select->select();
         //return the data in view
         $this->load->view('fetch_view', $data);
      }

}

?>

select.php

This is my model. Unable to view form page in Codeigniter, When I try to open.

<?php

class select extends CI_model

{
    function __construct()
      {
         // Call the Model constructor
         parent::__construct();
     $this->load->database();
      }

    function datas()
    {
        $pzi=[
        'name'=>'pratibha',
        'email'=>'pratibha@gmail.com',
        'mobile'=>998858585,
        'address'=>'noida'

        ];

        return $pzi;
    }

    function insertdata($data)
    {
        $this->load->database();
        return $this->db->insert('student',
        $data);
    }

    public function select()
      {
         //data is retrive from this query

         $query = $this->db->get('student');
         return $query;
      }

    function getDataById($id)
    {
        $this->db->select('*');
        $this->db->where('id',$id);
        $this->db->from('student');
      $query = $this->db->get()->row_array();
         return $query;
    }
}

?>

Body:
you are calling insert function from your controller. call an update function

$this->db->where('id',$id);
$this->db->set($data);
$this->db->update('student');


问:
Stuck on a simple code
I have a code for open and read a csv file which is fopen() method.
But it is showing error. below is the code

```<code><?php
$file = fopen('C:\Users\Abby\Desktop\testbad\testbed_information.csv', `r`);
?>
</code>```

And the error is

```<code>Warning: fopen(C:\Users\Abby\Desktop\testbad\testbed_information.csv): failed to open stream: No error in C:\wamp64\www\date.php on line 2
</code>```

Please help me...!!?

答:
You have issue with quotation. You are using back-quotes in second params. change it with double or single quote</p>

```<code><?php
$file = fopen('C:\Users\Abby\Desktop\testbad\testbed_information.csv', "r");
?>
</code>```

Title: Stuck on a simple code

Body:
I have a code for open and read a csv file which is fopen() method.
But it is showing error. below is the code

<?php
$file = fopen('C:\Users\Abby\Desktop\testbad\testbed_information.csv', `r`);
?>

And the error is

Warning: fopen(C:\Users\Abby\Desktop\testbad\testbed_information.csv): failed to open stream: No error in C:\wamp64\www\date.php on line 2

Please help me...!!?

Body:
You have issue with quotation. You are using back-quotes in second params. change it with double or single quote

<?php
$file = fopen('C:\Users\Abby\Desktop\testbad\testbed_information.csv', "r");
?>


问:
Select from multi access tables
Try to get result of this query:

```<code>SELECT DISTINCT
       invoices.invoice_id,
       invoices.customer,
       invoices.total,
       SUM(pay_amount) AS paid
FROM invoices,
     invoice_payment
WHERE invoices.invoice_id = invoice_payment.invoice_id
      AND invoices.type = 'client'
      AND invoice_payment.pay_type <> 'postpaid'
      AND format(invoices.create_date, "dd/mm/yyyy") BETWEEN '01/11/2017' AND '14/11/2017';
</code>```

I got

"Your query does not include the specific expression 'invoice_id' as
  part of an aggregate function"

答:
Add a GROUP BY when you are aggregating data, e.g. count, sum etc

Like this:

```<code>SELECT DISTINCT
       invoices.invoice_id,
       invoices.customer,
       invoices.total,
       SUM(pay_amount) AS paid
FROM invoices,
     invoice_payment
WHERE invoices.invoice_id = invoice_payment.invoice_id
      AND invoices.type = 'client'
      AND invoice_payment.pay_type <> 'postpaid'
      AND format(invoices.create_date, "dd/mm/yyyy") BETWEEN '01/11/2017' AND '14/11/2017'
GROUP BY invoices.invoice_id,
         invoices.customer,
         invoices.total;
</code>```

The Access docs for GROUP BY are here

Also try to avoid the old style joins, they are nasty and outdated. This would be much better:

```<code>FROM invoices
INNER JOIN invoice_payment ON invoices.invoice_id = invoice_payment.invoice_id
</code>```

Title: Select from multi access tables

Body:
Try to get result of this query:

SELECT DISTINCT
       invoices.invoice_id,
       invoices.customer,
       invoices.total,
       SUM(pay_amount) AS paid
FROM invoices,
     invoice_payment
WHERE invoices.invoice_id = invoice_payment.invoice_id
      AND invoices.type = 'client'
      AND invoice_payment.pay_type <> 'postpaid'
      AND format(invoices.create_date, "dd/mm/yyyy") BETWEEN '01/11/2017' AND '14/11/2017';

I got

"Your query does not include the specific expression 'invoice_id' as
  part of an aggregate function"

Body:
Add a GROUP BY when you are aggregating data, e.g. count, sum etc

Like this:

SELECT DISTINCT
       invoices.invoice_id,
       invoices.customer,
       invoices.total,
       SUM(pay_amount) AS paid
FROM invoices,
     invoice_payment
WHERE invoices.invoice_id = invoice_payment.invoice_id
      AND invoices.type = 'client'
      AND invoice_payment.pay_type <> 'postpaid'
      AND format(invoices.create_date, "dd/mm/yyyy") BETWEEN '01/11/2017' AND '14/11/2017'
GROUP BY invoices.invoice_id,
         invoices.customer,
         invoices.total;

The Access docs for GROUP BY are here

Also try to avoid the old style joins, they are nasty and outdated. This would be much better:

FROM invoices
INNER JOIN invoice_payment ON invoices.invoice_id = invoice_payment.invoice_id


问:
Best approach to query SQL server for numpy
In a previous programme I was reading data from a csv file like this:

```<code>AllData = np.genfromtxt(open("PSECSkew.csv", "rb"),
                        delimiter=',',
                        dtype=[('CalibrationDate', datetime),('Expiry', datetime), ('B0', float), ('B1', float), ('B2', float), ('ATMAdjustment', float)],
                        converters={0: ConvertToDate, 1: ConvertToDate})
</code>```

I'm now writing an incredibly similar programme but this time I want to get a really similar data structure to AllData (except the floats will all be in a csv string this time) but from SQL Server instead of a csv file. What's the best approach?

pyodbc looks like it involves using cursors a lot which I'm not familiar with and would like to avoid. I just want to run the query and get the data in a structure like above (or like a DataTable in C#).

答:
How about using pandas? For example:</p>

```<code>import psycopg2
import pandas

try :
    con = psycopg2.connect(
    host = "host",
    database = "innovate",
    user = "username",
    password = "password")
except:
    print "Could not connect to database."

data = pandas.read_sql_query("SELECT * FROM table", con)
</code>```

Body:
In a previous programme I was reading data from a csv file like this:

AllData = np.genfromtxt(open("PSECSkew.csv", "rb"),
                        delimiter=',',
                        dtype=[('CalibrationDate', datetime),('Expiry', datetime), ('B0', float), ('B1', float), ('B2', float), ('ATMAdjustment', float)],
                        converters={0: ConvertToDate, 1: ConvertToDate})

I'm now writing an incredibly similar programme but this time I want to get a really similar data structure to AllData (except the floats will all be in a csv string this time) but from SQL Server instead of a csv file. What's the best approach?

pyodbc looks like it involves using cursors a lot which I'm not familiar with and would like to avoid. I just want to run the query and get the data in a structure like above (or like a DataTable in C#).

Body:
How about using pandas? For example:

import psycopg2
import pandas

try :
    con = psycopg2.connect(
    host = "host",
    database = "innovate",
    user = "username",
    password = "password")
except:
    print "Could not connect to database."

data = pandas.read_sql_query("SELECT * FROM table", con)


问:
java : Array , How can I use find Distance (distance,name) function and display distance?
java : Array , How can I use find Distance (distance,name) function and display distance?

java : Array , How can I use find Distance (distance,name) function and display distance?
java : Array , How can I use find Distance (distance,name) function and display distance?

```<code>package practice;

public class displayDistance
{
   /*I'm playing around with Arrays in Java and had this doubt.
     How do I call the  find Distance (distance,name) and display distance .

     5 Requirement are :
     1) Define 2-D Array for distance and populate it.
     2) ask user for source and destination ( preferably lets use Exception Handling along with JOptionPane prompt .
        e.g. 1st prompt-> From city :  , 2nd prompt->  To city :
     3)define a city Array
     4)call function findDistance (distance,name) to find distance and  return it .
     5)display distance.*/

    public class practice {
        public void main(String[] args)
        {

          //1. Define 2-D Array for distance and populate it .
          int [][] distances = { {0,50,100,20},{50,0,70,110},
                               {100,70,0,200},{20,110,200,0} };

          //3. define a city Array
          String [] names = {"manassas","fairfax","baltimore","centerville"};

          // calling (invoking)the function
           findDistance (distances,names);

          // JOptionPane.showMessageDialog(null, "The distance value is: " + findDistance(distances), "DISTANCE VALUE",
          // JOptionPane.INFORMATION_MESSAGE);

        }

     private String findDistance(int[][] distances, String[] names) {
         return null;
     }
  }
}
</code>```

答:
```<code>import java.util.*;
import java.lang.*;
import java.io.*;

class Demo6 {
    public static void main(String[] args) {

        int[][] distances = {{0, 50, 100, 20}, {50, 0, 70, 110},
                {100, 70, 0, 200}, {20, 110, 200, 0}};

        String[] names = {"manassas", "fairfax", "baltimore", "centerville"};

        /* Take two more inputs which are FROM city TO city */
        /* I have taken two default city names below */
        /* And findDistance method should have four arguments */

        findDistance(distances, names, "baltimore", "centerville");
    }

    private static void findDistance(int[][] distances, String[] names, String a, String b) {

        int x = 0, y = 0;

        /*below i am finding the index of the cities 'a' and 'b'*/
        /*below logic works only if both the cities exist  in the array*/

        for (int i = 0; i < names.length; i++) {
            if (names[i].equals(a))
                x = i;
            if (names[i].equals(b))
                y = i;
        }
    /*after calculating the index just print their cost from the matrix distance*/
    /*its as simple as that*/
        System.out.println(distances[x][y]);

    }
}
</code>```

Hope it helps. I have explained the code in comments.

Body:
java : Array , How can I use find Distance (distance,name) function and display distance?

java : Array , How can I use find Distance (distance,name) function and display distance?
java : Array , How can I use find Distance (distance,name) function and display distance?

package practice;

public class displayDistance
{
   /*I'm playing around with Arrays in Java and had this doubt.
     How do I call the  find Distance (distance,name) and display distance .

     5 Requirement are :
     1) Define 2-D Array for distance and populate it.
     2) ask user for source and destination ( preferably lets use Exception Handling along with JOptionPane prompt .
        e.g. 1st prompt-> From city :  , 2nd prompt->  To city :
     3)define a city Array
     4)call function findDistance (distance,name) to find distance and  return it .
     5)display distance.*/

    public class practice {
        public void main(String[] args)
        {

          //1. Define 2-D Array for distance and populate it .
          int [][] distances = { {0,50,100,20},{50,0,70,110},
                               {100,70,0,200},{20,110,200,0} };

          //3. define a city Array
          String [] names = {"manassas","fairfax","baltimore","centerville"};

          // calling (invoking)the function
           findDistance (distances,names);

          // JOptionPane.showMessageDialog(null, "The distance value is: " + findDistance(distances), "DISTANCE VALUE",
          // JOptionPane.INFORMATION_MESSAGE);

        }

     private String findDistance(int[][] distances, String[] names) {
         return null;
     }
  }
}

Body:
import java.util.*;
import java.lang.*;
import java.io.*;

class Demo6 {
    public static void main(String[] args) {

        int[][] distances = {{0, 50, 100, 20}, {50, 0, 70, 110},
                {100, 70, 0, 200}, {20, 110, 200, 0}};

        String[] names = {"manassas", "fairfax", "baltimore", "centerville"};

        /* Take two more inputs which are FROM city TO city */
        /* I have taken two default city names below */
        /* And findDistance method should have four arguments */

        findDistance(distances, names, "baltimore", "centerville");
    }

    private static void findDistance(int[][] distances, String[] names, String a, String b) {

        int x = 0, y = 0;

        /*below i am finding the index of the cities 'a' and 'b'*/
        /*below logic works only if both the cities exist  in the array*/

        for (int i = 0; i < names.length; i++) {
            if (names[i].equals(a))
                x = i;
            if (names[i].equals(b))
                y = i;
        }
    /*after calculating the index just print their cost from the matrix distance*/
    /*its as simple as that*/
        System.out.println(distances[x][y]);

    }
}

Hope it helps. I have explained the code in comments.


问:
Implementation of quartic equation solver doesn't work
What's going wrong with my implementation of a quartic equation solver?

Here is my code on GitHub. I followed this: http://www.1728.com/quartic2.htm

In fact the real implementation starts at line 271, where I create the monic poly.

If I try it with a polynomial with 4 real roots it works fine (for example with 3x^4 + 6x^3 - 123x^2 - 126x + 1,080), otherwise gives wrong roots.

Thanks,

rubik

P.S. I called the function __quartic because it is still in development

答: Does your cubic root solver work? You should have it reduced to only returning a single real root for use within the quartic solver. Run a number of test cases on the cubic solver first, including equations with both 1 and 3 real roots. Only after this is verified should you try to debug the quartic solver.</p>


问:
setLayoutParams overriding setGravity for layout
I have this section in my layout file:

```<code><RelativeLayout>
    <LinearLayout android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <TextView></TextView>
        <TextView></TextView>
    </LinearLayout>
</RelativeLayout>
</code>```

My objective is to set the gravity of the items inside the linearLayout and then to add a margin to the whole LinearLayout programmatically.

This is what I have:

```<code>linearLayout_textBackground.setGravity(gravity); //where gravity is the int of the desired gravity

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                   RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
linearLayout_textBackground.setLayoutParams(layoutParams);
linearLayout_textBackground.requestLayout();
</code>```

I would like to set the margin in using layoutParams but when I run the above code, I notice that my gravity value had been reset. However, if I comment out linearLayout_textBackground.setLayoutParams(layoutParams);, my gravity value are set correctly.

Why is the gravity resetting after I setLayoutParams to my layout?

答:
When you do this :

```<code>RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
               RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
</code>```

You are creating new reference for your layout parameters the one you mention here will change the others not mentioned will be changed to default of android. If you want to change gravity then you need to change it after creating new params like:

Use this:

```<code>linearLayout_textBackground.setGravity(gravity);
</code>```

after this:

```<code>linearLayout_textBackground.setLayoutParams(layoutParams);
</code>```

or define your layout gravity in defining layoutParams.

But the recommended way of setting your gravity is inside your xml as follows:

```<code>android:layout_gravity="center"
</code>```

then you dont need to do this :

```<code>linearLayout_textBackground.setGravity(gravity);
</code>```

Body:
I have this section in my layout file:

<RelativeLayout>
    <LinearLayout android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <TextView></TextView>
        <TextView></TextView>
    </LinearLayout>
</RelativeLayout>

My objective is to set the gravity of the items inside the linearLayout and then to add a margin to the whole LinearLayout programmatically.

This is what I have:

linearLayout_textBackground.setGravity(gravity); //where gravity is the int of the desired gravity

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                   RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
linearLayout_textBackground.setLayoutParams(layoutParams);
linearLayout_textBackground.requestLayout();

I would like to set the margin in using layoutParams but when I run the above code, I notice that my gravity value had been reset. However, if I comment out linearLayout_textBackground.setLayoutParams(layoutParams);, my gravity value are set correctly.

Why is the gravity resetting after I setLayoutParams to my layout?

Body:
When you do this :

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
               RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

You are creating new reference for your layout parameters the one you mention here will change the others not mentioned will be changed to default of android. If you want to change gravity then you need to change it after creating new params like:

Use this:

linearLayout_textBackground.setGravity(gravity);

after this:

linearLayout_textBackground.setLayoutParams(layoutParams);

or define your layout gravity in defining layoutParams.

But the recommended way of setting your gravity is inside your xml as follows:

android:layout_gravity="center"

then you dont need to do this :

linearLayout_textBackground.setGravity(gravity);


答:
service_args are used inconjunction with chromedriver binary to pass the List of args to the chromedriver service

An example would be to pass the parameters e.g. log file path, to ignore ssl errors, any ssl protocol as follows :

```<code>service_args=["--log-path=D:\\Alex.log", "--ignore-ssl-errors=true", "--ssl-protocol=any"]
</code>```

Your line of code will be :

```<code>driver = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe', service_args=["--log-path=D:\\qc1.log", "--ignore-ssl-errors=true", "--ssl-protocol=any"])
</code>```

Title: What are 'service_args' for the selenium-python chrome webdriver?

Body:
I searched documentation for the argument service_args for the chrome webdriver, and I found the following pages: here and here, which unfortunately do not contain any useful content to answer my question.

So where can I find proper documentation on the service_args argument?

Body:
service_args are used inconjunction with chromedriver binary to pass the List of args to the chromedriver service

An example would be to pass the parameters e.g. log file path, to ignore ssl errors, any ssl protocol as follows :

service_args=["--log-path=D:\\Alex.log", "--ignore-ssl-errors=true", "--ssl-protocol=any"]

Your line of code will be :

driver = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe', service_args=["--log-path=D:\\qc1.log", "--ignore-ssl-errors=true", "--ssl-protocol=any"])


问:
Spotify MP3 preview link not working with AVPlayer
I am having an issue with Spotify preview links, they are not playing using AVPlayer.

```<code>    var aSongURL: String = String(format: "https://p.scdn.co/mp3-preview/2d933f6474345c8af7e164356f30f450d0fc1309?cid=5e9ac4fc700442599e05f987a9cb1d4a")
    var aPlayerItem: AVPlayerItem = AVPlayerItem(url: NSURL(string: aSongURL)! as URL)
    var anAudioStreamer: AVPlayer = AVPlayer(playerItem: aPlayerItem)
    anAudioStreamer.play()
</code>```

It's a MP3, why is it not supported by AVPlayer, any ideas?

答: Try the method described here. It worked for me for your URL. </p>

Body:
I am having an issue with Spotify preview links, they are not playing using AVPlayer.

    var aSongURL: String = String(format: "https://p.scdn.co/mp3-preview/2d933f6474345c8af7e164356f30f450d0fc1309?cid=5e9ac4fc700442599e05f987a9cb1d4a")
    var aPlayerItem: AVPlayerItem = AVPlayerItem(url: NSURL(string: aSongURL)! as URL)
    var anAudioStreamer: AVPlayer = AVPlayer(playerItem: aPlayerItem)
    anAudioStreamer.play()

It's a MP3, why is it not supported by AVPlayer, any ideas?


问:
Mocha change timeout for afterEach
I am writing a node application with mocha and chai. Some of the tests call an external API for integration tests, which might take up to 90sec to perform the action.

In order to cleanup properly, I defined an afterEach()-block, which will delete any generated remote resources, in case an expect fails and some resources weren't deleted.

The tests themselves have an increased timeout, while the rest of the tests should retain their default and small timeout:

```<code>it('should create remote resource', () => {...}).timeout(120000)
</code>```

However, I can't do the same with afterEach().timeout(120000), because the function does not exist - nor can I use the function ()-notation due to the unknown resource names:

```<code>describe('Resources', function () {
  beforeEach(() => {
    this._resources = null
  })

  it('should create resources', async () => {
    this._resources = await createResources()
    expect(false).to.equal(true)   // fail test, so...
    await deleteResources()        // will never be called
  })

  afterEach(async() => {
    this._resources.map(entry => {
      await // ... delete any created resources ...
    })
  }).timeout(120000)
})
</code>```

Any hints? Mocha is version 4.0.1, chai is 4.1.2

答:
If you need to use dynamic context you have to use normal function.</p>

```<code>describe('Resources', function () {
  // ...
  afterEach(function (){
    this.timeout(120000)  // this should work
    // ... delete any created resources ...
  })
})
</code>```

Title: Mocha change timeout for afterEach

Body:
I am writing a node application with mocha and chai. Some of the tests call an external API for integration tests, which might take up to 90sec to perform the action.

In order to cleanup properly, I defined an afterEach()-block, which will delete any generated remote resources, in case an expect fails and some resources weren't deleted.

The tests themselves have an increased timeout, while the rest of the tests should retain their default and small timeout:

it('should create remote resource', () => {...}).timeout(120000)

However, I can't do the same with afterEach().timeout(120000), because the function does not exist - nor can I use the function ()-notation due to the unknown resource names:

describe('Resources', function () {
  beforeEach(() => {
    this._resources = null
  })

  it('should create resources', async () => {
    this._resources = await createResources()
    expect(false).to.equal(true)   // fail test, so...
    await deleteResources()        // will never be called
  })

  afterEach(async() => {
    this._resources.map(entry => {
      await // ... delete any created resources ...
    })
  }).timeout(120000)
})

Any hints? Mocha is version 4.0.1, chai is 4.1.2

Body:
If you need to use dynamic context you have to use normal function.

describe('Resources', function () {
  // ...
  afterEach(function (){
    this.timeout(120000)  // this should work
    // ... delete any created resources ...
  })
})


问:
How do I send HTML email in Spring MVC?
I have successfully sent simple email using this:

```<code>SimpleMailMessage mailMessage = new SimpleMailMessage();

mailMessage.setTo("someone@abc.example");
mailMessage.setSubject("This is the test message for testing gmail smtp server using spring mail");
mailMessage.setFrom("abc@gmail.com");
mailMessage.setText("This is the test message for testing gmail smtp server using spring mail. \n" +
        "Thanks \n Regards \n Saurabh ");
mailSender.send(mailMessage);
</code>```

What setting I need to chnage so that I can send HTML emails

答:
Class Level:

```<code>public String sendEmailToUsers(String emailId,String subject, String name){
    String result =null;
    MimeMessage message =mailSender.createMimeMessage();
    try {

        MimeMessageHelper helper = new MimeMessageHelper(message, false, "utf-8");
        String htmlMsg = "<body style='border:2px solid black'>"
                    +"Your onetime password for registration is  "
                        + "Please use this OTP to complete your new user registration."+
                          "OTP is confidential, do not share this  with anyone.</body>";
        message.setContent(htmlMsg, "text/html");
        helper.setTo(emailId);
        helper.setSubject(subject);
        result="success";
        mailSender.send(message);
    } catch (MessagingException e) {
        throw new MailParseException(e);
    }finally {
        if(result !="success"){
            result="fail";
        }
    }

    return result;

}
</code>```

XML Level:

```<code>    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com" />
    <property name="port" value="587" />
    <property name="username" value="********@gmail.com" />
    <property name="password" value="********" />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.transport.protocol">smtp</prop>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
        </props>
    </property>
</bean>
</code>```

OwnerDisplayName: John

Title: How do I send HTML email in Spring MVC?

Body:
I have successfully sent simple email using this:

SimpleMailMessage mailMessage = new SimpleMailMessage();

mailMessage.setTo("someone@abc.example");
mailMessage.setSubject("This is the test message for testing gmail smtp server using spring mail");
mailMessage.setFrom("abc@gmail.com");
mailMessage.setText("This is the test message for testing gmail smtp server using spring mail. \n" +
        "Thanks \n Regards \n Saurabh ");
mailSender.send(mailMessage);

What setting I need to chnage so that I can send HTML emails

Body:
Class Level:

public String sendEmailToUsers(String emailId,String subject, String name){
    String result =null;
    MimeMessage message =mailSender.createMimeMessage();
    try {

        MimeMessageHelper helper = new MimeMessageHelper(message, false, "utf-8");
        String htmlMsg = "<body style='border:2px solid black'>"
                    +"Your onetime password for registration is  "
                        + "Please use this OTP to complete your new user registration."+
                          "OTP is confidential, do not share this  with anyone.</body>";
        message.setContent(htmlMsg, "text/html");
        helper.setTo(emailId);
        helper.setSubject(subject);
        result="success";
        mailSender.send(message);
    } catch (MessagingException e) {
        throw new MailParseException(e);
    }finally {
        if(result !="success"){
            result="fail";
        }
    }

    return result;

}

XML Level:

    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com" />
    <property name="port" value="587" />
    <property name="username" value="********@gmail.com" />
    <property name="password" value="********" />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.transport.protocol">smtp</prop>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
        </props>
    </property>
</bean>


问:
unity3d Caching.CleanCache won't work
I'm using AssetBundles in my game and want to let the user to clear AssetBundle cache in the settings page.
I've tried to use Caching.CleanCache but it returns "false" because I'm using AssetBundle cache in the settings page.I have tried to load an empty scene and clear cache but it won't work either.
do I need to restart the app? does anybody know any solution?    </p>

答:
let me answer my question.
after doing some research,I found that my game has some unloaded assetbundles.
I was able to remove cache after unload all assetbundles.</p>

Title: unity3d Caching.CleanCache won't work


问:
How to reuse one html head section?
I am using zend and not using AJAX in my site. Therefore I have to include all my CSS and JS files in head section of every phtml page.

```<code><html>
<head>
  <link rel="stylesheet" type="text/css" href="mycssfile.css" />
  <script type="text/javascript" src="myjsfile1.js"></script>
  <script type="text/javascript" src="myjsfile2.js"></script>
  .........
</head>
<body>
  .........
</body>

</html>
</code>```

Whenever I add any new CSS/JS file, I have to include it everywhere. Is there a good way that I can include all my CSS and JS file in a file/place and use that reference everywhere. May be there is a good way in zend.

答:
In normal PHP, you would just put the common bits in another template and include it:

```<code><?php include 'common/header_assets.php'; ?>

common/header_assets.php:
<link rel="stylesheet" type="text/css" href="main.css" />
<script type="text/javascript" src="myjsfile1.js"></script>
<script type="text/javascript" src="myjsfile1.js"></script>
</code>```

With the Zend Framework, you would want to create a layout for all of your templates to share that would have these common bits:

http://zendframework.com/manual/en/learning.quickstart.create-layout.html

Title: How to reuse one html head section?

Body:
I am using zend and not using AJAX in my site. Therefore I have to include all my CSS and JS files in head section of every phtml page.

  <link rel="stylesheet" type="text/css" href="mycssfile.css" />

  .........

  .........

Whenever I add any new CSS/JS file, I have to include it everywhere. Is there a good way that I can include all my CSS and JS file in a file/place and use that reference everywhere. May be there is a good way in zend.

Body:
In normal PHP, you would just put the common bits in another template and include it:

<?php include 'common/header_assets.php'; ?>

common/header_assets.php:
<link rel="stylesheet" type="text/css" href="main.css" />
<script type="text/javascript" src="myjsfile1.js"></script>
<script type="text/javascript" src="myjsfile1.js"></script>

With the Zend Framework, you would want to create a layout for all of your templates to share that would have these common bits:

http://zendframework.com/manual/en/learning.quickstart.create-layout.html


问:
Saving date into SQLite Database using javafx wrong
Whenever I try to enter the date into the database using my JavaFX JFXDatePicker in the application. However, it always enters the date as '1992'. I don't even have 1992 available in the choices.

When I print the DatePicker.getValue() the correct date is being printed to the console.
This is the code:

```<code>public void RemRoom() {
    Connection con = null;
    PreparedStatement pst = null;
    ResultSet rs = null;
    try {
        con = DriverManager.getConnection("jdbc:sqlite:Rooms.db");
        pst = con.prepareStatement("UPDATE " + tp + " set isAvail = 'false' where RoomID = '" + rm + "'");
        pst.execute();
        LocalDate sd = ControllerScr2.getInstance().chkIn.getValue();
        System.out.println(sd);
        pst = con.prepareStatement("UPDATE " + tp + " set StartDate = " + sd + " where RoomID = '" + rm + "'");
        pst.execute();
        pst.close();
        con.close();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
</code>```

答:
Have you tried formatting the date picked?

```<code>myDatePicker.getValue().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"))
</code>```

There's also some useful info on how to manipulate DatePickers here

Body:
Whenever I try to enter the date into the database using my JavaFX JFXDatePicker in the application. However, it always enters the date as '1992'. I don't even have 1992 available in the choices.

When I print the DatePicker.getValue() the correct date is being printed to the console.
This is the code:

public void RemRoom() {
    Connection con = null;
    PreparedStatement pst = null;
    ResultSet rs = null;
    try {
        con = DriverManager.getConnection("jdbc:sqlite:Rooms.db");
        pst = con.prepareStatement("UPDATE " + tp + " set isAvail = 'false' where RoomID = '" + rm + "'");
        pst.execute();
        LocalDate sd = ControllerScr2.getInstance().chkIn.getValue();
        System.out.println(sd);
        pst = con.prepareStatement("UPDATE " + tp + " set StartDate = " + sd + " where RoomID = '" + rm + "'");
        pst.execute();
        pst.close();
        con.close();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Body:
Have you tried formatting the date picked?

myDatePicker.getValue().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"))

There's also some useful info on how to manipulate DatePickers here


问:
Add dynamic values for ID, href and aria-controls using Jquery
I want to add the dynamic values for the attributes(href, id, aria-controls), so that i can toggle down the text in multiple places for a single page. Just for your reference i have added "href="#0_read_more", aria-controls="0_read_more", id="0_read_more" in three places in the provided sample code. As well i have increment the values for other two div sections like given in the sample html code. Kindly help me out on this..

Thanks in advance.

                  Read More

                  Read More

                  Read More

```

答:
try this

$(document).ready(function(){
    $('.collapsed').each(function(i){
        var a = '#'+ (i++)+'_read_more';
        $(this).attr('href',a);
    });
    $('.collapsed').each(function(i){
        var b = (i++)+'_read_more'  ;
        $(this).attr('aria-controls',b);
    });
    $('.collapse').each(function(i){
        var c = (i++)+'_read_more' ;
        $(this).attr('id',c);
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="image-text">

                  Read More
    <div class="collapse" aria-expanded="false" style="height: 0px;"></div>
</div>

<div class="image-text">

                  Read More
    <div class="collapse" aria-expanded="false" style="height: 0px;"></div>
</div>

<div class="image-text">

                  Read More
    <div class="collapse" aria-expanded="false" style="height: 0px;"></div>
</div></code>```

Body:
try this

$(document).ready(function(){
    $('.collapsed').each(function(i){
        var a = '#'+ (i++)+'_read_more';
        $(this).attr('href',a);
    });
    $('.collapsed').each(function(i){
        var b = (i++)+'_read_more'  ;
        $(this).attr('aria-controls',b);
    });
    $('.collapse').each(function(i){
        var c = (i++)+'_read_more' ;
        $(this).attr('id',c);
    });
});

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="image-text">
    <a data-toggle="collapse" aria-expanded="false" class="collapsed">
                  Read More</a>
    <div class="collapse" aria-expanded="false" style="height: 0px;"></div>
</div>

<div class="image-text">
    <a data-toggle="collapse" aria-expanded="false" class="collapsed">
                  Read More</a>
    <div class="collapse" aria-expanded="false" style="height: 0px;"></div>
</div>

<div class="image-text">
    <a data-toggle="collapse" aria-expanded="false" class="collapsed">
                  Read More</a>
    <div class="collapse" aria-expanded="false" style="height: 0px;"></div>
</div>


问:
Suspended mode in the UWP application
I have the UWP application that uses ReactiveUI for viewmodel to view binding. When the user gets logged in to the app the (when the log in command is executed) the following method is called:

```<code>private void RegisterActivityTrackingFunctionality()
    {
        Container = _container;
        Container.Resolve<IDialogService>().IsActive = true;
        _dispatcher = Window.Current.Dispatcher;

        Window.Current.CoreWindow.PointerPressed += CoreWindow_PointerPressed;
        Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
        _timer = Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(30)).Subscribe(_ => CheckActivityTime());
    }
</code>```

The timer is created to monitor users activity in the application. If the user is inactive for more than 15 minutes he is logged off from the application. Basically method CheckActivityTime() is called for this purpose:

```<code>private void CheckActivityTime()
    {
        _logger.Info("In a CheckActivityTime Method");
        if (Container.Resolve<TokenHolder>().IsActivityTimeElapsed)
        {
            if (_timer != null)
            {
                _timer.Dispose();
            }

            Task.Run(async () => await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
            () =>
            {
                try
                {
                    Container.Resolve<IDialogService>().IsActive = false;

                    var dialogService = Container.Resolve<IContentDialogService>();

                    if (dialogService.CurrentContentDialog != null)
                    {
                        dialogService.CurrentContentDialog.Hide();
                    }

                    var shellViewModel = Container.Resolve<ShellViewModel>();

                    if (shellViewModel.Router.NavigationStack.Count > 1)
                    {
                        shellViewModel.Router.NavigateBack.Execute(null);
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error("The unhandled exception occured in UI thread for logout mechanism", ex);
                }
            }
            ));
        }
    }
</code>```

The problem is like that: When app goes to suspended mode it does not always logout the user if the inactivity time exceeds 15 minutes.
Could anyone explain to me, what is the problem?
Maybe there is something wrong with timer setting? Or maybe I should not do the logout operation on the UI thread?

答:
What you can do is attach a handler to OnResuming event of App which is called each time app is resumed from suspended state and then check for the Activitytime and lock your app from there.

```<code>Application.Current.Resuming += new EventHandler<Object>(App_Resuming);
</code>```

Title: Suspended mode in the UWP application

Body:
I have the UWP application that uses ReactiveUI for viewmodel to view binding. When the user gets logged in to the app the (when the log in command is executed) the following method is called:

private void RegisterActivityTrackingFunctionality()
    {
        Container = _container;
        Container.Resolve<IDialogService>().IsActive = true;
        _dispatcher = Window.Current.Dispatcher;

        Window.Current.CoreWindow.PointerPressed += CoreWindow_PointerPressed;
        Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
        _timer = Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(30)).Subscribe(_ => CheckActivityTime());
    }

The timer is created to monitor users activity in the application. If the user is inactive for more than 15 minutes he is logged off from the application. Basically method CheckActivityTime() is called for this purpose:

private void CheckActivityTime()
    {
        _logger.Info("In a CheckActivityTime Method");
        if (Container.Resolve<TokenHolder>().IsActivityTimeElapsed)
        {
            if (_timer != null)
            {
                _timer.Dispose();
            }

            Task.Run(async () => await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
            () =>
            {
                try
                {
                    Container.Resolve<IDialogService>().IsActive = false;

                    var dialogService = Container.Resolve<IContentDialogService>();

                    if (dialogService.CurrentContentDialog != null)
                    {
                        dialogService.CurrentContentDialog.Hide();
                    }

                    var shellViewModel = Container.Resolve<ShellViewModel>();

                    if (shellViewModel.Router.NavigationStack.Count > 1)
                    {
                        shellViewModel.Router.NavigateBack.Execute(null);
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error("The unhandled exception occured in UI thread for logout mechanism", ex);
                }
            }
            ));
        }
    }

The problem is like that: When app goes to suspended mode it does not always logout the user if the inactivity time exceeds 15 minutes.
Could anyone explain to me, what is the problem?
Maybe there is something wrong with timer setting? Or maybe I should not do the logout operation on the UI thread?

Body:
What you can do is attach a handler to OnResuming event of App which is called each time app is resumed from suspended state and then check for the Activitytime and lock your app from there.

Application.Current.Resuming += new EventHandler<Object>(App_Resuming);


问:
Wicket one form with two submit buttons with the same validation
I use wicket 7.x. I have a form with two submit buttons. The two button do different things on submit event but they have the same field validation. I override the AjaxButton onSubmit in one of them to separate the different behavior but i couldn't pass into the same validation method.

```<code>button = new AjaxButton("id",this.getRootForm()) {
    @Override
    protected void onSubmit(AjaxRequestTarget target, Form<?> form){...}
}
button.setDefaultFormProcessing(false);

@Override
protected void onValidate() {...}

@Override
protected void onSubmit() {...}
</code>```

How could i pass through the same validation method with alle the forms?

Edited Answer

```<code>this.getRootForm().add(new IFormValidator() {

     @Override
     public void validate(Form<?> form) {
           doValidate(form);
     }
     @Override
     public FormComponent<?>[] getDependentFormComponents() {
         FormComponent<?>[] c = new FormComponent<?>[6];
         c[0] = nome;
         c[1] = email;
         c[2] = cognome;
         c[3] = indirizzo;
         c[4] = telefono;
         c[5] = captcha;
         return c;
      }
});

protected void doValidate(Form<?> form) {...}

button = new AjaxButton("id",this.getRootForm()) {
    @Override
    protected void onSubmit(AjaxRequestTarget target, Form<?> form){
        doValidate(form);
        if (!form.hasError()) {
            ...
        } else{
            target.add(feedbackPanel);
        }
    }
}
button.setDefaultFormProcessing(false);
</code>```

答:
You should implement IValidator or IFormValidator and use it in all your Forms.

See https://ci.apache.org/projects/wicket/guide/8.x/single.html#_form_validation_and_feedback_messages

Update

```<code>public class MyValidatingBehavior extends Behavior implements IValidator {

  @Override
  public void onComponentTag(Component component, ComponentTag tag) {
    super.onComponentTag(component, tag);
    if (component.hasErrorMessage()) {
      tag.append("class", "my-error-style", " ");
    }
  }

  @Override
  public void validate(final IValidatable<String> validatable) {
    final String candidate = validatable.getValue();
    if (!isValid(candidate)) {
        validatable.error(new ValidationError(this));
    }
  }
}
</code>```

Body:
I use wicket 7.x. I have a form with two submit buttons. The two button do different things on submit event but they have the same field validation. I override the AjaxButton onSubmit in one of them to separate the different behavior but i couldn't pass into the same validation method.

button = new AjaxButton("id",this.getRootForm()) {
    @Override
    protected void onSubmit(AjaxRequestTarget target, Form<?> form){...}
}
button.setDefaultFormProcessing(false);

@Override
protected void onValidate() {...}

@Override
protected void onSubmit() {...}

How could i pass through the same validation method with alle the forms?

Edited Answer

this.getRootForm().add(new IFormValidator() {

     @Override
     public void validate(Form<?> form) {
           doValidate(form);
     }
     @Override
     public FormComponent<?>[] getDependentFormComponents() {
         FormComponent<?>[] c = new FormComponent<?>[6];
         c[0] = nome;
         c[1] = email;
         c[2] = cognome;
         c[3] = indirizzo;
         c[4] = telefono;
         c[5] = captcha;
         return c;
      }
});

protected void doValidate(Form<?> form) {...}

button = new AjaxButton("id",this.getRootForm()) {
    @Override
    protected void onSubmit(AjaxRequestTarget target, Form<?> form){
        doValidate(form);
        if (!form.hasError()) {
            ...
        } else{
            target.add(feedbackPanel);
        }
    }
}
button.setDefaultFormProcessing(false);

Body:
You should implement IValidator or IFormValidator and use it in all your Forms.

See https://ci.apache.org/projects/wicket/guide/8.x/single.html#_form_validation_and_feedback_messages

Update

public class MyValidatingBehavior extends Behavior implements IValidator {

  @Override
  public void onComponentTag(Component component, ComponentTag tag) {
    super.onComponentTag(component, tag);
    if (component.hasErrorMessage()) {
      tag.append("class", "my-error-style", " ");
    }
  }

  @Override
  public void validate(final IValidatable<String> validatable) {
    final String candidate = validatable.getValue();
    if (!isValid(candidate)) {
        validatable.error(new ValidationError(this));
    }
  }
}