问:
Validation for textbox with two sets of phone numbers
I am trying to do a validation on a textbox that can allow the input of one or more phone number in a single textbox. What I am trying to do is to send an message to the phone numbers included in the textbox.
I have no problem when I enter just one set of number into the textbox and the message can be sent.
However, whenever I type two sets of digit into the same textbox, my validation error will appear.

I am using user controls and putting the user control in a listview.

Here are my codes:

```<code>private ObservableCollection<IFormControl> formFields;
internal ObservableCollection<IFormControl> FormFields
    {
        get
        {
            if (formFields == null)
            {

                formFields = new ObservableCollection<IFormControl>(new List<IFormControl>()
            {
                new TextFieldInputControlViewModel(){ColumnWidth = new GridLength(350) ,HeaderName = "Recipient's mobile number *"  , IsMandatory = true, MatchingPattern = @"^[\+]?[1-9]{1,3}\s?[0-9]{6,11}$", Tag="phone", ContentHeight = 45, ErrorMessage = "Please enter recipient mobile number. "},

            });
            }

            return formFields;
        }
    }
</code>```

And here is the codes for the button click event:

```<code>private void OkButton_Click(object sender, RoutedEventArgs e)
    {
        MessageDialog clickMessage;
        UICommand YesBtn;
        int result = 0;

        //Fetch Phone number
        var phoneno = FormFields.FirstOrDefault(x => x.Tag?.ToLower() == "phone").ContentToStore;

        string s = phoneno;
        string[] numbers = s.Split(';');
        foreach (string number in numbers)
        {
            int parsedValue;
            if (int.TryParse(number, out parsedValue) && number.Length.Equals(8))
            {
                result++;
            }
            else
            { }
        }
        if (result.Equals(numbers.Count()))
        {
            try
            {
                for (int i = 0; i < numbers.Count(); i++)
                {
                    Class.SMS sms = new Class.SMS();
                    sms.sendSMS(numbers[i], @"Hi, this is a message from Nanyang Polytechnic School of IT. The meeting venue is located at Block L." + Environment.NewLine + "Click below to view the map " + Environment.NewLine + location);
                    clickMessage = new MessageDialog("The SMS has been sent to the recipient.");
                    timer = new DispatcherTimer();
                    timer.Interval = TimeSpan.FromSeconds(1);
                    timer.Tick += timer_Tick;
                    timer.Start();
                    YesBtn = new UICommand("Ok", delegate (IUICommand command)
                    {
                        timer.Stop();
                        idleTimer.Stop();
                        var rootFrame = (Window.Current.Content as Frame);
                        rootFrame.Navigate(typeof(HomePage));
                        rootFrame.BackStack.Clear();
                    });
                    clickMessage.Commands.Add(YesBtn);
                    clickMessage.ShowAsync();
                }
            }
            catch (Exception ex)
            { }
        }

    }
</code>```

I am trying to separate the two numbers with ";" sign.... and I am wondering if that is the problem. Or maybe it is the matchingpattern that I have placed in.

答:
The answer is quite simple, create a bool property in your TextFieldInputControlViewModel something like

```<code>public bool AcceptMultiple {get;set;}
</code>```

and to keep things dynamic, create a char property as a separator like below:

```<code>public char Separator {get;set;}
</code>```

Now, modify your  new TextFieldInputControlViewModel() code statement by adding values to your new fields like below:

```<code>new TextFieldInputControlViewModel(){Separator = ';', AcceptMultiple = true, ColumnWidth = new GridLength(350) ,HeaderName = "Recipient's mobile number *"  , IsMandatory = true, MatchingPattern = @"^[\+]?[1-9]{1,3}\s?[0-9]{6,11}$", Tag="phone", ContentHeight = 45, ErrorMessage = "Please enter recipient mobile number. "},
</code>```

Once it's done, now in your checkValidation() function (or where you check the validation or pattern match) can be replaced with something like below:

```<code>if(AcceptMultiple)
{
    if(Separator == null)
        throw new ArgumentNullException("You have to provide a separator to accept multiple entries.");

    string[] textItems = textField.Split(Separator);
    if(textItems?.Length < 1)
    {
        ErrorMessage = "Please enter recipient mobile number." //assuming that this is your field for what message has to be shown.
        IsError = true; //assuming this is your bool field that shows all the errors
        return;
    }

    //do a quick check if the pattern matching is mandatory. if it's not, just return.
    if(!IsMandatory)
        return;

    //your Matching Regex Pattern
    Regex rgx = new Regex(MatchingPattern);

    //loop through every item in the array to find the first entry that's invalid
    foreach(var item in textItems)
    {
        //only check for an invalid input as the valid one's won't trigger any thing.
        if(!rgx.IsMatch(item))
        {
            ErrorMessage = $"{item} is an invalid input";
            IsError = true;
            break;  //this statement will prevent the loop from continuing.
        }
    }
}
</code>```

And that'll do it.

I've taken a few variable names as an assumption as the information was missing in the question. I've mentioned it in the comments about them. Make sure you replace them.

Body:
I am trying to do a validation on a textbox that can allow the input of one or more phone number in a single textbox. What I am trying to do is to send an message to the phone numbers included in the textbox.
I have no problem when I enter just one set of number into the textbox and the message can be sent.
However, whenever I type two sets of digit into the same textbox, my validation error will appear.

I am using user controls and putting the user control in a listview.

Here are my codes:

private ObservableCollection<IFormControl> formFields;
internal ObservableCollection<IFormControl> FormFields
    {
        get
        {
            if (formFields == null)
            {

                formFields = new ObservableCollection<IFormControl>(new List<IFormControl>()
            {
                new TextFieldInputControlViewModel(){ColumnWidth = new GridLength(350) ,HeaderName = "Recipient's mobile number *"  , IsMandatory = true, MatchingPattern = @"^[\+]?[1-9]{1,3}\s?[0-9]{6,11}$", Tag="phone", ContentHeight = 45, ErrorMessage = "Please enter recipient mobile number. "},

            });
            }

            return formFields;
        }
    }

And here is the codes for the button click event:

private void OkButton_Click(object sender, RoutedEventArgs e)
    {
        MessageDialog clickMessage;
        UICommand YesBtn;
        int result = 0;

        //Fetch Phone number
        var phoneno = FormFields.FirstOrDefault(x => x.Tag?.ToLower() == "phone").ContentToStore;

        string s = phoneno;
        string[] numbers = s.Split(';');
        foreach (string number in numbers)
        {
            int parsedValue;
            if (int.TryParse(number, out parsedValue) && number.Length.Equals(8))
            {
                result++;
            }
            else
            { }
        }
        if (result.Equals(numbers.Count()))
        {
            try
            {
                for (int i = 0; i < numbers.Count(); i++)
                {
                    Class.SMS sms = new Class.SMS();
                    sms.sendSMS(numbers[i], @"Hi, this is a message from Nanyang Polytechnic School of IT. The meeting venue is located at Block L." + Environment.NewLine + "Click below to view the map " + Environment.NewLine + location);
                    clickMessage = new MessageDialog("The SMS has been sent to the recipient.");
                    timer = new DispatcherTimer();
                    timer.Interval = TimeSpan.FromSeconds(1);
                    timer.Tick += timer_Tick;
                    timer.Start();
                    YesBtn = new UICommand("Ok", delegate (IUICommand command)
                    {
                        timer.Stop();
                        idleTimer.Stop();
                        var rootFrame = (Window.Current.Content as Frame);
                        rootFrame.Navigate(typeof(HomePage));
                        rootFrame.BackStack.Clear();
                    });
                    clickMessage.Commands.Add(YesBtn);
                    clickMessage.ShowAsync();
                }
            }
            catch (Exception ex)
            { }
        }

    }

I am trying to separate the two numbers with ";" sign.... and I am wondering if that is the problem. Or maybe it is the matchingpattern that I have placed in.

Body:
The answer is quite simple, create a bool property in your TextFieldInputControlViewModel something like

public bool AcceptMultiple {get;set;}

and to keep things dynamic, create a char property as a separator like below:

public char Separator {get;set;}

Now, modify your  new TextFieldInputControlViewModel() code statement by adding values to your new fields like below:

new TextFieldInputControlViewModel(){Separator = ';', AcceptMultiple = true, ColumnWidth = new GridLength(350) ,HeaderName = "Recipient's mobile number *"  , IsMandatory = true, MatchingPattern = @"^[\+]?[1-9]{1,3}\s?[0-9]{6,11}$", Tag="phone", ContentHeight = 45, ErrorMessage = "Please enter recipient mobile number. "},

Once it's done, now in your checkValidation() function (or where you check the validation or pattern match) can be replaced with something like below:

if(AcceptMultiple)
{
    if(Separator == null)
        throw new ArgumentNullException("You have to provide a separator to accept multiple entries.");

    string[] textItems = textField.Split(Separator);
    if(textItems?.Length < 1)
    {
        ErrorMessage = "Please enter recipient mobile number." //assuming that this is your field for what message has to be shown.
        IsError = true; //assuming this is your bool field that shows all the errors
        return;
    }

    //do a quick check if the pattern matching is mandatory. if it's not, just return.
    if(!IsMandatory)
        return;

    //your Matching Regex Pattern
    Regex rgx = new Regex(MatchingPattern);

    //loop through every item in the array to find the first entry that's invalid
    foreach(var item in textItems)
    {
        //only check for an invalid input as the valid one's won't trigger any thing.
        if(!rgx.IsMatch(item))
        {
            ErrorMessage = $"{item} is an invalid input";
            IsError = true;
            break;  //this statement will prevent the loop from continuing.
        }
    }
}

And that'll do it.

I've taken a few variable names as an assumption as the information was missing in the question. I've mentioned it in the comments about them. Make sure you replace them.


来源: stackexchange

问:
convert pdf to byteArray - byteArray to String - String to byteArray - byteArray to pdf
I have the following code which works for text files but doesn't work for pdf files. My files contain english and greek characters. I try to convert a pdf file to byteStream and the byteStream to String format in order to save it in database. After this I try to create the pdf from the saved String.

Any help?

```<code>public class PdfToByteStream {

    public static byte[] convertDocToByteArray(String path)throws FileNotFoundException, IOException{
        File file = new File(path);

        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
            }
        } catch (IOException ex) {
            Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
        }
        byte[] bytes = bos.toByteArray();
        return bytes;
    }

    public static void convertByteArrayToDoc(String path, byte[] bytes)throws FileNotFoundException, IOException {
        File someFile = new File(path);
        FileOutputStream fos = new FileOutputStream(someFile);
        fos.write(bytes);
        fos.flush();
        fos.close();
    }

    public static void main(String[] args) throws FileNotFoundException, IOException {
        byte[] bytes = convertDocToByteArray("path/test.pdf");

        String stream = new String(bytes, "UTF-8");//ok for txt
        byte[] newBytes = stream.getBytes(Charset.forName("UTF-8")); // ok for txt

        convertByteArrayToDoc("path/newTest.pdf", newBytes);
    }
}
</code>```

答:
If you use Base64 encoding you will be able to convert the PDF to a string and back.

Here is the relevant part of the code which needs to be changed:

```<code>import java.util.Base64;

...

public static void main(String[] args) throws FileNotFoundException, IOException {
    byte[] bytes = convertDocToByteArray("some.pdf");
    String stream = Base64.getEncoder().encodeToString(bytes);
    byte[] newBytes = Base64.getDecoder().decode(stream);
    convertByteArrayToDoc("some_new.pdf", newBytes);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following code which works for text files but doesn't work for pdf files. My files contain english and greek characters. I try to convert a pdf file to byteStream and the byteStream to String format in order to save it in database. After this I try to create the pdf from the saved String.

Any help?

public class PdfToByteStream {

    public static byte[] convertDocToByteArray(String path)throws FileNotFoundException, IOException{
        File file = new File(path);

        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
            }
        } catch (IOException ex) {
            Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
        }
        byte[] bytes = bos.toByteArray();
        return bytes;
    }

    public static void convertByteArrayToDoc(String path, byte[] bytes)throws FileNotFoundException, IOException {
        File someFile = new File(path);
        FileOutputStream fos = new FileOutputStream(someFile);
        fos.write(bytes);
        fos.flush();
        fos.close();
    }

    public static void main(String[] args) throws FileNotFoundException, IOException {
        byte[] bytes = convertDocToByteArray("path/test.pdf");

        String stream = new String(bytes, "UTF-8");//ok for txt
        byte[] newBytes = stream.getBytes(Charset.forName("UTF-8")); // ok for txt

        convertByteArrayToDoc("path/newTest.pdf", newBytes);
    }
}

Body:
If you use Base64 encoding you will be able to convert the PDF to a string and back.

Here is the relevant part of the code which needs to be changed:

import java.util.Base64;

...

public static void main(String[] args) throws FileNotFoundException, IOException {
    byte[] bytes = convertDocToByteArray("some.pdf");
    String stream = Base64.getEncoder().encodeToString(bytes);
    byte[] newBytes = Base64.getDecoder().decode(stream);
    convertByteArrayToDoc("some_new.pdf", newBytes);
}


问:
How to avoid query execution timeout in PostgreSQL?
I am running a below update query on a table with 10M records,

```<code>update table1 t1 set col1=(select coalesce((select t2.col2 from table1 t2 where t1.col3=t2.col4 limit 1), null));
</code>```

When I am running above query I am getting the below exception because it is taking so much time to execute the query,

```<code>java.net.SocketException: Socket closed
    at java.net.SocketInputStream.socketRead0(Native Method) ~[na:1.8.0_121]
    at java.net.SocketInputStream.socketRead(SocketInputStream.java:116) ~[na:1.8.0_121]
    at java.net.SocketInputStream.read(SocketInputStream.java:171) ~[na:1.8.0_121]
    at java.net.SocketInputStream.read(SocketInputStream.java:141) ~[na:1.8.0_121]
    at sun.security.ssl.InputRecord.readFully(InputRecord.java:465) ~[na:1.8.0_121]
    at sun.security.ssl.InputRecord.read(InputRecord.java:503) ~[na:1.8.0_121]
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973) ~[na:1.8.0_121]
    at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:930) ~[na:1.8.0_121]
    at sun.security.ssl.AppInputStream.read(AppInputStream.java:105) ~[na:1.8.0_121]
    at org.postgresql.core.VisibleBufferedInputStream.readMore(VisibleBufferedInputStream.java:146) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.core.VisibleBufferedInputStream.ensureBytes(VisibleBufferedInputStream.java:115) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.core.VisibleBufferedInputStream.read(VisibleBufferedInputStream.java:71) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.core.PGStream.ReceiveChar(PGStream.java:283) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1719) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:173) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    ... 64 common frames omitted
Wrapped by: org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:201) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:622) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:458) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.jdbc.PgStatement.executeUpdate(PgStatement.java:406) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.springframework.jdbc.core.JdbcTemplate$1UpdateStatementCallback.doInStatement(JdbcTemplate.java:523) ~[spring-jdbc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate$1UpdateStatementCallback.doInStatement(JdbcTemplate.java:520) ~[spring-jdbc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:404) ~[spring-jdbc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    ... 58 common frames omitted
</code>```

Is there a way I can simply say that, "Just fire the query and don't wait for the response" so that I can avoid socket timeout? I am using spring provided JDBC Template.

答:
I can give you two pragmatic solutions for this:

Execute the query in a new Thread(){...}.start(). Even better would be to create lightweight Runnables and give them to a Executors.newCachedThreadPool()

use a typesafe query constructor language like for example JOOQ or QueryDSL. JOOQ can generate type-safe classes from the database for you to create your queries. These classes have all the asynchronous implementations you need: dsl.update(TABLE1).set(...).executeAsync()

But still, one main question remains: Do you want to avoid the socket timeout or do you want to ignore it?

The above is for ignoring the socket-timeout.
The following solutions may fit better by avoiding the socket-timeout:

Catch the error and react to it. For example: Tell the user, that the number of records to update is too many.

Split the update statements into several batches (in the background), so the update will always succeed. (there are tools to do this for you easily. JOOQ can do also that for you)

Body:
I am running a below update query on a table with 10M records,

update table1 t1 set col1=(select coalesce((select t2.col2 from table1 t2 where t1.col3=t2.col4 limit 1), null));

When I am running above query I am getting the below exception because it is taking so much time to execute the query,

java.net.SocketException: Socket closed
    at java.net.SocketInputStream.socketRead0(Native Method) ~[na:1.8.0_121]
    at java.net.SocketInputStream.socketRead(SocketInputStream.java:116) ~[na:1.8.0_121]
    at java.net.SocketInputStream.read(SocketInputStream.java:171) ~[na:1.8.0_121]
    at java.net.SocketInputStream.read(SocketInputStream.java:141) ~[na:1.8.0_121]
    at sun.security.ssl.InputRecord.readFully(InputRecord.java:465) ~[na:1.8.0_121]
    at sun.security.ssl.InputRecord.read(InputRecord.java:503) ~[na:1.8.0_121]
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973) ~[na:1.8.0_121]
    at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:930) ~[na:1.8.0_121]
    at sun.security.ssl.AppInputStream.read(AppInputStream.java:105) ~[na:1.8.0_121]
    at org.postgresql.core.VisibleBufferedInputStream.readMore(VisibleBufferedInputStream.java:146) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.core.VisibleBufferedInputStream.ensureBytes(VisibleBufferedInputStream.java:115) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.core.VisibleBufferedInputStream.read(VisibleBufferedInputStream.java:71) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.core.PGStream.ReceiveChar(PGStream.java:283) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1719) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:173) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    ... 64 common frames omitted
Wrapped by: org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:201) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:622) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:458) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.postgresql.jdbc.PgStatement.executeUpdate(PgStatement.java:406) ~[postgresql-9.4.1207.jre7.jar:9.4.1207.jre7]
    at org.springframework.jdbc.core.JdbcTemplate$1UpdateStatementCallback.doInStatement(JdbcTemplate.java:523) ~[spring-jdbc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate$1UpdateStatementCallback.doInStatement(JdbcTemplate.java:520) ~[spring-jdbc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:404) ~[spring-jdbc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    ... 58 common frames omitted

Is there a way I can simply say that, "Just fire the query and don't wait for the response" so that I can avoid socket timeout? I am using spring provided JDBC Template.


问:
Commands not working in a script
I'm trying to write my first bash script to automate some boring stuff I have to type everytime but can't get it working.
I've created pgAdmin.sh in my home directory:

```<code>#!/bin/bash
cd /opt/enviromentpy/pgadmin4
source bin/activate
python lib/python2.7/site-packages/pgadmin4/pgAdmin4.py
</code>```

When I run it using ./pgAdmin.sh I get:

```<code>./pgAdmin.sh: line 2: cd: /opt/enviromentpy/pgadmin4: No such file or
directory
./pgAdmin.sh: line 3: bin/activate: No such file or directory
python: can't open file 'lib/python2.7/site-packages/pgadmin4/pgAdmin4.py': [Errno 2] No such file or directory
</code>```

But when I open terminal and just put those commands one by one from Home directory it works just fine.

答:
You have made a simple spelling mistake.

Instead of enviromentpy you probably meant to write enviromentpy (notice the extra n)

Title: Commands not working in a script

Body:
I'm trying to write my first bash script to automate some boring stuff I have to type everytime but can't get it working.
I've created pgAdmin.sh in my home directory:

#!/bin/bash
cd /opt/enviromentpy/pgadmin4
source bin/activate
python lib/python2.7/site-packages/pgadmin4/pgAdmin4.py

When I run it using ./pgAdmin.sh I get:

./pgAdmin.sh: line 2: cd: /opt/enviromentpy/pgadmin4: No such file or
directory
./pgAdmin.sh: line 3: bin/activate: No such file or directory
python: can't open file 'lib/python2.7/site-packages/pgadmin4/pgAdmin4.py': [Errno 2] No such file or directory

But when I open terminal and just put those commands one by one from Home directory it works just fine.


问:
XAML editing options
I use Visual Studio 2010 for WPF development of desktop apps.  I edit my XAML with the visual editor, often tweaking it manually.  My code-behind is C#.   I haven't had any particular problems with this arrangement.

What are the advantages of Expression Blend over Visual Studio for editing XAML?    Why is Expression Blend so expensive (it's more expensive than I paid for Visual Studio!!)   Are there other full-featured XAML editors which are cheaper?   (I'm not talking about free ones like kaxaml - those are too limited)

Thanks in advance.

答:
Expression Blend does not come stand alone any longer; it is part of Expression Studio which also provides SketchFlow, Design, and a couple of other tools.

Visual Studio is geared towards the development aspect while Expression Blend is geared towards the design aspect. Building animations and performing binding all within the UI of Expression Blend is possible; not forcing you to modify the XAML by hand. You can however modify the XAML directly within Blend as you can the C# code behind as well.

I typically use Blend to lay out the UI and then make use of Visual Studio for the code behind and tweaking of the XAML. Blend is definitely a nice tool to have within your tool belt and I would recommend you download the trial to get a better understanding on the offering.

ContentLicense: CC BY-SA 2.5

Title: XAML editing options


问:
Image to the left, text centered (in page)
I am trying to align an about me page, where i would like an image to the left of the container and the text to the right aligned centered to the page.
this is what i've got

```<code><img link img>
<h2>
jack
</h2>
<p>
dummy text
</p>
</code>```

https://jsfiddle.net/a0sozwjk/1/

article#main-col {
  float: left;
  width: 65%;
}

.dark {
  padding: 15px;
  background: #35424a;
  color: #fff;
  margin-top: 10px;
  margin-bottom: 10px;
}

.container {
  width: 80%;
  margin: auto;
  overflow: hidden;
}

article#main-col {
  float: left;
  width: 65%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><center>
  <Section id="main">
    <div class="container">
      <article id="main-About-Col">
        <h1 class="PTitle">About us</h1>
        <div class="dark">
          <img style="float:left; vertical-align:center;" alt="Jack Picture" width="125px" src="https://thumb1.shutterstock.com/display_pic_with_logo/1000172/291874463/stock-vector-notebook-template-vector-example-of-using-hand-drawn-food-pattern-for-cover-of-cooking-book-291874463.jpg">
          <h2>
            Jack
          </h2>
          <p>
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis,
            sem.
          </p>
        </div>
      </article>
    </div>
  </Section>
</center></code>```

答:
I just put the elements in a flexbox, group the text elements in the same flex child, then use align-items: center;!

Does it work for you?

article#main-col {
  float: left;
  width: 65%;
}

.dark {
  padding: 15px;
  background: #35424a;
  color: #fff;
  margin-top: 10px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.container {
  width: 80%;
  margin: auto;
  overflow: hidden;
}

article#main-col {
  float: left;
  width: 65%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><center>
  <Section id="main">
    <div class="container">
      <article id="main-About-Col">
        <h1 class="PTitle">About us</h1>
        <div class="dark">
          <img style="float:left; vertical-align:center;" alt="Jack Picture" width="125px" src="https://thumb1.shutterstock.com/display_pic_with_logo/1000172/291874463/stock-vector-notebook-template-vector-example-of-using-hand-drawn-food-pattern-for-cover-of-cooking-book-291874463.jpg">
          <div>
          <h2>
            Jack
          </h2>
          <p>
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis,
            sem.
          </p>
          </div>
        </div>
      </article>
    </div>
  </Section>
</center></code>```

Here is a cheatsheet if you don't know about flexboxes yet: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Body:
I am trying to align an about me page, where i would like an image to the left of the container and the text to the right aligned centered to the page.
this is what i've got

jack

dummy text

https://jsfiddle.net/a0sozwjk/1/

article#main-col {
  float: left;
  width: 65%;
}

.dark {
  padding: 15px;
  background: #35424a;
  color: #fff;
  margin-top: 10px;
  margin-bottom: 10px;
}

.container {
  width: 80%;
  margin: auto;
  overflow: hidden;
}

article#main-col {
  float: left;
  width: 65%;
}

About us

            Jack

            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis,
            sem.

Body:
I just put the elements in a flexbox, group the text elements in the same flex child, then use align-items: center;!

Does it work for you?

article#main-col {
  float: left;
  width: 65%;
}

.dark {
  padding: 15px;
  background: #35424a;
  color: #fff;
  margin-top: 10px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.container {
  width: 80%;
  margin: auto;
  overflow: hidden;
}

article#main-col {
  float: left;
  width: 65%;
}

<center>
  <Section id="main">
    <div class="container">
      <article id="main-About-Col">
        <h1 class="PTitle">About us</h1>
        <div class="dark">
          <img style="float:left; vertical-align:center;" alt="Jack Picture" width="125px" src="https://thumb1.shutterstock.com/display_pic_with_logo/1000172/291874463/stock-vector-notebook-template-vector-example-of-using-hand-drawn-food-pattern-for-cover-of-cooking-book-291874463.jpg">
          <div>
          <h2>
            Jack
          </h2>
          <p>
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis,
            sem.
          </p>
          </div>
        </div>
      </article>
    </div>
  </Section>
</center>

Here is a cheatsheet if you don't know about flexboxes yet: https://css-tricks.com/snippets/css/a-guide-to-flexbox/


问:
ReactJs - Function in Render doesn't Show Up
**

Update: This questions has an answer that worked. It is important to
  note that even though you have a return statement in your function
  called within render(), it is still important to wrap the entire loop
  in a parent "return" in order for it to render properly on state
  change. This is a different common issue where state is not updated
  properly.

I have the following ClientList component, which shows a list of customers retrieved from database.

Below in the Render() function, i am calling the showList function which will display a list once this.props.clientList Reducer is populated.

Problem is... if I were to call the showList codes directly inside the Render() method, it will show.

IF i were to put it in a showList function, and call {this.showList} it doesn't shows up in the render.

I have the screen shot of the console as well, showing that the list is populated already.

Is this method disallowed? I see many tutorials teaching us to do this but it's not working for me. What are the restrictions to use this method to return the codes for render?

```<code>class ClientList extends Component {

    constructor(props) {
        super(props);

        this.state = {
            clientId : ''

        }
        this.getClientList = this.getClientList.bind(this);
        this.showList = this.showList.bind(this);
        console.log('initializing', this.props);
    }

    componentDidMount(){
        this.getClientList();
    }

    getClientList() {
        if (this.props.actions) {
        this.props.actions.getClientList(); //This is an ajax action to retrieve from Api
        }

    }

    showList() {

            //If i put all the codes below directly in Render, it will show.
            console.log('props from showList', this.props.clientList);

                        this.props.clientList && Object.keys(this.props.clientList).reverse().map((index,key) => {

                     return (

                     <div key={key}>
                     <div><a onClick={() => this.showProfileBox(this.props.clientList[index].customerId)}>Name: {this.props.clientList[index].firstname} {this.props.clientList[index].lastname}</a><span className="pull-right"><Link to={"/client/" + this.props.clientList[index].customerId}>Edit</Link></span></div>

                     </div>
                    );
                })
        }

    render() {
        console.log('rendering', this.props);
        return (

                <div>

                <Col xs={12} md={8}>
                <h1>Client List</h1>

                { this.showList() }  // <= This function doesn't print
                </Col>

                </div>
            )
    }

}

function mapStateToProps(state) {

    return {
        clientList: state.clientList,

    };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(clientActions, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(ClientList);
</code>```

答:
You don't need to bind showList in the constructor.

Remove it and you should be fine.

Also, as @JayabalajiJ pointed out, you need to return something out of showList otherwise you won't see the final result.

class ClientList extends React.Component {
  constructor() {
    super()

    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
     console.log('click')
  }

  showList() {
    return <button onClick={this.handleClick}>From showList</button>
  }

  render() {
    return (

        <button onClick={this.handleClick}>Click-me</button>
        {this.showList()}

    )
  }
}

ReactDOM.render(
  <ClientList />,
  document.getElementById('root')
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

Body:
**

Update: This questions has an answer that worked. It is important to
  note that even though you have a return statement in your function
  called within render(), it is still important to wrap the entire loop
  in a parent "return" in order for it to render properly on state
  change. This is a different common issue where state is not updated
  properly.

I have the following ClientList component, which shows a list of customers retrieved from database.

Below in the Render() function, i am calling the showList function which will display a list once this.props.clientList Reducer is populated.

Problem is... if I were to call the showList codes directly inside the Render() method, it will show.

IF i were to put it in a showList function, and call {this.showList} it doesn't shows up in the render.

I have the screen shot of the console as well, showing that the list is populated already.

Is this method disallowed? I see many tutorials teaching us to do this but it's not working for me. What are the restrictions to use this method to return the codes for render?

class ClientList extends Component {

    constructor(props) {
        super(props);

        this.state = {
            clientId : ''

        }
        this.getClientList = this.getClientList.bind(this);
        this.showList = this.showList.bind(this);
        console.log('initializing', this.props);
    }

    componentDidMount(){
        this.getClientList();
    }

    getClientList() {
        if (this.props.actions) {
        this.props.actions.getClientList(); //This is an ajax action to retrieve from Api
        }

    }

    showList() {

            //If i put all the codes below directly in Render, it will show.
            console.log('props from showList', this.props.clientList);

                        this.props.clientList && Object.keys(this.props.clientList).reverse().map((index,key) => {

                     return (

 this.showProfileBox(this.props.clientList[index].customerId)}>Name: {this.props.clientList[index].firstname} {this.props.clientList[index].lastname}<Link to={"/client/" + this.props.clientList[index].customerId}>Edit</Link>

                    );
                })
        }

    render() {
        console.log('rendering', this.props);
        return (

                <Col xs={12} md={8}>

Client List

                { this.showList() }  // <= This function doesn't print
                </Col>

            )
    }

}

function mapStateToProps(state) {

    return {
        clientList: state.clientList,

    };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(clientActions, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(ClientList);

Body:
You don't need to bind showList in the constructor.

Remove it and you should be fine.

Also, as @JayabalajiJ pointed out, you need to return something out of showList otherwise you won't see the final result.

class ClientList extends React.Component {
  constructor() {
    super()

    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
     console.log('click')
  }

  showList() {
    return <button onClick={this.handleClick}>From showList</button>
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Click-me</button>
        {this.showList()}
      </div>
    )
  }
}

ReactDOM.render(
  <ClientList />,
  document.getElementById('root')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>


问:
options caption and subscribe in dropdown knockout
I Have a dropdown which has some status for e.g like Delivered, Cancelled, Failure, Inprogress. I am using drop down to bind the values using knockout. Below is the sample code.

```<code><select id="ddlStatus" data-bind="options: status, optionsText: 'statusName', optionsValue:  'statusId', optionsCaption: '', value : $root.SelectedStatus"></select>
</code>```

I want the optionsCaption to be defaulted to the first option of "status" collection. Basically instead of a hardcoded caption in the dropdown i want the first option in the status to be default option. I am using subscribe for "selected status" and it called every time if i dont give the Optionscaptions.

答:
The default behavior

When knockout renders the options in your view, it tries to immediately sync the right selection:

ko.applyBindings({ options: [1, 2, 3], selection: ko.observable(2) })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: options, value: selection"></select></code>```

The cause of your problem

If you don't have a predefined selection, knockout will default to the first item in the options list (just like an ordinary static HTML <select> element would.)

Since the value binding binds two-ways, knockout will actually set selected upon calling applyBindings.

Any subscriptions to selection will be triggered:

var vm = { options: [1, 2, 3], selection: ko.observable() };
vm.selection.subscribe(console.log.bind(console, "CHANGED:"));

ko.applyBindings(vm)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: options, value: selection"></select></code>```

The solution

If you don't want this subscription to happpen, the easiest solution is to predefine the selection with the default value: the first item in options:

Any subscriptions to selection will be triggered:

var vm = { options: [1, 2, 3], selection: ko.observable() };

// Make sure there's a defined selection that is in our options:
vm.selection(vm.options[0])

vm.selection.subscribe(console.log.bind(console, "CHANGED:"));

ko.applyBindings(vm)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: options, value: selection"></select></code>```

Body:
I Have a dropdown which has some status for e.g like Delivered, Cancelled, Failure, Inprogress. I am using drop down to bind the values using knockout. Below is the sample code.

<select id="ddlStatus" data-bind="options: status, optionsText: 'statusName', optionsValue:  'statusId', optionsCaption: '', value : $root.SelectedStatus"></select>

I want the optionsCaption to be defaulted to the first option of "status" collection. Basically instead of a hardcoded caption in the dropdown i want the first option in the status to be default option. I am using subscribe for "selected status" and it called every time if i dont give the Optionscaptions.

Body:
The default behavior

When knockout renders the options in your view, it tries to immediately sync the right selection:

ko.applyBindings({ options: [1, 2, 3], selection: ko.observable(2) })

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: options, value: selection"></select>

The cause of your problem

If you don't have a predefined selection, knockout will default to the first item in the options list (just like an ordinary static HTML <select> element would.)

Since the value binding binds two-ways, knockout will actually set selected upon calling applyBindings.

Any subscriptions to selection will be triggered:

var vm = { options: [1, 2, 3], selection: ko.observable() };
vm.selection.subscribe(console.log.bind(console, "CHANGED:"));

ko.applyBindings(vm)

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: options, value: selection"></select>

The solution

If you don't want this subscription to happpen, the easiest solution is to predefine the selection with the default value: the first item in options:

Any subscriptions to selection will be triggered:

var vm = { options: [1, 2, 3], selection: ko.observable() };

// Make sure there's a defined selection that is in our options:
vm.selection(vm.options[0])

vm.selection.subscribe(console.log.bind(console, "CHANGED:"));

ko.applyBindings(vm)

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: options, value: selection"></select>


问:
How To Run Mac OS Terminal Commands From Java (Using Runtime?)
I've been looking up ways to run external programs using Java's runtime. This works fine, for instance:

```<code>String[] cmd = {"mkdir", "test"};
Runtime.getRuntime().exec(cmd);
</code>```

Creates a new directory as you would expect. Now, from a bash window in Mac I can write this:

```<code>love testgame
</code>```

To run the 'Love' game engine on a folder called testgame. Now, the reason this works is because I've aliased 'love' to call the love executable. I have a feeling that this is the reason that the following does not work:

```<code>String[] cmd = {"love", "/Users/mtc06/testgame"};
Runtime.getRuntime().exec(cmd);
</code>```

And nor does this (for those wondering):

```<code>String[] cmd = {"/bin/bash", "love", "/Users/mtc06/testgame"};
Runtime.getRuntime().exec(cmd);
</code>```

No doubt this is either some Java idiocy on my part, or some clash with the way that aliasing works. I hand it over to your venerable intellects, SO!

UPDATE: this doesn't work either:

```<code>String[] cmd = {"/bin/sh", "/Applications/love", "/Users/michaelcook/Desktop/Playout"};
Runtime.getRuntime().exec(cmd);
</code>```

The error I'm receiving is 127 from the process generated by Runtime. I'm getting that as 'command not found' wherever I research it.

答:
I suspect the problem you have is the path used to find your executables.  It depends also if you use an OSX app or a unix cmd

If a unix cmd  (or use the Unix part of an OSX app e.g. /Applications/AppName.app/Contents/MacOS/AppName) then there are two ways to fix this

Put the full path to the executable in the Java code e.g.

String[] cmd = {"/full/absolute/path/to/love", "/Users/mtc06/testgame"};

Alter the path to include the executable. This depends on the method java is launched.

a)If java is run from the command line then add the directory of the executable to the PATH environment variable.

b) For old versions of OSX and if the java program is run from the Finder the path has to be altered in ~/MacOSX/environment.plist e.g. adding /Users/mark/bin

```<code>   <?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
   <plist version="1.0">
   <dict>
      <key>PATH</key>
      <string>/Users/mark/bin:/usr/local/bin:/bin:/usr/bin:/sbin:/usr/sbin:/usr/X11R6/bin:/usr/libexec/binutils:</string>
   </dict>
   </plist>
</code>```

If the app is an OSX app the you need to launch it using open so the command line is

```<code>open -a love.app "/Users/mtc06/testgame"
</code>```

so Java command is (not tested)

```<code>String[] cmd = {"/usr/bin/open", "-a" , "love.app",  "/Users/mtc06/testgame"};
</code>```

Body:
I've been looking up ways to run external programs using Java's runtime. This works fine, for instance:

String[] cmd = {"mkdir", "test"};
Runtime.getRuntime().exec(cmd);

Creates a new directory as you would expect. Now, from a bash window in Mac I can write this:

love testgame

To run the 'Love' game engine on a folder called testgame. Now, the reason this works is because I've aliased 'love' to call the love executable. I have a feeling that this is the reason that the following does not work:

String[] cmd = {"love", "/Users/mtc06/testgame"};
Runtime.getRuntime().exec(cmd);

And nor does this (for those wondering):

String[] cmd = {"/bin/bash", "love", "/Users/mtc06/testgame"};
Runtime.getRuntime().exec(cmd);

No doubt this is either some Java idiocy on my part, or some clash with the way that aliasing works. I hand it over to your venerable intellects, SO!

UPDATE: this doesn't work either:

String[] cmd = {"/bin/sh", "/Applications/love", "/Users/michaelcook/Desktop/Playout"};
Runtime.getRuntime().exec(cmd);

The error I'm receiving is 127 from the process generated by Runtime. I'm getting that as 'command not found' wherever I research it.

Body:
I suspect the problem you have is the path used to find your executables.  It depends also if you use an OSX app or a unix cmd

If a unix cmd  (or use the Unix part of an OSX app e.g. /Applications/AppName.app/Contents/MacOS/AppName) then there are two ways to fix this

Put the full path to the executable in the Java code e.g.

String[] cmd = {"/full/absolute/path/to/love", "/Users/mtc06/testgame"};

Alter the path to include the executable. This depends on the method java is launched.

a)If java is run from the command line then add the directory of the executable to the PATH environment variable.

b) For old versions of OSX and if the java program is run from the Finder the path has to be altered in ~/MacOSX/environment.plist e.g. adding /Users/mark/bin

   <?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
   <plist version="1.0">
   <dict>
      <key>PATH</key>
      <string>/Users/mark/bin:/usr/local/bin:/bin:/usr/bin:/sbin:/usr/sbin:/usr/X11R6/bin:/usr/libexec/binutils:</string>
   </dict>
   </plist>

If the app is an OSX app the you need to launch it using open so the command line is

open -a love.app "/Users/mtc06/testgame"

so Java command is (not tested)

String[] cmd = {"/usr/bin/open", "-a" , "love.app",  "/Users/mtc06/testgame"};

ContentLicense: CC BY-SA 4.0


问:
How to call the same API for N number of times using Retrofit and RXJava.I am using the following approach as of now
Ok. So the API documentation says :

Get up to 100 restaurants by changing the 'start' and 'count' parameters with the maximum value of count being
20.
API LINK : https://developers.zomato.com/documentation#!/restaurant/search

This is the sample code :

```<code>restaurantList = new ArrayList<>();
    restaurantFinderAPI = RetrofitClient.getRetrofitClientAPI();
    restaurantScheduler = Schedulers.newThread();

    for (int i = 0; i <= 80; i += 20) {
        restaurantModelObservable = restaurantFinderAPI.getRestaraunts(city, entitytype, searchString, i, 20);

        restaurantModelObservable.subscribeOn(restaurantScheduler);
        restaurantModelObservable.observeOn(AndroidSchedulers.mainThread());
        restaurantModelObservable.subscribe(new Observer<RestaurantModel>() {
            @Override
            public void onSubscribe(Disposable d) {
                COUNT++;
                restaurantDisposable = d;
            }

            @Override
            public void onNext(RestaurantModel value) {
                restaurantList.addAll(value.getRestaurants());
            }

            @Override
            public void onError(Throwable e) {
                restaurantDisposable.dispose();
                onRestaurantSync.onRestaurantSyncFail();
            }

            @Override
            public void onComplete() {
                if (COUNT == 5) {
                    new ModifyTask().execute(restaurantList);
                    COUNT = 0;
                }
            }
        });
</code>```

This is the Retrofit interface :

```<code>    String ZOMATO_ROOT_URL = "https://developers.zomato.com/api/v2.1/";

@GET("search")
@Headers({"Accept: application/json","user-key: 258f3e496748d15cb792bc554000d6b6"})
Observable<RestaurantModel> getRestaraunts(@Query("entity_id") int entityID,
                                           @Query("entity_type") String entity_type,
                                           @Query("q")String searchFor,
                                           @Query("start") int start,
                                           @Query("count") int count);
</code>```

I making the call 5 times which is counted by the COUNT field, so it would give 100 results , by changing 'i'. Once I get 100 results, I start an asynctask for some processing on the dat. Is this a good way to call the same API multiple times. I am new to RXJava and I could not find a nice answer. Please help. Thanks

答:
Maybe smth like this:</p>

```<code>Disposable disposable = Observable.range(0, 5)
            .subscribeOn(Schedulers.io())
            .flatMap(i -> getRestaraunts(city, entitytype, searchString, i * 20, 20))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe();
</code>```

Body:
Ok. So the API documentation says :

Get up to 100 restaurants by changing the 'start' and 'count' parameters with the maximum value of count being
20.
API LINK : https://developers.zomato.com/documentation#!/restaurant/search

This is the sample code :

restaurantList = new ArrayList<>();
    restaurantFinderAPI = RetrofitClient.getRetrofitClientAPI();
    restaurantScheduler = Schedulers.newThread();

    for (int i = 0; i <= 80; i += 20) {
        restaurantModelObservable = restaurantFinderAPI.getRestaraunts(city, entitytype, searchString, i, 20);

        restaurantModelObservable.subscribeOn(restaurantScheduler);
        restaurantModelObservable.observeOn(AndroidSchedulers.mainThread());
        restaurantModelObservable.subscribe(new Observer<RestaurantModel>() {
            @Override
            public void onSubscribe(Disposable d) {
                COUNT++;
                restaurantDisposable = d;
            }

            @Override
            public void onNext(RestaurantModel value) {
                restaurantList.addAll(value.getRestaurants());
            }

            @Override
            public void onError(Throwable e) {
                restaurantDisposable.dispose();
                onRestaurantSync.onRestaurantSyncFail();
            }

            @Override
            public void onComplete() {
                if (COUNT == 5) {
                    new ModifyTask().execute(restaurantList);
                    COUNT = 0;
                }
            }
        });

This is the Retrofit interface :

    String ZOMATO_ROOT_URL = "https://developers.zomato.com/api/v2.1/";

@GET("search")
@Headers({"Accept: application/json","user-key: 258f3e496748d15cb792bc554000d6b6"})
Observable<RestaurantModel> getRestaraunts(@Query("entity_id") int entityID,
                                           @Query("entity_type") String entity_type,
                                           @Query("q")String searchFor,
                                           @Query("start") int start,
                                           @Query("count") int count);

I making the call 5 times which is counted by the COUNT field, so it would give 100 results , by changing 'i'. Once I get 100 results, I start an asynctask for some processing on the dat. Is this a good way to call the same API multiple times. I am new to RXJava and I could not find a nice answer. Please help. Thanks

Body:
Maybe smth like this:

Disposable disposable = Observable.range(0, 5)
            .subscribeOn(Schedulers.io())
            .flatMap(i -> getRestaraunts(city, entitytype, searchString, i * 20, 20))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe();


问:
convert string to array of integer in c++
Someone will help me, in understanding the while loop in following code about what it does? for example, take input from the user: 1 2 3 8 (input size not given) and one value (any index) show size of an array. it is printing the maximum value of the array. here the answer is 8.</p>

```<code>#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
    int t;
    cin >> t;
    while(t--)
    {
        string x;
        getline(cin, x);
        ll p;
        istringstream iss(x);// use of this function
        vector<ll> v;
        ll ans;
        while(iss>>p)// what this loop do
        {
           v.push_back(p);
        }
        ll size=v.size()-1;
        sort(v.begin(), v.end());
        if(size==v[size])
        {
            ans=v[size-1];
        }
        else
        {
            ans=v[size];
        }
        cout<<ans<<"\n";
    }
    return 0;
}
</code>```

答:
istringstream iss(x) creates a string stream called iss consisting of the string x. iss >> p extracts the next element from the iss stream and puts it into p. the return value is int because the variable p is of type int.

```<code>while(iss>>p)           // get an int value from string stream iss
{
     v.push_back(p);    // push the int value to the vector
}
</code>```

you have to use cin.ignore() after cin. otherwise the next getline function will take only new line character. like this:

```<code>cin >> t;
cin.ignore();
</code>```

Body:
Someone will help me, in understanding the while loop in following code about what it does? for example, take input from the user: 1 2 3 8 (input size not given) and one value (any index) show size of an array. it is printing the maximum value of the array. here the answer is 8.

#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
    int t;
    cin >> t;
    while(t--)
    {
        string x;
        getline(cin, x);
        ll p;
        istringstream iss(x);// use of this function
        vector<ll> v;
        ll ans;
        while(iss>>p)// what this loop do
        {
           v.push_back(p);
        }
        ll size=v.size()-1;
        sort(v.begin(), v.end());
        if(size==v[size])
        {
            ans=v[size-1];
        }
        else
        {
            ans=v[size];
        }
        cout<<ans<<"\n";
    }
    return 0;
}

Body:
istringstream iss(x) creates a string stream called iss consisting of the string x. iss >> p extracts the next element from the iss stream and puts it into p. the return value is int because the variable p is of type int.

while(iss>>p)           // get an int value from string stream iss
{
     v.push_back(p);    // push the int value to the vector
}

you have to use cin.ignore() after cin. otherwise the next getline function will take only new line character. like this:

cin >> t;
cin.ignore();


问:
In place insertion into list (or array)
I'm running a script in Python, where I need to insert new numbers into an array  (or list) at certain index locations. The problem is that obviously as I insert new numbers, the index locations are invalidated. Is there a clever way to insert the new values at the index locations all at once? Or is the only solution to increment the index number (first value of the pair) as I add?

Sample test code snippets:

```<code>original_list = [0, 1, 2, 3, 4, 5, 6, 7]
insertion_indices = [1, 4, 5]
new_numbers = [8, 9, 10]
pairs = [(insertion_indices[i], new_numbers[i]) for i in range(len(insertion_indices))]

for pair in pairs:
    original_list.insert(pair[0], pair[1])
</code>```

Results in:

```<code>[0, 8, 1, 2, 9, 10, 3, 4, 5, 6, 7]
</code>```

whereas I want:

```<code>[0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7]
</code>```

答:
Add this before your for loop:</p>

```<code>for i in range(len(insertion_indices)):
    insertion_indices[i]+=i
</code>```

Title: In place insertion into list (or array)

Body:
I'm running a script in Python, where I need to insert new numbers into an array  (or list) at certain index locations. The problem is that obviously as I insert new numbers, the index locations are invalidated. Is there a clever way to insert the new values at the index locations all at once? Or is the only solution to increment the index number (first value of the pair) as I add?

Sample test code snippets:

original_list = [0, 1, 2, 3, 4, 5, 6, 7]
insertion_indices = [1, 4, 5]
new_numbers = [8, 9, 10]
pairs = [(insertion_indices[i], new_numbers[i]) for i in range(len(insertion_indices))]

for pair in pairs:
    original_list.insert(pair[0], pair[1])

Results in:

[0, 8, 1, 2, 9, 10, 3, 4, 5, 6, 7]

whereas I want:

[0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7]

Body:
Add this before your for loop:

for i in range(len(insertion_indices)):
    insertion_indices[i]+=i


问:
grep for * in windows with gnuwin grep
I would like to grep for * in a text file (test.txt) like:

```<code>*text1
blablabla
*something_else
another_words
</code>```

so the result should be:

```<code>*text1
*something_else
</code>```

I tried with gnuwin grep like this:

```<code>grep '*' test.txt
</code>```

but without success. Any ideas are welcome.

答:
I found a windows native solution like:</p>

```<code>findstr /B * Rav4_V2.k > grep_star
</code>```

Title: grep for * in windows with gnuwin grep

Body:
I would like to grep for * in a text file (test.txt) like:

*text1
blablabla
*something_else
another_words

so the result should be:

*text1
*something_else

I tried with gnuwin grep like this:

grep '*' test.txt

but without success. Any ideas are welcome.

Body:
I found a windows native solution like:

findstr /B * Rav4_V2.k > grep_star


问:
How to configure delay until condition is true in Jmeter
I have a question about Jmeter delay, I created a test plan and in one step I make a call to DB using JDBC, and store the results in actual_vertica_results parameter (counts number of employees in temp table).
I want to configure Jmeter to Waite until actual_vertica_results will be 0.
(the table in DB deletes itself)
Can someone please advise how can I perform such scenario in Jmeter, today I am using constant timer for delay, and increase it manually each iteration to make sure all the data deleted.
How can I ask Jmeter making call to DB every 5 seconds and check  the results and only after all temp data deleted from the table to progress to the next step?
if someone can provide step by step scenario with PIC it will be very helpful
regards

答:
I'm thinking about two options:

I guess the clean way would be to include a Transaction Controller + Constant Timer + While Controller (as Dmitri wrote - with condition ${__javaScript("${Actual_vertica_results}" != "0",)}), so that JDBC request fires off in line with the timer delay:

The "nasty" way could be to use an anonymous code block in JDBC Request (Callable Statement as query type) and the code below (Oracle as an example):

```<code>declare
  var integer;
begin
  var := 1;
  while var <> 0
    loop
      select count(rec) into var from test_count;
      dbms_lock.sleep(5);
    end loop;
end;
</code>```

but this assumes that you do not need the Actual_vertica_results variable for other purposes and your db user has granted privileges to execute a delay/sleep (on DBMS_LOCK package in Oracle example). Possibly you could also create a function in your database with a given return value (if you tend to some validations on different tables).

Body:
I'm thinking about two options:

I guess the clean way would be to include a Transaction Controller + Constant Timer + While Controller (as Dmitri wrote - with condition ${__javaScript("${Actual_vertica_results}" != "0",)}), so that JDBC request fires off in line with the timer delay:

The "nasty" way could be to use an anonymous code block in JDBC Request (Callable Statement as query type) and the code below (Oracle as an example):

declare
  var integer;
begin
  var := 1;
  while var <> 0
    loop
      select count(rec) into var from test_count;
      dbms_lock.sleep(5);
    end loop;
end;

but this assumes that you do not need the Actual_vertica_results variable for other purposes and your db user has granted privileges to execute a delay/sleep (on DBMS_LOCK package in Oracle example). Possibly you could also create a function in your database with a given return value (if you tend to some validations on different tables).


问:
C# Parse XML to Object and store into Database
I'm currently working on an ASP.NET MVC 4.6 application using SQL Server 2014 as a data storage.

I need to parse a XML document from an URL, transform the XML into an object and store it into the database using Entity Framework 6.

I need to parse the XML from an URL like this:

http: //api.myserver.com/notes.xml

My XML looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<notes>
    <note>
      <to>Tove</to>
      <from>Jane</from>
      <heading>Reminder</heading>
      <body>Don't forget me this weekend!</body>
    </note>
    <note>
      <to>Doe</to>
      <from>John</from>
      <heading>Meeting</heading>
      <body>Hello Monday!</body>
    </note>
<notes>
</code>```

My model class note looks like this:

```<code>public class Note
{
    public string To { get; set; }
    public string From { get; set; }
    public string Heading { get; set; }
    public string Body { get; set; }
}
</code>```

My current test implementation looks like this, BUT I'm not so happy about the parsing of the XML:

```<code>namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            String url = "https://www.w3schools.com/xml/note.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(url);
            XmlElement root = doc.DocumentElement;

            StringBuilder sb = new StringBuilder();
            sb.Append("<note>");

            foreach (XmlNode item in root)
            {
                sb.Append(item.OuterXml);
            }
            sb.Append("</note>");

            var result = Deserialize<Note>(sb.ToString());

            // further processing of result using EF 6

            Console.ReadKey();
        }

        public static T Deserialize<T>(string xmlText)
        {
            try
            {
                var stringReader = new StringReader(xmlText);
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(stringReader);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }

    [XmlRoot(ElementName = "note", Namespace = "")]
    public class Note
    {
        [XmlElement("to")]
        public string To { get; set; }
        [XmlElement("from")]
        public string From { get; set; }
        [XmlElement("heading")]
        public string Heading { get; set; }
        [XmlElement("body")]
        public string Body { get; set; }
    }

}
</code>```

As far as I noticed, .NET provides several approaches on how to parse XML:

XmlReader Class

XPath

XDocument

DataSet

LINQ

I was wondering, what would you use and how would u solve the parsing of the XML document from an URL using .NET and converting into an object to store it in a SQL Server DB?

Thanks for your help and consideration!!

答:
You can use LINQ to XML to traverse the nodes of your documents and either EF or ADO.NET to store them in the DB.
You can start with this helpful tutorial: http://www.c-sharpcorner.com/UploadFile/de41d6/learning-linq-made-easy-tutorial-1/</p>

Body:
I'm currently working on an ASP.NET MVC 4.6 application using SQL Server 2014 as a data storage.

I need to parse a XML document from an URL, transform the XML into an object and store it into the database using Entity Framework 6.

I need to parse the XML from an URL like this:

http: //api.myserver.com/notes.xml

My XML looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<notes>
    <note>
      <to>Tove</to>
      <from>Jane</from>
      <heading>Reminder</heading>
      Don't forget me this weekend!
    </note>
    <note>
      <to>Doe</to>
      <from>John</from>
      <heading>Meeting</heading>
      Hello Monday!
    </note>
<notes>

My model class note looks like this:

public class Note
{
    public string To { get; set; }
    public string From { get; set; }
    public string Heading { get; set; }
    public string Body { get; set; }
}

My current test implementation looks like this, BUT I'm not so happy about the parsing of the XML:

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            String url = "https://www.w3schools.com/xml/note.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(url);
            XmlElement root = doc.DocumentElement;

            StringBuilder sb = new StringBuilder();
            sb.Append("<note>");

            foreach (XmlNode item in root)
            {
                sb.Append(item.OuterXml);
            }
            sb.Append("</note>");

            var result = Deserialize<Note>(sb.ToString());

            // further processing of result using EF 6

            Console.ReadKey();
        }

        public static T Deserialize<T>(string xmlText)
        {
            try
            {
                var stringReader = new StringReader(xmlText);
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(stringReader);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }

    [XmlRoot(ElementName = "note", Namespace = "")]
    public class Note
    {
        [XmlElement("to")]
        public string To { get; set; }
        [XmlElement("from")]
        public string From { get; set; }
        [XmlElement("heading")]
        public string Heading { get; set; }
        [XmlElement("body")]
        public string Body { get; set; }
    }

}

As far as I noticed, .NET provides several approaches on how to parse XML:

XmlReader Class

XPath

XDocument

DataSet

LINQ

I was wondering, what would you use and how would u solve the parsing of the XML document from an URL using .NET and converting into an object to store it in a SQL Server DB?

Thanks for your help and consideration!!


问:
Load profile image from Facebook with Actionscript 3
I'm trying to load profile images (friend images) from Facebook with AS3 but I seem to be running into a security issue.

I'm currently using the "official" Adobe Facebook API for Actionscript 3 which works fine. However, I seem to be having trouble loading profile images when running my application in a browser. The images load fine when running in the Flash IDE.

The images are being loaded from https://graph.facebook.com and there seems to be a crossdomain.xml policy on that domain:

```<code><!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <allow-access-from domain="*" secure="false" />
 <site-control permitted-cross-domain-policies="master-only" />
</cross-domain-policy>
</code>```

In other sources I found that adding a ContextLoader to my Loader object when loading the image should solve the problem but this doesn't seem to be the case either:

```<code>loader = new Loader();
// add some listeners here...
loader.load( new URLRequest( "imageurl" ), new LoaderContext(true) );
</code>```

I'm not quite sure how to proceed at the moment. I was hoping that the Adobe Facebook API would provide assistance in this but I can't seem to find anything that solves this issue.

Any help greatly appreciated.

UPDATE:

I just noticed that when I visit one of the images in a browser that I'm actually redirected to Facebook's CDN where the actual image is stored. When I hard-code the image url with the redirected URL I can load the image in the browser. It seems that this is not a security issue after all but a redirection issue.

If this is a redirection issue then the question would become; How can I have Flash Player load an image from a redirected URL?

UPDATE 2:

It seems that the URLRequest class has a followRedirects property which is only available in AIR.

UPDATE 3:

I'm currently using a PHP script to get me the redirected URL as a work around but this of course is far from ideal and potentially a big strain on my server.

答:
I would like to confirm martin's solution here.

My case goes from testing the application on AIR platform which is fine and works great, the image loaded successfully.

But when I port it into canvas app on facebook then I face a problem, the profile images won't come along, it cannot load.

I use what martin suggest here. And if you track a url redirection, you will see that actually image profiles are located at that CDN server not facebook itself, so you need to load that domain's policy file according to actionscript's security-sandbox.

Thanks again.

Body:
I'm trying to load profile images (friend images) from Facebook with AS3 but I seem to be running into a security issue.

I'm currently using the "official" Adobe Facebook API for Actionscript 3 which works fine. However, I seem to be having trouble loading profile images when running my application in a browser. The images load fine when running in the Flash IDE.

The images are being loaded from https://graph.facebook.com and there seems to be a crossdomain.xml policy on that domain:

<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <allow-access-from domain="*" secure="false" />
 <site-control permitted-cross-domain-policies="master-only" />
</cross-domain-policy>

In other sources I found that adding a ContextLoader to my Loader object when loading the image should solve the problem but this doesn't seem to be the case either:

loader = new Loader();
// add some listeners here...
loader.load( new URLRequest( "imageurl" ), new LoaderContext(true) );

I'm not quite sure how to proceed at the moment. I was hoping that the Adobe Facebook API would provide assistance in this but I can't seem to find anything that solves this issue.

Any help greatly appreciated.

UPDATE:

I just noticed that when I visit one of the images in a browser that I'm actually redirected to Facebook's CDN where the actual image is stored. When I hard-code the image url with the redirected URL I can load the image in the browser. It seems that this is not a security issue after all but a redirection issue.

If this is a redirection issue then the question would become; How can I have Flash Player load an image from a redirected URL?

UPDATE 2:

It seems that the URLRequest class has a followRedirects property which is only available in AIR.

UPDATE 3:

I'm currently using a PHP script to get me the redirected URL as a work around but this of course is far from ideal and potentially a big strain on my server.


问:
Javascript : onclick="class method" => possible?
I have a class who has a method generating 100 input text.

And I want to add another method (to set a instance property for example) in these input text.

Here the code below :

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

<script type="text/javascript">

container = document.getElementById("container");

//Class :
function Foo(age)
{
    //Attribute :
    this.age = age;

    //Setter :
    this.setAge = function(age)
    {
        this.age = age;

        console.log(this.age);
    };

    this.displayInputText = function()
    {
        for(var i = 0; i < 100; i++)
        {container.innerHTML += '<input type="text" onkeyup="'+this.setAge(value)+';">';}
    };
}

foo1 = new Foo(32);
foo1.displayInputText();

</script>
</code>```

But onkeyup="'+this.setAge(value)+'" generates javascript error in console, so it doesn't work.

Have you an idea ?

Thank you, cordially.

答:
this.setAge returns undefined, so your line translates to

```<code>{container.innerHTML += '<input type="text" onkeyup="undefined">';}
</code>```

If you want to use whatever value given in this input box to be set as setAge then you need to use addEventListener.

```<code>  var self = this;
  for (var i = 0; i < 10; i++)
  {
    var inputEl = document.createElement( "input" );
    inputEl.addEventListener("keyup", function(){
        self.setAge( this.value );
    });
    container.append( inputEl );
  }
</code>```

Demo

```

Body:
I have a class who has a method generating 100 input text.

And I want to add another method (to set a instance property for example) in these input text.

Here the code below :

But onkeyup="'+this.setAge(value)+'" generates javascript error in console, so it doesn't work.

Have you an idea ?

Thank you, cordially.

Body:
this.setAge returns undefined, so your line translates to

{container.innerHTML += '<input type="text" onkeyup="undefined">';}

If you want to use whatever value given in this input box to be set as setAge then you need to use addEventListener.

  var self = this;
  for (var i = 0; i < 10; i++)
  {
    var inputEl = document.createElement( "input" );
    inputEl.addEventListener("keyup", function(){
        self.setAge( this.value );
    });
    container.append( inputEl );
  }

Demo

<div id="container"></div>

<script type="text/javascript">
  container = document.getElementById("container");

  //Class :
  function Foo(age) {
    //Attribute :
    this.age = age;

    //Setter :
    this.setAge = function(age) {
      this.age = age;

      console.log(this.age);
    };

    this.displayInputText = function() {
      var self = this;
      for (var i = 0; i < 10; i++)
      {
        var inputEl = document.createElement( "input" );
        inputEl.addEventListener("keyup", function(){
            self.setAge( this.value );
        });
        container.append( inputEl );
      }
    };
  }

  foo1 = new Foo(32);
  foo1.displayInputText();
</script>


问:
Alternative for file dump
I'm trying to use fopen() in a .cpp file as

```<code>fp = fopen("/sdcard/inputdump.txt", "wb");
</code>```

to dump some data into it and later analyse the contents of the file.

The problem is fp is always NULL irrespective of the path mentioned in the fopen(). So is there any other way we can use instead of dumping it into a file?

答:
Using freopen("./path/to/file.txt", "w", stdout); you can redirect standard output to file and save your staff just using cout. As an example

```<code>cout << "write this text to file" << endl;
</code>```

Also ofstream do the same without changing the standard output.

```<code>#include <fstream>
using namespace std;
...
ofstream out("./path/to/file.txt", ofstream::out);
out << "write this text to file" << endl;
</code>```

PS: See this link fopen has not b option.

Title: Alternative for file dump

Body:
I'm trying to use fopen() in a .cpp file as

fp = fopen("/sdcard/inputdump.txt", "wb");

to dump some data into it and later analyse the contents of the file.

The problem is fp is always NULL irrespective of the path mentioned in the fopen(). So is there any other way we can use instead of dumping it into a file?

Body:
Using freopen("./path/to/file.txt", "w", stdout); you can redirect standard output to file and save your staff just using cout. As an example

cout << "write this text to file" << endl;

Also ofstream do the same without changing the standard output.

#include <fstream>
using namespace std;
...
ofstream out("./path/to/file.txt", ofstream::out);
out << "write this text to file" << endl;

PS: See this link fopen has not b option.


问:
Which one is better to iterate through each entry in HashMap?
I have two ways we can iterate through each entry in hashmap, can you explain which one is to be preferred over other and why ?

```<code>HashMap m = new HashMap();
m.put("A",100);
m.put("B",100);
m.put("C",100);
m.put("D",100);
</code>```

One way to iterate

```<code>Set s1 = m.entrySet();
Iterator itr = s1.iterate();
while(itr.hasNext()) {
Map.Entry m1 = (Map.Entry)s1.next();
System.out.println(m1.getKey()+"..."+m1.getValue);
}
</code>```

Second Way to iterate

```<code>Set<Map.Entry<String,Integer>> s1 = m.entrySet();
for(Map.Entry<String,Integer> m1:s1){
System.out.println(m1.getKey()+"..."+m1.getValue);
}
</code>```

答:
The two are essentially the same (except of the raw types in the first snippet - if you use explicit Iterator, there's no reason to use raw Set, Iterator and Map.Entry - use Set<Map.Entry<String,Integer>>, Iterator<Map.Entry<String,Integer>> and Map.Entry<String,Integer>).

The enhanced for loop creates an Iterator behind the scenes.

However, if you wish to remove elements from the Set while iterating over it, you must use an explicit Iterator (and that Iterator's remove() method).

In addition, in the first snippet you can combine the first two statements - Iterator<Map.Entry<String,Integer>> itr = m.entrySet().iterator(); - since you don't need the Set reference.

Body:
I have two ways we can iterate through each entry in hashmap, can you explain which one is to be preferred over other and why ?

HashMap m = new HashMap();
m.put("A",100);
m.put("B",100);
m.put("C",100);
m.put("D",100);

One way to iterate

Set s1 = m.entrySet();
Iterator itr = s1.iterate();
while(itr.hasNext()) {
Map.Entry m1 = (Map.Entry)s1.next();
System.out.println(m1.getKey()+"..."+m1.getValue);
}

Second Way to iterate

Set<Map.Entry<String,Integer>> s1 = m.entrySet();
for(Map.Entry<String,Integer> m1:s1){
System.out.println(m1.getKey()+"..."+m1.getValue);
}


问:
Unity3d android 2d sprites placement
Please take a look at this picture

It's a final look of the game exported from photoshop

I marked the ui sprites with red marker and the gameplay sprites with blue marker

My question is how should i correctly use these sprites in unity3d 2d game development.

This is the ways i can think of:

Use the red sprites in a canvas as Image component inside a layout group (vertical or horizontal, so i can place them in in the corner and it will work with every resolution)

Use blue sprites outside of a canvas and obviously via a Sprite Renderer component

Use blue sprites in canvas viaSprite Renderer component and set the canvas render mode to Screen Space - Camera

Use blue sprites in canvas via Image component

These ways all might be wrong but these are all i can think of right now.

I'm open to all of your suggestions.

My unity version is 2017.2.0f and i want the game to work with every resolution.

答:
I Would use Canvas for the red marker sprites, as this is UI element that need to be behave like an UI, and get adventage of RectTrasnform to modify it to fit your screen need i.e Anchoring, use Text and other stuff to fill the UI Content.

and use Sprites for blue markered sprites, and use Prespective Camera to render it, make the Tree sprites a little bit higher/backward to get nice parallax effect easily.

Why we need to place it with sprites and don't place it in canvas, because RectTransform and Transform are behave differently, use Transform if you want to apply Physic, when you use Transform instead of RectTransform you will work in World spaces, but if you use RectTransform with Canvas you will work in Screen Spaces which make it's harder and inacuratte.

Title: Unity3d android 2d sprites placement


答: Simply wrap the text in a div and add overflow: hidden; like this https://jsfiddle.net/a0sozwjk/2/

Title: Image to the left, text centered (in page)

Body:
I am trying to align an about me page, where i would like an image to the left of the container and the text to the right aligned centered to the page.
this is what i've got

jack

dummy text

https://jsfiddle.net/a0sozwjk/1/

article#main-col {
  float: left;
  width: 65%;
}

.dark {
  padding: 15px;
  background: #35424a;
  color: #fff;
  margin-top: 10px;
  margin-bottom: 10px;
}

.container {
  width: 80%;
  margin: auto;
  overflow: hidden;
}

article#main-col {
  float: left;
  width: 65%;
}

About us

            Jack

            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis,
            sem.


问:
CoreBluetooth peripheral:didDiscoverServices not firing
I have a simple app where I implemented a Central that can connect to a Peripheral and read or write to him.

For some reasons always this worked, but now I don't know why the delegate method didDiscoverServices is not firing. I am calling peripheral.discoverServices() in didConnect method. When discoverServices method is called I keep getting the error that the delegate method is not implemented or is nil. But the method is implemented and I am looking for services that exists.

This is my code

```<code>class SearchForPeripheralsTableViewController: UITableViewController, CBCentralManagerDelegate, CBPeripheralDelegate {

var centralManager: CBCentralManager?
var cbPeripheral: CBPeripheral!
var peripherals: [DiscoveryPeripherals] = []

 var listOfServices: [ServiceIdentifier] = []

 fileprivate func fillServices(){
        listOfServices.append(ServiceIdentifier(CBUUID(string: "FFF0")))
    }

 override func viewWillAppear(_ animated: Bool) {
    tableViewSearchPeripherals.dataSource = self
    tableViewSearchPeripherals.delegate = self

    initCentralManager()
}

override func viewDidAppear(_ animated: Bool) {
    tableViewSearchPeripherals.reloadData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    print("Peripheral connected")
    let service = listOfServices.first(where: { $0.uuid == CBUUID(string:"FFF0")})
     peripheral.discoverServices([(service?.uuid)!])
}

override func viewDidLoad() {
    super.viewDidLoad()
    fillServices()
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    if error != nil {
        print("Error discovering services: \(String(describing: error?.localizedDescription))")
        return
    }

    if let services = peripheral.services {
        for service in services {
            let characteristics = listOfCharacteristics.map({ (element) -> CBUUID in return element.uuid})
           //   let characteristic = GetCharacteristicByCBUUID(uuid: CBUUID(string: "FFF1"))
            peripheral.discoverCharacteristics(characteristics, for: service)
        }
    }
}
</code>```

}

答:
swift 3</p>

```<code>func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {

    peripheral.delegate = self

    self.selectPeripheral.discoverServices(nil)
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {

    if let errorService = error{

        print(errorService)

        return
    }
    else if let services = peripheral.services as [CBService]!{

        for service in services{

            peripheral.discoverCharacteristics(nil, for: service)
        }
    }
    print("==>",peripheral.services!)
}
</code>```

Body:
I have a simple app where I implemented a Central that can connect to a Peripheral and read or write to him.

For some reasons always this worked, but now I don't know why the delegate method didDiscoverServices is not firing. I am calling peripheral.discoverServices() in didConnect method. When discoverServices method is called I keep getting the error that the delegate method is not implemented or is nil. But the method is implemented and I am looking for services that exists.

This is my code

class SearchForPeripheralsTableViewController: UITableViewController, CBCentralManagerDelegate, CBPeripheralDelegate {

var centralManager: CBCentralManager?
var cbPeripheral: CBPeripheral!
var peripherals: [DiscoveryPeripherals] = []

 var listOfServices: [ServiceIdentifier] = []

 fileprivate func fillServices(){
        listOfServices.append(ServiceIdentifier(CBUUID(string: "FFF0")))
    }

 override func viewWillAppear(_ animated: Bool) {
    tableViewSearchPeripherals.dataSource = self
    tableViewSearchPeripherals.delegate = self

    initCentralManager()
}

override func viewDidAppear(_ animated: Bool) {
    tableViewSearchPeripherals.reloadData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    print("Peripheral connected")
    let service = listOfServices.first(where: { $0.uuid == CBUUID(string:"FFF0")})
     peripheral.discoverServices([(service?.uuid)!])
}

override func viewDidLoad() {
    super.viewDidLoad()
    fillServices()
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    if error != nil {
        print("Error discovering services: \(String(describing: error?.localizedDescription))")
        return
    }

    if let services = peripheral.services {
        for service in services {
            let characteristics = listOfCharacteristics.map({ (element) -> CBUUID in return element.uuid})
           //   let characteristic = GetCharacteristicByCBUUID(uuid: CBUUID(string: "FFF1"))
            peripheral.discoverCharacteristics(characteristics, for: service)
        }
    }
}

}

Body:
swift 3

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {

    peripheral.delegate = self

    self.selectPeripheral.discoverServices(nil)
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {

    if let errorService = error{

        print(errorService)

        return
    }
    else if let services = peripheral.services as [CBService]!{

        for service in services{

            peripheral.discoverCharacteristics(nil, for: service)
        }
    }
    print("==>",peripheral.services!)
}


问:
How to get the conda environment path inside a rule?
On previous versions of Snakemake (tested on 3.9.1 using integration with bioconda --use-conda) I could just check for the md5 hash of the environment.yaml file and find the respective environment at: workdir/.snakemake/conda/md5

On version 4.3.0 the md5 hash of the file does not match the environment folder. Looking at the source code I found out that the full path of the environment file is included when calculating the md5 hash to avoid conda errors on hard-coded paths but I am not sure how to generate the correct hash.

Is there another easier way to get the environment path inside a rule? If not, how can I generate the correct md5 to finde the environment?

答:
Currently, the only reasonable way is to check the log. The path is displayed when the environment is activated. However, it is a very good idea to provide a command line option to list all environments, something like snakemake --list-conda-envs. I will do that as soon as possible.

EDIT: I have implemented --list-conda-envs in the master branch. It will be in the next release.


答:
They're equivalent, so I would definitely prefer the second, because it's simpler, and a little bit faster (although it will probably be hard to notice).

I'd simplify it even further though:

```<code>for(Map.Entry<String,Integer> m1 : s1.entrySet()){
  System.out.println(m1.getKey() + "..." + m1.getValue);
}
</code>```

Title: Which one is better to iterate through each entry in HashMap?

Body:
They're equivalent, so I would definitely prefer the second, because it's simpler, and a little bit faster (although it will probably be hard to notice).

I'd simplify it even further though:

for(Map.Entry<String,Integer> m1 : s1.entrySet()){
  System.out.println(m1.getKey() + "..." + m1.getValue);
}


问:
Button position in optiontransferselect tag
I am trying to relocate the button position in optiontransferselect tag.

When I run the program, I notice the addToRightLabel="-> move to the right side" button is under addToLeftLabel="<- move to the left side" button.

So I try to make the addToLeftLabel="<- move to the left side" button below the addToRightLabel="-> move to the right side" button.

Here is the code in the jsp.

```<code><s:optiontransferselect
allowUpDownOnLeft="false"
allowUpDownOnRight="false"
allowSelectAll="false"
allowAddAllToLeft="false"
allowAddAllToRight="false"

addToRightLabel="-> move to the right side"
addToLeftLabel="<- move to the left side"

leftTitle="Option values:"
headerKey="0"
name="option"
list= "optionList"
doubleId="selectedValues"
doubleHeaderKey="0"
rightTitle="Selected Values:"
doubleList="selectedOptionList" doubleName="selectOption">
</s:optiontransferselect>
</code>```

In the code, I notice addToLeftLabel="<- move to the left side" is already under addToRightLabel="-> move to the right side" , however when I run the program, the addToRightLabel="-> move to the right side" still below the  addToLeftLabel="<- move to the left side"

I visit this two websites Struts 2 optiontransferselect example and optiontransferselect but I don't get the idea to solve the problem.

Although in worst case, I think I can swap values between list= "optionList" and doubleList="selectedOptionList", I am seeking a better solution on how to relocate the button position.

Therefore, my question is how to relocate the button position in optiontransferselect tag (put addToLeftLabel="<- move to the left side" under addToRightLabel="-> move to the right side").

Thanks.

答:
I notice I am using struts2-core jar, so I open it in Eclipse, go to template.simple and then find optiontransferselect.ftl. Once open the file, just swap the position for <#if parameters.allowAddToRight?default(true)><#t/> and <#if parameters.allowAddToLeft?default(true)><#t/>.

Although this is not a good solution, this solves the problem.

The better practice is to create a new ftl file for optiontransferselect and then write code to suit my case, this action is to prevent the new struts2-core jar update overwrite the modified code.

Body:
I am trying to relocate the button position in optiontransferselect tag.

When I run the program, I notice the addToRightLabel="-> move to the right side" button is under addToLeftLabel="<- move to the left side" button.

So I try to make the addToLeftLabel="<- move to the left side" button below the addToRightLabel="-> move to the right side" button.

Here is the code in the jsp.

<s:optiontransferselect
allowUpDownOnLeft="false"
allowUpDownOnRight="false"
allowSelectAll="false"
allowAddAllToLeft="false"
allowAddAllToRight="false"

addToRightLabel="-> move to the right side"
addToLeftLabel="<- move to the left side"

leftTitle="Option values:"
headerKey="0"
name="option"
list= "optionList"
doubleId="selectedValues"
doubleHeaderKey="0"
rightTitle="Selected Values:"
doubleList="selectedOptionList" doubleName="selectOption">
</s:optiontransferselect>

In the code, I notice addToLeftLabel="<- move to the left side" is already under addToRightLabel="-> move to the right side" , however when I run the program, the addToRightLabel="-> move to the right side" still below the  addToLeftLabel="<- move to the left side"

I visit this two websites Struts 2 optiontransferselect example and optiontransferselect but I don't get the idea to solve the problem.

Although in worst case, I think I can swap values between list= "optionList" and doubleList="selectedOptionList", I am seeking a better solution on how to relocate the button position.

Therefore, my question is how to relocate the button position in optiontransferselect tag (put addToLeftLabel="<- move to the left side" under addToRightLabel="-> move to the right side").

Thanks.


问:
To get the value in row from webgrid and pass it to the controller
I am getting value in Column , following is the code.

```<code>grid.Column(columnName: "Name", header: "Name",format: @<text>
      <span id="Name">@item.Name</span></text>, canSort: false),
</code>```

want to use this value in function which I have called on delete button

```<code>function DeleteEnterpriseID() {
        var checkID = $(".edit-mode:checked").map(function () {
            return this.value;
        }).toArray();
        alert(checkID.join(","));

        if (confirm("Are you sure you want to delete?") == true) {
            var url = "@Url.Action("DeleteEnterpriseIdDetails")";
            var pname = $('#Name').val();  //// Here I want that value from the clicked row so that I can pass that to controller.
            alert(pname);
            $.ajaxSetup({ cache: false });
            $.post(url, { Pname: pname, EnterpriseID: checkID.join(",") })
            .success(function (response) {
                if (response != null && response.success) {
                    alert(response.responseText);
                    window.location.href = response.newurl;

                } else {
                    alert(response.responseText);
                }
            })
            .error(function (response) { alert("error"); });
        }
        else {
            return false;
        }
    }
</code>```

But I am getting blank value for Name from clicked row.
Kindly assist.

答:
It should be:

```<code>var pname = $('#Name').text();
</code>```

Because its a span tag and not an input element. val() works for input elements.

Body:
I am getting value in Column , following is the code.

grid.Column(columnName: "Name", header: "Name",format: @<text>
      @item.Name</text>, canSort: false),

want to use this value in function which I have called on delete button

function DeleteEnterpriseID() {
        var checkID = $(".edit-mode:checked").map(function () {
            return this.value;
        }).toArray();
        alert(checkID.join(","));

        if (confirm("Are you sure you want to delete?") == true) {
            var url = "@Url.Action("DeleteEnterpriseIdDetails")";
            var pname = $('#Name').val();  //// Here I want that value from the clicked row so that I can pass that to controller.
            alert(pname);
            $.ajaxSetup({ cache: false });
            $.post(url, { Pname: pname, EnterpriseID: checkID.join(",") })
            .success(function (response) {
                if (response != null && response.success) {
                    alert(response.responseText);
                    window.location.href = response.newurl;

                } else {
                    alert(response.responseText);
                }
            })
            .error(function (response) { alert("error"); });
        }
        else {
            return false;
        }
    }

But I am getting blank value for Name from clicked row.
Kindly assist.

Body:
It should be:

var pname = $('#Name').text();

Because its a span tag and not an input element. val() works for input elements.