问:
Problems with Azure application manifest trying to authenticate with office-js-helpers in an Outlook web add-in
I'm using office-js-helpers in order to get an OAuth token in my Outlook web add-in so I can use it for OAuthCredentials with the EWS Managed API (code for that is in an Azure App Service using the ASP.NET Web API).

I have configured my app's application registration in my test Office 365 tenant (e.g. mytenant.onmicrosoft.com, which is NOT the same Azure subscription hosting the web app - if that matters) as a Native app with oauth2AllowImplicitFlow set to true.  I used a Native app type instead of a Web/API app to bypass an unexpected error indicating my app requires admin consent - even though no application permissions were requested - but that's another story (perhaps I must use Native anyway - not 100% sure).

I made sure that the Redirect URI (aka reply URL) in the app registration points to the same page as the Outlook add-in (e.g. https://mywebapp.azurewebsites.net/MessageRead.html).

Here is my app manifest:

{
  "appId": "a11aaa11-1a5c-484a-b1d6-86c298e8f250",
  "appRoles": [],
  "availableToOtherTenants": true,
  "displayName": "My App",
  "errorUrl": null,
  "groupMembershipClaims": null,
  "optionalClaims": null,
  "acceptMappedClaims": null,
  "homepage": "https://myapp.azurewebsites.net/MessageRead.html",
  "identifierUris": [],
  "keyCredentials": [],
  "knownClientApplications": [],
  "logoutUrl": null,
  "oauth2AllowImplicitFlow": true,
  "oauth2AllowUrlPathMatching": false,
  "oauth2Permissions": [],
  "oauth2RequiredPostResponse": false,
  "objectId": "a11aaa11-99a1-4044-a950-937b484deb8e",
  "passwordCredentials": [],
  "publicClient": true,
  "supportsConvergence": null,
  "replyUrls": [
    "https://myapp.azurewebsites.net/MessageRead.html"
  ],
  "requiredResourceAccess": [
    {
      "resourceAppId": "00000003-0000-0000-c000-000000000000",
      "resourceAccess": [
        {
          "id": "e1fe6dd8-ba31-4d61-89e7-88639da4683d",
          "type": "Scope"
        }
      ]
    },
    {
      "resourceAppId": "00000002-0000-0000-c000-000000000000",
      "resourceAccess": [
        {
          "id": "311a71cc-e848-46a1-bdf8-97ff7156d8e6",
          "type": "Scope"
        },
        {
          "id": "a42657d6-7f20-40e3-b6f0-cee03008a62a",
          "type": "Scope"
        }
      ]
    },
    {
      "resourceAppId": "00000002-0000-0ff1-ce00-000000000000",
      "resourceAccess": [
        {
          "id": "2e83d72d-8895-4b66-9eea-abb43449ab8b",
          "type": "Scope"
        },
        {
          "id": "ab4f2b77-0b06-4fc1-a9de-02113fc2ab7c",
          "type": "Scope"
        },
        {
          "id": "5eb43c10-865a-4259-960a-83946678f8dd",
          "type": "Scope"
        },
        {
          "id": "3b5f3d61-589b-4a3c-a359-5dd4b5ee5bd5",
          "type": "Scope"
        }
      ]
    }
  ],
  "samlMetadataUrl": null
}

I also made sure to add the authority URLs to my add-in's manifest:

```<code><AppDomains>
 <AppDomain>https://login.windows.net</AppDomain>
 <AppDomain>https://login.microsoftonline.com</AppDomain>
</AppDomains>
</code>```

This is the code I'm using in the add-in for the authentication with office-js-helpers:

```<code>    // The Office initialize function must be run each time a new page is loaded.
Office.initialize = function(reason) {
    $(document).ready(function () {

        // Determine if we are running inside of an authentication dialog
        // If so then just terminate the running function

        if (OfficeHelpers.Authenticator.isAuthDialog()) {
            // Adding code here isn't guaranteed to run as we need to close the dialog
            // Currently we have no realistic way of determining when the dialog is completely
            // closed.
            return;
        }

        // Create a new instance of Authenticator
        var authenticator = new OfficeHelpers.Authenticator();

        authenticator.endpoints.registerAzureADAuth('a11aaa11-1a5c-484a-b1d6-86c298e8f250', 'mytenant.onmicrosoft.com');

        // Add event handler to the button
        $('#login').click(function () {
            $('#token', window.parent.document).text('Authenticating...');

            authenticator.authenticate('AzureAD', true)
                .then(function (token) {
                    // Consume and store the acess token
                    $('#token', window.parent.document).text(prettify(token));
                    authToken = token.access_token;
                })
                .catch(function (error) {
                    // Handle the error
                    $('#token', window.parent.document).text(prettify(error));
                });
        });
    });
};
</code>```

Now the code in the add-in can properly sign in the user and ask for the required permissions, but after clicking the Accept button on the application authorization step the following error is returned:

AADSTS50011: The reply address 'https://mywebapp.azurewebsites.net' does not match the reply addresses configured for the application: 'a11aaa11-1a5c-484a-b1d6-86c298e8f250'. More details: not specified

The error now returns every time I click the Login button (the user is no longer prompted to sign in).  It never did retrieve the token.  The full auth URL is:

https://login.windows.net/mydomain.onmicrosoft.com/oauth2/authorize?response_type=token&client_id=a11aaa11-484a-b1d6-86c298e8f250&redirect_uri=https%3A%2F%2Fmywebapp.azurewebsites.net&resource=https%3A%2F%2Fgraph.microsoft.com&state=982599964&nonce=3994725115

What am I doing wrong? Could the issue actually be because the host name of the web app (the redirect URI) does not match the domain of the Azure AD tenant hosting the app registration?  If so, how can I grant permissions to Exchange Online from my Azure subscription hosting the web app which does not have Office 365 or Exchange Online?  Would I have to add an Azure subscription to my test Office 365 tenant so that it can also host a web application??

答:
From your app manifest, I found that you used https://myapp.azurewebsites.net/MessageRead.html as one of the replyUrls.
And below is the url that you are using to get consent from user.

https://login.windows.net/mydomain.onmicrosoft.com/oauth2/authorize?response_type=token&client_id=a11aaa11-484a-b1d6-86c298e8f250&redirect_uri=https%3A%2F%2Fmywebapp.azurewebsites.net&resource=https%3A%2F%2Fgraph.microsoft.com&state=982599964&nonce=3994725115.

If you observe above url, you mentioned redirect_uri as https://myapp.azurewebsites.net. But redirect_uri should match with at least one of the replyUrls you mentioned in the app manifest.

Try to replace https://myapp.azurewebsites.net with https://myapp.azurewebsites.net/MessageRead.html in authorization url.

I have updated them in below url, if you want you can directly try below url.

https://login.windows.net/mydomain.onmicrosoft.com/oauth2/authorize?response_type=token&client_id=a11aaa11-484a-b1d6-86c298e8f250&redirect_uri=https%3A%2F%2Fmywebapp.azurewebsites.net%2FMessageRead.html&resource=https%3A%2F%2Fgraph.microsoft.com&state=982599964&nonce=3994725115

Body:
I'm using office-js-helpers in order to get an OAuth token in my Outlook web add-in so I can use it for OAuthCredentials with the EWS Managed API (code for that is in an Azure App Service using the ASP.NET Web API).

I have configured my app's application registration in my test Office 365 tenant (e.g. mytenant.onmicrosoft.com, which is NOT the same Azure subscription hosting the web app - if that matters) as a Native app with oauth2AllowImplicitFlow set to true.  I used a Native app type instead of a Web/API app to bypass an unexpected error indicating my app requires admin consent - even though no application permissions were requested - but that's another story (perhaps I must use Native anyway - not 100% sure).

I made sure that the Redirect URI (aka reply URL) in the app registration points to the same page as the Outlook add-in (e.g. https://mywebapp.azurewebsites.net/MessageRead.html).

Here is my app manifest:

{
  "appId": "a11aaa11-1a5c-484a-b1d6-86c298e8f250",
  "appRoles": [],
  "availableToOtherTenants": true,
  "displayName": "My App",
  "errorUrl": null,
  "groupMembershipClaims": null,
  "optionalClaims": null,
  "acceptMappedClaims": null,
  "homepage": "https://myapp.azurewebsites.net/MessageRead.html",
  "identifierUris": [],
  "keyCredentials": [],
  "knownClientApplications": [],
  "logoutUrl": null,
  "oauth2AllowImplicitFlow": true,
  "oauth2AllowUrlPathMatching": false,
  "oauth2Permissions": [],
  "oauth2RequiredPostResponse": false,
  "objectId": "a11aaa11-99a1-4044-a950-937b484deb8e",
  "passwordCredentials": [],
  "publicClient": true,
  "supportsConvergence": null,
  "replyUrls": [
    "https://myapp.azurewebsites.net/MessageRead.html"
  ],
  "requiredResourceAccess": [
    {
      "resourceAppId": "00000003-0000-0000-c000-000000000000",
      "resourceAccess": [
        {
          "id": "e1fe6dd8-ba31-4d61-89e7-88639da4683d",
          "type": "Scope"
        }
      ]
    },
    {
      "resourceAppId": "00000002-0000-0000-c000-000000000000",
      "resourceAccess": [
        {
          "id": "311a71cc-e848-46a1-bdf8-97ff7156d8e6",
          "type": "Scope"
        },
        {
          "id": "a42657d6-7f20-40e3-b6f0-cee03008a62a",
          "type": "Scope"
        }
      ]
    },
    {
      "resourceAppId": "00000002-0000-0ff1-ce00-000000000000",
      "resourceAccess": [
        {
          "id": "2e83d72d-8895-4b66-9eea-abb43449ab8b",
          "type": "Scope"
        },
        {
          "id": "ab4f2b77-0b06-4fc1-a9de-02113fc2ab7c",
          "type": "Scope"
        },
        {
          "id": "5eb43c10-865a-4259-960a-83946678f8dd",
          "type": "Scope"
        },
        {
          "id": "3b5f3d61-589b-4a3c-a359-5dd4b5ee5bd5",
          "type": "Scope"
        }
      ]
    }
  ],
  "samlMetadataUrl": null
}

I also made sure to add the authority URLs to my add-in's manifest:

<AppDomains>
 <AppDomain>https://login.windows.net</AppDomain>
 <AppDomain>https://login.microsoftonline.com</AppDomain>
</AppDomains>

This is the code I'm using in the add-in for the authentication with office-js-helpers:

    // The Office initialize function must be run each time a new page is loaded.
Office.initialize = function(reason) {
    $(document).ready(function () {

        // Determine if we are running inside of an authentication dialog
        // If so then just terminate the running function

        if (OfficeHelpers.Authenticator.isAuthDialog()) {
            // Adding code here isn't guaranteed to run as we need to close the dialog
            // Currently we have no realistic way of determining when the dialog is completely
            // closed.
            return;
        }

        // Create a new instance of Authenticator
        var authenticator = new OfficeHelpers.Authenticator();

        authenticator.endpoints.registerAzureADAuth('a11aaa11-1a5c-484a-b1d6-86c298e8f250', 'mytenant.onmicrosoft.com');

        // Add event handler to the button
        $('#login').click(function () {
            $('#token', window.parent.document).text('Authenticating...');

            authenticator.authenticate('AzureAD', true)
                .then(function (token) {
                    // Consume and store the acess token
                    $('#token', window.parent.document).text(prettify(token));
                    authToken = token.access_token;
                })
                .catch(function (error) {
                    // Handle the error
                    $('#token', window.parent.document).text(prettify(error));
                });
        });
    });
};

Now the code in the add-in can properly sign in the user and ask for the required permissions, but after clicking the Accept button on the application authorization step the following error is returned:

AADSTS50011: The reply address 'https://mywebapp.azurewebsites.net' does not match the reply addresses configured for the application: 'a11aaa11-1a5c-484a-b1d6-86c298e8f250'. More details: not specified

The error now returns every time I click the Login button (the user is no longer prompted to sign in).  It never did retrieve the token.  The full auth URL is:

https://login.windows.net/mydomain.onmicrosoft.com/oauth2/authorize?response_type=token&client_id=a11aaa11-484a-b1d6-86c298e8f250&redirect_uri=https%3A%2F%2Fmywebapp.azurewebsites.net&resource=https%3A%2F%2Fgraph.microsoft.com&state=982599964&nonce=3994725115

What am I doing wrong? Could the issue actually be because the host name of the web app (the redirect URI) does not match the domain of the Azure AD tenant hosting the app registration?  If so, how can I grant permissions to Exchange Online from my Azure subscription hosting the web app which does not have Office 365 or Exchange Online?  Would I have to add an Azure subscription to my test Office 365 tenant so that it can also host a web application??


来源: stackexchange

问:
Sending a message through a url
I have an application that allows me to send as sms in a url using my android phone as follows:

```<code>http://196.96.53.25/sendsms? phone=0724206400&text=Yusuf_kiprop
</code>```

however, when I remove the underscore from the text as follows:

```<code>http://196.96.53.25/sendsms?phone=0724206400&text=Yusuf kiprop
</code>```

I get an error that webpage is unavailable. What could be the issue?

答:
If you are sending from php  then encode the message like

```<code>$message=urlencode('Yusuf kiprop');
http://196.96.53.25/sendsms?phone=0724206400&text=$message
</code>```

If you are checking it in the browser directly its not being url encoded thats why.
Try this insted-:

```<code>http://196.96.53.25/sendsms?phone=0724206400&text=Yusuf%20kiprop
</code>```

ContentLicense: CC BY-SA 3.0

Title: Sending a message through a url

Body:
I have an application that allows me to send as sms in a url using my android phone as follows:

http://196.96.53.25/sendsms? phone=0724206400&text=Yusuf_kiprop

however, when I remove the underscore from the text as follows:

http://196.96.53.25/sendsms?phone=0724206400&text=Yusuf kiprop

I get an error that webpage is unavailable. What could be the issue?

Body:
If you are sending from php  then encode the message like

$message=urlencode('Yusuf kiprop');
http://196.96.53.25/sendsms?phone=0724206400&text=$message

If you are checking it in the browser directly its not being url encoded thats why.
Try this insted-:

http://196.96.53.25/sendsms?phone=0724206400&text=Yusuf%20kiprop


问:
How to show ajax response into bootstrap modal
I want to pop up a modal which will show dynamic data comes from query. so when a user clicked related school will show into modal. I got the response but i'm not getting how can i show into that modal. any suggestion please?

Button:

```<code> <a href="#." data-toggle="modal" data-target="#myModal" data-id="{{$user->id}}"  class="chooseSchoolBtn">Choose School</a>
</code>```

Ajax :

```<code>$(".chooseSchoolBtn").on("click", function (argument) {
    //console.log($(this).data("id"))
    var user_id = $(this).data("id")
    var info = $.get("{{url('school-list')}}", {
        id: user_id
    });
    info.done(function (data) {
        console.log(data)
    });
});
</code>```

Modal:

```<code><div class="modal-body">
    // This section will come dynamically
    <div class="col-md-2 col-sm-4 col-xs-12">
        <div class="single_school">
            <div class="selection_area">
                <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
            </div>
            <div class="school_img_area" style="background-image: url(school/images/school/school1.jpg);">
            </div>
            <div class="school_info">
                <p class="school_name">School Name</p>
                <p class="school_description">Good School...</p>
                <p class="school_price">12$</p>
            </div>
        </div>
    </div>
    // dynamic section ends
</div>
</code>```

json response :

```<code>{
    id: 1,
    user_id: 2,
    price: "2340.00",
    name: "XYZ",
    display_image: "1510570005ajaPXajmik.png"
}, {
    id: 3,
    user_id: 2,
    price: "123.00",
    name: "ABC",
    display_image: "1510570049QZWiQUh7zY.jpg"
}
</code>```

答:
```<code>$(document).on("click", ".chooseSchoolBtn", function () {
        var schoolId= $(this).data('id');
        $('#modalId').modal('show');
        $.ajax({
            type: "POST",
            url: "some_url_to_get_school_info",
            data: {'sid':schoolId},
            success: function(data){
              $('#div_id_to_show').html(data);
            },
            error: function(){
                alert("Fail")
            }
        });
    });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to pop up a modal which will show dynamic data comes from query. so when a user clicked related school will show into modal. I got the response but i'm not getting how can i show into that modal. any suggestion please?

Button:

 id}}"  class="chooseSchoolBtn">Choose School

Ajax :

$(".chooseSchoolBtn").on("click", function (argument) {
    //console.log($(this).data("id"))
    var user_id = $(this).data("id")
    var info = $.get("{{url('school-list')}}", {
        id: user_id
    });
    info.done(function (data) {
        console.log(data)
    });
});

Modal:

    // This section will come dynamically

School Name

Good School...

12$

    // dynamic section ends

json response :

{
    id: 1,
    user_id: 2,
    price: "2340.00",
    name: "XYZ",
    display_image: "1510570005ajaPXajmik.png"
}, {
    id: 3,
    user_id: 2,
    price: "123.00",
    name: "ABC",
    display_image: "1510570049QZWiQUh7zY.jpg"
}


问:
Connection string for different MS SQL servers
I have several SQL servers in my system:

```<code>2017 MSSQLSERVER
2008 SQLEXPRESS
</code>```

In SSMS I see them like:

```<code>GM\
GM\SQLEXPRESS
</code>```

If I need to connect to SQLEXPRESS I use connection string with . in Server:

```<code>connectionString="Server=.;Database=LearnCSharp;Integrated Security=True"
</code>```

But what does . means in my case and what should be placed in connection string in order to connect to 2017 MSSQLSERVER?

UPD.:

. connects to 2017 server. I have noticed that before computer restart it was connecting to 2008 server

GM connects to 2017 server.

.\MSSQLSERVER generates exception in my application;

```<code>System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid) ---> System.ComponentModel.Win32Exception (0x80004005): The parameter is incorrect
</code>```

.\SQLEXPRESS and GM\SQLEXPRESS - both connects to server 2008

答:
It means localhost or "this machine"

To specify an instance name, use a backslash after the dot (or computer name):

```<code>.\SQLEXPRESS
YOURCOMPUTER\SQLEXPRESS
OTHERCOMPUTER\SQLEXPRESS
</code>```

etc

Remember when this app is deployed to another machine, the value of "this machine" changes. This may or may not be what you want, so watch for it in future

It's also worth noting that the default SQL Server instance cannot be referenced by name, and if you try to give its name the connection won't work out. If you know you want to connect to the default SQL Server instance (whichever one that is, and there can be only one) then don't put a slash or a name, just a reference to the machine:

```<code>.

YOURCOMPUTER
</code>```

etc

Body:
I have several SQL servers in my system:

2017 MSSQLSERVER
2008 SQLEXPRESS

In SSMS I see them like:

GM\
GM\SQLEXPRESS

If I need to connect to SQLEXPRESS I use connection string with . in Server:

connectionString="Server=.;Database=LearnCSharp;Integrated Security=True"

But what does . means in my case and what should be placed in connection string in order to connect to 2017 MSSQLSERVER?

UPD.:

. connects to 2017 server. I have noticed that before computer restart it was connecting to 2008 server

GM connects to 2017 server.

.\MSSQLSERVER generates exception in my application;

System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid) ---> System.ComponentModel.Win32Exception (0x80004005): The parameter is incorrect

.\SQLEXPRESS and GM\SQLEXPRESS - both connects to server 2008

Body:
It means localhost or "this machine"

To specify an instance name, use a backslash after the dot (or computer name):

.\SQLEXPRESS
YOURCOMPUTER\SQLEXPRESS
OTHERCOMPUTER\SQLEXPRESS

etc

Remember when this app is deployed to another machine, the value of "this machine" changes. This may or may not be what you want, so watch for it in future

It's also worth noting that the default SQL Server instance cannot be referenced by name, and if you try to give its name the connection won't work out. If you know you want to connect to the default SQL Server instance (whichever one that is, and there can be only one) then don't put a slash or a name, just a reference to the machine:

.

YOURCOMPUTER

etc


问:
Xcode UItextField Transparency
I figured out how to make the UITextField transparent, but I now need to make the placeholder text white. Is this possible? Thanks in advance for your help!</p>

答:
Try this:    </p>

```<code>UIColor *color = [UIColor whiteColor];
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];
</code>```

Title: Xcode UItextField Transparency

Body:
Try this:

UIColor *color = [UIColor whiteColor];
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];


问:
Entity Framework Inheritance - determine object type
I have an Entity Framework Model similar to this:

Person

Employee (Inherits Person)

Contact (Inherits Person)

I can Add,Query (Using OfType), and Update Employees and Contacts with no problem. However, I can not determine what type a Person object is. Say for example:

```<code>var person = entities.People.Single(p => p.Id == 5);
</code>```

How can I do this:

```<code>if (person.IsEmployee){
//do something
} else if (person.IsContact) {
// do something else
}
</code>```

Alternatively, I can settle for this:

```<code>if (person.IsOfType<Employee>()){
// do something
} else if (person.IsOfType<Contact>()) {
// do something else
}
</code>```

Is there a way?

答:
```<code>if (person is Employee){
//do something
} else if (person is Contact) {
// do something else
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have an Entity Framework Model similar to this:

Person

Employee (Inherits Person)

Contact (Inherits Person)

I can Add,Query (Using OfType), and Update Employees and Contacts with no problem. However, I can not determine what type a Person object is. Say for example:

var person = entities.People.Single(p => p.Id == 5);

How can I do this:

if (person.IsEmployee){
//do something
} else if (person.IsContact) {
// do something else
}

Alternatively, I can settle for this:

if (person.IsOfType<Employee>()){
// do something
} else if (person.IsOfType<Contact>()) {
// do something else
}

Is there a way?


问:
textarea keyup event for submit
Here in my code I am having a textarea, where after user typed anything and press enter then some code need to be executed, but if the user press shift+enter then a new line should come in the textarea only. Below is my code so far --

```<code><textarea id="commentarea<?php echo $row[slno]; ?>" class="secondtextareay pull-left" rows="2" cols="50" placeholder="Post comments here..." onkeyup="enter_comment(<?php echo $row['slno']; ?>,<?php echo $CUID; ?>);"></textarea>

<script type="text/javascript">
function enter_comment(postid,userpostedid) {
       if (event.which == 13) {
           document.getElementById('commentarea'+postid).value='';
           //insert_comment(id); // Call any function here: Just pass your actual Parameters to enter_comment().
       }
       else
       {
           return;
       }
}
</script>
</code>```

Now, when I am pressing enter, it's working fine, but if I press shift+enter, then also it is doing the same. I want to prevent this, kindly help.

答:
```<code> if (event.keyCode == 13 && event.shiftKey) {
   // shift+enter pressed
 }
 else if(event.keyCode == 13){
          //enter key pressed
}else{
    //nothing
}
</code>```

Title: textarea keyup event for submit

Body:
Here in my code I am having a textarea, where after user typed anything and press enter then some code need to be executed, but if the user press shift+enter then a new line should come in the textarea only. Below is my code so far --

<textarea id="commentarea<?php echo $row[slno]; ?>" class="secondtextareay pull-left" rows="2" cols="50" placeholder="Post comments here..." onkeyup="enter_comment(<?php echo $row['slno']; ?>,<?php echo $CUID; ?>);"></textarea>

Now, when I am pressing enter, it's working fine, but if I press shift+enter, then also it is doing the same. I want to prevent this, kindly help.


问:
How can I refresh a tab from another using Javascript
I'm looking to achieve something like Wordpress does when you create a new post. It allows you to preview your post by opening a new tab. If, after that, you edit the post and preview it again, rather than opening another tab, it refreshes the previously opened tab (provided it is still open).

From some research it seems I can open a new window and give it a name to identify it, like this:

window.open(url,"foobar");

But, how can I later refresh this tab? location.reload() does not seem to take a name as an argument.

答:
You can do this by "storage" event. for more details follow

Communication between tabs or windows

https://developer.mozilla.org/en-US/docs/Web/Events/storage


问:
Update QUERY_STRING without page reload
I currently have this code snippet in a CGI script:

```<code>document.onkeydown = function(e) {
    switch (e.keyCode)  {
        case 37:
            document.location = "?direction=West";
            break;
        case 38:
            document.location = "?direction=North";
            break;
        case 39:
            document.location = "?direction=East";
            break;
        case 40:
            document.location = "?direction=South";
            break;
    }
};
</code>```

That will update the QUERY_STRING and then reload the page.
Can this be done without constantly reloading after every key stroke?
JSON? jQuery?

I've tried fiddling with url.replace() and history.pushState().. no luck..

答:
you can use window.history.pushState('page1', 'Title', 'page1?direction=West');
for this.
for more infomation adn help check link

Title: Update QUERY_STRING without page reload

Body:
I currently have this code snippet in a CGI script:

document.onkeydown = function(e) {
    switch (e.keyCode)  {
        case 37:
            document.location = "?direction=West";
            break;
        case 38:
            document.location = "?direction=North";
            break;
        case 39:
            document.location = "?direction=East";
            break;
        case 40:
            document.location = "?direction=South";
            break;
    }
};

That will update the QUERY_STRING and then reload the page.
Can this be done without constantly reloading after every key stroke?
JSON? jQuery?

I've tried fiddling with url.replace() and history.pushState().. no luck..


问:
convert list of lists with time strings to seconds and find count times between
I have a list of lists with time strings in them (this format "17:04:20"). I want to iterate through the list and count the times with a gap of 5 minutes or greater.

```<code>Eg. [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]
</code>```

In this case the gap would be from 17:08:54 + 5 minutes until 17:50:33.

I've been trying to do this by replacing the : in  the time strings and then turning the value into seconds and putting them sorted into a list of lists. Then I wanted to go through the list and if the next value is more than 300 seconds record this value.

Im having trouble even changing the strings to second can anyone help ?

答:
use datetime module to convert a string into time like below:</p>

```<code>from datetime import datetime

first_time = "17:08:54"

second_time = "17:50:33"

format = "%H:%M:%S"

time_delta = datetime.strptime(second_time, FMT) -datetime.strptime(first_time, FMT)

count = 0
gap = 5
if time_delta.seconds >= 5*60:
    count+=1
</code>```

Body:
I have a list of lists with time strings in them (this format "17:04:20"). I want to iterate through the list and count the times with a gap of 5 minutes or greater.

Eg. [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]

In this case the gap would be from 17:08:54 + 5 minutes until 17:50:33.

I've been trying to do this by replacing the : in  the time strings and then turning the value into seconds and putting them sorted into a list of lists. Then I wanted to go through the list and if the next value is more than 300 seconds record this value.

Im having trouble even changing the strings to second can anyone help ?

Body:
use datetime module to convert a string into time like below:

from datetime import datetime

first_time = "17:08:54"

second_time = "17:50:33"

format = "%H:%M:%S"

time_delta = datetime.strptime(second_time, FMT) -datetime.strptime(first_time, FMT)

count = 0
gap = 5
if time_delta.seconds >= 5*60:
    count+=1


问:
Firebase user data storage issue
I am working with Firebase Authentication and while coding I realised that I can use User user = FirebaseAuth.getInstance().getCurrentUser; to fetch user data in any activity through out the application if user successfully logged in but I am confused that whether I can store user data in sharedPreferences after user login or I can use User user = FirebaseAuth.getInstance().getCurrentUser; way to get user data in whichever activity I want to. So which method is preferable to use firebase user data. And if there any other method you have to suggest then you are always welcome. Thanks in advance.

答: Use always firebase user instance, because it gives to you an updated user instance. if you are going to save user data in sharedPreferences, you should always save user details in sharedPreferences when you update the user data.</p>

Title: Firebase user data storage issue


问:
Objective C: Custom keyboard extensions with images in iOS
I have created custom keyboard in my application.Now i want to display only 8 images at the beginning and later after payment i want to display whole collection of images. I am checking condition for payment if its done then only show all images but i cant debug it why images are not displayed even though condition is satisfied.
Also my question is keyboard view is base class of UIInputViewController so it will hit only once after app execution.

Please any help would be appreciated.

答: Click on image resources and then File Inspector tab in right side. Check Targets are selected or not.</p>


问:
how to make single array using all index value?
```<code>Array
(
    [8] => Array
        (
            [9] => Array
                (
                    [13] => Array()
            )
    )

[14] => Array
    (
        [15] => Array()
    )
)
</code>```

I want all index value in single array like this one array('8','9','13','14','15');

答:
Here's one possible way to do this. I've use recursion.</p>

```<code><?php

function getkeys($arr) {
    $keys = array();
    foreach (array_keys($arr) as $key) {
        $keys[] = $key;
        if (is_array($arr[$key])) {
            $keys = array_merge($keys, getkeys($arr[$key]));
        }
    }
    return $keys;
}

$arr = array(
    8 => array(
        9 => array(
            13 => array()
        )
    ),
    14 => array(
        15 => array()
    )
);

print_r(getKeys($arr));
</code>```

Body:
Array
(
    [8] => Array
        (
            [9] => Array
                (
                    [13] => Array()
            )
    )

[14] => Array
    (
        [15] => Array()
    )
)

I want all index value in single array like this one array('8','9','13','14','15');

Body:
Here's one possible way to do this. I've use recursion.

<?php

function getkeys($arr) {
    $keys = array();
    foreach (array_keys($arr) as $key) {
        $keys[] = $key;
        if (is_array($arr[$key])) {
            $keys = array_merge($keys, getkeys($arr[$key]));
        }
    }
    return $keys;
}

$arr = array(
    8 => array(
        9 => array(
            13 => array()
        )
    ),
    14 => array(
        15 => array()
    )
);

print_r(getKeys($arr));


问:
How to download a folder from github?
I wished to download the mysite folder from this link:
https://github.com/username/repository/master/</p>

答:
You can download the complete folder under Clone or Download options (Git URL or Download Zip)

There is a button of Download Zip

By using command you can download the complete folder on your machine but for that you need git on your machine. You can find the Git url uner

git clone  https://github.com/url

Title: How to download a folder from github?


问:
Debugging Jquery ajax function
JS code:

```<code>$.ajax({

        type: 'POST',
         url: 'http://localhost/MyServiceDir/Service.asmx/Foo',
         contentType: 'application/json; charset=utf-8',
         data: jsonData,
         success: function (msg) {
             alert("good");
         },
         error: function (xhr, status) {
              switch (status) {
                 case 404:
                     alert('File not found');
                     break;
                 case 500:
                     alert('Server error');
                     break;
                 case 0:
                     alert('Request aborted');
                     break;
                 default:
                     alert('Unknown error ' + status);
             }
         }
     });
</code>```

I get "unknown error error". How do I get to the bottom of this? I would like to know what the error actually is. Thanks!

答:
Try this out in the onerror event:

```<code>alert(xhr.statusText)
</code>```

EDIT:

I think your best bet here would be to install the FireBug Plugin on Firefox. This will allow you to see the ajax calls(enable "console" tab for this), responses, and error messages. Hopefully you will be able to get the info you need in this manner. This has been always been my method of choice for debugging ajax calls

Title: Debugging Jquery ajax function

Body:
JS code:

$.ajax({

        type: 'POST',
         url: 'http://localhost/MyServiceDir/Service.asmx/Foo',
         contentType: 'application/json; charset=utf-8',
         data: jsonData,
         success: function (msg) {
             alert("good");
         },
         error: function (xhr, status) {
              switch (status) {
                 case 404:
                     alert('File not found');
                     break;
                 case 500:
                     alert('Server error');
                     break;
                 case 0:
                     alert('Request aborted');
                     break;
                 default:
                     alert('Unknown error ' + status);
             }
         }
     });

I get "unknown error error". How do I get to the bottom of this? I would like to know what the error actually is. Thanks!

Body:
Try this out in the onerror event:

alert(xhr.statusText)

EDIT:

I think your best bet here would be to install the FireBug Plugin on Firefox. This will allow you to see the ajax calls(enable "console" tab for this), responses, and error messages. Hopefully you will be able to get the info you need in this manner. This has been always been my method of choice for debugging ajax calls


问:
create a employee in biometric machine using odoo 8
i am trying to many time create user using odoo 8 custom button using this code please help me.</p>

```<code>@api.multi
def createBioUsers(self):
    zk = zklib.ZKLib(config.key['ip'], int(config.key['port']))
    res = zk.connect()
    if res == False:
        zk.enableDevice()
        zk.disableDevice()
        zk.setUser(uid=8888, userid=8888, name='Ehtisham Faisal',
        password='1234', role=zkconst.LEVEL_USER)
        zk.enableDevice()
        zk.disconnect()
</code>```

答:
https://www.youtube.com/watch?v=ZWVS3ojgcAo
https://www.youtube.com/watch?v=TCL15yJBNuI&feature=youtu.be
https://github.com/saasier1/saasier_public_addons/tree/master/fingerprint_scanner
https://www.odoo.com/forum/help-1/question/is-there-a-fingerprint-scanner-that-feeds-into-hr-attendance-66704

I hope this information will help

Body:
i am trying to many time create user using odoo 8 custom button using this code please help me.

@api.multi
def createBioUsers(self):
    zk = zklib.ZKLib(config.key['ip'], int(config.key['port']))
    res = zk.connect()
    if res == False:
        zk.enableDevice()
        zk.disableDevice()
        zk.setUser(uid=8888, userid=8888, name='Ehtisham Faisal',
        password='1234', role=zkconst.LEVEL_USER)
        zk.enableDevice()
        zk.disconnect()


问:
ErrorException (E_ERROR) Creating default object from empty value (View: D:\
I am Newbie. I'm trying to return a view when i go to (for instance with selected id) /home/1 but i get this following error:

ErrorException (E_ERROR)
  Creating default object from empty value (View: D:\Michael..\resources\views\home.blade.php)

this is my route

```<code>Route::get('/', function () {
    return view('auth.login');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/home/{team_id}', 'HomeController@materialID');
</code>```

This is my controller

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Team;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $code = \App\Team::where('team_name',"Coding")->get();
        $design = \App\Team::where('team_name',"Design")->get();
        $qa = \App\Team::where('team_name',"Quality Assurance")->get();
        $ana = \App\Team::where('team_name',"Analytics")->get();
        return view('home',compact('code','design','qa','ana'));
    }

    public function materialID($team_id)
    {
        $material = Team::find($team_id);
        return view('material', compact('material'));
    }
}
</code>```

This is how i call it in my blade

```<code><a href="{{ url('home',$material->team_id = '1')}}">
     <h3>{{$code[0]->team_name}}</h3>
     <p style="padding-right: 35px">{{$code[0]->team_description}}</p>
</a>
</code>```

i dont know how to fix it.

答:
You should try this:</p>

```<code><a href="{{ url('home','1')}}">
     <h3>{{$code[0]->team_name}}</h3>
     <p style="padding-right: 35px">{{$code[0]->team_description}}</p>
</a>
</code>```

Body:
I am Newbie. I'm trying to return a view when i go to (for instance with selected id) /home/1 but i get this following error:

ErrorException (E_ERROR)
  Creating default object from empty value (View: D:\Michael..\resources\views\home.blade.php)

this is my route

Route::get('/', function () {
    return view('auth.login');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/home/{team_id}', 'HomeController@materialID');

This is my controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Team;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $code = \App\Team::where('team_name',"Coding")->get();
        $design = \App\Team::where('team_name',"Design")->get();
        $qa = \App\Team::where('team_name',"Quality Assurance")->get();
        $ana = \App\Team::where('team_name',"Analytics")->get();
        return view('home',compact('code','design','qa','ana'));
    }

    public function materialID($team_id)
    {
        $material = Team::find($team_id);
        return view('material', compact('material'));
    }
}

This is how i call it in my blade

team_id = '1')}}">

{{$code[0]->team_name}}

{{$code[0]->team_description}}

i dont know how to fix it.

Body:
You should try this:

<a href="{{ url('home','1')}}">
     <h3>{{$code[0]->team_name}}</h3>
     <p style="padding-right: 35px">{{$code[0]->team_description}}</p>
</a>


问:
Make multiple row of three dependent dropboxes
I built three dependent dropboxes: supplayer (supplier), kode_barang (ItemID), and nama_barang (variant). User can select a supplier, then choose an ItemID provided by that supplier, then decide which variant of product from the ItemID he want. I use this script:

```<code>window.load=$( document ).ready(function() {
    $.ajax({
        type:'POST',
        url:'supplayerAjaxData.php',
        success:function(html){
            $('#supplayer').html(html);
        }
    });
});

$( document ).ready(function() {
    $('#supplayer').on('change',function(){//change function on country to display all state
        var kode_supplayer = $('#supplayer').val();
        if(kode_supplayer){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'kode_supplayer='+kode_supplayer,
                success:function(html){
                    $('#kode_barang').html(html);
                    $('#nama_barang').html('<option value="">Select state first</option>');
                }
            });
        }else{
            $('#kode_barang').html('<option value="">Select country first</option>');
            $('#nama_barang').html('<option value="">Select state first</option>');
        }
    });

    $('#kode_barang').on('change',function(){//change state to display all city
        var kode_barang = $('#kode_barang').val();
        if(kode_barang){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'kode_barang='+kode_barang,
                success:function(html){
                    $('#nama_barang').html(html);
                }
            });
        }else{
            $('#nama_barang').html('<option value="">Select state first</option>');
        }
    });
});
</code>```

Then I show it in this way:

```<code><table id="theTable" border="1">

<thead><br><br>
    <tr>
        <th> Supplayer </th>
        <th> Kode Barang </th>
        <th> Nama Barang </th>
        <th> Quantity </th>
    <tr>
</thead>

<tbody>
    <tr>
        <td>
            <select class="selectpicker form-control" name="supplayer[]" id="supplayer" autofocus="autofocus" required>
                <option value="">Select an Option</option>
            </select>
        </td>
        <td>
            <select class="selectpicker form-control" name="kode_barang[]" id="kode_barang"  autofocus="autofocus" required>
                <option value="">Select an Option</option>
            </select>
        </td>
        <td>
            <select class="selectpicker form-control" name="nama_barang[]" id="nama_barang" standard title="Select an Option" autofocus="autofocus" required>
                <option value="">Select an Option</option>
            </select>
        </td>
        <td><input class="valOne" type="text" name='qty[]'></td>
    </tr>
</code>```

Until this point, everything works perfectly. Then I make second row by copying the first row literlally from
 to
, but it's not working. Selected value in the second row appears in the first row instead. Would you please help me to fix this? Thank you.

答:
If you are adding rows manually then giving different IDs should work and you would have to listen for them individually however i would not do it this way.

I'd rather add an onchange attribute to select, assign a function and then do the work

HTML:

```<code><select onchange="supplierChanged(this)">
    <option>Option 1</option>
</select>
</code>```

JS:

```<code>function supplierChanged(elem) {
    var selectValue = $(elem).val();
    // Rest of your code
}
</code>```

Update 1

```<code>$('.supplayer').on('change',function(){
  //change function on country to display all state
  // change 'id' - supplayer to 'class' - supplayer
        var self = this; // maintaining reference of 'this' so as to use in other functions
        var kode_supplayer = $(self).val();

        // Not sure about these two below (not tested), you need to test them
        var kode_barang = $(self).closest(".kode_barang")[0];
        var nama_barang = $(self).closest(".nama_barang")[0];

        if(kode_supplayer){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'kode_supplayer='+kode_supplayer,
                success:function(html){
                    $(kode_barang).html(html);
                    $(nama_barang).html('<option value="">Select state first</option>');
                }
            });
        }else{
            $(kode_barang).html('<option value="">Select country first</option>');
            $(nama_barang).html('<option value="">Select state first</option>');
        }
    });
</code>```

Body:
I built three dependent dropboxes: supplayer (supplier), kode_barang (ItemID), and nama_barang (variant). User can select a supplier, then choose an ItemID provided by that supplier, then decide which variant of product from the ItemID he want. I use this script:

window.load=$( document ).ready(function() {
    $.ajax({
        type:'POST',
        url:'supplayerAjaxData.php',
        success:function(html){
            $('#supplayer').html(html);
        }
    });
});

$( document ).ready(function() {
    $('#supplayer').on('change',function(){//change function on country to display all state
        var kode_supplayer = $('#supplayer').val();
        if(kode_supplayer){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'kode_supplayer='+kode_supplayer,
                success:function(html){
                    $('#kode_barang').html(html);
                    $('#nama_barang').html('<option value="">Select state first</option>');
                }
            });
        }else{
            $('#kode_barang').html('<option value="">Select country first</option>');
            $('#nama_barang').html('<option value="">Select state first</option>');
        }
    });

    $('#kode_barang').on('change',function(){//change state to display all city
        var kode_barang = $('#kode_barang').val();
        if(kode_barang){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'kode_barang='+kode_barang,
                success:function(html){
                    $('#nama_barang').html(html);
                }
            });
        }else{
            $('#nama_barang').html('<option value="">Select state first</option>');
        }
    });
});

Then I show it in this way:

         Supplayer
         Kode Barang
         Nama Barang
         Quantity

            <select class="selectpicker form-control" name="supplayer[]" id="supplayer" autofocus="autofocus" required>
                <option value="">Select an Option</option>
            </select>

            <select class="selectpicker form-control" name="kode_barang[]" id="kode_barang"  autofocus="autofocus" required>
                <option value="">Select an Option</option>
            </select>

            <select class="selectpicker form-control" name="nama_barang[]" id="nama_barang" standard title="Select an Option" autofocus="autofocus" required>
                <option value="">Select an Option</option>
            </select>

        <input class="valOne" type="text" name='qty[]'>

Until this point, everything works perfectly. Then I make second row by copying the first row literlally from
 to
, but it's not working. Selected value in the second row appears in the first row instead. Would you please help me to fix this? Thank you.

Body:
If you are adding rows manually then giving different IDs should work and you would have to listen for them individually however i would not do it this way.

I'd rather add an onchange attribute to select, assign a function and then do the work

HTML:

<select onchange="supplierChanged(this)">
    <option>Option 1</option>
</select>

JS:

function supplierChanged(elem) {
    var selectValue = $(elem).val();
    // Rest of your code
}

Update 1

$('.supplayer').on('change',function(){
  //change function on country to display all state
  // change 'id' - supplayer to 'class' - supplayer
        var self = this; // maintaining reference of 'this' so as to use in other functions
        var kode_supplayer = $(self).val();

        // Not sure about these two below (not tested), you need to test them
        var kode_barang = $(self).closest(".kode_barang")[0];
        var nama_barang = $(self).closest(".nama_barang")[0];

        if(kode_supplayer){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'kode_supplayer='+kode_supplayer,
                success:function(html){
                    $(kode_barang).html(html);
                    $(nama_barang).html('<option value="">Select state first</option>');
                }
            });
        }else{
            $(kode_barang).html('<option value="">Select country first</option>');
            $(nama_barang).html('<option value="">Select state first</option>');
        }
    });


问:
How to pull trending news from Facebook Graph API?
I would like to pull trending news from Facebook in JSON, in order to use it in other application, but I couldn't find a way to do this. I have tried:

```<code>https://graph.facebook.com/v2.5/search/type=trending&access_token=my_accesstoken
</code>```

and

```<code>https://graph.facebook.com/v2.5/search/type=news&access_token=my_accesstoken
</code>```

but neither work.

Can someone help me please? I would like to know the correct url and type for accessing it.

答:
The API you are looking for is Keyword Insights

Which is not available to public anymore.

Body:
I would like to pull trending news from Facebook in JSON, in order to use it in other application, but I couldn't find a way to do this. I have tried:

https://graph.facebook.com/v2.5/search/type=trending&access_token=my_accesstoken

and

https://graph.facebook.com/v2.5/search/type=news&access_token=my_accesstoken

but neither work.

Can someone help me please? I would like to know the correct url and type for accessing it.


问:
Vertx connection timeout not catched JDBCClient (.getConnection)
I can't handle case when connection failed in JDBCClient, example: no host to route, connection time out and etc. Because the method .getConnection() is not return failedFuture but it show cause in monitor then it's will silence.
I think it should send the fail future more than print error log when connection time out or other cause.

My example code is.

```<code>JDBCClient client = ...;
client.getConnection(conn -> {
    if (conn.succeeded()) {
        ....
    } else {
        // This is never executed (connection time out and etc.)
        handler.handle(Future.failedFuture(conn.cause()));
    }
});
</code>```

i got this Error in logs:

```<code>An attempt by a client to checkout a Connection has timed out.
java.sql.SQLException: An attempt by a client to checkout a Connection has timed out.
    at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118)
    at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:77)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:690)
    at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140)
    at JDBCClient.lambda$getConnection$1(JDBCClient.java:132)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) ~[?:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) ~[?:1.8.0_144]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_144]
Caused by: com.mchange.v2.resourcepool.TimeoutException: A client timed out while waiting to acquire a resource from com.mchange.v2.resourcepool.BasicResourcePool@16404129 -- timeout at awaitAvailable()
    at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1467)
    at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:644)
    at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:554)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:758)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:685)
    ... 5 more
</code>```

Someone can help me please.

thank you.

答:
You can try to make something like this:

```<code>  public Future<SQLConnection> tryConnect() {
    JDBCClient client = JDBCClient.createNonShared(vertx, config());
    Future<SQLConnection> future = Future.future();
    client.getConnection(it -> {
      if (it.succeeded()) {
        future.complete(it.result());
      } else {
        future.fail(it.cause());
      }
    });
    return future;
  }
</code>```

Just create future manually and then resolve or reject it in the callback. It's actually common approach for such cases.

Body:
I can't handle case when connection failed in JDBCClient, example: no host to route, connection time out and etc. Because the method .getConnection() is not return failedFuture but it show cause in monitor then it's will silence.
I think it should send the fail future more than print error log when connection time out or other cause.

My example code is.

JDBCClient client = ...;
client.getConnection(conn -> {
    if (conn.succeeded()) {
        ....
    } else {
        // This is never executed (connection time out and etc.)
        handler.handle(Future.failedFuture(conn.cause()));
    }
});

i got this Error in logs:

An attempt by a client to checkout a Connection has timed out.
java.sql.SQLException: An attempt by a client to checkout a Connection has timed out.
    at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118)
    at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:77)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:690)
    at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140)
    at JDBCClient.lambda$getConnection$1(JDBCClient.java:132)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) ~[?:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) ~[?:1.8.0_144]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_144]
Caused by: com.mchange.v2.resourcepool.TimeoutException: A client timed out while waiting to acquire a resource from com.mchange.v2.resourcepool.BasicResourcePool@16404129 -- timeout at awaitAvailable()
    at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1467)
    at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:644)
    at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:554)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:758)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:685)
    ... 5 more

Someone can help me please.

thank you.

Body:
You can try to make something like this:

  public Future<SQLConnection> tryConnect() {
    JDBCClient client = JDBCClient.createNonShared(vertx, config());
    Future<SQLConnection> future = Future.future();
    client.getConnection(it -> {
      if (it.succeeded()) {
        future.complete(it.result());
      } else {
        future.fail(it.cause());
      }
    });
    return future;
  }

Just create future manually and then resolve or reject it in the callback. It's actually common approach for such cases.


问:
MakeAppx.exe crashes with Access Denied (error 5)
When trying to create an Appx file from a packaged Microsoft Edge extension, the MakeAppx.exe utility crashes with Access Denied (error 5).</p>

答:
Downloading a Windows 10 Fall Creators Update SDK to get a Windows 10 version of makeappx.exe fixed the problem for me. The Windows 8.1 version was crashing.

Download from:
https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk

And then run the utility from:

```<code>"C:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\x64\makeappx.exe"
</code>```

Body:
Downloading a Windows 10 Fall Creators Update SDK to get a Windows 10 version of makeappx.exe fixed the problem for me. The Windows 8.1 version was crashing.

Download from:
https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk

And then run the utility from:

"C:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\x64\makeappx.exe"


问:
How to get list of employees in each department seperated by comma
I have tried below one using XML Path but getting error.

Conversion failed when converting the varchar value ',' to data type int.

Can you correct the below query.

```<code>SELECT STUFF((SELECT ',' + COUNT(E.EMployeeId) FROM EMployee E WHERE E.DepartmentId IN(SELECT DepartmentId FROM Department)
            FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')
</code>```

Required Output

```<code>5,7,8,9
</code>```

答:
Try the following:

The COUNT() Returns integer value, you can't merge int with varchar. So you have to convert the value to char.

```<code>SELECT STUFF((SELECT ',' + CAST(COUNT(E.EMployeeId) AS VARCHAR) FROM EMployee E WHERE E.DepartmentId IN(SELECT DepartmentId FROM Department)
            FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')
</code>```

Try this answer, If you face any issue, mention in the comments:

```<code>SELECT DISTINCT DepartmentId,
     STUFF(
        (
            SELECT ',' + CAST(COUNT(E.EMployeeId) AS VARCHAR)
            FROM EMployee E
            WHERE E.DepartmentId IN(SELECT DepartmentId FROM Department)
                AND E.DepartmentId=T.DepartmentId
            FOR XML PATH(''), TYPE
            ), 1, 1, '') AS id_list
FROM EMployee as T
</code>```

Try this one for, both department and COUNT() in Comma separated:

```<code>SELECT STUFF((SELECT ',' + CAST((DepartmentId)AS VARCHAR)
FROM(
    SELECT DepartmentId,COUNT(EMployeeId) EMployeeId
    FROM EMployee E
    WHERE E.DepartmentId IN(SELECT DepartmentId FROM Department)
    GROUP BY DepartmentId
    )E
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'') DepID
    ,STUFF((SELECT ',' + CAST((EMployeeId)AS VARCHAR)
FROM(
    SELECT DepartmentId,COUNT(EMployeeId) EMployeeId
    FROM EMployee E
    WHERE E.DepartmentId IN(SELECT DepartmentId FROM Department)
    GROUP BY DepartmentId
    )E
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')EmpCount
</code>```

Body:
I have tried below one using XML Path but getting error.

Conversion failed when converting the varchar value ',' to data type int.

Can you correct the below query.

SELECT STUFF((SELECT ',' + COUNT(E.EMployeeId) FROM EMployee E WHERE E.DepartmentId IN(SELECT DepartmentId FROM Department)
            FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')

Required Output

5,7,8,9

Body:
Try the following:

The COUNT() Returns integer value, you can't merge int with varchar. So you have to convert the value to char.

SELECT STUFF((SELECT ',' + CAST(COUNT(E.EMployeeId) AS VARCHAR) FROM EMployee E WHERE E.DepartmentId IN(SELECT DepartmentId FROM Department)
            FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')

Try this answer, If you face any issue, mention in the comments:

SELECT DISTINCT DepartmentId,
     STUFF(
        (
            SELECT ',' + CAST(COUNT(E.EMployeeId) AS VARCHAR)
            FROM EMployee E
            WHERE E.DepartmentId IN(SELECT DepartmentId FROM Department)
                AND E.DepartmentId=T.DepartmentId
            FOR XML PATH(''), TYPE
            ), 1, 1, '') AS id_list
FROM EMployee as T

Try this one for, both department and COUNT() in Comma separated:

SELECT STUFF((SELECT ',' + CAST((DepartmentId)AS VARCHAR)
FROM(
    SELECT DepartmentId,COUNT(EMployeeId) EMployeeId
    FROM EMployee E
    WHERE E.DepartmentId IN(SELECT DepartmentId FROM Department)
    GROUP BY DepartmentId
    )E
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'') DepID
    ,STUFF((SELECT ',' + CAST((EMployeeId)AS VARCHAR)
FROM(
    SELECT DepartmentId,COUNT(EMployeeId) EMployeeId
    FROM EMployee E
    WHERE E.DepartmentId IN(SELECT DepartmentId FROM Department)
    GROUP BY DepartmentId
    )E
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')EmpCount


问:
Could I Intercept Exit FullScreen event from octane.xam.VideoPlayer plugin (XAMARIN FORMS)?
My application works portait, ma i want fullscreen video playback even in landscape mode using the plugin mentionend above.

For this purpose I create a customrenderer to take access to native AVPlayerViewController Ios Control.

I tried in many many ways, but seems to be impossible to handle exit fullscreen event. In that method i want to force layout portrait. I have the code for reset orientation already implemented but the problem is to put the code in the right place.

Any other that faced the same issue??

I tried to search for something useful in AVPlayerView(not accessible), AVPlayerVideoController, AVPlayerCurrentItem etc

Any ideas?

Thanks you in advance.

答:
I have translated the OC code to C# in this link for you, see the following codes:</p>

```<code>using Foundation;
using CoreGraphics;

playerViewController = new AVPlayerViewController();
playerViewController.ContentOverlayView.AddObserver(this, new NSString("bounds"), NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old , IntPtr.Zero);

public override void ObserveValue(NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context)
        {
            base.ObserveValue(keyPath, ofObject, change, context);

            if(ofObject == playerViewController.ContentOverlayView)
            {
                if(keyPath == "bounds")
                {
                    NSValue oldRect = change.ValueForKey(new NSString("NSKeyValueChangeOldKey")) as NSValue;
                    NSValue newRect = change.ValueForKey(new NSString("NSKeyValueChangeNewKey")) as NSValue;
                    CGRect oldBounds = oldRect.CGRectValue;
                    CGRect newBounds = newRect.CGRectValue;

                    bool wasFullscreen = CGRect.Equals(oldBounds, UIScreen.MainScreen.Bounds);
                    bool isFullscreen = CGRect.Equals(newBounds, UIScreen.MainScreen.Bounds);

                    if(isFullscreen && !wasFullscreen)
                    {
                        if(CGRect.Equals(oldBounds,new CGRect(0,0,newBounds.Size.Height, newBounds.Size.Width)))
                        {
                            Console.WriteLine("rotated fullscreen");
                        }
                        else
                        {
                            Console.WriteLine("entered fullscreen");
                        }
                    }
                    else if(!isFullscreen && wasFullscreen)
                    {
                        Console.WriteLine("exited fullscreen");
                    }
                }
            }
        }
</code>```

Body:
I have translated the OC code to C# in this link for you, see the following codes:

using Foundation;
using CoreGraphics;

playerViewController = new AVPlayerViewController();
playerViewController.ContentOverlayView.AddObserver(this, new NSString("bounds"), NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old , IntPtr.Zero);

public override void ObserveValue(NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context)
        {
            base.ObserveValue(keyPath, ofObject, change, context);

            if(ofObject == playerViewController.ContentOverlayView)
            {
                if(keyPath == "bounds")
                {
                    NSValue oldRect = change.ValueForKey(new NSString("NSKeyValueChangeOldKey")) as NSValue;
                    NSValue newRect = change.ValueForKey(new NSString("NSKeyValueChangeNewKey")) as NSValue;
                    CGRect oldBounds = oldRect.CGRectValue;
                    CGRect newBounds = newRect.CGRectValue;

                    bool wasFullscreen = CGRect.Equals(oldBounds, UIScreen.MainScreen.Bounds);
                    bool isFullscreen = CGRect.Equals(newBounds, UIScreen.MainScreen.Bounds);

                    if(isFullscreen && !wasFullscreen)
                    {
                        if(CGRect.Equals(oldBounds,new CGRect(0,0,newBounds.Size.Height, newBounds.Size.Width)))
                        {
                            Console.WriteLine("rotated fullscreen");
                        }
                        else
                        {
                            Console.WriteLine("entered fullscreen");
                        }
                    }
                    else if(!isFullscreen && wasFullscreen)
                    {
                        Console.WriteLine("exited fullscreen");
                    }
                }
            }
        }


问:
Is there any work around for Sikuli IDE image replacement?
I am using Sikulix for UI testing, the problem is that when ever there are changes in UI I need to replace all the images which got changed using the IDE and I need to again describe the actions ( accuracy, click position) which is becoming a sort of overhead in my case. Is there any work around by which I can simply replace the new UI images in the project folder with the same old name ( It wont work directly as the new coordinates might be different + the new image should be of same resolution that of older one)

PS: I have completely understood that sikuli works at pixel level, but still curious to find out if any one has found a work around.

答: Unfortunately, you will need to recreate the images. What could make it a bit easier, is if you had more descriptive names than the ones generated by Sikuli IDE automatically. Keep in mind these are just image files stored on your PC. If you have names like button1.png, button1.png, etc.., it will make your life easier.


问:
What is the use of manifest list in context of docker containers?
I am trying to pull a image from docker hub using a command on windows server 2016

```<code>docker pull alpine
</code>```

The command returns an error as follows
no supported platform found in manifest list

I am not sure what is manifest list and how is this related? Thanks for help.

答:
This might be due to OS compatibility as specified here

To resolve this try to Right click on Docker and select Switch to Windows containers or try adding the --experimental flag to see if it works.

Body:
I am trying to pull a image from docker hub using a command on windows server 2016

docker pull alpine

The command returns an error as follows
no supported platform found in manifest list

I am not sure what is manifest list and how is this related? Thanks for help.


问:
Django: Distinct Users Filtering
I'm trying to build a messaging app. Here's my model,

```<code>class Message(models.Model):
    sender = models.ForeignKey(User, related_name="sender")
    receiver = models.ForeignKey(User, related_name="receiver")
    msg_content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
</code>```

This is what I tried in view,

```<code>data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user))
</code>```

In the template,

```<code>{% for abc in data %}
    {{ abc.receiver }} <br/>
{% endfor %}
</code>```

Here i wants to filter the distinct receivers and re-order them based upon the fact that to whom request.user sent new message recently (as we see on social media platforms). How can I do that?

答:
You need to write two queries. One is to fetch all the messages and another to get recipient list in order. receiver_list in following code will give you receiver list. Based on receiver list, you can filter out messages in template.    </p>

```<code>from django.db.models.aggregates import Max
data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user))
receiver_list = data.filter(sender=request.user).values('receiver').annotate(max_time=Max('created_at').order_by('-max_time')
</code>```

Title: Django: Distinct Users Filtering

Body:
I'm trying to build a messaging app. Here's my model,

class Message(models.Model):
    sender = models.ForeignKey(User, related_name="sender")
    receiver = models.ForeignKey(User, related_name="receiver")
    msg_content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

This is what I tried in view,

data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user))

In the template,

{% for abc in data %}
    {{ abc.receiver }}

{% endfor %}

Here i wants to filter the distinct receivers and re-order them based upon the fact that to whom request.user sent new message recently (as we see on social media platforms). How can I do that?

Body:
You need to write two queries. One is to fetch all the messages and another to get recipient list in order. receiver_list in following code will give you receiver list. Based on receiver list, you can filter out messages in template.

from django.db.models.aggregates import Max
data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user))
receiver_list = data.filter(sender=request.user).values('receiver').annotate(max_time=Max('created_at').order_by('-max_time')


问:
Error when executing `jupyter notebook` (No such file or directory)
When I execute jupyter notebook in my virtual environment in Arch Linux, the following error occurred.

Error executing Jupyter command 'notebook': [Errno 2] No such file or directory

My Python version is 3.6, and my Jupyter version is 4.3.0

How can I resolve this issue?

答:
Since both pip and pip3.6 was installed and
pip install --upgrade --force-reinstall jupyter
was failing, so I used

pip3.6 install --upgrade --force-reinstall jupyter

and it worked for me.
Running jupyter notebook also worked after this installation.


问:
How to create a directory using Ansible
How do you create a directory www at /srv on a Debian-based system using an Ansible playbook?

答:
```<code>---
- hosts: all
  connection: local
  tasks:
    - name: Creates directory
      file: path=/src/www state=directory
</code>```

Above playbook will create www directory in /src path.

Before running above playbook. Please make sure your ansible host connection should be set,

"localhost ansible_connection=local"

should be present in /etc/ansible/hosts

for more information please let me know.

Title: How to create a directory using Ansible

Body:
---
- hosts: all
  connection: local
  tasks:
    - name: Creates directory
      file: path=/src/www state=directory

Above playbook will create www directory in /src path.

Before running above playbook. Please make sure your ansible host connection should be set,

"localhost ansible_connection=local"

should be present in /etc/ansible/hosts

for more information please let me know.


问:
MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)
First let me mention that I've gone through many suggested questions and found no relevent answer. Here is what I'm doing.

I'm connected to my Amazon EC2 instance. I can login with MySQL root with this command:

```<code>mysql -u root -p
</code>```

Then I created a new user bill with host %

```<code>CREATE USER 'bill'@'%' IDENTIFIED BY 'passpass';
</code>```

Granted all the privileges to user bill:

```<code>grant all privileges on *.* to 'bill'@'%' with grant option;
</code>```

Then I exit from root user and try to login with bill:

```<code>mysql -u bill -p
</code>```

entered the correct password and got this error:

ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

答:
Debugging Summary

Check for typo error: username or password.

Check the host name and compare it with mysql.user table host name.

Check user exists or not.

Check whether host contains IP address or host name.

There is a great chance that, you might have encountered this issue multiple times in your work. This issue occurred to me most of times due to the incorrectly entering user name or password. Though this is one of the reasons, there are other many chances you might get this issue. Sometimes, it looks very similar, but when you dig deeper, you will realize multiple factors contributing to this error. This post will explain in detail, most of the common reasons and work around to fix this issue.

Possible reasons:

Case 1: Typo error: username or password.

This is the most common reason for this error. If you entered the username or password wrongly, surely you will get this error.

Solution:

Solution for this type of error is very simple. Just enter the correct username and password. This error will be resolved. In case if you forget the password you can reset the username/password.
If you forget the password for admin / root account, there are many ways to reset / recapture the root password. I will publish another post on how to reset the root password in-case if you forget root password.

Case 2: Accessing from wrong host.

MySQL provides host based restriction for user access as a security features. In our production environment, we used to restrict the access request only to the Application servers. This feature is really helpful in many production scenarios.

Solution:

When you face this type of issue, first check whether your host is allowed or not by checking the mysql.user table.
If it is not defined, you can update or insert new record to mysql.user table.
Generally, accessing as a root user from remote machine is disabled and it is not a best practice, because of security concerns.
If you have requirements to access your server from multiple machines, give access only to those machines. It is better not to use wildcards (%) and gives universal accesses.
Let me update the mysql.user table, now the demouser can access MySQL server from any host.

Case 3: User does not exists on the server.

This type of error occurs when the user, which you are trying to access not exist on the MySQL server.

Solutions:

When you face this type of issue, just check whether the user is exists in mysql.user table or not. If the record not exists, user cannot access. If there is a requirement for that user to access, create a new user with that username.

Case 4: Mix of numeric and name based hosts.

Important points

It is not advisable to use wildcards while defining user host, try to use the exact host name.

Disable root login from remote machine.

Use proxy user concept.

There are few other concepts related with this topic and getting into details of those topics is very different scope of this article. We will look into the following related topics in the upcoming articles.

What to do, if you forgot root password in of MySQL server.

MySQL Access privilege issues and user related tables.

MySQL security features with best practices.

I hope this post will help for you to fix the MySQL Error Code 1045 Access denied for user in MySQL.

Body:
First let me mention that I've gone through many suggested questions and found no relevent answer. Here is what I'm doing.

I'm connected to my Amazon EC2 instance. I can login with MySQL root with this command:

mysql -u root -p

Then I created a new user bill with host %

CREATE USER 'bill'@'%' IDENTIFIED BY 'passpass';

Granted all the privileges to user bill:

grant all privileges on *.* to 'bill'@'%' with grant option;

Then I exit from root user and try to login with bill:

mysql -u bill -p

entered the correct password and got this error:

ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)


问:
How to redirect intended user to a different route based on their role?
I'd like to redirect my user to different route, based on their role. I have two secured area in my app, "admin" and "dashboard". I'd like to check if user is authenticated, then redirect to intended, but if user has role editor it should be redirected to dashboard, otherwise if he has role admin should be redirected to admin area.

I'm using AuthenticatesAndRegistersUsers class in my login. I have this on my custom controller:

```<code> /**
 * The default redirecTo path.
 *
 */
 protected $redirectTo = '/dashboard';
</code>```

So when a user is authenticated it will be redirected to dashboard, but I'd like to check if the intended url is on admin group route and if user has admin role it should be redirected to admin area.

I'm using this middleware to redirect to login:

```<code>public function handle($request, Closure $next)
{
    if ($this->auth->guest())
    {
        if ($request->ajax())
        {
            return response('Unauthorized.', 401);
        }
        else
        {
            return redirect()->guest('auth/login');
        }
    }

    return $next($request);
}
</code>```

答:
I use this one. You also need to modify middleware RedirectIfAuthenticated so that it won't route home. Just to different user's dashboard.

```<code>public function authenticated()
{
    if($request->user()->hasRole('admin'))
             {
                 // return redirect()->intended(route('admin.index'));
                 return redirect()->route('admin.index');
             }
         if($request->user()->hasRole('super'))
             {
                 return redirect()->route('super.index');
             }
         if($request->user()->hasRole('officer'))
             {
                 return redirect()->route('officer.index');
             }
}
</code>```

Body:
I'd like to redirect my user to different route, based on their role. I have two secured area in my app, "admin" and "dashboard". I'd like to check if user is authenticated, then redirect to intended, but if user has role editor it should be redirected to dashboard, otherwise if he has role admin should be redirected to admin area.

I'm using AuthenticatesAndRegistersUsers class in my login. I have this on my custom controller:

 /**
 * The default redirecTo path.
 *
 */
 protected $redirectTo = '/dashboard';

So when a user is authenticated it will be redirected to dashboard, but I'd like to check if the intended url is on admin group route and if user has admin role it should be redirected to admin area.

I'm using this middleware to redirect to login:

public function handle($request, Closure $next)
{
    if ($this->auth->guest())
    {
        if ($request->ajax())
        {
            return response('Unauthorized.', 401);
        }
        else
        {
            return redirect()->guest('auth/login');
        }
    }

    return $next($request);
}

Body:
I use this one. You also need to modify middleware RedirectIfAuthenticated so that it won't route home. Just to different user's dashboard.

public function authenticated()
{
    if($request->user()->hasRole('admin'))
             {
                 // return redirect()->intended(route('admin.index'));
                 return redirect()->route('admin.index');
             }
         if($request->user()->hasRole('super'))
             {
                 return redirect()->route('super.index');
             }
         if($request->user()->hasRole('officer'))
             {
                 return redirect()->route('officer.index');
             }
}


问:
Pyspark2 replace ? in data
I have Question Marks "?" in my data. In my column called "Name". These question marks "?" act as null values in my data. How do I replace the ? with NaN.

Using pyspark2, I tried

```<code>from pyspark.sql.functions import regexp_replace, col

data = data.select(regexp_replace(col("Name"), "?", "NaN"))
</code>```

Is there perhaps another way using a user defined function?

答:
The character '?' has a special meaning in regular expressions. Use escape sequence. Hope this helps,</p>

```<code>data = data.select(regexp_replace(col("Name"), "\?", "NaN"))
</code>```

Title: Pyspark2 replace ? in data

Body:
I have Question Marks "?" in my data. In my column called "Name". These question marks "?" act as null values in my data. How do I replace the ? with NaN.

Using pyspark2, I tried

from pyspark.sql.functions import regexp_replace, col

data = data.select(regexp_replace(col("Name"), "?", "NaN"))

Is there perhaps another way using a user defined function?

Body:
The character '?' has a special meaning in regular expressions. Use escape sequence. Hope this helps,

data = data.select(regexp_replace(col("Name"), "\?", "NaN"))


问:
Connection string for different MS SQL servers
I have several SQL servers in my system:

```<code>2017 MSSQLSERVER
2008 SQLEXPRESS
</code>```

In SSMS I see them like:

```<code>GM\
GM\SQLEXPRESS
</code>```

If I need to connect to SQLEXPRESS I use connection string with . in Server:

```<code>connectionString="Server=.;Database=LearnCSharp;Integrated Security=True"
</code>```

But what does . means in my case and what should be placed in connection string in order to connect to 2017 MSSQLSERVER?

UPD.:

. connects to 2017 server. I have noticed that before computer restart it was connecting to 2008 server

GM connects to 2017 server.

.\MSSQLSERVER generates exception in my application;

```<code>System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid) ---> System.ComponentModel.Win32Exception (0x80004005): The parameter is incorrect
</code>```

.\SQLEXPRESS and GM\SQLEXPRESS - both connects to server 2008

答: The dot is simply an abbreviated way of referencing your local machine and as highlighted in the following ".\MSSQLSERVER" should do it: SQL Server Connection Strings - dot(".") or "(local)" or "(localdb)").</p>

Body:
I have several SQL servers in my system:

2017 MSSQLSERVER
2008 SQLEXPRESS

In SSMS I see them like:

GM\
GM\SQLEXPRESS

If I need to connect to SQLEXPRESS I use connection string with . in Server:

connectionString="Server=.;Database=LearnCSharp;Integrated Security=True"

But what does . means in my case and what should be placed in connection string in order to connect to 2017 MSSQLSERVER?

UPD.:

. connects to 2017 server. I have noticed that before computer restart it was connecting to 2008 server

GM connects to 2017 server.

.\MSSQLSERVER generates exception in my application;

System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid) ---> System.ComponentModel.Win32Exception (0x80004005): The parameter is incorrect

.\SQLEXPRESS and GM\SQLEXPRESS - both connects to server 2008


问:
Parsing mixed data with Java
Kind of a Java noob, and have flipped between about 6 different streams+scanner and still haven't found a way to do everything I need to.  Am trying to implement an algorithm to parse a file that follows a certain syntax.  There are several places where I need to peek at the next character to see if it is a parenthesis or comma, and also need to be able to read strings and decimal values.  I had it working with a stream up to the point that I tried to read the double.  The double is NOT in a binary format, so DataInputStream is not what I want.

I could use the scanner for its getNextFloat, but the problem with using a scanner is there are no real delimiters in the file: (test:1.234,rightTest:5.6789)

If I specify ( , : ) as delimeters with the Scanner, then I lose the ability to test for their existence of the delimiter(I thionk, because the way it seems is it eats the delimiter).  These blocks can be nested in each other in various ways, so I often need to test the next char to see if it's a opening parenthesis and then branch to different pieces of logic. I.e. it forms a tree(but please don't right code to parse a tree because that is my homework assignment).

I could do away with the scanner and just go back to my original solution with a stream if I could only figure out how to parse the decimal value.  I need something that does a "read until you find one of these characters" so that I can say stream.ReadUntil(",)").  The decimals are always followed by a comma or closing paren.  As a hack I will probably just read one char at a time.  This is the same thing I did to grab the string like "test" and "rightTest", and it felt really awful.

The only other option I know if is something with a string tokenizer, but my feeling from examples is that I'd have to read the entire file into a string to tokenize it, essentially defeating the purpose of using a stream.  These files can be really big and just as an exersize for myself I like to try and code such that I don't bring it all into memory if it is unnecessary, even though for this assignment it doesn't really matter.

So essentially what I'm looking for is some help on the mechanics of the file IO to be able to peek at the next char so I can check for  ( , : ) when necesary, and also have the ability to read a string up to a : and read a decimal value up to a : or )

答:
Stream and Scanner are the only acceptable options? I would've used the Matcher Pattern.
For example this snippet determines the charset of a given html page and encodes the rest of content using that charset:

```<code>BufferedReader in = new BufferedReader(new FileReader(new File("index.html")));
String inputLine;
String returnedContent = "";
Pattern charsetPattern = Pattern.compile(".*<meta.*content=\"text/html;.*charset=([A-Za-z0-9\\-]*)\">.*");
while ((inputLine = in.readLine()) != null) {
    if (serviceCharset == null) {
        Matcher m = charsetPattern.matcher(inputLine);
        if (m.find()) {
            charset = m.group(1);//the expression included in the () is one ordered group
        }

    }
    returnedContent += new String(inputLine.getBytes(), charset != null? charset : "UTF8");
}
in.close();
</code>```

I know the example has not much to do with your question, it just shows how handy is regex in this sort of problems: you read the file line after line (so no worries about your buffer) and match the text you need using regular expressions.

Title: Parsing mixed data with Java

Body:
Stream and Scanner are the only acceptable options? I would've used the Matcher Pattern.
For example this snippet determines the charset of a given html page and encodes the rest of content using that charset:

BufferedReader in = new BufferedReader(new FileReader(new File("index.html")));
String inputLine;
String returnedContent = "";
Pattern charsetPattern = Pattern.compile(".*<meta.*content=\"text/html;.*charset=([A-Za-z0-9\\-]*)\">.*");
while ((inputLine = in.readLine()) != null) {
    if (serviceCharset == null) {
        Matcher m = charsetPattern.matcher(inputLine);
        if (m.find()) {
            charset = m.group(1);//the expression included in the () is one ordered group
        }

    }
    returnedContent += new String(inputLine.getBytes(), charset != null? charset : "UTF8");
}
in.close();

I know the example has not much to do with your question, it just shows how handy is regex in this sort of problems: you read the file line after line (so no worries about your buffer) and match the text you need using regular expressions.


问:
Android Studio - SQL database/table not creating - app won't open
Working on creating a SQL database in Android Studio, however, the app won't open on the emulator and no database file is found at /data/data/package/databases/ when using the device monitor.

I'm working on api_21 emulator which I believe should support sqlite. Eventually I'll be using the database information to perform various function with the buttons, but as of right now, those are ignored.

please help!

MainActivity.java

```<code>package edu.tamu.thecaddyapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

Button buttonDriver, buttonFouriron, buttonFiveiron, buttonSixiron, buttonSeveniron, buttonEightiron, buttonNineiron, buttonPW, buttonFiftysix, buttonSW, buttonSixty;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SQLiteHelper db = new SQLiteHelper(this);
    db.getWritableDatabase();

    buttonDriver = findViewById(R.id.button_DRIVER);
    buttonFouriron = findViewById(R.id.button_4IRON);
    buttonFiveiron = findViewById(R.id.button_5IRON);
    buttonSixiron = findViewById(R.id.button_6IRON);
    buttonSeveniron = findViewById(R.id.button_7IRON);
    buttonEightiron = findViewById(R.id.button_8IRON);
    buttonNineiron = findViewById(R.id.button_9IRON);
    buttonPW = findViewById(R.id.button_PW);
    buttonSW = findViewById(R.id.button_SW);
    buttonFiftysix = findViewById(R.id.button_56DEG);
    buttonSixty = findViewById(R.id.button_60DEG);

}

public void buttonDriver(View view) {
}

public void buttonFouriron(View view) {
}

public void buttonFiveiron(View view) {
}

public void buttonSixiron(View view) {
}

public void buttonSeveniron(View view) {
}

public void buttonEightiron(View view) {
}

public void buttonNineiron(View view) {
}

public void buttonPW(View view) {
}

public void buttonSW(View view) {
}

public void buttonFiftysix(View view) {
}

public void buttonSixty(View view) {
}

}
</code>```

SQLiteHelper.java

```<code>package edu.tamu.thecaddyapp;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SQLiteHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "SQLiteDatabase.db";
public static final String TABLE_NAME = "golf_averages";
public static final String _id = "_id";
public static final String COL_1 = "COL_1";
public static final String COL_2 = "COL_2";
public static final String COL_3 = "COL_3";
public static final String COL_4 = "COL_4";
public static final String COL_5 = "COL_5";
public static final String COL_6 = "COL_6";
public static final String COL_7 = "COL_7";
public static final String COL_8 = "COL_8";
public static final String COL_9 = "COL_9";
public static final String COL_10 = "COL_10";

public String create_table = "CREATE TABLE" + TABLE_NAME
        + " (_id integer primary key autoincrement, "
        + COL_1 + "text, "
        + COL_2 + "text, "
        + COL_3 + "text, "
        + COL_4 + "text, "
        + COL_5 + "text, "
        + COL_6 + "text, "
        + COL_7 + "text, "
        + COL_8 + "text, "
        + COL_9 + "text, "
        + COL_10 + "text" +")";

public SQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    Log.d("SQLiteHelper", "Context Reached");
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    sqLiteDatabase.execSQL(create_table);
    Log.d("onCreate", "onCreate reached");
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS golf_averages");
    onCreate(sqLiteDatabase);
}
}
</code>```

答:
Add Proper spacing in the query, please

```<code>public String create_table = "CREATE TABLE " + TABLE_NAME
    + " (_id integer primary key autoincrement, "
    + COL_1 + " text, "
    + COL_2 + " text, "
    + COL_3 + " text, "
    + COL_4 + " text, "
    + COL_5 + " text, "
    + COL_6 + " text, "
    + COL_7 + " text, "
    + COL_8 + " text, "
    + COL_9 + " text, "
    + COL_10 + " text" +")";
</code>```

Spacing is very important in SQL Queries

Body:
Working on creating a SQL database in Android Studio, however, the app won't open on the emulator and no database file is found at /data/data/package/databases/ when using the device monitor.

I'm working on api_21 emulator which I believe should support sqlite. Eventually I'll be using the database information to perform various function with the buttons, but as of right now, those are ignored.

please help!

MainActivity.java

package edu.tamu.thecaddyapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

Button buttonDriver, buttonFouriron, buttonFiveiron, buttonSixiron, buttonSeveniron, buttonEightiron, buttonNineiron, buttonPW, buttonFiftysix, buttonSW, buttonSixty;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SQLiteHelper db = new SQLiteHelper(this);
    db.getWritableDatabase();

    buttonDriver = findViewById(R.id.button_DRIVER);
    buttonFouriron = findViewById(R.id.button_4IRON);
    buttonFiveiron = findViewById(R.id.button_5IRON);
    buttonSixiron = findViewById(R.id.button_6IRON);
    buttonSeveniron = findViewById(R.id.button_7IRON);
    buttonEightiron = findViewById(R.id.button_8IRON);
    buttonNineiron = findViewById(R.id.button_9IRON);
    buttonPW = findViewById(R.id.button_PW);
    buttonSW = findViewById(R.id.button_SW);
    buttonFiftysix = findViewById(R.id.button_56DEG);
    buttonSixty = findViewById(R.id.button_60DEG);

}

public void buttonDriver(View view) {
}

public void buttonFouriron(View view) {
}

public void buttonFiveiron(View view) {
}

public void buttonSixiron(View view) {
}

public void buttonSeveniron(View view) {
}

public void buttonEightiron(View view) {
}

public void buttonNineiron(View view) {
}

public void buttonPW(View view) {
}

public void buttonSW(View view) {
}

public void buttonFiftysix(View view) {
}

public void buttonSixty(View view) {
}

}

SQLiteHelper.java

package edu.tamu.thecaddyapp;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SQLiteHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "SQLiteDatabase.db";
public static final String TABLE_NAME = "golf_averages";
public static final String _id = "_id";
public static final String COL_1 = "COL_1";
public static final String COL_2 = "COL_2";
public static final String COL_3 = "COL_3";
public static final String COL_4 = "COL_4";
public static final String COL_5 = "COL_5";
public static final String COL_6 = "COL_6";
public static final String COL_7 = "COL_7";
public static final String COL_8 = "COL_8";
public static final String COL_9 = "COL_9";
public static final String COL_10 = "COL_10";

public String create_table = "CREATE TABLE" + TABLE_NAME
        + " (_id integer primary key autoincrement, "
        + COL_1 + "text, "
        + COL_2 + "text, "
        + COL_3 + "text, "
        + COL_4 + "text, "
        + COL_5 + "text, "
        + COL_6 + "text, "
        + COL_7 + "text, "
        + COL_8 + "text, "
        + COL_9 + "text, "
        + COL_10 + "text" +")";

public SQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    Log.d("SQLiteHelper", "Context Reached");
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    sqLiteDatabase.execSQL(create_table);
    Log.d("onCreate", "onCreate reached");
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS golf_averages");
    onCreate(sqLiteDatabase);
}
}

Body:
Add Proper spacing in the query, please

public String create_table = "CREATE TABLE " + TABLE_NAME
    + " (_id integer primary key autoincrement, "
    + COL_1 + " text, "
    + COL_2 + " text, "
    + COL_3 + " text, "
    + COL_4 + " text, "
    + COL_5 + " text, "
    + COL_6 + " text, "
    + COL_7 + " text, "
    + COL_8 + " text, "
    + COL_9 + " text, "
    + COL_10 + " text" +")";

Spacing is very important in SQL Queries