问:
Combine arguments using double quotes
I'm making a TeamSpeak3 ServerQuery bot, command line style. I already have the commands down, but what I can't seem to wrap my head around is the arguments to a command. I use a reset() method to create a List of arguments so combining the string(s) would be easier.

For example, say I change a setting in memory for my bot name

```<code>set query name "Kyles Bot"
</code>```

But the program takes "Kyles and Bot" as two different arguments. I want them as one. How would I go about doing this?

Fields needed for reset():

```<code>// Keep String[] and 3 strings null for now, they'll be changed.
private String command, to1, to2;
private String[] to3;
private List<String> args = new ArrayList<>();
</code>```

The reset() method:

```<code>private void reset() {
            args.clear();
            to1 = line.getText();
            command = to1.split(" ")[0];
            if (to1.split(" ").length > 1) {
                to2 = to1.substring(command.length() + 1, to1.length());
                to3 = to2.split(" ");
                for (int i = 0; i < to3.length; i++) {
                    if (to3[i].isEmpty() || to3[i].startsWith(" ")) {
                        System.out.println("Argument null, command cancelled. [" + to3[i] + "]");
                        break;
                    } else {
                        args.add(to3[i]);
                    }
                }
                //EDIT2: Removed useless for loop,
                //it was my previous attempt to solve the problem.
            } else {
                //EDIT: This loop here is used to prevent AIOUB
                command = to1;
                for (int i = 0; i < 5; i++) {
                    args.add("NullElement");
                }
            }
        }
</code>```

答:
The problem is this line:

```<code>to3 = to2.split(" ");
</code>```

it splits the read command on every space, including spaces inside quoted text.

You need to split the command line properly, for example using a Regular Expression:

```<code>    // matches either a "quoted string" or a single word, both followed by any amount of whitespace
    Pattern argumentPattern = Pattern.compile("(\"([^\"]|\\\")*\"|\\S+)\\s*");

    // loop over all arguments
    Matcher m = argumentPattern.matcher(to2);
    for (int start = 0; m.find(start); start = m.end()) {

        // get a single argument and remove whitespace around it
        String argument = m.group(1).trim();

        // handle quoted arguments - remove outer quotes and unescape inner ones
        if (argument.startsWith("\""))
            argument = argument.substring(1,  argument.length() - 1).replace("\\\"", "\"");

        // ... your code that uses the argument here

    }
</code>```

Please note that this is not a complete implementation of a command line parser – if you receive arbitrary commands, you should look into libraries that do this parsing for you and can handle all the specifics properly.

PS: please use descriptive variable names instead of to1, to2, to3 etc., for example I used argument instead of to3 in my code.

Title: Combine arguments using double quotes

Body:
I'm making a TeamSpeak3 ServerQuery bot, command line style. I already have the commands down, but what I can't seem to wrap my head around is the arguments to a command. I use a reset() method to create a List of arguments so combining the string(s) would be easier.

For example, say I change a setting in memory for my bot name

set query name "Kyles Bot"

But the program takes "Kyles and Bot" as two different arguments. I want them as one. How would I go about doing this?

Fields needed for reset():

// Keep String[] and 3 strings null for now, they'll be changed.
private String command, to1, to2;
private String[] to3;
private List<String> args = new ArrayList<>();

The reset() method:

private void reset() {
            args.clear();
            to1 = line.getText();
            command = to1.split(" ")[0];
            if (to1.split(" ").length > 1) {
                to2 = to1.substring(command.length() + 1, to1.length());
                to3 = to2.split(" ");
                for (int i = 0; i < to3.length; i++) {
                    if (to3[i].isEmpty() || to3[i].startsWith(" ")) {
                        System.out.println("Argument null, command cancelled. [" + to3[i] + "]");
                        break;
                    } else {
                        args.add(to3[i]);
                    }
                }
                //EDIT2: Removed useless for loop,
                //it was my previous attempt to solve the problem.
            } else {
                //EDIT: This loop here is used to prevent AIOUB
                command = to1;
                for (int i = 0; i < 5; i++) {
                    args.add("NullElement");
                }
            }
        }

Body:
The problem is this line:

to3 = to2.split(" ");

it splits the read command on every space, including spaces inside quoted text.

You need to split the command line properly, for example using a Regular Expression:

    // matches either a "quoted string" or a single word, both followed by any amount of whitespace
    Pattern argumentPattern = Pattern.compile("(\"([^\"]|\\\")*\"|\\S+)\\s*");

    // loop over all arguments
    Matcher m = argumentPattern.matcher(to2);
    for (int start = 0; m.find(start); start = m.end()) {

        // get a single argument and remove whitespace around it
        String argument = m.group(1).trim();

        // handle quoted arguments - remove outer quotes and unescape inner ones
        if (argument.startsWith("\""))
            argument = argument.substring(1,  argument.length() - 1).replace("\\\"", "\"");

        // ... your code that uses the argument here

    }

Please note that this is not a complete implementation of a command line parser – if you receive arbitrary commands, you should look into libraries that do this parsing for you and can handle all the specifics properly.

PS: please use descriptive variable names instead of to1, to2, to3 etc., for example I used argument instead of to3 in my code.


来源: stackexchange

问:
Java DynamoDBMapper. Mapping Attribute value 'M'
I'm just getting started on my first DynamoDB project and I've been trying to read the documentation as much as possible. I think the best possibility for my project is to use the High Level DynamoDbMapper in the SDK to allow CRUD operations.

In the DynamoDB Documentation there is a type of attribute value 'M' which can be seen here
http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html

In the lower level java API, such as getItem, or getItemBatch, this value type translates to java.util.map<>.

But I can't seem to find any resources that say I can use the HigherLevel DBMapper to use this data type. Supported Data Types here.
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.DataTypes.html

I noticed at the bottom of the page it gives some insight to creating your own higher level mapping system. But I figured I would ask here first before I dove into the code for trying that. So I guess my question is... Is there anyway to use the DynamoDBMapper to work with a Java.Util.Map data type?

The only insight I could find on google was this weird github error where the user is seemingly doing exactly what I want to do.
https://github.com/aws/aws-sdk-java/issues/520

Hope this makes sense.
Ralph

答:
A bit old post but I think worth answering my experience here.
what I noticed with DynamoDB Map is that it supports map with String as key. So if you have Map it should work (with conversion schema as ConversionSchemas.V2 as explained here (basically create your DynamoDB mapper like below -

```<code>DynamoDBMapper dbMapper = new DynamoDBMapper(dbClient, DynamoDBMapperConfig.DEFAULT);
</code>```

Now the Value part of this Map should be a supported dynamoDB data-type too; that means it can have numbers, strings etc.

If you do not have key (or/and value) as String then you need to write your own converters.
Here is the example of my converter that I used for LocalDate with use of Map as key.

```<code> public class LocalDateMapConverter implements DynamoDBTypeConverter< Map<String, Long>, Map<LocalDate, Long>> {
@Override
public Map<String, Long> convert(Map<LocalDate, Long> localDateToStringMap) {
    return localDateToStringMap.entrySet()
            .stream()
            .collect(toMap(k -> k.getKey().toString(),
                    Map.Entry::getValue));
}

@Override
public Map<LocalDate, Long> unconvert(Map<String, Long> stringToLocalDateMap) {
    return stringToLocalDateMap.entrySet()
            .stream()
            .collect(toMap(k -> LocalDate.parse(k.getKey()),
                    Map.Entry::getValue));
}
}

@DynamoDBTable(tableName = "someTable")
public class SomeTable {

@DynamoDBHashKey(attributeName = "someKey")
    private String key;

@DynamoDBAttribute(attributeName = "someMapName")
    @DynamoDBTypeConverted(converter = LocalDateMapConverter.class)
    private Map<LocalDate, Long> someMap;

}
</code>```

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
A bit old post but I think worth answering my experience here.
what I noticed with DynamoDB Map is that it supports map with String as key. So if you have Map it should work (with conversion schema as ConversionSchemas.V2 as explained here (basically create your DynamoDB mapper like below -

DynamoDBMapper dbMapper = new DynamoDBMapper(dbClient, DynamoDBMapperConfig.DEFAULT);

Now the Value part of this Map should be a supported dynamoDB data-type too; that means it can have numbers, strings etc.

If you do not have key (or/and value) as String then you need to write your own converters.
Here is the example of my converter that I used for LocalDate with use of Map as key.

 public class LocalDateMapConverter implements DynamoDBTypeConverter< Map<String, Long>, Map<LocalDate, Long>> {
@Override
public Map<String, Long> convert(Map<LocalDate, Long> localDateToStringMap) {
    return localDateToStringMap.entrySet()
            .stream()
            .collect(toMap(k -> k.getKey().toString(),
                    Map.Entry::getValue));
}

@Override
public Map<LocalDate, Long> unconvert(Map<String, Long> stringToLocalDateMap) {
    return stringToLocalDateMap.entrySet()
            .stream()
            .collect(toMap(k -> LocalDate.parse(k.getKey()),
                    Map.Entry::getValue));
}
}

@DynamoDBTable(tableName = "someTable")
public class SomeTable {

@DynamoDBHashKey(attributeName = "someKey")
    private String key;

@DynamoDBAttribute(attributeName = "someMapName")
    @DynamoDBTypeConverted(converter = LocalDateMapConverter.class)
    private Map<LocalDate, Long> someMap;

}

Hope this helps.


问:
How to calculate value from a dynamically generated table and its rows using angular js?
I am trying to find the value for net worth from the table.

Net Worth = Sum(Stock Price * Shares Held)

Below is the table which is created as per user selection.

For ex: from the above table, Net Worth = (842.21*1 + 230.16*2 + 1002.2*2).

I am trying with ng-change as the networth can change every time the user adds or deletes stocks. Besides, I am also facing the css issue as networth goes down when a row is getting added to table.

Here is the plnkr.

```<code>  <section class="pickstocks">
    <label class="basiclabel">Manage Portfolio</label>
    <div class="pickstocks-align">
        <table>
            <thead>
                <tr>
                    <th>STOCK</th>
                    <th>PRICE</th>
                    <th>SHARES</th>
                    <th>WEIGHT</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="stock in stocksArray" class="portfoliokey">
                    <td>{{stock.key}}</td>
                    <td class="portfoliovalue">{{"₹" + stock.value}}</td>
                    <td class="changer">
                        <input type="button" id="num1" ng-click="decrementValue( stock.index )" value="-">
                        <input type="button" id="number{{ stock.index }}" value="1" />
                        <input type="button" ng-click="incrementValue( stock.index )" value="+" />
                    </td>
                    <td>{{stock.weight}}</td>
                </tr>
            </tbody>
        </table>
        <div class="networth">
            <h3>Networth</h3>
        </div>
    </div>
</section>
</code>```

答:
you need to calculate sum at each instance

```<code> <tr ng-repeat="stock in stocksArray" class="portfoliokey">
                    <td>{{stock.key}}</td>
                    <td ng-init="totalAmount = totalAmount + (stock.value*stock.index)" class="portfoliovalue">{{"₹" + stock.value}}</td>
                    <td class="changer">
                        <input type="button" id="num1" ng-click="decrementValue( stock.index )" value="-">
                        <input type="button" id="number{{ stock.index }}" value="1" />
                        <input type="button" ng-click="incrementValue( stock.index )" value="+" />
                    </td>
                    <td>{{stock.weight}}</td>
                </tr>
</code>```

and total will be

```<code><div class="networth">
        <h3>{{totalAmount }}</h3>
    </div>
</code>```

Body:
I am trying to find the value for net worth from the table.

Net Worth = Sum(Stock Price * Shares Held)

Below is the table which is created as per user selection.

For ex: from the above table, Net Worth = (842.21*1 + 230.16*2 + 1002.2*2).

I am trying with ng-change as the networth can change every time the user adds or deletes stocks. Besides, I am also facing the css issue as networth goes down when a row is getting added to table.

Here is the plnkr.

    Manage Portfolio

                    STOCK
                    PRICE
                    SHARES
                    WEIGHT

                    {{stock.key}}
                    {{"₹" + stock.value}}

                        <input type="button" id="num1" ng-click="decrementValue( stock.index )" value="-">
                        <input type="button" id="number{{ stock.index }}" value="1" />
                        <input type="button" ng-click="incrementValue( stock.index )" value="+" />

                    {{stock.weight}}

Networth

Body:
you need to calculate sum at each instance

 <tr ng-repeat="stock in stocksArray" class="portfoliokey">
                    <td>{{stock.key}}</td>
                    <td ng-init="totalAmount = totalAmount + (stock.value*stock.index)" class="portfoliovalue">{{"&#x20b9;" + stock.value}}</td>
                    <td class="changer">
                        <input type="button" id="num1" ng-click="decrementValue( stock.index )" value="-">
                        <input type="button" id="number{{ stock.index }}" value="1" />
                        <input type="button" ng-click="incrementValue( stock.index )" value="+" />
                    </td>
                    <td>{{stock.weight}}</td>
                </tr>

and total will be

<div class="networth">
        <h3>{{totalAmount }}</h3>
    </div>


问:
Code coverage with Mocha
I am using Mocha for testing my NodeJS application. I am not able to figure out how to use its code coverage feature. I tried googling it but did not find any proper tutorial. Please help.</p>

答:
Now (2023) the preferred way to use istanbul is via its "state of the art command line interface" nyc.

Setup

First, install it in your project with

```<code>npm i nyc --save-dev
</code>```

Then, if you have a npm based project, just change the test script inside the scripts object of your package.json file to execute code coverage of your mocha tests:

```<code>{
  "scripts": {
    "test": "nyc --reporter=text mocha"
  }
}
</code>```

Run

Now run your tests

```<code>npm test
</code>```

and you will see a table like this in your console, just after your tests output:

Customization

Html report

Just use

```<code>nyc --reporter=html
</code>```

instead of text. Now it will produce a report inside ./coverage/index.html.

Report formats

Istanbul supports a wide range of report formats. Just look at its reports library to find the most useful for you.
Just add a --reporter=REPORTER_NAME option for each format you want.
For example, with

```<code>nyc --reporter=html --reporter=text
</code>```

you will have both the console and the html report.

Don't run coverage with npm test

Just add another script in your package.json and leave the test script with only your test runner (e.g. mocha):

```<code>{
  "scripts": {
    "test": "mocha",
    "test-with-coverage": "nyc --reporter=text mocha"
  }
}
</code>```

Now run this custom script

```<code>npm run test-with-coverage
</code>```

to run tests with code coverage.

Force test failing if code coverage is low

Fail if the total code coverage is below 90%:

```<code>nyc --check-coverage --lines 90
</code>```

Fail if the code coverage of at least one file is below 90%:

```<code>nyc --check-coverage --lines 90 --per-file
</code>```

Title: Code coverage with Mocha

Body:
Now (2023) the preferred way to use istanbul is via its "state of the art command line interface" nyc.

Setup

First, install it in your project with

npm i nyc --save-dev

Then, if you have a npm based project, just change the test script inside the scripts object of your package.json file to execute code coverage of your mocha tests:

{
  "scripts": {
    "test": "nyc --reporter=text mocha"
  }
}

Run

Now run your tests

npm test

and you will see a table like this in your console, just after your tests output:

Customization

Html report

Just use

nyc --reporter=html

instead of text. Now it will produce a report inside ./coverage/index.html.

Report formats

Istanbul supports a wide range of report formats. Just look at its reports library to find the most useful for you.
Just add a --reporter=REPORTER_NAME option for each format you want.
For example, with

nyc --reporter=html --reporter=text

you will have both the console and the html report.

Don't run coverage with npm test

Just add another script in your package.json and leave the test script with only your test runner (e.g. mocha):

{
  "scripts": {
    "test": "mocha",
    "test-with-coverage": "nyc --reporter=text mocha"
  }
}

Now run this custom script

npm run test-with-coverage

to run tests with code coverage.

Force test failing if code coverage is low

Fail if the total code coverage is below 90%:

nyc --check-coverage --lines 90

Fail if the code coverage of at least one file is below 90%:

nyc --check-coverage --lines 90 --per-file

ContentLicense: CC BY-SA 4.0


问:
mysqld.exe stop working
Need your help.
I'm trying to run UwAmp on my pc, everything is working except for MySQL server which keep crashing over and over again. Apache server works well, but when I try to run MySQL server, "mysqld.exe stop working".
And not a single mysql logs.
What is the problem and how can I fix it ?

Thanks.

答:
Possible missing of VC++ 2011, 2013 or 2015 Redist?
For me, it was the case, because, moreover, I've upgraded Apache to 2.4.25 and MySql to 5.7.17</p>

Title: mysqld.exe stop working


问:
Why do comma separated placeholder rules not get applied in css?
If I apply the following rule to an input element with id #one then the placeholder color will change,

```<code>#one::-webkit-input-placeholder {
  color: red;
}
</code>```

But if I use comma separater to combine placeholder rules of different browsers then the color doesn't apply, e.g.

```<code>#two::-webkit-input-placeholder,
#two::-moz-placeholder{
  color: red;
}
</code>```

Working example:

#one::-webkit-input-placeholder {
  color: red;
}

#two::-webkit-input-placeholder,
#two::-moz-placeholder{
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="one" type="text" placeholder="one">
<input id="two" type="text" placeholder="two"></code>```

Why does the #two placeholder not change its color to red?

答:
I know it is now a complete answer, but you could add different classes for each input

#one::-webkit-input-placeholder {
  color: red;
}

#two::-webkit-input-placeholder{
  color: red;
}
#two::-moz-placeholder{
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="one" type="text" placeholder="one">
<input id="two" type="text" placeholder="two"></code>```

Body:
If I apply the following rule to an input element with id #one then the placeholder color will change,

#one::-webkit-input-placeholder {
  color: red;
}

But if I use comma separater to combine placeholder rules of different browsers then the color doesn't apply, e.g.

#two::-webkit-input-placeholder,
#two::-moz-placeholder{
  color: red;
}

Working example:

#one::-webkit-input-placeholder {
  color: red;
}

#two::-webkit-input-placeholder,
#two::-moz-placeholder{
  color: red;
}

<input id="one" type="text" placeholder="one">
<input id="two" type="text" placeholder="two">

Why does the #two placeholder not change its color to red?

Body:
I know it is now a complete answer, but you could add different classes for each input

#one::-webkit-input-placeholder {
  color: red;
}

#two::-webkit-input-placeholder{
  color: red;
}
#two::-moz-placeholder{
  color: red;
}

<input id="one" type="text" placeholder="one">
<input id="two" type="text" placeholder="two">


问:
How to start a thread to keep GUI refreshed?
I have window with button which triggers lengthy processing. I put processing in a separate thread, but -- to my surprise -- it makes GUI frozen anyway. No control is refreshed, I cannot even move the window.

So the question is how to start the thread, so it won't interfere with GUI, i.e. so the GUI would always be up to date (while processing I change the data, and GUI displays some pieces of it)?

That is how I start thread currectly:

```<code>        var thread = new Thread(doLearn);
        thread.IsBackground = true;
        thread.Start();
</code>```

Edit 1

Jon:

I don't use any locks at all

No Join calling

The UI thread is left alone -- it simply sits there

The processing is a big loop with math operations, not even allocating memory, on UI side I have controls with binding (WPF) to data, like the number of current iteration of the main loop. It should be refreshed each time the main loop "ticks". The counter of the loop is a property which triggers OnPropertyChanged with each change (classic WPF binding).

Edit 2 -- Almost there!

Ok, so Jon hit the nail at the head (who is surprises? ;-D) -- thank you! The problem comes from changing the Counter. When I used instead the Counter, local counter the GUI was refreshed -- I mean I could move windows, but... I couldn't see display of the Counter.

What I have here -- a WPF GUI, with such data-binding

```<code><TextBlock Text="{Binding Path=Counter"/>
</code>```

and I have Counter property of course which on each change sends event PropertyChanged. One of the listeners is for sure GUI.

So, Jon answer is valid "the answer", but from good design POV not exactly, because if GUI part has to pull up the info about Counter and update the display every (let's say) 3 seconds, why would anyone use data binding? For me such approach invalidates data binding idea.

I could, theoretically, pass to the processing thread the GUI dispatcher, and do all the sending in GUI thread, and it could work (I didn't try it) but it would mean tight coupling of non-GUI part and GUI part.

So far, I have no idea how to do it "right" way. The best guess so far is to create TimerDispatcher but not at GUI side but inside the processing library, and update Counter value immediately but do all the sending from time to time (I didn't try it yet though).

Small remark: I have more properties binded actually, like IsRunning, which is changed at the beginning and at the end of processing. And those changes DO affect the display correctly -- but the Counter change triggers around 3000 notifications in 3-4 seconds. So it looks like jamming problem. I did another test -- I killed the data binding partially, so notifications were sent, but GUI was not "receiving" them -- but was listening to them. In such case the GUI was also frozen.

So, I am still listening to all advices -- thank you advance for sharing.

Edit 3

The saga continues here:

How to do the processing and keep GUI refreshed using databinding?

答: There are numerous methods to run functions off the UI thread, but the easiest and generally most suitable is to look at the BackgroundWorker component. Many decent tutorials can be found. For example, here.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have window with button which triggers lengthy processing. I put processing in a separate thread, but -- to my surprise -- it makes GUI frozen anyway. No control is refreshed, I cannot even move the window.

So the question is how to start the thread, so it won't interfere with GUI, i.e. so the GUI would always be up to date (while processing I change the data, and GUI displays some pieces of it)?

That is how I start thread currectly:

        var thread = new Thread(doLearn);
        thread.IsBackground = true;
        thread.Start();

Edit 1

Jon:

I don't use any locks at all

No Join calling

The UI thread is left alone -- it simply sits there

The processing is a big loop with math operations, not even allocating memory, on UI side I have controls with binding (WPF) to data, like the number of current iteration of the main loop. It should be refreshed each time the main loop "ticks". The counter of the loop is a property which triggers OnPropertyChanged with each change (classic WPF binding).

Edit 2 -- Almost there!

Ok, so Jon hit the nail at the head (who is surprises? ;-D) -- thank you! The problem comes from changing the Counter. When I used instead the Counter, local counter the GUI was refreshed -- I mean I could move windows, but... I couldn't see display of the Counter.

What I have here -- a WPF GUI, with such data-binding

<TextBlock Text="{Binding Path=Counter"/>

and I have Counter property of course which on each change sends event PropertyChanged. One of the listeners is for sure GUI.

So, Jon answer is valid "the answer", but from good design POV not exactly, because if GUI part has to pull up the info about Counter and update the display every (let's say) 3 seconds, why would anyone use data binding? For me such approach invalidates data binding idea.

I could, theoretically, pass to the processing thread the GUI dispatcher, and do all the sending in GUI thread, and it could work (I didn't try it) but it would mean tight coupling of non-GUI part and GUI part.

So far, I have no idea how to do it "right" way. The best guess so far is to create TimerDispatcher but not at GUI side but inside the processing library, and update Counter value immediately but do all the sending from time to time (I didn't try it yet though).

Small remark: I have more properties binded actually, like IsRunning, which is changed at the beginning and at the end of processing. And those changes DO affect the display correctly -- but the Counter change triggers around 3000 notifications in 3-4 seconds. So it looks like jamming problem. I did another test -- I killed the data binding partially, so notifications were sent, but GUI was not "receiving" them -- but was listening to them. In such case the GUI was also frozen.

So, I am still listening to all advices -- thank you advance for sharing.

Edit 3

The saga continues here:

How to do the processing and keep GUI refreshed using databinding?


问:
Trying to add a custom field to the Magento page CMS
I am attempting to add a custom field to the Magento CMS page editor using this guide, but I am not able to get the additional field to display in the backend.

Here are the files I have created:

ddog_customcms.xml in /app/etc/modules

```<code><config>
    <modules>
        <ddog_customcms>
            <active>true</active>
            <codePool>local</codePool>
            <depends/>
        </ddog_customcms>
    </modules>
</config>
</code>```

config.xml in /app/code/local/ddog/customcms/etc

```<code><?xml version="1.0"?>
<config>
    <modules>
        <ddog_customcms>
            <version>1.0.0</version>
        </ddog_customcms>
    </modules>
    <global>
        <models>
            <ddog_customcms>
                <class>ddog_customcms_Model</class>
            </ddog_customcms>
        </models>
        <events>
            <adminhtml_cms_page_edit_tab_content_prepare_form>
                <observers>
                    <ddog_customcms_page_edit_tab_content>
                        <type>singleton</type>
                        <class>ddog_customcms_Model_Observer</class>
                        <method>cmsField</method>
                    </ddog_customcms_page_edit_tab_content>
                </observers>
            </adminhtml_cms_page_edit_tab_content_prepare_form>
        </events>
        <resources>
            <ddog_customcms_setup>
                <setup>
                    <module>ddog_customcms</module>
                </setup>
            </ddog_customcms_setup>
        </resources>
    </global>
</config>
</code>```

content_custom column added to cms_page database table

observer.php in /app/code/local/ddog/customcms/Model/

```<code><?php

class ddog_customcms_observer
{
    public function addNewCmsField($observer)
    {
        //get CMS model with data
        $model = Mage::registry('cms_page');
        //get form instance
        $form = $observer->getForm();
        //create new custom fieldset 'ddog_customcms_content_fieldset'
        $fieldset = $form->addFieldset('ddog_customcms_content_fieldset', array('legend'=>Mage::helper('cms')->__('Custom'),'class'=>'fieldset-wide'));
        //add new field
        $fieldset->addField('content_custom', 'text', array(
            'name'      => 'content_custom',
            'label'     => Mage::helper('cms')->__('Content Custom'),
            'title'     => Mage::helper('cms')->__('Content Custom'),
            'disabled'  => false,
            //set field value
            'value'     => $model->getContentCustom()
        ));

    }
}
</code>```

I have cleared the cache but I can't get the field to appear anywhere in the page editor. Can anybody help?

答:
here in declaration

```<code><events>
     <adminhtml_cms_page_edit_tab_content_prepare_form>
         <observers>
             <ddog_customcms_page_edit_tab_content>
                 <type>singleton</type>
                 <class>ddog_customcms_Model_Observer</class>
                 <method>cmsField</method>
             </ddog_customcms_page_edit_tab_content>
         </observers>
     </adminhtml_cms_page_edit_tab_content_prepare_form>
</events>
</code>```

you set method name cmsField but in observer you write method name addNewCmsField change it to cmsField and it will work

Body:
I am attempting to add a custom field to the Magento CMS page editor using this guide, but I am not able to get the additional field to display in the backend.

Here are the files I have created:

ddog_customcms.xml in /app/etc/modules

<config>
    <modules>
        <ddog_customcms>
            <active>true</active>
            <codePool>local</codePool>
            <depends/>
        </ddog_customcms>
    </modules>
</config>

config.xml in /app/code/local/ddog/customcms/etc

<?xml version="1.0"?>
<config>
    <modules>
        <ddog_customcms>
            <version>1.0.0</version>
        </ddog_customcms>
    </modules>
    <global>
        <models>
            <ddog_customcms>
                <class>ddog_customcms_Model</class>
            </ddog_customcms>
        </models>
        <events>
            <adminhtml_cms_page_edit_tab_content_prepare_form>
                <observers>
                    <ddog_customcms_page_edit_tab_content>
                        <type>singleton</type>
                        <class>ddog_customcms_Model_Observer</class>
                        <method>cmsField</method>
                    </ddog_customcms_page_edit_tab_content>
                </observers>
            </adminhtml_cms_page_edit_tab_content_prepare_form>
        </events>
        <resources>
            <ddog_customcms_setup>
                <setup>
                    <module>ddog_customcms</module>
                </setup>
            </ddog_customcms_setup>
        </resources>
    </global>
</config>

content_custom column added to cms_page database table

observer.php in /app/code/local/ddog/customcms/Model/

<?php

class ddog_customcms_observer
{
    public function addNewCmsField($observer)
    {
        //get CMS model with data
        $model = Mage::registry('cms_page');
        //get form instance
        $form = $observer->getForm();
        //create new custom fieldset 'ddog_customcms_content_fieldset'
        $fieldset = $form->addFieldset('ddog_customcms_content_fieldset', array('legend'=>Mage::helper('cms')->__('Custom'),'class'=>'fieldset-wide'));
        //add new field
        $fieldset->addField('content_custom', 'text', array(
            'name'      => 'content_custom',
            'label'     => Mage::helper('cms')->__('Content Custom'),
            'title'     => Mage::helper('cms')->__('Content Custom'),
            'disabled'  => false,
            //set field value
            'value'     => $model->getContentCustom()
        ));

    }
}

I have cleared the cache but I can't get the field to appear anywhere in the page editor. Can anybody help?

Body:
here in declaration

<events>
     <adminhtml_cms_page_edit_tab_content_prepare_form>
         <observers>
             <ddog_customcms_page_edit_tab_content>
                 <type>singleton</type>
                 <class>ddog_customcms_Model_Observer</class>
                 <method>cmsField</method>
             </ddog_customcms_page_edit_tab_content>
         </observers>
     </adminhtml_cms_page_edit_tab_content_prepare_form>
</events>

you set method name cmsField but in observer you write method name addNewCmsField change it to cmsField and it will work


问:
Android emulator doesn't work
I am new to Xamarin and trying to run the 'Hello, Android' application found in the introductory chapter of the official on-line Xamarin guide (link here). I use Visual Studio Community 2017 (VS).

I've created an Android Virtual Device (AVD) using Visual Studio's Android Emulator Manager tool. Here's a screenshot of the settings of the AVD I've set up:

My hardware specs are: Intel Core2 Duo 8400, 5GB of DDR2 667MHz RAM. I also use Win10 Enterprise.

Now, when try to run my application I initiate the AVD from within VS and after waiting for at least 5 minutes get the following screenshot from the Android Emulator:

How can I troubleshoot this error? As it is right now I simply cannot debug any Android application using Visual Studio and the specs described above.

Update:

I installed the exact same software on my laptop. The hardware specs of the laptop are: Core I5 4210U, 12GB DDR3 1600MHz.

Now the emulator runs smoothly, but, although I installed the same software I get a different GUI for the AVD. Anyway, problem solved. It seems the low hardware specifications was the issue.

Update 2:

It seems the AVD has problems. The build process intermittently halts at this point:

1 >  Processing: obj\Debug\res\layout\main.xml

1 >  Processing: obj\Debug\res\values\strings.xml

Also the sample application I tried to deploy (when the AVD starts) doesn't work.

答: Install Intel HAXM and enable Use Host GPU in AVD properties

Title: Android emulator doesn't work


问:
No numbered pagination custom post type
I have a problem showing numbered pagination on only one of my Wordpress pages.

```<code><?php
/**
 * Template Name: Sale template
 */
?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$args = array(
    'post_type' => array(
        'houten_vloeren', 'keramische_tegels', 'natuursteen_vloeren', 'tegels', 'laminaat', 'pvc_vloeren', 'tafels_stoelen',

    ),
    'posts_per_page' => 5,
    'post_status' => 'publish',
    'paged' => $paged,
    'meta_query' => array(
        'key' => 'prijsknaller',
        'value' => '1',
        'compare' => '==',
        //'type'    => 'date',
    ),
);
$query = new WP_Query($args);
?>

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="row">
                <div class="product-overview">

                    <?php if ($query->have_posts()) :
                        while ($query->have_posts()) : $query->the_post(); ?>
                            <div class="col-md-3">
                                <div class="featured-block">
                                    <div class="featured-block-image">
                                        <a href="<?php the_permalink(); ?>"><img src="<?php the_field('productafbeelding'); ?>"
                                                                                alt="<?php the_title(); ?>"></a>
                                    </div>
                                    <div class="featured-block-info">
                                        <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
                                        <?php if (get_field('prijs_oud')) : ?>
                                            <span class="oud"><?php the_field('prijs_oud'); ?></span>
                                        <?php endif; ?>
                                        <span class="nieuw"><?php the_field('prijs_nieuw'); ?></span> p/m<sub>2</sub>
                                    </div>
                                </div>
                            </div>

                        <?php endwhile; ?>
                    <?php endif; ?>
                    <?php the_posts_pagination(array(
                        'prev_text' => '«',
                        'next_text' => '»',
                    )); ?>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

The query returns about 70 products, so I would expect it to show at least 7 numbers. However, it does not show any pagination.

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

```<code><?php
/**
 * Template Name: Sale template
 */
?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
if ($paged == "1") {
    $args = array(
    'post_type' => array(
        'houten_vloeren', 'keramische_tegels', 'natuursteen_vloeren', 'tegels', 'laminaat', 'pvc_vloeren', 'tafels_stoelen',

    ),
    'posts_per_page' => 5,
    'post_status' => 'publish',
    'paged' => $paged,
    'offset' => 0,
    'meta_query' => array(
        'key' => 'prijsknaller',
        'value' => '1',
        'compare' => '==',
        //'type'    => 'date',
    ),
);
} else {
    $offset = $paged * 5;
    $offset = $offset - 5;
    $args = array(
    'post_type' => array(
        'houten_vloeren', 'keramische_tegels', 'natuursteen_vloeren', 'tegels', 'laminaat', 'pvc_vloeren', 'tafels_stoelen',

    ),
    'posts_per_page' => 5,
    'post_status' => 'publish',
    'paged' => $paged,
    'offset' => $offset,
    'meta_query' => array(
        'key' => 'prijsknaller',
        'value' => '1',
        'compare' => '==',
        //'type'    => 'date',
    ),
);
}

$query = new WP_Query($args);
?>

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="row">
                <div class="product-overview">

                    <?php if ($query->have_posts()) :
                        while ($query->have_posts()) : $query->the_post(); ?>
                            <div class="col-md-3">
                                <div class="featured-block">
                                    <div class="featured-block-image">
                                        <a href="<?php the_permalink(); ?>"><img src="<?php the_field('productafbeelding'); ?>"
                                                                                alt="<?php the_title(); ?>"></a>
                                    </div>
                                    <div class="featured-block-info">
                                        <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
                                        <?php if (get_field('prijs_oud')) : ?>
                                            <span class="oud"><?php the_field('prijs_oud'); ?></span>
                                        <span class="nieuw"><?php the_field('prijs_nieuw'); ?></span> p/m<sub>2</sub>
                                    </div>
                                </div>
                            </div>

                        <?php endwhile; ?>
                   <div class="pagination-grp">
                        <?php
                        $big = 999999999; // need an unlikely integer
                        //$i=1;

                        echo paginate_links(array(
                            'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
                            'format' => '?paged=%#%',
                            'current' => max(1, get_query_var('paged')),
                            'prev_text' => __('<'),
                            'next_text' => __('>'),
                            'total' => $loop->max_num_pages

                        ));
                        wp_reset_postdata();
                        endif;
                        ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Title: No numbered pagination custom post type

Body:
I have a problem showing numbered pagination on only one of my Wordpress pages.

<?php
/**
 * Template Name: Sale template
 */
?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$args = array(
    'post_type' => array(
        'houten_vloeren', 'keramische_tegels', 'natuursteen_vloeren', 'tegels', 'laminaat', 'pvc_vloeren', 'tafels_stoelen',

    ),
    'posts_per_page' => 5,
    'post_status' => 'publish',
    'paged' => $paged,
    'meta_query' => array(
        'key' => 'prijsknaller',
        'value' => '1',
        'compare' => '==',
        //'type'    => 'date',
    ),
);
$query = new WP_Query($args);
?>

                    <?php if ($query->have_posts()) :
                        while ($query->have_posts()) : $query->the_post(); ?>

                                        <a href="<?php the_permalink(); ?>"><img src="<?php the_field('productafbeelding'); ?>"
                                                                                alt="<?php the_title(); ?>">

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

                                        <?php if (get_field('prijs_oud')) : ?>
                                            <?php the_field('prijs_oud'); ?>
                                        <?php endif; ?>
                                        <?php the_field('prijs_nieuw'); ?> p/m2

                        <?php endwhile; ?>
                    <?php endif; ?>
                    <?php the_posts_pagination(array(
                        'prev_text' => '«',
                        'next_text' => '»',
                    )); ?>

The query returns about 70 products, so I would expect it to show at least 7 numbers. However, it does not show any pagination.

Body:
Replace your code with this:

<?php
/**
 * Template Name: Sale template
 */
?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
if ($paged == "1") {
    $args = array(
    'post_type' => array(
        'houten_vloeren', 'keramische_tegels', 'natuursteen_vloeren', 'tegels', 'laminaat', 'pvc_vloeren', 'tafels_stoelen',

    ),
    'posts_per_page' => 5,
    'post_status' => 'publish',
    'paged' => $paged,
    'offset' => 0,
    'meta_query' => array(
        'key' => 'prijsknaller',
        'value' => '1',
        'compare' => '==',
        //'type'    => 'date',
    ),
);
} else {
    $offset = $paged * 5;
    $offset = $offset - 5;
    $args = array(
    'post_type' => array(
        'houten_vloeren', 'keramische_tegels', 'natuursteen_vloeren', 'tegels', 'laminaat', 'pvc_vloeren', 'tafels_stoelen',

    ),
    'posts_per_page' => 5,
    'post_status' => 'publish',
    'paged' => $paged,
    'offset' => $offset,
    'meta_query' => array(
        'key' => 'prijsknaller',
        'value' => '1',
        'compare' => '==',
        //'type'    => 'date',
    ),
);
}

$query = new WP_Query($args);
?>

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="row">
                <div class="product-overview">

                    <?php if ($query->have_posts()) :
                        while ($query->have_posts()) : $query->the_post(); ?>
                            <div class="col-md-3">
                                <div class="featured-block">
                                    <div class="featured-block-image">
                                        <a href="<?php the_permalink(); ?>"><img src="<?php the_field('productafbeelding'); ?>"
                                                                                alt="<?php the_title(); ?>"></a>
                                    </div>
                                    <div class="featured-block-info">
                                        <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
                                        <?php if (get_field('prijs_oud')) : ?>
                                            <span class="oud"><?php the_field('prijs_oud'); ?></span>
                                        <span class="nieuw"><?php the_field('prijs_nieuw'); ?></span> p/m<sub>2</sub>
                                    </div>
                                </div>
                            </div>

                        <?php endwhile; ?>
                   <div class="pagination-grp">
                        <?php
                        $big = 999999999; // need an unlikely integer
                        //$i=1;

                        echo paginate_links(array(
                            'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
                            'format' => '?paged=%#%',
                            'current' => max(1, get_query_var('paged')),
                            'prev_text' => __('<'),
                            'next_text' => __('>'),
                            'total' => $loop->max_num_pages

                        ));
                        wp_reset_postdata();
                        endif;
                        ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


问:
QWizard: Confirmation on back button
I've created a wizard by subclassing QWizard, and I created pages of my wizard by subclassing QWizardPage.

I would like to show a confirmation dialog when the user press the Back button, and I want my wizard to not go to the previous page if the user press no on the confirmation dialog.

When clicking Next on a QWizard dialog, the virtual function bool validatePage() is called and allows to return false if we don't want to go to the next page (for example when there is an incomplete field).

However, when pressing Back, I don't know any way to say "Don't go back". The virtual function void cleanupPage() is called (I can ask the user confirmation here), but the Wizard will go back anyway.

Is it possible to do so?

Thanks in advance.

答:
Try to do it with void QWizardPage::setCommitPage(bool commitPage) function. This function prevents user to going back on the page. Set it on cleanupPage() of the wizard:

```<code>MyWizard::cleaupPage(int id)
{
    //Test here if 'id' is the page that you want and the do the following

    if(QMessageBox::question(...) == QMessageBox::Yes)
       this->page(id)->setCommitPage(false);
    else
       this->page(id)->setCommitPage(true);
}
</code>```

Title: QWizard: Confirmation on back button

Body:
Try to do it with void QWizardPage::setCommitPage(bool commitPage) function. This function prevents user to going back on the page. Set it on cleanupPage() of the wizard:

MyWizard::cleaupPage(int id)
{
    //Test here if 'id' is the page that you want and the do the following

    if(QMessageBox::question(...) == QMessageBox::Yes)
       this->page(id)->setCommitPage(false);
    else
       this->page(id)->setCommitPage(true);
}


问:
Setting up an environment for a frontend project
I'm working on a pure frontend project using VS Code. I have a folder for typescript and another one for sass. I'm compiling those with Gulp in separate folders for js and css.

I faced a problem when I tried to use var something = require('some-node-module'); and got an error both in typescript and browser console. I added @types for this but it didn't worked as I still got an error in browser console. I searched more and found this question, I understood what the problem is and I used Browserify from there. Now typescript is compiled without errors and I have to make a bundle everytime I change something. Is there anything I can do to get rid of Browserify and still be able to use require() in typescript. As this is my first pure frontend project I want to keep it simple and clean, not to use a lot of plugins/modules to make it work.

My tsconfig.json:

```<code>{
"files": [
    "ts/main.ts"
],
"compilerOptions": {
    "noImplicitAny": true,
    "target": "es5",
    "outDir": "js"
}
}
</code>```

Is there any way I can use types without the need to install more node modules to make it work?

答:
Every Front End project needs Browserify or Webpack (recommended) which will bundle your modules into browser compatible script. require() is nodejs' function which imports other modules/scripts but it doesn't exist in browser ecosystem.

Read about webpack here.

Body:
I'm working on a pure frontend project using VS Code. I have a folder for typescript and another one for sass. I'm compiling those with Gulp in separate folders for js and css.

I faced a problem when I tried to use var something = require('some-node-module'); and got an error both in typescript and browser console. I added @types for this but it didn't worked as I still got an error in browser console. I searched more and found this question, I understood what the problem is and I used Browserify from there. Now typescript is compiled without errors and I have to make a bundle everytime I change something. Is there anything I can do to get rid of Browserify and still be able to use require() in typescript. As this is my first pure frontend project I want to keep it simple and clean, not to use a lot of plugins/modules to make it work.

My tsconfig.json:

{
"files": [
    "ts/main.ts"
],
"compilerOptions": {
    "noImplicitAny": true,
    "target": "es5",
    "outDir": "js"
}
}

Is there any way I can use types without the need to install more node modules to make it work?


问:
How to prevent user from selecting the same value from more than one combobox in wpf
I have a simple class as such:

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

I have a List of this class in my Mainwindow.xaml.cs as such:

```<code>public List<Item> AllItems=GetAllItems();
</code>```

I have four properties of Item class in my Mainwindow.xaml.cs as such:

```<code>public Item Item1{get;set;}
public Item Item2{get;set;}
public Item Item3{get;set;}
public Item Item4{get;set;}
</code>```

This List:AllItems is databinded to four Comboboxes as under:

```<code> <ComboBox x:Name="cmbCode1" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode2" ItemsSource="{Binding AllItems}"  DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode3" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode4" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
</code>```

I have four TextBoxes corresponding to these four Comboboxes as such:

```<code><TextBlock x:Name="txtName1" Text="{Binding Item1.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName2" Text="{Binding Item2.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName3" Text="{Binding Item3.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName4" Text="{Binding Item4.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
</code>```

What i want is that the user should never be able to select the same ID from more than one combobox.
Is there some simple way that could be done,especially using xaml only?How can i hide or show the items selected/unselected from other comboboxes so that the user can't select the same ID from more than one combobox ever?
So far i have tried to send the selected Item and the entire List to a MultivalueConverter and eliminating/adding items to the Lists there itself,but this seems too meesy.Any other better idea would be appreciated.

答:
You could have a separate list for each of your ComboBoxes. You could then add a LostFocus event handler to each of them. You could use this to repopulate the lists for the other ComboBoxes to exclude the selection.

For example, if I've got 5 items in my list; initially I'll be able to select all 5 in any of my ComboBoxes. When I select Item1 in ComboBox1 the LostFocus event handler will update the lists behind ComboBoxes 2-4 to remove Item1. When I then select Item2 in ComboBox2 the LostFocus event handler will then update the lists behind ComboBoxes 3 and 4 to remove Item2. And so on...

An alternative approach might be to let the user select whatever they like and then run some kind of validation on the selected values to make sure that they're unique. This article goes through some of your options.

Personally, I'd go with the second approach; perhaps with a message above the textboxes indicating that the selection must be unique. You could indicate any errors and block any actions that rely on the selection while it's invalid but you're not having to update your data constantly which will probably lead to a smoother UI.

Body:
I have a simple class as such:

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

I have a List of this class in my Mainwindow.xaml.cs as such:

public List<Item> AllItems=GetAllItems();

I have four properties of Item class in my Mainwindow.xaml.cs as such:

public Item Item1{get;set;}
public Item Item2{get;set;}
public Item Item3{get;set;}
public Item Item4{get;set;}

This List:AllItems is databinded to four Comboboxes as under:

 <ComboBox x:Name="cmbCode1" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode2" ItemsSource="{Binding AllItems}"  DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode3" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode4" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>

I have four TextBoxes corresponding to these four Comboboxes as such:

<TextBlock x:Name="txtName1" Text="{Binding Item1.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName2" Text="{Binding Item2.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName3" Text="{Binding Item3.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName4" Text="{Binding Item4.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>

What i want is that the user should never be able to select the same ID from more than one combobox.
Is there some simple way that could be done,especially using xaml only?How can i hide or show the items selected/unselected from other comboboxes so that the user can't select the same ID from more than one combobox ever?
So far i have tried to send the selected Item and the entire List to a MultivalueConverter and eliminating/adding items to the Lists there itself,but this seems too meesy.Any other better idea would be appreciated.


问:
HTTP Connection in Iphone
Since I'm new in iphone I need help in learning about http Connections in Iphone.
Please guide me to some tutorials so that I could learn some http connections tricks in iphone and could communicate with websites.

Also please guide me through some Sample code for the following problem:
I want to send some "Hello world" text to the site and got a reply back from the Web the same word with adiition of s i.e. "Hello Worlds".. please brothers guide me through any sample code.. it's a part of my application that I'm developing in iphone.

答: The best resource is the URL Loading System Programming Guide from Apple. Using NSURLConnection section contains a number of sample codes. </p>

Title: HTTP Connection in Iphone


问:
Test integration .Net Core with TestServer return 404 not found?
I'm trying to create a Integration Test project , for test my web api .Net Core with the Microsoft sample best practice here https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing
But i don't know why, i always get a error message [404 not found], the HttpClient can't find the 'testServer' . And i'm sure my 'route' is right ["api/Registration/" + guid] , if i try on debug mode from iisexpress. it's work great

If someone have some idea to fix it, will be very gratefull. Thanks

Here is the code i use in my Integration Test project:

RegistrationIntegrationTest.cs:

```<code>[TestClass]
public class RegistrationIntegrationTest
{
    private static TestServer server;
    private static HttpClient client;

    [ClassInitialize]
    public static void ClassInitialize(TestContext context)
    {
        var basePath = PlatformServices.Default.Application.ApplicationBasePath;
        var projectPath = Path.GetFullPath(Path.Combine(basePath, "../../../../Registration"));

        var builder = new WebHostBuilder()
            .UseContentRoot(projectPath)
            .UseEnvironment(EnvironmentName.Development)
            .UseStartup<Startup>();

        server = new TestServer(builder);
        client = server.CreateClient();
    }

    private async Task<string> GetRegistrationResponse(string guid)
    {
        var request = "api/Registration/" + guid;

        var response = await client.GetAsync(request);
        response.EnsureSuccessStatusCode();

        return await response.Content.ReadAsStringAsync();
    }

    [TestMethod]
    public async Task GetRegistration()
    {
        // Act
        var responseString = await GetRegistrationResponse("A5A3CBFD-8B61-E711-80E2-00505693113A");
        // Assert
        Assert.Equals("test",
            responseString);
    }
}
</code>```

And here is my startup Class from my Integration Test project:

Startup.cs

```<code>public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            //.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            //.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();

    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddCors();
        services.AddAntiforgery();
        services.AddSingleton<IControllerActivator>(new SimpleInjectorControllerActivator(this.Container));
        services.Configure<MyAppSettings>(Configuration);
        services.UseSimpleInjectorAspNetRequestScoping(this.Container);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));

        if (env.IsDevelopment())
        {
            loggerFactory.AddDebug();
            app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
        }
        else if (env.IsStaging())
        {
            app.UseCors(builder => builder.WithOrigins("https://apitest.swisscaution.ch"));
        }
        else if (env.IsProduction())
        {
            app.UseCors(builder => builder.WithOrigins("https://internalapi.swisscaution.ch"));
        }
        else
        {
            throw new InvalidOperationException("Bad application environement.");
        }

        app.UseMvc();

        this.InitializeContainer(app);
    }
</code>```

Here is a photo of the architecture of my solution Visual Studio,
as you can see, the integration test project is separate from my web api project called 'registration'

The Exception i get:

答:
I  find finally the problem.
Is because my [ Integration Test Project ] was target the .Net Core Version , and i tried to test and host a project with .Net Framework 4.5.6 Version.
I find the solution online, i need to modify the csproj file and add this 3 config on the "PropertyGroup" section.

```<code><PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  </PropertyGroup>
</code>```

Here is the url i find : http://quabr.com/44027215/system-net-http-httpclient-microsoft-aspnetcore-testhost-testserver-createclient

Body:
I'm trying to create a Integration Test project , for test my web api .Net Core with the Microsoft sample best practice here https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing
But i don't know why, i always get a error message [404 not found], the HttpClient can't find the 'testServer' . And i'm sure my 'route' is right ["api/Registration/" + guid] , if i try on debug mode from iisexpress. it's work great

If someone have some idea to fix it, will be very gratefull. Thanks

Here is the code i use in my Integration Test project:

RegistrationIntegrationTest.cs:

[TestClass]
public class RegistrationIntegrationTest
{
    private static TestServer server;
    private static HttpClient client;

    [ClassInitialize]
    public static void ClassInitialize(TestContext context)
    {
        var basePath = PlatformServices.Default.Application.ApplicationBasePath;
        var projectPath = Path.GetFullPath(Path.Combine(basePath, "../../../../Registration"));

        var builder = new WebHostBuilder()
            .UseContentRoot(projectPath)
            .UseEnvironment(EnvironmentName.Development)
            .UseStartup<Startup>();

        server = new TestServer(builder);
        client = server.CreateClient();
    }

    private async Task<string> GetRegistrationResponse(string guid)
    {
        var request = "api/Registration/" + guid;

        var response = await client.GetAsync(request);
        response.EnsureSuccessStatusCode();

        return await response.Content.ReadAsStringAsync();
    }

    [TestMethod]
    public async Task GetRegistration()
    {
        // Act
        var responseString = await GetRegistrationResponse("A5A3CBFD-8B61-E711-80E2-00505693113A");
        // Assert
        Assert.Equals("test",
            responseString);
    }
}

And here is my startup Class from my Integration Test project:

Startup.cs

public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            //.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            //.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();

    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddCors();
        services.AddAntiforgery();
        services.AddSingleton<IControllerActivator>(new SimpleInjectorControllerActivator(this.Container));
        services.Configure<MyAppSettings>(Configuration);
        services.UseSimpleInjectorAspNetRequestScoping(this.Container);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));

        if (env.IsDevelopment())
        {
            loggerFactory.AddDebug();
            app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
        }
        else if (env.IsStaging())
        {
            app.UseCors(builder => builder.WithOrigins("https://apitest.swisscaution.ch"));
        }
        else if (env.IsProduction())
        {
            app.UseCors(builder => builder.WithOrigins("https://internalapi.swisscaution.ch"));
        }
        else
        {
            throw new InvalidOperationException("Bad application environement.");
        }

        app.UseMvc();

        this.InitializeContainer(app);
    }

Here is a photo of the architecture of my solution Visual Studio,
as you can see, the integration test project is separate from my web api project called 'registration'

The Exception i get:

Body:
I  find finally the problem.
Is because my [ Integration Test Project ] was target the .Net Core Version , and i tried to test and host a project with .Net Framework 4.5.6 Version.
I find the solution online, i need to modify the csproj file and add this 3 config on the "PropertyGroup" section.

<PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  </PropertyGroup>

Here is the url i find : http://quabr.com/44027215/system-net-http-httpclient-microsoft-aspnetcore-testhost-testserver-createclient


问:
Google maps api with infowindow not working
I'm trying to create a map with info windows that open with the user clicks on a marker. So far the code doesn't seem to be working, the map was displaying before but once I put in the code for the info window pop-ups not only did the info window not show but the map also stopped showing on my webpage. Here's the code:</p>

```<code><div id= "map"> </div>

        <script>
        var map;

            var markers=[];

        function initMap(){

            map= new google.maps.Map(document.getElementById('map'),{

                center:{ lat:40.7413549, lng:-73.9980244},
                zoom:13
            });

        var locations=[

            {title:"Park Ave Penthouse",location:{lat:40.7713024,lng:-73.9632393}},
            {title:"Chelsea Loft", location;{lat:40.7444883,lng:-73.9949465}},
            {title:"Union Square Open Floor Plan",location:{lat:40.7347062,lng:-73.984377}},
            {title:"East Village Hip Studio",location:{lat:40.7281777,lng:-73.984377}},
            {title:"TriBeCa Artsy Bachelor Pad",location:{lat:40.7195264,lng:-74.0089934}},
            {title:"Chinatown Homey Space",location:{lat:40.7180628,lng:-73.9961237}}

        ];
            var largeInfowindow= new google.maps.InfoWindow();
            var bounds= new google.maps.LatLngBounds();

            for (var i=0; i< locations.lenght;i++){

                var position = locations[i].location;
                var title = locations[i].title;

                var marker= new google.maps.Marker({

                    map: map,
                    position:position,
                    title:title,
                    animation:google.maps.Animation.Drop,
                    id:i

                  });

                    markers.push(marker);
                    bounds.extend(marker.position);
                    marker.addListner ("click",function(){

                    populateInfoWindow(this,largeInfowindow);

            });

             map.fitBounds(bounds);

                };

                markers.push(marker);

                markers.addListner("click",function(){

                    populateInfoWindow(this,largeInfoWindow);
                });

                }

            function populateInfoWindow (marker, infowindow){

                if(infowindow.marker=!marker){

                    infowindow.marker= marker;
                    infowindow.setContent("<div>"+marker.title+"</div>");

                    infowindow.open(map,marker);

                    infowindow.addListner("closeclick",function(){

                        infowindow.setMarker(null);
                    });

                }

            }

 <script async defer
               src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAvrWT4KKcsDSSGYXpxRry3m7j90pPjZgA&v=3&callback=initMap"></script>
</code>```

答:
The error is in this line:

```<code>if(infowindow.marker=!marker){ //it is "!=" and not "=!"
</code>```

Always check console for javascript errors. After infowindow code, you could not even see the mao which means you have javascript errors.

Body:
The error is in this line:

if(infowindow.marker=!marker){ //it is "!=" and not "=!"

Always check console for javascript errors. After infowindow code, you could not even see the mao which means you have javascript errors.


问:
Can xcodebuild manage automatic signing?
SUMMARY:

If you open a project in Xcode 8 with "Automatically manage signing" enabled and a new bundle ID, it will automatically create and download a provisioning profile for it. But how can I make the same thing happen with xcodebuild, so I can use it on a remote build server?

DETAILS:

I'm trying to build a Cordova app on a Mac. Cordova configures the Xcode project to use "Automatically manage signing", so I'm trying to use that.

I change the bundle ID often, so I want Cordova to be able to build it with a new bundle ID, that hasn't been used before.

But when I run cordova build ios --release --device --buildConfig build.json, I get a return code 65 and the following error:

```<code>Check dependencies
No profiles for 'com.my.bundle.id' were found:  Xcode couldn't find a provisioning profile matching 'com.my.bundle.id'.
Code signing is required for product type 'Application' in SDK 'iOS 10.3'

** ARCHIVE FAILED **

The following build commands failed:
    Check dependencies
(1 failure)
Error: Error code 65 for command: xcodebuild with args: -xcconfig,/cordova-project/platforms/ios/cordova/build-debug.xcconfig,-workspace,MyApp.xcworkspace,-scheme,MyApp,-configuration,Debug,-destination,generic/platform=iOS,-archivePath,MyApp.xcarchive,archive,CONFIGURATION_BUILD_DIR=/cordova-project/platforms/ios/build/device,SHARED_PRECOMPS_DIR=/cordova-project/platforms/ios/build/sharedpch
</code>```

(I can manually run that xcodebuild command and get the same error, so it's probably not a Cordova issue.)

My build.json file looks like this:

```<code>{
    "ios": {
        "debug": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "MY_TEAM_ID",
            "packageType": "development"
        },
        "release": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "MY_TEAM_ID",
            "packageType": "enterprise"
        }
    }
}
</code>```

I'm using cordova 7.0.1, cordova-ios 4.4.0, Xcode 8.3.3, and MacOS 10.12.5. I have an Apple Enterprise account.

WHAT I TRIED:

If I open the generated project in Xcode, it fixes the automatic signing, and from then on I can run cordova successfully with that bundle ID. But if I try to run it with a different bundle ID, it will fail again.

I tried using security unlock-keychain ~/Library/Keychains/login.keychain-db first, since that's worked in the past, but it didn't help.

I also tried opening my private signing key in Keychain Access and setting it to "Allow all applications to access this item", without any luck.

I get the same error regardless of whether I pass --debug or --release to cordova.

答: There is no way to manage signing automatically using xcodebuild. You must either use third parties like Fastlane as mentioned before or use manual code signing as mentioned here.

Body:
SUMMARY:

If you open a project in Xcode 8 with "Automatically manage signing" enabled and a new bundle ID, it will automatically create and download a provisioning profile for it. But how can I make the same thing happen with xcodebuild, so I can use it on a remote build server?

DETAILS:

I'm trying to build a Cordova app on a Mac. Cordova configures the Xcode project to use "Automatically manage signing", so I'm trying to use that.

I change the bundle ID often, so I want Cordova to be able to build it with a new bundle ID, that hasn't been used before.

But when I run cordova build ios --release --device --buildConfig build.json, I get a return code 65 and the following error:

Check dependencies
No profiles for 'com.my.bundle.id' were found:  Xcode couldn't find a provisioning profile matching 'com.my.bundle.id'.
Code signing is required for product type 'Application' in SDK 'iOS 10.3'

** ARCHIVE FAILED **

The following build commands failed:
    Check dependencies
(1 failure)
Error: Error code 65 for command: xcodebuild with args: -xcconfig,/cordova-project/platforms/ios/cordova/build-debug.xcconfig,-workspace,MyApp.xcworkspace,-scheme,MyApp,-configuration,Debug,-destination,generic/platform=iOS,-archivePath,MyApp.xcarchive,archive,CONFIGURATION_BUILD_DIR=/cordova-project/platforms/ios/build/device,SHARED_PRECOMPS_DIR=/cordova-project/platforms/ios/build/sharedpch

(I can manually run that xcodebuild command and get the same error, so it's probably not a Cordova issue.)

My build.json file looks like this:

{
    "ios": {
        "debug": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "MY_TEAM_ID",
            "packageType": "development"
        },
        "release": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "MY_TEAM_ID",
            "packageType": "enterprise"
        }
    }
}

I'm using cordova 7.0.1, cordova-ios 4.4.0, Xcode 8.3.3, and MacOS 10.12.5. I have an Apple Enterprise account.

WHAT I TRIED:

If I open the generated project in Xcode, it fixes the automatic signing, and from then on I can run cordova successfully with that bundle ID. But if I try to run it with a different bundle ID, it will fail again.

I tried using security unlock-keychain ~/Library/Keychains/login.keychain-db first, since that's worked in the past, but it didn't help.

I also tried opening my private signing key in Keychain Access and setting it to "Allow all applications to access this item", without any luck.

I get the same error regardless of whether I pass --debug or --release to cordova.


问:
uisearchbar issue when scopebar is hide and show

while presenting the search controller i am setting the showScopeBar property to hide or show the scope bar

```<code>- (void)willPresentSearchController:(UISearchController *)searchController {
    // do something before the search controller is presented
    NSMutableArray *scopeArray = @[@"All"].mutableCopy;
    UISearchBar *searchBar =_searchController.searchBar;
    if (![labelDepartmentSelection.text isEqualToString:@"Department"]) {
        [scopeArray addObject:@"Department"];
    }
    if (![labelJobSelection.text isEqualToString:@"Job"]) {
        [scopeArray addObject:@"Job"];
    }
    searchBar.scopeButtonTitles = scopeArray;

    searchBar.showsScopeBar = scopeArray.count>1;
    [searchBar layoutIfNeeded];
    NSArray *subviews = searchBar.subviews;
    if([[UIDevice currentDevice].systemVersion floatValue]>=7.0) {
        //Get search bar with scope bar to reappear after search keyboard is dismissed
        UIView *scopeBar = [subviews.firstObject subviews].firstObject;
        [scopeBar setHidden:NO];
        CGRect frame = scopeBar.frame;
        frame.origin.y = frame.origin.y = 64.0;
        scopeBar.frame = frame;
    }
    [searchBar layoutSubviews];

    [searchBar sizeToFit];
    [serviceOptionTableView setContentInset:UIEdgeInsetsMake(scopeArray.count>1?44:0, 0, 0, 0)];

    serviceOptionTableView.tableHeaderView = searchController.searchBar;
}
</code>```

and when i simply hide and show the scope bar base on the scope titles i want it giet distorted
here is the case for this

```<code>- (void)willPresentSearchController:(UISearchController *)searchController {
    // do something before the search controller is presented
    NSMutableArray *scopeArray = @\[@"All"\].mutableCopy;
    UISearchBar *searchBar =_searchController.searchBar;
    if (!\[labelDepartmentSelection.text isEqualToString:@"Department"\]) {
        \[scopeArray addObject:@"Department"\];
    }
    if (!\[labelJobSelection.text isEqualToString:@"Job"\]) {
        \[scopeArray addObject:@"Job"\];
    }
    searchBar.scopeButtonTitles = scopeArray;

    searchBar.showsScopeBar = scopeArray.count>1;

    \[serviceOptionTableView setContentInset:UIEdgeInsetsMake(scopeArray.count>1?44:0, 0, 0, 0)\];

}
</code>```

this is the image of case 2

答:
The issue should fix itself if you remove the line:

```<code>searchBar.showsScopeBar = scopeArray.count>1;
</code>```

Setting the showScopeBar property has a weird effect for some reason. Removing it allows the default animation behaviour without any issues.

Body:
while presenting the search controller i am setting the showScopeBar property to hide or show the scope bar

- (void)willPresentSearchController:(UISearchController *)searchController {
    // do something before the search controller is presented
    NSMutableArray *scopeArray = @[@"All"].mutableCopy;
    UISearchBar *searchBar =_searchController.searchBar;
    if (![labelDepartmentSelection.text isEqualToString:@"Department"]) {
        [scopeArray addObject:@"Department"];
    }
    if (![labelJobSelection.text isEqualToString:@"Job"]) {
        [scopeArray addObject:@"Job"];
    }
    searchBar.scopeButtonTitles = scopeArray;

    searchBar.showsScopeBar = scopeArray.count>1;
    [searchBar layoutIfNeeded];
    NSArray *subviews = searchBar.subviews;
    if([[UIDevice currentDevice].systemVersion floatValue]>=7.0) {
        //Get search bar with scope bar to reappear after search keyboard is dismissed
        UIView *scopeBar = [subviews.firstObject subviews].firstObject;
        [scopeBar setHidden:NO];
        CGRect frame = scopeBar.frame;
        frame.origin.y = frame.origin.y = 64.0;
        scopeBar.frame = frame;
    }
    [searchBar layoutSubviews];

    [searchBar sizeToFit];
    [serviceOptionTableView setContentInset:UIEdgeInsetsMake(scopeArray.count>1?44:0, 0, 0, 0)];

    serviceOptionTableView.tableHeaderView = searchController.searchBar;
}

and when i simply hide and show the scope bar base on the scope titles i want it giet distorted
here is the case for this

- (void)willPresentSearchController:(UISearchController *)searchController {
    // do something before the search controller is presented
    NSMutableArray *scopeArray = @\[@"All"\].mutableCopy;
    UISearchBar *searchBar =_searchController.searchBar;
    if (!\[labelDepartmentSelection.text isEqualToString:@"Department"\]) {
        \[scopeArray addObject:@"Department"\];
    }
    if (!\[labelJobSelection.text isEqualToString:@"Job"\]) {
        \[scopeArray addObject:@"Job"\];
    }
    searchBar.scopeButtonTitles = scopeArray;

    searchBar.showsScopeBar = scopeArray.count>1;

    \[serviceOptionTableView setContentInset:UIEdgeInsetsMake(scopeArray.count>1?44:0, 0, 0, 0)\];

}

this is the image of case 2

Body:
The issue should fix itself if you remove the line:

searchBar.showsScopeBar = scopeArray.count>1;

Setting the showScopeBar property has a weird effect for some reason. Removing it allows the default animation behaviour without any issues.


问:
Java says FileNotFoundException but file exists
I have an assignment for my CS class where it says to read a file with several test scores and asks me to sum and average them. While summing and averaging is easy, I am having problems with the file reading. The instructor said to use this syntax

```<code>Scanner scores = new Scanner(new File("scores.dat"));
</code>```

However, this throws a FileNotFoundException, but I have checked over and over again to see if the file exists in the current folder, and after that, I figured that it had to do something with the permissions. I changed the permissions for read and write for everyone, but it still did not work and it still keeps throwing the error. Does anyone have any idea why this may be occurring?

EDIT: It was actually pointing to a directory up, however, I have fixed that problem. Now file.exists() returns true, but when I try to put it in the Scanner, it throws the FileNotFoundException

Here is all my code

```<code>import java.util.Scanner;
import java.io.*;
public class readInt{
        public static void main(String args[]){
                File file = new File("lines.txt");
                System.out.println(file.exists());
                Scanner scan = new Scanner(file);
        }
}
</code>```

答:
Reading and writing from and to a file can be blocked by your OS depending on the file's permission attributes.

If you are trying to read from the file, then I recommend using File's setReadable method to set it to true, or, this code for instance:

```<code>String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file;
File f = new File(arbitrary_path);
f.setReadable(true);
data_of_file = Files.readAllBytes(f);
f.setReadable(false); // do this if you want to prevent un-knowledgeable
                      //programmers from accessing your file.
</code>```

If you are trying to write to the file, then I recommend using File's setWritable method to set it to true, or, this code for instance:

```<code>String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file = { (byte) 0x00, (byte) 0xFF, (byte) 0xEE };
File f = new File(arbitrary_path);
f.setWritable(true);
Files.write(f, byte_array);
f.setWritable(false); // do this if you want to prevent un-knowledgeable
                      //programmers from changing your file (for security.)
</code>```

Body:
I have an assignment for my CS class where it says to read a file with several test scores and asks me to sum and average them. While summing and averaging is easy, I am having problems with the file reading. The instructor said to use this syntax

Scanner scores = new Scanner(new File("scores.dat"));

However, this throws a FileNotFoundException, but I have checked over and over again to see if the file exists in the current folder, and after that, I figured that it had to do something with the permissions. I changed the permissions for read and write for everyone, but it still did not work and it still keeps throwing the error. Does anyone have any idea why this may be occurring?

EDIT: It was actually pointing to a directory up, however, I have fixed that problem. Now file.exists() returns true, but when I try to put it in the Scanner, it throws the FileNotFoundException

Here is all my code

import java.util.Scanner;
import java.io.*;
public class readInt{
        public static void main(String args[]){
                File file = new File("lines.txt");
                System.out.println(file.exists());
                Scanner scan = new Scanner(file);
        }
}

Body:
Reading and writing from and to a file can be blocked by your OS depending on the file's permission attributes.

If you are trying to read from the file, then I recommend using File's setReadable method to set it to true, or, this code for instance:

String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file;
File f = new File(arbitrary_path);
f.setReadable(true);
data_of_file = Files.readAllBytes(f);
f.setReadable(false); // do this if you want to prevent un-knowledgeable
                      //programmers from accessing your file.

If you are trying to write to the file, then I recommend using File's setWritable method to set it to true, or, this code for instance:

String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file = { (byte) 0x00, (byte) 0xFF, (byte) 0xEE };
File f = new File(arbitrary_path);
f.setWritable(true);
Files.write(f, byte_array);
f.setWritable(false); // do this if you want to prevent un-knowledgeable
                      //programmers from changing your file (for security.)


问:
Swagger UI doesn't support uploading a file properly for RestEasy
I use a JAX-RS (RestEasy) along with a Swagger. One of my endpoint can upload a file. Defined way to upload the file (in RestEasy) is to provide a org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput as a parameter.

Here is my endpoint:

```<code>@PUT
@Path("/apis/{id}/file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Registers a file.", code = 201, nickname = "registerFile")
@ApiResponses(
    value = {
        @ApiResponse(code = 201, message = "File created.",
                     response = FileCreated.class),
        @ApiResponse(code = 400, message = "Invalid parameters."),
        @ApiResponse(code = 404, message = "API is not found.")})
Response registerFile(
    @ApiParam(value = "API ID.", required = true) @PathParam("id") String apiId,
    @ApiParam(value = "File to register.", required = true, type = "file", name = "apiFile")
        MultipartFormDataInput apiFile) throws AppException;
</code>```

What is the problem?

Unfortunately, swagger-ui generates a schema based on the inner properties of the MultipartFormDataInput instead of a button to upload the file.
I tried use a @FormParam annotation (to indicate that the providing parameter should be interpreted as file) along with the MultipartFormDataInput parameter, but then the app doesn't want to compile.

Question: Is there any solution/workaround to provide the button to upload the file in the swagger-ui?

答:
The final solution

The final solution includes a selected answer, but instead of removing @ApiParam we should add @ApiParam(hidden = true). Why?

If we remove @ApiParam, there are two fields: apiId, body with the inner properties of the MultipartFormDataInput and the button to upload the file in the swagger-ui. This body field is a side effect. To fix this issue we should provide @ApiParam(hidden = true), then there are the field with apiId and the button to upload the file in the swagger-ui.

BTW: I tested below code for swagger-ui in 1.5.12 version.

```<code>@PUT
@Path("/apis/{id}/file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Registers a file.", code = 201, nickname = "registerFile")
@ApiResponses(
    value = {
        @ApiResponse(code = 201, message = "File created.",
                     response = FileCreated.class),
        @ApiResponse(code = 400, message = "Invalid parameters."),
        @ApiResponse(code = 404, message = "API is not found.")})
@ApiImplicitParams(
    @ApiImplicitParam(value = "File to register.", required = true, dataType = "file",
                      name = "apiFile", paramType = "formData"))
Response registerFile(
    @ApiParam(value = "API ID.", required = true) @PathParam("id") String apiId,
    @ApiParam(hidden = true) MultipartFormDataInput apiFile) throws AppException;
</code>```

Body:
I use a JAX-RS (RestEasy) along with a Swagger. One of my endpoint can upload a file. Defined way to upload the file (in RestEasy) is to provide a org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput as a parameter.

Here is my endpoint:

@PUT
@Path("/apis/{id}/file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Registers a file.", code = 201, nickname = "registerFile")
@ApiResponses(
    value = {
        @ApiResponse(code = 201, message = "File created.",
                     response = FileCreated.class),
        @ApiResponse(code = 400, message = "Invalid parameters."),
        @ApiResponse(code = 404, message = "API is not found.")})
Response registerFile(
    @ApiParam(value = "API ID.", required = true) @PathParam("id") String apiId,
    @ApiParam(value = "File to register.", required = true, type = "file", name = "apiFile")
        MultipartFormDataInput apiFile) throws AppException;

What is the problem?

Unfortunately, swagger-ui generates a schema based on the inner properties of the MultipartFormDataInput instead of a button to upload the file.
I tried use a @FormParam annotation (to indicate that the providing parameter should be interpreted as file) along with the MultipartFormDataInput parameter, but then the app doesn't want to compile.

Question: Is there any solution/workaround to provide the button to upload the file in the swagger-ui?

Body:
The final solution

The final solution includes a selected answer, but instead of removing @ApiParam we should add @ApiParam(hidden = true). Why?

If we remove @ApiParam, there are two fields: apiId, body with the inner properties of the MultipartFormDataInput and the button to upload the file in the swagger-ui. This body field is a side effect. To fix this issue we should provide @ApiParam(hidden = true), then there are the field with apiId and the button to upload the file in the swagger-ui.

BTW: I tested below code for swagger-ui in 1.5.12 version.

@PUT
@Path("/apis/{id}/file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Registers a file.", code = 201, nickname = "registerFile")
@ApiResponses(
    value = {
        @ApiResponse(code = 201, message = "File created.",
                     response = FileCreated.class),
        @ApiResponse(code = 400, message = "Invalid parameters."),
        @ApiResponse(code = 404, message = "API is not found.")})
@ApiImplicitParams(
    @ApiImplicitParam(value = "File to register.", required = true, dataType = "file",
                      name = "apiFile", paramType = "formData"))
Response registerFile(
    @ApiParam(value = "API ID.", required = true) @PathParam("id") String apiId,
    @ApiParam(hidden = true) MultipartFormDataInput apiFile) throws AppException;


问:
My tkinter command only runs once
I am using tkinter to code a little thing which displays new images each time a button is pressed, but it won't cycle more than once.</p>

```<code> from tkinter import *
 root=Tk()
 image1=PhotoImage(file="SCIMG_Gagagigo.png")
 image2=PhotoImage(file="SCIMG_7_Coloured_Fish.png")
 image3=PhotoImage(file="SCIMG_Jerry_Beans_Man.png")
 image4=PhotoImage(file="SCIMG_Axe_Raider.png")
 image5=PhotoImage(file="SCIMG_Guardian_of_the_Throne_Room.png")
 image6=PhotoImage(file="SCIMG_Alien_Shocktrooper.png")
 image7=PhotoImage(file="SCIMG_Evilswarm_Heliotrope.png")
 image8=PhotoImage(file="SCIMG_Alexandrite_Dragon.png")
 def change():
     for a in range(4):
         array.append(array[0])
         array.pop(0)
     b1=Button(image=array[0])
     b2=Button(image=array[1])
     b3=Button(image=array[2])
     b4=Button(image=array[3])
     b1.grid(row=0,column=0)
     b2.grid(row=0,column=1)
     b3.grid(row=1,column=0)
     b4.grid(row=1,column=1)
 array=[image8,image7,image6,image5,image4,image3,image2,image1]
 b1=Button(image=array[0],command=change)
 b2=Button(image=array[1],command=change)
 b3=Button(image=array[2],command=change)
 b4=Button(image=array[3],command=change)
 b1.grid(row=0,column=0)
 b2.grid(row=0,column=1)
 b3.grid(row=1,column=0)
 b4.grid(row=1,column=1)
 root.mainloop()
</code>```

答:
I can't understand why do you create a new button every time. You can just edit their image:

```<code>def change():
    for a in range(4):
        array.append(array[0])
        array.pop(0)
    b1.configure(image=array[1])
    b2.configure(image=array[2])
    b3.configure(image=array[3])
    b4.configure(image=array[4])
</code>```

I also suggest you to use some for loops and arrays instead of creating PhotoImage and Button elements one by one.

Title: My tkinter command only runs once

Body:
I am using tkinter to code a little thing which displays new images each time a button is pressed, but it won't cycle more than once.

 from tkinter import *
 root=Tk()
 image1=PhotoImage(file="SCIMG_Gagagigo.png")
 image2=PhotoImage(file="SCIMG_7_Coloured_Fish.png")
 image3=PhotoImage(file="SCIMG_Jerry_Beans_Man.png")
 image4=PhotoImage(file="SCIMG_Axe_Raider.png")
 image5=PhotoImage(file="SCIMG_Guardian_of_the_Throne_Room.png")
 image6=PhotoImage(file="SCIMG_Alien_Shocktrooper.png")
 image7=PhotoImage(file="SCIMG_Evilswarm_Heliotrope.png")
 image8=PhotoImage(file="SCIMG_Alexandrite_Dragon.png")
 def change():
     for a in range(4):
         array.append(array[0])
         array.pop(0)
     b1=Button(image=array[0])
     b2=Button(image=array[1])
     b3=Button(image=array[2])
     b4=Button(image=array[3])
     b1.grid(row=0,column=0)
     b2.grid(row=0,column=1)
     b3.grid(row=1,column=0)
     b4.grid(row=1,column=1)
 array=[image8,image7,image6,image5,image4,image3,image2,image1]
 b1=Button(image=array[0],command=change)
 b2=Button(image=array[1],command=change)
 b3=Button(image=array[2],command=change)
 b4=Button(image=array[3],command=change)
 b1.grid(row=0,column=0)
 b2.grid(row=0,column=1)
 b3.grid(row=1,column=0)
 b4.grid(row=1,column=1)
 root.mainloop()

Body:
I can't understand why do you create a new button every time. You can just edit their image:

def change():
    for a in range(4):
        array.append(array[0])
        array.pop(0)
    b1.configure(image=array[1])
    b2.configure(image=array[2])
    b3.configure(image=array[3])
    b4.configure(image=array[4])

I also suggest you to use some for loops and arrays instead of creating PhotoImage and Button elements one by one.


问:
Runtime splash screen iPhone
I made a iPhone application which supports French and English languages. When application is loading there is black screen appears initially. Instead of this I want to add splash screens for French and English. Both splash screens are different. When language is French it will load French splash screen and when language is English, it will load English splash screen.

In simple words, How I add Default.png for English and French?

Please let me know if there is any way to implement this.

答:
You can dynamically load a universal screen, then switch it up with one of your language specific screens. You can play with this code:

Add this to your AppDelegate.m

```<code>@interface SwitchDefault : UIViewController {}
@end
@implementation SwitchDefault

- (void)viewDidLoad {
    [super viewDidLoad];

    /* use an if statement here to display a specific French / English spash  */
    UIImageView *switch = @"English.png";
    self.view = switch;

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:2.0];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(imageDidFadeOut:finished:context:)];
    /*  add a fade into your app  */
    [UIView commitAnimations];

}
- (void)imageDidFadeOut:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
    [self.view removeFromSuperview];
}
@end
</code>```

And in your didFinishLaunchingWithOptions do thig:

```<code>SwitchDefault * switch = [[[SwitchDefault alloc] init] autorelease];
[window addSubview:navigationController.view];
[window addSubview:switch.view];
[window makeKeyAndVisible];
</code>```

Title: Runtime splash screen iPhone

Body:
You can dynamically load a universal screen, then switch it up with one of your language specific screens. You can play with this code:

Add this to your AppDelegate.m

@interface SwitchDefault : UIViewController {}
@end
@implementation SwitchDefault

- (void)viewDidLoad {
    [super viewDidLoad];

    /* use an if statement here to display a specific French / English spash  */
    UIImageView *switch = @"English.png";
    self.view = switch;

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:2.0];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(imageDidFadeOut:finished:context:)];
    /*  add a fade into your app  */
    [UIView commitAnimations];

}
- (void)imageDidFadeOut:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
    [self.view removeFromSuperview];
}
@end

And in your didFinishLaunchingWithOptions do thig:

SwitchDefault * switch = [[[SwitchDefault alloc] init] autorelease];
[window addSubview:navigationController.view];
[window addSubview:switch.view];
[window makeKeyAndVisible];