问:
Get non matching records from School table (highlighted)

I want to get the highlighted records from table 'School' which has the subject not in Tution. Tried left join which is going wrong for some reason. Can someone help please. I am using sql server.

答:
Try that query:</p>

```<code>SELECT *
FROM TUTION
WHERE MARKS NOT IN
(SELECT MARKS FROM SCHOOL WHERE MARKS IN(90,70) AND STUDENT NOT IN('PETER',JOHN'))
</code>```

Body:
Try that query:

SELECT *
FROM TUTION
WHERE MARKS NOT IN
(SELECT MARKS FROM SCHOOL WHERE MARKS IN(90,70) AND STUDENT NOT IN('PETER',JOHN'))


来源: stackexchange

问:
ASP C# Gridview confirmation on delete and prompt user with text message
I'm using ASP C# VS 2015. I managed to generate a gridview with data from MySQL. The update and delete command appear as links and I managed to hooked them up to the events properly.

Now I would like to add a feature to add confirmation before delete plus a  message (textbox) for reason of deletion?

How do I do that in .NET?

I'm well versed in PHP and jQuery but still in learning curve in .NET.
Thanks in advance.

```<code><asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="id"
            OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
            OnRowUpdating="OnRowUpdating" EmptyDataText="No records has been added." OnRowDeleting="OnRowDeleting" OnRowDeleted="OnRowDeleted">
   <Columns>
       <asp:TemplateField HeaderText="Id" ItemStyle-Width="20">
           <ItemTemplate>
               <asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
           </ItemTemplate>
           <ItemStyle Width="20px"></ItemStyle>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Email">
           <ItemTemplate>
               <asp:Label ID="lblEmail" runat="server" Text='<%# Eval("email") %>'></asp:Label>
           </ItemTemplate>
       </asp:TemplateField>
       <asp:CommandField ShowEditButton="True" ShowDeleteButton="True" DeleteText="Reject" headertext="Controls"></asp:CommandField>
   </Columns>
</asp:GridView>
</code>```

答:
Try this</p>

```<code>protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string item = e.Row.Cells[0].Text;
        foreach (Button button in e.Row.Cells[2].Controls.OfType<Button>())
        {
            if (button.CommandName == "Delete")
            {
                button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + item + "?')){ return false; };";
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using ASP C# VS 2015. I managed to generate a gridview with data from MySQL. The update and delete command appear as links and I managed to hooked them up to the events properly.

Now I would like to add a feature to add confirmation before delete plus a  message (textbox) for reason of deletion?

How do I do that in .NET?

I'm well versed in PHP and jQuery but still in learning curve in .NET.
Thanks in advance.

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="id"
            OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
            OnRowUpdating="OnRowUpdating" EmptyDataText="No records has been added." OnRowDeleting="OnRowDeleting" OnRowDeleted="OnRowDeleted">
   <Columns>
       <asp:TemplateField HeaderText="Id" ItemStyle-Width="20">
           <ItemTemplate>
               <asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
           </ItemTemplate>
           <ItemStyle Width="20px"></ItemStyle>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Email">
           <ItemTemplate>
               <asp:Label ID="lblEmail" runat="server" Text='<%# Eval("email") %>'></asp:Label>
           </ItemTemplate>
       </asp:TemplateField>
       <asp:CommandField ShowEditButton="True" ShowDeleteButton="True" DeleteText="Reject" headertext="Controls"></asp:CommandField>
   </Columns>
</asp:GridView>

Body:
Try this

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string item = e.Row.Cells[0].Text;
        foreach (Button button in e.Row.Cells[2].Controls.OfType<Button>())
        {
            if (button.CommandName == "Delete")
            {
                button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + item + "?')){ return false; };";
            }
        }
    }
}


问:
How to router PHP error log to CloudWatch
How can I forward all php warnings and errors that typically go to the errror_log file , to go to CloudWatch ( preferably, also know which instance generated each warning)?</p>

答: If you use or switch to using Monolog, then here is a connector you can use for Monolog and CloudWatch Logs: AWS CloudWatch Logs Handler for Monolog</p>


问:
Words in a list with consecutively repeated letters
Right now I have a list of for example

```<code>data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']
</code>```

I want to remove the words with the repeated letters, in which I want to remove the words

```<code>'aa','aac','bbb','bcca','ffffff'
</code>```

Maybe import re?

答:
Loop is the way to go. Forget about sets so far as they do not work for words with repetitive letters.

Here is a method you can use to determine if word is valid in a single loop:

```<code>def is_valid(word):
    last_char = None
    for i in word:
        if i == last_char:
            return False

        last_char = i

    return True
</code>```

Example

```<code>In [28]: is_valid('dogo')
Out[28]: True

In [29]: is_valid('doo')
Out[29]: False
</code>```

Body:
Right now I have a list of for example

data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']

I want to remove the words with the repeated letters, in which I want to remove the words

'aa','aac','bbb','bcca','ffffff'

Maybe import re?

Body:
Loop is the way to go. Forget about sets so far as they do not work for words with repetitive letters.

Here is a method you can use to determine if word is valid in a single loop:

def is_valid(word):
    last_char = None
    for i in word:
        if i == last_char:
            return False

        last_char = i

    return True

Example

In [28]: is_valid('dogo')
Out[28]: True

In [29]: is_valid('doo')
Out[29]: False


问:
Elements of the layout not showing in phone auto-rotate mode
I am participating in the Udacity Android Basics degree. I am struggling with the project explained below. I am yet using only basic knowledge so please do not be surprised by the code simplicity. :)) I am eager to understand how to position elements so that they appear in every phone orientation mode using RelativeLayout.

You can find the XML here.

There are two screenshots of the app displayed in portrait and auto-rotate. The portrait looks alright but in auto-rotate half of the information displayed disappears.

My second question is related to the clickable elements. Once, I made them clickable they turned into red and underlined. Is this common or I should offset this with another statement?

This is my GitHub project.
Any help is appreciated.

Thanks,
Iva

答:
For Your First Issue of Portrait and Landscape Try to put your view contents in a scrollview so that the screen contents will be scrollable when the height of the view is more than the screen height (In Portrait and Landscape Modes)

Sample with your code

```<code><ScrollView
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="com.example.android.helloandroid.MainActivity"
android:background="#03B3E4">
  <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

       Add Your Contents Here ...

  </LinearLayout>

</ScrollView>
</code>```

For the Second question
Textviews with android:autoLink="" always takes the color from your colorAccent in styles.xml in your project if it has text that can be linked like website or mobile or map

you can change the text color by adding android:textColorLink="yourcolorhere"
to your textviews

Thanks

Body:
For Your First Issue of Portrait and Landscape Try to put your view contents in a scrollview so that the screen contents will be scrollable when the height of the view is more than the screen height (In Portrait and Landscape Modes)

Sample with your code

<ScrollView
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="com.example.android.helloandroid.MainActivity"
android:background="#03B3E4">
  <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

       Add Your Contents Here ...

  </LinearLayout>

</ScrollView>

For the Second question
Textviews with android:autoLink="" always takes the color from your colorAccent in styles.xml in your project if it has text that can be linked like website or mobile or map

you can change the text color by adding android:textColorLink="yourcolorhere"
to your textviews

Thanks


问:
With EntityFramework, how can I make two databases with the same context but one without auto-increment IDs?
I'm using EntityFramework Code-First with a context that has a model like:

```<code>public class Person {
  public int ID {get;set;}
  public string Name {get;set;}
}
</code>```

with a context like

```<code>public class DataContext: DbContext {
   public DbSet<Person> People {get;set;}
}
</code>```

And this gets saved into DatabaseA. When I insert a new person, it auto-generates an ID for that person. I need to have a DatabaseB that has the exact same structure, but without the ID auto-generation. I want to transfer some records from DatabaseA to DatabaseB but without DatabaseB generating new IDs. I know that I can wrap

```<code>[DatabaseGenerated(DatabaseGeneratedOption.None)]
</code>```

around the ID property, but I only want it to apply to DatabaseB without affecting DatabaseA.

So the only solution I've come up with so far is to have a new model

```<code>public class PersonB : Person {
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public new int ID { get; set; }
}
</code>```

and a new context

```<code>public class DataContextB : DbContext {
     public DbSet<PersonB> People {get;set;}
}
</code>```

But this is a bit of a nuisance, as I'd have to maintain two sets of fairly identical models. Ideally, I'd like to be able to do something in
using(var db = new DataContextB) {
db.
}

答:
You can override OnModelCreating function of DbContext and write some fluent api code.

Please have a look on this approach

```<code>public class DataContextB : DbContext
{
    public DbSet<Person> People {get;set;}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().Property(t => t.ID)
                    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

        base.OnModelCreating(modelBuilder);
    }
}
</code>```

Body:
I'm using EntityFramework Code-First with a context that has a model like:

public class Person {
  public int ID {get;set;}
  public string Name {get;set;}
}

with a context like

public class DataContext: DbContext {
   public DbSet<Person> People {get;set;}
}

And this gets saved into DatabaseA. When I insert a new person, it auto-generates an ID for that person. I need to have a DatabaseB that has the exact same structure, but without the ID auto-generation. I want to transfer some records from DatabaseA to DatabaseB but without DatabaseB generating new IDs. I know that I can wrap

[DatabaseGenerated(DatabaseGeneratedOption.None)]

around the ID property, but I only want it to apply to DatabaseB without affecting DatabaseA.

So the only solution I've come up with so far is to have a new model

public class PersonB : Person {
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public new int ID { get; set; }
}

and a new context

public class DataContextB : DbContext {
     public DbSet<PersonB> People {get;set;}
}

But this is a bit of a nuisance, as I'd have to maintain two sets of fairly identical models. Ideally, I'd like to be able to do something in
using(var db = new DataContextB) {
db.
}

Body:
You can override OnModelCreating function of DbContext and write some fluent api code.

Please have a look on this approach

public class DataContextB : DbContext
{
    public DbSet<Person> People {get;set;}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().Property(t => t.ID)
                    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

        base.OnModelCreating(modelBuilder);
    }
}


问:
Metatags aren't displayed when set them with angularjs
I have one problem with metatags in Angularjs.
In my html file I have metatags with content property set like this
{{ meta.siteName }}, and on every route I programmatically set these tags. Everything is fine, it sets these tags properly, but whem I'm trying to send link to some page via skype/slack etc, it shows {{ meta.siteName }} and {{ meta.description }} instead of their actual values. Sorry for my bad language.

答:
That's most likely because the Slack and Skype bots do not execute Javascript. Thus, your angular code never gets the chance to replace {{ meta.siteName }} and {{ meta.description }} in the template.

To get this to work, you either have to set them on the server side or use prerendering (for example using https://prerender.io/).

The problem also occurs with other bots that do not execute Javascript, like the Facebook and the Twitter bots. Also, it is not clear how much Javascript is executed by googlebot, so your site might have SEO problems.


问:
Printing Work Items in TFS
I am looking for a fancy way the print individual work items in TFS.
OK ... maybe not the work item directly but I need to produce printable forms based on data on a work item. And by fancy I mean: header, footer, formatting, tables maybe ... stuff like that.

No, I am not trying to print a list of work items, read carefully, I need an output based on a single work item.

For those who are wondering "Why on earth do you need that?" I should say:
We are keeping everything on TFS around here. (For now only software development stuff, but I am thinking bigger...) Sometimes somethings need to be on hard copy, to be signed for instance, and that is why I need printable forms.

答:
I came up with a solution a little interesting from my point of view.

I used the "mail merge" function of MS Word to print work items. I prepared an SQL query that reads whatever fields are needed from TFS database and set the query as a datasource for mail marge.

Now I can design a word document of any kind and use TFS fields in the document. I just select the appropriate record by work item number and voila!! my printable work item is ready.

It is a little slow when selecting a work item if you use a query that returns all work items, but who is perfect? Right ?

ContentLicense: CC BY-SA 2.5

Title: Printing Work Items in TFS


问:
Drag and Drop not working in C# Winforms Application
I am trying to create a windows form onto which I can drop a file/folder.

I have the following code in a WinForms app

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_DragEnter(object sender, DragEventArgs e)
    {
        Debug.Print("DragEnter");
    }

    private void Form1_DragDrop(object sender, DragEventArgs e)
    {
        MessageBox.Show("Dropped!");
    }
}
</code>```

I have set the AllowDrop property to true.
I've tried running the application in debug within Visual Studio.
Based on answers to other similar questions, I've tried running the compiled exe as administrator.
I've tried running the compiled exe not as administrator.

But whatever I do, I cannot get the DragDrop event to fire. The DragEnter event does fire, however. What am I missing?

答:
I also had this perplexing issue despite the form having AllowDrop set to true!

In my Windows Forms app (VS2017) I had to make sure I had set a valid Startup object: e.g myprojectname.Program and all was fine!

Body:
I am trying to create a windows form onto which I can drop a file/folder.

I have the following code in a WinForms app

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_DragEnter(object sender, DragEventArgs e)
    {
        Debug.Print("DragEnter");
    }

    private void Form1_DragDrop(object sender, DragEventArgs e)
    {
        MessageBox.Show("Dropped!");
    }
}

I have set the AllowDrop property to true.
I've tried running the application in debug within Visual Studio.
Based on answers to other similar questions, I've tried running the compiled exe as administrator.
I've tried running the compiled exe not as administrator.

But whatever I do, I cannot get the DragDrop event to fire. The DragEnter event does fire, however. What am I missing?


问:
Equal Transition
I want to have a transition that extends a div both at the top and bottom on hover. Right now it overlaps the div above and pushes away the div on the bottom.

I want to either push away on both sides or overlap on both sides. Not one of both.

#blue, #red {
  width: 100%;
  height: 100px;
  float: left;
  transition: 0.8s;
  transition-timing-function: ease-out;
  font-size: 24px;
  margin-top: 0;
  margin-bottom: 0;
}

#blue {
  background-color: blue;
}

#red {
  background-color: red;
}

#blue:hover, #red:hover {
  height: 200px;
  font-size: 48px;
  margin-top: -50px;
}
```

<p>This is what I'm working with:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#blue, #red {
  width: 100%;
  height: 50px;
  float: left;
  transition: 0.8s;
  transition-timing-function: ease-out;
  font-size: 12px;
  margin-top: 0;
  margin-bottom: 0;
}

#blue {
  background-color: blue;
}

#red {
  background-color: red;
}

#blue:hover, #red:hover {
  height: 100px;
  margin-top: -25px;
}</code>```

```

Thanks!

答:
PLease check this

#blue, #red {
    width: 100%;
    height:50px;
    float: left;
    transition: 0.8s;
    transition-timing-function: ease-out;
    font-size: 12px;
    margin-top: 0;
    margin-bottom:0;
}
#blue {
    background-color: blue;
}
#red {
    background-color: red;
}
#blue:hover, #red:hover {
    height:100px;
    padding-top:25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div id="blue"></div>
    <div id="red"></div>
    <div id="blue"></div>
    <div id="red"></div>
    <div id="blue"></div>
    <div id="red"></div>
    <div id="blue"></div></code>```

Title: Equal Transition

Body:
I want to have a transition that extends a div both at the top and bottom on hover. Right now it overlaps the div above and pushes away the div on the bottom.

I want to either push away on both sides or overlap on both sides. Not one of both.

#blue, #red {
  width: 100%;
  height: 100px;
  float: left;
  transition: 0.8s;
  transition-timing-function: ease-out;
  font-size: 24px;
  margin-top: 0;
  margin-bottom: 0;
}

#blue {
  background-color: blue;
}

#red {
  background-color: red;
}

#blue:hover, #red:hover {
  height: 200px;
  font-size: 48px;
  margin-top: -50px;
}

This is what I'm working with:

#blue, #red {
  width: 100%;
  height: 50px;
  float: left;
  transition: 0.8s;
  transition-timing-function: ease-out;
  font-size: 12px;
  margin-top: 0;
  margin-bottom: 0;
}

#blue {
  background-color: blue;
}

#red {
  background-color: red;
}

#blue:hover, #red:hover {
  height: 100px;
  margin-top: -25px;
}

Thanks!

Body:
PLease check this

#blue, #red {
    width: 100%;
    height:50px;
    float: left;
    transition: 0.8s;
    transition-timing-function: ease-out;
    font-size: 12px;
    margin-top: 0;
    margin-bottom:0;
}
#blue {
    background-color: blue;
}
#red {
    background-color: red;
}
#blue:hover, #red:hover {
    height:100px;
    padding-top:25px;
}

    <div id="blue"></div>
    <div id="red"></div>
    <div id="blue"></div>
    <div id="red"></div>
    <div id="blue"></div>
    <div id="red"></div>
    <div id="blue"></div>


问:
if else condition in shell script to check empty input by user
I am taking input from the user, and wants that if user give empty input , it should display the error message , I am trying below code , please correct me where I am wrong  .

```<code>  #!/bin/bash
    echo "please enter previous version number"
    read prevversion
    echo "please enter new version number"
    read newversion
    echo "please enter environment [DEV2/QAT2/PPE2/PRD]"
    read env

    if[["$env"=" " &&"$prevversion"=" " &&"$newversion"= " "]]
    then
        echo "Please enter the details and try again"

    else

        if [ "$env" = "QAT2" ]
        then
                prevversion="$prevversion"_QAT2
                echo "previous version is $prevversion"
                newversion="$newversion"_QAT2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PPE2" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PRD" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "DEV2" ]
        then
                prevversion="$prevversion"_DEV2
                echo "previous version is $prevversion"
                newversion="$newversion"_DEV2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        fi

    fi
</code>```

please provide me with correct solution

答:
Use -z to check for an empty string, and don't repeat so much code.

```<code>#!/bin/bash
# Prompt for what should be command line arguments.  If
# the script is going to be used in a batch environment to read
# from a stream, then prompting is unhelpful.  If it is used
# in an interactive environment, it is easier to pass this
# data on the command line.
echo "please enter previous version number"
read prevversion
echo "please enter new version number"
read newversion
echo "please enter environment [DEV2/QAT2/PPE2/PRD]"
read env

if test -z "$env" || test -z "$prevversion" || test -z "$newversion"; then
        echo "Please enter the details and try again" >&2
        exit 1
fi

case "$env" in
QAT2)
        prevversion="$prevversion"_QAT2
        newversion="$newversion"_QAT2
;;
PPE2)
        prevversion="$prevversion"
        newversion="$newversion"
;;
PRD)
        prevversion="$prevversion"
        newversion="$newversion"
;;
DEV2)
        prevversion="$prevversion"_DEV2
        newversion="$newversion"_DEV2
;;
esac
echo "previous version is $prevversion"
echo "new version is $newversion"
echo "enviornment is $env"
</code>```

Body:
I am taking input from the user, and wants that if user give empty input , it should display the error message , I am trying below code , please correct me where I am wrong  .

  #!/bin/bash
    echo "please enter previous version number"
    read prevversion
    echo "please enter new version number"
    read newversion
    echo "please enter environment [DEV2/QAT2/PPE2/PRD]"
    read env

    if[["$env"=" " &&"$prevversion"=" " &&"$newversion"= " "]]
    then
        echo "Please enter the details and try again"

    else

        if [ "$env" = "QAT2" ]
        then
                prevversion="$prevversion"_QAT2
                echo "previous version is $prevversion"
                newversion="$newversion"_QAT2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PPE2" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PRD" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "DEV2" ]
        then
                prevversion="$prevversion"_DEV2
                echo "previous version is $prevversion"
                newversion="$newversion"_DEV2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        fi

    fi

please provide me with correct solution

Body:
Use -z to check for an empty string, and don't repeat so much code.

#!/bin/bash
# Prompt for what should be command line arguments.  If
# the script is going to be used in a batch environment to read
# from a stream, then prompting is unhelpful.  If it is used
# in an interactive environment, it is easier to pass this
# data on the command line.
echo "please enter previous version number"
read prevversion
echo "please enter new version number"
read newversion
echo "please enter environment [DEV2/QAT2/PPE2/PRD]"
read env

if test -z "$env" || test -z "$prevversion" || test -z "$newversion"; then
        echo "Please enter the details and try again" >&2
        exit 1
fi

case "$env" in
QAT2)
        prevversion="$prevversion"_QAT2
        newversion="$newversion"_QAT2
;;
PPE2)
        prevversion="$prevversion"
        newversion="$newversion"
;;
PRD)
        prevversion="$prevversion"
        newversion="$newversion"
;;
DEV2)
        prevversion="$prevversion"_DEV2
        newversion="$newversion"_DEV2
;;
esac
echo "previous version is $prevversion"
echo "new version is $newversion"
echo "enviornment is $env"


问:
drive pdf app shows download option even file is downloaded
My android app downloads pdf file from web service via get method and url is https. After downloading it sends the file to drive pdf app to open the file. Drive app opens the file correctly but there is something weird. On top right menu there is a download option. When I click it drive app try to download the file and file gets broken. Never open it again. Drive app says: "invalid type". Why drive pdf app shows download option even the file is downloaded? Is there a way to hide it?

Edit: My piece of code that opens drive app is;

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri contentUri = FileProvider.getUriForFile(context,
                context.getApplicationContext().getPackageName() + ".provider", file);
        intent.setDataAndType(contentUri, "application/pdf");
    } else {
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        intent.setDataAndType(uri, "application/pdf");
    }
</code>```

答:
If this pdf you are downloading via GET method I am assuming is not from drive. You are firing an intent to open that pdf via drive. The pdf opened on your drive viewer is not uploaded(exists) on your drive. Now when you click the download option it shows up on notification as that pdf as downloaded which it does not(it just shows up as notification I don't know why this happens it might be a bug in drive viewer maybe). and hence when you click on the notification it shows you the error as invalid type because no such file is downloaded(it like an empty intent).

The download option shown in drive viewer is a default and will show up in every pdf you open from drive viewer.

Also, there is no way to hide that button as it is in drive app and not yours.

Also, I did the exact steps and also get the same error.

Body:
My android app downloads pdf file from web service via get method and url is https. After downloading it sends the file to drive pdf app to open the file. Drive app opens the file correctly but there is something weird. On top right menu there is a download option. When I click it drive app try to download the file and file gets broken. Never open it again. Drive app says: "invalid type". Why drive pdf app shows download option even the file is downloaded? Is there a way to hide it?

Edit: My piece of code that opens drive app is;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri contentUri = FileProvider.getUriForFile(context,
                context.getApplicationContext().getPackageName() + ".provider", file);
        intent.setDataAndType(contentUri, "application/pdf");
    } else {
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        intent.setDataAndType(uri, "application/pdf");
    }


问:
Progressbar with Paging library android
I'm looking to use the new architecture component "Paging Library" https://developer.android.com/topic/libraries/architecture/paging.html in my app where it fetches data from server and displays in a recyclerview.

The paging library is a good addition and helps to manage paginating the content. I've checked all the samples and they work fine. But one requirement I have is that when we scroll to the end of recyclerview and the next page starts loading (managed by the Paging Library) I need to show a progress bar row at the bottom.

I know how to do this with recyclerview scroll listeners and 2 view types. But the solution I'm seeking is how to do this with the "Paging Library". It has option to enable place holders which is not what I want.

Any help on this is highly appreciated.

答: if I right understand you use custom TiledDataSource, so from loadRange(int, int) you can send signal to UI thread about progress starting, and in your observer stop progressBar showing.

Title: Progressbar with Paging library android


问:
Get the number of lines of code in a R script
I would like to know if there is a way to count the number of lines in a R script.

Ignoring lines of comment.

I didn't find a solution on the Internet. But maybe I missed something.

答:
That doesn't seem like very useful information, but you can do this:

```<code>script <- "#assign
a <- 1

b <- 2
"

nrow(read.table(text = script, sep = "°"))
[1] 2
</code>```

I use ° as the separator, because it's an unlikely character in most R scripts. Adjust that as needed.

Of course, this could be done much more efficiently outside of R.

Body:
That doesn't seem like very useful information, but you can do this:

script <- "#assign
a <- 1

b <- 2
"

nrow(read.table(text = script, sep = "°"))
[1] 2

I use ° as the separator, because it's an unlikely character in most R scripts. Adjust that as needed.

Of course, this could be done much more efficiently outside of R.


问:
How can i get bank information from source?
I have liked a online bank with plaid API to stripe. i have created a stripe customer with source bank token. But later I couldn't get bank information from source. It is showing </p>

```<code>An uncaught Exception was encountered

Type: Stripe\Error\InvalidRequest

Message: No such source: btok_1BOiMhGnklINT0gr7TYCRuvO
</code>```

答:
This error means that the API key you used to make the second API call is not from the Stripe account you linked to your Plaid account and also not the same you used when creating the customer. I'd recommend checking the API keys in both of your scripts.

Also once you fix this part, you should not reuse the token in subsequent calls as it would have been consumed by the customer creation call. You need to use the bank account id that was created instead (ba_xxx).

Body:
I have liked a online bank with plaid API to stripe. i have created a stripe customer with source bank token. But later I couldn't get bank information from source. It is showing

An uncaught Exception was encountered

Type: Stripe\Error\InvalidRequest

Message: No such source: btok_1BOiMhGnklINT0gr7TYCRuvO


问:
Django oscar Failed lookup for key [basket] in <WSGIRequest GET >
I am new to django-oscar and this is the first time I tried launching a website with it. I am facing the following stack trace when trying to load a webpage (localhost:8000). I tried to search a lot on the internet but I couldn't find any solution.

    Environment:
    Request Method: GET
    Request URL: http://localhost:8000/

```<code>Django Version: 1.9
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'django.contrib.flatpages',
 'compressor',
 'widget_tweaks',
 'oscar',
 'oscar.apps.analytics',
 'oscar.apps.checkout',
 'oscar.apps.address',
 'oscar.apps.shipping',
 'oscar.apps.catalogue',
 'oscar.apps.catalogue.reviews',
 'oscar.apps.partner',
 'oscar.apps.basket',
 'oscar.apps.payment',
 'oscar.apps.offer',
 'oscar.apps.order',
 'oscar.apps.customer',
 'oscar.apps.promotions',
 'oscar.apps.search',
 'oscar.apps.voucher',
 'oscar.apps.wishlists',
 'oscar.apps.dashboard',
 'oscar.apps.dashboard.reports',
 'oscar.apps.dashboard.users',
 'oscar.apps.dashboard.orders',
 'oscar.apps.dashboard.promotions',
 'oscar.apps.dashboard.catalogue',
 'oscar.apps.dashboard.offers',
 'oscar.apps.dashboard.partners',
 'oscar.apps.dashboard.pages',
 'oscar.apps.dashboard.ranges',
 'oscar.apps.dashboard.reviews',
 'oscar.apps.dashboard.vouchers',
 'oscar.apps.dashboard.communications',
 'oscar.apps.dashboard.shipping',
 'haystack',
 'treebeard',
 'sorl.thumbnail',
 'django_tables2']

Installed Middleware:<br>
['django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware']

Template error:
In template
/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/oscar/templates/oscar/promotions/home.html, error at line 0
   Failed lookup for key [%s] in %r   1 : {% extends "layout_2_col.html" %}
   2 : {% load i18n %}
   3 :
   4 : {% block navigation %}
   5 :     {% include "partials/nav_primary.html" with expand_dropdown=1 %}
   6 : {% endblock %}
   7 :
   8 : {% block header %}{% endblock %}
   9 :
   10 : {% block column_left %}

Traceback:

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
  879.                     current = current[bit]

During handling of the above exception ('WSGIRequest' object is not subscriptable), another exception occurred:

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
  887.                         current = getattr(current, bit)

During handling of the above exception ('WSGIRequest' object has no attribute 'basket'), another exception occurred:

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
  894.                             current = current[int(bit)]

During handling of the above exception (invalid literal for int() with base 10: 'basket'), another exception occurred:

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  174.                     response = self.process_exception_by_middleware(e, request)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  172.                     response = response.render()

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/response.py" in render
  160.             self.content = self.rendered_content

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/response.py" in rendered_content
  137.         content = template.render(context, self._request)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/backends/django.py" in render
  95.             return self.template.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  206.                     return self._render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _render
  197.         return self.nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/loader_tags.py" in render
  173.         return compiled_parent._render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _render
  197.         return self.nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/loader_tags.py" in render
  173.         return compiled_parent._render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _render
  197.         return self.nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/loader_tags.py" in render
  173.         return compiled_parent._render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _render
  197.         return self.nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/loader_tags.py" in render
  69.                 result = block.nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/loader_tags.py" in render
  69.                 result = block.nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/loader_tags.py" in render
  209.                 return template.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  208.                 return self._render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _render
  197.         return self.nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/defaulttags.py" in render
  326.                 return nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  1039.             output = self.filter_expression.resolve(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in resolve
  726.                     arg_vals.append(arg.resolve(context))

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in resolve
  846.             value = self._resolve_lookup(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
  901.                                                        (bit, current))  # missing attribute

Exception Type: VariableDoesNotExist at /
Exception Value: Failed lookup for key [basket] in "<WSGIRequest: GET '/'>"
</code>```

Also if you can suggest a better or less error prone e-commerce framework for django, it would be great!

答: You are lack of oscar.apps.basket.middleware.BasketMiddleware, in middleware setting.

Body:
I am new to django-oscar and this is the first time I tried launching a website with it. I am facing the following stack trace when trying to load a webpage (localhost:8000). I tried to search a lot on the internet but I couldn't find any solution.

    Environment:
    Request Method: GET
    Request URL: http://localhost:8000/

Django Version: 1.9
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'django.contrib.flatpages',
 'compressor',
 'widget_tweaks',
 'oscar',
 'oscar.apps.analytics',
 'oscar.apps.checkout',
 'oscar.apps.address',
 'oscar.apps.shipping',
 'oscar.apps.catalogue',
 'oscar.apps.catalogue.reviews',
 'oscar.apps.partner',
 'oscar.apps.basket',
 'oscar.apps.payment',
 'oscar.apps.offer',
 'oscar.apps.order',
 'oscar.apps.customer',
 'oscar.apps.promotions',
 'oscar.apps.search',
 'oscar.apps.voucher',
 'oscar.apps.wishlists',
 'oscar.apps.dashboard',
 'oscar.apps.dashboard.reports',
 'oscar.apps.dashboard.users',
 'oscar.apps.dashboard.orders',
 'oscar.apps.dashboard.promotions',
 'oscar.apps.dashboard.catalogue',
 'oscar.apps.dashboard.offers',
 'oscar.apps.dashboard.partners',
 'oscar.apps.dashboard.pages',
 'oscar.apps.dashboard.ranges',
 'oscar.apps.dashboard.reviews',
 'oscar.apps.dashboard.vouchers',
 'oscar.apps.dashboard.communications',
 'oscar.apps.dashboard.shipping',
 'haystack',
 'treebeard',
 'sorl.thumbnail',
 'django_tables2']

Installed Middleware:

['django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware']

Template error:
In template
/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/oscar/templates/oscar/promotions/home.html, error at line 0
   Failed lookup for key [%s] in %r   1 : {% extends "layout_2_col.html" %}
   2 : {% load i18n %}
   3 :
   4 : {% block navigation %}
   5 :     {% include "partials/nav_primary.html" with expand_dropdown=1 %}
   6 : {% endblock %}
   7 :
   8 : {% block header %}{% endblock %}
   9 :
   10 : {% block column_left %}

Traceback:

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
  879.                     current = current[bit]

During handling of the above exception ('WSGIRequest' object is not subscriptable), another exception occurred:

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
  887.                         current = getattr(current, bit)

During handling of the above exception ('WSGIRequest' object has no attribute 'basket'), another exception occurred:

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
  894.                             current = current[int(bit)]

During handling of the above exception (invalid literal for int() with base 10: 'basket'), another exception occurred:

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  174.                     response = self.process_exception_by_middleware(e, request)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  172.                     response = response.render()

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/response.py" in render
  160.             self.content = self.rendered_content

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/response.py" in rendered_content
  137.         content = template.render(context, self._request)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/backends/django.py" in render
  95.             return self.template.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  206.                     return self._render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _render
  197.         return self.nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/loader_tags.py" in render
  173.         return compiled_parent._render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _render
  197.         return self.nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/loader_tags.py" in render
  173.         return compiled_parent._render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _render
  197.         return self.nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/loader_tags.py" in render
  173.         return compiled_parent._render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _render
  197.         return self.nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/loader_tags.py" in render
  69.                 result = block.nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/loader_tags.py" in render
  69.                 result = block.nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/loader_tags.py" in render
  209.                 return template.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  208.                 return self._render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _render
  197.         return self.nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/defaulttags.py" in render
  326.                 return nodelist.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in render
  1039.             output = self.filter_expression.resolve(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in resolve
  726.                     arg_vals.append(arg.resolve(context))

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in resolve
  846.             value = self._resolve_lookup(context)

File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
  901.                                                        (bit, current))  # missing attribute

Exception Type: VariableDoesNotExist at /
Exception Value: Failed lookup for key [basket] in "<WSGIRequest: GET '/'>"

Also if you can suggest a better or less error prone e-commerce framework for django, it would be great!


问:
Using parameters throughout multiple subroutines python
I am currently trying to write a program where the user inputs what colour carpet they would like and then depending on what carpet and what area they have inputted it will give them a different price, However my current issue is using the parameters correctly since I am very new to both using python and to programming. The current program specification requires the use of subroutines. An example problem is with my last line main(exit1) where it says that exit1 isn't defined and if I try to edit the code to main() it says that exit1 is required. Any help will be greatly appreciated.</p>

```<code>def prices():
    PriceA = 40
    PriceB = 50
    PriceC = 60
def main(exit1):
    exit1 = False
    while exit1 == False:
        carpet = str(input("What carpet would you like blue, red or yellow "))
        carpet = carpet.upper()
        if carpet == "X":
            exit1 = True
        else:
            width = int(input("What is the width of the room in M^2 "))
            height = int(input("What is the height of the room in M^2 "))
            area = width * height

            if carpet == "BLUE":
                a(area)

            elif carpet == "RED":
                b(area)

            elif carpet == "YELLOW":
                c(area)

            else:
                print("Invalid carpet")
                cost = 0
                output(cost)

def output(cost, exit1):
print ("the price is £", cost)

def a(area, PriceA):
    cost = PriceA * area
    output(cost)

def b(area, PriceB):
    cost = PriceB * area
    output(cost)

def c(area, PriceC):
    cost = PriceC * area
    output(cost)

main(exit1)
</code>```

答:
The problem you are having is that a variable needs to be defined before it can be entered into a function. I fixed the code and made a few corrections it also appeared that you had an indentation error and didn't feed in enough arguments into your functions when you called them. The code ive written is a bit easier to follwo. If I have done anything you dont understand send me a message, otherwise I recommend sites such as code acadamy and pythonprogramming .net.
    def main():</p>

```<code>    PriceA = 40
    PriceB = 50
    PriceC = 60
    while True:
        carpet = str(input('What carpet would you like blue, red or yellow? '))
        carpet = carpet.upper()
        if carpet == 'X':
            break
        else:
            width = int(input("What is the width of the room in M? "))
            height = int(input("What is the height of the room in M? "))
            area = width * height

        if carpet == "BLUE":
            output(area,PriceA)

        elif carpet == "RED":
            output(area,PriceB)

        elif carpet == "YELLOW":
            output(area,PriceC)
        else:
            print('Invalid carpet')
def output(area,Price):
    cost = area*Price
    print('the price is £',cost)
main()
</code>```

Body:
I am currently trying to write a program where the user inputs what colour carpet they would like and then depending on what carpet and what area they have inputted it will give them a different price, However my current issue is using the parameters correctly since I am very new to both using python and to programming. The current program specification requires the use of subroutines. An example problem is with my last line main(exit1) where it says that exit1 isn't defined and if I try to edit the code to main() it says that exit1 is required. Any help will be greatly appreciated.

def prices():
    PriceA = 40
    PriceB = 50
    PriceC = 60
def main(exit1):
    exit1 = False
    while exit1 == False:
        carpet = str(input("What carpet would you like blue, red or yellow "))
        carpet = carpet.upper()
        if carpet == "X":
            exit1 = True
        else:
            width = int(input("What is the width of the room in M^2 "))
            height = int(input("What is the height of the room in M^2 "))
            area = width * height

            if carpet == "BLUE":
                a(area)

            elif carpet == "RED":
                b(area)

            elif carpet == "YELLOW":
                c(area)

            else:
                print("Invalid carpet")
                cost = 0
                output(cost)

def output(cost, exit1):
print ("the price is £", cost)

def a(area, PriceA):
    cost = PriceA * area
    output(cost)

def b(area, PriceB):
    cost = PriceB * area
    output(cost)

def c(area, PriceC):
    cost = PriceC * area
    output(cost)

main(exit1)

Body:
The problem you are having is that a variable needs to be defined before it can be entered into a function. I fixed the code and made a few corrections it also appeared that you had an indentation error and didn't feed in enough arguments into your functions when you called them. The code ive written is a bit easier to follwo. If I have done anything you dont understand send me a message, otherwise I recommend sites such as code acadamy and pythonprogramming .net.
    def main():

    PriceA = 40
    PriceB = 50
    PriceC = 60
    while True:
        carpet = str(input('What carpet would you like blue, red or yellow? '))
        carpet = carpet.upper()
        if carpet == 'X':
            break
        else:
            width = int(input("What is the width of the room in M? "))
            height = int(input("What is the height of the room in M? "))
            area = width * height

        if carpet == "BLUE":
            output(area,PriceA)

        elif carpet == "RED":
            output(area,PriceB)

        elif carpet == "YELLOW":
            output(area,PriceC)
        else:
            print('Invalid carpet')
def output(area,Price):
    cost = area*Price
    print('the price is £',cost)
main()


问:
`UICollectionViewLayout` has no member `itemSize`
I am a beginner in iOS/Swift development.  When I use the layout's itemSize property, I get the following error message, and I don't understand why:

```<code>Value of type `UICollectionViewLayout` has no member `itemSize`
</code>```

Here is my code:

```<code>let layout = collectionView!.collectionViewLayout as! UICollectionViewLayout
layout.itemSize = CGSize(width: cellWeight, height: cellHeight)
</code>```

答: UICollectionViewLayout is an abstract base class. You probably want to use UICollectionViewFlowLayout, which has the itemSize property you're after.

Body:
I am a beginner in iOS/Swift development.  When I use the layout's itemSize property, I get the following error message, and I don't understand why:

Value of type `UICollectionViewLayout` has no member `itemSize`

Here is my code:

let layout = collectionView!.collectionViewLayout as! UICollectionViewLayout
layout.itemSize = CGSize(width: cellWeight, height: cellHeight)


问:
VBA code to search for string then a second string and return lines of data from a text file
I am trying to search through large log files to find a string of text, then if that string is present to find another string of text and then return the next 5 lines of data. I have managed to search the text file for the string and return the 5 lines after however I cannot seem to get the macro to search for both lines of text before returning the 5 lines.

For example if the text file looked like this:

17:42:56: Log File Closed
17:42:56: PrintInvoice: 2
17:42:56: copyReportData:
17:42:56: getNextRptDataID:
17:42:58: CalcDelCharge:
17:42:58:    Sub Total: 3.80
17:42:58:    Del Total: 0.00
17:42:58:    Disc Total: 0.00
17:42:58:    Vat Total: 0.00
17:42:58:    Inv Total: 3.80
18:33:00: CalculateAmtDue:
18:33:00: CalculateChange:
18:33:00: UpdateDelCharge:
18:33:00: UpdateTotals
18:42:58: CalcDelCharge:
18:42:58:    Sub Total: 5.80
18:42:58:    Del Total: 0.00
18:42:58:    Disc Total: 0.00
18:42:58:    Vat Total: 0.00
18:42:58:    Inv Total: 5.80

I want to extract the 5 lines after the first 'CalcDelCharge' as it is follows 'PrintInvoice: 2', which is one of the strings I am also wanting to search for.

The text file contains 'CalcDelCharge' throughout, however I am only interested in the instances when it comes after 'PrintInvoice: 2', which appears much less frequently.

Here is what I have so far

```<code>Dim fn As String, txt As String, delim As String, a() As String
Dim i As Long, ii As Long, iii As Long, x, y
fn = "C:\Documents\tilllogfile.log"
delim = vbTab
temp = CreateObject("Scripting.FileSystemObject").OpenTextFile(fn).ReadAll
x = Split(temp, vbCrLf)
ReDim a(1 To UBound(x) + 1, 1 To 100)
For i = 0 To UBound(x)
    If InStr(1, x(i), "CalcDelCharge", 1) Then
    For ii = 0 To 5
        n = n + 1: y = Split(x(i + ii), delim)
        For iii = 0 To UBound(y)
            a(n, iii + 1) = y(iii)
        Next
    Next
End If
</code>```

This will extract 5 lines after all 'CalcDelCharge' and put it into a spreadsheet for me, I have not been able to narrow it down to the instances when it follows 'PrintInvoice: 2'.

Any help would be greatly appreciated.

Thanks.

答:
Declare boolean variable to tell the macro if your text was found

```<code>Dim boolFound As Boolean
</code>```

in your most external loop add first test:

```<code>For i = 0 To UBound(x)
    If InStr(1, x(i), "PrintInvoice: 2", 1) Then
        boolFound = True
    End If
</code>```

in your second test add condition:

```<code>If InStr(1, x(i), "CalcDelCharge", 1) And boolFound Then
</code>```

don't forget to change boolFound to false after you copy your five rows:

```<code>    boolFound = False
End If
</code>```

Body:
I am trying to search through large log files to find a string of text, then if that string is present to find another string of text and then return the next 5 lines of data. I have managed to search the text file for the string and return the 5 lines after however I cannot seem to get the macro to search for both lines of text before returning the 5 lines.

For example if the text file looked like this:

17:42:56: Log File Closed
17:42:56: PrintInvoice: 2
17:42:56: copyReportData:
17:42:56: getNextRptDataID:
17:42:58: CalcDelCharge:
17:42:58:    Sub Total: 3.80
17:42:58:    Del Total: 0.00
17:42:58:    Disc Total: 0.00
17:42:58:    Vat Total: 0.00
17:42:58:    Inv Total: 3.80
18:33:00: CalculateAmtDue:
18:33:00: CalculateChange:
18:33:00: UpdateDelCharge:
18:33:00: UpdateTotals
18:42:58: CalcDelCharge:
18:42:58:    Sub Total: 5.80
18:42:58:    Del Total: 0.00
18:42:58:    Disc Total: 0.00
18:42:58:    Vat Total: 0.00
18:42:58:    Inv Total: 5.80

I want to extract the 5 lines after the first 'CalcDelCharge' as it is follows 'PrintInvoice: 2', which is one of the strings I am also wanting to search for.

The text file contains 'CalcDelCharge' throughout, however I am only interested in the instances when it comes after 'PrintInvoice: 2', which appears much less frequently.

Here is what I have so far

Dim fn As String, txt As String, delim As String, a() As String
Dim i As Long, ii As Long, iii As Long, x, y
fn = "C:\Documents\tilllogfile.log"
delim = vbTab
temp = CreateObject("Scripting.FileSystemObject").OpenTextFile(fn).ReadAll
x = Split(temp, vbCrLf)
ReDim a(1 To UBound(x) + 1, 1 To 100)
For i = 0 To UBound(x)
    If InStr(1, x(i), "CalcDelCharge", 1) Then
    For ii = 0 To 5
        n = n + 1: y = Split(x(i + ii), delim)
        For iii = 0 To UBound(y)
            a(n, iii + 1) = y(iii)
        Next
    Next
End If

This will extract 5 lines after all 'CalcDelCharge' and put it into a spreadsheet for me, I have not been able to narrow it down to the instances when it follows 'PrintInvoice: 2'.

Any help would be greatly appreciated.

Thanks.

Body:
Declare boolean variable to tell the macro if your text was found

Dim boolFound As Boolean

in your most external loop add first test:

For i = 0 To UBound(x)
    If InStr(1, x(i), "PrintInvoice: 2", 1) Then
        boolFound = True
    End If

in your second test add condition:

If InStr(1, x(i), "CalcDelCharge", 1) And boolFound Then

don't forget to change boolFound to false after you copy your five rows:

    boolFound = False
End If


问:
Using a select box to trigger JS event to make another select box become passive/active? HTML/JS
I want select box B to become visible when option 2 is selected in select box A, otherwise it should remain hidden.  It's not working.  Here's my code: [EDIT: I actually want it to be passive instead of hidden.]

The JavaScript first:

```<code>function toggle2(value){
if(value=='confirm')
 document.getElementById('test').style.visibility='visible';
else
 document.getElementById('test').style.visibility='hidden';
}

 <select class="select3" name="CaseType" onchange="toggle2()">
  <option value="select" selected="selected">- Select Case Type -</option>
  <option value="suspect">Suspected</option>
  <option value="confirm">Confirmed</option>
  </select>

  <select id="test" class="select4" name="test" style="visibility: hidden;">
  <option selected="selected">- Select test -</option>
  </select>
</code>```

Thanks!

答:
Here's some amended code</p>

```<code>function toggle2(incontrol){
   var value=incontrol.options[incontrol.selectedIndex).value;
   if(value=='confirm'){
    document.getElementById('test').style.visibility='visible';
   }
   else{
    document.getElementById('test').style.visibility='hidden';
  }
}

 <select class="select3" name="CaseType" onchange="toggle2(this)">
  <option value="select" selected="selected">- Select Case Type -</option>
  <option value="suspect">Suspected</option>
  <option value="confirm">Confirmed</option>
  </select>

  <select id="test" class="select4" name="test" style="visibility: hidden;">
  <option selected="selected">- Select test -</option>
  </select>
</code>```

Body:
I want select box B to become visible when option 2 is selected in select box A, otherwise it should remain hidden.  It's not working.  Here's my code: [EDIT: I actually want it to be passive instead of hidden.]

The JavaScript first:

function toggle2(value){
if(value=='confirm')
 document.getElementById('test').style.visibility='visible';
else
 document.getElementById('test').style.visibility='hidden';
}

 <select class="select3" name="CaseType" onchange="toggle2()">
  <option value="select" selected="selected">- Select Case Type -</option>
  <option value="suspect">Suspected</option>
  <option value="confirm">Confirmed</option>
  </select>

  <select id="test" class="select4" name="test" style="visibility: hidden;">
  <option selected="selected">- Select test -</option>
  </select>

Thanks!

Body:
Here's some amended code

function toggle2(incontrol){
   var value=incontrol.options[incontrol.selectedIndex).value;
   if(value=='confirm'){
    document.getElementById('test').style.visibility='visible';
   }
   else{
    document.getElementById('test').style.visibility='hidden';
  }
}

 <select class="select3" name="CaseType" onchange="toggle2(this)">
  <option value="select" selected="selected">- Select Case Type -</option>
  <option value="suspect">Suspected</option>
  <option value="confirm">Confirmed</option>
  </select>

  <select id="test" class="select4" name="test" style="visibility: hidden;">
  <option selected="selected">- Select test -</option>
  </select>


问:
Include error messages from testthat in R markdown document
I want to include error messages in an R markdown pdf report. This works well:

```<code>---
output: pdf_document
---

This will be knitted and show the error message in the pdf.
```{r, error = TRUE}
stopifnot(2 == 3)
```
</code>```

However, if I try the same approach with an error that comes from testthat, my document does not knit anymore.

```<code>---
output: pdf_document
---

This will not knit
```{r, error = TRUE}
library(testthat)
expect_equal(2, 3)
```
</code>```

Why is that? And what can I do to include error messages from testthat's expect_something functions without wrapping them up in a test?

I think this must be possible since Hadley Wickham includes many error messages in his book R packages that come directly from expect_something-functions.

This is related, but not answered in Include errors in R markdown package vignette and How to skip error checking at Rmarkdown compiling?

答:
I don't understand the reason for the behavior (good question!), but this could be a workaround:</p>

```<code>---
output: pdf_document
---

This will knit
```{r, error = TRUE}
library(testthat)
# expect_equal(2, 3)
# skip_if_not(2, 3)
assertthat::assert_that(2 == 3)
```
</code>```

Body:
I want to include error messages in an R markdown pdf report. This works well:

---
output: pdf_document
---

This will be knitted and show the error message in the pdf.
```{r, error = TRUE}
stopifnot(2 == 3)
```

However, if I try the same approach with an error that comes from testthat, my document does not knit anymore.

---
output: pdf_document
---

This will not knit
```{r, error = TRUE}
library(testthat)
expect_equal(2, 3)
```

Why is that? And what can I do to include error messages from testthat's expect_something functions without wrapping them up in a test?

I think this must be possible since Hadley Wickham includes many error messages in his book R packages that come directly from expect_something-functions.

This is related, but not answered in Include errors in R markdown package vignette and How to skip error checking at Rmarkdown compiling?

Body:
I don't understand the reason for the behavior (good question!), but this could be a workaround:

---
output: pdf_document
---

This will knit
```{r, error = TRUE}
library(testthat)
# expect_equal(2, 3)
# skip_if_not(2, 3)
assertthat::assert_that(2 == 3)
```


问:
SQL Server 2016 T-SQL convert comma string to inner join database name(s)
I have a value for one of my columns that looks like this:

```<code>ID   | userPerms | Name      | DOB
-----+-----------+-----------+----------
5985 |1,3,4      |Bob Barker |12/12/1923
895  |1,2        |Bill Gates |10/14/1955
5897 |1,2,4      |Steve Jobs |02/24/1955
</code>```

That column being the userPerms column.

I need to be able to Inner Join with the userPerm table associated with those numbers.

My query is currently:

```<code>SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' + uT.email + '|' +
    uT.firstName  + '|' + uT.lastName        + '|' + uT.active + '|' + uT.userPerms + '|' +
    uT.userPermPages
FROM
    usersTbl AS uT
INNER JOIN
    usersPermissions AS uP ON uP.id = uT.userPerms
WHERE
    uT.id = 1
</code>```

Naturally it won't work since the data has commas in it.

So what I am looking for in the output:

```<code>ID   | userPerms        | Name      | DOB
-----+------------------+-----------+------------
5985 |Read,Upload,Admin |Bob Barker |12/12/1923
895  |Read,Write        |Bill Gates |10/14/1955
5897 |Read,Write,Admin  |Steve Jobs |02/24/1955
</code>```

Does anyone know how to split these out so that the inner join would then work as designed?

UPDATE 1

I got it working but:

It does not combine the userPerms into the original string

```<code>SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' +
    uT.email + '|' + uT.firstName + '|' + uT.lastName + '|' + uT.active,
    (
        SELECT
            ',' + uP.type
        FROM
            usersPermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPerms,
    (
        SELECT
            ',' + uP.name
        FROM
            pagePermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPermPages
FROM
    usersTbl as uT
WHERE
    uT.id = '1';
</code>```

答:
```<code>create table  #tblData (ID INT, userPerms VARCHAR(100),Name VARCHAR(100),DOB DATE);
INSERT INTO #tbldata VALUES
 (5985,'1,3,4','Bob Barker','12/12/1923')
,(895,'1,2','Bill Gates','10/14/1955')
,(5897,'1,2,4','Steve Jobs','02/24/1955');

create table   #tblPerm (ID INT, Perm VARCHAR(100));
INSERT INTO #tblPerm VALUES
 (1,'Read')
,(2,'Write')
,(3,'Upload')
,(4,'Admin');

Create FUNCTION [dbo].[fnSplitString]
    (
        @string NVARCHAR(MAX),
        @delimiter CHAR(1)
    )
    RETURNS @output TABLE(splitdata NVARCHAR(MAX)
    )
    BEGIN
        DECLARE @start INT, @end INT
        SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)
        WHILE @start < LEN(@string) + 1 BEGIN
            IF @end = 0
                SET @end = LEN(@string) + 1

            INSERT INTO @output (splitdata)
            VALUES(SUBSTRING(@string, @start, @end - @start))
            SET @start = @end + 1
            SET @end = CHARINDEX(@delimiter, @string, @start)

        END
        RETURN
    END
    go
    ;with cte
    as
    (
    select t1.ID,t1.userPerms,t1.Name,t3.Perm ,t1.DOB from #tblData as t1
    cross apply
    dbo.fnsplitstring(t1.userPerms,',') as t2
    join #tblPerm as t3
    on t3.ID=t2.splitdata
    )

    select id,STUFF((select ','+perm from cte t1
    where t1.ID=t2.id
    for XML path('')),1,1,'')  as userperms,Name,DOB
    from cte t2
    group by id ,name,DOB
</code>```

Body:
I have a value for one of my columns that looks like this:

ID   | userPerms | Name      | DOB
-----+-----------+-----------+----------
5985 |1,3,4      |Bob Barker |12/12/1923
895  |1,2        |Bill Gates |10/14/1955
5897 |1,2,4      |Steve Jobs |02/24/1955

That column being the userPerms column.

I need to be able to Inner Join with the userPerm table associated with those numbers.

My query is currently:

SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' + uT.email + '|' +
    uT.firstName  + '|' + uT.lastName        + '|' + uT.active + '|' + uT.userPerms + '|' +
    uT.userPermPages
FROM
    usersTbl AS uT
INNER JOIN
    usersPermissions AS uP ON uP.id = uT.userPerms
WHERE
    uT.id = 1

Naturally it won't work since the data has commas in it.

So what I am looking for in the output:

ID   | userPerms        | Name      | DOB
-----+------------------+-----------+------------
5985 |Read,Upload,Admin |Bob Barker |12/12/1923
895  |Read,Write        |Bill Gates |10/14/1955
5897 |Read,Write,Admin  |Steve Jobs |02/24/1955

Does anyone know how to split these out so that the inner join would then work as designed?

UPDATE 1

I got it working but:

It does not combine the userPerms into the original string

SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' +
    uT.email + '|' + uT.firstName + '|' + uT.lastName + '|' + uT.active,
    (
        SELECT
            ',' + uP.type
        FROM
            usersPermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPerms,
    (
        SELECT
            ',' + uP.name
        FROM
            pagePermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPermPages
FROM
    usersTbl as uT
WHERE
    uT.id = '1';


问:
Angular animation: Slider Effect
Have a look at the code here: Simple Angular animation example
I want to generate a similar effect in in my webpage using Angular animation. The only difference is, in the above example, the code is generating slider effect when fetching different html files. My project has a slight modification to that. Instead,  i want to display two different div of the same html file. On clicking button one I want to display a div. lets call it div1 for now. On clicking button 2 I want to display div2 and remove display of div1 by showing sliding animation. How do I do that?
The index.html code is here:</p>

```<code><!DOCTYPE html>
<html ng-app="myApp">

<head>
  <title>AngularJS Swipe Slider animation</title>
  <meta name="viewport" content="width=device-width,height=device-height,user-scalable=no">
  <link href="style.css" rel="stylesheet" />
  <link href="http://ajax.aspnetcdn.com/ajax/bootstrap/3.2.0/css/bootstrap.css" rel="stylesheet" />
</head>

<body>
  <div ng-controller="tabsSwipeCtrl as responsive">
    <div class="btn-group btn-group-justified">
      <div class="btn-group">
        <button type="button" class="btn btn-default" ng-click="responsive.selectPage(0)" ng-class="{'active': responsive.ngIncludeSelected.index == 0}">First</button>
      </div>
      <div class="btn-group">
        <button type="button" class="btn btn-default" ng-click="responsive.selectPage(1)" ng-class="{'active': responsive.ngIncludeSelected.index == 1}">Second</button>
      </div>
      <div class="btn-group">
        <button type="button" class="btn btn-default" ng-click="responsive.selectPage(2)" ng-class="{'active': responsive.ngIncludeSelected.index == 2}">Third</button>
      </div>
      <div class="btn-group">
        <button type="button" class="btn btn-default" ng-click="responsive.selectPage(3)" ng-class="{'active': responsive.ngIncludeSelected.index == 3}">Fourth</button>
      </div>
    </div>
    <div class="ngIncludeRelative">
      <div class="ngIncludeItem" ng-include="responsive.ngIncludeSelected.url" ng-class="{'moveToLeft' : responsive.moveToLeft}"></div>
    </div>
  </div>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular-touch.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular-animate.min.js"></script>
<script src="script.js"></script>
</body>

</html>
</code>```

答:
Within div u can simply do by using jquery animate function</p>

```<code>$(".btn-default").click(function(){
$("div2").animate({
    left: '250px'
});
});
</code>```

Title: Angular animation: Slider Effect

Body:
Have a look at the code here: Simple Angular animation example
I want to generate a similar effect in in my webpage using Angular animation. The only difference is, in the above example, the code is generating slider effect when fetching different html files. My project has a slight modification to that. Instead,  i want to display two different div of the same html file. On clicking button one I want to display a div. lets call it div1 for now. On clicking button 2 I want to display div2 and remove display of div1 by showing sliding animation. How do I do that?
The index.html code is here:

<!DOCTYPE html>

  <title>AngularJS Swipe Slider animation</title>
  <meta name="viewport" content="width=device-width,height=device-height,user-scalable=no">
  <link href="style.css" rel="stylesheet" />
  <link href="http://ajax.aspnetcdn.com/ajax/bootstrap/3.2.0/css/bootstrap.css" rel="stylesheet" />

        <button type="button" class="btn btn-default" ng-click="responsive.selectPage(0)" ng-class="{'active': responsive.ngIncludeSelected.index == 0}">First</button>

        <button type="button" class="btn btn-default" ng-click="responsive.selectPage(1)" ng-class="{'active': responsive.ngIncludeSelected.index == 1}">Second</button>

        <button type="button" class="btn btn-default" ng-click="responsive.selectPage(2)" ng-class="{'active': responsive.ngIncludeSelected.index == 2}">Third</button>

        <button type="button" class="btn btn-default" ng-click="responsive.selectPage(3)" ng-class="{'active': responsive.ngIncludeSelected.index == 3}">Fourth</button>

Body:
Within div u can simply do by using jquery animate function

$(".btn-default").click(function(){
$("div2").animate({
    left: '250px'
});
});


问:
Run Java Script in Wordpress
I have bought one WordPress theme which have Live Chat button in header. Its support link to open chat. But I have got java script to open button. I am learning php and does not know how can I run java script on button press WordPress.

I have code in wordpress header theme is like below

```<code><?php }if( !empty( $king->cfg['topInfoLiveChat'] ) ){ ?>
                <a href="<?php echo esc_attr( $king->cfg['topInfoLiveChat'] ); ?>" class="chat">
                    <i class="fa fa-comments-o"></i> <?php _e('Live Chat', 'arkahost' ); ?>
                </a>
</code>```

Zopim chat have given me script to run is like below.

```<code>$zopim.livechat.window.show();
</code>```

They have given example to include like below

```<code><a href="javascript:$zopim.livechat.window.show()"><img src="INSERT_IMG_SRC_HERE"/></a>
</code>```

But if I use like above my design getting changed. Anyone can please help me how can I integrate this script in my above codes ?

Thanks

答:
Did you learn some javascript and jQuery? You can run codes when an event happen. Like you have clicked a ahref element with .chat class.

```<code><script>
    jQuery("a.chat").on("click", function(e) {
       e.preventDefault();
       // Your code goes here. Example:
       $zopim.livechat.window.show();
    });
</script>
</code>```

P/s: you should have a better selector like .header a.chat, or all ahref element have .chat class will show your Zopim windows when users clicked on it.

Title: Run Java Script in Wordpress

Body:
I have bought one WordPress theme which have Live Chat button in header. Its support link to open chat. But I have got java script to open button. I am learning php and does not know how can I run java script on button press WordPress.

I have code in wordpress header theme is like below

<?php }if( !empty( $king->cfg['topInfoLiveChat'] ) ){ ?>
                <a href="<?php echo esc_attr( $king->cfg['topInfoLiveChat'] ); ?>" class="chat">
                     <?php _e('Live Chat', 'arkahost' ); ?>

Zopim chat have given me script to run is like below.

$zopim.livechat.window.show();

They have given example to include like below

But if I use like above my design getting changed. Anyone can please help me how can I integrate this script in my above codes ?

Thanks

Body:
Did you learn some javascript and jQuery? You can run codes when an event happen. Like you have clicked a ahref element with .chat class.

<script>
    jQuery("a.chat").on("click", function(e) {
       e.preventDefault();
       // Your code goes here. Example:
       $zopim.livechat.window.show();
    });
</script>

P/s: you should have a better selector like .header a.chat, or all ahref element have .chat class will show your Zopim windows when users clicked on it.


问:
Regular expression to match single parentheses
I need to parse excel formulas to generate C-compatible code. Now I need to parse the "power" expressions using Java:

```<code>1. F15^2
2. (A1*A2)^2
3. SQRT((A1*A2)^2)
</code>```

I have the following regular expression:

```<code>(\([^)]*\)|\w+)\^(\([^)]*\)|\w+)
</code>```

This expression parses 1. and 2. correctly.

```<code>1. Group1: F15, group2: 2
2. Group1: (A1*A2), group2: 2
</code>```

However for 3. it returns 1 parenthesis too much:

```<code>3. Group1: ((A1*A2), group2: 2
</code>```

How should I modify my regular expression so group 1 becomes (A1*A2) instead of ((A1*A2) ?

答:
If you just need it to work on these examples, I would change the regex to this: (\([^)(]*\)|\w+)\^(\([^)]*\)|\w+) (I added a single ()

But in general, I don't think a regex is the proper way to do it. I would try finding a library that could do parenthesis-parsing, instead of trying to implement it myself.

Body:
I need to parse excel formulas to generate C-compatible code. Now I need to parse the "power" expressions using Java:

1. F15^2
2. (A1*A2)^2
3. SQRT((A1*A2)^2)

I have the following regular expression:

(\([^)]*\)|\w+)\^(\([^)]*\)|\w+)

This expression parses 1. and 2. correctly.

1. Group1: F15, group2: 2
2. Group1: (A1*A2), group2: 2

However for 3. it returns 1 parenthesis too much:

3. Group1: ((A1*A2), group2: 2

How should I modify my regular expression so group 1 becomes (A1*A2) instead of ((A1*A2) ?


问:
How is using Join faster than using just Rand() in MySQL
How is

```<code>SELECT t.id
FROM table t
JOIN (SELECT(FLOOR(max(id) * rand())) AS maxid FROM table)
AS tt
ON t.id >= tt.maxid
LIMIT 1
</code>```

faster than

```<code>SELECT * FROM `table` ORDER BY RAND() LIMIT 1
</code>```

I am actually having trouble understanding the first. Maybe if I knew why one is faster than the other I would have a better understanding.

*original post @ Difficult MySQL self-join please explain

答:
You can use EXPLAIN on the queries, but basically:

In the first you're getting a random number (which isn't very slow), based on the maximum of a (i presume) indexed field. This is quite quick, i'd say maybe even near-constant time (depends on the implementation of the index hash?)

Then you're joining on that number and returning only the first row that's greater then, and because you're using an index again, this is lightning quick.

The second is ordering by some random function. This has to, but you'll need to look at the explain for that, do a FULL TABLE scan, and then return the first. This is ofcourse VERY expensive. You're not using any indexes because of that rand.

(the explain will look like this, showing that you're not using keys)

```<code>id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE  table    ALL    NULL    NULL    NULL    NULL    14  Using temporary; Using filesort
</code>```

Body:
How is

SELECT t.id
FROM table t
JOIN (SELECT(FLOOR(max(id) * rand())) AS maxid FROM table)
AS tt
ON t.id >= tt.maxid
LIMIT 1

faster than

SELECT * FROM `table` ORDER BY RAND() LIMIT 1

I am actually having trouble understanding the first. Maybe if I knew why one is faster than the other I would have a better understanding.

*original post @ Difficult MySQL self-join please explain

Body:
You can use EXPLAIN on the queries, but basically:

In the first you're getting a random number (which isn't very slow), based on the maximum of a (i presume) indexed field. This is quite quick, i'd say maybe even near-constant time (depends on the implementation of the index hash?)

Then you're joining on that number and returning only the first row that's greater then, and because you're using an index again, this is lightning quick.

The second is ordering by some random function. This has to, but you'll need to look at the explain for that, do a FULL TABLE scan, and then return the first. This is ofcourse VERY expensive. You're not using any indexes because of that rand.

(the explain will look like this, showing that you're not using keys)

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE  table    ALL    NULL    NULL    NULL    NULL    14  Using temporary; Using filesort


问:
Parse XML to JSON and back ... with xml2js and xmlbuilder?
Trying to parse XML into JSON with xml2js and then return the JSON to XML using xmlbuilder (usually after modifying the content programmatically).

I think that the two should be complements, per this post https://github.com/oozcitak/xmlbuilder-js/issues/69.  But am having some difficulty, and it's gotta be that I'm not getting the config parameters right.

Here's the code I'm running:

```<code>var xml = fs.readFileSync(__dirname + '/../xml/theme.xml', 'utf8');

xml2js.parseString(xml, { attrkey: '@',  xmlns: true }, function(err, json) {
    var xml2 = xmlbuilder.create(json,
       {version: '1.0', encoding: 'UTF-8', standalone: true}
    ).end({pretty: true, standalone: true})
});
</code>```

Here's the first bit of the original XML:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">
    <a:themeElements>
        <a:clrScheme name="Office">
            <a:dk1>
                <a:sysClr val="windowText" lastClr="000000"/>
            </a:dk1>
            <a:lt1>
                <a:sysClr val="window" lastClr="FFFFFF"/>
            </a:lt1>
            <a:dk2>
                <a:srgbClr val="1F497D"/>
            </a:dk2>
            ...
     </a:themeElements>
 </a:theme>
</code>```

Here;s how xml2js parses that to JSON, this looks right to me:

```<code>{
    "a:theme": {
        "@": {
            "xmlns:a": {
                "name": "xmlns:a",
                "value": "http://schemas.openxmlformats.org/drawingml/2006/main",
                "prefix": "xmlns",
                "local": "a",
                "uri": "http://www.w3.org/2000/xmlns/"
            },
            "name": {
                "name": "name",
                "value": "Office Theme",
                "prefix": "",
                "local": "name",
                "uri": ""
            }
        },
        "@ns": {
            "uri": "http://schemas.openxmlformats.org/drawingml/2006/main",
            "local": "theme"
        },
        "a:themeElements": [
            {
                "@ns": {
                    "uri": "http://schemas.openxmlformats.org/drawingml/2006/main",
                    "local": "themeElements"
                },
                "a:clrScheme": [
                    {
                        "@": {
                            "name": {
                                "name": "name",
                                "value": "Office",
                                "prefix": "",
                                "local": "name",
                                "uri": ""
                            }
                        },
                        "@ns": {
                            "uri": "http://schemas.openxmlformats.org/drawingml/2006/main",
                            "local": "clrScheme"
                        },
                       ...
</code>```

Note that in the JSON above:

the attribute (e.g. name=) are turned into keys inside an @ object and

the attribute values are turned into objects

Now here's how it looks when xmlbuilder turns it back into XML:

```<code><a:theme ="[object Object]" ns="[object Object]">
  <a:themeElements ns="[object Object]">
    <a:clrScheme ="[object Object]" ns="[object Object]">
      <a:dk1 ns="[object Object]">
        <a:sysClr ="[object Object]" ns="[object Object]"/>
      </a:dk1>
      <a:lt1 ns="[object Object]">
        <a:sysClr ="[object Object]" ns="[object Object]"/>
      </a:lt1>
       ...
    </a:themeElements>
 </a:theme>
</code>```

So there are two problems that XML builder is facing:
  * it's not recognizing the attribute names within the @ object and
  * it's not recognizing the attribute value within the attribute object

Hacking it appears that xmlbuilder wants attributes names structured like:

```<code>  `{ "@name": "Office Theme"} `
</code>```

rather than

```<code>  `{ "@" : { "name" : { value: "Office Theme" }}}`
</code>```

Should I configure xml2js differently, xmlbuilder differently, or is there a different pair of libraries that can parse XML -> JSON -> XML?

答:
I came across similar requirement recently. Had to convert Yahoo weather service xml data into json object. Solved the issue with xml2js and js2xmlparser modules. Thought to share how I did here. An example which I worked out:

```<code>const https = require('https');
var parseString = require('xml2js').parseString;

https.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22surat%22)&format=xml&env=store%3A%2F%2F    datatables.org%2Falltableswithkeys', (resp) => {
    let data = '';

    // A chunk of data has been recieved.
    resp.on('data', (chunk) => {
        data += chunk;
    });

    // The whole response has been received. Print out the result.
    resp.on('end', () => {
        //console.log(JSON.parse(data).explanation);

        parseString(data, function (err, result) {
            console.log(JSON.stringify(result));
        });
    });

}).on("error", (err) => {
    console.log("Error: " + err.message);
});
</code>```

After this one can use js2xmlparser for converting the obtained json to xml.

```<code>js2xmlparser.parse("weather", data);
....
</code>```

here's a Github link for the detailed code: https://github.com/joshiparthin/ReNode/tree/master/soap-api

Body:
Trying to parse XML into JSON with xml2js and then return the JSON to XML using xmlbuilder (usually after modifying the content programmatically).

I think that the two should be complements, per this post https://github.com/oozcitak/xmlbuilder-js/issues/69.  But am having some difficulty, and it's gotta be that I'm not getting the config parameters right.

Here's the code I'm running:

var xml = fs.readFileSync(__dirname + '/../xml/theme.xml', 'utf8');

xml2js.parseString(xml, { attrkey: '@',  xmlns: true }, function(err, json) {
    var xml2 = xmlbuilder.create(json,
       {version: '1.0', encoding: 'UTF-8', standalone: true}
    ).end({pretty: true, standalone: true})
});

Here's the first bit of the original XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

            ...

Here;s how xml2js parses that to JSON, this looks right to me:

{
    "a:theme": {
        "@": {
            "xmlns:a": {
                "name": "xmlns:a",
                "value": "http://schemas.openxmlformats.org/drawingml/2006/main",
                "prefix": "xmlns",
                "local": "a",
                "uri": "http://www.w3.org/2000/xmlns/"
            },
            "name": {
                "name": "name",
                "value": "Office Theme",
                "prefix": "",
                "local": "name",
                "uri": ""
            }
        },
        "@ns": {
            "uri": "http://schemas.openxmlformats.org/drawingml/2006/main",
            "local": "theme"
        },
        "a:themeElements": [
            {
                "@ns": {
                    "uri": "http://schemas.openxmlformats.org/drawingml/2006/main",
                    "local": "themeElements"
                },
                "a:clrScheme": [
                    {
                        "@": {
                            "name": {
                                "name": "name",
                                "value": "Office",
                                "prefix": "",
                                "local": "name",
                                "uri": ""
                            }
                        },
                        "@ns": {
                            "uri": "http://schemas.openxmlformats.org/drawingml/2006/main",
                            "local": "clrScheme"
                        },
                       ...

Note that in the JSON above:

the attribute (e.g. name=) are turned into keys inside an @ object and

the attribute values are turned into objects

Now here's how it looks when xmlbuilder turns it back into XML:

       ...

So there are two problems that XML builder is facing:
  * it's not recognizing the attribute names within the @ object and
  * it's not recognizing the attribute value within the attribute object

Hacking it appears that xmlbuilder wants attributes names structured like:

  `{ "@name": "Office Theme"} `

rather than

  `{ "@" : { "name" : { value: "Office Theme" }}}`

Should I configure xml2js differently, xmlbuilder differently, or is there a different pair of libraries that can parse XML -> JSON -> XML?

Body:
I came across similar requirement recently. Had to convert Yahoo weather service xml data into json object. Solved the issue with xml2js and js2xmlparser modules. Thought to share how I did here. An example which I worked out:

const https = require('https');
var parseString = require('xml2js').parseString;

https.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22surat%22)&format=xml&env=store%3A%2F%2F    datatables.org%2Falltableswithkeys', (resp) => {
    let data = '';

    // A chunk of data has been recieved.
    resp.on('data', (chunk) => {
        data += chunk;
    });

    // The whole response has been received. Print out the result.
    resp.on('end', () => {
        //console.log(JSON.parse(data).explanation);

        parseString(data, function (err, result) {
            console.log(JSON.stringify(result));
        });
    });

}).on("error", (err) => {
    console.log("Error: " + err.message);
});

After this one can use js2xmlparser for converting the obtained json to xml.

js2xmlparser.parse("weather", data);
....

here's a Github link for the detailed code: https://github.com/joshiparthin/ReNode/tree/master/soap-api