问:
Error creating ASP web page with single sign on over AAD
I'm struggling with creating an ASP web page with SSO like in this tutorial https://learn.microsoft.com/en-us/aspnet/identity/overview/getting-started/developing-aspnet-apps-with-windows-azure-active-directory but first I got redirected to localhost after deploying the aplication, so I searched and found the solution in ASP.Net redirecting to local host after authentication. But now when I autenticate on the web page I've created I get the next error

```<code>[ArgumentException: Format of the initialization string does not conform to     specification starting at index 152.]
System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue) +5778570
System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) +124
System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) +95
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +59
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +27
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +167
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) +61
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +87
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<SetConnectionString>b__18(DbConnection t, DbConnectionPropertyInterceptionContext`1 c) +12
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext`1 interceptionContext) +360
System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection) +269
System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config) +32
System.Data.Entity.Internal.LazyInternalConnection.Initialize() +127
System.Data.Entity.Internal.LazyInternalConnection.get_ProviderName() +13
System.Data.Entity.Internal.LazyInternalContext.get_ProviderName() +11
System.Data.Entity.Internal.DefaultModelCacheKeyFactory.Create(DbContext context) +92
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +515
    System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +15
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +38
System.Linq.Queryable.FirstOrDefault(IQueryable`1 source, Expression`1 predicate) +83
pruebamvc.Models.ADALTokenCache..ctor(String signedInUserId) +380
pruebamvc.Startup.<ConfigureAuth>b__7_0(AuthorizationCodeReceivedNotification context) +111
Microsoft.Owin.Security.OpenIdConnect.<AuthenticateCoreAsync>d__1a.MoveNext() +4931
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +26
Microsoft.Owin.Security.OpenIdConnect.<AuthenticateCoreAsync>d__1a.MoveNext() +6453
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Security.Infrastructure.<BaseInitializeAsync>d__0.MoveNext() +571
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +255
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +182
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +638
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +182
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<DoFinalWork>d__2.MoveNext() +180
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +69
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +64
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +380
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
</code>```

I've searched if anybody else has got the same error, but not success. I have tried to update nuget packages because it looks like a parsing error with the tokem, but in Startup.Auth.cs sais that authenticationcontext has AcquireTokenByAuthorizationCode deprecated so I tried to replace old code

```<code>AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;
                        ClientCredential credential = new ClientCredential(clientId, appKey);
                        string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                        AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                        code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                        return Task.FromResult(0);
                    }
</code>```

with:

```<code>AuthorizationCodeReceived = async (context) =>
                    {
                        var code = context.Code;
                        ClientCredential credential = new ClientCredential(clientId, appKey);
                        string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                        AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                        AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                        return ;
                    }
</code>```

But still etting errors. Do you have any idea?

答:
but first I got redirected to localhost after deploying the apllication

You could change the redirect url both in web.config and azure ad application , please follow below steps :

After deploy , you will get the published app url :https://webapplicationname.azurewebsites.net/ , cope the url and modify the web config :

```<code><add key="ida:PostLogoutRedirectUri" value="https://webapplicationname.azurewebsites.net/" />
</code>```

In azure portal ,click Azure AD blade, click "App registrations" button , find the app you registered . You could find the app by app id(client id) , that could be find in web config:

```<code><add key="ida:ClientId" value="ae7afda3-b24b-42a7-bb14-8d7a08227f66" />
</code>```

select the app , click "Reply URLs" button , add the published app url(this demo i used webapplication420170330110754 as my app name ,change that to your own app name ) ,click save button:

Now you need to re-publish the app to make the new web.config available .

Edit :

For this error ,please firstly confirm whether you have set the correct connect string . You could find the connect string of azure sql :

Click the connect string you will get that :

Body:
I'm struggling with creating an ASP web page with SSO like in this tutorial https://learn.microsoft.com/en-us/aspnet/identity/overview/getting-started/developing-aspnet-apps-with-windows-azure-active-directory but first I got redirected to localhost after deploying the aplication, so I searched and found the solution in ASP.Net redirecting to local host after authentication. But now when I autenticate on the web page I've created I get the next error

[ArgumentException: Format of the initialization string does not conform to     specification starting at index 152.]
System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue) +5778570
System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) +124
System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) +95
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +59
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +27
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +167
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) +61
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +87
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<SetConnectionString>b__18(DbConnection t, DbConnectionPropertyInterceptionContext`1 c) +12
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext`1 interceptionContext) +360
System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection) +269
System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config) +32
System.Data.Entity.Internal.LazyInternalConnection.Initialize() +127
System.Data.Entity.Internal.LazyInternalConnection.get_ProviderName() +13
System.Data.Entity.Internal.LazyInternalContext.get_ProviderName() +11
System.Data.Entity.Internal.DefaultModelCacheKeyFactory.Create(DbContext context) +92
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +515
    System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +15
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +38
System.Linq.Queryable.FirstOrDefault(IQueryable`1 source, Expression`1 predicate) +83
pruebamvc.Models.ADALTokenCache..ctor(String signedInUserId) +380
pruebamvc.Startup.<ConfigureAuth>b__7_0(AuthorizationCodeReceivedNotification context) +111
Microsoft.Owin.Security.OpenIdConnect.<AuthenticateCoreAsync>d__1a.MoveNext() +4931
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +26
Microsoft.Owin.Security.OpenIdConnect.<AuthenticateCoreAsync>d__1a.MoveNext() +6453
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Security.Infrastructure.<BaseInitializeAsync>d__0.MoveNext() +571
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +255
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +182
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +638
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +182
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<DoFinalWork>d__2.MoveNext() +180
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +69
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +64
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +380
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

I've searched if anybody else has got the same error, but not success. I have tried to update nuget packages because it looks like a parsing error with the tokem, but in Startup.Auth.cs sais that authenticationcontext has AcquireTokenByAuthorizationCode deprecated so I tried to replace old code

AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;
                        ClientCredential credential = new ClientCredential(clientId, appKey);
                        string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                        AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                        code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                        return Task.FromResult(0);
                    }

with:

AuthorizationCodeReceived = async (context) =>
                    {
                        var code = context.Code;
                        ClientCredential credential = new ClientCredential(clientId, appKey);
                        string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                        AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                        AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                        return ;
                    }

But still etting errors. Do you have any idea?

Body:
but first I got redirected to localhost after deploying the apllication

You could change the redirect url both in web.config and azure ad application , please follow below steps :

After deploy , you will get the published app url :https://webapplicationname.azurewebsites.net/ , cope the url and modify the web config :

<add key="ida:PostLogoutRedirectUri" value="https://webapplicationname.azurewebsites.net/" />

In azure portal ,click Azure AD blade, click "App registrations" button , find the app you registered . You could find the app by app id(client id) , that could be find in web config:

<add key="ida:ClientId" value="ae7afda3-b24b-42a7-bb14-8d7a08227f66" />

select the app , click "Reply URLs" button , add the published app url(this demo i used webapplication420170330110754 as my app name ,change that to your own app name ) ,click save button:

Now you need to re-publish the app to make the new web.config available .

Edit :

For this error ,please firstly confirm whether you have set the correct connect string . You could find the connect string of azure sql :

Click the connect string you will get that :


来源: stackexchange

问:
Passing two values in select dropdown using angularjs
I want to pass two values in select dropdown.
Here is my code.

```<code><tbody>
    <tr ng-repeat="x in studyTeamObj" align="center">
        <td>
            <select class="form-control" ng-model="x.Designation">
                <option value=""></option>
                <option ng-repeat="x in createStudyObj.Study_User"
                        value="{{x.Designation}}">{{x.Emp_Name}}
                </option>
            </select>
        </td>
        <td>
            {{x.Emp_Id}}
        </td>
        <td>
            {{x.Designation}}
        </td>
        <td class="mdrf-add-row-col">
            <i class="fa  fa-minus-circle"
               data-ng-click="deleteMem($index)"></i>
        </td>
    </tr>
</tbody>
</code>```

This is what the data I am getting from {{createStudyObj.Study_User}}

```<code>[{"Emp_Name":"mdrf","Emp_Id":2,"Designation":"Research Dietitian","DesignationID":20},{"Emp_Name":"Sudha","Emp_Id":1045,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1046,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1047,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1048,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1049,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"fdgedd","Emp_Id":1050,"Designation":"MDRF HOD","DesignationID":16}]
</code>```

when I click on emp name from the dropdown,it should fetch Emp_Id and Designation.But I am getting only the Designation.Plz help

答:
You should be using ng-options instead of building your own options list.  https://docs.angularjs.org/api/ng/directive/ngOptions

If you have problems with that, add those questions up top and I will update my answer.

ContentLicense: CC BY-SA 3.0

Body:
I want to pass two values in select dropdown.
Here is my code.

            <select class="form-control" ng-model="x.Designation">
                <option value=""></option>
                <option ng-repeat="x in createStudyObj.Study_User"
                        value="{{x.Designation}}">{{x.Emp_Name}}
                </option>
            </select>

            {{x.Emp_Id}}

            {{x.Designation}}

This is what the data I am getting from {{createStudyObj.Study_User}}

[{"Emp_Name":"mdrf","Emp_Id":2,"Designation":"Research Dietitian","DesignationID":20},{"Emp_Name":"Sudha","Emp_Id":1045,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1046,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1047,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1048,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1049,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"fdgedd","Emp_Id":1050,"Designation":"MDRF HOD","DesignationID":16}]

when I click on emp name from the dropdown,it should fetch Emp_Id and Designation.But I am getting only the Designation.Plz help


问:
select grandparent in css
i have an html code like this

```<code><div class="main-container">
   <div class="main">
     <div class="col-main">
        <div class="category-products">
           <div class="toolbar"> </div>
        </div>
     </div>
   </div>
</div>
</code>```

i've tried to change the main-container background if it has toolbar descendant, ive tried like this :

```<code> .main-container > .main .col-main .category-products .toolbar{
  background-color: #f5f5f5;
  padding-top: 0;
}

.main-container >  .toolbar{
  background-color: #f5f5f5;
  padding-top: 0;
}
</code>```

but nothing works

答:
Try This:

.main-container[data-toolbaar="yes"] {
   background-color:#999;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main-container" data-toolbaar="yes">
   <div class="main">
     <div class="col-main">
        <div class="category-products">
           <div class="toolbar"> HELLO</div>
        </div>
     </div>
   </div>
</div></code>```

Description

You can pass a custom  attribute data-toolbar="yes" and target it with css properties and change the target class or id properties.

Title: select grandparent in css

Body:
i have an html code like this

i've tried to change the main-container background if it has toolbar descendant, ive tried like this :

 .main-container > .main .col-main .category-products .toolbar{
  background-color: #f5f5f5;
  padding-top: 0;
}

.main-container >  .toolbar{
  background-color: #f5f5f5;
  padding-top: 0;
}

but nothing works

Body:
Try This:

.main-container[data-toolbaar="yes"] {
   background-color:#999;

<div class="main-container" data-toolbaar="yes">
   <div class="main">
     <div class="col-main">
        <div class="category-products">
           <div class="toolbar"> HELLO</div>
        </div>
     </div>
   </div>
</div>

Description

You can pass a custom  attribute data-toolbar="yes" and target it with css properties and change the target class or id properties.


问:
Shorter way to test range for a certain string
Trying to create code that will export my Excel invoice sheet to PDF, to a specified file path. The path is based on the whether the invoice lists a certain product, ProductX.

This is what I came up with, but seems cumbersome to loop through every single cell in a range to see if ProductX is there.

Is there an easier way to do this? Appreciate any help!

```<code>Sub ExportToPDF()
'
Dim file_path As String
Dim search_range As Range
Dim each_cell As Range

' Set search_range as desired search range
Set search_range = ActiveSheet.Range("A53:R56")

For Each each_cell In search_range.Cells
    If InStr(1, each_cell.Value, "ProductX", vbTextCompare) Then
        file_path = Some_path_A
    Else: file_path = Some_path_B
    End If
Next each_cell

'Export the sheet as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:=file_path, Quality:=xlQualityStandard _
        , IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
        True
End Sub
</code>```

答:
You can use Find for a partial match.

This code assumes that the returned path contains the filepath variable you need - you may need to tweak this.

```<code>Dim rng1 As Range
Set rng1 = ActiveSheet.Range("A53:R56").Find("ProductX", , xlFormulas, xlPart)
If rng1 Is Nothing Then Exit Sub

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=rng1.Value, Quality:=xlQualityStandard _
        , IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
        True
</code>```

Body:
Trying to create code that will export my Excel invoice sheet to PDF, to a specified file path. The path is based on the whether the invoice lists a certain product, ProductX.

This is what I came up with, but seems cumbersome to loop through every single cell in a range to see if ProductX is there.

Is there an easier way to do this? Appreciate any help!

Sub ExportToPDF()
'
Dim file_path As String
Dim search_range As Range
Dim each_cell As Range

' Set search_range as desired search range
Set search_range = ActiveSheet.Range("A53:R56")

For Each each_cell In search_range.Cells
    If InStr(1, each_cell.Value, "ProductX", vbTextCompare) Then
        file_path = Some_path_A
    Else: file_path = Some_path_B
    End If
Next each_cell

'Export the sheet as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:=file_path, Quality:=xlQualityStandard _
        , IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
        True
End Sub

Body:
You can use Find for a partial match.

This code assumes that the returned path contains the filepath variable you need - you may need to tweak this.

Dim rng1 As Range
Set rng1 = ActiveSheet.Range("A53:R56").Find("ProductX", , xlFormulas, xlPart)
If rng1 Is Nothing Then Exit Sub

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=rng1.Value, Quality:=xlQualityStandard _
        , IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
        True


问:
Pimcore Custom Button Link on Toolbar CKEditor
Toolbars CKEditor

The result by filling up the data like picture above is

```<code><a id="detil" name="detil" </a>
</code>```

What I want to ask is how should I do to have a result

```<code><a data-target="#modal-detil" data-toggle="modal" href="#detil"  id="detil" name="detil" </a>
</code>```

How to add the attributes: data target, data toggle and href ?

答:
Using jquery add attribute :-</p>

```<code>$(document).ready(function(){
$("#detil").attr("href","#detil");
$("#detil").attr("data-toggle","modal");
$("#detil").attr("data-target","#modal-detil");
});
</code>```

Body:
Toolbars CKEditor

The result by filling up the data like picture above is

<a id="detil" name="detil"

What I want to ask is how should I do to have a result

<a data-target="#modal-detil" data-toggle="modal" href="#detil"  id="detil" name="detil"

How to add the attributes: data target, data toggle and href ?

Body:
Using jquery add attribute :-

$(document).ready(function(){
$("#detil").attr("href","#detil");
$("#detil").attr("data-toggle","modal");
$("#detil").attr("data-target","#modal-detil");
});


问:
how to add column value when date have same month and year in php
I have a query result as attached

I want to sum the column value as per the month and year display in
 column 1 as per the attached image in the below table column 1 show
 dec-2014 in column 1 and the sum of all value of colum2 till this
 month and year.

答:
You should use GROUP BY column1 then SUM the column2

EDIT :

Asumming your table name is date_test

SQL :

```<code> SELECT MONTHNAME(column1) as month, YEAR(column1) as years , SUM(column2) FROM `date_test` GROUP BY month , years
</code>```

You can see we alias the month and year and use it for the GROUP BY

You can change the name of the table or concat the aliased date to fit your format as Dec 2014

Body:
You should use GROUP BY column1 then SUM the column2

EDIT :

Asumming your table name is date_test

SQL :

 SELECT MONTHNAME(column1) as month, YEAR(column1) as years , SUM(column2) FROM `date_test` GROUP BY month , years

You can see we alias the month and year and use it for the GROUP BY

You can change the name of the table or concat the aliased date to fit your format as Dec 2014


问:
Sticky footer works on all but one page
Page is here

I am using a sticky footer, which works fine everywhere but my portfolio page. The gallery is relatively positioned, and is overflowing from it's parent div. The footer is sticking to the bottom of the parent, rather than the page.

Help? Preferably in a way where I don't have to rewrite all my code?

答:
Please try this one i hope it will helpful to you.

```<code>html, body {
    height: 100%;
}
header {
    background: #fff;
    position: relative;
    z-index: 100;
}
.content2 {
    clear: both;
    margin: 0 auto;
    padding: 0;
    text-align: center;
    width: 70%;
}
.gallery {
    display: table;
    height: 100%;
    margin-left: auto;
    margin-right: auto;
    margin-top: auto;
    position: relative;
    width: 100%;
}
#footer-block {
    bottom: 0;
    position: fixed;
    width: 100%;
}
</code>```

Thanks

Title: Sticky footer works on all but one page

Body:
Please try this one i hope it will helpful to you.

html, body {
    height: 100%;
}
header {
    background: #fff;
    position: relative;
    z-index: 100;
}
.content2 {
    clear: both;
    margin: 0 auto;
    padding: 0;
    text-align: center;
    width: 70%;
}
.gallery {
    display: table;
    height: 100%;
    margin-left: auto;
    margin-right: auto;
    margin-top: auto;
    position: relative;
    width: 100%;
}
#footer-block {
    bottom: 0;
    position: fixed;
    width: 100%;
}

Thanks


问:
capturing audio and video using flash in asp.net web application
I have a simple web application in asp.net in which i want to record interview of any candidate and after finish upload the video file to server.

I have searched a lot on internet but not found any satisfactory solution for this.

Any help will be highly appreciated .

Thanks in Advance.

答:
Finally I completed my task as creating Solution through HTML5 Media Recorder API And Posted the recorded video to Asp.net Server by making a post request to aspx page from java script and saving that BLOB Stream to Server.

As it is only supported in chrome and Firefox now i am searching any flash solution that can run on Internet Explorer also.


问:
Creating and clearing rectangles in Flash CS5
I have an XML document that I am reading in and drawing a bunch of rectangles from the data that I get.  This bit of code is inserted in one frame.  Buttons are used to navigate through the frames. A button on the main screen takes you to the frame that draws the rectangles.  I have a Back button on the frame that draws the rectangles that takes you back to the main screen and that works fine but when I click Back, the rectangles that I drew still remain on the scene.  Is there anyway that I can erase all of the rectangles at once?

Thanks

答:
Define an array of type DisplayObject and add each object (Sprite, Movieclip) to it.

When you want to remove them, iterate through the array and remove the child:

```<code>// Adding object to the array
var objArray:Array;    // this could be a field member
objArray = [];

// ... navigate to your XML file and get each entry
// ... after you create an object, add it
if( objArray.indexOf(obj1) < 0 ) // Make sure it is not there so we do not add it twice
    objArray.push(obj1);

// Clearing...
for each (var obj1:DisplayObject in objArray)
{
    obj1.parent.removeChild(obj1);
}

// when done, clear the array
objArray = [];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Define an array of type DisplayObject and add each object (Sprite, Movieclip) to it.

When you want to remove them, iterate through the array and remove the child:

// Adding object to the array
var objArray:Array;    // this could be a field member
objArray = [];

// ... navigate to your XML file and get each entry
// ... after you create an object, add it
if( objArray.indexOf(obj1) < 0 ) // Make sure it is not there so we do not add it twice
    objArray.push(obj1);

// Clearing...
for each (var obj1:DisplayObject in objArray)
{
    obj1.parent.removeChild(obj1);
}

// when done, clear the array
objArray = [];


问:
Html5 elements in .md file
I have a static html file with animations and different html5 tags. Is it possible to include this file (will all resources, images, js) in a jekyl blog post/page. More specifically, from .md file can I use include tag to use my static html5 file. I am very new to both jekyl, markdown. thnx</p>

答:
Markdown doesn't allow all html tags, you can take a look here to see which html tags are allowed and how to type them in markdown

for animations if you can wrap your animation in a gif then you can use it in markdown like so

```<code>![](http://i.imgur.com/OUkLi.gif)
</code>```

and if you want to add a still image like so

```<code>![](http://i.imgur.com/Ssfp7.png)
</code>```

Title: Html5 elements in .md file

Body:
Markdown doesn't allow all html tags, you can take a look here to see which html tags are allowed and how to type them in markdown

for animations if you can wrap your animation in a gif then you can use it in markdown like so

![](http://i.imgur.com/OUkLi.gif)

and if you want to add a still image like so

![](http://i.imgur.com/Ssfp7.png)


问:
Inline assembler causes freezing inside of another function
I've noticed that when using my inline assembly code is either incredibly slow or stops compared to my C++ code which finishes very quickly. I'm curious as to why to happens when I call upon the inline assembler in a different function as opposed to having the assembler where the function was called. I tested both ways and found that my program did not freeze when omitting the function.

```<code>    __asm {

    push dword ptr[rw] //rw is a C++ floating-point variable
    fld[esp] // Using the stack as temporary storage in order to insert it into the FPU
    add esp, 4 //preserving the memory

    push dword ptr[lwB]
    fld[esp]
    add esp, 4

    fsubp ST(1), ST(0) // Subtracting rw - lwB

    push dword ptr[sp]
    fld[esp]
    add esp, 4

    fdivp ST(1), ST(0) // Dividing previous resultant by span -> (rw - lwB) / sp

    push dword ptr[dimen]
    fld[esp]
    add esp, 4

    fmulp ST(1), ST(0) // Multiplying previous resultant by dimension > ((rw - lwB) / (sp)* dimen)

    sub esp, 4 // Allocating space in order to save result temporarily to ram then to eax then to a C++ variable
    fstp[esp]
    pop eax
    mov fCord, eax

    }
    return (int)fCord; //fCord is also a floating-point C++ variable
</code>```

The much faster C++ Code:

```<code>    return (int)(((rw - lwB) / (sp)* dimen));
</code>```

答: Today's compilers are much more advanced which can do branch prediction, memory operation reduction etc compared to handcoded assembly. This does not mean hand coded assembly is bad all the time but for most of the cases compiler can do equally good or better job of optimization when configured with right flags. In your case, you have used lot of stack operation and everyone of them leads to a memory load/store which is expensive in terms of CPU cycles. This could be the reason for slower performance. See the disassmbly code of your c++ implementation when compiled in release mode for comparing your handcoded assembly with the compiler generated output.

Body:
I've noticed that when using my inline assembly code is either incredibly slow or stops compared to my C++ code which finishes very quickly. I'm curious as to why to happens when I call upon the inline assembler in a different function as opposed to having the assembler where the function was called. I tested both ways and found that my program did not freeze when omitting the function.

    __asm {

    push dword ptr[rw] //rw is a C++ floating-point variable
    fld[esp] // Using the stack as temporary storage in order to insert it into the FPU
    add esp, 4 //preserving the memory

    push dword ptr[lwB]
    fld[esp]
    add esp, 4

    fsubp ST(1), ST(0) // Subtracting rw - lwB

    push dword ptr[sp]
    fld[esp]
    add esp, 4

    fdivp ST(1), ST(0) // Dividing previous resultant by span -> (rw - lwB) / sp

    push dword ptr[dimen]
    fld[esp]
    add esp, 4

    fmulp ST(1), ST(0) // Multiplying previous resultant by dimension > ((rw - lwB) / (sp)* dimen)

    sub esp, 4 // Allocating space in order to save result temporarily to ram then to eax then to a C++ variable
    fstp[esp]
    pop eax
    mov fCord, eax

    }
    return (int)fCord; //fCord is also a floating-point C++ variable

The much faster C++ Code:

    return (int)(((rw - lwB) / (sp)* dimen));


问:
Application going to background, data is not loaded
I created a simple json application and working fine but when the app is going to background data is not loaded,some one please suggest me with code.  </p>

```<code>    let task = URLSession.shared.dataTask(with: URL(string: "http://tour-pedia.org/api/getReviews?location=Rome&category=poi")!) { (data, response , error) in
    if error != nil {
        print(error?.localizedDescription ?? "")
    }
    if let resultArray = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [[String:Any]] {
        for jsonreviews in resultArray {
            let review = Review()
            review.rating = jsonreviews["rating"] as? Int ?? 0
            review.text = jsonreviews["text"] as! String
            review.time = jsonreviews["time"] as! String
            reviews.append(review)
        }
        DispatchQueue.main.async {
            self.tableview.reloadData()   // if you use tableview
        }
    }
}
task.resume()
</code>```

答: Please check this Downloading in background using Swift 3.0</p>

Body:
I created a simple json application and working fine but when the app is going to background data is not loaded,some one please suggest me with code.

    let task = URLSession.shared.dataTask(with: URL(string: "http://tour-pedia.org/api/getReviews?location=Rome&category=poi")!) { (data, response , error) in
    if error != nil {
        print(error?.localizedDescription ?? "")
    }
    if let resultArray = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [[String:Any]] {
        for jsonreviews in resultArray {
            let review = Review()
            review.rating = jsonreviews["rating"] as? Int ?? 0
            review.text = jsonreviews["text"] as! String
            review.time = jsonreviews["time"] as! String
            reviews.append(review)
        }
        DispatchQueue.main.async {
            self.tableview.reloadData()   // if you use tableview
        }
    }
}
task.resume()


问:
How do I reload UITableView data when the app comes to foreground? (Xcode 8.3 / Swift 3)
I have the following methods in my "ViewController" class to populate custom cells in a UITableView from a GET API call. This works fine when app first loads.

```<code>//ViewController
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    loadDataInUITableViewCell()
}

func loadDataInUITableViewCell() {
        apiCentral.sharedInstance.fetchData() {
        result in
        guard result.error == nil else {
            self.handleError(result.error!)
            return
        }
        if let fetchedData = result.value {
            self.data = fetchedData
        }
        self.messagesTableView.reloadData()
    }
}
</code>```

How do I refresh the data when the app comes to the foreground? Well, I added the following to AppDelegate to run the "loadDataInUITableViewCell" method so that the data reloads.

```<code>//AppDelegate
let mainViewController = ViewController()

func applicationWillEnterForeground(_ application: UIApplication) {
    mainViewController.loadDataInUITableViewCell()
}
</code>```

ISSUE: The above mechanism works fine however, I get the following error when the app comes to the foreground.

"fatal error: unexpectedly found nil while unwrapping an Optional value"

The issue seems to be happening at "self.messagesTableView.reloadData()" line of code. I'm using Xcode 8.3 and coding in Swift 3. Any guidance would be appreciated. Thank you.

答:
```<code>NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: .UIApplicationWillEnterForeground, object: nil)
</code>```

Write this above line in viewWillAppear()

```<code>func willEnterForeground() {
   tableView.reloadData()
}
</code>```

Used this above code in your ViewController where there is UITableView

Body:
I have the following methods in my "ViewController" class to populate custom cells in a UITableView from a GET API call. This works fine when app first loads.

//ViewController
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    loadDataInUITableViewCell()
}

func loadDataInUITableViewCell() {
        apiCentral.sharedInstance.fetchData() {
        result in
        guard result.error == nil else {
            self.handleError(result.error!)
            return
        }
        if let fetchedData = result.value {
            self.data = fetchedData
        }
        self.messagesTableView.reloadData()
    }
}

How do I refresh the data when the app comes to the foreground? Well, I added the following to AppDelegate to run the "loadDataInUITableViewCell" method so that the data reloads.

//AppDelegate
let mainViewController = ViewController()

func applicationWillEnterForeground(_ application: UIApplication) {
    mainViewController.loadDataInUITableViewCell()
}

ISSUE: The above mechanism works fine however, I get the following error when the app comes to the foreground.

"fatal error: unexpectedly found nil while unwrapping an Optional value"

The issue seems to be happening at "self.messagesTableView.reloadData()" line of code. I'm using Xcode 8.3 and coding in Swift 3. Any guidance would be appreciated. Thank you.

Body:
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: .UIApplicationWillEnterForeground, object: nil)

Write this above line in viewWillAppear()

func willEnterForeground() {
   tableView.reloadData()
}

Used this above code in your ViewController where there is UITableView


问:
Is there a way to nuke all AWS resources in an AWS account?
I have an AWS account where multiple EC2 instances, load balancers, target groups, security groups etc are setup by multiple owners.
We use terraform to set this up but sometimes due to corruption, the state becomes inconsistent. Current mechanism to recover is to manually destroy all resources in that account owned by a particular owner.
Is there an easy way to nuke all resources in an AWS account belonging to a particular owner?</p>

答:
Short answer: no.

Longer answer: actually, that's also no.  There's no built-in capabillity for this.

The case you're describing is not within the bounds of typical AWS usage... destroying everything in an account -- usually -- should not be easy.

Of course, you could script it, fairly trivially, by wrapping calls to aws-cli to custom code to iterate through the resources and generate additional requests to destroy them... but if you do, lock that code away, since such capability is inherently dangerous.


问:
Azure Powershell - Add-AzureVirtualIP cmdlet not found
I need to add another VIP for my Azure cloud service using Powershell for Azure, since there is no way to do it via the web console. In the past I was able to do it by using the Add-AzureVirtualIP command.

However, that command seems to no longer be found since MS switched everything to Azure Resource Manager mode. How can I use this command again, or is there another way to add a VIP to my cloud service?

Add-AzureVirtualIP : The term 'Add-AzureVirtualIP' is not recognized as the name of a cmdlet, function, script file,
  or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and

答:
According to your error code, it seems the Azure PowerShell is not loaded correctly.  we can install Azure PowerShell with this command:

Install-Module -Name Azure

More information about Azure PowerShell, please refer to the link.


问:
JS Equivalent of Linking to a Font File
I have used css to link to font files in the conventional way, as seen here:

How can I use Google's Roboto font on a website?

However there are a few instances where I may need more complicated style rules, and I use javascript in such cases. Strangely google searches only returned css font link methods, but I'm suspecting js has a way. I got as far as:

```<code>d3.select('body').append('text').text('my text')
    .attr('font-family', 'Roboto')
    .attr('src', 'url(my_url) format('truetype')');
</code>```

However I'm not sure if it's supposed to look like that. Given that it's not working, my hunch is no. Any ideas?

答: CSS is by far the easiest way to do this. You can always manipulate the tags containing text that you are working with different classes or id's using JS as you need. </p>

Title: JS Equivalent of Linking to a Font File

Body:
I have used css to link to font files in the conventional way, as seen here:

How can I use Google's Roboto font on a website?

However there are a few instances where I may need more complicated style rules, and I use javascript in such cases. Strangely google searches only returned css font link methods, but I'm suspecting js has a way. I got as far as:

d3.select('body').append('text').text('my text')
    .attr('font-family', 'Roboto')
    .attr('src', 'url(my_url) format('truetype')');

However I'm not sure if it's supposed to look like that. Given that it's not working, my hunch is no. Any ideas?


问:
Is it possible to assign different attributes to different characters in a string in UITextView?Swift 3
I placed a large text in a UITextView In Xcode in interface builder. Is it possible to assign different attributes (colors, headings, alignments..etc) to different parts of the string. Using MutableAttributedString would not work for me since the string is longer than 5000 words, it would take ages to format it.

答:
There is a simple way to do this. Outside Xcode :)

Open TextEditor in MAC and paste your text into it and format it as per your requirement and again copy it.

Now Add your UITextView into your ViewController in Storyboard and make that textView Attributed.

Now Paste your formatted text there in the text field.

Check below screenshot for reference.

Hope this will help you.

ContentLicense: CC BY-SA 4.0


问:
What is the minimum file size of a PE file (exe) on Windows? And the minimal memory allocation?
What is the minimum file size of a PE file (exe) on Windows?
And the minimum memory allocation?

I assembled (using MASM (ml.exe) and link.exe that come with VS 10) the following code:
I can not leave out kernel32.lib and ExitProcess, if I do, the program crashes.

```<code>; Assmebly options
.386
.MODEL FLAT, STDCALL
option casemap:none

; Include Libs
includelib kernel32.lib

; Imported symbols
ExitProcess PROTO :Dword
Sleep PROTO :Dword

; Code
.CODE

start:
    invoke Sleep, 10000
    invoke ExitProcess, 0
END start
</code>```

The Sleep command is included only to be able to read the memory usage before the program ends.

Now I measure the following: The .exe file is exactly 2.5 KB in size (if I include user32.lib and MessageBoxA, it becomes 3 KB in size --> blocks?) and the application uses 136 KB RAM when it's run (Vista 32bit).

Isn't that somewhat much memory for such a simple program? Why is the exe file so large, and the RAM requirement much larger than the exe file?

Are there some minimal memory sizes? What about the file? It looks like it's organized in blocks of 0.5 KB in size, but isn't it 0.5 KB then for this shortest possible program?

Where can I read about this (except http://msdn.microsoft.com/en-us/magazine/cc301805.aspx which I will check out)?

Thanks (my first question here)

答: Remember, that even though it might say "using 136KB" of memory, the majority of that is shared between all the applications. You really need to check out the private bytes, and even then, there are other factors like the default heap reservation, etc. The Windows OS would rather your apps run faster than to save RAM - wasted memory doesn't help anything.</p>

Body:
What is the minimum file size of a PE file (exe) on Windows?
And the minimum memory allocation?

I assembled (using MASM (ml.exe) and link.exe that come with VS 10) the following code:
I can not leave out kernel32.lib and ExitProcess, if I do, the program crashes.

; Assmebly options
.386
.MODEL FLAT, STDCALL
option casemap:none

; Include Libs
includelib kernel32.lib

; Imported symbols
ExitProcess PROTO :Dword
Sleep PROTO :Dword

; Code
.CODE

start:
    invoke Sleep, 10000
    invoke ExitProcess, 0
END start

The Sleep command is included only to be able to read the memory usage before the program ends.

Now I measure the following: The .exe file is exactly 2.5 KB in size (if I include user32.lib and MessageBoxA, it becomes 3 KB in size --> blocks?) and the application uses 136 KB RAM when it's run (Vista 32bit).

Isn't that somewhat much memory for such a simple program? Why is the exe file so large, and the RAM requirement much larger than the exe file?

Are there some minimal memory sizes? What about the file? It looks like it's organized in blocks of 0.5 KB in size, but isn't it 0.5 KB then for this shortest possible program?

Where can I read about this (except http://msdn.microsoft.com/en-us/magazine/cc301805.aspx which I will check out)?

Thanks (my first question here)


问:
How to insert text box values from C# into Oracle Database
Okay I'm new to all of this and am struggling to insert TextBox values (user input) in Windows Form Application and storing these into an Oracle Database Table.

C# code:

```<code>string oradb = "DATA SOURCE = larry.uopnet.plymouth.ac.uk:1521/orcl.fost.plymouth.ac.uk;PERSIST SECURITY INFO = True;USER ID = xxxxxxxxxx;password = xxxxxxxxx";

OracleConnection con = new OracleConnection(oradb);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "Insert into USER.Client VALUES (txtBoxClientName, txtBoxClientCity, txtBoxClientCountry, txtBoxClientNumber, txtBoxClientURL, comboClientStatus)";

int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
    MessageBox.Show("Please fill in required fields");
else
    MessageBox.Show("Client has been added");
con.Dispose();
</code>```

This error appears at the int rowsUpdated = cmd.ExecuteNonQuery(); line - An unhandled exception of type Oracle.DataAccess.Client.OracleException occurred in Oracle.DataAccess.dll

Trigger code in Oracle:

```<code>create or replace TRIGGER trg_client_ClientID
BEFORE INSERT ON client FOR EACH ROW
BEGIN
  :NEW.ClientID := seq_client_ClientID.nextval;
END;
</code>```

答:
like that:</p>

```<code>    cmd.CommandText = "Insert into USER.Client VALUES (:param_txtBoxClientName, :param_txtBoxClientCity, :param_txtBoxClientCountry, :param_txtBoxClientNumber, :param_txtBoxClientURL, :param_comboClientStatus)";

    cmd.Parameters.Add(new OracleParameter("param_txtBoxClientName", OracleDbType.Varchar2, txtBoxClientName.Text, ParameterDirection.Input));
    cmd.Parameters.Add(new OracleParameter("param_txtBoxClientCity", OracleDbType.Varchar2, txtBoxClientCity.Text, ParameterDirection.Input));
    cmd.Parameters.Add(new OracleParameter("param_txtBoxClientNumber", OracleDbType.Varchar2, txtBoxClientNumber.Text, ParameterDirection.Input));
    cmd.Parameters.Add(new OracleParameter("param_txtBoxClientURL", OracleDbType.Varchar2, txtBoxClientURL.Text, ParameterDirection.Input));
</code>```

Body:
Okay I'm new to all of this and am struggling to insert TextBox values (user input) in Windows Form Application and storing these into an Oracle Database Table.

C# code:

string oradb = "DATA SOURCE = larry.uopnet.plymouth.ac.uk:1521/orcl.fost.plymouth.ac.uk;PERSIST SECURITY INFO = True;USER ID = xxxxxxxxxx;password = xxxxxxxxx";

OracleConnection con = new OracleConnection(oradb);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "Insert into USER.Client VALUES (txtBoxClientName, txtBoxClientCity, txtBoxClientCountry, txtBoxClientNumber, txtBoxClientURL, comboClientStatus)";

int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
    MessageBox.Show("Please fill in required fields");
else
    MessageBox.Show("Client has been added");
con.Dispose();

This error appears at the int rowsUpdated = cmd.ExecuteNonQuery(); line - An unhandled exception of type Oracle.DataAccess.Client.OracleException occurred in Oracle.DataAccess.dll

Trigger code in Oracle:

create or replace TRIGGER trg_client_ClientID
BEFORE INSERT ON client FOR EACH ROW
BEGIN
  :NEW.ClientID := seq_client_ClientID.nextval;
END;

Body:
like that:

    cmd.CommandText = "Insert into USER.Client VALUES (:param_txtBoxClientName, :param_txtBoxClientCity, :param_txtBoxClientCountry, :param_txtBoxClientNumber, :param_txtBoxClientURL, :param_comboClientStatus)";

    cmd.Parameters.Add(new OracleParameter("param_txtBoxClientName", OracleDbType.Varchar2, txtBoxClientName.Text, ParameterDirection.Input));
    cmd.Parameters.Add(new OracleParameter("param_txtBoxClientCity", OracleDbType.Varchar2, txtBoxClientCity.Text, ParameterDirection.Input));
    cmd.Parameters.Add(new OracleParameter("param_txtBoxClientNumber", OracleDbType.Varchar2, txtBoxClientNumber.Text, ParameterDirection.Input));
    cmd.Parameters.Add(new OracleParameter("param_txtBoxClientURL", OracleDbType.Varchar2, txtBoxClientURL.Text, ParameterDirection.Input));


问:
nltk for python 3.6 in windows64
I'm new to python, I'm using Windows 10 and have  python36  and I basically have to use nltk for my project and i basically have two questions.

1 I heard pip is automatically downloaded for versions 3+ but when I type pip install nltk in command prompt im getting the following error even though i added its path "C:\Users\dheeraj\AppData\Local\Programs\Python\Python36\Scripts\pip36" in advanced settings and ya in above path i tried pip36 and pip in both cases result is same.

'pip' is not recognized as an internal or external command,"

2 In www.nltk.org I found nltk for mac, unix and windows32 but not for windows64 ,does that mean it doesnt support for 64bit or is there any way for me to install nltk.

答: I had the same problem as you, but I accidentally found pip.exe in my python directory, so I navigated to said directory with CMD and ran the command pip install -U nltk and it worked.

Title: nltk for python 3.6 in windows64


问:
jQuery UI datepicker not triggering a change in extjs field
I have a form that has two fields, a "start" date, and an "end" date. I have to use the jQuery UI datepicker because I this application will be run on a 7" touchscreen, and I needed to customize the size of the calendar popped up by the datepicker. The problem that I'm facing is that when I select a date, it is not triggering a "change" event in the field, and therefore the graph below isn't changing. If I physically type in the date, everything works as intended. What event should I look for in my code to trigger the chart below the date fields?

答:
I assume that you are applying the date of the datepicker to a Ext.form.field.Textfield.
Have a look at the checkChange-config from the ExtJs 6.2.1 docs:

A list of event names that will be listened for on the field's input
  element, which will cause the field's value to be checked for changes.
  If a change is detected, the change event will be fired, followed by
  validation if the validateOnChange option is enabled. Defaults to
  ['change', 'propertychange', 'keyup'] in Internet Explorer, and
  ['change', 'input', 'textInput', 'keyup', 'dragdrop'] in other
  browsers.

  ...

  If you need
  to guarantee on-the-fly change notifications including these edge
  cases, you can call the checkChange method on a repeating interval,
  e.g. using Ext.TaskManager, or if the field is within a
  Ext.form.Panel, you can use the FormPanel's
  Ext.form.Panel#pollForChanges configuration to set up such a task
  automatically.

  ...

So you may tweak the list there to fit your needs or try the workaround with Ext.TaskManager.


问:
How to create a view using EF code-first POCO
That simple. I need to create a View using Code First. I found nothing about this on google nor SO. Is there a way to accomplish this?

I need that view to be created and queried using linq, so it's not a solution to create it using an script on Database creation, for example:

```<code>var results = from c in db.Customer
join v in db.MyView on c.Id equals v.Id
select c;
</code>```

A work around is also acceptable. I need a way to query entities against non-constant/ non-entities values.

答:
A lot of good insights from the official issues thread of EF7:

1) Don't have a DbSet, and instead have a property or extension method

A) Property

```<code>class YourContext
{
    public IQueryable<YourView> YourView
    {
        get
        {
            return this.Database.SqlQuery<YourView>("select * from dbo.YourView");
        }
    }
}
</code>```

B) Extension Method

```<code>static class YourContextExtensions
{
    public static IQueryable<YourView>(this YourContext context)
    {
        return context.Database.SqlQuery<YourView>("select * from dbo.YourView");
    }
</code>```

2) Apparently, you can have the migration process ignore certain dbsets

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  if (IsMigration)
    modelBuilder.Ignore<YourViewTable>();
 ...
}
</code>```

(All the above are untested)

Body:
That simple. I need to create a View using Code First. I found nothing about this on google nor SO. Is there a way to accomplish this?

I need that view to be created and queried using linq, so it's not a solution to create it using an script on Database creation, for example:

var results = from c in db.Customer
join v in db.MyView on c.Id equals v.Id
select c;

A work around is also acceptable. I need a way to query entities against non-constant/ non-entities values.

Body:
A lot of good insights from the official issues thread of EF7:

1) Don't have a DbSet, and instead have a property or extension method

A) Property

class YourContext
{
    public IQueryable<YourView> YourView
    {
        get
        {
            return this.Database.SqlQuery<YourView>("select * from dbo.YourView");
        }
    }
}

B) Extension Method

static class YourContextExtensions
{
    public static IQueryable<YourView>(this YourContext context)
    {
        return context.Database.SqlQuery<YourView>("select * from dbo.YourView");
    }

2) Apparently, you can have the migration process ignore certain dbsets

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  if (IsMigration)
    modelBuilder.Ignore<YourViewTable>();
 ...
}

(All the above are untested)


问:
java object streams
I'm trying to create a server in java which will maintain up to 4 connections simultaneously.  I thought that holding the relevant information in an array would serve my purpose, well, but I'm having some trouble.

Here is the class I've created:

```<code>
import java.net.*;
import java.io.*;
public class tcpConnects{
private ObjectInputStream input;
private ObjectOutputStream output;
private int player;
public tcpConnects(int playerNumber, Socket connect) {
    // TODO Auto-generated method stub
        try{
            System.out.println("create InputStream");
            input= new ObjectInputStream(connect.getInputStream());
            System.out.println("create OutputStream");
            output= new ObjectOutputStream(connect.getOutputStream());
            System.out.println("streams created");
            //sendData("Welcome!");
            player=playerNumber;
        }catch (IOException ioException){
            ioException.printStackTrace();
        }
    }
    public ObjectInputStream getInput(){
        return input;
    }
    public void setInput(ObjectInputStream in){
        input=in;
    }
    public ObjectOutputStream getOutput(){
        return output;
    }
    public void setOutput(ObjectOutputStream out){
        output=out;
    }
    public int getPlayer(){
        return player;
    }
    public void sendData(String data){
        try{
            output.writeObject(data);
            output.flush();
        }catch (IOException ioException){
            ioException.printStackTrace();
        }
    }
}
</code>```

anyway, when I send a socket into the class, it gets to the stage of creating the input stream, but then the stream is never actually created.  The syntax appears to be correct, so I can only assume that there is some form of logic error which I am not aware of.  Any help in deciphering why this class will not create an input or output stream would be greatly appreciated.

Thanks,

答: Create the ObjectOutputStream before the ObjectInputStream, at both ends. The constructor of ObjectOutputStream writes a header to the stream that the constructor of ObjectInputStream reads, so if you create the ObjectInputStreams first you get a deadlock.

Title: java object streams

Body:
I'm trying to create a server in java which will maintain up to 4 connections simultaneously.  I thought that holding the relevant information in an array would serve my purpose, well, but I'm having some trouble.

Here is the class I've created:

import java.net.*;
import java.io.*;
public class tcpConnects{
private ObjectInputStream input;
private ObjectOutputStream output;
private int player;
public tcpConnects(int playerNumber, Socket connect) {
    // TODO Auto-generated method stub
        try{
            System.out.println("create InputStream");
            input= new ObjectInputStream(connect.getInputStream());
            System.out.println("create OutputStream");
            output= new ObjectOutputStream(connect.getOutputStream());
            System.out.println("streams created");
            //sendData("Welcome!");
            player=playerNumber;
        }catch (IOException ioException){
            ioException.printStackTrace();
        }
    }
    public ObjectInputStream getInput(){
        return input;
    }
    public void setInput(ObjectInputStream in){
        input=in;
    }
    public ObjectOutputStream getOutput(){
        return output;
    }
    public void setOutput(ObjectOutputStream out){
        output=out;
    }
    public int getPlayer(){
        return player;
    }
    public void sendData(String data){
        try{
            output.writeObject(data);
            output.flush();
        }catch (IOException ioException){
            ioException.printStackTrace();
        }
    }
}

anyway, when I send a socket into the class, it gets to the stage of creating the input stream, but then the stream is never actually created.  The syntax appears to be correct, so I can only assume that there is some form of logic error which I am not aware of.  Any help in deciphering why this class will not create an input or output stream would be greatly appreciated.

Thanks,


问:
PHP/AJax Freemium Tools - How to Limit The Number of Uses Before Showing Results
I've done some searches for this and can't seem to find anything on it. I'm looking for a starting point to create freemium model tools.

The languages that I'll be using are PHP, Ajax and MySQL.

Here's what I would like to get done.

Any random user can use the free tools on the site, but after X number of uses, they are asked to register an account, otherwise, they can't use the tool for another 24 hours.

From what I've seen from other tools, it seems to be done through IP tracking and storing them in a DB. But I can see this getting pretty messy after hitting the millions of results.

Can anyone with experience provide guidance on how I can start limiting the number of uses? I just have no idea where to start at this point.

答:
if they don't register with a email first then the only solution i think is IP it doesnt have to get messy if you set it up right. you just a table with column for ip column for counter and column for date and time.
then when you insert the data the same time you run another query to delete data older than 24 hours. Some guys use IP combined with device info.</p>


问:
Mongodb authentication not working from config file
I am trying to enable authentication in my mongodb version v3.4.3  from the config file but it doesn't work.

The following works:
sudo mongod --auth --port 27017 --dbpath /var/lib/mongodb

I can access via authentication

The following works as well

sudo service mongod start
but only when in the config file (which is /etc/mongod.conf) I don't put authorization: enabled

When I add authorization: enabled (as described in the documentation for that version), I can no longer launch mongod. It gives an error saying that my database folder does not exist, so I assume the config file is corrupt and it doesn't read anymore that the database folder is in /var/lib/mongodb.

Any suggestions are appreciated.

Here the full config file (standard config file, except that I added authorization)

ubuntu@ip-172-31-28-105:~$ cat /etc/mongod.conf

```<code># mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0

#processManagement:

#security:
    authorization: enabled

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:
</code>```

答:
The mongodb config file is a YAML file. Also, you cannot use tabs in the config file of mongodb. Always use spaces. In the config file, you have commented out the security parameter. Uncomment it and it may work

Change the config file to

```<code># mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0

#processManagement:

security:
  authorization: enabled

#operationProfiling:

#replication:

#sharding:

#Enterprise-Only Options:

#auditLog:

#snmp:
</code>```

Body:
I am trying to enable authentication in my mongodb version v3.4.3  from the config file but it doesn't work.

The following works:
sudo mongod --auth --port 27017 --dbpath /var/lib/mongodb

I can access via authentication

The following works as well

sudo service mongod start
but only when in the config file (which is /etc/mongod.conf) I don't put authorization: enabled

When I add authorization: enabled (as described in the documentation for that version), I can no longer launch mongod. It gives an error saying that my database folder does not exist, so I assume the config file is corrupt and it doesn't read anymore that the database folder is in /var/lib/mongodb.

Any suggestions are appreciated.

Here the full config file (standard config file, except that I added authorization)

ubuntu@ip-172-31-28-105:~$ cat /etc/mongod.conf

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0

#processManagement:

#security:
    authorization: enabled

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:

Body:
The mongodb config file is a YAML file. Also, you cannot use tabs in the config file of mongodb. Always use spaces. In the config file, you have commented out the security parameter. Uncomment it and it may work

Change the config file to

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0

#processManagement:

security:
  authorization: enabled

#operationProfiling:

#replication:

#sharding:

#Enterprise-Only Options:

#auditLog:

#snmp:


问:
Pattern within a pattern?
I want to capture Alta, Utah, USA from asd Alta, Utah, USA qwe. Basically I'm trying to capture places from a text. It won't be a perfect method, but the places must start with a capital and use a comma, followed by another word with a capital.

So far, I have wrote:

```<code>\s[A-Z][a-z]+[,]?
</code>```

I want to do multiple words, not just the first word, Alta. This is my attempt to use square brackets inside other square brackets.

```<code>[\s[A-Z][a-z]+[,]?]+
</code>```

But that doesn't work, so it must be syntactically incorrect.

答:
I think this is what you need:

```<code>([A-Z][a-zA-Z]+)(,\s*([A-Z][a-zA-Z]+))*
</code>```

Though the requirement pointed out by @Rizwan (in his comment) is still to be understood.

Debuggex Demo

Title: Pattern within a pattern?

Body:
I want to capture Alta, Utah, USA from asd Alta, Utah, USA qwe. Basically I'm trying to capture places from a text. It won't be a perfect method, but the places must start with a capital and use a comma, followed by another word with a capital.

So far, I have wrote:

\s[A-Z][a-z]+[,]?

I want to do multiple words, not just the first word, Alta. This is my attempt to use square brackets inside other square brackets.

[\s[A-Z][a-z]+[,]?]+

But that doesn't work, so it must be syntactically incorrect.

Body:
I think this is what you need:

([A-Z][a-zA-Z]+)(,\s*([A-Z][a-zA-Z]+))*

Though the requirement pointed out by @Rizwan (in his comment) is still to be understood.

Debuggex Demo


问:
replace multiple values in json/jsObject/string
I have a response from a web service and want to replace some values in the response with my custom values.

One way is to write a tree traverser and then check for the value and replace with my custom value

so the response is some what like this:

```<code>[
  {
    "name": "n1",
    "value": "v1",
    "children": [
      {
        "name": "n2",
        "value": "v2"
      }
    ]
  },
  {
    "name": "n3",
    "value": "v3"
  }
]
</code>```

now my custom map is like this

```<code>const map = {
  "v1": "v11",
  "v2": "v22",
  "v3": "v33"
};
</code>```

All I want is

```<code>[
  {
    "name": "n1",
    "value": "v11",
    "children": [
      {
        "name": "n2",
        "value": "v22"
      }
    ]
  },
  {
    "name": "n3",
    "value": "v33"
  }
]
</code>```

I was thinking if I could stringify my response and then replace values using a custom build regex from my map of values.

Will it be faster as compared to tree traverser?

If yes, how should I do that?

somewhat like this

originalString.replace(regexp, function (replacement))

答: definitely traverser go faster as string replace means travels against each characters in the final string as opposed to iterator that can skips no necessarily item.</p>

Body:
I have a response from a web service and want to replace some values in the response with my custom values.

One way is to write a tree traverser and then check for the value and replace with my custom value

so the response is some what like this:

[
  {
    "name": "n1",
    "value": "v1",
    "children": [
      {
        "name": "n2",
        "value": "v2"
      }
    ]
  },
  {
    "name": "n3",
    "value": "v3"
  }
]

now my custom map is like this

const map = {
  "v1": "v11",
  "v2": "v22",
  "v3": "v33"
};

All I want is

[
  {
    "name": "n1",
    "value": "v11",
    "children": [
      {
        "name": "n2",
        "value": "v22"
      }
    ]
  },
  {
    "name": "n3",
    "value": "v33"
  }
]

I was thinking if I could stringify my response and then replace values using a custom build regex from my map of values.

Will it be faster as compared to tree traverser?

If yes, how should I do that?

somewhat like this

originalString.replace(regexp, function (replacement))


问:
How to setup GIT for a GWT project
Which files and folders of a GWT project have to be tracked, which can I ignore?

I think ./src, ./test have to be tracked. I found out ./war is also important, but I've red, that it contains generated files.

I also found out that ./test-classes must be tracked, but I don't understand why.

答:
How to setup GIT for a GWT project:

I assume that you have a git repository created for your GWT project

1) Clone your git repository : Open git perspective in your IDE(eclipse) , paste your repository URL and follow the steps to setup a local git repo .

2) Adding project to git : Right click on the project in team click share project and select the repository you created .Done now all your local changes can be tracked by git .

Title: How to setup GIT for a GWT project


问:
codeigniter validation process for checking same data in one table
```<code>$sort_order=$this->input->post('sort_order','Sort Of Category','trim|required|max_length[128]|xss_clean|is_unique[categories.sort_order]');
</code>```

Why is the is_unique function not working here?

答:
It should be for set_rules on your form validation on controller

https://www.codeigniter.com/user_guide/libraries/form_validation.html

```<code>$this->form_validation->set_rules('sort_order','Sort Of Category','trim|required|max_length[128]|xss_clean|is_unique[categories.sort_order]');
</code>```

https://www.codeigniter.com/user_guide/libraries/form_validation.html#setting-validation-rules

https://www.codeigniter.com/user_guide/libraries/form_validation.html#rule-reference

```<code><?php

class Example extends CI_Controller {

   public function __construct() {
      parent::__construct();
      $this->load->library('form_validation');
   }

  public function index() {
     $data['title'] = 'Example';

     $this->form_validation->set_rules('sort_order','Sort Of Category','trim|required|max_length[128]|is_unique[categories.sort_order]');

     if ($this->form_validation->run() == false) {

            $this->load->view('header', $data);
            $this->load->view('example', $data);
            $this->load->view('footer');

     } else {

         // You can put your update or insert model function here
         redirect('success_controller');

     }
  }

}
</code>```

Body:
$sort_order=$this->input->post('sort_order','Sort Of Category','trim|required|max_length[128]|xss_clean|is_unique[categories.sort_order]');

Why is the is_unique function not working here?

Body:
It should be for set_rules on your form validation on controller

https://www.codeigniter.com/user_guide/libraries/form_validation.html

$this->form_validation->set_rules('sort_order','Sort Of Category','trim|required|max_length[128]|xss_clean|is_unique[categories.sort_order]');

https://www.codeigniter.com/user_guide/libraries/form_validation.html#setting-validation-rules

https://www.codeigniter.com/user_guide/libraries/form_validation.html#rule-reference

<?php

class Example extends CI_Controller {

   public function __construct() {
      parent::__construct();
      $this->load->library('form_validation');
   }

  public function index() {
     $data['title'] = 'Example';

     $this->form_validation->set_rules('sort_order','Sort Of Category','trim|required|max_length[128]|is_unique[categories.sort_order]');

     if ($this->form_validation->run() == false) {

            $this->load->view('header', $data);
            $this->load->view('example', $data);
            $this->load->view('footer');

     } else {

         // You can put your update or insert model function here
         redirect('success_controller');

     }
  }

}


问:
Does the sub class inherit the private data members too in c++? But are accessed through the public methods of the super class?
I'm new to c++. I used to believe that the super class private data members and member functions are not inherited by the derived class. But recently I saw a program in which the private member of the super class could be accessed through its public member function. How is it possible when the derived class doesn't have the private data member ..? please clear my concept if I am wrong .</p>

答:
used to believe that the super class private data members and member functions are not inherited by the derived class.

Your understanding is a bit flawed.

The private members still exist in the base class. They are simply not directly accessible by the derived class.


问:
Simple Interval Not Clearing
I am building a game program with the following prompt:

"Modify Challenge #3 so that every time a player clicks the heading, instead of stopping, the heading speeds up, making it harder and harder to click. Keep track of the number of times the heading has been clicked and update the heading text so it shows this number. When the player has reached 10 clicks, stop the animation and change the text of the heading to “You Win.” Hint: To speed up, you’ll have to cancel the current interval and then start a new one with a shorter interval time."

Here is the click event itself. I have everything down except the text won't stop when there are more than 10 clicks. I have linked my jfiddle as well.

```<code>$("#heading").click(function() {
       clearInterval(move);
       if (clicks < 10)
       {
            var move = setInterval(moveHeading, speed -= 2);
            $("#heading").html(clicks + " Clicks!");
            clicks++;
       }
       else
       {
            $("#heading").html("You won!");
            $("#heading").css("color","red");
            clearInterval(move);
       }
 });
</code>```

https://jsfiddle.net/jggzb49j/1/

答:
declare variable move outside instead of the inside handler function

```<code>var move;
$("#heading").click(function() {
  clearInterval(move);
  if (clicks < 10) {
    move = setInterval(moveHeading, speed -= 2);
    $("#heading").html(clicks + " Clicks!");
    clicks++;
  } else {
    $("#heading").html("You won!");
    $("#heading").css("color", "red");
    clearInterval(move);
  }
});
</code>```

Title: Simple Interval Not Clearing

Body:
I am building a game program with the following prompt:

"Modify Challenge #3 so that every time a player clicks the heading, instead of stopping, the heading speeds up, making it harder and harder to click. Keep track of the number of times the heading has been clicked and update the heading text so it shows this number. When the player has reached 10 clicks, stop the animation and change the text of the heading to “You Win.” Hint: To speed up, you’ll have to cancel the current interval and then start a new one with a shorter interval time."

Here is the click event itself. I have everything down except the text won't stop when there are more than 10 clicks. I have linked my jfiddle as well.

$("#heading").click(function() {
       clearInterval(move);
       if (clicks < 10)
       {
            var move = setInterval(moveHeading, speed -= 2);
            $("#heading").html(clicks + " Clicks!");
            clicks++;
       }
       else
       {
            $("#heading").html("You won!");
            $("#heading").css("color","red");
            clearInterval(move);
       }
 });

https://jsfiddle.net/jggzb49j/1/

Body:
declare variable move outside instead of the inside handler function

var move;
$("#heading").click(function() {
  clearInterval(move);
  if (clicks < 10) {
    move = setInterval(moveHeading, speed -= 2);
    $("#heading").html(clicks + " Clicks!");
    clicks++;
  } else {
    $("#heading").html("You won!");
    $("#heading").css("color", "red");
    clearInterval(move);
  }
});


问:
Git and PhpStorm project play together
I am trying to understand how to work with Git and PhpStorm together.

Lets imagine situation, I have an APP in a local git repo in folder some_project, so in git meaning this is will be a working area .git folder inside with. In repository I have 2 branches master and develop which equal for this moment.

So now I implement some new future in my APP, to do this I am making new branch with name, say, new_future. After that I am checkout new_future and ready to go do some work.

Now, I faced with certain questions:

Where I must to create PhpStorm project? Do I need to create it in repository folder? Cause if I will create it in repo folder then while changing branch with checkout using GIT my project files will be changed, do I need this? And after all, if I will delete project using PhpStorm - I could delete my all repository! This is unacceptable!

So if I will create project in other folders out my repo then how I will get code from my branch new_future? How I will commit and so on? Cause my project will be out of SVC folder and to do this all I guess need to do is after some changes code in PhpStorm project manually copy it to folder some_project and then using GIT in that folder add changes and commit them.

Is this right to do this or there is other easy options?

So I think you got the idea what I am trying to know - some recipe of actions in this usual working case.

答:
Since you need to use the code from new_feature branch, so you should create the phpstorm project in the git repo folder some_project.

For your concerns to create project in some_project folder:

Cause if I will create it in repo folder then while changing branch
  with checkout using GIT my project files will be changed, do I need
  this?

Yes, when you checkout to different branch, the working directory will changed. But the project is still exist in new_feature branch. If necessary, you can checkout to new_feature branch back. And usually you are not checkout/commit/merge etc both by git command and phpstorm at the same time since phpstorm already has options for you to use git to do version control.

And after all, if I will delete project using PhpStorm - I could
  delete my all repository! This is unacceptable!

If you delete the whole project using PhpStorm, of cause, the whole repo will be deleted. But it’s not the risk only exist on phpstorm. If you delete the folder manually, the repo will also gone. The safer way is to manage the git repo in remote, such as github, bitbucket etc. Even you delete the local one, but you can still clone from remote.

Title: Git and PhpStorm project play together


问:
How to configure on-behalf-of authentication in multi-tenant environment?
I have a native client that calls a service I wrote-- that in turn calls the Graph API (using the original caller's credentials).

This is exactly like the 'onbehalfof' sample found here (my code fails the same way as the sample):

https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof

When logging in as a user from the same tenant as the service (tenant A), everything works fine (just like the onbehalf of sample).  When logging in as a user from a different tenant (tenant B), I get an exception on this line in the service:

```<code>result = await authContext.AcquireTokenAsync(GraphResourceId, clientCred, userAssertion);
</code>```

(this is line 153 from TodoListController.cs in the onbehalfof sample).

The exception is this:

AADSTS65001: The user or administrator has not consented to use the
  application with ID 'de2fb28b-83f8-419d-9b00-3fbce0a60bf4'. Send an
  interactive authorization request for this user and resource.\r\nTrace
  ID: 6865c420-674a-4adf-a070-3d9b9c500200\r\nCorrelation ID:
  7e088563-d7fe-4131-a05c-cbe04dbb2bbd\r\nTimestamp: 2017-03-29
  22:56:58Z

The application id above refers to the service I wrote (which is the same line in the TodoListService in the onbehalfofsample).

I configured everything for multi-tenant authentication. But it's the additional call that my service is making to another service (Graph API) that's causing the problem.  What additional configuration do I need to do in the Azure portal to make this work?

答:
In the instructions written for the sample you linked above, they address this issue with the following section:

Configure known client applications

For the middle tier web API to be able to call the downstream web API,
  the user must grant the middle tier permission to do so in the form of
  consent. Because the middle tier has no interactive UI of its own, you
  need to explicitly bind the client app registration in Azure AD with
  the registration for the web API, which merges the consent required by
  both the client & middle tier into a single dialog. You can do so by
  adding the "Client ID" of the client app, to the manifest of the web
  API in the knownClientApplications property. Here's how:

Navigate to your 'TodoListService' app registration, and open the manifest editor.

In the manifest, locate the knownClientApplications array property, and add the Client ID of your client application as an element.

Your code should look like the following after you're done:
  "knownClientApplications": ["94da0930-763f-45c7-8d26-04d5938baab2"]

Save the TodoListService manifest by clicking the "Save" button.

My assumption is that because you are running into this problem, that you have not done this special configuration.

The other option you have is to explicitly request consent between the middle tier and the AAD Graph API. You can do this by having a tenant administrator 'login' and consent to your middle tier service. All you need to do is generate a login url with the middle tier App ID.

However, I strongly recommend you do it the documented way, since this will provide a better experience for your users.

Body:
I have a native client that calls a service I wrote-- that in turn calls the Graph API (using the original caller's credentials).

This is exactly like the 'onbehalfof' sample found here (my code fails the same way as the sample):

https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof

When logging in as a user from the same tenant as the service (tenant A), everything works fine (just like the onbehalf of sample).  When logging in as a user from a different tenant (tenant B), I get an exception on this line in the service:

result = await authContext.AcquireTokenAsync(GraphResourceId, clientCred, userAssertion);

(this is line 153 from TodoListController.cs in the onbehalfof sample).

The exception is this:

AADSTS65001: The user or administrator has not consented to use the
  application with ID 'de2fb28b-83f8-419d-9b00-3fbce0a60bf4'. Send an
  interactive authorization request for this user and resource.\r\nTrace
  ID: 6865c420-674a-4adf-a070-3d9b9c500200\r\nCorrelation ID:
  7e088563-d7fe-4131-a05c-cbe04dbb2bbd\r\nTimestamp: 2017-03-29
  22:56:58Z

The application id above refers to the service I wrote (which is the same line in the TodoListService in the onbehalfofsample).

I configured everything for multi-tenant authentication. But it's the additional call that my service is making to another service (Graph API) that's causing the problem.  What additional configuration do I need to do in the Azure portal to make this work?


问:
How to check mysql fetched rows in while loop are same
how to check resulted row values from while loop are same,I need to update when status is completed from all results...</p>

```<code>        $result = $db->query("SELECT * FROM fy_working_staf_cstm WHERE task_id_c='".$t_id."'");
        while($row = $db->fetchRow($result)){
          ++$tas;
            $staff_id=$row['id_c'];
            $result1 = $db->query("SELECT `status` FROM `fy_working_staf` WHERE id='".$staff_id."' AND `status`='Completed'");
            $staf = $db->fetchByAssoc($result1);
            $status = $staf['status'];
            if($stat=='Completed')
             {
                ++$tas1;
                //$comple_staus='Closed_Closed';
             }
        }
        if(($tas == $tas1) && ($tas1 !=0) )
        {
            $q = $db->query("UPDATE `tasks` SET `status`='Completed' WHERE id='".$t_id."' ");
            $st = $db->fetchByAssoc($q);
        }
</code>```

答:
Instead i can use break condition in this  as :</p>

```<code>  while($row = $db->fetchRow($result)){
        $staff_id=$row['id_c'];
        $result1 = $db->query("SELECT `status` FROM `fy_working_staf` WHERE id='".$staff_id."' AND `status`='Completed'");
        $staf = $db->fetchByAssoc($result1);
        $status = $staf['status'];
        if($stat!='Completed')
         {
            $comple_staus='Closed_Closed';
            break;// will exit the loop when the row is not same

         }
    }
</code>```

Body:
how to check resulted row values from while loop are same,I need to update when status is completed from all results...

        $result = $db->query("SELECT * FROM fy_working_staf_cstm WHERE task_id_c='".$t_id."'");
        while($row = $db->fetchRow($result)){
          ++$tas;
            $staff_id=$row['id_c'];
            $result1 = $db->query("SELECT `status` FROM `fy_working_staf` WHERE id='".$staff_id."' AND `status`='Completed'");
            $staf = $db->fetchByAssoc($result1);
            $status = $staf['status'];
            if($stat=='Completed')
             {
                ++$tas1;
                //$comple_staus='Closed_Closed';
             }
        }
        if(($tas == $tas1) && ($tas1 !=0) )
        {
            $q = $db->query("UPDATE `tasks` SET `status`='Completed' WHERE id='".$t_id."' ");
            $st = $db->fetchByAssoc($q);
        }

Body:
Instead i can use break condition in this  as :

  while($row = $db->fetchRow($result)){
        $staff_id=$row['id_c'];
        $result1 = $db->query("SELECT `status` FROM `fy_working_staf` WHERE id='".$staff_id."' AND `status`='Completed'");
        $staf = $db->fetchByAssoc($result1);
        $status = $staf['status'];
        if($stat!='Completed')
         {
            $comple_staus='Closed_Closed';
            break;// will exit the loop when the row is not same

         }
    }


问:
How to change Stage name in javaFX Web Browser on loading of Web page?

I am creating a web browser using JavaFx. Suppose I have a name for my browser MY BROWSER . I want that whenever web page(for example http:www.google.com) load then Stage Name should be MY BROWSER - Google. How to do it. I have already set my stage name as MY BROWSER.

This is constructor of my HomeEngine class.

```<code>HomeEngine(){
WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();
webEngine.load("http://google.com");
}
</code>```

I am using making object of this HomeEngine class in my Main Class.

```<code>HomeEngine browser = new HomeEngine();
</code>```

I had already set Title for my Main class stage as MY BROWSER.

```<code>primaryStage.setTitle("MY BROWSER :"+browser.getWebEngine().getTitle());
</code>```

Before Loading Webpage

After Loading Webpage

答:
I think the answer according to what i understood from the comments and the question is very simple

but at first let's understand the problem you sometimes have a null title of the loaded web page and this is due to two things

you try to get the title before the page being loaded completely,so you must put a listener when a page is completely loaded, get its title as the following simple sample of code

```<code>browser.getEngine().getLoadWorker().
            stateProperty().
            addListener(new ChangeListener()
            {
                @Override
                public void changed(ObservableValue observable, Worker.State oldValue, Worker.State newValue)
                {
                    if (newValue == Worker.State.SUCCEEDED)
                    {
                        primaryStage.setTitle("My Browser : " + browser.getEngine().getTitle());
                    }
                }
            });</code>```

and as you knew the WebView works asynchronously

the page itself has no title so when the WebView tries to get the title it finds nothing ie:null

hope this is useful

Body:
I am creating a web browser using JavaFx. Suppose I have a name for my browser MY BROWSER . I want that whenever web page(for example http:www.google.com) load then Stage Name should be MY BROWSER - Google. How to do it. I have already set my stage name as MY BROWSER.

This is constructor of my HomeEngine class.

HomeEngine(){
WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();
webEngine.load("http://google.com");
}

I am using making object of this HomeEngine class in my Main Class.

HomeEngine browser = new HomeEngine();

I had already set Title for my Main class stage as MY BROWSER.

primaryStage.setTitle("MY BROWSER :"+browser.getWebEngine().getTitle());

Before Loading Webpage

After Loading Webpage

Body:
I think the answer according to what i understood from the comments and the question is very simple

but at first let's understand the problem you sometimes have a null title of the loaded web page and this is due to two things

you try to get the title before the page being loaded completely,so you must put a listener when a page is completely loaded, get its title as the following simple sample of code

browser.getEngine().getLoadWorker().
            stateProperty().
            addListener(new ChangeListener()
            {
                @Override
                public void changed(ObservableValue observable, Worker.State oldValue, Worker.State newValue)
                {
                    if (newValue == Worker.State.SUCCEEDED)
                    {
                        primaryStage.setTitle("My Browser : " + browser.getEngine().getTitle());
                    }
                }
            });

and as you knew the WebView works asynchronously

the page itself has no title so when the WebView tries to get the title it finds nothing ie:null

hope this is useful


问:
Unable to route in ruby on rails as I encounter specific error

I'm using rails 5.0 and I get the

PostsController#index is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: []

NOTE! For XHR/Ajax or API requests while trying to input my url/posts.

my routing.rb file is below:

```<code>Rails.application.routes.draw do
    get 'posts/index' => 'posts#index'
    resources: posts
end
</code>```

my posts_controller.rb looks like below:

```<code>class PostsController < ApplicationController
    def index

    end
end
</code>```

I want to know specifically what I'm doing wrong. I've just started to learning Ruby on Rails.

答:
GET profiles/employees- Should display all the employees
GET profiles/employees/:id should display a specfic employee
GET profiles/donors - Should display all the donors
GET profiles/donors/:id - Should display a specfic donor```

routes in ruby on rails behave in the same way as href tag in rails

we use get for link and if we want toi perform any action on button then w e have to use button.

if you have any doubt let me know in detail.

for more details refer this

http://guides.rubyonrails.org/routing.html

if we write only localhost:3000/employees then bydefault our application will redirect to index page.

Body:
I'm using rails 5.0 and I get the

PostsController#index is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: []

NOTE! For XHR/Ajax or API requests while trying to input my url/posts.

my routing.rb file is below:

Rails.application.routes.draw do
    get 'posts/index' => 'posts#index'
    resources: posts
end

my posts_controller.rb looks like below:

class PostsController < ApplicationController
    def index

    end
end

I want to know specifically what I'm doing wrong. I've just started to learning Ruby on Rails.

Body:
GET profiles/employees- Should display all the employees
GET profiles/employees/:id should display a specfic employee
GET profiles/donors - Should display all the donors
GET profiles/donors/:id - Should display a specfic donor

routes in ruby on rails behave in the same way as href tag in rails

we use get for link and if we want toi perform any action on button then w e have to use button.

if you have any doubt let me know in detail.

for more details refer this

http://guides.rubyonrails.org/routing.html

if we write only localhost:3000/employees then bydefault our application will redirect to index page.


问:
Creating a List of Names from an Input File
I'm going crazy trying to figure out how to get rid of the error 'str has no attribute append'. I need to add the people's names to name_list from the input file.

A typical line from the input file would read:

Tameka harris 3/4/17

Here is the code I have so far:

```<code>def process_input(file1, any_dict, any_set):

    #open input file
    customer_input_file = open(file1, 'r')

    #initialize a list to store info by line
    line_list = []

    #Create a name counter
    index = 0

    #read file line by line
    for line in customer_input_file:
        #split the line
        line_list = line.split()
        #slice the list to make a list with only names and no dates
        name_list = line_list[-1]
        #create a variable for first name from list
        fname = name_list[0].title()
        #create a last name variable from list
        lname = name_list[1].title()
        #add the two name variables together as a new list
        input_name = [fname + ' ' + lname]

        #add names to name list
        name_list.append(input_name)

        #add names to name list
        any_set.add(name_list[index])

        #count the times a name repeats in the name list
        any_dict[input_name] = name_list.count(input_name)

        #add 1 to index
        index += 1

    #Close input file
    customer_input_file.close
</code>```

答:
```<code># slice the list to make a list with only names and no dates
name_list = line_list[-1]
</code>```

The above returns the last item in the list which is a string and that's why name_list.append(input_name) throws the error.

What you need is to exclude the last item:

```<code>name_list = line_list[:-1]
</code>```

Body:
I'm going crazy trying to figure out how to get rid of the error 'str has no attribute append'. I need to add the people's names to name_list from the input file.

A typical line from the input file would read:

Tameka harris 3/4/17

Here is the code I have so far:

def process_input(file1, any_dict, any_set):

    #open input file
    customer_input_file = open(file1, 'r')

    #initialize a list to store info by line
    line_list = []

    #Create a name counter
    index = 0

    #read file line by line
    for line in customer_input_file:
        #split the line
        line_list = line.split()
        #slice the list to make a list with only names and no dates
        name_list = line_list[-1]
        #create a variable for first name from list
        fname = name_list[0].title()
        #create a last name variable from list
        lname = name_list[1].title()
        #add the two name variables together as a new list
        input_name = [fname + ' ' + lname]

        #add names to name list
        name_list.append(input_name)

        #add names to name list
        any_set.add(name_list[index])

        #count the times a name repeats in the name list
        any_dict[input_name] = name_list.count(input_name)

        #add 1 to index
        index += 1

    #Close input file
    customer_input_file.close

Body:
# slice the list to make a list with only names and no dates
name_list = line_list[-1]

The above returns the last item in the list which is a string and that's why name_list.append(input_name) throws the error.

What you need is to exclude the last item:

name_list = line_list[:-1]