问:
No Suitable method findViewById
So I am getting this error when I go to run the app, the thing is my webview code worked for my previous java files, all i did was change a digit in ff1walkthrough to ff2walkthrough and ff1 to ff2:

```<code>Error:(28, 36) error: no suitable method found for findViewById(WebView)
method Activity.<T>findViewById(int) is not applicable
(cannot infer type-variable(s) T
(argument mismatch; WebView cannot be converted to int))
method AppCompatActivity.findViewById(int) is not applicable
(argument mismatch; WebView cannot be converted to int)
where T is a type-variable:
T extends View declared in method <T>findViewById(int)
</code>```

my code:

FinalFantasy2.Java

```<code>package net.sunsetdevelopment.masteryourrpgs;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class FinalFantasy2 extends AppCompatActivity {
WebView ff2walkthrough;

/* Go Back Function */
@Override
public void onBackPressed() {
    if (ff2walkthrough.canGoBack()){
        ff2walkthrough.goBack();
    }else {
        super.onBackPressed();
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_final_fantasy2);
    ff2walkthrough = (WebView) findViewById(ff2walkthrough);

    /* Enable Javascript */
    ff2walkthrough.getSettings().setJavaScriptEnabled(true);
    ff2walkthrough.setFocusable(true);
    ff2walkthrough.setFocusableInTouchMode(true);

    /* Render Priority */
    ff2walkthrough.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    ff2walkthrough.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    ff2walkthrough.getSettings().setDomStorageEnabled(true);
    ff2walkthrough.getSettings().setDatabaseEnabled(true);
    ff2walkthrough.getSettings().setAppCacheEnabled(true);
    ff2walkthrough.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

    /* URL */
    ff2walkthrough.loadUrl("link hidden for stackoverflow");
    ff2walkthrough.setWebViewClient(new WebViewClient());

    }

}
</code>```

HomeScreen.Java

```<code>package net.sunsetdevelopment.masteryourrpgs;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;

public class HomeScreen extends AppCompatActivity {

/* Declarations */
ImageButton ff1walkthrough;
ImageButton ff2walkthrough;

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

    /* Final Fantasy 1 Walkthrough */
    ff1walkthrough = (ImageButton) findViewById(R.id.ff1);

    ff1walkthrough.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intentLoadNewActivity = new Intent(HomeScreen.this, FinalFantasy1.class);
            startActivity(intentLoadNewActivity);
        }
    });

    /* Final Fantasy 2 Walkthrough */

    ff2walkthrough = (ImageButton) findViewById(R.id.ff2);

    ff2walkthrough.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intentLoadNewActivity = new Intent(HomeScreen.this, FinalFantasy2.class);
            startActivity(intentLoadNewActivity);
        }
    });

}
}
</code>```

activity_final_fantasy2.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="net.sunsetdevelopment.masteryourrpgs.FinalFantasy2">

<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/ff2walkthrough"/>

</RelativeLayout>
</code>```

I am still very new to Java Programming / Android App Development. I have barely read some books, just simply trying to learn by doing and following along to YouTube tutorials.

Thanks for your help, in advance.

答:
Change it to:</p>

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_final_fantasy2);
    ff2walkthrough = (WebView) findViewById(R.id.ff2walkthrough); //HERE IS THE ERROR

    /* Enable Javascript */
    ff2walkthrough.getSettings().setJavaScriptEnabled(true);
    ff2walkthrough.setFocusable(true);
    ff2walkthrough.setFocusableInTouchMode(true);

    /* Render Priority */
    ff2walkthrough.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    ff2walkthrough.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    ff2walkthrough.getSettings().setDomStorageEnabled(true);
    ff2walkthrough.getSettings().setDatabaseEnabled(true);
    ff2walkthrough.getSettings().setAppCacheEnabled(true);
    ff2walkthrough.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

    /* URL */
    ff2walkthrough.loadUrl("link hidden for stackoverflow");
    ff2walkthrough.setWebViewClient(new WebViewClient());

    }
</code>```

Title: No Suitable method findViewById

Body:
So I am getting this error when I go to run the app, the thing is my webview code worked for my previous java files, all i did was change a digit in ff1walkthrough to ff2walkthrough and ff1 to ff2:

Error:(28, 36) error: no suitable method found for findViewById(WebView)
method Activity.<T>findViewById(int) is not applicable
(cannot infer type-variable(s) T
(argument mismatch; WebView cannot be converted to int))
method AppCompatActivity.findViewById(int) is not applicable
(argument mismatch; WebView cannot be converted to int)
where T is a type-variable:
T extends View declared in method <T>findViewById(int)

my code:

FinalFantasy2.Java

package net.sunsetdevelopment.masteryourrpgs;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class FinalFantasy2 extends AppCompatActivity {
WebView ff2walkthrough;

/* Go Back Function */
@Override
public void onBackPressed() {
    if (ff2walkthrough.canGoBack()){
        ff2walkthrough.goBack();
    }else {
        super.onBackPressed();
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_final_fantasy2);
    ff2walkthrough = (WebView) findViewById(ff2walkthrough);

    /* Enable Javascript */
    ff2walkthrough.getSettings().setJavaScriptEnabled(true);
    ff2walkthrough.setFocusable(true);
    ff2walkthrough.setFocusableInTouchMode(true);

    /* Render Priority */
    ff2walkthrough.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    ff2walkthrough.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    ff2walkthrough.getSettings().setDomStorageEnabled(true);
    ff2walkthrough.getSettings().setDatabaseEnabled(true);
    ff2walkthrough.getSettings().setAppCacheEnabled(true);
    ff2walkthrough.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

    /* URL */
    ff2walkthrough.loadUrl("link hidden for stackoverflow");
    ff2walkthrough.setWebViewClient(new WebViewClient());

    }

}

HomeScreen.Java

package net.sunsetdevelopment.masteryourrpgs;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;

public class HomeScreen extends AppCompatActivity {

/* Declarations */
ImageButton ff1walkthrough;
ImageButton ff2walkthrough;

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

    /* Final Fantasy 1 Walkthrough */
    ff1walkthrough = (ImageButton) findViewById(R.id.ff1);

    ff1walkthrough.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intentLoadNewActivity = new Intent(HomeScreen.this, FinalFantasy1.class);
            startActivity(intentLoadNewActivity);
        }
    });

    /* Final Fantasy 2 Walkthrough */

    ff2walkthrough = (ImageButton) findViewById(R.id.ff2);

    ff2walkthrough.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intentLoadNewActivity = new Intent(HomeScreen.this, FinalFantasy2.class);
            startActivity(intentLoadNewActivity);
        }
    });

}
}

activity_final_fantasy2.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="net.sunsetdevelopment.masteryourrpgs.FinalFantasy2">

<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/ff2walkthrough"/>

</RelativeLayout>

I am still very new to Java Programming / Android App Development. I have barely read some books, just simply trying to learn by doing and following along to YouTube tutorials.

Thanks for your help, in advance.

Body:
Change it to:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_final_fantasy2);
    ff2walkthrough = (WebView) findViewById(R.id.ff2walkthrough); //HERE IS THE ERROR

    /* Enable Javascript */
    ff2walkthrough.getSettings().setJavaScriptEnabled(true);
    ff2walkthrough.setFocusable(true);
    ff2walkthrough.setFocusableInTouchMode(true);

    /* Render Priority */
    ff2walkthrough.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    ff2walkthrough.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    ff2walkthrough.getSettings().setDomStorageEnabled(true);
    ff2walkthrough.getSettings().setDatabaseEnabled(true);
    ff2walkthrough.getSettings().setAppCacheEnabled(true);
    ff2walkthrough.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

    /* URL */
    ff2walkthrough.loadUrl("link hidden for stackoverflow");
    ff2walkthrough.setWebViewClient(new WebViewClient());

    }


来源: stackexchange

问:
How can I navigate to lazy loaded module child routes?
I am trying to lazy load module with child routes declared in it's routing configuration file,
The lazy module loaded successfully but I can't navigate to it's child routes.

I am using the technique as if it were a eagerly loaded module.
I declared path and inside it it's children.
Please see 'moduleB' routing file in the Plunker
The link button is trying to navigate to the child route and load CmpC. but it fails.

Here is my root module routing decalration:

```<code>{ path: 'feature-b', loadChildren:'src/featureB/featureB.module#FeatureBModule' ,  pathMatch: 'full'}
</code>```

Here is my lazy loaded module routing declaration.

```<code>export const moduleBRoutes: Routes = [

  { path: '', component:CmpC , pathMatch: 'full',children:[
      {path: '' , pathMatch: 'full'},
      { path: 'c', component:CmpB , pathMatch: 'full'}
  ]},

];

export const subRouting: ModuleWithProviders = RouterModule.forChild(moduleBRoutes);
</code>```

trying to navigate to : localhost:999/feature-b succeeded

trying to navigate to : localhost:999/feature-b/c failed

https://plnkr.co/edit/wFlJoDXRmAlMOswmwWFk?p=preview

答:
I had the same issue, in my case no error appear but the view doesnt load, I can solved the problem by this way:

This is my lazy module

const routes: Routes = [
  {
    path: ''
    },
    children: [
      { path: '', component: AdminComponent },
      { path: 'users', component: AdminUsersComponent },
      { path: 'games', component: AdminGamesComponent },
      { path: '**', redirectTo: '' }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AdminRoutingModule { }
```

<ul>
<li>This is my root module</li>
</ul>

<pre class="lang-js prettyprint-override"><code>const routes: Routes = [
  {
    path: 'admin', loadChildren: 'app/admin/admin.module#AdminModule'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { enableTracing: !environment.production })],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

Now the routes:

admin/

admin/users

admin/games

works perfectly

ContentLicense: CC BY-SA 3.0

Body:
I am trying to lazy load module with child routes declared in it's routing configuration file,
The lazy module loaded successfully but I can't navigate to it's child routes.

I am using the technique as if it were a eagerly loaded module.
I declared path and inside it it's children.
Please see 'moduleB' routing file in the Plunker
The link button is trying to navigate to the child route and load CmpC. but it fails.

Here is my root module routing decalration:

{ path: 'feature-b', loadChildren:'src/featureB/featureB.module#FeatureBModule' ,  pathMatch: 'full'}

Here is my lazy loaded module routing declaration.

export const moduleBRoutes: Routes = [

  { path: '', component:CmpC , pathMatch: 'full',children:[
      {path: '' , pathMatch: 'full'},
      { path: 'c', component:CmpB , pathMatch: 'full'}
  ]},

];

export const subRouting: ModuleWithProviders = RouterModule.forChild(moduleBRoutes);

trying to navigate to : localhost:999/feature-b succeeded

trying to navigate to : localhost:999/feature-b/c failed

https://plnkr.co/edit/wFlJoDXRmAlMOswmwWFk?p=preview

Body:
I had the same issue, in my case no error appear but the view doesnt load, I can solved the problem by this way:

This is my lazy module

const routes: Routes = [
  {
    path: ''
    },
    children: [
      { path: '', component: AdminComponent },
      { path: 'users', component: AdminUsersComponent },
      { path: 'games', component: AdminGamesComponent },
      { path: '**', redirectTo: '' }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AdminRoutingModule { }

This is my root module

const routes: Routes = [
  {
    path: 'admin', loadChildren: 'app/admin/admin.module#AdminModule'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { enableTracing: !environment.production })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Now the routes:

admin/

admin/users

admin/games

works perfectly


问:
How can I convert a date from the format "dd/mm/yyyy" to "yyyy/dd/mm"?
I have a Textbox in which the user is supposed to enter a date in the format dd/mm/yyyy, this date is stored as yyyy/mm/dd in the database.

So I want the user to enter the date in dd/mm/yyyy format and later I want to convert to yyyy/mm/dd so that I can query database.

How can I convert the user input date dd/mm/yyyy to yyyy/mm/dd?

答:
Assuming you store the date in a DateTime field in the database, the date is not actually stored in the format dd/mm/yyyy.

To render the date use:

```<code>string formattedDate = dateFromDb.ToString("yyyy/MM/dd");
</code>```

To convert a date string for a particular format you can use:

```<code>DateTime value;

if (DateTime.TryParseExact(
  date,
  "dd/MM/yyyy",
  new CultureInfo("en-GB"),
  System.Globalization.DateTimeStyles.None,
  out value))
{
  Console.Write(value.ToString("yyyy/MM/dd"));
}
else
{
  Console.Write("Date parse failed!");
}
</code>```

Body:
Assuming you store the date in a DateTime field in the database, the date is not actually stored in the format dd/mm/yyyy.

To render the date use:

string formattedDate = dateFromDb.ToString("yyyy/MM/dd");

To convert a date string for a particular format you can use:

DateTime value;

if (DateTime.TryParseExact(
  date,
  "dd/MM/yyyy",
  new CultureInfo("en-GB"),
  System.Globalization.DateTimeStyles.None,
  out value))
{
  Console.Write(value.ToString("yyyy/MM/dd"));
}
else
{
  Console.Write("Date parse failed!");
}

ContentLicense: CC BY-SA 2.5


问:
The Comment&Like design with Redis

I am drunk in the design of 'Comment & Like'!
I've finished the mysql works with the help in the stackoverflow,But when I am try to design the redis for it,I feel bad again -_-|||

The situation is:

When the client request the comment data from my service with the user info,service should tell client if the user had already liked the comment,Okay,I have 3 tables:User,Comment,Like(include user_id,and comment_id)
I'd like to select comments from table 'Comment' and use 'left join' to query out the like info from table 'Like'(with user_id and comment_id).It's the way solution for mysql.
I found that the query will be very slow if there have lots of Comments and Likes in the mysql DB,so,I have to use Redis to optimise it.But I am very confused when trying to work:

**1.**It's easy to cache data if the data have no relation with the user,I mean every user will get the same data,like the articles,post.

**2.**It's hard to cache data if the data have relation with the user,I mean every user will get the different data,like the 'like or not for a comment'

I am thinking about cache every Like info to redis,and query it out after the comment be queried,and set it into the comment.like.But the issue is that if I can not query the like info in redis, it could be caused by the crashing of redis,should I try to load from mysql again?If so,the redis make no means,mysql will be in heavy queries

答:
Like/no like is just the same as yes/no, true/false, they are only binary information. Binary information can be easily recorded as 1/0. Therefore you should consider using bitmap to record this type of information.

This is a typical Redis bitmap usage, so instead of me copying and pasting these information from a blog, I shall introduce you to one that's been mentioned in the Redis official documentation: http://blog.getspool.com/2011/11/29/fast-easy-realtime-metrics-using-redis-bitmaps/

It is a quite detailed technical blog and come with code examples. I am sure you will find it useful.

Title: The Comment&Like design with Redis


答:
Forgot to add the reference to R.id, like this:

```<code>findViewById(R.id.ff2walkthrough);
</code>```

Instead of just calling ff2walkthrough, for further reference check the Docs to know more about Android resources.

Title: No Suitable method findViewById

Body:
Forgot to add the reference to R.id, like this:

findViewById(R.id.ff2walkthrough);

Instead of just calling ff2walkthrough, for further reference check the Docs to know more about Android resources.


问:
Sliding menu from the top hides behind Safari mobile bar
I have a serious issue with my dropdown settings on iOS Safari. Imagine a website, which has a header on the top. If you click the header, it will slide down, just like any notification center on mobile phones. The way I chose was quite simple. I have a
 with this css:

```<code>.settings{
    position: fixed;
    width: 100%;
    height: calc(100vh + 60px);
    border-bottom-left-radius: 15px;
    border-bottom-right-radius: 15px;
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
    z-index: 10;
}

.hide{
    top: -100vh;
}
</code>```

Now, this makes it look like so:

Now, the next step was to create it "slide-able" which I've done using jQuery, by adding class called "show".

```<code>.show{
    top: calc(0vh - 60px);
}
</code>```

And this actually made it great. It just worked! Suddenly I tried the website on my iPhone, and because of the bottom bar, always showing until you scroll, my hipe was all gone.

Because it look like this:

Getting it so far? My menu did slide correctly, looks great in any browser, but here in Safari, it is hidden right behind the bar, so user actually can't close it.

I tried my best to solve this issue, butnothing really worked as I wanted.

PS: I assume you know that, but it kinda works when you use bottom: 0;, then it "knows" about the bar and stops correctly right above it. But because the setting is calculated with top position, it does not do the animation, which is necessary for my design.

Any help/solution appreciated!

答:
David, unfortunately iOS Safari is full of unpleasant surprises.

One of them is what iOS Safari considers 100vh.

Viewport height in iOS Safari is not equal window inner height as in Chrome or Firefox.

E.g. on iPhone 7plus 100vh == 696px, but window.innerHeight == 628px.

On iPhone 6 100vh == 628px, but window.innerHeight == 559px.

And so on...

So the solution is getting rid of 100vh.

Assuming that body is offset parent of .settings use 100% instead:

```<code>.settings {
    position: fixed;
    width: 100%;
    height: calc(100% + 60px);
    ...
}

.hide {
    top: -100%;
}
</code>```

Also you do not need to use calc in your .show class (since 0vh === 0):

```<code>.show {
    top: -60px;
}
</code>```

Body:
I have a serious issue with my dropdown settings on iOS Safari. Imagine a website, which has a header on the top. If you click the header, it will slide down, just like any notification center on mobile phones. The way I chose was quite simple. I have a
 with this css:

.settings{
    position: fixed;
    width: 100%;
    height: calc(100vh + 60px);
    border-bottom-left-radius: 15px;
    border-bottom-right-radius: 15px;
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
    z-index: 10;
}

.hide{
    top: -100vh;
}

Now, this makes it look like so:

Now, the next step was to create it "slide-able" which I've done using jQuery, by adding class called "show".

.show{
    top: calc(0vh - 60px);
}

And this actually made it great. It just worked! Suddenly I tried the website on my iPhone, and because of the bottom bar, always showing until you scroll, my hipe was all gone.

Because it look like this:

Getting it so far? My menu did slide correctly, looks great in any browser, but here in Safari, it is hidden right behind the bar, so user actually can't close it.

I tried my best to solve this issue, butnothing really worked as I wanted.

PS: I assume you know that, but it kinda works when you use bottom: 0;, then it "knows" about the bar and stops correctly right above it. But because the setting is calculated with top position, it does not do the animation, which is necessary for my design.

Any help/solution appreciated!

Body:
David, unfortunately iOS Safari is full of unpleasant surprises.

One of them is what iOS Safari considers 100vh.

Viewport height in iOS Safari is not equal window inner height as in Chrome or Firefox.

E.g. on iPhone 7plus 100vh == 696px, but window.innerHeight == 628px.

On iPhone 6 100vh == 628px, but window.innerHeight == 559px.

And so on...

So the solution is getting rid of 100vh.

Assuming that body is offset parent of .settings use 100% instead:

.settings {
    position: fixed;
    width: 100%;
    height: calc(100% + 60px);
    ...
}

.hide {
    top: -100%;
}

Also you do not need to use calc in your .show class (since 0vh === 0):

.show {
    top: -60px;
}


问:
JavaScript. Creating a dynamic table based on a user input
I'm trying to ask the user through a prompt for a number that is an: integer, greater than 0, and is numeric. I did that with a do while loop and seems to be working correctly. With that number I have to pass it to the function called "genTable" and create a table with a dynamic amount of rows based on what the user typed. However, with my current code I can't seem to get the table to appear on the page. Any ideas on where I went wrong and how to fix it?</p>

```<code><!DOCTYPE HTML>

<html>
<head>
<title>jsLoopDemo</title>

<!--
Honor Code: I acknowledge that this code represents my own work: CC
Date:  July 6, 2017
-->

<meta charset="utf-8" />
<meta name="description" content="Create a chart with rows based on a number
user chose." />
<meta name="keywords" content="loop, row, dynamic" />
<meta name="author" content="" />

<script type="text/javascript">

    do{
       var numChose = prompt("Please enter an interger greater than zero.");
    }while (isNaN(numChose) || numChose % 1 !== 0 || numChose < 1 );

    function genTable(numChose)
    {
        var table = document.createElement("TABLE");
        var tableBody = document.createElement("TBODY");
        table.appendChild(tableBody);
        var myTableDiv = document.getElementById("mytable");

        for (var r = 0; r <= numChose; r++)
            {
                var tr = document.createElement("TR");
                tableBody.appendChild(tr);
                var td = document.createElement("TD");
                tr.appendChild(td);
                td.appendChild(document.createTextNode("Row " + r));
            }
     myTableDiv.appendChild(table);
    }

</script>

</head>

<body>

<div id="mytable">
</div>

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

答: Move the

Body:
I'm trying to ask the user through a prompt for a number that is an: integer, greater than 0, and is numeric. I did that with a do while loop and seems to be working correctly. With that number I have to pass it to the function called "genTable" and create a table with a dynamic amount of rows based on what the user typed. However, with my current code I can't seem to get the table to appear on the page. Any ideas on where I went wrong and how to fix it?

<!DOCTYPE HTML>

<title>jsLoopDemo</title>

<meta charset="utf-8" />
<meta name="description" content="Create a chart with rows based on a number
user chose." />
<meta name="keywords" content="loop, row, dynamic" />
<meta name="author" content="" />

Body:
Move the <script> code after the

<div id="mytable">
</div>

in <body> so that the element is rendered on DOM while table is being generated and call the function

genTable(numChose);

after you get the number from user.


问:
Application-Defined or Object-defined error - Qualifying References Excel
Trying to hammer out bugs in my code. Currently trying to do some very simple, open worksheet, copy and paste data over. Trying to do it all without using .Select or .Activate. Hitting "Application-defined or Object defined error", which, from reading the other threads on the matter, probably means that my statements aren't fully qualified. However, I can't figure out how they're not fully qualified - other posts on the topic seem to be missing a "." somewhere in the code, but my attempts to fix it haven't gotten anywhere. Heavily truncated code as follows (If you don't see it dimmed/defined, it's elsewhere)

```<code>Sub CopyPaste()
Dim CitiReportEUR As Workbook
Dim CitiReportPathEUR  As String

CitiReportPathEUR = Range("CitiReportPathEUR")
  Workbooks.Open Filename:=CitiReportPathEUR
         Set CitiReportEUR = ActiveWorkbook

         LastRowCiti = CitiReportEUR.Sheets(1).Range("I" & Rows.Count).End(xlUp).Row
         Set RngCitiEUR = CitiReportEUR.Sheets(1).Range("A1:CT" & LastRowCiti).SpecialCells(xlCellTypeVisible)

 Set CabReport.Sheets("CITI").Range("C1").Resize(RngCitiEUR.Rows.Count).Value = RngCitiEUR.Value
End Sub
</code>```

Currently the error is occurring when I define the range. I've had problems historically with pasting into the range as well... but that's an issue for when I can actually get the code to run that far!

答:
Rows.Count is implicitly working with the ActiveSheet.

The use of Set when assigning values to the Value property of a Range is inappropriate.  Set should only be used when assigning a reference to an object.

The Resize probably needs to cater for the number of columns in the source as well as rows.

This code is more explicit:

```<code>Sub CopyPaste()
    Dim CitiReportEUR As Workbook
    Dim CitiReportPathEUR  As String

    CitiReportPathEUR = Range("CitiReportPathEUR")
    Set CitiReportEUR = Workbooks.Open(Filename:=CitiReportPathEUR)
    With CitiReportEUR.Sheets(1)
        LastRowCiti = .Range("I" & .Rows.Count).End(xlUp).Row
        Set RngCitiEUR = .Range("A1:CT" & LastRowCiti).SpecialCells(xlCellTypeVisible)
    End With
    CabReport.Sheets("CITI").Range("C1").Resize(RngCitiEUR.Rows.Count, RngCitiEUR.Columns.Count).Value = RngCitiEUR.Value
End Sub
</code>```

Body:
Trying to hammer out bugs in my code. Currently trying to do some very simple, open worksheet, copy and paste data over. Trying to do it all without using .Select or .Activate. Hitting "Application-defined or Object defined error", which, from reading the other threads on the matter, probably means that my statements aren't fully qualified. However, I can't figure out how they're not fully qualified - other posts on the topic seem to be missing a "." somewhere in the code, but my attempts to fix it haven't gotten anywhere. Heavily truncated code as follows (If you don't see it dimmed/defined, it's elsewhere)

Sub CopyPaste()
Dim CitiReportEUR As Workbook
Dim CitiReportPathEUR  As String

CitiReportPathEUR = Range("CitiReportPathEUR")
  Workbooks.Open Filename:=CitiReportPathEUR
         Set CitiReportEUR = ActiveWorkbook

         LastRowCiti = CitiReportEUR.Sheets(1).Range("I" & Rows.Count).End(xlUp).Row
         Set RngCitiEUR = CitiReportEUR.Sheets(1).Range("A1:CT" & LastRowCiti).SpecialCells(xlCellTypeVisible)

 Set CabReport.Sheets("CITI").Range("C1").Resize(RngCitiEUR.Rows.Count).Value = RngCitiEUR.Value
End Sub

Currently the error is occurring when I define the range. I've had problems historically with pasting into the range as well... but that's an issue for when I can actually get the code to run that far!

Body:
Rows.Count is implicitly working with the ActiveSheet.

The use of Set when assigning values to the Value property of a Range is inappropriate.  Set should only be used when assigning a reference to an object.

The Resize probably needs to cater for the number of columns in the source as well as rows.

This code is more explicit:

Sub CopyPaste()
    Dim CitiReportEUR As Workbook
    Dim CitiReportPathEUR  As String

    CitiReportPathEUR = Range("CitiReportPathEUR")
    Set CitiReportEUR = Workbooks.Open(Filename:=CitiReportPathEUR)
    With CitiReportEUR.Sheets(1)
        LastRowCiti = .Range("I" & .Rows.Count).End(xlUp).Row
        Set RngCitiEUR = .Range("A1:CT" & LastRowCiti).SpecialCells(xlCellTypeVisible)
    End With
    CabReport.Sheets("CITI").Range("C1").Resize(RngCitiEUR.Rows.Count, RngCitiEUR.Columns.Count).Value = RngCitiEUR.Value
End Sub


问:
jQuery browser detection?
Is there a good way to detect if the user's browser is Internet Explorer using jQuery?

I have an issue with PNG graphics using IE and want to swap them for GIF's only if the user is viewing the site with IE.

答:
Check out the $.browser function.

To detect IE, you can also and better go for IE conditional comments.

Example:

```<code><!--[if IE]>
  Special instructions for IE here
<![endif]-->
</code>```

Title: jQuery browser detection?

Body:
Check out the $.browser function.

To detect IE, you can also and better go for IE conditional comments.

Example:

<!--[if IE]>
  Special instructions for IE here
<![endif]-->


问:
Using for loop to append div
In my code I have a HTML form that a user fills. They then enter a value in the field "member" and click on the button to generate additional copies of div = 'sector_prop'.
FORM part is -
        Number of Sectors (LTE)

```<code><br>
<br>
<input type="text" id="member" name="member" value="">
 <br>
 <br>

 <button>Generate Sector Properties</button>
</code>```

Here div "sector_prop" is

```<code><div class="sector_prop">
<fieldset>
Primary LTE Carrier (Select lowest frequency on the site 850 for Band 5, AWS
for Band 4 and PCS for Band 2)<br>
<br>
<select name="lte_freq1">
<option value="6">850</option>
<option value="2">AWS</option>
<option value="4">PCS</option>
</select>
<br>
</fieldset>
</code>```

I want to append the div using a for loop. This code works perfectly well for values 1,2,3,4,5. When value of number is 6 or above the code breaks and appends more  than the needed div. I am trying to find out why this happens. Any suggestions ?

```<code>$(document).ready(function(){
$("button").click(function(){
var number = document.getElementById("member").value;
var repeat = $('.sector_prop');
var cloned = repeat.clone(true);
console.log(number);
for (i=1;i<number;i++){
    cloned.appendTo('.sector_prop');
    console.log(i);
console.log(cloned);
}

 });
});
</code>```

$(document).ready(function(){
    $("button").click(function(){
    var number = document.getElementById("member").value;
    var repeat = $('.sector_prop');
    var cloned = repeat.clone(true);
console.log(number);
 for (i=1;i<number;i++){
        cloned.appendTo('.sector_prop');
        console.log(i);
 console.log(cloned);
 }

    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</head>
<body>

<form action="/form" method="post">

<fieldset>
<legend><b> Transport Information</b></legend>
<br>
<br>
 OAM IP:<br>
<input type="text" name="oam_ip" pattern="^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$"  required>
<br>
<br>

<fieldset>
<fieldset>
<legend><b> RF Parameters</b></legend>
<br>
Number of Sectors (LTE)<br>
<br>
<input type="text" id="member" name="member" value="">
<br>
<br>

<button>Generate Sector Properties</button>

<br>
<br>
<fieldset>

<div class="sector_prop">
<fieldset>
Primary LTE Carrier (Select lowest frequency on the site 850 for Band 5, AWS for Band 4 and PCS for Band 2)<br>
<br>
<select name="lte_freq1">
  <option value="6">850</option>
  <option value="2">AWS</option>
  <option value="4">PCS</option>
</select>
<br>

<br>

</fieldset>
</div>

<input type="submit">
</form>
<br>
<br>
</body></code>```

答:
Does this look like what you are talking about?

$(document).ready(function(){
$("button").click(function(){
var number = document.getElementById("member").value;
var repeat = $('fieldset');
var cloned;
//console.log(number);
for (i=1;i<number;i++){
    cloned = repeat.clone(true);
    cloned.appendTo('.sector_prop');
    //console.log(i);
    //console.log(cloned);
}

 });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br>
<br>
<input type="text" id="member" name="member" value="">
 <br>
 <br>

 <button>Generate Sector Properties</button>
Here div "sector_prop" is

<div class="sector_prop">
<fieldset>
Primary LTE Carrier (Select lowest frequency on the site 850 for Band 5, AWS
for Band 4 and PCS for Band 2)<br>
<br>
<select name="lte_freq1">
<option value="6">850</option>
<option value="2">AWS</option>
<option value="4">PCS</option>
</select>
<br>
</fieldset>
</div></code>```

Title: Using for loop to append div

Body:
In my code I have a HTML form that a user fills. They then enter a value in the field "member" and click on the button to generate additional copies of div = 'sector_prop'.
FORM part is -
        Number of Sectors (LTE)

<input type="text" id="member" name="member" value="">

 <button>Generate Sector Properties</button>

Here div "sector_prop" is

<fieldset>
Primary LTE Carrier (Select lowest frequency on the site 850 for Band 5, AWS
for Band 4 and PCS for Band 2)

<select name="lte_freq1">
<option value="6">850</option>
<option value="2">AWS</option>
<option value="4">PCS</option>
</select>

</fieldset>

I want to append the div using a for loop. This code works perfectly well for values 1,2,3,4,5. When value of number is 6 or above the code breaks and appends more  than the needed div. I am trying to find out why this happens. Any suggestions ?

$(document).ready(function(){
$("button").click(function(){
var number = document.getElementById("member").value;
var repeat = $('.sector_prop');
var cloned = repeat.clone(true);
console.log(number);
for (i=1;i<number;i++){
    cloned.appendTo('.sector_prop');
    console.log(i);
console.log(cloned);
}

 });
});

$(document).ready(function(){
    $("button").click(function(){
    var number = document.getElementById("member").value;
    var repeat = $('.sector_prop');
    var cloned = repeat.clone(true);
console.log(number);
 for (i=1;i<number;i++){
        cloned.appendTo('.sector_prop');
        console.log(i);
 console.log(cloned);
 }

    });
});

<!DOCTYPE html>

<form action="/form" method="post">

<fieldset>
<legend> Transport Information</legend>

 OAM IP:

<input type="text" name="oam_ip" pattern="^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$"  required>

<fieldset>
<fieldset>
<legend> RF Parameters</legend>

Number of Sectors (LTE)

<input type="text" id="member" name="member" value="">

<button>Generate Sector Properties</button>

<fieldset>

<fieldset>
Primary LTE Carrier (Select lowest frequency on the site 850 for Band 5, AWS for Band 4 and PCS for Band 2)

<select name="lte_freq1">
  <option value="6">850</option>
  <option value="2">AWS</option>
  <option value="4">PCS</option>
</select>

</fieldset>

<input type="submit">
</form>

Body:
Does this look like what you are talking about?

$(document).ready(function(){
$("button").click(function(){
var number = document.getElementById("member").value;
var repeat = $('fieldset');
var cloned;
//console.log(number);
for (i=1;i<number;i++){
    cloned = repeat.clone(true);
    cloned.appendTo('.sector_prop');
    //console.log(i);
    //console.log(cloned);
}

 });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br>
<br>
<input type="text" id="member" name="member" value="">
 <br>
 <br>

 <button>Generate Sector Properties</button>
Here div "sector_prop" is

<div class="sector_prop">
<fieldset>
Primary LTE Carrier (Select lowest frequency on the site 850 for Band 5, AWS
for Band 4 and PCS for Band 2)<br>
<br>
<select name="lte_freq1">
<option value="6">850</option>
<option value="2">AWS</option>
<option value="4">PCS</option>
</select>
<br>
</fieldset>
</div>


问:
How to combine two sql expressions into one?
I have the following issue:

It is necessary to write a query that will output 'item_id', 'price_in_byr'.

'price_in_byr' is calculated as the 'price' of the items table multiplied by the currency rate at the maximum date of the rate from the table rates.

See Schema

I apologize for my English, I'll try to explain by example:

Goods with item_id = 5 costs 20 euros, in the rates table the maximum date for the euro is January 12, at that date the exchange rate was 25.  Total our 'price_in_byr' is 25 * 20 = 500

My solution with temp table:

```<code>CREATE TABLE tempRate SELECT currency, MAX(rate) AS maxRate FROM rates GROUP
BY currency;

SELECT items.item_id,(ifnull(tempRate.maxRate,1) * items.price) AS price_in_byr
FROM items
LEFT JOIN tempRate ON items.currency = tempRate.currency;
</code>```

Tell me please, how can I do it in one query?

答:
I am not sure if mysql supports this level of subquery but see if it works:</p>

```<code>select I.item_id, I.price * CR.rt
from
items as I,
(
    select r.currency cy, r.rate rt
    from
        rates as r, (select currency, max(date) max_date from rates group by currency) as R_MAXDATES
    where
        r.currency = R_MAXDATES.currency
        and r.date = R_MAXDATES.max_date;
) As CR
where
I.currency = CR.cy
</code>```

Body:
I have the following issue:

It is necessary to write a query that will output 'item_id', 'price_in_byr'.

'price_in_byr' is calculated as the 'price' of the items table multiplied by the currency rate at the maximum date of the rate from the table rates.

See Schema

I apologize for my English, I'll try to explain by example:

Goods with item_id = 5 costs 20 euros, in the rates table the maximum date for the euro is January 12, at that date the exchange rate was 25.  Total our 'price_in_byr' is 25 * 20 = 500

My solution with temp table:

CREATE TABLE tempRate SELECT currency, MAX(rate) AS maxRate FROM rates GROUP
BY currency;

SELECT items.item_id,(ifnull(tempRate.maxRate,1) * items.price) AS price_in_byr
FROM items
LEFT JOIN tempRate ON items.currency = tempRate.currency;

Tell me please, how can I do it in one query?

Body:
I am not sure if mysql supports this level of subquery but see if it works:

select I.item_id, I.price * CR.rt
from
items as I,
(
    select r.currency cy, r.rate rt
    from
        rates as r, (select currency, max(date) max_date from rates group by currency) as R_MAXDATES
    where
        r.currency = R_MAXDATES.currency
        and r.date = R_MAXDATES.max_date;
) As CR
where
I.currency = CR.cy


问:
how to disabled each items in gridview according to the textbox text?

if booking closed column values is equal or more than textbox1 text then the book button in gridview will be disabled for each gridview item whose booking closed time is greater and equal to textbox1 time ..

How to do that ?

M using VS 2008 and vb

答:
You should handle this issue in the rowbound event handler of the GridView.

Update #1

```<code>protected void books_RowDataBound(object sender, GridViewRowEventArgs e) {
            if(e.Row.RowType == DataControlRowType.DataRow) {

                //Do this only if the textbox value is ....
                Button btn =  (( GridView )sender).FindControl("button");
                btn.Enabled = false;
            }
        }
</code>```

Update #2

```<code>Protected Sub books_RowDataBound(sender As Object, e As GridViewRowEventArgs)
 If e.Row.RowType = DataControlRowType.DataRow Then

  'Do this only if the textbox value is ....
  Dim btn As Button = DirectCast(sender, GridView).FindControl("button")
  btn.Enabled = False
 End If
End Sub
</code>```

Body:
You should handle this issue in the rowbound event handler of the GridView.

Update #1

protected void books_RowDataBound(object sender, GridViewRowEventArgs e) {
            if(e.Row.RowType == DataControlRowType.DataRow) {

                //Do this only if the textbox value is ....
                Button btn =  (( GridView )sender).FindControl("button");
                btn.Enabled = false;
            }
        }

Update #2

Protected Sub books_RowDataBound(sender As Object, e As GridViewRowEventArgs)
 If e.Row.RowType = DataControlRowType.DataRow Then

  'Do this only if the textbox value is ....
  Dim btn As Button = DirectCast(sender, GridView).FindControl("button")
  btn.Enabled = False
 End If
End Sub


问:
How to avoid generating intermediate files in bash script
I would like to know if it is possible to change the following script, such that "intermediate.tmp" is not generated as output:

To call the script on the command line:

```<code>./script.sh file1 file2
</code>```

script.sh:

```<code>#!/bin/bash

FILE_1=$1
FILE_2=$2

awk '{print $1,$2}' $FILE_1 > intermediate.tmp

awk 'NR==FNR {h[$1] = $0; next} {print $0,h[$1]}' intermediate.tmp $FILE_2 > output.file
</code>```

The awk scripts are not really important per se. I just want to know how to "feed" intermediate.tmp into the second awk command without generating an intermediate.tmp output file in addition to the desired output.file.

Thanks.

答:
```<code>awk 'NR==FNR {h[$1] = $1 OFS $2; next} {print $0,h[$1]}' "$FILE_1" "$FILE_2" > output.file
</code>```

or less sensibly:

```<code>awk '{print $1,$2}' "$FILE_1" |
awk 'NR==FNR {h[$1] = $0; next} {print $0,h[$1]}' - "$FILE_2" > output.file
</code>```

Body:
I would like to know if it is possible to change the following script, such that "intermediate.tmp" is not generated as output:

To call the script on the command line:

./script.sh file1 file2

script.sh:

#!/bin/bash

FILE_1=$1
FILE_2=$2

awk '{print $1,$2}' $FILE_1 > intermediate.tmp

awk 'NR==FNR {h[$1] = $0; next} {print $0,h[$1]}' intermediate.tmp $FILE_2 > output.file

The awk scripts are not really important per se. I just want to know how to "feed" intermediate.tmp into the second awk command without generating an intermediate.tmp output file in addition to the desired output.file.

Thanks.

Body:
awk 'NR==FNR {h[$1] = $1 OFS $2; next} {print $0,h[$1]}' "$FILE_1" "$FILE_2" > output.file

or less sensibly:

awk '{print $1,$2}' "$FILE_1" |
awk 'NR==FNR {h[$1] = $0; next} {print $0,h[$1]}' - "$FILE_2" > output.file


问:
Fix migrate android code error on eclipse?

I got an error while i build my app on eclipse

anyone can tell me how can i fix it ?

答:
Something wrong with your resources files

You must check if there are some mistake in your resources: images or
xml files in Drawable folder or Value or Color ( RES )

Or file in RES missing

Then clean your project


答:
You can using $.browser, yes, but it's a bad idea to use browser detection:

```<code>if($.browser.msie) { /* IE */ }
</code>```

A better option for instance would be $.support which is feature detection, like this:

```<code>if(!$.support.opacity) { /* IE 6-8 */ }
</code>```

$.support.opacity is false in browsers that don't support opacity in styling (though IE 7-8 handle transparent PNGs file, so this still isn't ideal, depending on what you're after...personally I think you'd be giving IE 7/8 users a sub-optimal experience).

What you should really do is target IE6 which doesn't support transparent PNGs (without an alpha filter), like this:

```<code><!--[if IE 6]>
  <link rel="stylesheet" type="text/css" href="IE6ImageStyles.css">
<![endif]-->
</code>```

Title: jQuery browser detection?

Body:
Is there a good way to detect if the user's browser is Internet Explorer using jQuery?

I have an issue with PNG graphics using IE and want to swap them for GIF's only if the user is viewing the site with IE.

Body:
You can using $.browser, yes, but it's a bad idea to use browser detection:

if($.browser.msie) { /* IE */ }

A better option for instance would be $.support which is feature detection, like this:

if(!$.support.opacity) { /* IE 6-8 */ }

$.support.opacity is false in browsers that don't support opacity in styling (though IE 7-8 handle transparent PNGs file, so this still isn't ideal, depending on what you're after...personally I think you'd be giving IE 7/8 users a sub-optimal experience).

What you should really do is target IE6 which doesn't support transparent PNGs (without an alpha filter), like this:

<!--[if IE 6]>
  <link rel="stylesheet" type="text/css" href="IE6ImageStyles.css">
<![endif]-->


问:
How to make a single button appear active in android
I have been learning java for a little while and am working on an android app.  I am trying to implement a boolean logic for my image buttons nested in a linear layout whereby just one button should show active button while the others are not.
For now each button can toggle between active and inactive but i don't want two ore more buttons showing active at the same time. I want a single one showing an active button at a time. </p>

```<code> public void showAudio(View view) {
        if (!audioButtonClicked) {
            audioButtonClicked = true;
            audioWindowButton.setImageResource(R.drawable.audio_active);
        } else {
            audioWindowButton.setImageResource(R.drawable.audio_inactive);
            audioButtonClicked = false;
        }

        }

    public void showEvents(View view) {
       if(!eventButtonClicked ) {
eventWindowButton.setImageResource(R.drawable.event_active);
           eventButtonClicked = true;
       } else {
           eventWindowButton.setImageResource(R.drawable.event_inactive);
           eventButtonClicked = false;
       }
    }

    public void showMore(View view) {
        if(!moreButtonClicked) {
            moreWindowButton.setImageResource(R.drawable.event_active);
            moreButtonClicked = true;

        } else {
            moreWindowButton.setImageResource(R.drawable.event_inactive);
            moreButtonClicked = false;
        }
    }
</code>```

答:
Replace your code with this:</p>

```<code>public void showAudio(View view) {

    audioWindowButton.setImageResource(R.drawable.audio_active);
    eventWindowButton.setImageResource(R.drawable.event_inactive);
    moreWindowButton.setImageResource(R.drawable.event_inactive);

}

public void showEvents(View view) {

    audioWindowButton.setImageResource(R.drawable.audio_inactive);
    eventWindowButton.setImageResource(R.drawable.event_active);
    moreWindowButton.setImageResource(R.drawable.event_inactive);

}

public void showMore(View view) {

    audioWindowButton.setImageResource(R.drawable.audio_inactive);
    eventWindowButton.setImageResource(R.drawable.event_inactive);
    moreWindowButton.setImageResource(R.drawable.event_active);

}
</code>```

Body:
I have been learning java for a little while and am working on an android app.  I am trying to implement a boolean logic for my image buttons nested in a linear layout whereby just one button should show active button while the others are not.
For now each button can toggle between active and inactive but i don't want two ore more buttons showing active at the same time. I want a single one showing an active button at a time.

 public void showAudio(View view) {
        if (!audioButtonClicked) {
            audioButtonClicked = true;
            audioWindowButton.setImageResource(R.drawable.audio_active);
        } else {
            audioWindowButton.setImageResource(R.drawable.audio_inactive);
            audioButtonClicked = false;
        }

        }

    public void showEvents(View view) {
       if(!eventButtonClicked ) {
eventWindowButton.setImageResource(R.drawable.event_active);
           eventButtonClicked = true;
       } else {
           eventWindowButton.setImageResource(R.drawable.event_inactive);
           eventButtonClicked = false;
       }
    }

    public void showMore(View view) {
        if(!moreButtonClicked) {
            moreWindowButton.setImageResource(R.drawable.event_active);
            moreButtonClicked = true;

        } else {
            moreWindowButton.setImageResource(R.drawable.event_inactive);
            moreButtonClicked = false;
        }
    }

Body:
Replace your code with this:

public void showAudio(View view) {

    audioWindowButton.setImageResource(R.drawable.audio_active);
    eventWindowButton.setImageResource(R.drawable.event_inactive);
    moreWindowButton.setImageResource(R.drawable.event_inactive);

}

public void showEvents(View view) {

    audioWindowButton.setImageResource(R.drawable.audio_inactive);
    eventWindowButton.setImageResource(R.drawable.event_active);
    moreWindowButton.setImageResource(R.drawable.event_inactive);

}

public void showMore(View view) {

    audioWindowButton.setImageResource(R.drawable.audio_inactive);
    eventWindowButton.setImageResource(R.drawable.event_inactive);
    moreWindowButton.setImageResource(R.drawable.event_active);

}


问:
Why isn't my try except catching if you put a string into the argument of score?
```<code>#Write a program to prompt for a score between 0.0 and 1.0.
#If the score is out of range print an error.
#If the score is between 0.0 and 1.0, print a grade using the following table:
#Score Grade >=0.9 A >=0.8 B >=0.7 C >=0.6 D <0.6 F

def computegrade(score):
    try:
        score1 = float(score)
        if score1 <= 1.0 and score1 >= 0.9:
            grade = "A"
        elif score1 < 0.9 and score1 >= 0.8:
            grade = "B"
        elif score1 < 0.8 and score1 >= 0.7:
            grade = "C"
        elif score1 < 0.7 and score1 >= 0.6:
            grade = "D"
        elif score1 < 0.6 and score1 > 0:
            grade = "F"
        else:
            grade = "ERROR: You did not enter a number or you entered a number out of the range of 0.0 and 1.0!"
        print(grade)
    except:
        print("ERROR: You did not enter a number or you entered a number out of the range of 0.0 and 1.0!")
</code>```

Everything seems to work as expected whether I enter an integer outside the range of 0.0 and 1.0 or enter within that range.  I created a try except to catch if the user inputs a string for score.  But it doesn't seem to catch it and I can't figure out why.

答:
I tried this and it worked fine. Make sure the input is a string that can't be converted to float and you should be fine.

```<code>def computegrade(score):
    try:
        score1 = float(score)
        if score1 <= 1.0 and score1 >= 0.9:
            grade = "A"
        elif score1 < 0.9 and score1 >= 0.8:
            grade = "B"
        elif score1 < 0.8 and score1 >= 0.7:
            grade = "C"
        elif score1 < 0.7 and score1 >= 0.6:
            grade = "D"
        elif score1 < 0.6 and score1 > 0:
            grade = "F"
        else:
            grade = "ERROR: You did not enter a number or you entered a     number out of the range of 0.0 and 1.0!"
        print(grade)
    except:
        print("ERROR: You did not enter a number or you entered a number out of the range of 0.0 and 1.0!")
computegrade("fire")
</code>```

Output:

```<code>ERROR: You did not enter a number or you entered a number out of the range of 0.0 and 1.0!
</code>```

Body:
#Write a program to prompt for a score between 0.0 and 1.0.
#If the score is out of range print an error.
#If the score is between 0.0 and 1.0, print a grade using the following table:
#Score Grade >=0.9 A >=0.8 B >=0.7 C >=0.6 D <0.6 F

def computegrade(score):
    try:
        score1 = float(score)
        if score1 <= 1.0 and score1 >= 0.9:
            grade = "A"
        elif score1 < 0.9 and score1 >= 0.8:
            grade = "B"
        elif score1 < 0.8 and score1 >= 0.7:
            grade = "C"
        elif score1 < 0.7 and score1 >= 0.6:
            grade = "D"
        elif score1 < 0.6 and score1 > 0:
            grade = "F"
        else:
            grade = "ERROR: You did not enter a number or you entered a number out of the range of 0.0 and 1.0!"
        print(grade)
    except:
        print("ERROR: You did not enter a number or you entered a number out of the range of 0.0 and 1.0!")

Everything seems to work as expected whether I enter an integer outside the range of 0.0 and 1.0 or enter within that range.  I created a try except to catch if the user inputs a string for score.  But it doesn't seem to catch it and I can't figure out why.

Body:
I tried this and it worked fine. Make sure the input is a string that can't be converted to float and you should be fine.

def computegrade(score):
    try:
        score1 = float(score)
        if score1 <= 1.0 and score1 >= 0.9:
            grade = "A"
        elif score1 < 0.9 and score1 >= 0.8:
            grade = "B"
        elif score1 < 0.8 and score1 >= 0.7:
            grade = "C"
        elif score1 < 0.7 and score1 >= 0.6:
            grade = "D"
        elif score1 < 0.6 and score1 > 0:
            grade = "F"
        else:
            grade = "ERROR: You did not enter a number or you entered a     number out of the range of 0.0 and 1.0!"
        print(grade)
    except:
        print("ERROR: You did not enter a number or you entered a number out of the range of 0.0 and 1.0!")
computegrade("fire")

Output:

ERROR: You did not enter a number or you entered a number out of the range of 0.0 and 1.0!


问:
Change style of parent element using ng-if directive in child element
I am new to angular js. Depending on the conditions, I change the background of the cells. But I'll be more than just happy if I can to change the background of the entire line.

Here is an example of the code:

```<code><table>
    <thead>
        <tr>
            <td>
                Status
            </td>
            <td>
                Time waiting
            </td>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="item in filteredAgentsDetailedArr">
            <td ng-if="item.name == 'Not Logged'">
                {{ item.name }}
            </td>
            <td ng-if="item.name == 'In Call'"
                ng-style="{backgroundColor: 'green'}">
                {{ item.name }}
            </td>
            <td ng-if="item.name == 'Waiting'"
                ng-style="{backgroundColor: 'red'}">
                {{ item.name }}
            </td>

           <td ng-if="item.time_waiting[6] < 3 && item.time_waiting[4] == 0"
               ng-style="{backgroundColor: 'yellow'}">
               {{ item.time_waiting }}
           </td>
           <td ng-if="item.time_waiting[6] >= 3 && item.time_waiting[4] < 2 ||
                      item.time_waiting[4] == 1 && item.time_waiting[3] == 0"
               ng-style="{backgroundColor: 'gold'}">
               {{ item.time_waiting }}
           <td>
       </tr>
    </tbody>
</table>
</code>```

That is, everything works. But I'd like to add a style(or maybe ng-class) to the entire string and not to one cell. Maybe someone knows how this can be implemented using the ng-if directive?

Thank you in advance!)

答:
Try this:

Your html

```<code><table>
<thead>
    <tr>
        <td>
            Status
        </td>
        <td>
            Time waiting
        </td>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="item in filteredAgentsDetailedArr"
        ng-class="{ 'incall' : item.name == 'In Call', 'waiting' : item.name == 'Waiting'}">
        <td ng-if="item.name == 'Not Logged'">
            {{ item.name }}
        </td>
        <td ng-if="item.name == 'In Call'">
            {{ item.name }}
        </td>
        <td ng-if="item.name == 'Waiting'">
            {{ item.name }}
        </td>

       <td >
         <span ng-if="item.time_waiting[6] < 3 && item.time_waiting[4] == 0"
               ng-style="{backgroundColor: 'yellow'}">
           {{ item.time_waiting }}
         </span>
       </td>
   </tr>
</tbody>
</code>```

On your css

```<code>table {
  border-collapse:collapse;
}

.incall {
  background-color: green;
}

.waiting {
  background-color: red;
}
</code>```

Body:
I am new to angular js. Depending on the conditions, I change the background of the cells. But I'll be more than just happy if I can to change the background of the entire line.

Here is an example of the code:

                Status

                Time waiting

                {{ item.name }}

                {{ item.name }}

                {{ item.name }}

           <td ng-if="item.time_waiting[6] < 3 && item.time_waiting[4] == 0"
               ng-style="{backgroundColor: 'yellow'}">
               {{ item.time_waiting }}

           = 3 && item.time_waiting[4] < 2 ||
                      item.time_waiting[4] == 1 && item.time_waiting[3] == 0"
               ng-style="{backgroundColor: 'gold'}">
               {{ item.time_waiting }}

That is, everything works. But I'd like to add a style(or maybe ng-class) to the entire string and not to one cell. Maybe someone knows how this can be implemented using the ng-if directive?

Thank you in advance!)

Body:
Try this:

Your html

<table>
<thead>
    <tr>
        <td>
            Status
        </td>
        <td>
            Time waiting
        </td>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="item in filteredAgentsDetailedArr"
        ng-class="{ 'incall' : item.name == 'In Call', 'waiting' : item.name == 'Waiting'}">
        <td ng-if="item.name == 'Not Logged'">
            {{ item.name }}
        </td>
        <td ng-if="item.name == 'In Call'">
            {{ item.name }}
        </td>
        <td ng-if="item.name == 'Waiting'">
            {{ item.name }}
        </td>

       <td >
         <span ng-if="item.time_waiting[6] < 3 && item.time_waiting[4] == 0"
               ng-style="{backgroundColor: 'yellow'}">
           {{ item.time_waiting }}
         </span>
       </td>
   </tr>
</tbody>

On your css

table {
  border-collapse:collapse;
}

.incall {
  background-color: green;
}

.waiting {
  background-color: red;
}


问:
How to consume Chatbot Analytics?
We want to somehow consume a Chatbot Analytics so we can create our Own Analytics site for our Clients.

Is that any Possible?
Are there Any tools that will help?
We don't want tools, we want to consume their Data and Present them in our own site on behalf of our Clients.

Conside creating Chatbot via Chatfuel, API.ai or something.

答:
You can use chatbotproxy.com API to fetch app and page specific metrics.

Currently, it collects 10 metrics, Note: if there is no data; then API does not return 0, it skips keys with 0 count. ChatbotProxy Metrics

Title: How to consume Chatbot Analytics?


问:
How to get a HTML element by text using XPath?
I'm encoutered a problem that is could not get a HTML element by element's text.My HTML looks like:

```<code>...
<table>
  ...
  <tr>
    ...
    <td class="oMain">test value</td>
    ...
  <tr>
  ...
</table>
...
</code>```

For some special reasons,I have to get the '' element using it's text 'test value'. I tried '//tr[td='test value']/td' but no result.How can i write the XPath expression?

Any help is welcome.Thanks!

答:
Your XPath expression seems to be correct. Do you have a default namespace (e.g. XHTML) in your html? If so, you can modify your XPath like this:

```<code>//*[local-name()='td' and text()='test value']
</code>```

If you can figure out how to use namespaces, you could also do

```<code>//xhtml:tr[xhtml:td='test value']/xhtml:td
</code>```

Does that help?

Body:
I'm encoutered a problem that is could not get a HTML element by element's text.My HTML looks like:

...

  ...

    ...
    test value
    ...

  ...

...

For some special reasons,I have to get the '' element using it's text 'test value'. I tried '//tr[td='test value']/td' but no result.How can i write the XPath expression?

Any help is welcome.Thanks!

Body:
Your XPath expression seems to be correct. Do you have a default namespace (e.g. XHTML) in your html? If so, you can modify your XPath like this:

//*[local-name()='td' and text()='test value']

If you can figure out how to use namespaces, you could also do

//xhtml:tr[xhtml:td='test value']/xhtml:td

Does that help?


问:
serializing array when nested with other attributes in rails 5
I have a ruby (2.4.0p0) rails (5.0.2) controller from which I wish to return a json result containing a list of Thing objects as well as some high level info (such as next and previous from Kaminari paging).

Consider a Thing with an association to Owner. Thing has a owner_id attribute.

For @things = Thing.page(1).per(2) I will be able to use

render json: @things

and get;

```<code>[
    { "id": 1, "owner_id": 1, "name": "thing1" },
    { "id": 2, "owner_id": 1, "name": "thing2" }
]
</code>```

Good.  If I then create a serializer called ThingSerializer.rb and define owner such that it adds "owner":"CatInHat" instead of "owner_id":1
This works as well;

```<code>[
    { "id": 1, "owner": "CatInHat", "name": "thing1" },
    { "id": 2, "owner": "CatInHat", "name": "thing2" }
]
</code>```

This is good, but, my problem comes when I want to add higher level data and label the list as "results" such as when I try;

render json: { next:"some_url_link",previous:"some_other_url_link", results: @bags}

I'd like to get;

```<code>{ "next":some_url_link,
    "prev":some_other_url_link,
    "results":[ { "id": 1, "owner": "CatInHat", "name": "thing1" }, { "id": 2, "owner": "CatInHat", "name": "thing2" } ]
}
</code>```

What I get is nearly the above but with "owner_id":1 instead of "owner":"CatInHat" - my serializer does not seem to be used when I label and nest my list of things.  What is the appropriate way to use my serializer and get this output?

If I create config/initializers/active_model_serializers.rb and add
    ActiveModel::Serializer.config.adapter = :json_api
It gives me an api which is similar but I don't know if it can be customized to fit the spec I need above.

thank you for any help

答:
It looks like the serialization logic in render json: ... only kicks in if the attribute is an ActiveRecord object or an array of ActiveRecord objects. Since you are giving it a hash, it will not inspect the individual attributes and recursively apply the serializers.

You can try manually applying ThingSerializer:

```<code>render json: {
  next: ...,
  prev: ...,
  results: @things.map { |thing|
    ThingSerializer.new(thing).attributes
  },
}
</code>```

Body:
I have a ruby (2.4.0p0) rails (5.0.2) controller from which I wish to return a json result containing a list of Thing objects as well as some high level info (such as next and previous from Kaminari paging).

Consider a Thing with an association to Owner. Thing has a owner_id attribute.

For @things = Thing.page(1).per(2) I will be able to use

render json: @things

and get;

[
    { "id": 1, "owner_id": 1, "name": "thing1" },
    { "id": 2, "owner_id": 1, "name": "thing2" }
]

Good.  If I then create a serializer called ThingSerializer.rb and define owner such that it adds "owner":"CatInHat" instead of "owner_id":1
This works as well;

[
    { "id": 1, "owner": "CatInHat", "name": "thing1" },
    { "id": 2, "owner": "CatInHat", "name": "thing2" }
]

This is good, but, my problem comes when I want to add higher level data and label the list as "results" such as when I try;

render json: { next:"some_url_link",previous:"some_other_url_link", results: @bags}

I'd like to get;

{ "next":some_url_link,
    "prev":some_other_url_link,
    "results":[ { "id": 1, "owner": "CatInHat", "name": "thing1" }, { "id": 2, "owner": "CatInHat", "name": "thing2" } ]
}

What I get is nearly the above but with "owner_id":1 instead of "owner":"CatInHat" - my serializer does not seem to be used when I label and nest my list of things.  What is the appropriate way to use my serializer and get this output?

If I create config/initializers/active_model_serializers.rb and add
    ActiveModel::Serializer.config.adapter = :json_api
It gives me an api which is similar but I don't know if it can be customized to fit the spec I need above.

thank you for any help

Body:
It looks like the serialization logic in render json: ... only kicks in if the attribute is an ActiveRecord object or an array of ActiveRecord objects. Since you are giving it a hash, it will not inspect the individual attributes and recursively apply the serializers.

You can try manually applying ThingSerializer:

render json: {
  next: ...,
  prev: ...,
  results: @things.map { |thing|
    ThingSerializer.new(thing).attributes
  },
}


问:
Use geom_ribbon (ggplot2) to plot difference between two time series with changing colors
I'm trying to visualize netexports (exports - imports) by plotting both exports and imports and coloring the difference between the two series depending on whether netexports are positive or negative.

Using R:

```<code>library(tidyverse)

data <- tribble(
  ~year, ~exports, ~imports,
  #--|--|----
  2003, 3, 3.6,
  2004, 4, 8.5,
  2005, 7, 7,
  2006, 9, 7,
  2007, 15, 9,
  2008, 17, 12,
  2009, 7, 8,
  2010, 8, 7,
  2011, 8, 8,
  2012, 7, 9,
  2013, 2, 11,
  2014, 9, 13,
  2015, 5, 15
)

ggplot(data, aes(x = year)) +
  geom_ribbon(aes(ymin = imports, ymax = exports))
</code>```

This gets me:

Which already colors in the differences between the series, but doesn't tell me which one is higher.

Next I've tried:

```<code>ggplot(data, aes(x = year)) +
  geom_ribbon(aes(ymin = imports, ymax = exports, fill = exports > imports))
</code>```

Which yields:

But there seems to be something wrong here and I'm not sure what it is.

答:
This gets closer, though it still fails where you don't have a row at the point where the values are equal. Depending on your needs, you could calculate the point between 2008 and 2009 where they cross, and artificially add it to your dataset. </p>

```<code>data$minval <- pmin(data$imports, data$exports)

ggplot(data, aes(x = year)) +
  geom_ribbon(aes(ymin = minval, ymax = exports), fill = "blue") +
  geom_ribbon(aes(ymin = minval, ymax = imports), fill = "red")
</code>```

Body:
I'm trying to visualize netexports (exports - imports) by plotting both exports and imports and coloring the difference between the two series depending on whether netexports are positive or negative.

Using R:

library(tidyverse)

data <- tribble(
  ~year, ~exports, ~imports,
  #--|--|----
  2003, 3, 3.6,
  2004, 4, 8.5,
  2005, 7, 7,
  2006, 9, 7,
  2007, 15, 9,
  2008, 17, 12,
  2009, 7, 8,
  2010, 8, 7,
  2011, 8, 8,
  2012, 7, 9,
  2013, 2, 11,
  2014, 9, 13,
  2015, 5, 15
)

ggplot(data, aes(x = year)) +
  geom_ribbon(aes(ymin = imports, ymax = exports))

This gets me:

Which already colors in the differences between the series, but doesn't tell me which one is higher.

Next I've tried:

ggplot(data, aes(x = year)) +
  geom_ribbon(aes(ymin = imports, ymax = exports, fill = exports > imports))

Which yields:

But there seems to be something wrong here and I'm not sure what it is.

Body:
This gets closer, though it still fails where you don't have a row at the point where the values are equal. Depending on your needs, you could calculate the point between 2008 and 2009 where they cross, and artificially add it to your dataset.

data$minval <- pmin(data$imports, data$exports)

ggplot(data, aes(x = year)) +
  geom_ribbon(aes(ymin = minval, ymax = exports), fill = "blue") +
  geom_ribbon(aes(ymin = minval, ymax = imports), fill = "red")


问:
Python dictionary values
Hi I am just starting to learn how to program and have a function that I need to write in Python, this is the idea behind it:

It returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList.

There is a function to call that checks the frequency of the letters in the word the user comes up with and that is a converted to a dict, I have tried using iteritems various ways but to no avail, I am getting stuck on the words that have repeated letters, they are being returned as true when I don't have two entries for that letter in the users hand.

Sorry if this is unclear I only started two weeks ago.
any pointers would be great I have been stuck on this for a long time!

```<code>def isValidWord(hand,word,wordList):

    """
    Returns True if word is in the wordList and is entirely

    composed of letters in the hand. Otherwise, returns False.

    Does not mutate hand or wordList.

    word: string
    hand: dictionary (string -> int)
    wordList: list of lowercase strings
    """

    wordC = getFrequencyDict(word)
    handC = dict.copy(hand)
    if word not in wordList:
        return False
    for c in word:
        if c not in hand:
            return False
        for k,v in wordC.iteritems():
            if k in hand and v > 1:
                 handC[k] -= 1
</code>```

basically my next step was trying to figure out how to compare word to handC with amended value and discounting any key with a value of zero.
I think(hope) that will work.

答:
here is mine</p>

```<code>def isValidWord(word, hand, wordList):
    """
    Returns True if word is in the wordList and is entirely
    composed of letters in the hand. Otherwise, returns False.

    Does not mutate hand or wordList.

    word: string
    hand: dictionary (string -> int)
    wordList: list of lowercase strings
    """
    if word in wordList:
        if set(word).issubset(set(hand)):
            return True
        else:
            return False
    else:
        return False
</code>```

Title: Python dictionary values

Body:
Hi I am just starting to learn how to program and have a function that I need to write in Python, this is the idea behind it:

It returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList.

There is a function to call that checks the frequency of the letters in the word the user comes up with and that is a converted to a dict, I have tried using iteritems various ways but to no avail, I am getting stuck on the words that have repeated letters, they are being returned as true when I don't have two entries for that letter in the users hand.

Sorry if this is unclear I only started two weeks ago.
any pointers would be great I have been stuck on this for a long time!

def isValidWord(hand,word,wordList):

    """
    Returns True if word is in the wordList and is entirely

    composed of letters in the hand. Otherwise, returns False.

    Does not mutate hand or wordList.

    word: string
    hand: dictionary (string -> int)
    wordList: list of lowercase strings
    """

    wordC = getFrequencyDict(word)
    handC = dict.copy(hand)
    if word not in wordList:
        return False
    for c in word:
        if c not in hand:
            return False
        for k,v in wordC.iteritems():
            if k in hand and v > 1:
                 handC[k] -= 1

basically my next step was trying to figure out how to compare word to handC with amended value and discounting any key with a value of zero.
I think(hope) that will work.

Body:
here is mine

def isValidWord(word, hand, wordList):
    """
    Returns True if word is in the wordList and is entirely
    composed of letters in the hand. Otherwise, returns False.

    Does not mutate hand or wordList.

    word: string
    hand: dictionary (string -> int)
    wordList: list of lowercase strings
    """
    if word in wordList:
        if set(word).issubset(set(hand)):
            return True
        else:
            return False
    else:
        return False


问:
Asymptotically optimal algorithm to compute if a line intersects a convex polygon
An O(n) algorithm to detect if a line intersects a convex polygon consists in checking if any edge of the polygon intersects the line, and look if the number of intersections is odd or even.

Is there an asymptotically faster algorithm, e.g. an O(log n) one?

答:
Bounding boxes may prove useful.

Recall that a convex part of an affine space is the intersection of all its envelope hyperplanes: you could get an approximation of your polygon (read a "bounding convex polygon") by considering only the intersection of a subset of the envelope hyperplanes, test for intersection of your line with this approximation, and refine if necessary.

All this works better if you expect a low number of intersections.


问:
Parse nested XML using XDocument
I have an xml of the below format. There are 2 parts of xml (job_type = "REQUESTED" and job_type = "RECOMMENDED"); I want to parse only the values from the Requested block.
Also in the Applicants tag there are two types of Application (type = "PB" and type = "CB")

I want to parse the result into a csv in the below format

```<code>id , social_security_number (where type = "PB"), first_name(where type = "PB"), city(where type = "PB" and item_code="CURRENT"), state_code_id(where type = "PB" and item_code="CURRENT"), com(where item_code="PEMAIL" and type ="PB"), social_security_number (where type = "CB"), first_name(where type = "CB"), city(where type = "CB" and item_code="CURRENT"), state_code_id(where type = "CB" and item_code="CURRENT"), com(where item_code="PEMAIL" and type ="CB")
</code>```

Eg Result :

```<code>2407132 ,999999999, Thomas, Portland, MI, edison@gmail.com, 123456789, Mary, BarHarBor, MI, mary@gmail.com

<?xml version="1.0" encoding="utf-8"?>
<JobApplications xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="2407132" bundle_id="2407132" version="1.0">
<JobApplication job_type="REQUESTED" request_date="2014-08-02T12:26:00.0000000">
<JobApplicationStates>
<JobApplicationState type="USEDCL" payment_call_flag="False">
<Applicants>
<Applicant social_security_number="999999999" type="PB" date_of_birth="1972-10-01T00:00:00.0000000" first_name="Thomas" last_name="Edison">
<Addresses>
<Address city="Portland" state_code_id="MI" country_code="USA" postal_code="12345" item_code="CURRENT" street_number="6297" street="LAKE ARBOR" />
<Address item_code="PREVIOUS" />
</Addresses>
<Communications>
<Communication item_code="PEMAIL" com="edison@gmail.com" contact_type="CU"/>
<Communication item_code="HOME" com="(123)-456-7890" contact_type="CU"/>
<Communication item_code="OTHER" contact_type="CU"/>
<Communication item_code="WORK" com="(100)-200-3000" contact_type="CU"/>
</Communications>
</Applicant>
<Applicant social_security_number="123456789" type="CB" date_of_birth="1976-10-01T00:00:00.0000000" first_name="Mary" last_name="Edison">
<Addresses>
<Address city="BarHarBor" state_code_id="MI" country_code="USA" postal_code="12345" item_code="CURRENT" street_number="6297" street="LAKE ARBOR" />
<Address item_code="PREVIOUS" />
</Addresses>
<Communications>
<Communication item_code="PEMAIL" com="mary@gmail.com" contact_type="CU"/>
<Communication item_code="HOME" com="(999)-456-7890" contact_type="CU"/>
<Communication item_code="OTHER" contact_type="CU"/>
<Communication item_code="WORK" com="(300)-200-3000" contact_type="CU"/>
</Communications>
</Applicant>
</Applicants>
</JobApplicationState>
</JobApplicationStates>
</JobApplication>
<JobApplication job_type="RECOMMENDED" request_date="2014-08-02T12:26:00.0000000">
<JobApplicationStates>
<JobApplicationState type="USEDCL" payment_call_flag="False">
<Applicants>
<Applicant social_security_number="999999999" type="PB" date_of_birth="1972-10-01T00:00:00.0000000" first_name="Thomas" last_name="Edison">
<Addresses>
<Address city="Portland" state_code_id="MI" country_code="USA" postal_code="12345" item_code="CURRENT" street_number="6297" street="LAKE ARBOR" />
<Address item_code="PREVIOUS" />
</Addresses>
<Communications>
<Communication item_code="PEMAIL" com="edison@gmail.com" contact_type="CU"/>
<Communication item_code="HOME" com="(123)-456-7890" contact_type="CU"/>
<Communication item_code="OTHER" contact_type="CU"/>
<Communication item_code="WORK" com="(100)-200-3000" contact_type="CU"/>
</Communications>
</Applicant>
<Applicant social_security_number="123456789" type="CB" date_of_birth="1976-10-01T00:00:00.0000000" first_name="Mary" last_name="Edison">
<Addresses>
<Address city="BarHarBor" state_code_id="MI" country_code="USA" postal_code="12345" item_code="CURRENT" street_number="6297" street="LAKE ARBOR" />
<Address item_code="PREVIOUS" />
</Addresses>
<Communications>
<Communication item_code="PEMAIL" com="mary@gmail.com" contact_type="CU"/>
<Communication item_code="HOME" com="(999)-456-7890" contact_type="CU"/>
<Communication item_code="OTHER" contact_type="CU"/>
<Communication item_code="WORK" com="(300)-200-3000" contact_type="CU"/>
</Communications>
</Applicant>
</Applicants>
</JobApplicationState>
</JobApplicationStates>
</JobApplication>
</code>```

Any pointers how to parse in the required format using XDocument ? I have millions of xmls to parse.

答:
Yo can often flatten xml file out so it is easier to put into a database and read.  In your case I think this is best method.  See code below.  I did not think it is a good idea to complicate the parsing method by only parsing certain items when the datatable result can be filtered after the parsing is completed.</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            DataTable dt = new DataTable();

            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Job Type", typeof(string));
            dt.Columns.Add("Request Date", typeof(DateTime));
            dt.Columns.Add("Job State Type",typeof(string));
            dt.Columns.Add("Payment Call Flag", typeof(Boolean));
            dt.Columns.Add("SSN", typeof(string));
            dt.Columns.Add("Appliacant Type", typeof(string));
            dt.Columns.Add("DOB", typeof(DateTime));
            dt.Columns.Add("First Name", typeof(string));
            dt.Columns.Add("Last Name", typeof(string));

            dt.Columns.Add("City", typeof(string));
            dt.Columns.Add("State", typeof(string));
            dt.Columns.Add("Country", typeof(string));
            dt.Columns.Add("Postal Code", typeof(string));
            dt.Columns.Add("Street Number", typeof(string));
            dt.Columns.Add("Street", typeof(string));
            dt.Columns.Add("Email", typeof(string));
            dt.Columns.Add("Home Phone", typeof(string));
            dt.Columns.Add("Other", typeof(string));
            dt.Columns.Add("Work Phone", typeof(string));

            XDocument doc = XDocument.Load(FILENAME);

            XElement jobApplications = doc.Root;
            int id = (int)jobApplications.Attribute("id");

            foreach (XElement jobApplication in jobApplications.Elements("JobApplication"))
            {
                string job_type = (string)jobApplication.Attribute("job_type");
                DateTime request_date = (DateTime)jobApplication.Attribute("request_date");
                string job_state_type = (string)jobApplication.Descendants("JobApplicationState").FirstOrDefault().Attribute("type");
                Boolean payment_call_flag = (Boolean)jobApplication.Descendants("JobApplicationState").FirstOrDefault().Attribute("payment_call_flag");

                foreach (XElement applicant in jobApplication.Descendants("Applicant"))
                {
                    string social_security_number = (string)applicant.Attribute("social_security_number");
                    string applicant_type = (string)applicant.Attribute("type");
                    DateTime date_of_birth = (DateTime)applicant.Attribute("date_of_birth");
                    string first_name = (string)applicant.Attribute("first_name");
                    string last_name = (string)applicant.Attribute("last_name");

                    XElement address = applicant.Descendants("Address").Where(x => (string)x.Attribute("item_code") == "CURRENT").FirstOrDefault();
                    string city = (string)address.Attribute("city");
                    string state = (string)address.Attribute("state_code_id");
                    string country = (string)address.Attribute("country_code");
                    string postal_code = (string)address.Attribute("postal_code");
                    string street_number = (string)address.Attribute("street_number");
                    string street = (string)address.Attribute("street");

                    XElement communications = applicant.Descendants("Communications").FirstOrDefault();
                    string email = communications.Elements().Where(x => (string)x.Attribute("item_code") == "PEMAIL").Select(x => (string)x.Attribute("com")).FirstOrDefault();
                    string home_phone = communications.Elements().Where(x => (string)x.Attribute("item_code") == "HOME").Select(x => (string)x.Attribute("com")).FirstOrDefault();
                    string other = communications.Elements().Where(x => (string)x.Attribute("item_code") == "OTHER").Select(x => (string)x.Attribute("com")).FirstOrDefault();
                    string work_phone = communications.Elements().Where(x => (string)x.Attribute("item_code") == "WORK").Select(x => (string)x.Attribute("com")).FirstOrDefault();

                    dt.Rows.Add(new object[] {
                        id,
                        job_type, request_date, job_state_type, payment_call_flag,
                        social_security_number, applicant_type, date_of_birth, first_name, last_name,
                        city, state, country, postal_code, street_number, street,
                        email, home_phone, other, work_phone
                    });
                }
            }

        }
    }
}
</code>```

Title: Parse nested XML using XDocument

Body:
I have an xml of the below format. There are 2 parts of xml (job_type = "REQUESTED" and job_type = "RECOMMENDED"); I want to parse only the values from the Requested block.
Also in the Applicants tag there are two types of Application (type = "PB" and type = "CB")

I want to parse the result into a csv in the below format

id , social_security_number (where type = "PB"), first_name(where type = "PB"), city(where type = "PB" and item_code="CURRENT"), state_code_id(where type = "PB" and item_code="CURRENT"), com(where item_code="PEMAIL" and type ="PB"), social_security_number (where type = "CB"), first_name(where type = "CB"), city(where type = "CB" and item_code="CURRENT"), state_code_id(where type = "CB" and item_code="CURRENT"), com(where item_code="PEMAIL" and type ="CB")

Eg Result :

2407132 ,999999999, Thomas, Portland, MI, edison@gmail.com, 123456789, Mary, BarHarBor, MI, mary@gmail.com

<?xml version="1.0" encoding="utf-8"?>
<JobApplications xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="2407132" bundle_id="2407132" version="1.0">
<JobApplication job_type="REQUESTED" request_date="2014-08-02T12:26:00.0000000">
<JobApplicationStates>
<JobApplicationState type="USEDCL" payment_call_flag="False">
<Applicants>
<Applicant social_security_number="999999999" type="PB" date_of_birth="1972-10-01T00:00:00.0000000" first_name="Thomas" last_name="Edison">
<Addresses>
<Address city="Portland" state_code_id="MI" country_code="USA" postal_code="12345" item_code="CURRENT" street_number="6297" street="LAKE ARBOR" />
<Address item_code="PREVIOUS" />
</Addresses>
<Communications>
<Communication item_code="PEMAIL" com="edison@gmail.com" contact_type="CU"/>
<Communication item_code="HOME" com="(123)-456-7890" contact_type="CU"/>
<Communication item_code="OTHER" contact_type="CU"/>
<Communication item_code="WORK" com="(100)-200-3000" contact_type="CU"/>
</Communications>
</Applicant>
<Applicant social_security_number="123456789" type="CB" date_of_birth="1976-10-01T00:00:00.0000000" first_name="Mary" last_name="Edison">
<Addresses>
<Address city="BarHarBor" state_code_id="MI" country_code="USA" postal_code="12345" item_code="CURRENT" street_number="6297" street="LAKE ARBOR" />
<Address item_code="PREVIOUS" />
</Addresses>
<Communications>
<Communication item_code="PEMAIL" com="mary@gmail.com" contact_type="CU"/>
<Communication item_code="HOME" com="(999)-456-7890" contact_type="CU"/>
<Communication item_code="OTHER" contact_type="CU"/>
<Communication item_code="WORK" com="(300)-200-3000" contact_type="CU"/>
</Communications>
</Applicant>
</Applicants>
</JobApplicationState>
</JobApplicationStates>
</JobApplication>
<JobApplication job_type="RECOMMENDED" request_date="2014-08-02T12:26:00.0000000">
<JobApplicationStates>
<JobApplicationState type="USEDCL" payment_call_flag="False">
<Applicants>
<Applicant social_security_number="999999999" type="PB" date_of_birth="1972-10-01T00:00:00.0000000" first_name="Thomas" last_name="Edison">
<Addresses>
<Address city="Portland" state_code_id="MI" country_code="USA" postal_code="12345" item_code="CURRENT" street_number="6297" street="LAKE ARBOR" />
<Address item_code="PREVIOUS" />
</Addresses>
<Communications>
<Communication item_code="PEMAIL" com="edison@gmail.com" contact_type="CU"/>
<Communication item_code="HOME" com="(123)-456-7890" contact_type="CU"/>
<Communication item_code="OTHER" contact_type="CU"/>
<Communication item_code="WORK" com="(100)-200-3000" contact_type="CU"/>
</Communications>
</Applicant>
<Applicant social_security_number="123456789" type="CB" date_of_birth="1976-10-01T00:00:00.0000000" first_name="Mary" last_name="Edison">
<Addresses>
<Address city="BarHarBor" state_code_id="MI" country_code="USA" postal_code="12345" item_code="CURRENT" street_number="6297" street="LAKE ARBOR" />
<Address item_code="PREVIOUS" />
</Addresses>
<Communications>
<Communication item_code="PEMAIL" com="mary@gmail.com" contact_type="CU"/>
<Communication item_code="HOME" com="(999)-456-7890" contact_type="CU"/>
<Communication item_code="OTHER" contact_type="CU"/>
<Communication item_code="WORK" com="(300)-200-3000" contact_type="CU"/>
</Communications>
</Applicant>
</Applicants>
</JobApplicationState>
</JobApplicationStates>
</JobApplication>

Any pointers how to parse in the required format using XDocument ? I have millions of xmls to parse.

Body:
Yo can often flatten xml file out so it is easier to put into a database and read.  In your case I think this is best method.  See code below.  I did not think it is a good idea to complicate the parsing method by only parsing certain items when the datatable result can be filtered after the parsing is completed.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            DataTable dt = new DataTable();

            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Job Type", typeof(string));
            dt.Columns.Add("Request Date", typeof(DateTime));
            dt.Columns.Add("Job State Type",typeof(string));
            dt.Columns.Add("Payment Call Flag", typeof(Boolean));
            dt.Columns.Add("SSN", typeof(string));
            dt.Columns.Add("Appliacant Type", typeof(string));
            dt.Columns.Add("DOB", typeof(DateTime));
            dt.Columns.Add("First Name", typeof(string));
            dt.Columns.Add("Last Name", typeof(string));

            dt.Columns.Add("City", typeof(string));
            dt.Columns.Add("State", typeof(string));
            dt.Columns.Add("Country", typeof(string));
            dt.Columns.Add("Postal Code", typeof(string));
            dt.Columns.Add("Street Number", typeof(string));
            dt.Columns.Add("Street", typeof(string));
            dt.Columns.Add("Email", typeof(string));
            dt.Columns.Add("Home Phone", typeof(string));
            dt.Columns.Add("Other", typeof(string));
            dt.Columns.Add("Work Phone", typeof(string));

            XDocument doc = XDocument.Load(FILENAME);

            XElement jobApplications = doc.Root;
            int id = (int)jobApplications.Attribute("id");

            foreach (XElement jobApplication in jobApplications.Elements("JobApplication"))
            {
                string job_type = (string)jobApplication.Attribute("job_type");
                DateTime request_date = (DateTime)jobApplication.Attribute("request_date");
                string job_state_type = (string)jobApplication.Descendants("JobApplicationState").FirstOrDefault().Attribute("type");
                Boolean payment_call_flag = (Boolean)jobApplication.Descendants("JobApplicationState").FirstOrDefault().Attribute("payment_call_flag");

                foreach (XElement applicant in jobApplication.Descendants("Applicant"))
                {
                    string social_security_number = (string)applicant.Attribute("social_security_number");
                    string applicant_type = (string)applicant.Attribute("type");
                    DateTime date_of_birth = (DateTime)applicant.Attribute("date_of_birth");
                    string first_name = (string)applicant.Attribute("first_name");
                    string last_name = (string)applicant.Attribute("last_name");

                    XElement address = applicant.Descendants("Address").Where(x => (string)x.Attribute("item_code") == "CURRENT").FirstOrDefault();
                    string city = (string)address.Attribute("city");
                    string state = (string)address.Attribute("state_code_id");
                    string country = (string)address.Attribute("country_code");
                    string postal_code = (string)address.Attribute("postal_code");
                    string street_number = (string)address.Attribute("street_number");
                    string street = (string)address.Attribute("street");

                    XElement communications = applicant.Descendants("Communications").FirstOrDefault();
                    string email = communications.Elements().Where(x => (string)x.Attribute("item_code") == "PEMAIL").Select(x => (string)x.Attribute("com")).FirstOrDefault();
                    string home_phone = communications.Elements().Where(x => (string)x.Attribute("item_code") == "HOME").Select(x => (string)x.Attribute("com")).FirstOrDefault();
                    string other = communications.Elements().Where(x => (string)x.Attribute("item_code") == "OTHER").Select(x => (string)x.Attribute("com")).FirstOrDefault();
                    string work_phone = communications.Elements().Where(x => (string)x.Attribute("item_code") == "WORK").Select(x => (string)x.Attribute("com")).FirstOrDefault();

                    dt.Rows.Add(new object[] {
                        id,
                        job_type, request_date, job_state_type, payment_call_flag,
                        social_security_number, applicant_type, date_of_birth, first_name, last_name,
                        city, state, country, postal_code, street_number, street,
                        email, home_phone, other, work_phone
                    });
                }
            }

        }
    }
}