问:
How do I get Android client side callback to fire after Firebase Cloud Function onWrite finishes?
So I'm on a user page and I'd like to let users create a post but fanout on the server side.

```<code>exports.fanoutUpdatePost = functions.database.ref('/post/{postKey}').onWrite(event => {
        var post = event.data.val();

        var fanoutObject = {};

        fanoutObject['/user-post/'+post.userKey+'/post/'+event.params.postKey] = post;
        fanoutObject['/blog-post/'+post.blogKey+'/post/'+event.params.postKey] = post;

       return event.data.adminRef.root.update(fanoutObject);
});
</code>```

I'm doing this so you can just post on /post/ and the server will automatically fanout.
The problem is that I want the client side to show progress bar until it gets saved in /user-post/.

But my client side callback fires immediately after post gets created on /post/.

```<code>public void addPost(final PostDao post, ProgressBar progressBar) {
    progressBar.setVisibility(View.VISIBLE);

    String key = mDatabase.child(“post”).push().getKey();

    Map<String, Object> postUpdateMap = new HashMap<>();
    postUpdateMap.put(“/post/” +key, post.toMap());

    mDatabase.updateChildren(postUpdateMap, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                    if(databaseError == null){
                        Log.e(TAG, databaseError);
                    }else{
                        // @@@@@ This executes before server side
                        // @@@@@ cloud function fanoutUpdatePost
                        // @@@@@ finishes. Can I make this happen
                        // @@@@@ after it?
                    }
                }
            });
}
</code>```

Is there a way to wait until my onWrite cloud function finishes?

答:
For your specific use-case I'd recommend Doug's approach.

But an alternative can be to think of your database as a bunch of request/response queues. So instead of creating a blog post, say that you're writing a request to create that post.

```<code>post-requests
  $pushid
    title: "..."
    body: "..."
</code>```

Then your Cloud Functions code processing this request, writes the actual blog post, writes the fanned-out data, deletes the request and then finally, writes a response back to the client:

```<code>post-responses
  $pushid: "ok"
</code>```

The trick here is that the request and the response use the same push ID. So as soon as the client has pushed its request, it knows where its response will eventually show up.

Now from the client's perspective, it:

Pushes the request to the database

Starts listening for the response on the response queue

Processes the response

While this approach seems over the top here, it can be useful for longer asynchronous processes where you can't/don't want to keep a single HTTP request open between the client and the server while your request is being processed.

Body:
So I'm on a user page and I'd like to let users create a post but fanout on the server side.

exports.fanoutUpdatePost = functions.database.ref('/post/{postKey}').onWrite(event => {
        var post = event.data.val();

        var fanoutObject = {};

        fanoutObject['/user-post/'+post.userKey+'/post/'+event.params.postKey] = post;
        fanoutObject['/blog-post/'+post.blogKey+'/post/'+event.params.postKey] = post;

       return event.data.adminRef.root.update(fanoutObject);
});

I'm doing this so you can just post on /post/ and the server will automatically fanout.
The problem is that I want the client side to show progress bar until it gets saved in /user-post/.

But my client side callback fires immediately after post gets created on /post/.

public void addPost(final PostDao post, ProgressBar progressBar) {
    progressBar.setVisibility(View.VISIBLE);

    String key = mDatabase.child(“post”).push().getKey();

    Map<String, Object> postUpdateMap = new HashMap<>();
    postUpdateMap.put(“/post/” +key, post.toMap());

    mDatabase.updateChildren(postUpdateMap, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                    if(databaseError == null){
                        Log.e(TAG, databaseError);
                    }else{
                        // @@@@@ This executes before server side
                        // @@@@@ cloud function fanoutUpdatePost
                        // @@@@@ finishes. Can I make this happen
                        // @@@@@ after it?
                    }
                }
            });
}

Is there a way to wait until my onWrite cloud function finishes?

Body:
For your specific use-case I'd recommend Doug's approach.

But an alternative can be to think of your database as a bunch of request/response queues. So instead of creating a blog post, say that you're writing a request to create that post.

post-requests
  $pushid
    title: "..."
    body: "..."

Then your Cloud Functions code processing this request, writes the actual blog post, writes the fanned-out data, deletes the request and then finally, writes a response back to the client:

post-responses
  $pushid: "ok"

The trick here is that the request and the response use the same push ID. So as soon as the client has pushed its request, it knows where its response will eventually show up.

Now from the client's perspective, it:

Pushes the request to the database

Starts listening for the response on the response queue

Processes the response

While this approach seems over the top here, it can be useful for longer asynchronous processes where you can't/don't want to keep a single HTTP request open between the client and the server while your request is being processed.


来源: stackexchange

问:
Opening spinner by clicking on EditText
Sorry to bother you guys, but I've been strangling to get this to work.

What I want it to do:

EditText to display hint.

User clicks on EditText, opens spinner and selects their sex. That then get's turned into a string and put inside the EditText(gender)

What it is actually doing:
"Male" the first element in my spinner is already put inside my EditText before the user even clicks on it.(I never see my hint: "Sex")....and the spinner won't open at all when I try clicking on the EditText(gender)

What's going on?

My code:

```<code>    private Spinner sexSpinner;
    String[] arrayForSpinner = {"Male", "Female"};

    //Inside OnCreate method:
    sexSpinner = (Spinner)findViewById(R.id.spinner);
    adapter = new ArrayAdapter<String>(this, R.layout.spinner_row, arrayForSpinner);
    sexSpinner.setAdapter(adapter);

sexSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
            gender.setText(sexSpinner.getSelectedItem().toString());

        }

gender.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View arg0, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
                sexSpinner.performClick();
            }
        }
    });
</code>```

Layout:

```<code><EditText
        android:layout_width="75dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:focusable="false"
        android:longClickable="false"
        android:clickable="true"
        android:inputType="date"
        android:maxLines="1"
        android:singleLine="true"
        android:hint="Gender"
        android:textColorHint="@color/white"
        android:textColor="@color/white"
        android:ems="10"
        android:id="@+id/signup_input_gender"
        android:layout_below="@+id/signup_input_birthday"
        android:layout_centerHorizontal="true"
        android:backgroundTint="@android:color/white"/>

<Spinner
        android:background="@color/Blue"
        android:id="@+id/spinner"
        android:paddingLeft="0dp"
        android:layout_width="75dp"
        android:layout_height="40dp"
        android:layout_marginRight="40dp"
        android:layout_marginBottom="6dp"
        android:layout_below="@+id/linearlayout"
        android:visibility="invisible" />
</code>```

答:
To show Spinner ( use gender.setOnClickListener()),

```<code>gender.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                flag = true;
                sexSpinner.performClick();
            }
        });
</code>```

To show hint first time as a 'Sex' define boolean globle variable 'flag',

```<code>    boolean flag = false;        // Here
.
.
.
sexSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (flag)        // Here
                    gender.setText(sexSpinner.getSelectedItem().toString());
            }
        });
.
.
.
gender.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                flag = true;        // Here
                sexSpinner.performClick();
            }
        });
</code>```

ContentLicense: CC BY-SA 3.0

Title: Opening spinner by clicking on EditText

Body:
Sorry to bother you guys, but I've been strangling to get this to work.

What I want it to do:

EditText to display hint.

User clicks on EditText, opens spinner and selects their sex. That then get's turned into a string and put inside the EditText(gender)

What it is actually doing:
"Male" the first element in my spinner is already put inside my EditText before the user even clicks on it.(I never see my hint: "Sex")....and the spinner won't open at all when I try clicking on the EditText(gender)

What's going on?

My code:

    private Spinner sexSpinner;
    String[] arrayForSpinner = {"Male", "Female"};

    //Inside OnCreate method:
    sexSpinner = (Spinner)findViewById(R.id.spinner);
    adapter = new ArrayAdapter<String>(this, R.layout.spinner_row, arrayForSpinner);
    sexSpinner.setAdapter(adapter);

sexSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
            gender.setText(sexSpinner.getSelectedItem().toString());

        }

gender.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View arg0, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
                sexSpinner.performClick();
            }
        }
    });

Layout:

<EditText
        android:layout_width="75dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:focusable="false"
        android:longClickable="false"
        android:clickable="true"
        android:inputType="date"
        android:maxLines="1"
        android:singleLine="true"
        android:hint="Gender"
        android:textColorHint="@color/white"
        android:textColor="@color/white"
        android:ems="10"
        android:id="@+id/signup_input_gender"
        android:layout_below="@+id/signup_input_birthday"
        android:layout_centerHorizontal="true"
        android:backgroundTint="@android:color/white"/>

<Spinner
        android:background="@color/Blue"
        android:id="@+id/spinner"
        android:paddingLeft="0dp"
        android:layout_width="75dp"
        android:layout_height="40dp"
        android:layout_marginRight="40dp"
        android:layout_marginBottom="6dp"
        android:layout_below="@+id/linearlayout"
        android:visibility="invisible" />

Body:
To show Spinner ( use gender.setOnClickListener()),

gender.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                flag = true;
                sexSpinner.performClick();
            }
        });

To show hint first time as a 'Sex' define boolean globle variable 'flag',

    boolean flag = false;        // Here
.
.
.
sexSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (flag)        // Here
                    gender.setText(sexSpinner.getSelectedItem().toString());
            }
        });
.
.
.
gender.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                flag = true;        // Here
                sexSpinner.performClick();
            }
        });


问:
Generate er diagram from Hibernate entity
I would like to generate ER diagram from Hibernate entities or Hibernate mapping. I have selected visual paradigm tool which provides this feature. I would like to know your feedback about visual paradigm or some other tools if you know which supports the above feature.</p>

答:
If you are using IntelliJ Idea (Ultimate) you can use Persistence Tool Window. In order to use this feature, you have to add Java EE Persistence Framework Support to your project or module. ( Note: To do that, go to Project Tool Window: right-click a module folder and select Add Framework Support.)

For the tool window to be available, there must be a JPA- or Hibernate-enabled module in your project, i.e. a module with a JPA or Hibernate facet.

To open the tool window, do one of the following:

Select View > Tool Windows > Persistence

If the tool window bars are
currently shown, click the Persistence button (normally located at the lower-left part of the workspace).

After that, you can generate persistence mapping. Then Right-click on the generated persistence unit and select “ER Diagram”.

References:

https://www.jetbrains.com/help/idea/persistence-tool-window.html

https://nixmash.com/post/using-intellij-persistence-view-and-er-diagram-mapping-tools


问:
Apache MINA Server and PHP Client
If I made a Apache MINA Server in Java and used a PHP Client would there be any problems? I do not quite understand the NIO thing so if you could explain that to me too I would <3 you :)</p>

答:
Your question is terribly broad, but the short answer is yes, you should be able to setup mina <--> php.

I don't know that you really have to know all the nitty gritty details about Java NIO in order to use Mina. To my knowledge, that is sorta the point of Mina - it abstracts out the "hard parts" of the low level NIO stuff.

If you really want to learn about NIO I'm afraid there is no silver bullet answer here that will explain everything you need to know in order to effectively do networking programming - in any language in particular.

That being said, start with the basics, like the wikipedia entry on sockets. Then try a tutorial on sockets in Java, PHP and whatever else you need. Read a book and\or take a class, etc, etc. This isn't one of those things that most people master via one stackoverflow post - it will take time and effort. Good luck!

ContentLicense: CC BY-SA 2.5

Title: Apache MINA Server and PHP Client


问:
Failed to start program. Path or permissions wrong? in Qt
I have downloaded Qt Mobility Open source project. I had a set of demo apps. And when built it and started the App, I got this error:

Failed to start program. Path or
  permissions wrong?

Can someone tell me what this problem could be?

UPDATE:

The complete error is:

Starting
  /Users/xxxxx/Qt/qt-mobility-opensource-src-1.0.2/config.app/Contents/MacOS/config...
  Failed to start program. Path or
  permissions wrong?

I have include the ".pro" file contents:

```<code>TEMPLATE = app
TARGET = writemessage

QT += gui

include(../examples.pri)

CONFIG += mobility
MOBILITY = messaging
INCLUDEPATH += ../../src/messaging

HEADERS += \
    messagesender.h

SOURCES += \
    messagesender.cpp\
    main.cpp

symbian:TARGET.CAPABILITY = NetworkServices \
    LocalServices \
    ReadUserData \
    WriteUserData \
    UserEnvironment \
    ReadDeviceData \
    WriteDeviceData
</code>```

答:
My mac didn't have valgrind installed by default so I had to

```<code>brew install valgrind
</code>```

Go back to QT Creator, and in Projects -> Run -> Valgrind Settings

Point the Valgrind executable to the brew installed version which you can
find by typing which valgrind on the command line.

Finally due to the bug report here I realized that valgrind 3.13 has a bug and doesn't work, and valgrind 3.12 also doesn't work on macs, and mac os high sierra isn't supported by valgrind. So you're basically out of look until 3.14 comes around.

Body:
I have downloaded Qt Mobility Open source project. I had a set of demo apps. And when built it and started the App, I got this error:

Failed to start program. Path or
  permissions wrong?

Can someone tell me what this problem could be?

UPDATE:

The complete error is:

Starting
  /Users/xxxxx/Qt/qt-mobility-opensource-src-1.0.2/config.app/Contents/MacOS/config...
  Failed to start program. Path or
  permissions wrong?

I have include the ".pro" file contents:

TEMPLATE = app
TARGET = writemessage

QT += gui

include(../examples.pri)

CONFIG += mobility
MOBILITY = messaging
INCLUDEPATH += ../../src/messaging

HEADERS += \
    messagesender.h

SOURCES += \
    messagesender.cpp\
    main.cpp

symbian:TARGET.CAPABILITY = NetworkServices \
    LocalServices \
    ReadUserData \
    WriteUserData \
    UserEnvironment \
    ReadDeviceData \
    WriteDeviceData

Body:
My mac didn't have valgrind installed by default so I had to

brew install valgrind

Go back to QT Creator, and in Projects -> Run -> Valgrind Settings

Point the Valgrind executable to the brew installed version which you can
find by typing which valgrind on the command line.

Finally due to the bug report here I realized that valgrind 3.13 has a bug and doesn't work, and valgrind 3.12 also doesn't work on macs, and mac os high sierra isn't supported by valgrind. So you're basically out of look until 3.14 comes around.

ContentLicense: CC BY-SA 4.0


问:
filter freemarker output by hash
```<code><#list reports as report>
<#list report.transactionList as expense>
    ${expense.transactionID}^<#t>
    ${table[expenses.transcationID}
    <#if expense.modifiedCreated?has_content>
      ${expense.modifiedCreated}^<#t>
    <#else>
      ${expense.created}^<#t>
    </#if>
</code>```

In the above code I have a hash table called table and I want to use expense.transactionID as the key to then load the table's value like in the above code.
when I run it, the second item instead of a value is just a blank spot.

答: figured it out. {table[expenses.transcationID} needs to cast the category I am using as the key into a string. so the answer is:   {table[expenses.transcationID?string}</p>

Title: filter freemarker output by hash

Body:
<#list reports as report>
<#list report.transactionList as expense>
    ${expense.transactionID}^<#t>
    ${table[expenses.transcationID}
    <#if expense.modifiedCreated?has_content>
      ${expense.modifiedCreated}^<#t>
    <#else>
      ${expense.created}^<#t>
    </#if>

In the above code I have a hash table called table and I want to use expense.transactionID as the key to then load the table's value like in the above code.
when I run it, the second item instead of a value is just a blank spot.


问:
@ExceptionHandler how to get raw json post from HttpServletRequest
My rest controller

```<code>@RestController
public class MyController {

    @RequestMapping(value = "/getrawjson",  method =  RequestMethod.POST)
    public @ResponseBody
    String search(@RequestBody Map<String, Object> json, HttpServletRequest httpServletRequest) throws PushNotiException,Exception {
        return "OK";
    }
}
</code>```

My Exception handling for invalid raw json post. I tried to use request.getInputStream() but I got the error

IllegalStateException: getInputStream() has already been called for this request

```<code>@ControllerAdvice
public class MethodArgumentNotValidExceptionHandler {

        @ExceptionHandler({org.springframework.http.converter.HttpMessageNotReadableException.class})
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ResponseBody
        public TrueIDResponse resolveException(HttpServletRequest request,Exception ex) throws IOException {

        }
}
</code>```

I want to keep log input raw json data on this exception.

Anyone Can help me? Thanks.

Update

As @Sean Carrol suggestion. I tried to use HttpServletRequestWrapper following a suggestion but it's still not work.

```<code>@ControllerAdvice
public class MethodArgumentNotValidExceptionHandler {

    @ExceptionHandler({org.springframework.http.converter.HttpMessageNotReadableException.class})
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ResponseBody
        public TrueIDResponse resolveException(HttpServletRequest request,Exception ex) throws IOException {
            MultiReadHttpServletRequest multiReadRequest = new MultiReadHttpServletRequest((HttpServletRequest) request);
            InputStream inputStream = multiReadRequest.getInputStream();
            String theString = IOUtils.toString(inputStream, "UTF-8");

        }
}
</code>```

I got this error at the InputStream inputStream = multiReadRequest.getInputStream(); line.

java.io.IOException: Stream closed

答:
I can solve this problem just add a filter , intercept the current HttpServletRequest and wrap it in a custom HttpServletRequestWrapper (MultipleReadHttpRequest)

```<code>@Component
public class CachingRequestBodyFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest currentRequest = (HttpServletRequest) servletRequest;
        MultipleReadHttpRequest wrappedRequest = new MultipleReadHttpRequest(currentRequest);
        chain.doFilter(wrappedRequest, servletResponse);
    }
}
</code>```

MultipleReadHttpRequest class for servlet 3.0

```<code>public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
    private ByteArrayOutputStream cachedBytes;

    public MultiReadHttpServletRequest(HttpServletRequest request) {
        super(request);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (cachedBytes == null)
            cacheInputStream();

        return new CachedServletInputStream();
    }

    @Override
    public BufferedReader getReader() throws IOException{
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    private void cacheInputStream() throws IOException {
    /* Cache the inputstream in order to read it multiple times. For
     * convenience, I use apache.commons IOUtils
     */
        cachedBytes = new ByteArrayOutputStream();
        IOUtils.copy(super.getInputStream(), cachedBytes);
    }

    /* An inputstream which reads the cached request body */
    public class CachedServletInputStream extends ServletInputStream {
        private ByteArrayInputStream input;

        public CachedServletInputStream() {
      /* create a new input stream from the cached request body */
            input = new ByteArrayInputStream(cachedBytes.toByteArray());
        }

        @Override
        public int read() throws IOException {
            return input.read();
        }

        @Override
        public boolean isFinished() {
            return input.available() == 0;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener listener) {
            throw new RuntimeException("Not implemented");
        }
    }
}
</code>```

Body:
My rest controller

@RestController
public class MyController {

    @RequestMapping(value = "/getrawjson",  method =  RequestMethod.POST)
    public @ResponseBody
    String search(@RequestBody Map<String, Object> json, HttpServletRequest httpServletRequest) throws PushNotiException,Exception {
        return "OK";
    }
}

My Exception handling for invalid raw json post. I tried to use request.getInputStream() but I got the error

IllegalStateException: getInputStream() has already been called for this request

@ControllerAdvice
public class MethodArgumentNotValidExceptionHandler {

        @ExceptionHandler({org.springframework.http.converter.HttpMessageNotReadableException.class})
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ResponseBody
        public TrueIDResponse resolveException(HttpServletRequest request,Exception ex) throws IOException {

        }
}

I want to keep log input raw json data on this exception.

Anyone Can help me? Thanks.

Update

As @Sean Carrol suggestion. I tried to use HttpServletRequestWrapper following a suggestion but it's still not work.

@ControllerAdvice
public class MethodArgumentNotValidExceptionHandler {

    @ExceptionHandler({org.springframework.http.converter.HttpMessageNotReadableException.class})
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ResponseBody
        public TrueIDResponse resolveException(HttpServletRequest request,Exception ex) throws IOException {
            MultiReadHttpServletRequest multiReadRequest = new MultiReadHttpServletRequest((HttpServletRequest) request);
            InputStream inputStream = multiReadRequest.getInputStream();
            String theString = IOUtils.toString(inputStream, "UTF-8");

        }
}

I got this error at the InputStream inputStream = multiReadRequest.getInputStream(); line.

java.io.IOException: Stream closed

Body:
I can solve this problem just add a filter , intercept the current HttpServletRequest and wrap it in a custom HttpServletRequestWrapper (MultipleReadHttpRequest)

@Component
public class CachingRequestBodyFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest currentRequest = (HttpServletRequest) servletRequest;
        MultipleReadHttpRequest wrappedRequest = new MultipleReadHttpRequest(currentRequest);
        chain.doFilter(wrappedRequest, servletResponse);
    }
}

MultipleReadHttpRequest class for servlet 3.0

public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
    private ByteArrayOutputStream cachedBytes;

    public MultiReadHttpServletRequest(HttpServletRequest request) {
        super(request);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (cachedBytes == null)
            cacheInputStream();

        return new CachedServletInputStream();
    }

    @Override
    public BufferedReader getReader() throws IOException{
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    private void cacheInputStream() throws IOException {
    /* Cache the inputstream in order to read it multiple times. For
     * convenience, I use apache.commons IOUtils
     */
        cachedBytes = new ByteArrayOutputStream();
        IOUtils.copy(super.getInputStream(), cachedBytes);
    }

    /* An inputstream which reads the cached request body */
    public class CachedServletInputStream extends ServletInputStream {
        private ByteArrayInputStream input;

        public CachedServletInputStream() {
      /* create a new input stream from the cached request body */
            input = new ByteArrayInputStream(cachedBytes.toByteArray());
        }

        @Override
        public int read() throws IOException {
            return input.read();
        }

        @Override
        public boolean isFinished() {
            return input.available() == 0;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener listener) {
            throw new RuntimeException("Not implemented");
        }
    }
}


问:
How to use Java to install multiple apks into android device
I have multiple app apks downloaded into my laptop. I want to use java to write a script, so that all apks can be installed to my device automatically. Anybody can help me out with this?

Thanks!

答:
if you are Using Linux

```<code>#!/bin/sh
for file in /dir/*
do
  adb install $file
done
</code>```

you can install using adb like

```<code>adb install application1.apk & adb install application2.apk & adb install applicaiton3
</code>```

you can install using

```<code>for %f in (D:\Directory\*.apk) do adb install "%f"
</code>```

using MAC

```<code>for file in apk/*;
do
./adb install $file;
done
</code>```

and a final solution using batch file created By Osman Vielma

```<code>@echo Preparing to install all .apk files in "C:\Directory\" folder to device

@pause

@for /f "delims=|" %%f in ('dir /b "C:\Directory\"*.apk') do @"C:\Directory_ADB\ADB\adb.exe" install -r "C:\Directory\%%f"

@echo End of Batch File

@pause
</code>```

Body:
if you are Using Linux

#!/bin/sh
for file in /dir/*
do
  adb install $file
done

you can install using adb like

adb install application1.apk & adb install application2.apk & adb install applicaiton3

you can install using

for %f in (D:\Directory\*.apk) do adb install "%f"

using MAC

for file in apk/*;
do
./adb install $file;
done

and a final solution using batch file created By Osman Vielma

@echo Preparing to install all .apk files in "C:\Directory\" folder to device

@pause

@for /f "delims=|" %%f in ('dir /b "C:\Directory\"*.apk') do @"C:\Directory_ADB\ADB\adb.exe" install -r "C:\Directory\%%f"

@echo End of Batch File

@pause


问:
Cannot horizontally center fixed width div in IE
I am creating a template for a website.

The example is at Framework Login Page

The main CSS sheet is at: master.css

I am trying to center the main parent div.

I am using

```<code>#body {
  width: 100%;
  background: url('pathtoimage.png');
}

#inner_body{
  width: 800px;
  margin: auto;
}

<body>
  <div id="body">
    <div id="inner_body"></div>
  </div>
</body>
</code>```

What could the issue be?

答:
Here is the explanation why you should use the correct doctype.

Use the correct DOCTYPE ( Document Type Definition, or
DTD)

This defines which version of HTML or XHTML your document
is actually using. It's needed by browsers or other tools
to process the document correctly.

Using an incomplete, outdated or no DOCTYPE at all, throws
some browsers into “Quirks” mode, where the browser assumes
you’ve written old-fashioned, invalid markup.

This means that your web pages may not render well in all
the major browsers.

Body:
I am creating a template for a website.

The example is at Framework Login Page

The main CSS sheet is at: master.css

I am trying to center the main parent div.

I am using

#body {
  width: 100%;
  background: url('pathtoimage.png');
}

#inner_body{
  width: 800px;
  margin: auto;
}

What could the issue be?


问:
CSS images not copied to output folder in Webpack
I am using Webpack to bundle a number of js/css files in a site.  I am bundling bootstrap.css and chosen.css as part of my bundles.  In order to create the bundles, I have a main.js that I am using as an entry point to import all the other files that I will need.  I am using file-loader to process font and image files and move them to the appropriate directories.  I am using the ExtractTextPlugin with the css-loader and resolve-url-loader to create a separate css bundle from my js bundle.

My main.js is:

```<code>import 'bootstrap/dist/css/bootstrap.css';
import 'chosen-js/chosen.css';
import './datetimehelper.js';
import './deletelink.js';
import './dropdown.js';
</code>```

My webpack.config.js is:

```<code>var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: './src/js/main.js',
  output: {
    filename: 'wwwroot/js/bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'images/[name].[ext]',
              outputPath: 'wwwroot/'
            }
          }
        ]
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'fonts/[name].[ext]',
              outputPath: 'wwwroot/'
            }
          }
        ]
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: ['css-loader?url=false', 'resolve-url-loader'],
          publicPath: '../'
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin({
      filename: 'wwwroot/css/bundle.css'
    })
  ]
};
</code>```

With the above configuration, the font references in bootstrap.css are picked up, moved to the appropriate directory and the urls are fixed in the css bundle that is emitted.  However, the images that are referenced in chosen.css are not being picked up.  Can anyone tell me what I need to do to make the images work correctly?  I've tried replacing file-loader with url-loader and no change.  I've also tried importing the images in my main.js and they were moved, but the urls in the css bundle were not rewritten correctly.

答: Having path configured in output makes life a lot easier. That would serve as the base output folder and all other loaders/plugins can work relative to that. May be the files were copied but not to your intended directory. Please do take a look at WebpackBootstrap repo. The config copies as well as converts image paths properly.

Body:
I am using Webpack to bundle a number of js/css files in a site.  I am bundling bootstrap.css and chosen.css as part of my bundles.  In order to create the bundles, I have a main.js that I am using as an entry point to import all the other files that I will need.  I am using file-loader to process font and image files and move them to the appropriate directories.  I am using the ExtractTextPlugin with the css-loader and resolve-url-loader to create a separate css bundle from my js bundle.

My main.js is:

import 'bootstrap/dist/css/bootstrap.css';
import 'chosen-js/chosen.css';
import './datetimehelper.js';
import './deletelink.js';
import './dropdown.js';

My webpack.config.js is:

var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: './src/js/main.js',
  output: {
    filename: 'wwwroot/js/bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'images/[name].[ext]',
              outputPath: 'wwwroot/'
            }
          }
        ]
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'fonts/[name].[ext]',
              outputPath: 'wwwroot/'
            }
          }
        ]
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: ['css-loader?url=false', 'resolve-url-loader'],
          publicPath: '../'
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin({
      filename: 'wwwroot/css/bundle.css'
    })
  ]
};

With the above configuration, the font references in bootstrap.css are picked up, moved to the appropriate directory and the urls are fixed in the css bundle that is emitted.  However, the images that are referenced in chosen.css are not being picked up.  Can anyone tell me what I need to do to make the images work correctly?  I've tried replacing file-loader with url-loader and no change.  I've also tried importing the images in my main.js and they were moved, but the urls in the css bundle were not rewritten correctly.


问:
What is type in Gradle task?

Hi, I'm almost new at Gradle in Android.
So.. I'm leanring the Gradle but there are many things that I don't understand.

```<code>task clean(type: Delete) {
    println "task clean~~"
    delete rootProject.buildDir
}
</code>```

In project A when I input "gradlew" in Android Studio Terminal,
I can see below result.

```<code>C:\Users\xxxx\AndroidStudioProjects\ProjectA>gradlew

> Configure project :
task clean~~

(..snip..)
</code>```

I have questions:

Why is the task clean executed?

Is it default task?

I couldn't find something like below code in the project's gradle file.

defaultTasks 'clean', 'run' .

What is type in task? (I saw type "Copy" too) .

答:
Well task clean is a default task of gradle. It runs every time you start your android studio. To know the working of gradle you should read this gradle documentation which will surely help you in your questions:
Gradle Docs

And for the second point according to gradle documentation:
A Task represents a single atomic piece of work for a build, such as compiling classes or generating javadoc.
So actually it's a task not type, type is a general term and to be specific task type belongs to central types which are used in Gradle scripts. If you go through the documentation you will also find the type:Copy too.

Title: What is type in Gradle task?

Body:
Hi, I'm almost new at Gradle in Android.
So.. I'm leanring the Gradle but there are many things that I don't understand.

task clean(type: Delete) {
    println "task clean~~"
    delete rootProject.buildDir
}

In project A when I input "gradlew" in Android Studio Terminal,
I can see below result.

C:\Users\xxxx\AndroidStudioProjects\ProjectA>gradlew

> Configure project :
task clean~~

(..snip..)

I have questions:

Why is the task clean executed?

Is it default task?

I couldn't find something like below code in the project's gradle file.

defaultTasks 'clean', 'run' .

What is type in task? (I saw type "Copy" too) .


问:
HTML5 validation when the input type is not "submit"
I'm using HTML5 for validating fields. I'm submitting the form using JavaScript on a button click. But the HTML5 validation doesn't work. It works only when then input type is submit. Can we do anything other than using JavaScript validation or changing the type to submit?

This is the HTML code:

```<code><input type="text" id="example" name="example" value="" required>
<button type="button"  onclick="submitform()" id="save">Save</button>
</code>```

I'm submitting the form in the function submitform().

答:
Either you can change the button type to submit

```<code><button type="submit"  onclick="submitform()" id="save">Save</button>
</code>```

Or you can hide the submit button, keep another button with type="button" and have click event for that button

```<code><form>
    <button style="display: none;" type="submit" >Hidden button</button>
    <button type="button" onclick="submitForm()">Submit</button>
</form>
</code>```

Body:
I'm using HTML5 for validating fields. I'm submitting the form using JavaScript on a button click. But the HTML5 validation doesn't work. It works only when then input type is submit. Can we do anything other than using JavaScript validation or changing the type to submit?

This is the HTML code:

<input type="text" id="example" name="example" value="" required>
<button type="button"  onclick="submitform()" id="save">Save</button>

I'm submitting the form in the function submitform().

Body:
Either you can change the button type to submit

<button type="submit"  onclick="submitform()" id="save">Save</button>

Or you can hide the submit button, keep another button with type="button" and have click event for that button

<form>
    <button style="display: none;" type="submit" >Hidden button</button>
    <button type="button" onclick="submitForm()">Submit</button>
</form>


问:
flask mysql db.execute loop
I am using python flask to do a db.execute into a sql database.
I need to do the folloing code for inputs [C4,C5,C6,C7, C8, C9, D7, D8, D9, D4, D5, D6, E7, E8, E9, E4, E5, E6] (So keep replacing C4 with every other input)
Copying and pasting this code below with minimal changes doesn't seem to be efficient, but I cannot find a way to do a loop. How to do a loop for the above list?</p>

```<code>C4 = request.form.get("C4")
db.execute("UPDATE user_table SET C4 = :C4 WHERE id = :id", id= session["user_id"], C4=C4)
</code>```

答:
You can update these fields all at once by manually constructing a query (sounds fragile, I agree) collecting the set conditions and query parameters:

```<code>fields = ["C4", "C5", "C6", "C7", "C8", "C9", "D7", "D8", "D9", "D4", "D5", "D6", "E7", "E8", "E9", "E4", "E5", "E6"]

query = "UPDATE user_table SET "
conditions = []
params = {}

for field in fields:
    conditions.append(" {field} = :{field} ".format(field=field))
    params[field] = request.form.get(field)

query += ", ".join(conditions) + " WHERE id = :id"
db.execute(query, id=session["user_id"], **params)
</code>```

That fields definition though - see if you can avoid hardcoding the list and get it dynamically from the request.form object or elsewhere.

Note that we are still properly parameterizing the query (except the column/field names that cannot be parameterized - make sure you trust the source of the fields to avoid potential SQL injections).

And, look into using ORMs like SQLAlchemy (and since you are using Flask - check out Flask-SQLAlchemy) - updating your models in cases like this would be much simpler, more readable and less error-prone to do with it.

Title: flask mysql db.execute loop

Body:
I am using python flask to do a db.execute into a sql database.
I need to do the folloing code for inputs [C4,C5,C6,C7, C8, C9, D7, D8, D9, D4, D5, D6, E7, E8, E9, E4, E5, E6] (So keep replacing C4 with every other input)
Copying and pasting this code below with minimal changes doesn't seem to be efficient, but I cannot find a way to do a loop. How to do a loop for the above list?

C4 = request.form.get("C4")
db.execute("UPDATE user_table SET C4 = :C4 WHERE id = :id", id= session["user_id"], C4=C4)

Body:
You can update these fields all at once by manually constructing a query (sounds fragile, I agree) collecting the set conditions and query parameters:

fields = ["C4", "C5", "C6", "C7", "C8", "C9", "D7", "D8", "D9", "D4", "D5", "D6", "E7", "E8", "E9", "E4", "E5", "E6"]

query = "UPDATE user_table SET "
conditions = []
params = {}

for field in fields:
    conditions.append(" {field} = :{field} ".format(field=field))
    params[field] = request.form.get(field)

query += ", ".join(conditions) + " WHERE id = :id"
db.execute(query, id=session["user_id"], **params)

That fields definition though - see if you can avoid hardcoding the list and get it dynamically from the request.form object or elsewhere.

Note that we are still properly parameterizing the query (except the column/field names that cannot be parameterized - make sure you trust the source of the fields to avoid potential SQL injections).

And, look into using ORMs like SQLAlchemy (and since you are using Flask - check out Flask-SQLAlchemy) - updating your models in cases like this would be much simpler, more readable and less error-prone to do with it.


问:
Hardware JPEG decompression / Win32
I know that most graphics hardware uses MPEG hardware decompression. I would like to use the hardware to decompress JPEG images. Does anyone know of a book or link to any information about using this functionality, or can tell me anything about it?

Also, I am willing to convert the images into a "video" if I can obtain hardware decompression of each frame. Would this be more viable?

答:
Decompression for jpeg using specialized hardware is stuff that's available at the driver level, so it's not easy to do from normal user space. It would be easier to try using generic hardware assisted processing (e.g. CUDA).

However if your need is just having a movie where frames are coming from jpegs then you should check ffmpeg, because it's a tool that can do many things for videos, including this or the opposite (i.e. getting all frames of a video as images).

For example to make a movie using a list of jpeg files (picture1.jpg, picture2.jpg, ...)

```<code>ffmpeg -i picture_%d.jpg result.wmv
</code>```

Most video players will then use hardware acceleration during playback if that is available

Title: Hardware JPEG decompression / Win32

Body:
Decompression for jpeg using specialized hardware is stuff that's available at the driver level, so it's not easy to do from normal user space. It would be easier to try using generic hardware assisted processing (e.g. CUDA).

However if your need is just having a movie where frames are coming from jpegs then you should check ffmpeg, because it's a tool that can do many things for videos, including this or the opposite (i.e. getting all frames of a video as images).

For example to make a movie using a list of jpeg files (picture1.jpg, picture2.jpg, ...)

ffmpeg -i picture_%d.jpg result.wmv

Most video players will then use hardware acceleration during playback if that is available


问:
programmatically clone /etc/skel for new users
/etc/skel is a folder that will be cloned for new users. Is there a possible way that we can define rules what to copy from /etc/skel folder?

For example, I'm looking for a way that if a user is created and belongs to group named A, clone /etc/skel folder except /etc/skel/not_for_a.txt. Possible?

答:
If  the  file  /usr/local/sbin/adduser.local exists, it will be exe‐
   cuted after the user account has been set up  in  order  to  do  any
   local setup.  The arguments passed to adduser.local are:
   username uid gid home-directory

I can use /usr/local/sbin/adduser.local to call commands after user is created


问:
How to get the jsonp link from this api?
I've been googling this forever but I'm just so confused. I'm trying to use the data from this api

https://github.com/artsmia/collection/blob/master/objects/0/1.json

I'm trying to use JSONP since I get cross-origin errors if I don't... Here's what I got...

```<code>function foo(data) {
    var parsedData = JSON.parse(data.responseText);
    console.log(parsedData.artist);
}

var script = document.createElement('script');
script.src = 'https://github.com/artsmia/collection/blob/master/objects/0/1.json';
document.getElementsByTagName('head')[0].appendChild(script);

foo(script);
</code>```

But this doesn't work. I guess it's because I'm not linking it correctly, but I'm not sure how to.

答:
You are trying to get the data from the html page. Click on raw button and use that url. You can't get jsonp from an api that doesn't serve jsonp but the raw endpoint is cors enabled

fetch('https://raw.githubusercontent.com/artsmia/collection/master/objects/0/1.json')
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(error => console.log(error))```

Body:
I've been googling this forever but I'm just so confused. I'm trying to use the data from this api

https://github.com/artsmia/collection/blob/master/objects/0/1.json

I'm trying to use JSONP since I get cross-origin errors if I don't... Here's what I got...

function foo(data) {
    var parsedData = JSON.parse(data.responseText);
    console.log(parsedData.artist);
}

var script = document.createElement('script');
script.src = 'https://github.com/artsmia/collection/blob/master/objects/0/1.json';
document.getElementsByTagName('head')[0].appendChild(script);

foo(script);

But this doesn't work. I guess it's because I'm not linking it correctly, but I'm not sure how to.


问:
How can i delete a file from document directory using the bar button item using objective-c?
I create a Bar button item (trash can) using storyboard.App crashes when i try to delete a file from document directory on button action. Here is code so far:</p>

```<code>@property (retain, nonatomic) IBOutlet UIBarButtonItem *deleteCsv;

-(void)deleteCsv:(id)sender{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSString *filePath = [documentsPath stringByAppendingPathComponent:fileDataString4];
    NSError *error;
    BOOL success = [fileManager removeItemAtPath:filePath error:&error];
    if (success) {
        UIAlertView *removedSuccessFullyAlert = [[UIAlertView alloc] initWithTitle:@"Congratulations:" message:@"Successfully removed" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
        [removedSuccessFullyAlert show];
    }
    else
    {
        NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
    }
</code>```

答:
I think you should check first whether file exist at path or not with following code,

```<code>if ([[NSFileManager defaultManager] fileExistsAtPath:[documentsDirectory stringByAppendingPathComponent:<your file path>]])
{
    //Delete your file
}
</code>```

By following this you will be able to handle the crash if it is occuring because of file nonexistence

Body:
I create a Bar button item (trash can) using storyboard.App crashes when i try to delete a file from document directory on button action. Here is code so far:

@property (retain, nonatomic) IBOutlet UIBarButtonItem *deleteCsv;

-(void)deleteCsv:(id)sender{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSString *filePath = [documentsPath stringByAppendingPathComponent:fileDataString4];
    NSError *error;
    BOOL success = [fileManager removeItemAtPath:filePath error:&error];
    if (success) {
        UIAlertView *removedSuccessFullyAlert = [[UIAlertView alloc] initWithTitle:@"Congratulations:" message:@"Successfully removed" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
        [removedSuccessFullyAlert show];
    }
    else
    {
        NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
    }

Body:
I think you should check first whether file exist at path or not with following code,

if ([[NSFileManager defaultManager] fileExistsAtPath:[documentsDirectory stringByAppendingPathComponent:<your file path>]])
{
    //Delete your file
}

By following this you will be able to handle the crash if it is occuring because of file nonexistence


问:
update a key in Yaml with list python
My Yaml looks like this

```<code>server-params:
    environment: prod
    artifact_version: 0.0.0.*
</code>```

I would like to insert another key named jobs and expected output as below,

```<code> server-params:
    environment: prod
    artifact_version: 0.0.0.*
    jobs: ['test','test2']
</code>```

I have tried this

```<code>jobs_list =['test','test2']

 params = yaml.safe_load(params)
 params['server-params']['jobs']=jobs_list
 yaml.dump(params, default_flow_style=False)

output:
     server-params:
        environment: prod
        artifact_version: 0.0.0.*
        jobs:
        - test
        - test2
</code>```

答:
Lose the default_flow_style parameter (or set it to True) if you want your lists not to expand in your YAML, e.g.:

```<code>test_yaml = """
server-params:
    environment: prod
    artifact_version: 0.0.0.*
"""

jobs_list = ['test', 'test2']

params = yaml.safe_load(test_yaml)
params['server-params']['jobs'] = jobs_list

print(yaml.dump(params))
</code>```

Which will yield:

```server-params:
  artifact_version: 0.0.0.*
  environment: prod
  jobs: [test, test2]```

If you want to keep your YAML ordered, tho, it will depend on the module you're using for all things YAML. If you're using ruamel.yaml (and if you're not, you should) use ruamel.yaml.RoundTripLoader as a Loader and ruamel.yaml.RoundTripDumper as a Dumper. If you're using PyYAML you can use the yamlordereddictloader module.

Title: update a key in Yaml with list python

Body:
My Yaml looks like this

server-params:
    environment: prod
    artifact_version: 0.0.0.*

I would like to insert another key named jobs and expected output as below,

 server-params:
    environment: prod
    artifact_version: 0.0.0.*
    jobs: ['test','test2']

I have tried this

jobs_list =['test','test2']

 params = yaml.safe_load(params)
 params['server-params']['jobs']=jobs_list
 yaml.dump(params, default_flow_style=False)

output:
     server-params:
        environment: prod
        artifact_version: 0.0.0.*
        jobs:
        - test
        - test2

Body:
Lose the default_flow_style parameter (or set it to True) if you want your lists not to expand in your YAML, e.g.:

test_yaml = """
server-params:
    environment: prod
    artifact_version: 0.0.0.*
"""

jobs_list = ['test', 'test2']

params = yaml.safe_load(test_yaml)
params['server-params']['jobs'] = jobs_list

print(yaml.dump(params))

Which will yield:

server-params:
  artifact_version: 0.0.0.*
  environment: prod
  jobs: [test, test2]

If you want to keep your YAML ordered, tho, it will depend on the module you're using for all things YAML. If you're using ruamel.yaml (and if you're not, you should) use ruamel.yaml.RoundTripLoader as a Loader and ruamel.yaml.RoundTripDumper as a Dumper. If you're using PyYAML you can use the yamlordereddictloader module.


问:
How to click on specific element out of the webelements in selenium webdriver in java
If the date from the list of dates is matching with the given date which is string format then it should click on that element from that list of dates which when fetched is converted to string only.
I have list of dates like below when converted to string:

```<code>2017-10-13
2017-09-29
2017-09-22
2017-09-15
2017-09-08
2017-09-01
2017-08-25
2017-08-18
</code>```

So now if the input which is "2017-Sep-29" which when parsed to another format gives 2017-09-29 matches with the second date from the list then it should be clicked but it is throwing an error.

Below is my java code with comments :

```<code>WebDriver driver;
List<WebElement> stageListOfFilters;
String finalSnapshot = "", finalSnapshot1 = "";

@Test
public void getDateAndclick()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
    try {
        Date varDate = dateFormat.parse("18-Aug-2017");
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        finalSnapshot1 = dateFormat.format(varDate).toString();
        System.out.println("Date: " + finalSnapshot1); // Prints 2017-08-18
        driver.findElement(By.xpath(config.getsnapshotFilter())).click();
        Thread.sleep(2000);
        finalSnap = finalSnapshot1.substring(5, 10);
        System.out.println("Date for final Comparison: " + finalSnap); // Prints 08-18 since i want to click on 18th august date
        stageListOfFilters = driver.findElements(By.xpath(".//*[@class='QvFrame DS']")); // This collects the list
                                                                                // of dates which is
                                                                                // fetched later on in
                                                                                // for loop
        Thread.sleep(2000);
        for (int i = 0; i < stageListOfFilters.size(); i++) {
            System.out.println(stageListOfFilters.get(i).getText());
            Thread.sleep(2000);
            if (finalSnap.contains(stageListOfFilters.get(i).getText())) {
                driver.findElement(By.xpath(".//*[@class='QvFrame DS']/div/div/div[1]/div[2]/div[" + i + "]"))
                        .click();// If it matches at that index then it should click on element present at that index
                Thread.sleep(2000);
            }
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
</code>```

So now it should click on the last element since date which is being passed is 18th August but it still clicks on 2017-09-29. I figured out that I am not getting value using get(i).getText() in if loop which is under for loop. Why is it so ?

Code for getAttribute("title") data :

```<code>stageListOfFilters = driver.findElements(By.xpath(".//*[@id='DS']")); // This collects the list
                                                                                // of dates which is
                                                                                // fetched later on in
                                                                                // for loop

            for (WebElement element : stageListOfFilters) {
                System.out.println("Dates are: " + element.getAttribute("title"));
            }
</code>```

答:
I was not able to select the proper xpath of the date list. I solved it now and below is my working code which fulfills my expectations. For css you can check this link:  </p>

```<code>try {
            Date varDate = dateFormat.parse("01-Sep-2017");
            dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 2017-08-18
            finalSnapshot1 = dateFormat.format(varDate).toString();
            System.out.println("Date: " + finalSnapshot1); // Prints 2017-08-18
            driver.findElement(By.xpath(config.getsnapshotFilter())).click();
            Thread.sleep(2000);

            stageListOfFilters = driver
                    .findElements(By.xpath("(//*[@class='QvFrame DS'])[1]/div/div/div[1]/child::div")); // This collects
                                                                                // the list
            // of dates which is
            // fetched later on in
            // for loop
            System.out.println("Size" + stageListOfFilters.size());
            Thread.sleep(2000);
            for (int i = 1; i < stageListOfFilters.size(); i++) {

                if (finalSnapshot1.equals(stageListOfFilters.get(i).getText())) {
                    System.out.println("Filters list value: " + stageListOfFilters.get(i).getText());
                    System.out.println("Value to be compared: " + finalSnapshot1);
                    i = i + 1;
                    driver.findElement(By.xpath(".//*[@class='QvFrame DS']/div/div/div[1]/div[" + i + "]/div[1]"))
                            .click();
                    System.out.println("Value of i: " + i +" and Date is: "+ finalSnapshot1.toString());
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
</code>```

Body:
If the date from the list of dates is matching with the given date which is string format then it should click on that element from that list of dates which when fetched is converted to string only.
I have list of dates like below when converted to string:

2017-10-13
2017-09-29
2017-09-22
2017-09-15
2017-09-08
2017-09-01
2017-08-25
2017-08-18

So now if the input which is "2017-Sep-29" which when parsed to another format gives 2017-09-29 matches with the second date from the list then it should be clicked but it is throwing an error.

Below is my java code with comments :

WebDriver driver;
List<WebElement> stageListOfFilters;
String finalSnapshot = "", finalSnapshot1 = "";

@Test
public void getDateAndclick()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
    try {
        Date varDate = dateFormat.parse("18-Aug-2017");
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        finalSnapshot1 = dateFormat.format(varDate).toString();
        System.out.println("Date: " + finalSnapshot1); // Prints 2017-08-18
        driver.findElement(By.xpath(config.getsnapshotFilter())).click();
        Thread.sleep(2000);
        finalSnap = finalSnapshot1.substring(5, 10);
        System.out.println("Date for final Comparison: " + finalSnap); // Prints 08-18 since i want to click on 18th august date
        stageListOfFilters = driver.findElements(By.xpath(".//*[@class='QvFrame DS']")); // This collects the list
                                                                                // of dates which is
                                                                                // fetched later on in
                                                                                // for loop
        Thread.sleep(2000);
        for (int i = 0; i < stageListOfFilters.size(); i++) {
            System.out.println(stageListOfFilters.get(i).getText());
            Thread.sleep(2000);
            if (finalSnap.contains(stageListOfFilters.get(i).getText())) {
                driver.findElement(By.xpath(".//*[@class='QvFrame DS']/div/div/div[1]/div[2]/div[" + i + "]"))
                        .click();// If it matches at that index then it should click on element present at that index
                Thread.sleep(2000);
            }
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

So now it should click on the last element since date which is being passed is 18th August but it still clicks on 2017-09-29. I figured out that I am not getting value using get(i).getText() in if loop which is under for loop. Why is it so ?

Code for getAttribute("title") data :

stageListOfFilters = driver.findElements(By.xpath(".//*[@id='DS']")); // This collects the list
                                                                                // of dates which is
                                                                                // fetched later on in
                                                                                // for loop

            for (WebElement element : stageListOfFilters) {
                System.out.println("Dates are: " + element.getAttribute("title"));
            }

Body:
I was not able to select the proper xpath of the date list. I solved it now and below is my working code which fulfills my expectations. For css you can check this link:

try {
            Date varDate = dateFormat.parse("01-Sep-2017");
            dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 2017-08-18
            finalSnapshot1 = dateFormat.format(varDate).toString();
            System.out.println("Date: " + finalSnapshot1); // Prints 2017-08-18
            driver.findElement(By.xpath(config.getsnapshotFilter())).click();
            Thread.sleep(2000);

            stageListOfFilters = driver
                    .findElements(By.xpath("(//*[@class='QvFrame DS'])[1]/div/div/div[1]/child::div")); // This collects
                                                                                // the list
            // of dates which is
            // fetched later on in
            // for loop
            System.out.println("Size" + stageListOfFilters.size());
            Thread.sleep(2000);
            for (int i = 1; i < stageListOfFilters.size(); i++) {

                if (finalSnapshot1.equals(stageListOfFilters.get(i).getText())) {
                    System.out.println("Filters list value: " + stageListOfFilters.get(i).getText());
                    System.out.println("Value to be compared: " + finalSnapshot1);
                    i = i + 1;
                    driver.findElement(By.xpath(".//*[@class='QvFrame DS']/div/div/div[1]/div[" + i + "]/div[1]"))
                            .click();
                    System.out.println("Value of i: " + i +" and Date is: "+ finalSnapshot1.toString());
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }


问:
Cannot change color of the text using if condition Swift 4.0
Below is my code. I'm trying to change the color of the text inside tableViewCell by using if condition that if the string contains - sign then it should go red or else green but it turns out all the strings go green.

```<code>cell.percentLabel.text = PercentChange[indexPath.row]

for i in PercentChange{
    if (i.range(of: "-") != nil) {
        cell.percentLabel.textColor = UIColor.red
   } else {
        cell.percentLabel.textColor = UIColor.green
    }
}
</code>```

答:
Assuming your posted code is in your cellForRowAt method, you should not be looping through all of the PercentChange values.

As written, you set the color of every cell based on the last value in PercentChange.

You should only be looking at the value specific to the given row.

```<code>let change = PercentChange[indexPath.row]
cell.percentLabel.text = change
cell.percentLabel.textColor = change.range(of: "-") != nil ? .red : .green
</code>```

Body:
Below is my code. I'm trying to change the color of the text inside tableViewCell by using if condition that if the string contains - sign then it should go red or else green but it turns out all the strings go green.

cell.percentLabel.text = PercentChange[indexPath.row]

for i in PercentChange{
    if (i.range(of: "-") != nil) {
        cell.percentLabel.textColor = UIColor.red
   } else {
        cell.percentLabel.textColor = UIColor.green
    }
}

Body:
Assuming your posted code is in your cellForRowAt method, you should not be looping through all of the PercentChange values.

As written, you set the color of every cell based on the last value in PercentChange.

You should only be looking at the value specific to the given row.

let change = PercentChange[indexPath.row]
cell.percentLabel.text = change
cell.percentLabel.textColor = change.range(of: "-") != nil ? .red : .green


问:
ActiveRecord could not connect to database server when running Rspec
So I'm running rspec tests with jruby-1.7.16.1 after completing a bundle install, and they are all failing to the same error:

```<code>     Failure/Error: Unable to find arjdbc/jdbc/RubyJdbcConnection.java to read failed line

 ActiveRecord::JDBCError:
   com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
 # arjdbc/jdbc/RubyJdbcConnection.java:453:in `init_connection'
</code>```

Occasionally I would get an error like this when I'd forget to start mysql server, but I ensured it was running.
The GemFile is as such

```<code>    source 'http://rubygems.org'

gem 'rails', '3.2.8'
gem 'rubyzip', '0.9.9'
gem 'roo','1.12.1'
gem 'jdbc-mysql', '5.1.33', platform: :jruby
gem 'activerecord-jdbcmysql-adapter', '1.3.12', platform: :jruby
gem 'jquery-rails', '2.1.2'

gem 'haml', '3.1.7'
gem 'puma', '2.9.2'

gem 'devise', '2.1.2'
gem 'devise-async', '0.5.0'
gem 'cancan', '1.6.8'
gem 'simple_form', '2.0.4'
gem 'cocoon', '1.1.1'
gem 'inherited_resources', '1.3.1'
gem 'will_paginate', '3.0.3'
gem 'bootstrap-will_paginate', '0.0.9'
gem 'mechanize', '2.5.1'
gem 'delayed_job', '3.0.4'
gem 'paperclip', '3.4.0'
gem 'spreadsheet', '0.6.4.1'
gem 'geocoder', '1.1.6'
gem 'whenever', '0.8.2'
gem 'american_date', '1.0.0'
gem 'money','5.1.1'
gem 'rets', '0.11.0'
gem 'haversine','0.3.0'

gem 'celluloid','0.15.2'
gem 'sinatra', '1.4.6'
source "https://9789474f:e71b0546@gems.contribsys.com/" do
  gem 'sidekiq-pro','1.9.2'
end
gem 'redis','3.2.1'
gem 'remote_lock','1.1.0'
gem 'sidekiq-limit_fetch','2.3.0'

group :assets do
  gem 'stylus', '0.7.1'
  gem 'coffee-rails', '3.2.2'
  gem 'uglifier', '1.3.0'
end

group :development do
  gem 'net-ssh', '2.9.4'
  gem 'capistrano', '3.4.1'
  gem 'capistrano-rails', '1.3.0'
  gem 'capistrano-rvm', '0.1.2'
end

group :development, :test do
  gem 'dotenv-rails', '2.2.1'
  gem 'rspec-rails', '~> 3.5'
  gem 'fantaskspec'
end

group :test do
  gem 'factory_girl_rails', '~> 4.0'
  gem 'fantaskspec'
  gem 'vcr'
  gem 'fakeweb'
end

gem 'rest-client', '1.8.0'
gem 'poltergeist', '1.8.1'
gem 'nokogiri', '1.5.11'
gem 'zip-codes', '0.2.1'

gem 'elasticsearch-model', '0.1.9'
gem 'elasticsearch-rails', '0.1.9'
gem "fog", '1.38.0'
gem 'newrelic_rpm', '3.18.1.330'
gem 'sidekiq-scheduler', '2.1.7'
gem 'aws-sdk', '2.10.28'
gem 'StreetAddress', '1.0.6'
</code>```

If there is more information required I'd be happy to provide it, let me know if anyone has run into this.

The odd thing is, these spec tests used to work fine prior to a merge I did with our repository. The other dev doesn't seem to be running into this same issue, so I can only assume the Gemfiles are all correct and that my environment is the issue.

答:
Make sure the database is up and running.

Does the user that's trying to connect to the database has permission to connect? Try logging in with that user in the client software.
Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

Try creating a new user with admin privileges and try connecting.

Advice: Try using a software that keeps your development environments in sync, and test it well. We use Vagrant to reproduce development environments.

Body:
So I'm running rspec tests with jruby-1.7.16.1 after completing a bundle install, and they are all failing to the same error:

     Failure/Error: Unable to find arjdbc/jdbc/RubyJdbcConnection.java to read failed line

 ActiveRecord::JDBCError:
   com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
 # arjdbc/jdbc/RubyJdbcConnection.java:453:in `init_connection'

Occasionally I would get an error like this when I'd forget to start mysql server, but I ensured it was running.
The GemFile is as such

    source 'http://rubygems.org'

gem 'rails', '3.2.8'
gem 'rubyzip', '0.9.9'
gem 'roo','1.12.1'
gem 'jdbc-mysql', '5.1.33', platform: :jruby
gem 'activerecord-jdbcmysql-adapter', '1.3.12', platform: :jruby
gem 'jquery-rails', '2.1.2'

gem 'haml', '3.1.7'
gem 'puma', '2.9.2'

gem 'devise', '2.1.2'
gem 'devise-async', '0.5.0'
gem 'cancan', '1.6.8'
gem 'simple_form', '2.0.4'
gem 'cocoon', '1.1.1'
gem 'inherited_resources', '1.3.1'
gem 'will_paginate', '3.0.3'
gem 'bootstrap-will_paginate', '0.0.9'
gem 'mechanize', '2.5.1'
gem 'delayed_job', '3.0.4'
gem 'paperclip', '3.4.0'
gem 'spreadsheet', '0.6.4.1'
gem 'geocoder', '1.1.6'
gem 'whenever', '0.8.2'
gem 'american_date', '1.0.0'
gem 'money','5.1.1'
gem 'rets', '0.11.0'
gem 'haversine','0.3.0'

gem 'celluloid','0.15.2'
gem 'sinatra', '1.4.6'
source "https://9789474f:e71b0546@gems.contribsys.com/" do
  gem 'sidekiq-pro','1.9.2'
end
gem 'redis','3.2.1'
gem 'remote_lock','1.1.0'
gem 'sidekiq-limit_fetch','2.3.0'

group :assets do
  gem 'stylus', '0.7.1'
  gem 'coffee-rails', '3.2.2'
  gem 'uglifier', '1.3.0'
end

group :development do
  gem 'net-ssh', '2.9.4'
  gem 'capistrano', '3.4.1'
  gem 'capistrano-rails', '1.3.0'
  gem 'capistrano-rvm', '0.1.2'
end

group :development, :test do
  gem 'dotenv-rails', '2.2.1'
  gem 'rspec-rails', '~> 3.5'
  gem 'fantaskspec'
end

group :test do
  gem 'factory_girl_rails', '~> 4.0'
  gem 'fantaskspec'
  gem 'vcr'
  gem 'fakeweb'
end

gem 'rest-client', '1.8.0'
gem 'poltergeist', '1.8.1'
gem 'nokogiri', '1.5.11'
gem 'zip-codes', '0.2.1'

gem 'elasticsearch-model', '0.1.9'
gem 'elasticsearch-rails', '0.1.9'
gem "fog", '1.38.0'
gem 'newrelic_rpm', '3.18.1.330'
gem 'sidekiq-scheduler', '2.1.7'
gem 'aws-sdk', '2.10.28'
gem 'StreetAddress', '1.0.6'

If there is more information required I'd be happy to provide it, let me know if anyone has run into this.

The odd thing is, these spec tests used to work fine prior to a merge I did with our repository. The other dev doesn't seem to be running into this same issue, so I can only assume the Gemfiles are all correct and that my environment is the issue.


问:
How to customize navigationbar in GooglePlacePicker on Swift4?

I'd have tried to customize NavigationController in GooglePlacePicker on Swift4, but there is not working what I want.

Does anyone know how to change navigation UI in placePicker on Swift4?
Thank you for reading this!

```<code>@IBAction func pickPlaceBtn(_ sender: Any) {

    let config:GMSPlacePickerConfig = GMSPlacePickerConfig(viewport: nil)
    print(config.viewport)
    let placePicker:GMSPlacePickerViewController = GMSPlacePickerViewController(config: config)

    placePicker.delegate = self
    present(placePicker, animated: true, completion: nil)

    //Does not work.
    placePicker.navigationController?.navigationBar.backgroundColor = UIColor.black

}
</code>```

enter image description here

答:
try this</p>

```<code>placePicker.navigationController?.navigationBar.barTintColor = UIColor.black
placePicker.navigationController?.navigationBar.isTranslucent = false
</code>```

Body:
I'd have tried to customize NavigationController in GooglePlacePicker on Swift4, but there is not working what I want.

Does anyone know how to change navigation UI in placePicker on Swift4?
Thank you for reading this!

@IBAction func pickPlaceBtn(_ sender: Any) {

    let config:GMSPlacePickerConfig = GMSPlacePickerConfig(viewport: nil)
    print(config.viewport)
    let placePicker:GMSPlacePickerViewController = GMSPlacePickerViewController(config: config)

    placePicker.delegate = self
    present(placePicker, animated: true, completion: nil)

    //Does not work.
    placePicker.navigationController?.navigationBar.backgroundColor = UIColor.black

}

enter image description here

Body:
try this

placePicker.navigationController?.navigationBar.barTintColor = UIColor.black
placePicker.navigationController?.navigationBar.isTranslucent = false


问:
Tensorflow neural network prediction is always the same
I have a deep CNN that predicts a label between "0" and "2" for every pixel in a 3d image. I have trained the model on an image where every pixel is labeled "1". Therefore, when testing the model, I believe every prediction should be "1". Instead the model only predicts "0".

Here is the repository for the whole model: https://github.com/dhasl002/Research-DeepLearning.

Since the code is almost 300 lines, I will include only the relevant code below.

```<code> x = tf.placeholder(tf.float32, shape=[None, 7168])
 y_ = tf.placeholder(tf.float32, shape=[None, 7168, 3])

 W_final = weight_variable([7168,7168,3])
 b_final = bias_variable([7168,3])

 #"final" is the result of the many convolutions
 final_conv = tf.tensordot(final, W_final, axes=[[1], [1]]) + b_final

 cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=final_conv))
 train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
 correct_prediction = tf.equal(tf.argmax(final_conv, 2), tf.argmax(y_, 2))
 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

 #a is a threshold associate with each pixel, b is the label of each pixel
 a = np.zeros((1,7168),dtype = float)
 b = np.zeros((1,7168, 3), dtype = float)

 #this is a little simplified for clarity of reader
 #TRAINING
 for line in inputFile:
   thresh, label = line.strip().split(",")
   a[0][it] = thresh
   b[0][it][label] = 1
 train_step.run(feed_dict={x: a, y_: b, keep_prob: .5})

 #TESTING
 for line in inputFile:
   thresh, label = line.strip().split(",")
   a[0][it] = thresh
   b[0][it][label] = 1
 temp = sess.run(tf.argmax(final_conv,2), feed_dict={x: a})
</code>```

I believe that "temp" from the last line should hold the correct predictions (7168 labels - one per pixel). Why does "temp" always result in all "0" labels when it is actually trained on images only with "1" labels?

答:
Since you're using ReLUs, one possibility is that you're suffering from the Dying ReLU Problem; you could fix this by switching to something like leaky ReLUs.

Beyond that, your model is quite deep and complex; in order to make sure it's working properly you might want to scale it back considerably, test it to see if it gives you reasonable results, and then add things back in stages.

In any event, it seems like your model is much too complex for the problem.  A model producing a label for each individual pixel should be pretty simple, since a given pixel's label probably only depends on nearby pixels, and probably not in a very complex way.

Body:
I have a deep CNN that predicts a label between "0" and "2" for every pixel in a 3d image. I have trained the model on an image where every pixel is labeled "1". Therefore, when testing the model, I believe every prediction should be "1". Instead the model only predicts "0".

Here is the repository for the whole model: https://github.com/dhasl002/Research-DeepLearning.

Since the code is almost 300 lines, I will include only the relevant code below.

 x = tf.placeholder(tf.float32, shape=[None, 7168])
 y_ = tf.placeholder(tf.float32, shape=[None, 7168, 3])

 W_final = weight_variable([7168,7168,3])
 b_final = bias_variable([7168,3])

 #"final" is the result of the many convolutions
 final_conv = tf.tensordot(final, W_final, axes=[[1], [1]]) + b_final

 cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=final_conv))
 train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
 correct_prediction = tf.equal(tf.argmax(final_conv, 2), tf.argmax(y_, 2))
 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

 #a is a threshold associate with each pixel, b is the label of each pixel
 a = np.zeros((1,7168),dtype = float)
 b = np.zeros((1,7168, 3), dtype = float)

 #this is a little simplified for clarity of reader
 #TRAINING
 for line in inputFile:
   thresh, label = line.strip().split(",")
   a[0][it] = thresh
   b[0][it][label] = 1
 train_step.run(feed_dict={x: a, y_: b, keep_prob: .5})

 #TESTING
 for line in inputFile:
   thresh, label = line.strip().split(",")
   a[0][it] = thresh
   b[0][it][label] = 1
 temp = sess.run(tf.argmax(final_conv,2), feed_dict={x: a})

I believe that "temp" from the last line should hold the correct predictions (7168 labels - one per pixel). Why does "temp" always result in all "0" labels when it is actually trained on images only with "1" labels?


问:
Suggestions on how to display 'correct_guesses'?
I am currently writing code for an interactive game of hangman. I have been given code to select a word at random, which I have then assigned to 'X' and made into a list.

I would like to be able to display a list of hyphens (correct_guesses) where the correct guesses are filled in in the correct place.
For example: if the word is 'glass', and the user guesses 'a', the computer displays "Good guess! [ - - a - -]" or something similar.
I'm not quite sure how to replace the hyphens with the correct guesses as the game goes on, or if I should I be approaching this in a different manner.

I apologize that this isn't very well articulated; I'm very new to coding.
I've included my code below.

```<code>    X = random.choice(wordlist)
    X.split()

    print "Welcome to Hangman."
    print "I've chosen a word that is", len(X), "letters long. Can you guess it? You have", (len(X) + 5 ), "guesses."

    alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    correct_guesses = [(len(X))*'-']

    guess = raw_input('Guess a letter.')

    for guess in alphabet:
        if guess in alphabet:
            alphabet.remove(guess)

            for guess in X:
                if guess in X:
                    print 'Good guess!'
                    break

                else:
                    print 'Nope! Try again.'
                    break

            break

        else:
               print "You have already guesssed that letter, try again."
</code>```

答:
Keep track of all the letters that have been guessed, then do:</p>

```<code>masked_letters = ''.join([if c in guessed then c else '-' for c in chosen_word])
</code>```

Body:
I am currently writing code for an interactive game of hangman. I have been given code to select a word at random, which I have then assigned to 'X' and made into a list.

I would like to be able to display a list of hyphens (correct_guesses) where the correct guesses are filled in in the correct place.
For example: if the word is 'glass', and the user guesses 'a', the computer displays "Good guess! [ - - a - -]" or something similar.
I'm not quite sure how to replace the hyphens with the correct guesses as the game goes on, or if I should I be approaching this in a different manner.

I apologize that this isn't very well articulated; I'm very new to coding.
I've included my code below.

    X = random.choice(wordlist)
    X.split()

    print "Welcome to Hangman."
    print "I've chosen a word that is", len(X), "letters long. Can you guess it? You have", (len(X) + 5 ), "guesses."

    alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    correct_guesses = [(len(X))*'-']

    guess = raw_input('Guess a letter.')

    for guess in alphabet:
        if guess in alphabet:
            alphabet.remove(guess)

            for guess in X:
                if guess in X:
                    print 'Good guess!'
                    break

                else:
                    print 'Nope! Try again.'
                    break

            break

        else:
               print "You have already guesssed that letter, try again."

Body:
Keep track of all the letters that have been guessed, then do:

masked_letters = ''.join([if c in guessed then c else '-' for c in chosen_word])


问:
How to change the location of classes generated by MapStruct?
I am using MapStruct to generate the mapping between the JAXB classes and my domain classes.
I am using gradle plugin as described in MapStruct official site. During the compilation process, the classes are generated in "build/generated/sources/apt/main".
How can i change this location? I am not able to find any guide for gradle though there is a compiler flag to change it through ant script, but unfortunately it is not working for gradle
Any help is appreciated. </p>

答:
This is not linked to MapStruct, but to the way the gradle apt plugin works and how it tells the Java compiler to place the generated sources.

To configure the generated sources of the plugin according to the configuration documentation. One needs to extend the aptOptions of the compile. The property controlling the destination of the generated is generatedSourcesDestinationDir


问:
Sort text column alphanumerically (letters before numbers)
I am trying to sort our inventory list alphanumerically by part number such that letters are sorted before numbers. For instance, given the list:

```<code>0004006A
AN42B10
0400975
1968
MS21042L3
0004006
AN414A
J961393
AN4H16A
SR22SCW20
STD1410
4914
15KE51CA
21
560
</code>```

the sorted list should be:

```<code>AN4H16A
AN414A
AN42B10
J961393
MS21042L3
SR22SCW20
STD1410
0004006
0004006A
0400975
15KE51CA
1968
21
4914
560
</code>```

Currently, I can only get it to sort with numbers before letters so the list looks like:

```<code>004006
0004006A
0400975
15KE51CA
1968
21
4914
560
AN414A
AN42B10
AN4H16A
J961393
MS21042L3
SR22SCW20
STD1410
</code>```

(Note especially AN4H16A coming after AN42B10 and AN414A rather than before.)

I have tried adding a custom list (A, B, C, ..., 7, 8, 9) but get the same result sorting by that list.

Is this possible?

答:
The following solution is for LO Calc.  If the data is in A1 through A15, then enter the following formula into B1.

```<code>=IF(LEN($A1)<COLUMN()-1;-1;IF(CODE(MID($A1;COLUMN()-1;1))<=CODE(9);MID($A1;COLUMN()-1;1)+27;CODE(MID($A1;COLUMN()-1;1))-CODE("A")))
</code>```

This gets the first character of the string in A1 and then determines a sorting value for that character, with "A" becoming 0 (the first in sorted order) and "9" becoming 36 (the last in sorted order).

Now, drag and fill over to J15 for the rest of the characters in the string, then down to J15 for the other strings.

Then, go to Data -> Sort.  Sort Key 1 is column B, sort key 2 is column C, and so on through J.

Alternatively, select A1 through A15 and then run the following Python macro.

import uno

def custom_sort():
    oSelect = XSCRIPTCONTEXT.getDocument().getCurrentSelection()
    rowTuples = oSelect.getDataArray()
    rowTuples = sorted(rowTuples, key=letters_then_numbers)
    oSelect.setDataArray(rowTuples)

def letters_then_numbers(rowTuple):
    strval = str(rowTuple[0])
    sresult = ""
    for c in strval:
        if c in (str(i) for i in range(10)):  # if character is a number
            c = chr(ord('z') + int(c))        # then order it after z
        sresult += c
    return sresult

g_exportedScripts = custom_sort,
```

Body:
I am trying to sort our inventory list alphanumerically by part number such that letters are sorted before numbers. For instance, given the list:

0004006A
AN42B10
0400975
1968
MS21042L3
0004006
AN414A
J961393
AN4H16A
SR22SCW20
STD1410
4914
15KE51CA
21
560

the sorted list should be:

AN4H16A
AN414A
AN42B10
J961393
MS21042L3
SR22SCW20
STD1410
0004006
0004006A
0400975
15KE51CA
1968
21
4914
560

Currently, I can only get it to sort with numbers before letters so the list looks like:

004006
0004006A
0400975
15KE51CA
1968
21
4914
560
AN414A
AN42B10
AN4H16A
J961393
MS21042L3
SR22SCW20
STD1410

(Note especially AN4H16A coming after AN42B10 and AN414A rather than before.)

I have tried adding a custom list (A, B, C, ..., 7, 8, 9) but get the same result sorting by that list.

Is this possible?

Body:
The following solution is for LO Calc.  If the data is in A1 through A15, then enter the following formula into B1.

=IF(LEN($A1)<COLUMN()-1;-1;IF(CODE(MID($A1;COLUMN()-1;1))<=CODE(9);MID($A1;COLUMN()-1;1)+27;CODE(MID($A1;COLUMN()-1;1))-CODE("A")))

This gets the first character of the string in A1 and then determines a sorting value for that character, with "A" becoming 0 (the first in sorted order) and "9" becoming 36 (the last in sorted order).

Now, drag and fill over to J15 for the rest of the characters in the string, then down to J15 for the other strings.

Then, go to Data -> Sort.  Sort Key 1 is column B, sort key 2 is column C, and so on through J.

Alternatively, select A1 through A15 and then run the following Python macro.

import uno

def custom_sort():
    oSelect = XSCRIPTCONTEXT.getDocument().getCurrentSelection()
    rowTuples = oSelect.getDataArray()
    rowTuples = sorted(rowTuples, key=letters_then_numbers)
    oSelect.setDataArray(rowTuples)

def letters_then_numbers(rowTuple):
    strval = str(rowTuple[0])
    sresult = ""
    for c in strval:
        if c in (str(i) for i in range(10)):  # if character is a number
            c = chr(ord('z') + int(c))        # then order it after z
        sresult += c
    return sresult

g_exportedScripts = custom_sort,


问:
android: proguard obfuscating imported jars
I've made a IM client that uses the asmack .jar library to communicate with google IM service server.

Now I am trying to export my application from eclipse and use the proguard tool to obfuscate my classes.
The problem is that after exporting the project and running it, I can't log on to google because I get errors from the asmack lib...

one of the errors: 01-21 09:52:19.602: WARN/System.err(24297): java.lang.UnsupportedOperationException: java.lang.NoSuchMethodException: values
I also get NoSuchClassException and some names of packages from asmack.

What settings do I have to make to get this work?
Thank you!

答: Problem solved... I had to put all the classes noticed in the error in the -keep public class property of progurad</p>


问:
JSON schema conditional dependency on value
I know there is a similar question here, but it didn't really address my issue. In short, I want one my fields to be dependent on the other field's value. But for some values, I don't want any field to be required. Here is an example:

Schema

```<code>{
  "definitions": {},
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {

    "colour": {
      "type": "string",
      "enum": ["red", "black", "blue"]
    },

    "blackQuote": {
      "type": "string",
      "maxLength": 11
    },

    "redQuote": {
      "type": "string",
      "maxLength": 11
    }
  },

  "oneOf": [
      {
        "properties": {
          "colour": {"enum": ["red"]}
        },
        "required": ["redQuote"]
      },
      {
        "properties": {
          "colour": {"enum": ["black"]}
        },
        "required": ["blackQuote"]
      }
  ],

  "required": [
    "colour"
  ]
}
</code>```

This works like this:

IF the colour is "red" THEN "redQuote" (but not "blackQuote") is required: this is fine

IF the colour is "black" THEN "blackQuote" (but not "redQuote") is required: this is also fine

BUT if I put the colour "blue" in my JSON, then the validator says that the properties "redQuote" and "blackQuote" are missing... I don't want that, I only want dependecies for "red" and "black", but if the colour is "blue" I don't want anything required. How to achieve this?

答:
You can do this with a boolean logic concept called implication (!A or B).  It can be used like an "if-then" statement.  For example, either "color" is not "red" or "redQuote" is required.  Any time I need to use this, I break it down with definitions so it reads as nice as possible.

```<code>{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "colour": { "enum": ["red", "black", "blue"] },
    "blackQuote": { "type": "string", "maxLength": 11 },
    "redQuote": { "type": "string", "maxLength": 11 }
  },
  "allOf": [
    { "$ref": "#/definitions/red-requires-redQuote" },
    { "$ref": "#/definitions/black-requires-blackQuote" }
  ],
  "required": ["colour"],
  "definitions": {
    "red-requires-redQuote": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/is-red" } },
        { "required": ["redQuote"] }
      ]
    },
    "black-requires-blackQuote": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/is-black" } },
        { "required": ["blackQuote"] }
      ]
    },
    "is-red": {
      "properties": {
        "colour": { "enum": ["red"] }
      },
      "required": ["colour"]
    },
    "is-black": {
      "properties": {
        "colour": { "enum": ["black"] }
      },
      "required": ["colour"]
    }
  }
}
</code>```

Body:
I know there is a similar question here, but it didn't really address my issue. In short, I want one my fields to be dependent on the other field's value. But for some values, I don't want any field to be required. Here is an example:

Schema

{
  "definitions": {},
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {

    "colour": {
      "type": "string",
      "enum": ["red", "black", "blue"]
    },

    "blackQuote": {
      "type": "string",
      "maxLength": 11
    },

    "redQuote": {
      "type": "string",
      "maxLength": 11
    }
  },

  "oneOf": [
      {
        "properties": {
          "colour": {"enum": ["red"]}
        },
        "required": ["redQuote"]
      },
      {
        "properties": {
          "colour": {"enum": ["black"]}
        },
        "required": ["blackQuote"]
      }
  ],

  "required": [
    "colour"
  ]
}

This works like this:

IF the colour is "red" THEN "redQuote" (but not "blackQuote") is required: this is fine

IF the colour is "black" THEN "blackQuote" (but not "redQuote") is required: this is also fine

BUT if I put the colour "blue" in my JSON, then the validator says that the properties "redQuote" and "blackQuote" are missing... I don't want that, I only want dependecies for "red" and "black", but if the colour is "blue" I don't want anything required. How to achieve this?

Body:
You can do this with a boolean logic concept called implication (!A or B).  It can be used like an "if-then" statement.  For example, either "color" is not "red" or "redQuote" is required.  Any time I need to use this, I break it down with definitions so it reads as nice as possible.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "colour": { "enum": ["red", "black", "blue"] },
    "blackQuote": { "type": "string", "maxLength": 11 },
    "redQuote": { "type": "string", "maxLength": 11 }
  },
  "allOf": [
    { "$ref": "#/definitions/red-requires-redQuote" },
    { "$ref": "#/definitions/black-requires-blackQuote" }
  ],
  "required": ["colour"],
  "definitions": {
    "red-requires-redQuote": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/is-red" } },
        { "required": ["redQuote"] }
      ]
    },
    "black-requires-blackQuote": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/is-black" } },
        { "required": ["blackQuote"] }
      ]
    },
    "is-red": {
      "properties": {
        "colour": { "enum": ["red"] }
      },
      "required": ["colour"]
    },
    "is-black": {
      "properties": {
        "colour": { "enum": ["black"] }
      },
      "required": ["colour"]
    }
  }
}


问:
Mule DataWeave - XML to json transformation - check XML attribute exists
This is my payload before transformation:

```<code>Payload: <stock article_id="28932" lot_number="282779"/>
</code>```

This is the dataweave code to transform xml to json:

```<code>stockPayload: {
        articleId: payload.stock_adjustment.@article_id,
        lotNumber: payload.stock_adjustment.@lot_number,
        uom: payload.stock_adjustment.@uom,
    }
</code>```

Now the uom is an optional field so it wouldn't be in xml attribute sometime. This transformation is currently throwing mapping error due to uom attribute not found.

How can I allow the dataweave to transform even attribute is not in xml?

答:
For XML to JSON transformation

, you can try below:

Skip Null On

Whenever the output is of XML or JSON type and has null values in its elements or attributes, you can specify whether this generates an outbound message that contains fields with "null" values, or if these fields are ignored entirely. This can be set through an attribute in the output directive named skipNullOn, which can be set to three different values: elements, attributes, or everywhere.

```<code>%output application/xml skipNullOn="everywhere"
</code>```

When set to:

elements: A key:value pair with a null value is ignored.

attributes: An XML attribute with a null value is skipped.

everywhere: Apply this rule to both elements and attributes.

Ref below link for more details,

DWL reference

Body:
This is my payload before transformation:

Payload: <stock article_id="28932" lot_number="282779"/>

This is the dataweave code to transform xml to json:

stockPayload: {
        articleId: payload.stock_adjustment.@article_id,
        lotNumber: payload.stock_adjustment.@lot_number,
        uom: payload.stock_adjustment.@uom,
    }

Now the uom is an optional field so it wouldn't be in xml attribute sometime. This transformation is currently throwing mapping error due to uom attribute not found.

How can I allow the dataweave to transform even attribute is not in xml?

Body:
For XML to JSON transformation

, you can try below:

Skip Null On

Whenever the output is of XML or JSON type and has null values in its elements or attributes, you can specify whether this generates an outbound message that contains fields with "null" values, or if these fields are ignored entirely. This can be set through an attribute in the output directive named skipNullOn, which can be set to three different values: elements, attributes, or everywhere.

%output application/xml skipNullOn="everywhere"

When set to:

elements: A key:value pair with a null value is ignored.

attributes: An XML attribute with a null value is skipped.

everywhere: Apply this rule to both elements and attributes.

Ref below link for more details,

DWL reference