问:
How do I hide a button until all elements are clicked in HTML?
I am trying to hide a button until all required elements on the page have been clicked. I found how to hide an element until one item is clicked but not sure how to set this to hide the button until all items are clicked.

The elements I want the users to click on are accordion panels with the ID's as "collaspeone", "collaspetwo" and so on. I want the user to click on each panel (which causes them to expand) then once they have clicked on each panel, show a button on the bottom of the page which allows them to continue to the next page.

Here is the element I want to show only when every panel has been clicked on.

```<code><button id="Continue" class="btn btn-primary"><a href="AddSupplier-SubmitReq.aspx" style="color:white">Continue to Set-Up<i class="fa fa-arrow-right" aria-hidden="true"></i></a></button>
</code>```

Here is my full HTML code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%@ Page Language="C#" %>
<%@ Register tagprefix="SharePoint" namespace="Microsoft.SharePoint.WebControls" assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<meta name="WebPartPageExpansion" content="full" />
<meta charset="utf-8"/>
    <meta http-equiv="x-ua-compatible" content="ie=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <link rel="canonical" href="http://html5-templates.com/" />
 <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"/>
 <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"/>
 <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"/>
 <link rel="manifest" href="/manifest.json"/>
 <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"/>
 <meta name="theme-color" content="#ffffff"/>
    <title>MySLM Portal</title>
 <meta name="description" content="A minimalist Bootstrap theme by StartBootstrap. Contains everything you need to get started building your website. All you have to do is change the text and images.">
    <link href="css/bootstrap.min.css" rel="stylesheet"/>
    <link href="css/modern-business.css" rel="stylesheet"/>
    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
    <link href="css/footer.css" rel="stylesheet" type="text/css"/>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                        Scope

                        General Questions

                        FAQ's

                        Processes

                                Create a New Supplier

                                Update an Existing Supplier

                                Reactivate a Supplier

                                Deactivate a Supplier

                        Contact

                        Resources

                                ERS Agreement Library

                                Corp Record List

                                Sanctioned Supplier List

                                Supplier Deactivation Listing

                                RemedyForce Training

                                Select Supplier Search

                                Yammer: Source to Pay NA

                                Job Aids

                                Knowledge/Self Help Articles

                                Policies

Sourcing and Purchasing Policy

Anti-bribery Policy

Bank Account & Payment Control Policy

Competition Policy

Conflicts of Interest Policy

Country Risk Policy

Insider Trading Policy

Legal Services Policy

Supplier Code of Conduct

Trade Sanctions Policy

United states & Canada Purchasing Cards Procedure

                        Links

                                Ariba

                                P2P Business Stakeholder Library

                                RemedyForce

                 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Wait! Make Your Job Easier!

Source through CSSP!

By sourcing through CSSP you can avoid having to navigate the entire complex supplier setup process and focus on your job while CSSP works for you in the background sourcing you a supplier and having them set-up in the appropriate ERP system for your use!

                 <button class="btn btn-primary">Lets go!  </button>

                  <button type="button" class="btn btn-default" data-dismiss="modal">No, I do not want to make my job easier</button>

Set-up a New Supplier
                    First Steps

The following steps should be completed by the requester prior to submitting a request to set-up a new supplier. Failure to perform these steps may result in rejection of, or delays on your request.

                        1

                    Panel Title

Panel Body

                        2

                    Panel Title

Panel Body

                        3

                    Panel Title

Panel Body

                        4

                    Panel Title

Panel Body

                        5

                    Panel Title

Panel Body

        <button id="Continue" class="btn btn-primary hidden disabled">Continue to Set-Up</button>

Questions? Check out our FAQ's

                    Go to FAQ's!

                            Code of Conduct

                            Supplier Code of Conduct

                            Policy Center

© 2017 Cargill, Incorporated. All Rights Reserved

```

答:
Add href(It is different for each panel) on click of a panel inside an accumulator, when its length reaches 5 display your button.

var panelsClicked = [];
$('.panel').on('click', function() {
  var href = $(this).find('a').attr('href');
  if(!panelsClicked.includes(href)){
    panelsClicked.push(href);
    if(panelsClicked.length === 5) {
      $('#Continue').show();
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Content Row -->
    <div class="row">
        <div class="col-lg-12">
            <div class="panel-group" id="accordion">
            <!-- panel -->
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">

                                <table>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <span class="fa-stack fa-2x">
                                                    <i class="fa fa-circle fa-stack-2x text-primary"></i>
                                                    <i class="fa-stack-1x fa-inverse">1</i>
                                                </span>
                                            </td>
                                            <td> </td>
                                            <td style="font-size:16pt">Panel Title</td>
                                        </tr>
                                    </tbody>
                                </table>

                        </h4>
                    </div>
                    <div id="collapseOne" class="panel-collapse collapse">
                        <div class="panel-body">
                            <p>Panel Body</p>
                        </div>
                    </div>
                </div>
                <!-- /.panel -->
                <!-- panel -->
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">

                                <table>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <span class="fa-stack fa-2x">
                                                    <i class="fa fa-circle fa-stack-2x text-primary"></i>
                                                    <i class="fa-stack-1x fa-inverse">2</i>
                                                </span>
                                            </td>
                                            <td> </td>
                                            <td style="font-size:16pt">Panel Title</td>
                                        </tr>
                                    </tbody>
                                </table>

                        </h4>
                    </div>
                    <div id="collapsetwo" class="panel-collapse collapse">
                        <div class="panel-body">
                            <p>Panel Body</p>
                        </div>
                    </div>
                </div>
                <!-- /.panel -->
                <!-- panel -->
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">

                                <table>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <span class="fa-stack fa-2x">
                                                    <i class="fa fa-circle fa-stack-2x text-primary"></i>
                                                    <i class="fa-stack-1x fa-inverse">3</i>
                                                </span>
                                            </td>
                                            <td> </td>
                                            <td style="font-size:16pt">Panel Title</td>
                                        </tr>
                                    </tbody>
                                </table>

                        </h4>
                    </div>
                    <div id="collapsethree" class="panel-collapse collapse">
                        <div class="panel-body">
                            <p>Panel Body</p>

                        </div>
                    </div>
                </div>
                <!-- /.panel -->
                <!-- panel -->
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">

                                <table>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <span class="fa-stack fa-2x">
                                                    <i class="fa fa-circle fa-stack-2x text-primary"></i>
                                                    <i class="fa-stack-1x fa-inverse">4</i>
                                                </span>
                                            </td>
                                            <td> </td>
                                            <td style="font-size:16pt">Panel Title</td>
                                        </tr>
                                    </tbody>
                                </table>

                        </h4>
                    </div>
                    <div id="collapsefour" class="panel-collapse collapse">
                        <div class="panel-body">
                            <p>Panel Body</p>

                        </div>
                    </div>
                </div>
                <!-- /.panel -->
                <!-- panel -->
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">

                                <table>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <span class="fa-stack fa-2x">
                                                    <i class="fa fa-circle fa-stack-2x text-primary"></i>
                                                    <i class="fa-stack-1x fa-inverse">5</i>
                                                </span>
                                            </td>
                                            <td> </td>
                                            <td style="font-size:16pt">Panel Title</td>
                                        </tr>
                                    </tbody>
                                </table>

                        </h4>
                    </div>
                    <div id="collapsefive" class="panel-collapse collapse">
                        <div class="panel-body">
                            <p>Panel Body</p>
                        </div>
                    </div>
                </div>
                <button style="display:none;" id="Continue" class="btn btn-primary">Continue to Set-Up<i class="fa fa-arrow-right" aria-hidden="true"></i></button>
                <!-- /.panel -->

            </div>
            <!-- /.panel-group -->
        </div>
        <!-- /.col-lg-12 -->
    </div></code>```

Body:
I am trying to hide a button until all required elements on the page have been clicked. I found how to hide an element until one item is clicked but not sure how to set this to hide the button until all items are clicked.

The elements I want the users to click on are accordion panels with the ID's as "collaspeone", "collaspetwo" and so on. I want the user to click on each panel (which causes them to expand) then once they have clicked on each panel, show a button on the bottom of the page which allows them to continue to the next page.

Here is the element I want to show only when every panel has been clicked on.

<button id="Continue" class="btn btn-primary">Continue to Set-Up</button>

Here is my full HTML code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%@ Page Language="C#" %>
<%@ Register tagprefix="SharePoint" namespace="Microsoft.SharePoint.WebControls" assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<meta name="WebPartPageExpansion" content="full" />
<meta charset="utf-8"/>
    <meta http-equiv="x-ua-compatible" content="ie=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <link rel="canonical" href="http://html5-templates.com/" />
 <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"/>
 <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"/>
 <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"/>
 <link rel="manifest" href="/manifest.json"/>
 <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"/>
 <meta name="theme-color" content="#ffffff"/>
    <title>MySLM Portal</title>
 <meta name="description" content="A minimalist Bootstrap theme by StartBootstrap. Contains everything you need to get started building your website. All you have to do is change the text and images.">
    <link href="css/bootstrap.min.css" rel="stylesheet"/>
    <link href="css/modern-business.css" rel="stylesheet"/>
    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
    <link href="css/footer.css" rel="stylesheet" type="text/css"/>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                        Scope

                        General Questions

                        FAQ's

                        Processes

                                Create a New Supplier

                                Update an Existing Supplier

                                Reactivate a Supplier

                                Deactivate a Supplier

                        Contact

                        Resources

                                ERS Agreement Library

                                Corp Record List

                                Sanctioned Supplier List

                                Supplier Deactivation Listing

                                RemedyForce Training

                                Select Supplier Search

                                Yammer: Source to Pay NA

                                Job Aids

                                Knowledge/Self Help Articles

                                Policies

Sourcing and Purchasing Policy

Anti-bribery Policy

Bank Account & Payment Control Policy

Competition Policy

Conflicts of Interest Policy

Country Risk Policy

Insider Trading Policy

Legal Services Policy

Supplier Code of Conduct

Trade Sanctions Policy

United states & Canada Purchasing Cards Procedure

                        Links

                                Ariba

                                P2P Business Stakeholder Library

                                RemedyForce

                 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Wait! Make Your Job Easier!

Source through CSSP!

By sourcing through CSSP you can avoid having to navigate the entire complex supplier setup process and focus on your job while CSSP works for you in the background sourcing you a supplier and having them set-up in the appropriate ERP system for your use!

                 <button class="btn btn-primary">Lets go!  </button>

                  <button type="button" class="btn btn-default" data-dismiss="modal">No, I do not want to make my job easier</button>

Set-up a New Supplier
                    First Steps

The following steps should be completed by the requester prior to submitting a request to set-up a new supplier. Failure to perform these steps may result in rejection of, or delays on your request.

                        1

                    Panel Title

Panel Body

                        2

                    Panel Title

Panel Body

                        3

                    Panel Title

Panel Body

                        4

                    Panel Title

Panel Body

                        5

                    Panel Title

Panel Body

        <button id="Continue" class="btn btn-primary hidden disabled">Continue to Set-Up</button>

Questions? Check out our FAQ's

                    Go to FAQ's!

                            Code of Conduct

                            Supplier Code of Conduct

                            Policy Center

© 2017 Cargill, Incorporated. All Rights Reserved

Body:
Add href(It is different for each panel) on click of a panel inside an accumulator, when its length reaches 5 display your button.

var panelsClicked = [];
$('.panel').on('click', function() {
  var href = $(this).find('a').attr('href');
  if(!panelsClicked.includes(href)){
    panelsClicked.push(href);
    if(panelsClicked.length === 5) {
      $('#Continue').show();
    }
  }
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Content Row -->
    <div class="row">
        <div class="col-lg-12">
            <div class="panel-group" id="accordion">
            <!-- panel -->
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">
                            <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
                                <table>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <span class="fa-stack fa-2x">
                                                    <i class="fa fa-circle fa-stack-2x text-primary"></i>
                                                    <i class="fa-stack-1x fa-inverse">1</i>
                                                </span>
                                            </td>
                                            <td>&nbsp;</td>
                                            <td style="font-size:16pt">Panel Title</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </a>
                        </h4>
                    </div>
                    <div id="collapseOne" class="panel-collapse collapse">
                        <div class="panel-body">
                            <p>Panel Body</p>
                        </div>
                    </div>
                </div>
                <!-- /.panel -->
                <!-- panel -->
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">
                            <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapsetwo">
                                <table>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <span class="fa-stack fa-2x">
                                                    <i class="fa fa-circle fa-stack-2x text-primary"></i>
                                                    <i class="fa-stack-1x fa-inverse">2</i>
                                                </span>
                                            </td>
                                            <td>&nbsp;</td>
                                            <td style="font-size:16pt">Panel Title</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </a>
                        </h4>
                    </div>
                    <div id="collapsetwo" class="panel-collapse collapse">
                        <div class="panel-body">
                            <p>Panel Body</p>
                        </div>
                    </div>
                </div>
                <!-- /.panel -->
                <!-- panel -->
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">
                            <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapsethree">
                                <table>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <span class="fa-stack fa-2x">
                                                    <i class="fa fa-circle fa-stack-2x text-primary"></i>
                                                    <i class="fa-stack-1x fa-inverse">3</i>
                                                </span>
                                            </td>
                                            <td>&nbsp;</td>
                                            <td style="font-size:16pt">Panel Title</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </a>
                        </h4>
                    </div>
                    <div id="collapsethree" class="panel-collapse collapse">
                        <div class="panel-body">
                            <p>Panel Body</p>

                        </div>
                    </div>
                </div>
                <!-- /.panel -->
                <!-- panel -->
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">
                            <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapsefour">
                                <table>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <span class="fa-stack fa-2x">
                                                    <i class="fa fa-circle fa-stack-2x text-primary"></i>
                                                    <i class="fa-stack-1x fa-inverse">4</i>
                                                </span>
                                            </td>
                                            <td>&nbsp;</td>
                                            <td style="font-size:16pt">Panel Title</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </a>
                        </h4>
                    </div>
                    <div id="collapsefour" class="panel-collapse collapse">
                        <div class="panel-body">
                            <p>Panel Body</p>

                        </div>
                    </div>
                </div>
                <!-- /.panel -->
                <!-- panel -->
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">
                            <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapsefive">
                                <table>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <span class="fa-stack fa-2x">
                                                    <i class="fa fa-circle fa-stack-2x text-primary"></i>
                                                    <i class="fa-stack-1x fa-inverse">5</i>
                                                </span>
                                            </td>
                                            <td>&nbsp;</td>
                                            <td style="font-size:16pt">Panel Title</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </a>
                        </h4>
                    </div>
                    <div id="collapsefive" class="panel-collapse collapse">
                        <div class="panel-body">
                            <p>Panel Body</p>
                        </div>
                    </div>
                </div>
                <button style="display:none;" id="Continue" class="btn btn-primary"><a href="AddSupplier-SubmitReq.aspx" style=" color:white">Continue to Set-Up<i class="fa fa-arrow-right" aria-hidden="true"></i></a></button>
                <!-- /.panel -->

            </div>
            <!-- /.panel-group -->
        </div>
        <!-- /.col-lg-12 -->
    </div>


来源: stackexchange

问:
How can I close the microphone/camera popup in Python / Selenium?

I want to click block. I tried this:

```<code>alert = browser.switch_to_alert()
alert.dismiss();
</code>```

However it says that there is no alert open. I think it's not considered as an alert?

答:
To get rid of the Microphone/Camera popup you can use the following arguments from ChromeOptions Class:

Java solution:

```<code>ChromeOptions options = new ChromeOptions();
options.addArguments("allow-file-access-from-files");
options.addArguments("use-fake-device-for-media-stream");
options.addArguments("use-fake-ui-for-media-stream");
WebDriver driver = new ChromeDriver(options);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to click block. I tried this:

alert = browser.switch_to_alert()
alert.dismiss();

However it says that there is no alert open. I think it's not considered as an alert?

Body:
To get rid of the Microphone/Camera popup you can use the following arguments from ChromeOptions Class:

Java solution:

ChromeOptions options = new ChromeOptions();
options.addArguments("allow-file-access-from-files");
options.addArguments("use-fake-device-for-media-stream");
options.addArguments("use-fake-ui-for-media-stream");
WebDriver driver = new ChromeDriver(options);

ContentLicense: CC BY-SA 4.0


问:
Migrating from Unity Container 2.0 to Unity Container 5
So, my app was using Unity Container v2 for dependency injection. Now I'm migrating it to 5+ using NUGET packages, however I'm having issues regarding the classes resolution.

```<code>var searchClient = IocContainer.Resolve<DocumentSearch>();
</code>```

Is giving me

The non-generic method 'IUnityContainer.Resolve(Type, string, params ResolverOverride[])' cannot be used with type arguments   App.Super.Web.App   D:\Repo\git1601\App.Super.Web.App\API\ApiControllers\DocumentsController.cs

I've changed the imports from Microsoft.Pratices.Unity to Unity only as the packages changed, but still its not working. Any ideas ?

答:
This works with last Unity downloaded from NuGet (5.3.2)

```<code>using Unity;

namespace ConsoleApplication1
{
    public class Foo
    {
    }

    class Program
    {
        static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();
            var f = container.Resolve<Foo>();
        }
    }
}
</code>```

Note that Resolve<T> is an extension method and while it is defined in the very same namespace (Unity), your compiler has to support extension methods.

Aren't you compiling this with a very old C#2 compiler where extension methods are not available?

Another possible reason is that you don't have the Unity.Abstractions on your reference list. Note that while UnityContainer type is defined in the Unity.Container assembly, the extension method is defined in the other assembly (installing from NuGet installs both, though).

Make sure both assemblies are referenced in the project you call the extension method, then.

Body:
So, my app was using Unity Container v2 for dependency injection. Now I'm migrating it to 5+ using NUGET packages, however I'm having issues regarding the classes resolution.

var searchClient = IocContainer.Resolve<DocumentSearch>();

Is giving me

The non-generic method 'IUnityContainer.Resolve(Type, string, params ResolverOverride[])' cannot be used with type arguments   App.Super.Web.App   D:\Repo\git1601\App.Super.Web.App\API\ApiControllers\DocumentsController.cs

I've changed the imports from Microsoft.Pratices.Unity to Unity only as the packages changed, but still its not working. Any ideas ?

Body:
This works with last Unity downloaded from NuGet (5.3.2)

using Unity;

namespace ConsoleApplication1
{
    public class Foo
    {
    }

    class Program
    {
        static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();
            var f = container.Resolve<Foo>();
        }
    }
}

Note that Resolve<T> is an extension method and while it is defined in the very same namespace (Unity), your compiler has to support extension methods.

Aren't you compiling this with a very old C#2 compiler where extension methods are not available?

Another possible reason is that you don't have the Unity.Abstractions on your reference list. Note that while UnityContainer type is defined in the Unity.Container assembly, the extension method is defined in the other assembly (installing from NuGet installs both, though).

Make sure both assemblies are referenced in the project you call the extension method, then.


问:
Ignoring "es6!" file prefix in webpack
We have a bunch of legacy code that's importing ES6 modules using

import x from 'es6!xpath'

We can't actually change those at the moment so I need webpack to basically ignore the es6! prefix at build time and act as if I'd just done

import x from 'xpath'

Is there anyway of doing that?

答:
This is a bit of a hack but add this to your webpack.config where the alias overwrites the es6!

```<code>const config = {
  resolve: {
    alias: {
      'es6!': ''
    },
    ...
  },
  ...
}
</code>```

Title: Ignoring "es6!" file prefix in webpack

Body:
This is a bit of a hack but add this to your webpack.config where the alias overwrites the es6!

const config = {
  resolve: {
    alias: {
      'es6!': ''
    },
    ...
  },
  ...
}


问:
zxing barcode not displaying any text
I made Barcode generator using ZXing Library but when barcode generate then it wont display text below barcode like

```<code>try {

    Map<EncodeHintType, Object> hints = null;
    hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
    hints.put(EncodeHintType.CHARACTER_SET, "ABC-abc-1234");

    BitMatrix bitMatrix = new Code128Writer().encode("ABC-abc-1234", BarcodeFormat.CODE_128, 350, 150, hints);

    int width = bitMatrix.getWidth();
    int height = bitMatrix.getHeight();
    int[] pixels = new int[width * height];
    // All are 0, or black, by default
    for (int y = 0; y < height; y++) {
        int offset = y * width;
        for (int x = 0; x < width; x++) {
            pixels[offset + x] = bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE;
        }
    }

    Bitmap bitmap = Bitmap.createBitmap(width, height,
            Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    mImageView.setImageBitmap(bitmap);
} catch (Exception e) {
    // TODO: handle exception
}
</code>```

答:
Maybe it's late to help you but I went through the same problem and was able to solve the following in a C#</p>

```<code>var barcodeWriter = new BarcodeWriter
{
    Format = BarcodeFormat.CODE_128,
    Options = new EncodingOptions
    {
        Height = 160,
        Width = 300,
        Margin = 0,
        PureBarcode = false
    },
    Renderer = new BitmapRenderer()
    {
        TextFont = new Font(FontFamily.GenericSerif, 15)
    }
};

var bitmap = barcodeWriter.Write("your content");
bitmap.Save(@"C:\\FULL\PATH\FILE.JPG");
</code>```

Title: zxing barcode not displaying any text

Body:
I made Barcode generator using ZXing Library but when barcode generate then it wont display text below barcode like

try {

    Map<EncodeHintType, Object> hints = null;
    hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
    hints.put(EncodeHintType.CHARACTER_SET, "ABC-abc-1234");

    BitMatrix bitMatrix = new Code128Writer().encode("ABC-abc-1234", BarcodeFormat.CODE_128, 350, 150, hints);

    int width = bitMatrix.getWidth();
    int height = bitMatrix.getHeight();
    int[] pixels = new int[width * height];
    // All are 0, or black, by default
    for (int y = 0; y < height; y++) {
        int offset = y * width;
        for (int x = 0; x < width; x++) {
            pixels[offset + x] = bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE;
        }
    }

    Bitmap bitmap = Bitmap.createBitmap(width, height,
            Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    mImageView.setImageBitmap(bitmap);
} catch (Exception e) {
    // TODO: handle exception
}

Body:
Maybe it's late to help you but I went through the same problem and was able to solve the following in a C#

var barcodeWriter = new BarcodeWriter
{
    Format = BarcodeFormat.CODE_128,
    Options = new EncodingOptions
    {
        Height = 160,
        Width = 300,
        Margin = 0,
        PureBarcode = false
    },
    Renderer = new BitmapRenderer()
    {
        TextFont = new Font(FontFamily.GenericSerif, 15)
    }
};

var bitmap = barcodeWriter.Write("your content");
bitmap.Save(@"C:\\FULL\PATH\FILE.JPG");


问:
How to implement generation of combinations in Array in Scala

I want Scala codes of a function that, given an array, generates k-combinations of the array.

Consider to generate 3-combinations of an array of 5 elements for example, the function, say computeNCK, behaves as follows:

```<code>computeNCK(Array(1,2,3,4,5),3) = Array(Array(1, 2, 3), Array(1, 2, 4), Array(1, 2, 5), Array(1, 3, 4), Array(1, 3, 5), Array(1, 4, 5), Array(2, 3, 4), Array(2, 3, 5), Array(2, 4, 5), Array(3, 4, 5))
</code>```

The program works similarly to combinations(n: Int): Iterator[List[A]] of List, but I want deal with Array.

Note I am thinking of a code that directly handle Array, but not one that first computes in other data type like List and converts it to Array (using such as toArray).

In other words, the program is like an "Array version" of the following Scala code to compute k-combinations.

```<code>  def computeNCK[A](l:List[A], n: Int): List[List[A]] =
    if (n > l.size) Nil
    else l match {
      case _ :: _ if n == 1 => l.map(List(_))
      case hd :: tl => computeNCK(tl, n - 1).map(hd :: _) ::: computeNCK(tl,n)
      case _ => Nil
  }
</code>```

答:
Can't you use the Array.combinations method?</p>

```<code>scala> Array("a","b","c", "d").combinations(2).toList
res0: List[Array[String]] = List(Array(a, b), Array(a, c), Array(a, d), Array(b, c), Array(b, d), Array(c, d))
</code>```

Body:
I want Scala codes of a function that, given an array, generates k-combinations of the array.

Consider to generate 3-combinations of an array of 5 elements for example, the function, say computeNCK, behaves as follows:

computeNCK(Array(1,2,3,4,5),3) = Array(Array(1, 2, 3), Array(1, 2, 4), Array(1, 2, 5), Array(1, 3, 4), Array(1, 3, 5), Array(1, 4, 5), Array(2, 3, 4), Array(2, 3, 5), Array(2, 4, 5), Array(3, 4, 5))

The program works similarly to combinations(n: Int): Iterator[List[A]] of List, but I want deal with Array.

Note I am thinking of a code that directly handle Array, but not one that first computes in other data type like List and converts it to Array (using such as toArray).

In other words, the program is like an "Array version" of the following Scala code to compute k-combinations.

  def computeNCK[A](l:List[A], n: Int): List[List[A]] =
    if (n > l.size) Nil
    else l match {
      case _ :: _ if n == 1 => l.map(List(_))
      case hd :: tl => computeNCK(tl, n - 1).map(hd :: _) ::: computeNCK(tl,n)
      case _ => Nil
  }

Body:
Can't you use the Array.combinations method?

scala> Array("a","b","c", "d").combinations(2).toList
res0: List[Array[String]] = List(Array(a, b), Array(a, c), Array(a, d), Array(b, c), Array(b, d), Array(c, d))


问:
PubSub framework + Core Data?
Is it possible to persist PubSub framework objects in a Core Data persistent store? Or is there a better way to do this...? I'm working on an RSS reader and looking for ways to cache RSS/Atom feeds retrieved by PubSub..

Thanks in advance

答:
there is an example in the mac developer site regarding reading news feeds. The sample code can be downloaded by clicking here. Hope it will be useful for you.

here is another example by Colin Wheeler

ContentLicense: CC BY-SA 2.5

Title: PubSub framework + Core Data?


问:
Spring-boot config properties to avoid use of beans
For now I have this code on my boot class

```<code>@Bean
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource bundle = new ReloadableResourceBundleMessageSource();
    bundle.setBasename("/WEB-INF/messages");
    bundle.setDefaultEncoding("UTF-8");
    bundle.setCacheSeconds(1);
    return bundle;

}

@Bean
public LocalValidatorFactoryBean validator() {
    LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
    bean.setValidationMessageSource(messageSource());
    return bean;
}
</code>```

I want to know if it´s possible to do that via properties like we do with dataSource and how to do it!

答:
From the spring-boot docs </p>

```<code># INTERNATIONALIZATION (MessageSourceAutoConfiguration)
spring.messages.always-use-message-format=false # Set whether to always apply the MessageFormat rules, parsing even messages without arguments.
spring.messages.basename=messages # Comma-separated list of basenames, each following the ResourceBundle convention.
spring.messages.cache-seconds=-1 # Loaded resource bundle files cache expiration, in seconds. When set to -1, bundles are cached forever.
spring.messages.encoding=UTF-8 # Message bundles encoding.
spring.messages.fallback-to-system-locale=true # Set whether to fall back to the system Locale if no files for a specific Locale have been found.
</code>```

Body:
For now I have this code on my boot class

@Bean
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource bundle = new ReloadableResourceBundleMessageSource();
    bundle.setBasename("/WEB-INF/messages");
    bundle.setDefaultEncoding("UTF-8");
    bundle.setCacheSeconds(1);
    return bundle;

}

@Bean
public LocalValidatorFactoryBean validator() {
    LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
    bean.setValidationMessageSource(messageSource());
    return bean;
}

I want to know if it´s possible to do that via properties like we do with dataSource and how to do it!

Body:
From the spring-boot docs

# INTERNATIONALIZATION (MessageSourceAutoConfiguration)
spring.messages.always-use-message-format=false # Set whether to always apply the MessageFormat rules, parsing even messages without arguments.
spring.messages.basename=messages # Comma-separated list of basenames, each following the ResourceBundle convention.
spring.messages.cache-seconds=-1 # Loaded resource bundle files cache expiration, in seconds. When set to -1, bundles are cached forever.
spring.messages.encoding=UTF-8 # Message bundles encoding.
spring.messages.fallback-to-system-locale=true # Set whether to fall back to the system Locale if no files for a specific Locale have been found.


问:
How to Hide default help_text fom date fields in django admin
I have a django model that has one date field.

```<code>class Employee(AbstractUser):
    dob = models.DateField(verbose_name="Date of Birth", null=True)
</code>```

when i register this model in admin site and display this field on the form during update, I see this default text for date fields.

How can i remove this default help_text
Note: You are 5.5 hours ahead of server time

I tried to override the help_text for date feild but it didn't work.

```<code>dob = models.DateField(verbose_name="Date of Birth", null=True, help_text='')
</code>```

答:
First of all,  Note: You are 5.5 hours ahead of server time isn't your provided help_text. You can check this after providing a different help_text to models.py.

How to remove this Note ?
Assuming your server running on Asia/Kolkata timezone and you are declared TIME_ZONE=UTC in settings.py. In order to remove that Note from admin page, you have to set  TIME_ZONE=Asia/Kolkata

Body:
I have a django model that has one date field.

class Employee(AbstractUser):
    dob = models.DateField(verbose_name="Date of Birth", null=True)

when i register this model in admin site and display this field on the form during update, I see this default text for date fields.

How can i remove this default help_text
Note: You are 5.5 hours ahead of server time

I tried to override the help_text for date feild but it didn't work.

dob = models.DateField(verbose_name="Date of Birth", null=True, help_text='')


问:
Pandas: apply different functions to different columns
When using df.mean() I get a result where the mean for each column is given. Now let's say I want the mean of the first column, and the sum of the second. Is there a way to do this? I don't want to have to disassemble and reassemble the DataFrame.

My initial idea was to do something along the lines of pandas.groupby.agg() like so:

```<code>df = pd.DataFrame(np.random.random((10,2)), columns=['A','B'])
df.apply({'A':np.mean, 'B':np.sum}, axis=0)

Traceback (most recent call last):

  File "<ipython-input-81-265d3e797682>", line 1, in <module>
    df.apply({'A':np.mean, 'B':np.sum}, axis=0)

  File "C:\Users\Patrick\Anaconda\lib\site-packages\pandas\core\frame.py", line 3471, in apply
    return self._apply_standard(f, axis, reduce=reduce)

  File "C:\Users\Patrick\Anaconda\lib\site-packages\pandas\core\frame.py", line 3560, in _apply_standard
    results[i] = func(v)

TypeError: ("'dict' object is not callable", u'occurred at index A')
</code>```

But clearly this doesn't work. It seems like passing a dict would be an intuitive way of doing this, but is there another way (again without disassembling and reassembling the DataFrame)?

答:
I think you can use the agg method with a dictionary as the argument. For example:

```<code>df = pd.DataFrame({'A': [0, 1, 2], 'B': [3, 4, 5]})

df =
A   B
0   0   3
1   1   4
2   2   5

df.agg({'A': 'mean', 'B': sum})

A     1.0
B    12.0
dtype: float64
</code>```

To add, it seems the example provided in the question also works now (as of version 1.5.3).

```<code>import numpy as np

df = pd.DataFrame(np.random.random((10,2)), columns=['A','B'])
df.apply({'A':np.mean, 'B':np.sum}, axis=0)

A    0.495771
B    5.939556
dtype: float64
</code>```

Body:
When using df.mean() I get a result where the mean for each column is given. Now let's say I want the mean of the first column, and the sum of the second. Is there a way to do this? I don't want to have to disassemble and reassemble the DataFrame.

My initial idea was to do something along the lines of pandas.groupby.agg() like so:

df = pd.DataFrame(np.random.random((10,2)), columns=['A','B'])
df.apply({'A':np.mean, 'B':np.sum}, axis=0)

Traceback (most recent call last):

  File "<ipython-input-81-265d3e797682>", line 1, in <module>
    df.apply({'A':np.mean, 'B':np.sum}, axis=0)

  File "C:\Users\Patrick\Anaconda\lib\site-packages\pandas\core\frame.py", line 3471, in apply
    return self._apply_standard(f, axis, reduce=reduce)

  File "C:\Users\Patrick\Anaconda\lib\site-packages\pandas\core\frame.py", line 3560, in _apply_standard
    results[i] = func(v)

TypeError: ("'dict' object is not callable", u'occurred at index A')

But clearly this doesn't work. It seems like passing a dict would be an intuitive way of doing this, but is there another way (again without disassembling and reassembling the DataFrame)?

Body:
I think you can use the agg method with a dictionary as the argument. For example:

df = pd.DataFrame({'A': [0, 1, 2], 'B': [3, 4, 5]})

df =
A   B
0   0   3
1   1   4
2   2   5

df.agg({'A': 'mean', 'B': sum})

A     1.0
B    12.0
dtype: float64

To add, it seems the example provided in the question also works now (as of version 1.5.3).

import numpy as np

df = pd.DataFrame(np.random.random((10,2)), columns=['A','B'])
df.apply({'A':np.mean, 'B':np.sum}, axis=0)

A    0.495771
B    5.939556
dtype: float64


问:
Xamarin.Forms UI Testing- Timed out waiting for keyboard
After Selecting Hardware->Keyboard->Toggle Software Keyboard still its not working.

Error while performing EnterText(Marked("Password"), "asdfg")

  Exception: System.TimeoutException: Timed out waiting for keyboard.

  at Xamarin.UITest.Shared.WaitForHelper.WaitFor (System.Func 1[TResult]
  predicate, System.String timeoutMessage, System.Nullable 1[T] timeout,
  System.Nullable 1[T] retryFrequency, System.Nullable 1[T] postTimeout)
  [0x000ff] in <40cdba9629c64993881ff8259cae4300>:0

  at Xamarin.UITest.iOS.iOSApp+c__AnonStorey6.<>m__0 ()
  [0x00165] in <40cdba9629c64993881ff8259cae4300>:0

  at Xamarin.UITest.Utils.ErrorReporting.With (System.Action func,
  System.Object[] args, System.String memberName) [0x00006] in
  <40cdba9629c64993881ff

答: When this happened to me I had to reset the sim. It was happening frequently until I upgraded to xcode 9.</p>


问:
How can i call another activity from a GridView?
i have gridview in my app. and i have 6 items in it. i want call another actvity when click item. how can i do it? here is my code. help me pls.
now when i click item i can show message with toast. but i want run another activity help me pls.</p>

```<code>public class GridViewImageTextActivity extends AppCompatActivity {

    GridView androidGridView;

    String[] gridViewString = {
            "Hesapla", "Geçmiş", "Paylaş", "Geribildirim", "Sıralama", "Beğen",

    } ;
    int[] gridViewImageId = {
            R.drawable.hesap, R.drawable.gecmis, R.drawable.paylas, R.drawable.geribildirim, R.drawable.siralama, R.drawable.begen

    };

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

        CustomGridViewActivity adapterViewAndroid = new CustomGridViewActivity(GridViewImageTextActivity.this, gridViewString, gridViewImageId);
        androidGridView=(GridView)findViewById(R.id.grid_view_image_text);
        androidGridView.setAdapter(adapterViewAndroid);
        androidGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int i, long id) {
                Toast.makeText(GridViewImageTextActivity.this, "GridView Item: " + gridViewString[+i], Toast.LENGTH_LONG).show();
            }
        });

    }
}
</code>```

答:
You have to create class of another activity, add this activity to AndroidManifest.xml file and start like this:

```<code>@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
    Context context = GridViewImageTextActivity.this;
    Intent intent = null;
        switch (position) {
            case 0:
                intent = new Intent(context, FirstActivity.class);
                startActivity(intent);
                return;
            case 1:
                intent = new Intent(context, SecondActivity.class);
                startActivity(intent);
                return;
            case 2:
                // start another activity
                return;
            // and so on
        }
}
</code>```

Body:
i have gridview in my app. and i have 6 items in it. i want call another actvity when click item. how can i do it? here is my code. help me pls.
now when i click item i can show message with toast. but i want run another activity help me pls.

public class GridViewImageTextActivity extends AppCompatActivity {

    GridView androidGridView;

    String[] gridViewString = {
            "Hesapla", "Geçmiş", "Paylaş", "Geribildirim", "Sıralama", "Beğen",

    } ;
    int[] gridViewImageId = {
            R.drawable.hesap, R.drawable.gecmis, R.drawable.paylas, R.drawable.geribildirim, R.drawable.siralama, R.drawable.begen

    };

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

        CustomGridViewActivity adapterViewAndroid = new CustomGridViewActivity(GridViewImageTextActivity.this, gridViewString, gridViewImageId);
        androidGridView=(GridView)findViewById(R.id.grid_view_image_text);
        androidGridView.setAdapter(adapterViewAndroid);
        androidGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int i, long id) {
                Toast.makeText(GridViewImageTextActivity.this, "GridView Item: " + gridViewString[+i], Toast.LENGTH_LONG).show();
            }
        });

    }
}

Body:
You have to create class of another activity, add this activity to AndroidManifest.xml file and start like this:

@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
    Context context = GridViewImageTextActivity.this;
    Intent intent = null;
        switch (position) {
            case 0:
                intent = new Intent(context, FirstActivity.class);
                startActivity(intent);
                return;
            case 1:
                intent = new Intent(context, SecondActivity.class);
                startActivity(intent);
                return;
            case 2:
                // start another activity
                return;
            // and so on
        }
}


问:
How to create a Wufoo-like (form builder) web application with JQuery and Rails?
I'm looking for some guidance on how to implement a Wufoo-like builder in a Rails 3 application with JQuery on the client side. Basically allow a user to build something (a form in the case of Wufoo) in "offline" mode then save all user edits to the server in one batch by clicking a Save button or similar (e.g. could be an auto-save triggered by the browser every 30s or so).

I'm leaning towards using the HTML5 local storage at this point. The "builder" would essentially store user edits locally in the browser local storage in JSON format. A click on the Save button would then HTTP Post the content of the local storage to the Rails app, again in JSON format. Does this sound about right? Any advice, suggestions?

Some additional considerations/questions:

What about older browsers that do not support HTML5? Should there be a fallback plan that uses cookie storage?

Any JQuery plugin that can help with some of this? e.g. abstract HTML5 local storage as primary storage and cookie storage as secondary/fallback storage.

Any Rails-specific considerations to be aware of?

Note: The following question addresses WYSIWYG form builder specifically and doesn't really provide any good solution.
Creating WYSIWYG form builder (á la Wufoo) in Rails

Thanks!

答:
Here's the design I ended up implementing. I'm far from having a complete solution but I think it's a good start.

Data Model

In my case users need to be able to build a list of tasks where tasks can have different types and therefore attributes. Tasks can also embed additional objects. Similar to a form builder in a sense although I'm dealing with a deeper hierarchy of nested objects. The key here is to make sure that your back-end application only exposes objects that pertain to your application domain (in the sense of Domain Driven Design) so that your client-side code doesn't spend time refactoring data after deserializing it from a server call and before serializing it in preparation for a Save. To that extent I had to make a few changes to my server-side presentation layer but as a result I think my client-side code is cleaner and more focused on processing actual user events.

Data Serialization

I chose JSON as the data-interchange format. On the client-side I have two functions that handle the data serialization and deserialization. The implementation is pretty straight forward (in part thanks to some of the changes I made to expose domain model objects). I pasted a simplified version below. Only challenge was that the _method parameter used by Rails to handle PUT requests does not seem to work with a JSON Content-Type. See Using HTTP PUT to send JSON with Jquery and Rails 3

```<code>var todoList = {};

$.getJSON("/users/123/todolists/456.json", function(data) {
  loadTodoList(data);
  ...
});

function loadTodoList(data) {
  todoList = data.todoList;
}

function saveTodoList() {
  $.ajax({
    type: 'POST',
    url: "/users/123/todolists/456",
    data: JSON.stringify({ todoList: todoList }),
    contentType: 'application/json',
    dataType: 'script', // could be "json", "html" too
    beforeSend: function(xhr){
      xhr.setRequestHeader("X-Http-Method-Override", "put");
    }
  });
}
</code>```

On the server-side, Rails makes it easy to handle JSON too (serialization and deserialization of JSON is performed automatically and transparently by the framework). I just overrode the to_json() method on my TodoList model to avoid passing back and forth useless data (e.g. create_at, modified_at attributes). Also had to make sure to include all nested objects when fetching my top-level object (i.e. TodoList).

```<code>  # TodoListsController
  def show
    @todolist = TodoList.find_by_id(params[:id], :include => [:tasks, ...])
    respond_to do |format|
      format.json do
        render :json => @todolist.to_json
      end
    end
  end

  # TodoList model
  def to_json
    super(:only => :name,
          :include => { :tasks => { :only => [:name, :description, ...],
                                    :include => ... }})
  end
</code>```

Client-side persistence

The goal here is to avoid accidentally losing user edits that haven't been saved. So far I'm directly using the HTML5 local storage (localStorage variable) but ultimately will be looking for a jQuery plugin that automatically handles falling back on cookie storage if HTML5 is not supported.

Dynamic HTML Generation

I'm relying on jQuery Template to generate HTML. The primary function of the builder is to dynamically generate HTML so this plugin comes in very handy. I've defined templates for all building blocks of my todo list model (e.g. tasks, notes, ...). The templates are invoked whenever new instances of these objects are created and need to be rendered.

I think this lays out most of the foundation. The rest is mostly hardcore Javascript to handle all user interactions with the form/todoList builder.

Body:
Here's the design I ended up implementing. I'm far from having a complete solution but I think it's a good start.

Data Model

In my case users need to be able to build a list of tasks where tasks can have different types and therefore attributes. Tasks can also embed additional objects. Similar to a form builder in a sense although I'm dealing with a deeper hierarchy of nested objects. The key here is to make sure that your back-end application only exposes objects that pertain to your application domain (in the sense of Domain Driven Design) so that your client-side code doesn't spend time refactoring data after deserializing it from a server call and before serializing it in preparation for a Save. To that extent I had to make a few changes to my server-side presentation layer but as a result I think my client-side code is cleaner and more focused on processing actual user events.

Data Serialization

I chose JSON as the data-interchange format. On the client-side I have two functions that handle the data serialization and deserialization. The implementation is pretty straight forward (in part thanks to some of the changes I made to expose domain model objects). I pasted a simplified version below. Only challenge was that the _method parameter used by Rails to handle PUT requests does not seem to work with a JSON Content-Type. See Using HTTP PUT to send JSON with Jquery and Rails 3

var todoList = {};

$.getJSON("/users/123/todolists/456.json", function(data) {
  loadTodoList(data);
  ...
});

function loadTodoList(data) {
  todoList = data.todoList;
}

function saveTodoList() {
  $.ajax({
    type: 'POST',
    url: "/users/123/todolists/456",
    data: JSON.stringify({ todoList: todoList }),
    contentType: 'application/json',
    dataType: 'script', // could be "json", "html" too
    beforeSend: function(xhr){
      xhr.setRequestHeader("X-Http-Method-Override", "put");
    }
  });
}

On the server-side, Rails makes it easy to handle JSON too (serialization and deserialization of JSON is performed automatically and transparently by the framework). I just overrode the to_json() method on my TodoList model to avoid passing back and forth useless data (e.g. create_at, modified_at attributes). Also had to make sure to include all nested objects when fetching my top-level object (i.e. TodoList).

  # TodoListsController
  def show
    @todolist = TodoList.find_by_id(params[:id], :include => [:tasks, ...])
    respond_to do |format|
      format.json do
        render :json => @todolist.to_json
      end
    end
  end

  # TodoList model
  def to_json
    super(:only => :name,
          :include => { :tasks => { :only => [:name, :description, ...],
                                    :include => ... }})
  end

Client-side persistence

The goal here is to avoid accidentally losing user edits that haven't been saved. So far I'm directly using the HTML5 local storage (localStorage variable) but ultimately will be looking for a jQuery plugin that automatically handles falling back on cookie storage if HTML5 is not supported.

Dynamic HTML Generation

I'm relying on jQuery Template to generate HTML. The primary function of the builder is to dynamically generate HTML so this plugin comes in very handy. I've defined templates for all building blocks of my todo list model (e.g. tasks, notes, ...). The templates are invoked whenever new instances of these objects are created and need to be rendered.

I think this lays out most of the foundation. The rest is mostly hardcore Javascript to handle all user interactions with the form/todoList builder.


问:
Pygame - Count Mouse Clicks
I am continuing my progress with python and pygames. I am trying to count the number of mouse clicks when the color changes. For some reason, it is only counting 0 or 1, but nothing more.

```<code>if mouseClicked:
    #I want to count the number of clicks when the color changes
    if event.button == 1:
        countMouseClick = countMouseClick + 1
        #Change the window or screen display to a random integer mapped to the list.
        displayScreen.fill(otherColors[random.randint(0,3)])
</code>```

Here's my code:

```<code>#Mouse click color changer.
import pygame, random, sys
from pygame.locals import *
pygame.time.wait(1000) # 1000 ms = 1 sec.
#Initializing variables
#RGB    =     R     G      B
white   =   (255,   255,  255)
black   =   (0,     0,      0)
red     =   (255,   0,      0)
green   =   (0,     255,    0)
blue    =   (0,     0,    255)
otherColors = [black, red, green, blue]
bgcolor = otherColors[random.randint(0,3)]
width   =   640
height  =   480
fps     =   30

#Create a function and call it main().
def main():
    pygame.init()
    pygame.mixer.init()
    fpsClock = pygame.time.Clock()
    displayScreen = pygame.display.set_mode((width, height))
    pygame.display.set_caption('Mouse Click Color Changer')
    colorBoard = getRandomizedColor(otherColors)

    #Game Loop
    while True:
        #Process Input (Events)Step
        mouseClicked = False
        countMouseClick = 0
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
                print(countMouseClick)
                pygame.quit()
                sys.exit()

            elif event.type == MOUSEBUTTONDOWN:
               mouseClicked = True

        #Update Step
        if mouseClicked:
            if event.button == 1:
                countMouseClick = countMouseClick + 1
                displayScreen.fill(otherColors[random.randint(0,3)])

        #Render (Draw) Step
        #Use cases for .update() & .flip() (https://www.pygame.org/docs/tut/newbieguide.html)
        pygame.display.update()
        fpsClock.tick(fps)

def getRandomizedColor(changeColor):
    backgroundColor = []
    for color in otherColors:
        backgroundColor.append(color)
    changeColor = random.shuffle(backgroundColor)
    return changeColor

if __name__ == '__main__':
    main()
</code>```

Any help is much appreciated even an explanation on what I am doing wrong.

答:
```<code>while True:
    countMouseClick = 0
    # ... rest ...
</code>```

This way you reset value in every loop. You have to set it before while

```<code>countMouseClick = 0
while True:
    # ... rest ...
</code>```

Title: Pygame - Count Mouse Clicks

Body:
I am continuing my progress with python and pygames. I am trying to count the number of mouse clicks when the color changes. For some reason, it is only counting 0 or 1, but nothing more.

if mouseClicked:
    #I want to count the number of clicks when the color changes
    if event.button == 1:
        countMouseClick = countMouseClick + 1
        #Change the window or screen display to a random integer mapped to the list.
        displayScreen.fill(otherColors[random.randint(0,3)])

Here's my code:

#Mouse click color changer.
import pygame, random, sys
from pygame.locals import *
pygame.time.wait(1000) # 1000 ms = 1 sec.
#Initializing variables
#RGB    =     R     G      B
white   =   (255,   255,  255)
black   =   (0,     0,      0)
red     =   (255,   0,      0)
green   =   (0,     255,    0)
blue    =   (0,     0,    255)
otherColors = [black, red, green, blue]
bgcolor = otherColors[random.randint(0,3)]
width   =   640
height  =   480
fps     =   30

#Create a function and call it main().
def main():
    pygame.init()
    pygame.mixer.init()
    fpsClock = pygame.time.Clock()
    displayScreen = pygame.display.set_mode((width, height))
    pygame.display.set_caption('Mouse Click Color Changer')
    colorBoard = getRandomizedColor(otherColors)

    #Game Loop
    while True:
        #Process Input (Events)Step
        mouseClicked = False
        countMouseClick = 0
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
                print(countMouseClick)
                pygame.quit()
                sys.exit()

            elif event.type == MOUSEBUTTONDOWN:
               mouseClicked = True

        #Update Step
        if mouseClicked:
            if event.button == 1:
                countMouseClick = countMouseClick + 1
                displayScreen.fill(otherColors[random.randint(0,3)])

        #Render (Draw) Step
        #Use cases for .update() & .flip() (https://www.pygame.org/docs/tut/newbieguide.html)
        pygame.display.update()
        fpsClock.tick(fps)

def getRandomizedColor(changeColor):
    backgroundColor = []
    for color in otherColors:
        backgroundColor.append(color)
    changeColor = random.shuffle(backgroundColor)
    return changeColor

if __name__ == '__main__':
    main()

Any help is much appreciated even an explanation on what I am doing wrong.

Body:
while True:
    countMouseClick = 0
    # ... rest ...

This way you reset value in every loop. You have to set it before while

countMouseClick = 0
while True:
    # ... rest ...


问:
inserting data to 2 tables mysql php
I have two tables, reservation and users. I want the column username and password to be also inserted in users table when the user filled the form. My query for reservation table is working but not in users table.

Php code:

```<code>if(isset($_POST['submit'])){

    $sql="INSERT INTO reservation
    VALUES (null,
    '".$_POST['type']."',
    '".$_POST['title']."',
    '".$_POST['fname']."',
    '".$_POST['lname']."',
    '".$_POST['contact']."',
    '".$_POST['username']."'
    ,'".$_POST['password']."',
    '".$_POST['email']."',
    '".$_POST['address']."',
    '".$_POST['checkin']."',
    '".$_POST['checkout']."');";

    $sql .= "INSERT INTO users
    VALUES (null,'".$_POST['username']."','".$_POST['password']."','client');";

    mysqli_multi_query($conn,$sql);

    mysqli_close($conn);
    header("Location: login.php");

}
</code>```

答:
you should validate the submission of data before redirect to the next page
i'm trying your code so i create two tables :
user {id,username,password,email}
and local {id,label,description}
and it works for me

```<code><?php

$host = "localhost";

$user = "root";

$password = "";

$database = "dbtestsub";

$conn = new mysqli($host, $user, $password, $database);

if ($conn->connect_errno) {

    echo "Failed to connect to MySQL: " . $mysqli->connect_error;

}
/*
$sql="INSERT INTO reservation
VALUES (null,
'".$_POST['type']."',
'".$_POST['title']."',
'".$_POST['fname']."',
'".$_POST['lname']."',
'".$_POST['contact']."',
'".$_POST['username']."'
,'".$_POST['password']."',
'".$_POST['email']."',
'".$_POST['address']."',
'".$_POST['checkin']."',
'".$_POST['checkout']."');"; */
/*

$sql .= "INSERT INTO users
VALUES (null,'".$_POST['username']."','".$_POST['password']."','client');"; */

$sql = "INSERT INTO user
    VALUES (null,'" . new_user . "','" . yeah_bro . "','" . useremail . "');";

$sql .= "INSERT INTO local
    VALUES (null,'" . local1 . "','" . descp1 . "');";

mysqli_multi_query($conn, $sql);

mysqli_close($conn);

//      header("Location: login.php");
</code>```

so tell if there any error to check that

Title: inserting data to 2 tables mysql php

Body:
I have two tables, reservation and users. I want the column username and password to be also inserted in users table when the user filled the form. My query for reservation table is working but not in users table.

Php code:

if(isset($_POST['submit'])){

    $sql="INSERT INTO reservation
    VALUES (null,
    '".$_POST['type']."',
    '".$_POST['title']."',
    '".$_POST['fname']."',
    '".$_POST['lname']."',
    '".$_POST['contact']."',
    '".$_POST['username']."'
    ,'".$_POST['password']."',
    '".$_POST['email']."',
    '".$_POST['address']."',
    '".$_POST['checkin']."',
    '".$_POST['checkout']."');";

    $sql .= "INSERT INTO users
    VALUES (null,'".$_POST['username']."','".$_POST['password']."','client');";

    mysqli_multi_query($conn,$sql);

    mysqli_close($conn);
    header("Location: login.php");

}

Body:
you should validate the submission of data before redirect to the next page
i'm trying your code so i create two tables :
user {id,username,password,email}
and local {id,label,description}
and it works for me

<?php

$host = "localhost";

$user = "root";

$password = "";

$database = "dbtestsub";

$conn = new mysqli($host, $user, $password, $database);

if ($conn->connect_errno) {

    echo "Failed to connect to MySQL: " . $mysqli->connect_error;

}
/*
$sql="INSERT INTO reservation
VALUES (null,
'".$_POST['type']."',
'".$_POST['title']."',
'".$_POST['fname']."',
'".$_POST['lname']."',
'".$_POST['contact']."',
'".$_POST['username']."'
,'".$_POST['password']."',
'".$_POST['email']."',
'".$_POST['address']."',
'".$_POST['checkin']."',
'".$_POST['checkout']."');"; */
/*

$sql .= "INSERT INTO users
VALUES (null,'".$_POST['username']."','".$_POST['password']."','client');"; */

$sql = "INSERT INTO user
    VALUES (null,'" . new_user . "','" . yeah_bro . "','" . useremail . "');";

$sql .= "INSERT INTO local
    VALUES (null,'" . local1 . "','" . descp1 . "');";

mysqli_multi_query($conn, $sql);

mysqli_close($conn);

//      header("Location: login.php");

so tell if there any error to check that


问:
Error in sample.split in R, 'SplitRatio' parameter has to be i [0, 1]
I need to analyse negative or positive text messages, and find out which words define a positive or negative text. At this point, I need to split the data between a test set and a training set. However, this happens:

```<code>library(caTools)
split = sample.split(smsSparse$sentiment, SplitRatio = .7)
# Error in sample.split(smsSparse$sentiment, SplitRatio = 0.7) :
#   Error in sample.split: 'SplitRatio' parameter has to be i [0, 1] range or [1, length(Y)] range
</code>```

As suggested in this post, I changed "smsSparse$Negative = sms$Negative" to "smsSparse$Negative = sms$negative", but it didn't help. I aslo tried 7/10 and 0,7 instead of 0.7. Same result.

Can someone tell me why R thinks that 0.7 is not between 0 and 1?

答:
As someone mentioned correctly, this is likely an assignment error, ex spelling error, or the column does not exist or is null, or even if the column based on which you are splitting (dependent variable) is not a factor, in which case you can convert it to one.
To check quickly, you can see a summary of the smsSparse$sentiment and confirm.</p>

Body:
I need to analyse negative or positive text messages, and find out which words define a positive or negative text. At this point, I need to split the data between a test set and a training set. However, this happens:

library(caTools)
split = sample.split(smsSparse$sentiment, SplitRatio = .7)
# Error in sample.split(smsSparse$sentiment, SplitRatio = 0.7) :
#   Error in sample.split: 'SplitRatio' parameter has to be i [0, 1] range or [1, length(Y)] range

As suggested in this post, I changed "smsSparse$Negative = sms$Negative" to "smsSparse$Negative = sms$negative", but it didn't help. I aslo tried 7/10 and 0,7 instead of 0.7. Same result.

Can someone tell me why R thinks that 0.7 is not between 0 and 1?


问:
How to check if a user is logged in (how to properly use user.is_authenticated)?
I am looking over this website but just can't seem to figure out how to do this as it's not working. I need to check if the current site user is logged in (authenticated), and am trying:

```<code>request.user.is_authenticated
</code>```

despite being sure that the user is logged in, it returns just:

```<code>>
</code>```

I'm able to do other requests (from the first section in the url above), such as:

```<code>request.user.is_active
</code>```

which returns a successful response.

答:
Django 1.10+

Use an attribute, not a method:

```<code>if request.user.is_authenticated: # <-  no parentheses any more!
    # do something if the user is authenticated
</code>```

The use of the method of the same name is deprecated in Django 2.0, and is no longer mentioned in the Django documentation.

Note that for Django 1.10 and 1.11, the value of the property is a CallableBool and not a boolean, which can cause some strange bugs.
 For example, I had a view that returned JSON

```<code>return HttpResponse(json.dumps({
    "is_authenticated": request.user.is_authenticated()
}), content_type='application/json')
</code>```

that after updated to the property request.user.is_authenticated was throwing the exception TypeError: Object of type 'CallableBool' is not JSON serializable.  The solution was to use JsonResponse, which could handle the CallableBool object properly when serializing:

```<code>return JsonResponse({
    "is_authenticated": request.user.is_authenticated
})
</code>```

Body:
I am looking over this website but just can't seem to figure out how to do this as it's not working. I need to check if the current site user is logged in (authenticated), and am trying:

request.user.is_authenticated

despite being sure that the user is logged in, it returns just:

>

I'm able to do other requests (from the first section in the url above), such as:

request.user.is_active

which returns a successful response.

Body:
Django 1.10+

Use an attribute, not a method:

if request.user.is_authenticated: # <-  no parentheses any more!
    # do something if the user is authenticated

The use of the method of the same name is deprecated in Django 2.0, and is no longer mentioned in the Django documentation.

Note that for Django 1.10 and 1.11, the value of the property is a CallableBool and not a boolean, which can cause some strange bugs.
 For example, I had a view that returned JSON

return HttpResponse(json.dumps({
    "is_authenticated": request.user.is_authenticated()
}), content_type='application/json')

that after updated to the property request.user.is_authenticated was throwing the exception TypeError: Object of type 'CallableBool' is not JSON serializable.  The solution was to use JsonResponse, which could handle the CallableBool object properly when serializing:

return JsonResponse({
    "is_authenticated": request.user.is_authenticated
})


问:
Array creation causes 'Type of expression is ambiguous without more context'
I am very new to Swift. Please forgive if my question sounds stupid.

I have declared a structure as follows:

```<code>struct RecorderState
{
    var setupComplete: Bool
    var dataFormat: AudioStreamBasicDescription
    var queue: UnsafeMutablePointer<AudioQueueRef>
    var buffers: [AudioQueueBufferRef]
    var recordFile: AudioFileID
    var bufferByteSize: UInt32
    var currentPacket: Int64
    var isRunning: Bool
    var recordPacket: Int64
    var errorHandler: ((NSError) -> Void)?
}
</code>```

Now I need to write the init method of my class which initializes a structure inside it.

```<code>class SimplePCMRecorder : NSObject
{
    private var recorderState: RecorderState

    init(numberBuffers: Int)
    {
        self.recorderState = RecorderState(
            setupComplete: false,
            dataFormat: AudioStreamBasicDescription(),
            queue: UnsafeMutablePointer<AudioQueueRef>.alloc(1),
            buffers: Array<AudioQueueBufferRef>(repeating: 0, count: numberBuffers),
            recordFile:AudioFileID(),
            bufferByteSize: 0,
            currentPacket: 0,
            isRunning: false,
            recordPacket: 0,
            errorHandler: nil
        )
    }
}
</code>```

The problem is, the error,  'Type of expression is ambiguous without more context' keeps on showing on the line buffers: Array<AudioQueueBufferRef>(repeating: 0, count: numberBuffers).

I tried the other way but still the same.

From what I read from here Error: 'Type of expression is ambiguous without more context' is that the compiler does not know the type of object therefore it shows the error. But here, I already declared it.

I tried to cast it again by adding as after the constructor method but still didn't work.

I don't understand why. I have declared the type of variable of buffers to be an Array containing AudioQueueBufferRef. But how come the compiler still can't detect that?

答:
As a result of Martin R's
comment above.</p>

```<code>class SimplePCMRecorder : NSObject
{
    private var recorderState: RecorderState
    init(numberBuffers: Int)
    {

        self.recorderState = RecorderState(
            setupComplete: false,
            dataFormat: AudioStreamBasicDescription(),
            queue: UnsafeMutablePointer<AudioQueueRef>.allocate(capacity: 1),
            buffers: Array<UnsafeMutablePointer<AudioQueueBuffer>>(repeating: UnsafeMutablePointer<AudioQueueBuffer>(bitPattern: 0)! , count: numberBuffers),
            recordFile:AudioFileID(bitPattern: 0)!,
            bufferByteSize: 0,
            currentPacket: 0,
            isRunning: false,
            recordPacket: 0,
            errorHandler: nil
        )
    }
}
</code>```

Body:
I am very new to Swift. Please forgive if my question sounds stupid.

I have declared a structure as follows:

struct RecorderState
{
    var setupComplete: Bool
    var dataFormat: AudioStreamBasicDescription
    var queue: UnsafeMutablePointer<AudioQueueRef>
    var buffers: [AudioQueueBufferRef]
    var recordFile: AudioFileID
    var bufferByteSize: UInt32
    var currentPacket: Int64
    var isRunning: Bool
    var recordPacket: Int64
    var errorHandler: ((NSError) -> Void)?
}

Now I need to write the init method of my class which initializes a structure inside it.

class SimplePCMRecorder : NSObject
{
    private var recorderState: RecorderState

    init(numberBuffers: Int)
    {
        self.recorderState = RecorderState(
            setupComplete: false,
            dataFormat: AudioStreamBasicDescription(),
            queue: UnsafeMutablePointer<AudioQueueRef>.alloc(1),
            buffers: Array<AudioQueueBufferRef>(repeating: 0, count: numberBuffers),
            recordFile:AudioFileID(),
            bufferByteSize: 0,
            currentPacket: 0,
            isRunning: false,
            recordPacket: 0,
            errorHandler: nil
        )
    }
}

The problem is, the error,  'Type of expression is ambiguous without more context' keeps on showing on the line buffers: Array<AudioQueueBufferRef>(repeating: 0, count: numberBuffers).

I tried the other way but still the same.

From what I read from here Error: 'Type of expression is ambiguous without more context' is that the compiler does not know the type of object therefore it shows the error. But here, I already declared it.

I tried to cast it again by adding as after the constructor method but still didn't work.

I don't understand why. I have declared the type of variable of buffers to be an Array containing AudioQueueBufferRef. But how come the compiler still can't detect that?

Body:
As a result of Martin R's
comment above.

class SimplePCMRecorder : NSObject
{
    private var recorderState: RecorderState
    init(numberBuffers: Int)
    {

        self.recorderState = RecorderState(
            setupComplete: false,
            dataFormat: AudioStreamBasicDescription(),
            queue: UnsafeMutablePointer<AudioQueueRef>.allocate(capacity: 1),
            buffers: Array<UnsafeMutablePointer<AudioQueueBuffer>>(repeating: UnsafeMutablePointer<AudioQueueBuffer>(bitPattern: 0)! , count: numberBuffers),
            recordFile:AudioFileID(bitPattern: 0)!,
            bufferByteSize: 0,
            currentPacket: 0,
            isRunning: false,
            recordPacket: 0,
            errorHandler: nil
        )
    }
}


问:
How to write a value to a memory address in python using a T32_WriteMemory function
I am trying to automate the Trace32 functions using python. And I am trying to write a value to a memory address using T32_WriteMemory() function. Can someone help me how to go ahead with this function?

Below is the reference from the T32 Api pdf (api_remote.pdf):

```<code>int T32_WriteMemory(
   uint32_t  byteAddress
   int       access,
   uint8_t  *buffer,
   int       byteSize
);
</code>```

byteAddress : target memory address to start write

access : memory access specifier

buffer : output

byteSize : number of bytes to read

答:
To write memory from a python script via TRACE32 do the following:

Enable the port for remote control at TRACE32

Get the compiled shared libraries for TRACE32 remote access (t32api.dll/.so)

Load the t32api library in your python script (using ctypes)

Connect via the t32api library to your TRACE32 GUI

Declare the parameter types of T32_WriteMemory

Create a byte buffer with the data to write in your target endianness

Call the T32_WriteMemory from the t32api library (using ctypes)

Close the connection to TRACE32 before ending your script

In detail:

1. Enable the port for remote control at TRACE32

Add the following lines to your TRACE32 configuration file (config.t32):

```<code>RCL=NETASSIST
PORT=20000
</code>```

There must be an empty line before and after that block. Of course you can also choose an other number for port. A TRACE32 GUI started with these setting opens a UDP/IP port to listen for possible requests to remote control TRACE32.

2. Get the compiled shared libraries for TRACE32 remote access

You'll find the required shared libraries in your TRACE32 installation at <T32>/demo/api/capi/dll (On Windows this is usually C:\t32\demo\api\capi\dll) You can also download it at http://www.lauterbach.com/scripts.html (search there for "capi" or "python")

For Windows there is t32api.dll and t32api64.dll. For Linux there is t32api.so or t32api64.so. (t32api64.* is for a 64-bit python interpreter, while t32api.* is for a 32-bit python interpreter.)

In the following I assume that you place the t32api-library at the same directory than your python script.

3. Load the t32api library in your python script

```<code>import platform
import ctypes

ostype = ctypes.sizeof(ctypes.c_voidp) * 8
if (platform.system()=='Windows') or (platform.system()[0:6]=='CYGWIN') :
    # WINDOWS
    t32api = ctypes.CDLL("./t32api64.dll" if ostype==64 else "./t32api.dll")
elif platform.system()=='Darwin' :
    # Mac OS X
    t32api = ctypes.CDLL("./t32api.dylib")
else :
    # Linux
    t32api = ctypes.CDLL("./t32api64.so" if ostype==64 else  "./t32api.so")
</code>```

In the t32api-library is not at the same directory than your python script, you have to adapt the paths of course.

4. Connect via the t32api library to your TRACE32 GUI

```<code># Declare UDP/IP socket of the TRACE32 instance to access
t32api.T32_Config(b"NODE=",b"localhost")
t32api.T32_Config(b"PORT=",b"20000")

# Connect to TRACE32
error = t32api.T32_Init()
if error != 0 :
    sys.exit("Can't connect to TRACE32!")

# Select to debugger component of TRACE32 (B:: prompt)
t32api.T32_Attach(1)
</code>```

If you've chosen another port in step 1, you have to change the line t32api.T32_Config(b"PORT=",b"20000") accordingly.

5. Declare the parameter types of T32_WriteMemory

```<code>t32api.T32_WriteMemory.argtypes = [ctypes.c_uint32, ctypes.c_int, ctypes.c_char_p, ctypes.c_int]
t32api.T32_WriteMemory.restype  = ctypes.c_int
</code>```

The first line tells python that T32_WriteMemory is a C-function which has four parameters with the types uint32_t, int, char* and int.
The second line tells python that the return value is of type int.

6. Create a byte buffer with the data to write in your target endianness

```<code>wdata = 0x12345678  # <- Your own value here !
wbuffer = wdata.to_bytes(4, byteorder='little')
</code>```

Here, 0x12345678 is the value I have choose to write. My target CPU, which I debug via TRACE32, has it's memory organized in little-endian byte-order. So I've chosen "byteorder='little'" in the second line which creates the byte-buffer.

7. Call the T32_WriteMemory from the t32api library

```<code># Set parameters for the memory access
byteAddress = 0x46c8  # <- Your address here !
access      = 0x20
byteSize    = 4  # amount of bytes to write (e.g. 4 bytes)

# Write data to memory via TRACE32
error = t32api.T32_WriteMemory(byteAddress, access, wbuffer, byteSize)
if error != 0 :
    print("write failed")
</code>```

access = 0x20 enables memory access while the CPU is running (if SYStem.MemAccess is enabled in TRACE32 and the CPU supports run-time access) Set it to 0 otherwise, or see the TRACE32 API documentation (api_remote.pdf) for other values.

8. Close connection to TRACE32 before ending your script

```<code>t32api.T32_Exit()
</code>```

Reading memory goes like this:

```<code># Declare argument types of T32_T32_ReadMemory
t32api.T32_T32_ReadMemory.argtypes = [ctypes.c_uint32,ctypes.c_int, ctypes.c_char_p,ctypes.c_int]
t32api.T32_T32_ReadMemory.restype  = ctypes.c_int

# Create a buffer for the result
rbuffer = ctypes.create_string_buffer(byteSize)

# Request memory content via TRACE32
error = t32api.T32_ReadMemory(byteAddress, access, rbuffer, byteSize)
if error == 0 :
  # Extract 32-bit value in little endian order from the buffer
  data32 = int.from_bytes(rbuffer[0:4], byteorder='little')
  print("read  0x%08X from D:0x%08X" % (data32, byteAddress))
else:
  print("read failed")
</code>```

Body:
I am trying to automate the Trace32 functions using python. And I am trying to write a value to a memory address using T32_WriteMemory() function. Can someone help me how to go ahead with this function?

Below is the reference from the T32 Api pdf (api_remote.pdf):

int T32_WriteMemory(
   uint32_t  byteAddress
   int       access,
   uint8_t  *buffer,
   int       byteSize
);

byteAddress : target memory address to start write

access : memory access specifier

buffer : output

byteSize : number of bytes to read

Body:
To write memory from a python script via TRACE32 do the following:

Enable the port for remote control at TRACE32

Get the compiled shared libraries for TRACE32 remote access (t32api.dll/.so)

Load the t32api library in your python script (using ctypes)

Connect via the t32api library to your TRACE32 GUI

Declare the parameter types of T32_WriteMemory

Create a byte buffer with the data to write in your target endianness

Call the T32_WriteMemory from the t32api library (using ctypes)

Close the connection to TRACE32 before ending your script

In detail:

1. Enable the port for remote control at TRACE32

Add the following lines to your TRACE32 configuration file (config.t32):

RCL=NETASSIST
PORT=20000

There must be an empty line before and after that block. Of course you can also choose an other number for port. A TRACE32 GUI started with these setting opens a UDP/IP port to listen for possible requests to remote control TRACE32.

2. Get the compiled shared libraries for TRACE32 remote access

You'll find the required shared libraries in your TRACE32 installation at <T32>/demo/api/capi/dll (On Windows this is usually C:\t32\demo\api\capi\dll) You can also download it at http://www.lauterbach.com/scripts.html (search there for "capi" or "python")

For Windows there is t32api.dll and t32api64.dll. For Linux there is t32api.so or t32api64.so. (t32api64.* is for a 64-bit python interpreter, while t32api.* is for a 32-bit python interpreter.)

In the following I assume that you place the t32api-library at the same directory than your python script.

3. Load the t32api library in your python script

import platform
import ctypes

ostype = ctypes.sizeof(ctypes.c_voidp) * 8
if (platform.system()=='Windows') or (platform.system()[0:6]=='CYGWIN') :
    # WINDOWS
    t32api = ctypes.CDLL("./t32api64.dll" if ostype==64 else "./t32api.dll")
elif platform.system()=='Darwin' :
    # Mac OS X
    t32api = ctypes.CDLL("./t32api.dylib")
else :
    # Linux
    t32api = ctypes.CDLL("./t32api64.so" if ostype==64 else  "./t32api.so")

In the t32api-library is not at the same directory than your python script, you have to adapt the paths of course.

4. Connect via the t32api library to your TRACE32 GUI

# Declare UDP/IP socket of the TRACE32 instance to access
t32api.T32_Config(b"NODE=",b"localhost")
t32api.T32_Config(b"PORT=",b"20000")

# Connect to TRACE32
error = t32api.T32_Init()
if error != 0 :
    sys.exit("Can't connect to TRACE32!")

# Select to debugger component of TRACE32 (B:: prompt)
t32api.T32_Attach(1)

If you've chosen another port in step 1, you have to change the line t32api.T32_Config(b"PORT=",b"20000") accordingly.

5. Declare the parameter types of T32_WriteMemory

t32api.T32_WriteMemory.argtypes = [ctypes.c_uint32, ctypes.c_int, ctypes.c_char_p, ctypes.c_int]
t32api.T32_WriteMemory.restype  = ctypes.c_int

The first line tells python that T32_WriteMemory is a C-function which has four parameters with the types uint32_t, int, char* and int.
The second line tells python that the return value is of type int.

6. Create a byte buffer with the data to write in your target endianness

wdata = 0x12345678  # <- Your own value here !
wbuffer = wdata.to_bytes(4, byteorder='little')

Here, 0x12345678 is the value I have choose to write. My target CPU, which I debug via TRACE32, has it's memory organized in little-endian byte-order. So I've chosen "byteorder='little'" in the second line which creates the byte-buffer.

7. Call the T32_WriteMemory from the t32api library

# Set parameters for the memory access
byteAddress = 0x46c8  # <- Your address here !
access      = 0x20
byteSize    = 4  # amount of bytes to write (e.g. 4 bytes)

# Write data to memory via TRACE32
error = t32api.T32_WriteMemory(byteAddress, access, wbuffer, byteSize)
if error != 0 :
    print("write failed")

access = 0x20 enables memory access while the CPU is running (if SYStem.MemAccess is enabled in TRACE32 and the CPU supports run-time access) Set it to 0 otherwise, or see the TRACE32 API documentation (api_remote.pdf) for other values.

8. Close connection to TRACE32 before ending your script

t32api.T32_Exit()

Reading memory goes like this:

# Declare argument types of T32_T32_ReadMemory
t32api.T32_T32_ReadMemory.argtypes = [ctypes.c_uint32,ctypes.c_int, ctypes.c_char_p,ctypes.c_int]
t32api.T32_T32_ReadMemory.restype  = ctypes.c_int

# Create a buffer for the result
rbuffer = ctypes.create_string_buffer(byteSize)

# Request memory content via TRACE32
error = t32api.T32_ReadMemory(byteAddress, access, rbuffer, byteSize)
if error == 0 :
  # Extract 32-bit value in little endian order from the buffer
  data32 = int.from_bytes(rbuffer[0:4], byteorder='little')
  print("read  0x%08X from D:0x%08X" % (data32, byteAddress))
else:
  print("read failed")


问:
Can I include dll in exe (in Visual Studio)?

Possible Duplicate:

  .NET windows application, can it be compressed into a single .exe?

To run my App I need AxInterop.WMPLib.dll and Interop.WMPLib.dll that are located in Debug and Release folder. Is there any way to include those dlls into exe so my app is available in one file only?

答:
Yes, I left out the code to write the file out...

```<code>FileStream so=new FileStream("c:\\\wherever\\\x.dll",FileMode.Create);

so.Write(buf,0,ssize);

so.Close();
</code>```

No extra utilities required.

OwnerDisplayName: mark

Body:
Yes, I left out the code to write the file out...

FileStream so=new FileStream("c:\\\wherever\\\x.dll",FileMode.Create);

so.Write(buf,0,ssize);

so.Close();

No extra utilities required.

OwnerDisplayName: cookre


问:
Docker service failed to start application container engine on CentOS7
Running service docker start presents:

```<code>Job for docker.service failed.  See 'systemctl status docker.service' and 'journalctl -xn' for details.
</code>```

Both of those yield this error:

```<code>Failed to start Docker Application Container Engine.
</code>```

I do not have internet access on this machine, and all the similar issues were resolved with a "yum reinstall docker" or "yum install device-mapper-event-libs" or "yum install docker-selinux".  I've tried commenting out selinux under docker options but nothing changes.

What can I do?  Should I download docker-selinux for my architecture and transfer it over and manually install?

Thanks for any help.

Edit: Adding some information, this is CentOS 7 Atomic Host & Docker version 1.71

答:
In my case I tried to create a conf file, /etc/systemd/system/docker.service.d/hosts.conf with extra options but still didn't work. Finally, a reboot started docker service without any issues.
Hope this helps someone.</p>

Body:
Running service docker start presents:

Job for docker.service failed.  See 'systemctl status docker.service' and 'journalctl -xn' for details.

Both of those yield this error:

Failed to start Docker Application Container Engine.

I do not have internet access on this machine, and all the similar issues were resolved with a "yum reinstall docker" or "yum install device-mapper-event-libs" or "yum install docker-selinux".  I've tried commenting out selinux under docker options but nothing changes.

What can I do?  Should I download docker-selinux for my architecture and transfer it over and manually install?

Thanks for any help.

Edit: Adding some information, this is CentOS 7 Atomic Host & Docker version 1.71