问:
NullPointerException at mocked class method
I am currently writing a test for the method buy of the class Buy which should actually test if the correct request is going to the server and if it's handling the response correctly.

At the moment I always receive a java.lang.NullPointerException because execute(post) returns null instead of the CloseableHttpResponse.

CloseableHttpResponse response = httpClient.execute(post);

But I don't understand because in my test I tell mockito to return the mocked closeableHttpResponse.

The test

```<code>  @Test
    public void testBid() throws IOException {
        //given:
        HttpPost post = mock(HttpPost.class);
        HttpResponse httpResponse = mock(HttpResponse.class);

        StatusLine statusLine = mock(StatusLine.class);

        ObserverImp observer = mock(ObserverImp.class);

        CloseableHttpClient closeableHttpClient = mock(CloseableHttpClient.class);
        CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
        HttpEntity httpEntity = mock(HttpEntity.class);
        BufferedInputStream inputStream = mock(BufferedInputStream.class);

        //and:
        when(statusLine.getStatusCode()).thenReturn(200);
        when(httpResponse.getStatusLine()).thenReturn(statusLine);
        when(closeableHttpClient.execute(post)).thenReturn(closeableHttpResponse);
        when(closeableHttpResponse.getEntity()).thenReturn(httpEntity);
        when(httpEntity.getContent()).thenReturn(inputStream);
        when(inputStream.read()).thenReturn(1);
        when(observer.getKey()).thenReturn("##213");

        Buy buy = new Buy(observer, closeableHttpClient);
        buy.bid(14455);
    }
</code>```

And the related Implementation

```<code>public class Buy {
    private ObserverImp observer;
    private CloseableHttpClient httpClient;

    public Buy (ObserverImp observer, CloseableHttpClient httpClient) {
       this.observer = observer;
       this.httpClient = httpClient;
    }

    public void buy(double price) {
            String queryArgs = "command=order&amount=1" + "&price=" + String.valueOf(price); // generates query

            HttpPost post = new HttpPost("wwww.hm.edu/projectGroup1");
            post.addHeader("Key", observer.getKey());
            try {
                post.setEntity(new ByteArrayEntity(queryArgs.getBytes("UTF-8")));
            } catch (UnsupportedEncodingException e) {
                System.out.println("Exception in run");
            }
            List<NameValuePair> params = new ArrayList<>();

            params.add(new BasicNameValuePair("command", "order"));
            params.add(new BasicNameValuePair("amount", "1"));
            params.add(new BasicNameValuePair("price", String.valueOf(price)));
            try {
                post.setEntity(new UrlEncodedFormEntity(params));
                CloseableHttpResponse response = httpClient.execute(post);
                HttpEntity entity = response.getEntity();
                Scanner in = new Scanner(entity.getContent());
                String orderNumber = "";
                while (in.hasNext()) {
                    orderNumber = in.nextLine();
                }
                String[] findOrderNumber = orderNumber.split(".");
                long lastOrderNumber = -1;
                try {
                    lastOrderNumber = Long.valueOf(findOrderNumber[3]);
                } catch (NumberFormatException exception) {
                    System.out.println("NumberFormatException");
                } finally {
                    if (lastOrderNumber != -1) {
                        observer.setOrderNumber(lastOrderNumber);
                    }
                }
                in.close();
                EntityUtils.consume(entity);
                httpClient.close();
            } catch (IOException e) {
                System.out.println("Exception occured during process");
            }
        }
}
</code>```

Please help me to fix that issue. Thank you a lot.

答:
You need that:

when(closeableHttpClient.execute(any(HttpPost.class))).thenReturn(closeableHttpResponse);

Your code before just waits for the exact post (equals) that you created in your test. But your buy method produces another post. Thats why your execute(post) cannot match the class. any() solves that

Body:
I am currently writing a test for the method buy of the class Buy which should actually test if the correct request is going to the server and if it's handling the response correctly.

At the moment I always receive a java.lang.NullPointerException because execute(post) returns null instead of the CloseableHttpResponse.

CloseableHttpResponse response = httpClient.execute(post);

But I don't understand because in my test I tell mockito to return the mocked closeableHttpResponse.

The test

  @Test
    public void testBid() throws IOException {
        //given:
        HttpPost post = mock(HttpPost.class);
        HttpResponse httpResponse = mock(HttpResponse.class);

        StatusLine statusLine = mock(StatusLine.class);

        ObserverImp observer = mock(ObserverImp.class);

        CloseableHttpClient closeableHttpClient = mock(CloseableHttpClient.class);
        CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
        HttpEntity httpEntity = mock(HttpEntity.class);
        BufferedInputStream inputStream = mock(BufferedInputStream.class);

        //and:
        when(statusLine.getStatusCode()).thenReturn(200);
        when(httpResponse.getStatusLine()).thenReturn(statusLine);
        when(closeableHttpClient.execute(post)).thenReturn(closeableHttpResponse);
        when(closeableHttpResponse.getEntity()).thenReturn(httpEntity);
        when(httpEntity.getContent()).thenReturn(inputStream);
        when(inputStream.read()).thenReturn(1);
        when(observer.getKey()).thenReturn("##213");

        Buy buy = new Buy(observer, closeableHttpClient);
        buy.bid(14455);
    }

And the related Implementation

public class Buy {
    private ObserverImp observer;
    private CloseableHttpClient httpClient;

    public Buy (ObserverImp observer, CloseableHttpClient httpClient) {
       this.observer = observer;
       this.httpClient = httpClient;
    }

    public void buy(double price) {
            String queryArgs = "command=order&amount=1" + "&price=" + String.valueOf(price); // generates query

            HttpPost post = new HttpPost("wwww.hm.edu/projectGroup1");
            post.addHeader("Key", observer.getKey());
            try {
                post.setEntity(new ByteArrayEntity(queryArgs.getBytes("UTF-8")));
            } catch (UnsupportedEncodingException e) {
                System.out.println("Exception in run");
            }
            List<NameValuePair> params = new ArrayList<>();

            params.add(new BasicNameValuePair("command", "order"));
            params.add(new BasicNameValuePair("amount", "1"));
            params.add(new BasicNameValuePair("price", String.valueOf(price)));
            try {
                post.setEntity(new UrlEncodedFormEntity(params));
                CloseableHttpResponse response = httpClient.execute(post);
                HttpEntity entity = response.getEntity();
                Scanner in = new Scanner(entity.getContent());
                String orderNumber = "";
                while (in.hasNext()) {
                    orderNumber = in.nextLine();
                }
                String[] findOrderNumber = orderNumber.split(".");
                long lastOrderNumber = -1;
                try {
                    lastOrderNumber = Long.valueOf(findOrderNumber[3]);
                } catch (NumberFormatException exception) {
                    System.out.println("NumberFormatException");
                } finally {
                    if (lastOrderNumber != -1) {
                        observer.setOrderNumber(lastOrderNumber);
                    }
                }
                in.close();
                EntityUtils.consume(entity);
                httpClient.close();
            } catch (IOException e) {
                System.out.println("Exception occured during process");
            }
        }
}

Please help me to fix that issue. Thank you a lot.


来源: stackexchange

问:
JMS Alternative
I was reading a blog, and one of the points was 'if you're using queues, you messed up', in the context of JMS.

I was thinking, do we even need JMS?  A simple alternative would be, if you need to do something asynchronously, why not just put a job request in a table somewhere, and have some process(es) polling the db every X time units looking for new jobs?

This approach is simpler than JMS, its easy to understand, and basically removes a dependency from an application.

What am I losing if I use the alternative I described? Perhaps one loses the possibility of using JMX to be able to administer things, but if your job 'queue' is fed off a table, you can write some simple code to 'manage' the processing.

答:
This approach is simpler than JMS, its easy to understand, and basically removes a dependency from an application.

Well, that's only true if you come from a Database background. I would think there is nothing easier than sending a message for every state change and 'forget about it'.

One advantage of message oriented middleware (e.g. JMS) is the higher performance - you can have rates of 1M msgs/sec - but the bigger benefit is usually a cleaner architecture: a message bus where multiple components plug into. Right now you have your one-to-one communication, but in 2 years you might want to log that traffic, in 3 years you might want to monitor errors and in 4 years you might want to automatically record and replay and test it...

ContentLicense: CC BY-SA 2.5

Title: JMS Alternative

ContentLicense: CC BY-SA 3.0


问:
PHP MVC: Default values for the constructor parameters
Before I begin:

My question was put on hold as primarily opinion-based. But I've done my best to reedit it in a more precise way again. In the hope, that its content will support its reopening.

So here is my question again:

It's about my HMVC project, a PHP framework, in which the M, V & C components are encapsulated in "independent" blocks (module directories). The project should not contain any static class members, static methods, singletons or service locators. I am using a dependency injection container, therefore beeing able to provide inversion of control (IoC).

In a class AbstractTemplate I assign the needed root paths of the template files as default values to the parameters of the class constructor:

```<code>abstract class AbstractTemplate {

    public function __construct(
        , $appLayoutsPath = '[app-root-path]/Layouts/Default'
        , $moduleLayoutsPath = '[module-root-path]/Templates/Layouts'
        , $moduleTemplatesPath = '[module-root-path]/Templates/Templates'
    ) {
        //...
    }

}
</code>```

But in this way I couple the class to a hard-coded representation of the file system.

Therefore I considered passing the default values by using a separate class, which in turn holds the required values as class constants:

```<code>class Constants {

    const APP_LAYOUTS_PATH = '[app-root-path]/Layouts/Default';
    const MODULE_LAYOUTS_PATH = '[module-root-path]/Templates/Layouts';
    const MODULE_TEMPLATES_PATH = '[module-root-path]/Templates/Templates';

}

abstract class AbstractTemplate {

    public function __construct(
        , $appLayoutsPath = Constants::APP_LAYOUTS_PATH
        , $moduleLayoutsPath = Constants::MODULE_LAYOUTS_PATH
        , $moduleTemplatesPath = Constants::MODULE_TEMPLATES_PATH
    ) {
        //...
    }

}
</code>```

This way I couple the abstract class to the concrete implementation Constants.

I'd like to ask you:

Can the second option be tested without problems?

Is there another concrete possibility to provide default values and in the mean time to preserve a good testability?

I appreciate your answers and thank you for your time.

答:
Option 2 is much cleaner and easier maintainable code example I would go with 2, code-hinting applications like phpStorm or DW will understand option 2 better.

I'd strongly recommend not to avoid entire functionality such as static class members purely for design or stylistic considerations, it's there for a reason.

Body:
Before I begin:

My question was put on hold as primarily opinion-based. But I've done my best to reedit it in a more precise way again. In the hope, that its content will support its reopening.

So here is my question again:

It's about my HMVC project, a PHP framework, in which the M, V & C components are encapsulated in "independent" blocks (module directories). The project should not contain any static class members, static methods, singletons or service locators. I am using a dependency injection container, therefore beeing able to provide inversion of control (IoC).

In a class AbstractTemplate I assign the needed root paths of the template files as default values to the parameters of the class constructor:

abstract class AbstractTemplate {

    public function __construct(
        , $appLayoutsPath = '[app-root-path]/Layouts/Default'
        , $moduleLayoutsPath = '[module-root-path]/Templates/Layouts'
        , $moduleTemplatesPath = '[module-root-path]/Templates/Templates'
    ) {
        //...
    }

}

But in this way I couple the class to a hard-coded representation of the file system.

Therefore I considered passing the default values by using a separate class, which in turn holds the required values as class constants:

class Constants {

    const APP_LAYOUTS_PATH = '[app-root-path]/Layouts/Default';
    const MODULE_LAYOUTS_PATH = '[module-root-path]/Templates/Layouts';
    const MODULE_TEMPLATES_PATH = '[module-root-path]/Templates/Templates';

}

abstract class AbstractTemplate {

    public function __construct(
        , $appLayoutsPath = Constants::APP_LAYOUTS_PATH
        , $moduleLayoutsPath = Constants::MODULE_LAYOUTS_PATH
        , $moduleTemplatesPath = Constants::MODULE_TEMPLATES_PATH
    ) {
        //...
    }

}

This way I couple the abstract class to the concrete implementation Constants.

I'd like to ask you:

Can the second option be tested without problems?

Is there another concrete possibility to provide default values and in the mean time to preserve a good testability?

I appreciate your answers and thank you for your time.


问:
Can't save nested attribute in Rails
Rails newb here. In my app I'm trying to create a database of Games that each have multiple MameControls as nested attributes. The fields for entering MameControls show up in the New view but not in Edit, the results aren't rendered in Show, and if i validate_presence_of :mameControls it won't save the form, stating "Mame controls can't be blank." And in the rails console, Game.first(or last, or any other record).mame_controls returns only []. So as far as I can tell the nested attribute is not being saved, even though i'm pretty sure i've set everything up similarly to what is shown in Railscast #196. Here is the Game class:

```<code>class Game < ActiveRecord::Base
  has_many :mame_controls, :dependent => :destroy

  attr_accessible :name, :year, :company, :designer, :genre,
  :sb_info, :wiki_link, :arcade_history_link, :arcade_museum_link,
  :caesar_link, :wildcard_link, :mame_controls

  accepts_nested_attributes_for :mame_controls, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true

  validates_presence_of :name, :year, :company, :genre, :sb_info, :mame_controls

end
</code>```

mame_control.rb:

```<code>class MameControl < ActiveRecord::Base
  belongs_to :game

  attr_accessible :name, :game_action
end
</code>```

The form code to enter in or edit MameControls is this.

in _form.html.erb:

```<code>  <% f.fields_for :mame_controls do |builder| %>
    <%= render "control_fields", :f => builder %>
<% end %>
</code>```

_control_fields.html.erb:

```<code><div class="field">
 <p>
     <%= f.label :name, "Mame Control Name" %><br />
  <%= f.text_field :name %><br />
  <%= f.label :game_action, "Game Action" %><br />
  <%= f.text_field :game_action %>
 </p>
</div>
</code>```

in games_controller.rb:

```<code> def new
    @game = Game.new
    5.times do
       mame_control = @game.mame_controls.build
     end
  end

def create
    @game = Game.new(params[:game])
end
</code>```

答: Alright, turns out the problem was a couple things wrong with my use of reject_if in accepts_nested_attributes_for. First of all I was checking for the wrong variable name (embarrassing,) and I misunderstood what the method was actually doing, or rather not doing - if a previously filled entry is rejected for being blank (as in that lambda), it won't delete or null the corresponding index value in the array. It just won't do anything to it. You have to explicitly set the nested attribute record to _destroy to destroy. I had read up on accepts_nested_attributes_for from a theoretical standpoint but I should've understood its options better.

Title: Can't save nested attribute in Rails

Body:
Rails newb here. In my app I'm trying to create a database of Games that each have multiple MameControls as nested attributes. The fields for entering MameControls show up in the New view but not in Edit, the results aren't rendered in Show, and if i validate_presence_of :mameControls it won't save the form, stating "Mame controls can't be blank." And in the rails console, Game.first(or last, or any other record).mame_controls returns only []. So as far as I can tell the nested attribute is not being saved, even though i'm pretty sure i've set everything up similarly to what is shown in Railscast #196. Here is the Game class:

class Game < ActiveRecord::Base
  has_many :mame_controls, :dependent => :destroy

  attr_accessible :name, :year, :company, :designer, :genre,
  :sb_info, :wiki_link, :arcade_history_link, :arcade_museum_link,
  :caesar_link, :wildcard_link, :mame_controls

  accepts_nested_attributes_for :mame_controls, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true

  validates_presence_of :name, :year, :company, :genre, :sb_info, :mame_controls

end

mame_control.rb:

class MameControl < ActiveRecord::Base
  belongs_to :game

  attr_accessible :name, :game_action
end

The form code to enter in or edit MameControls is this.

in _form.html.erb:

  <% f.fields_for :mame_controls do |builder| %>
    <%= render "control_fields", :f => builder %>
<% end %>

_control_fields.html.erb:

     <%= f.label :name, "Mame Control Name" %>

  <%= f.text_field :name %>

  <%= f.label :game_action, "Game Action" %>

  <%= f.text_field :game_action %>

in games_controller.rb:

 def new
    @game = Game.new
    5.times do
       mame_control = @game.mame_controls.build
     end
  end

def create
    @game = Game.new(params[:game])
end


问:
angular - create a new line on HTML
I have a simple question (I hope this). I have a service that return a string as result. The format is something like this:

"
Test1: the association has been accepted.\nTest2: the association has been accepted.\n"
"

On the client side (I'm using Angular 1.5.x) I put that string into a object (say the variable $scope.alert.message). After that I want to print that string in a modal. My html is:

```<code><script type="text/ng-template" id="infoTemplate.html">
    <div class="modal-header left" ng-class="['div-' + alert.type, closeable ? 'alert-dismissible' : null]">
        <h3 class="modal-title" id="modal-title">Info</h3>
    </div>
    <div class="modal-body" id="modal-body">
        <img class="imm-info" ng-class="['imm-' + alert.type, closeable ? 'alert-dismissible' : null]" />
        <p class="col-sm-10 col-sm-offset-2">{{alert.message}}</p><button class="col-sm-3 col-sm-offset-5 btn " ng-class="['button-' + alert.type, closeable ? 'alert-dismissible' : null]" ng-click="cancel()">OK</button>
    </div>
</script>
</code>```

You can see the '{{alert.message}}'. My problem is that my message "doesn't display" the character '\n'. So it doesn't create more than one line. An example here:

example

答:
\n is not interpreted in html. You need to replace these instances with
 elements. You could for example replace them with a regex if you do not want to change the original string.

Title: angular - create a new line on HTML

Body:
I have a simple question (I hope this). I have a service that return a string as result. The format is something like this:

"
Test1: the association has been accepted.\nTest2: the association has been accepted.\n"
"

On the client side (I'm using Angular 1.5.x) I put that string into a object (say the variable $scope.alert.message). After that I want to print that string in a modal. My html is:

You can see the '{{alert.message}}'. My problem is that my message "doesn't display" the character '\n'. So it doesn't create more than one line. An example here:

example

Body: \n is not interpreted in html. You need to replace these instances with <br/> elements. You could for example replace them with a regex if you do not want to change the original string.


问:
SQL - Combine multiple text records to one
I want to combine multiple text records to one.
I have a table with data like this:

```<code>+----+---------+
| id | comment |
+----+---------+
| 1  | Peter   |
| 2  | is      |
| 3  | stupid  |
+----+---------+
</code>```

I want Peter is stupid as output.

Do you have any idea?

I am sorry for my bad SQl knowledge.

答:
Start with this </p>

```<code>SELECT  GROUP_CONCAT(comment SEPARATOR ' ')
FROM table_name
</code>```

Body:
I want to combine multiple text records to one.
I have a table with data like this:

+----+---------+
| id | comment |
+----+---------+
| 1  | Peter   |
| 2  | is      |
| 3  | stupid  |
+----+---------+

I want Peter is stupid as output.

Do you have any idea?

I am sorry for my bad SQl knowledge.

Body:
Start with this

SELECT  GROUP_CONCAT(comment SEPARATOR ' ')
FROM table_name


问:
Communication between microservices for large data
I am building a spring cloud-based microservice ML pipeline.
I have a data ingestion service that (currently) takes in data from SQL, this data needs to be used by the prediction service.

The general consensus is that writes should use async message-based communication using kafka/rabbitmq.

What I am not sure about is how do I orchestrate these services?

Should I use an API gateway that invokes ingestion that starts the pipeline?

答:
Typically you would build a service with rest endpoints (Spring Boot) to ingest the data. This service can then be deployed multiple times behind a api gateway (Zuul, Spring Cloud) that takes care about routing. This is the default spring cloud microservices setup. The ingest service can then convert the data and produce it to a RabbitMQ or Kafka. I recommend using Spring Cloud Stream for the interaction with the queue, it's abstraction on top of RabbitMQ and Kafka, which can be configured using starters/binders.

Spring Cloud Dataflow is a declarative approach for orchestration of your queues and also takes care of deployment on several cloud services/platforms. This can also be used but might add extra complexity to your use case.


问:
How to find the css version?
How do I find the version of CSS that I am using?</p>

答:
The version is only defined by the CSS selectors, propreties and attributes that you use.

You are free to mix elements of CSS 1, 2 and 3 in any styles that you write.

You can refer to the CSS specifications to see more details.  The specifications and drafts at the W3C is available via this index: http://www.w3schools.com/w3c/w3c_css.asp

ContentLicense: CC BY-SA 4.0

Title: How to find the css version?


问:
What is alternative of Thread.Join() to overcome UI freezing issue
I have two thread which start running When user select play button.
But when use select Pause or Resume button my UI hangs because of Thread.Join().

Below is code, I am looking for some alternative to overcome this.
I already tried with Invoke but it's not working even with this approach my UI freeze the moment I call Thread methods.

```<code>ThreadStart m_executeThreadStart;
        Thread m_executeThread;
        //user Selected Start Button
        private void Start()
        {
            m_executeThreadStart = new ThreadStart(method1);
            m_executeThread = new Thread(m_executeThreadStart);
            m_executeThread.Name = "ExecuteTestSession";
            m_executeThread.IsBackground = true;
            m_executeThread.Start();

            // Start the asynchronous operation.
            // InitializeBackgroundWorker();
            // backgroundWorker1.RunWorkerAsync();

            //Creating result sync thread
            ThreadStart m_resultSyncThreadStart = new ThreadStart(method2);
            Thread m_resultSyncThread = new Thread(m_resultSyncThreadStart);
            m_resultSyncThread.Name = "SyncResultDatabase";
            m_resultSyncThread.Start();
        }
        private void method1()
        {
            //do some work
            //read data from OPC sever (device)
        }
        private void method2()
        {
            //do some work
            //updated database accordingly method 1 data
        }

        //user Press Pause button
        public void Suspend()
        {
            //do work
            m_executeThread.Join();
            //do work
        }

        //user Press Resume button
        public void Resume()
        {
            //do work
            m_executeThread.Join();
            //do work
        }
</code>```

答:
You can add an event handler to your background worker, then you don't need Thread.Join(). Your event handler can then perform the necessary actions when the long running process has completed:

```<code>backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
     // code to run after long running process has completed
}
</code>```

The async / await pattern was designed to stop the UI from freezing (when implemented correctly) you could use this as an alternative approach - https://learn.microsoft.com/en-us/dotnet/csharp/async

Also see: https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/keep-the-ui-thread-responsive

Body:
I have two thread which start running When user select play button.
But when use select Pause or Resume button my UI hangs because of Thread.Join().

Below is code, I am looking for some alternative to overcome this.
I already tried with Invoke but it's not working even with this approach my UI freeze the moment I call Thread methods.

ThreadStart m_executeThreadStart;
        Thread m_executeThread;
        //user Selected Start Button
        private void Start()
        {
            m_executeThreadStart = new ThreadStart(method1);
            m_executeThread = new Thread(m_executeThreadStart);
            m_executeThread.Name = "ExecuteTestSession";
            m_executeThread.IsBackground = true;
            m_executeThread.Start();

            // Start the asynchronous operation.
            // InitializeBackgroundWorker();
            // backgroundWorker1.RunWorkerAsync();

            //Creating result sync thread
            ThreadStart m_resultSyncThreadStart = new ThreadStart(method2);
            Thread m_resultSyncThread = new Thread(m_resultSyncThreadStart);
            m_resultSyncThread.Name = "SyncResultDatabase";
            m_resultSyncThread.Start();
        }
        private void method1()
        {
            //do some work
            //read data from OPC sever (device)
        }
        private void method2()
        {
            //do some work
            //updated database accordingly method 1 data
        }

        //user Press Pause button
        public void Suspend()
        {
            //do work
            m_executeThread.Join();
            //do work
        }

        //user Press Resume button
        public void Resume()
        {
            //do work
            m_executeThread.Join();
            //do work
        }

Body:
You can add an event handler to your background worker, then you don't need Thread.Join(). Your event handler can then perform the necessary actions when the long running process has completed:

backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
     // code to run after long running process has completed
}

The async / await pattern was designed to stop the UI from freezing (when implemented correctly) you could use this as an alternative approach - https://learn.microsoft.com/en-us/dotnet/csharp/async

Also see: https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/keep-the-ui-thread-responsive


问:
Python way of doing this for loop
I have the following piece of code:

```<code>for item in packages:
    if item["name"] == dependency_to_install:
        dependencies = item["requires"]
        for dependency in dependencies:
            get_dependency(packages, dependency, requirements)
        requirements.append(item["name"])
</code>```

Is there a python way of doing all this in one line of code?

Thank you in advance!

EDDITED:

Or this is good enough and I don't need to look for better one, because this is self explanatory?

答:
It is (probably a list comprehension), but don't do it!

I'll attach a quote which is probably relevant:

Beautiful is better than ugly.

  Explicit is better than implicit.

  Simple is better than complex.

  Readability counts

What you can do, however, is to at most remove dependencies = item["requires"] if you're not using anywhere else:

```<code>for item in packages:
    if item["name"] == dependency_to_install:
        for dependency in item["requires"]:
            get_dependency(packages, dependency, requirements)
        requirements.append(item["name"])
</code>```

As @Stefan Pochmann suggested, your naming can also be improved. You might want to rename item to package.

Title: Python way of doing this for loop

Body:
I have the following piece of code:

for item in packages:
    if item["name"] == dependency_to_install:
        dependencies = item["requires"]
        for dependency in dependencies:
            get_dependency(packages, dependency, requirements)
        requirements.append(item["name"])

Is there a python way of doing all this in one line of code?

Thank you in advance!

EDDITED:

Or this is good enough and I don't need to look for better one, because this is self explanatory?

Body:
It is (probably a list comprehension), but don't do it!

I'll attach a quote which is probably relevant:

Beautiful is better than ugly.

  Explicit is better than implicit.

  Simple is better than complex.

  Readability counts

What you can do, however, is to at most remove dependencies = item["requires"] if you're not using anywhere else:

for item in packages:
    if item["name"] == dependency_to_install:
        for dependency in item["requires"]:
            get_dependency(packages, dependency, requirements)
        requirements.append(item["name"])

As @Stefan Pochmann suggested, your naming can also be improved. You might want to rename item to package.


答:
You can write a function where you take the alert-message and split it by "\n"
than iterate trough it via *ngFor.

For example:

```<code><p *ngFor="let msg of getMessageSplitted(alert.message)">{{msg}}</p>
</code>```

Title: angular - create a new line on HTML

Body:
You can write a function where you take the alert-message and split it by "\n"
than iterate trough it via *ngFor.

For example:

<p *ngFor="let msg of getMessageSplitted(alert.message)">{{msg}}</p>


问:
Prev and next buttons to change divs
I'm trying to create a code in jQuery that adds the class active to the next div and removes it from the previous div and vice versa with the previous. This all in mind with animations I want to add later.

If you want to see the code with HTML and CSS:
http://codepen.io/salman15/pen/kXVmRG?editors=1010

```<code>$(document).ready(function() {
    $('#next').click(function() {
        var location = $(this).parent().parent();
        $('.active').removeClass('active');
        $('div').next('#case').addClass('active');
    });

    $('#prev').click(function() {
        var location = $(this).parent().parent();
        $('.active').removeClass('active');
        $(this).prev('#case').removeClass('active');
    });
});
</code>```

答:
```<code>$('.ggg').click(function(){
   $('.ggg,.sss').removeClass("active");
  $(this).addClass("active");
  $(this).next();
  });

 var x22 = $( "#MainMenu" ).find( ".ggg" ).length;
 //alert(x22);

 var i = 118;
    var hrefa2;
      $(".previous").click(function () {

      hrefa = $( "#MainMenu").find(".ggg").eq(i).attr("alt");
       //hrefa3 = $("#MainMenu").find(".ggg").eq(0);
     i--;
    //alert(hrefa);
     $('.ggg').removeClass("active");
    $( "#MainMenu" ).find( ".ggg" ).eq(i).addClass("active");
 });

  var i = 0;
    var hrefa;
      $(".next").click(function () {

      hrefa = $( "#MainMenu").find(".ggg").eq(i).attr("alt");
      //hrefa1 = $("#MainMenu").find(".ggg").eq(0);
     i++;
    //alert(hrefa);
     $('.ggg').removeClass("active");
    $( "#MainMenu" ).find( ".ggg" ).eq(i).addClass("active");
 });
</code>```

Title: Prev and next buttons to change divs

Body:
I'm trying to create a code in jQuery that adds the class active to the next div and removes it from the previous div and vice versa with the previous. This all in mind with animations I want to add later.

If you want to see the code with HTML and CSS:
http://codepen.io/salman15/pen/kXVmRG?editors=1010

$(document).ready(function() {
    $('#next').click(function() {
        var location = $(this).parent().parent();
        $('.active').removeClass('active');
        $('div').next('#case').addClass('active');
    });

    $('#prev').click(function() {
        var location = $(this).parent().parent();
        $('.active').removeClass('active');
        $(this).prev('#case').removeClass('active');
    });
});


问:
How to programmatically fire a dblclick event defined with addEventListener?
For JS Unit test, I need to check that a double-click behaves as expected. The issue is that the event was registered via element.addEventListener. And for some reason, in this case, element.ondblclick() does not work.
HTML:

```<code><input type="image" src="pic.jpg" id="aa"/>
</code>```

Javasript:

```
document.getElementById('aa').addEventListener("dblclick", function(){alert('aa')});
document.getElementById('aa').ondblclick();
```

Fiddle: http://jsfiddle.net/prZKy/

If you double click on the image, it works, but the ondblclick() in the javascript does not work.

Anyone has an idea on how to do it?

答:
This should work:</p>

```<code>var doubleClickEvent = document.createEvent('MouseEvents');
doubleClickEvent.initEvent('dblclick', true, true);
e.currentTarget.dispatchEvent(doubleClickEvent); // inside method
</code>```

Body:
For JS Unit test, I need to check that a double-click behaves as expected. The issue is that the event was registered via element.addEventListener. And for some reason, in this case, element.ondblclick() does not work.
HTML:

<input type="image" src="pic.jpg" id="aa"/>

Javasript:

document.getElementById('aa').addEventListener("dblclick", function(){alert('aa')});
document.getElementById('aa').ondblclick();

Fiddle: http://jsfiddle.net/prZKy/

If you double click on the image, it works, but the ondblclick() in the javascript does not work.

Anyone has an idea on how to do it?

Body:
This should work:

var doubleClickEvent = document.createEvent('MouseEvents');
doubleClickEvent.initEvent('dblclick', true, true);
e.currentTarget.dispatchEvent(doubleClickEvent); // inside method


问:
Image uploading doesn't work
So guys.. I want to upload an image to a certain folder name "uploads" and insert the name of that image on database, the problem is that he isn't uploading the image..

So i have this basic HTML code:

<form action="newimage.php" method="POST">

        <input type="file" name="pic" id="pic">

      <button type="submit" class="btn btn-success">Submit</button>

</form>```
</div>
</div>
</p>

<p>And this is my <strong>PHP</strong> page</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
  $mysqli = new mysqli("localhost", "root", "", "homepage");

  if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
  }

  $name = "somethinghere";

  #do upload
  $target_dir = "uploads";
  $temp = explode(".", $_FILES["pic"]["name"]);
  $newfilename = $target_dir . '/Foto-' . $name . '.' . end($temp);

  if (move_uploaded_file($_FILES['pic']['tmp_name'], $newfilename) ) {
    $productimage = 'Foto-' . $name . '.' . end($temp);
  }
  else
  {
    $productimage = '';
  }

  $sql = "INSERT INTO galeria_front (image_name) VALUES ('$productimage')";

  if ($mysqli->query($sql) === TRUE) {
      header("Location: galery.php");
  } else {
      echo "Error: " . $sql . "<br>" . $mysqli->error;
  }

  $mysqli->close();
?></code>```

As you can see i have a conection which works, and tried to insert the productimage into the database table but for some reason , it's entering the else{} and making my productimage empty on the database which means the above upload isn't working.

P.S(Pardon me for any bad english)

答:
try adding these

```<code>     <form action="newimage.php" method="POST" enctype="multipart/form-data">
    </form
</code>```

Alter your script into this

```<code>    <?php
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
    }
     // Check file size
     if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
     }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !=
     "jpeg"
    && $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
     }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
     if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
   {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been
    uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
    }
    ?>
</code>```

https://www.w3schools.com/php/php_file_upload.asp

Title: Image uploading doesn't work

Body:
So guys.. I want to upload an image to a certain folder name "uploads" and insert the name of that image on database, the problem is that he isn't uploading the image..

So i have this basic HTML code:

<form action="newimage.php" method="POST">

        <input type="file" name="pic" id="pic">

      <button type="submit" class="btn btn-success">Submit</button>

</form>

And this is my PHP page

<?php
  $mysqli = new mysqli("localhost", "root", "", "homepage");

  if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
  }

  $name = "somethinghere";

  #do upload
  $target_dir = "uploads";
  $temp = explode(".", $_FILES["pic"]["name"]);
  $newfilename = $target_dir . '/Foto-' . $name . '.' . end($temp);

  if (move_uploaded_file($_FILES['pic']['tmp_name'], $newfilename) ) {
    $productimage = 'Foto-' . $name . '.' . end($temp);
  }
  else
  {
    $productimage = '';
  }

  $sql = "INSERT INTO galeria_front (image_name) VALUES ('$productimage')";

  if ($mysqli->query($sql) === TRUE) {
      header("Location: galery.php");
  } else {
      echo "Error: " . $sql . "
" . $mysqli->error;
  }

  $mysqli->close();
?>

As you can see i have a conection which works, and tried to insert the productimage into the database table but for some reason , it's entering the else{} and making my productimage empty on the database which means the above upload isn't working.

P.S(Pardon me for any bad english)

Body:
try adding these

     <form action="newimage.php" method="POST" enctype="multipart/form-data">
    </form

Alter your script into this

    <?php
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
    }
     // Check file size
     if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
     }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !=
     "jpeg"
    && $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
     }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
     if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
   {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been
    uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
    }
    ?>

https://www.w3schools.com/php/php_file_upload.asp


问:
Why does Firefox ignores bottom margin of flex-item?
It respects margin-bottom only when there is enough room for it. Otherwise Firefox behaves as if there is no margin-bottom at all.

Chrome Full:

Chrome Shrinked:

Firefox Shrinked:

Is it correct behaviour of flexbox? How to fix it?

codepen

.container {
  position: fixed;
  display: flex;
  flex-direction: column;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;
}

.grow {
  flex-grow: 1;
  flex-shrink: 0;
  background: #8f8;
}

.content {
  width: 500px;
  margin: 20px auto;
  border: 1px solid currentColor;
  background: #f88;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="container">
    <div class="grow"></div>
    <div class="content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatibus, facilis omnis inventore, illum eos quis fuga quos id, labore consectetur quas. Unde sed nemo nobis recusandae saepe ex nulla accusantium?</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias asperiores a enim magnam voluptatem. Ab sint possimus quis odit vero explicabo unde quod rem, quasi voluptatibus cupiditate voluptatem veritatis repudiandae.</p>
    </div>
    <div class="grow"></div>
  </div>
</body></code>```

答:
I'm stick to flex-direction: row with just one flex item having margin: auto. Inside of it I put my container. That way it works in Chrome, Firefox, IE, and Safari without issues:

codepen

.container {
  position: fixed;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  /* when using *column* Safari 9.0 and below will ignore bottom margins */
  flex-direction: row;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;
  background: #f88;
}
.content-wrapper {
  margin: auto;
}
.content {
  width: 500px;
  margin: 20px;
  border: 1px solid currentColor;
  background: #8f8;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="container">
    <div class="content-wrapper">
      <div class="content">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatibus, facilis omnis inventore, illum eos quis fuga quos id, labore consectetur quas. Unde sed nemo nobis recusandae saepe ex nulla accusantium?</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias asperiores a enim magnam voluptatem. Ab sint possimus quis odit vero explicabo unde quod rem, quasi voluptatibus cupiditate voluptatem veritatis repudiandae.</p>
      </div>
    </div>
  </div>
</body></code>```

Body:
It respects margin-bottom only when there is enough room for it. Otherwise Firefox behaves as if there is no margin-bottom at all.

Chrome Full:

Chrome Shrinked:

Firefox Shrinked:

Is it correct behaviour of flexbox? How to fix it?

codepen

.container {
  position: fixed;
  display: flex;
  flex-direction: column;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;
}

.grow {
  flex-grow: 1;
  flex-shrink: 0;
  background: #8f8;
}

.content {
  width: 500px;
  margin: 20px auto;
  border: 1px solid currentColor;
  background: #f88;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatibus, facilis omnis inventore, illum eos quis fuga quos id, labore consectetur quas. Unde sed nemo nobis recusandae saepe ex nulla accusantium?

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias asperiores a enim magnam voluptatem. Ab sint possimus quis odit vero explicabo unde quod rem, quasi voluptatibus cupiditate voluptatem veritatis repudiandae.

Body:
I'm stick to flex-direction: row with just one flex item having margin: auto. Inside of it I put my container. That way it works in Chrome, Firefox, IE, and Safari without issues:

codepen

.container {
  position: fixed;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  /* when using *column* Safari 9.0 and below will ignore bottom margins */
  flex-direction: row;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;
  background: #f88;
}
.content-wrapper {
  margin: auto;
}
.content {
  width: 500px;
  margin: 20px;
  border: 1px solid currentColor;
  background: #8f8;
}

<body>
  <div class="container">
    <div class="content-wrapper">
      <div class="content">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatibus, facilis omnis inventore, illum eos quis fuga quos id, labore consectetur quas. Unde sed nemo nobis recusandae saepe ex nulla accusantium?</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias asperiores a enim magnam voluptatem. Ab sint possimus quis odit vero explicabo unde quod rem, quasi voluptatibus cupiditate voluptatem veritatis repudiandae.</p>
      </div>
    </div>
  </div>
</body>


问:
How to temporarily hide elements while designing in Gluon Scene Builder?
I have complex design that has several layers on top of each other. Problem is that if I click on object, other object that on top of it gets selected. How I can switch off visibility of my top objects while working on my bottom layer, so that they won't get in the way?</p>

答: I finally found how to achieve what I wanted. Just select element that in the way and in properties remove tick from visible. Now you can design without anything obstructing your view! Just don't forget to make visible all elements before you save your work.


问:
WARNING: UNPROTECTED PRIVATE KEY FILE! when trying to SSH into Amazon EC2 Instance
I'm working to set up Panda on an Amazon EC2 instance.
I set up my account and tools last night and had no problem using SSH to interact with my own personal instance, but right now I'm not being allowed permission into Panda's EC2 instance.
Getting Started with Panda

I'm getting the following error:

```<code>@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @

Permissions 0644 for '~/.ec2/id_rsa-gsg-keypair' are too open.
It is recommended that your private key files are NOT accessible by others.
This private key will be ignored.
</code>```

I've chmoded my keypair to 600 in order to get into my personal instance last night, and experimented at length setting the permissions to 0 and even generating new key strings, but nothing seems to be working.

Any help at all would be a great help!

Hm, it seems as though unless permissions are set to 777 on the directory, the ec2-run-instances script is unable to find my keyfiles.

答:
Keep your private key, public key, known_hosts in same directory and try login as below:

```<code>ssh -I(small i) "hi.pem" ec2-user@ec2-**-***-**-***.us-west-2.compute.amazonaws.com
</code>```

Same directory in the sense,
cd /Users/prince/Desktop.
Now type ls command
and you should  see
**.pem **.ppk known_hosts

Note: You have to try to login from the same directory or you'll get a permission denied error as it can't find the .pem file from your present directory.

If you want to be able to SSH from any directory, you can add the following to you ~/.ssh/config file...

```<code>Host your.server
HostName ec2-user@ec2-**-***-**-***.us-west-2.compute.amazonaws.com
User ec2-user
IdentityFile ~/.ec2/id_rsa-gsg-keypair
IdentitiesOnly yes
</code>```

Now you can SSH to your server regardless of where the directory is by simply typing ssh your.server (or whatever name you place after "Host").

OwnerDisplayName: Bryan Woods

Body:
I'm working to set up Panda on an Amazon EC2 instance.
I set up my account and tools last night and had no problem using SSH to interact with my own personal instance, but right now I'm not being allowed permission into Panda's EC2 instance.
Getting Started with Panda

I'm getting the following error:

@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @

Permissions 0644 for '~/.ec2/id_rsa-gsg-keypair' are too open.
It is recommended that your private key files are NOT accessible by others.
This private key will be ignored.

I've chmoded my keypair to 600 in order to get into my personal instance last night, and experimented at length setting the permissions to 0 and even generating new key strings, but nothing seems to be working.

Any help at all would be a great help!

Hm, it seems as though unless permissions are set to 777 on the directory, the ec2-run-instances script is unable to find my keyfiles.

LastEditorDisplayName: Stu Thompson

Body:
Keep your private key, public key, known_hosts in same directory and try login as below:

ssh -I(small i) "hi.pem" ec2-user@ec2-**-***-**-***.us-west-2.compute.amazonaws.com

Same directory in the sense,
cd /Users/prince/Desktop.
Now type ls command
and you should  see
**.pem **.ppk known_hosts

Note: You have to try to login from the same directory or you'll get a permission denied error as it can't find the .pem file from your present directory.

If you want to be able to SSH from any directory, you can add the following to you ~/.ssh/config file...

Host your.server
HostName ec2-user@ec2-**-***-**-***.us-west-2.compute.amazonaws.com
User ec2-user
IdentityFile ~/.ec2/id_rsa-gsg-keypair
IdentitiesOnly yes

Now you can SSH to your server regardless of where the directory is by simply typing ssh your.server (or whatever name you place after "Host").


问:
Assign a list<T> to a variable in javascript using thymeleaf
I'm trying to get a list of objects in a variable in javascript, added to model in the controller. As a test, I passed a list of Strings and it worked fine but it doesn't work with the list of objects. Can anybody help me please? I've been searching for a solution but I can't find anything.

This is the controller

```<code>@GetMapping(value= "/view_dates")
public String viewDates(Model model){
    List<Division> list =divisionService.getActiveDates();
    model.addAttribute("dates", list);
    return  "course_view_dates";
}
</code>```

and this is the javascript code

```<code>   <script th:inline = "javascript">
        /*<![CDATA[*/
            var examDates = /*[[${dates}]]*/ null;
            for (i=0; i< examDates.length; i++){
                alert(examDates[i].name);
            }
        /*]]>*/
    </script>
</code>```

This is the entity for more information

```<code>@Entity
@Table(name="division")
public class Division implements Serializable{
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id", unique = true, nullable = false)
  private Integer id;
  @OneToMany(mappedBy = "division")
  private List<Kind> kinds;
  @JsonIgnore
  @OneToMany(mappedBy = "division", cascade = CascadeType.ALL)
  private List<Sample> samples;
  @ManyToMany(mappedBy = "divisions", cascade = CascadeType.ALL)
  private List<Candidate> candidates;
  @Column(name = "name", nullable = false)
  private String name;
  @Column(name = "description", nullable = true)
  private String description;
  @Column(name = "course_days", nullable = true)
  private Integer courseDays;
  @Temporal(TemporalType.DATE)
  @DateTimeFormat(pattern= "dd/MM/yyy")
  @Column(name = "exam_date", nullable = true)
  private Date examDate;
  @Column(name = "active", nullable = true)
  private Boolean active;

  public Division() {
    this.name = "";
    this.description = "";
    this.courseDays = 0;
    this.examDate = null;
    this.active = false;
  }

public Division(String name, String description, Integer courseDays, Date examDate, Boolean dateActive){
    this.name = name;
    this.description = description;
    this.courseDays = courseDays;
    this.examDate = examDate;
    this.active = dateActive;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public Integer getCourseDays() {
    return courseDays;
}

public void setCourseDays(Integer courseDays) {
    this.courseDays = courseDays;
}

public List<Sample> getSamples() {
    return this.samples;
}

public void setSamples(List<Sample> samples) {
    this.samples = samples;
}

public Date getExamDate() {
    return examDate;
}

public void setExamDate(Date ExamDate) {
    this.examDate = ExamDate;
}

public Boolean getActive() {
    return active;
}

public void setActive(Boolean active) {
    this.active = active;
}

public List<Kind> getKinds() {
    return this.kinds;
}

public void setKinds(List<Kind> varieties) {
    this.kinds = varieties;
}

public List<Candidate> getCandidates() {
    return this.candidates;
}

public void setCandidates(List<Candidate> candidates) {
    this.candidates = candidates;
}
</code>```

It produces two calls to the database and then the ERROR

```<code>Hibernate: select candidates0_.division_id as division2_1_0_,             candidates0_.candidate_id as candidat1_1_0_, candidate1_.id as id1_0_1_, candidate1_.name as name2_0_1_ from ostscourses.candidate_division candidates0_ inner join ostscourses.candidate candidate1_ on candidates0_.candidate_id=candidate1_.id where candidates0_.division_id=?
Hibernate: select divisions0_.candidate_id as candidat1_1_0_, divisions0_.division_id as division2_1_0_, division1_.id as id1_2_1_, division1_.active as active2_2_1_, division1_.course_days as course_d3_2_1_, division1_.description as descript4_2_1_, division1_.exam_date as exam_dat5_2_1_, division1_.name as name6_2_1_ from ostscourses.candidate_division divisions0_ inner join ostscourses.division division1_ on divisions0_.division_id=division1_.id where divisions0_.candidate_id=? order by division1_.name asc
2017-06-07 10:55:19.994 ERROR 5576 --- [pr-8080-exec-17] o.s.boot.web.support.ErrorPageFilter     : Forwarding to error page from request [/course/view_dates/] due to exception [null]

java.lang.StackOverflowError: null
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:562) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:135) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:277) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.thymeleaf.util.JavaScriptUtils.printCollection(JavaScriptUtils.java:316) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
</code>```

答:
I advise you to convert to JSON list variable and to manage an array of json object in javascript handler.

For example using GSON library:

```<code>//class fields...
private Gson GSON = new GsonBuilder().create();

@GetMapping(value= "/view_dates")
public String viewDates(Model model){
    List<Division> list =divisionService.getActiveDates();
    model.addAttribute("dates", GSON.toJson(list));
    return  "course_view_dates";
}
</code>```

Your javscript handler should work without any change.

EDIT: maybe you Need to parse dates JSON.parse(dates)

Body:
I'm trying to get a list of objects in a variable in javascript, added to model in the controller. As a test, I passed a list of Strings and it worked fine but it doesn't work with the list of objects. Can anybody help me please? I've been searching for a solution but I can't find anything.

This is the controller

@GetMapping(value= "/view_dates")
public String viewDates(Model model){
    List<Division> list =divisionService.getActiveDates();
    model.addAttribute("dates", list);
    return  "course_view_dates";
}

and this is the javascript code

This is the entity for more information

@Entity
@Table(name="division")
public class Division implements Serializable{
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id", unique = true, nullable = false)
  private Integer id;
  @OneToMany(mappedBy = "division")
  private List<Kind> kinds;
  @JsonIgnore
  @OneToMany(mappedBy = "division", cascade = CascadeType.ALL)
  private List<Sample> samples;
  @ManyToMany(mappedBy = "divisions", cascade = CascadeType.ALL)
  private List<Candidate> candidates;
  @Column(name = "name", nullable = false)
  private String name;
  @Column(name = "description", nullable = true)
  private String description;
  @Column(name = "course_days", nullable = true)
  private Integer courseDays;
  @Temporal(TemporalType.DATE)
  @DateTimeFormat(pattern= "dd/MM/yyy")
  @Column(name = "exam_date", nullable = true)
  private Date examDate;
  @Column(name = "active", nullable = true)
  private Boolean active;

  public Division() {
    this.name = "";
    this.description = "";
    this.courseDays = 0;
    this.examDate = null;
    this.active = false;
  }

public Division(String name, String description, Integer courseDays, Date examDate, Boolean dateActive){
    this.name = name;
    this.description = description;
    this.courseDays = courseDays;
    this.examDate = examDate;
    this.active = dateActive;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public Integer getCourseDays() {
    return courseDays;
}

public void setCourseDays(Integer courseDays) {
    this.courseDays = courseDays;
}

public List<Sample> getSamples() {
    return this.samples;
}

public void setSamples(List<Sample> samples) {
    this.samples = samples;
}

public Date getExamDate() {
    return examDate;
}

public void setExamDate(Date ExamDate) {
    this.examDate = ExamDate;
}

public Boolean getActive() {
    return active;
}

public void setActive(Boolean active) {
    this.active = active;
}

public List<Kind> getKinds() {
    return this.kinds;
}

public void setKinds(List<Kind> varieties) {
    this.kinds = varieties;
}

public List<Candidate> getCandidates() {
    return this.candidates;
}

public void setCandidates(List<Candidate> candidates) {
    this.candidates = candidates;
}

It produces two calls to the database and then the ERROR

Hibernate: select candidates0_.division_id as division2_1_0_,             candidates0_.candidate_id as candidat1_1_0_, candidate1_.id as id1_0_1_, candidate1_.name as name2_0_1_ from ostscourses.candidate_division candidates0_ inner join ostscourses.candidate candidate1_ on candidates0_.candidate_id=candidate1_.id where candidates0_.division_id=?
Hibernate: select divisions0_.candidate_id as candidat1_1_0_, divisions0_.division_id as division2_1_0_, division1_.id as id1_2_1_, division1_.active as active2_2_1_, division1_.course_days as course_d3_2_1_, division1_.description as descript4_2_1_, division1_.exam_date as exam_dat5_2_1_, division1_.name as name6_2_1_ from ostscourses.candidate_division divisions0_ inner join ostscourses.division division1_ on divisions0_.division_id=division1_.id where divisions0_.candidate_id=? order by division1_.name asc
2017-06-07 10:55:19.994 ERROR 5576 --- [pr-8080-exec-17] o.s.boot.web.support.ErrorPageFilter     : Forwarding to error page from request [/course/view_dates/] due to exception [null]

java.lang.StackOverflowError: null
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:562) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:135) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:277) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.thymeleaf.util.JavaScriptUtils.printCollection(JavaScriptUtils.java:316) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]

Body:
I advise you to convert to JSON list variable and to manage an array of json object in javascript handler.

For example using GSON library:

//class fields...
private Gson GSON = new GsonBuilder().create();

@GetMapping(value= "/view_dates")
public String viewDates(Model model){
    List<Division> list =divisionService.getActiveDates();
    model.addAttribute("dates", GSON.toJson(list));
    return  "course_view_dates";
}

Your javscript handler should work without any change.

EDIT: maybe you Need to parse dates JSON.parse(dates)


问:
How to set the value in hashmap key:value pair conditionally?
I'am using grails.
I want to set the values in map conditionally.
For Eg:

```<code>HashMap<String, String> mymap= new HashMap<String, String>();
    if (author != null){
        mymap['TITLE'] = book.title
    }else{
        mymap['TITLE'] = 'NA'
    }
</code>```

So, what I want to acheive is, I want to set the value of my title as "book.title" if the particular value is not null otherwise it should be a normal string "NA".

Output I'am Getting

```<code>mymap:[TITLE: NA]
</code>```

Output I want

```<code>mymap:[TITLE: [TITLE1, TITLE2, NA, TITLE4, TITLE5]]
</code>```

Something like this

Thanks in advance.

答:
You are using groovy all of this can be done more elegantly:

You must be getting iteration of book from somewhere ?

Change this from:

```<code>HashMap<String, String> mymap= new HashMap<String, String>();
    if (author != null){
        mymap['TITLE'] = book.title
    }else{
        mymap['TITLE'] = 'NA'
    }
</code>```

to:

```<code>List titles=[]
books?.title?.each { title->
    titles<< (title?:'NA')
}
def mymap=['TITLE':titles]
</code>```

Body:
I'am using grails.
I want to set the values in map conditionally.
For Eg:

HashMap<String, String> mymap= new HashMap<String, String>();
    if (author != null){
        mymap['TITLE'] = book.title
    }else{
        mymap['TITLE'] = 'NA'
    }

So, what I want to acheive is, I want to set the value of my title as "book.title" if the particular value is not null otherwise it should be a normal string "NA".

Output I'am Getting

mymap:[TITLE: NA]

Output I want

mymap:[TITLE: [TITLE1, TITLE2, NA, TITLE4, TITLE5]]

Something like this

Thanks in advance.

Body:
You are using groovy all of this can be done more elegantly:

You must be getting iteration of book from somewhere ?

Change this from:

HashMap<String, String> mymap= new HashMap<String, String>();
    if (author != null){
        mymap['TITLE'] = book.title
    }else{
        mymap['TITLE'] = 'NA'
    }

to:

List titles=[]
books?.title?.each { title->
    titles<< (title?:'NA')
}
def mymap=['TITLE':titles]


问:
PHP: Change only a portion of a URL string?
I’m working on a small hoppy project where I want to replace a specific page on a URL. Let me explain:

I’ve got the URL

http://www.example.com/article/paragraph/low/

I want to keep the URL but replace the last segment /low/ with /high/ so the new URL is:

http://www.example.com/article/paragraph/high/

I’ve tried different explode, split and splice but I just can’t seem to wrap my head around it and make it work. I can change the entire URL but not just the last segment and save it in a new variable.

I’m pretty confidence that it is a pretty straight forward case but I’ve never worked that much with arrays / string-manipulation in PHP so I’m pretty lost.

I guess that I have to first split the URL up in segments, using the "\" to separate it (I tried that but have problems by using explode("\", $string)) and then replace the last \low\ with \high\

Hope someone could help or point me in the right direction to what methods to use for doing this.

Sincere

Mestika

答:
You took \ for /.</p>

```<code>$url = explode('/', rtrim($url, '/'));
if (end($url) == 'low') {
    $url[count($url)-1] = 'high';
}
$url = implode('/', $url) .'/';
</code>```

Body:
You took \ for /.

$url = explode('/', rtrim($url, '/'));
if (end($url) == 'low') {
    $url[count($url)-1] = 'high';
}
$url = implode('/', $url) .'/';


问:
Complex comprehensions with os.walk - the limit of expressive power?
I wanted to make os.walk based list comprehension (latter to be turned into a generator expression) with full control, but couldn't find a way. Have I hit the limit of Python's expressive power or is my vocabulary of tricks just lacking ? :-)

Here's what I've got and even for that I had to hack a bit (short circuit logical expression and forced True) because I could find a way to inject anything with assignment operator. No matter how much I tried to bury it, parser would find me :-) Also couldn't inject print anywhere (as a debugging aid).

```<code>[( s, re.sub(r"^.*?FStar\.(.*)\.fs(.*)", dest_dir + r"Fstar.\1.fst\2", s) )
     for s in ( x[0].replace('\\', '/') + "/" + f
        for x in os.walk(".")
            if (skip_dir in x[1] and x[1].remove(skip_dir) or True)
            for f in x[2] if fnmatch(f ,patt))
]
</code>```

What I wanted was full control of dirs along the lines of:

```<code>x[1][:]=[d for d in x[1] if d not in skip_list]
</code>```

And that got me thinking about the limits of Python's expressiveness.

Any ideas for this particular case appreciated, but also if someone knows/has an example of a construct offering even more potential control than os.walk only to be faced with limits of comprehension nesting/combining.

Also I started wishing for pipes or other form of generator combinators while writing this.

The ultimate limits of expressiveness in a comprehension structure (and in general in syntactic constructs) is the bigger question here.

For those asking for clarification - the first question is how to do achieve control of os.walk in a comprehension, to be able to remove multiple items (coming from skip_list) and not just one, the second is what are the limits of Pythons expressive power - what else, could be done within a nested comprehension structure. Assignments for example.

答:
All of Python users should be familiar with Zen.

In this case I can see violation of next rules

Readability counts.

given example is too hard to reason about.

Simple is better than complex.

Sparse is better than dense.

there are too many statements in one comprehension.

Flat is better than nested.

and we've got nested comprehensions here.

Overview

side effects inside of comprehensions is not a good idea

```<code>x[1].remove(skip_dir)
</code>```

see discussion here

instead of string concatenation

```<code>x[0].replace('\\', '/') + "/" + f
</code>```

we use os.path.join

```<code>os.path.join(x[0].replace('\\', '/'), f)
</code>```

about statement

```<code>for x in os.walk(".")
</code>```

os.walk yields tuples with names of root directory, subdirectories and files, so it will be better to unpack tuple instead of accessing coordinates by index

```<code>for root, directories_names, files_names in os.walk('.')
</code>```

if we are using the same regular expression many times then it deserves to be compiled before using, so

```<code>... re.sub(r"^.*?FStar\.(.*)\.fs(.*)", dest_dir + r"Fstar.\1.fst\2", s) ...
</code>```

can be separated into

```<code>TARGET_FILES_NAMES_RE = re.compile(r"^.*?FStar\.(.*)\.fs(.*)")

... TARGET_FILES_NAMES_RE.sub(dest_dir + r"Fstar.\1.fst\2", s) ...
</code>```

also it is unlear what should dest_dir + r"Fstar.\1.fst\2" do: i believe that it should join dest_dir to simplified file name.

Main idea

When comprehension becomes complex (or especially complicated) it is a good idea to rewrite it into generator function.

For given example it may be like

```<code>TARGET_FILES_NAMES_RE = re.compile(r"^.*?FStar\.(.*)\.fs(.*)")

def modify_paths(top, dest_dir, skip_dir, pattern):
    replacement = os.path.join(dest_dir, r"Fstar.\1.fst\2")
    for root, directories_names, files_names in os.walk(top):
        try:
            # we are removing `skip_dir` from all subdirectories,
            # is it a desired behavior?
            directories_names.remove(skip_dir)
        except ValueError:
            # not in list
            pass

        for file_name in files_names:
            if not fnmatch(file_name, pattern):
                continue
            s = os.path.join(root.replace('\\', '/'), file_name)
            yield (s,
                   TARGET_FILES_NAMES_RE.sub(replacement, s))
</code>```

but it is still raw and should be refactored.

Test

I've created directory

```<code>/
    doc.txt
    FStar.anotherfs
    FStar.other.fS
    FStar.some.fs90
    FStar.text..fs
    test.py

    skip_me/
            FStar.file.fs
            FStar.sample.fs
            FStar.skipped.fs
</code>```

where test.py contents:

```<code>import os
import re
from fnmatch import fnmatch

TARGET_FILES_NAMES_RE = re.compile(r"^.*?FStar\.(.*)\.fs(.*)")

def modify_paths(top, dest_dir, skip_dir, pattern):
    replacement = os.path.join(dest_dir, r"Fstar.\1.fst\2")
    for root, directories_names, files_names in os.walk(top):
        try:
            # we are removing `skip_dir` from all subdirectories,
            # is it a desired behavior?
            directories_names.remove(skip_dir)
        except ValueError:
            # not in list
            pass

        for file_name in files_names:
            if not fnmatch(file_name, pattern):
                continue
            s = os.path.join(root.replace('\\', '/'), file_name)
            yield (s,
                   TARGET_FILES_NAMES_RE.sub(replacement, s))

if __name__ == '__main__':
    top = '.'
    skip_dir = 'skip_me'
    patt = '*'
    # slash is required for version with list comprehension
    dest_dir = 'dest_dir/'
    before = [
        (s,
         re.sub(r"^.*?FStar\.(.*)\.fs(.*)", dest_dir + r"Fstar.\1.fst\2", s))
        for s in (os.path.join(x[0].replace('\\', '/'), f)
                  for x in os.walk(top)
                  if (skip_dir in x[1] and
                      x[1].remove(skip_dir) or True)
                  for f in x[2] if fnmatch(f, patt))]
    after = list(
        modify_paths(top=top, dest_dir=dest_dir, skip_dir=skip_dir,
                     pattern=patt))
    assert after == before
</code>```

and assertion is successful.

P. S.

Skipping exceptions is not a good idea but if you know what to expect it can become a powerful tool.

Also it can be re-written using contextlib.suppress context manager from

```<code>x[0].replace('\\', '/') + "/" + f
</code>```0

to

```<code>x[0].replace('\\', '/') + "/" + f
</code>```1

Body:
I wanted to make os.walk based list comprehension (latter to be turned into a generator expression) with full control, but couldn't find a way. Have I hit the limit of Python's expressive power or is my vocabulary of tricks just lacking ? :-)

Here's what I've got and even for that I had to hack a bit (short circuit logical expression and forced True) because I could find a way to inject anything with assignment operator. No matter how much I tried to bury it, parser would find me :-) Also couldn't inject print anywhere (as a debugging aid).

[( s, re.sub(r"^.*?FStar\.(.*)\.fs(.*)", dest_dir + r"Fstar.\1.fst\2", s) )
     for s in ( x[0].replace('\\', '/') + "/" + f
        for x in os.walk(".")
            if (skip_dir in x[1] and x[1].remove(skip_dir) or True)
            for f in x[2] if fnmatch(f ,patt))
]

What I wanted was full control of dirs along the lines of:

x[1][:]=[d for d in x[1] if d not in skip_list]

And that got me thinking about the limits of Python's expressiveness.

Any ideas for this particular case appreciated, but also if someone knows/has an example of a construct offering even more potential control than os.walk only to be faced with limits of comprehension nesting/combining.

Also I started wishing for pipes or other form of generator combinators while writing this.

The ultimate limits of expressiveness in a comprehension structure (and in general in syntactic constructs) is the bigger question here.

For those asking for clarification - the first question is how to do achieve control of os.walk in a comprehension, to be able to remove multiple items (coming from skip_list) and not just one, the second is what are the limits of Pythons expressive power - what else, could be done within a nested comprehension structure. Assignments for example.

Body:
All of Python users should be familiar with Zen.

In this case I can see violation of next rules

Readability counts.

given example is too hard to reason about.

Simple is better than complex.

Sparse is better than dense.

there are too many statements in one comprehension.

Flat is better than nested.

and we've got nested comprehensions here.

Overview

side effects inside of comprehensions is not a good idea

x[1].remove(skip_dir)

see discussion here

instead of string concatenation

x[0].replace('\\', '/') + "/" + f

we use os.path.join

os.path.join(x[0].replace('\\', '/'), f)

about statement

for x in os.walk(".")

os.walk yields tuples with names of root directory, subdirectories and files, so it will be better to unpack tuple instead of accessing coordinates by index

for root, directories_names, files_names in os.walk('.')

if we are using the same regular expression many times then it deserves to be compiled before using, so

... re.sub(r"^.*?FStar\.(.*)\.fs(.*)", dest_dir + r"Fstar.\1.fst\2", s) ...

can be separated into

TARGET_FILES_NAMES_RE = re.compile(r"^.*?FStar\.(.*)\.fs(.*)")

... TARGET_FILES_NAMES_RE.sub(dest_dir + r"Fstar.\1.fst\2", s) ...

also it is unlear what should dest_dir + r"Fstar.\1.fst\2" do: i believe that it should join dest_dir to simplified file name.

Main idea

When comprehension becomes complex (or especially complicated) it is a good idea to rewrite it into generator function.

For given example it may be like

TARGET_FILES_NAMES_RE = re.compile(r"^.*?FStar\.(.*)\.fs(.*)")

def modify_paths(top, dest_dir, skip_dir, pattern):
    replacement = os.path.join(dest_dir, r"Fstar.\1.fst\2")
    for root, directories_names, files_names in os.walk(top):
        try:
            # we are removing `skip_dir` from all subdirectories,
            # is it a desired behavior?
            directories_names.remove(skip_dir)
        except ValueError:
            # not in list
            pass

        for file_name in files_names:
            if not fnmatch(file_name, pattern):
                continue
            s = os.path.join(root.replace('\\', '/'), file_name)
            yield (s,
                   TARGET_FILES_NAMES_RE.sub(replacement, s))

but it is still raw and should be refactored.

Test

I've created directory

/
    doc.txt
    FStar.anotherfs
    FStar.other.fS
    FStar.some.fs90
    FStar.text..fs
    test.py

    skip_me/
            FStar.file.fs
            FStar.sample.fs
            FStar.skipped.fs

where test.py contents:

import os
import re
from fnmatch import fnmatch

TARGET_FILES_NAMES_RE = re.compile(r"^.*?FStar\.(.*)\.fs(.*)")

def modify_paths(top, dest_dir, skip_dir, pattern):
    replacement = os.path.join(dest_dir, r"Fstar.\1.fst\2")
    for root, directories_names, files_names in os.walk(top):
        try:
            # we are removing `skip_dir` from all subdirectories,
            # is it a desired behavior?
            directories_names.remove(skip_dir)
        except ValueError:
            # not in list
            pass

        for file_name in files_names:
            if not fnmatch(file_name, pattern):
                continue
            s = os.path.join(root.replace('\\', '/'), file_name)
            yield (s,
                   TARGET_FILES_NAMES_RE.sub(replacement, s))

if __name__ == '__main__':
    top = '.'
    skip_dir = 'skip_me'
    patt = '*'
    # slash is required for version with list comprehension
    dest_dir = 'dest_dir/'
    before = [
        (s,
         re.sub(r"^.*?FStar\.(.*)\.fs(.*)", dest_dir + r"Fstar.\1.fst\2", s))
        for s in (os.path.join(x[0].replace('\\', '/'), f)
                  for x in os.walk(top)
                  if (skip_dir in x[1] and
                      x[1].remove(skip_dir) or True)
                  for f in x[2] if fnmatch(f, patt))]
    after = list(
        modify_paths(top=top, dest_dir=dest_dir, skip_dir=skip_dir,
                     pattern=patt))
    assert after == before

and assertion is successful.

P. S.

Skipping exceptions is not a good idea but if you know what to expect it can become a powerful tool.

Also it can be re-written using contextlib.suppress context manager from

try:
    directories_names.remove(skip_dir)
except ValueError:
    pass

to

with suppress(ValueError):
    directories_names.remove(skip_dir)


问:
What is the difference between render size and display size
What is the difference between render size (width and height) and display size (style.width and style.height)

Even when I change it to px it is still not same.

These are the examples
https://codepen.io/chartjs/pen/oWLZaR

```<code><canvas id="chart_0" height="40vw" width="80vw"></canvas>
</code>```

https://codepen.io/chartjs/pen/WjxpmO

```<code><canvas id="chart_0" style="height:40vh; width:80vw">
</code>```

答:
height="" and width="" are HTML and do not use "view height" or "view width", only fixed sizes.

vh and vw are used in CSS only.

Body:
What is the difference between render size (width and height) and display size (style.width and style.height)

Even when I change it to px it is still not same.

These are the examples
https://codepen.io/chartjs/pen/oWLZaR

<canvas id="chart_0" height="40vw" width="80vw"></canvas>

https://codepen.io/chartjs/pen/WjxpmO

<canvas id="chart_0" style="height:40vh; width:80vw">


答:
Use  this instead : </p>

```<code>HashMap<String, List<String>> map = new HashMap<String, List<String>>();
List<String> myList = new ArrayList<String>();
 if (author != null){
    myList.add(book.title)
}else{
    myList.add('NA')
}
map.put("TITLE",myList) ;
</code>```

Title: How to set the value in hashmap key:value pair conditionally?

Body:
Use  this instead :

HashMap<String, List<String>> map = new HashMap<String, List<String>>();
List<String> myList = new ArrayList<String>();
 if (author != null){
    myList.add(book.title)
}else{
    myList.add('NA')
}
map.put("TITLE",myList) ;


问:
Laravel Collective Formbuilder label localization
I just started using the Laravel Collective Form Service Provider/FormBuilder.

I use this custom component for rendering a text field with label. The problem is that I am trying to translate it's label with the __() function but the $name variable gets tansformed from first_name to First Name in a really late stage.

```<code><div class="control-group">
    {{ Form::label($name, null, ['class' => 'group__label']) }}
    {{ Form::text($name, $value, array_merge(['class' => 'control-
    group__control'], $attributes)) }}
</div>
</code>```

I can't simply do this:

```<code>{{ Form::label(__($name), null, ['class' => 'group__label']) }}
</code>```

Again, because it gets first_name and later transforms it into First Name. My nl.json file contains a translation for First Name, not first_name.

If I  add the _() translate function to the last rule of the label method in FormBuilder is, then it solves my problem. But ofcourse, I don't want to modify vendor code!

```<code> return $this->toHtmlString('<label for="' . $name . '"' . $options . '>' . __($value) . '</label>');
</code>```

So. How to solve this issue? Do I, somehow, need to create a custom FormBuilder->label() method?

答:
Use trans() helper:

```<code>{{ Form::label(trans($name), null, ['class' => 'group__label']) }}
</code>```

Body:
I just started using the Laravel Collective Form Service Provider/FormBuilder.

I use this custom component for rendering a text field with label. The problem is that I am trying to translate it's label with the __() function but the $name variable gets tansformed from first_name to First Name in a really late stage.

    {{ Form::label($name, null, ['class' => 'group__label']) }}
    {{ Form::text($name, $value, array_merge(['class' => 'control-
    group__control'], $attributes)) }}

I can't simply do this:

{{ Form::label(__($name), null, ['class' => 'group__label']) }}

Again, because it gets first_name and later transforms it into First Name. My nl.json file contains a translation for First Name, not first_name.

If I  add the _() translate function to the last rule of the label method in FormBuilder is, then it solves my problem. But ofcourse, I don't want to modify vendor code!

 return $this->toHtmlString('' . __($value) . '');

So. How to solve this issue? Do I, somehow, need to create a custom FormBuilder->label() method?

Body:
Use trans() helper:

{{ Form::label(trans($name), null, ['class' => 'group__label']) }}


问:
Assert in Selenium C#
Is there a Assert class present in Selenium C# just like we have in Coded UI test.

Or I should use the Microsoft.VisualStudio.TestTools.UnitTesting.Assert class to perform asserts in Selenium?

答:
This way assert can be used for switching into popup's displayed:</p>

```<code>IAlert alert = driver.SwitchTo().Alert();
String alertcontent = alert.Text;
Assert.AreEqual(alertcontent, "Do you want to save this article as draft?");
obj.waitfn(5000);
alert.Accept();
</code>```

Title: Assert in Selenium C#

Body:
This way assert can be used for switching into popup's displayed:

IAlert alert = driver.SwitchTo().Alert();
String alertcontent = alert.Text;
Assert.AreEqual(alertcontent, "Do you want to save this article as draft?");
obj.waitfn(5000);
alert.Accept();


问:
Constructing dict with arbritary number of key/value pairs
I'd like to know if the above is possible. I currently have a list of dictionaries (# of dictionaries in the list is arbritary). I will have to 'copy' the dictionaries from the list into another dictionary which will be the payload to my HTTP post request. An example below should make this clearer:

```<code>myList = [{'updates[123]': '1'}, {'updates[234]': '2'}, {'updates[345]': '3'}]
</code>```

Then I will need to copy it into another dict.

```<code>payload = {
    'updates[123]': '1',
    'updates[234]': '2',
    'updates[345]': '3'
    }
</code>```

Is it possible to create your 'payload' dictionary not knowing the number of elements in the original list, or is the only way just to have if else cases where it checks for len(myList) in order to index the correct number of times?

Thank you

答:
Just loop and combine the dictionaries:

```<code>payload = {}
for d in myList:
    payload.update(d)
</code>```

or using a single dict comprehension:

```<code>payload = {k: v for d in myList for k, v in d.items()}
</code>```

or using a generator expression and dict():

```<code>payload = dict(kv for d in myList for kv in d.items())
</code>```

or using functools.reduce():

```<code>from functools import reduce

payload = reduce(lambda d1, d2: d1.update(d2) or d1, myList, {})
</code>```

In all cases, if there are  duplicate keys, the key-value from dictionary listed last wins.

Performance comparison:

```<code>>>> import timeit
>>> from functools import reduce
>>> from random import choice, randint
>>> from string import ascii_letters
>>> testdata = [
...     {''.join([choice(ascii_letters) for _ in range(randint(10, 25))]): None
...     for _ in range(randint(1, 5))} for _ in range(100)]
>>> def loop(myList):
...     payload = {}
...     for d in myList:
...         payload.update(d)
...
>>> def dictcomp(myList):
...     {k: v for d in myList for k, v in d.items()}
...
>>> def genexpr(myList):
...     {k: v for d in myList for k, v in d.items()}
...
>>> def with_reduce(myList, _reduce=reduce):
...     _reduce(lambda d1, d2: d1.update(d2) or d1, myList, {})
...
>>> def trial(f, testdata):
...     t = timeit.Timer('f(l)', globals={'f': f, 'l': testdata})
...     loops, time = t.autorange()
...     print(f'{f.__name__:>12}: {(time/loops) * 1000000:0.1f} µs')
...
>>> for f in (loop, dictcomp, genexpr, with_reduce):
...     trial(f, testdata)
...
        loop: 24.6 µs
    dictcomp: 34.7 µs
     genexpr: 35.6 µs
 with_reduce: 35.2 µs
</code>```

So of all the options, the simple for loop is the most efficient.

Body:
I'd like to know if the above is possible. I currently have a list of dictionaries (# of dictionaries in the list is arbritary). I will have to 'copy' the dictionaries from the list into another dictionary which will be the payload to my HTTP post request. An example below should make this clearer:

myList = [{'updates[123]': '1'}, {'updates[234]': '2'}, {'updates[345]': '3'}]

Then I will need to copy it into another dict.

payload = {
    'updates[123]': '1',
    'updates[234]': '2',
    'updates[345]': '3'
    }

Is it possible to create your 'payload' dictionary not knowing the number of elements in the original list, or is the only way just to have if else cases where it checks for len(myList) in order to index the correct number of times?

Thank you

Body:
Just loop and combine the dictionaries:

payload = {}
for d in myList:
    payload.update(d)

or using a single dict comprehension:

payload = {k: v for d in myList for k, v in d.items()}

or using a generator expression and dict():

payload = dict(kv for d in myList for kv in d.items())

or using functools.reduce():

from functools import reduce

payload = reduce(lambda d1, d2: d1.update(d2) or d1, myList, {})

In all cases, if there are  duplicate keys, the key-value from dictionary listed last wins.

Performance comparison:

>>> import timeit
>>> from functools import reduce
>>> from random import choice, randint
>>> from string import ascii_letters
>>> testdata = [
...     {''.join([choice(ascii_letters) for _ in range(randint(10, 25))]): None
...     for _ in range(randint(1, 5))} for _ in range(100)]
>>> def loop(myList):
...     payload = {}
...     for d in myList:
...         payload.update(d)
...
>>> def dictcomp(myList):
...     {k: v for d in myList for k, v in d.items()}
...
>>> def genexpr(myList):
...     {k: v for d in myList for k, v in d.items()}
...
>>> def with_reduce(myList, _reduce=reduce):
...     _reduce(lambda d1, d2: d1.update(d2) or d1, myList, {})
...
>>> def trial(f, testdata):
...     t = timeit.Timer('f(l)', globals={'f': f, 'l': testdata})
...     loops, time = t.autorange()
...     print(f'{f.__name__:>12}: {(time/loops) * 1000000:0.1f} µs')
...
>>> for f in (loop, dictcomp, genexpr, with_reduce):
...     trial(f, testdata)
...
        loop: 24.6 µs
    dictcomp: 34.7 µs
     genexpr: 35.6 µs
 with_reduce: 35.2 µs

So of all the options, the simple for loop is the most efficient.


问:
Pre loading csv files with flask
I'm working with flask to build a web app and there are several bits in python code where I need to load a csv file.

```<code>with open('{}/src/public/file.csv'.format(current_app.config['PROJECT_ROOT']), 'r') as f:
    rows = csv.readlines(f)
</code>```

Then I go on to use rows to do some calculations.

My problem is that I'd rather not do this every time a user triggers the request. I'd rather have this loaded when I start Flask, and have rows accessible to the python code within the request.

Naturally, my first try was to take it out of the python function and put it at the start of my views.py file but that raises an app context error.

How do I achieve what I am after?

NB: I'm not familiar with the terms thread, stack, context (but willing to learn).

答:
I haven't seen your whole code so not sure if it can help. But usually when you have app context problems in flask you need to use this:</p>

```<code>from flask import Flask, current_app
# All other imports go here
app = Flask(__name__)
with app.app_context():
    with open('{}/src/public/file.csv'.format(current_app.config['PROJECT_ROOT']), 'r') as f:
    rows = csv.readlines(f)
</code>```

Title: Pre loading csv files with flask

Body:
I'm working with flask to build a web app and there are several bits in python code where I need to load a csv file.

with open('{}/src/public/file.csv'.format(current_app.config['PROJECT_ROOT']), 'r') as f:
    rows = csv.readlines(f)

Then I go on to use rows to do some calculations.

My problem is that I'd rather not do this every time a user triggers the request. I'd rather have this loaded when I start Flask, and have rows accessible to the python code within the request.

Naturally, my first try was to take it out of the python function and put it at the start of my views.py file but that raises an app context error.

How do I achieve what I am after?

NB: I'm not familiar with the terms thread, stack, context (but willing to learn).

Body:
I haven't seen your whole code so not sure if it can help. But usually when you have app context problems in flask you need to use this:

from flask import Flask, current_app
# All other imports go here
app = Flask(__name__)
with app.app_context():
    with open('{}/src/public/file.csv'.format(current_app.config['PROJECT_ROOT']), 'r') as f:
    rows = csv.readlines(f)


问:
Spring mvc it, compare payload and header values
We have some intergation tests over @RestController with a common pattern to verify that an Xpath expression exists and that an Http header is set. But I would like to go further and verify that the XPath value is equald or contained into the header.

```<code>mvc.perform(..)
  .andExpect(xpath("Item/@id/").isIn(header("Location")))
</code>```

Is it something for that or should I create my own ResultMatcher ?

答:
org.springframework.test.web.servlet.result.MockMvcResultMatchers.xpath(xpathExpress, args) is what you want.
For example:

```<code>    ResultActions resultActions = mvc.perform(..);
    String location = resultActions.andReturn().getResponse().getHeader("Location");
    resultActions.andExpect(MockMvcResultMatchers.xpath("Item/@id/", null)
            .string(org.hamcrest.Matchers.containsString(location)));
</code>```

If you need to compare by Node, XMLUnit for Java 2.x offers more usefule Matcher.

Body:
We have some intergation tests over @RestController with a common pattern to verify that an Xpath expression exists and that an Http header is set. But I would like to go further and verify that the XPath value is equald or contained into the header.

mvc.perform(..)
  .andExpect(xpath("Item/@id/").isIn(header("Location")))

Is it something for that or should I create my own ResultMatcher ?

Body:
org.springframework.test.web.servlet.result.MockMvcResultMatchers.xpath(xpathExpress, args) is what you want.
For example:

    ResultActions resultActions = mvc.perform(..);
    String location = resultActions.andReturn().getResponse().getHeader("Location");
    resultActions.andExpect(MockMvcResultMatchers.xpath("Item/@id/", null)
            .string(org.hamcrest.Matchers.containsString(location)));

If you need to compare by Node, XMLUnit for Java 2.x offers more usefule Matcher.


答:
you are missing enctype="multipart/form-data" </p>

```<code><form action="/process.php" method="post" enctype="multipart/form-data"></form>
</code>```

Title: Image uploading doesn't work

Body:
So guys.. I want to upload an image to a certain folder name "uploads" and insert the name of that image on database, the problem is that he isn't uploading the image..

So i have this basic HTML code:

<form action="newimage.php" method="POST">

        <input type="file" name="pic" id="pic">

      <button type="submit" class="btn btn-success">Submit</button>

</form>

And this is my PHP page

<?php
  $mysqli = new mysqli("localhost", "root", "", "homepage");

  if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
  }

  $name = "somethinghere";

  #do upload
  $target_dir = "uploads";
  $temp = explode(".", $_FILES["pic"]["name"]);
  $newfilename = $target_dir . '/Foto-' . $name . '.' . end($temp);

  if (move_uploaded_file($_FILES['pic']['tmp_name'], $newfilename) ) {
    $productimage = 'Foto-' . $name . '.' . end($temp);
  }
  else
  {
    $productimage = '';
  }

  $sql = "INSERT INTO galeria_front (image_name) VALUES ('$productimage')";

  if ($mysqli->query($sql) === TRUE) {
      header("Location: galery.php");
  } else {
      echo "Error: " . $sql . "
" . $mysqli->error;
  }

  $mysqli->close();
?>

As you can see i have a conection which works, and tried to insert the productimage into the database table but for some reason , it's entering the else{} and making my productimage empty on the database which means the above upload isn't working.

P.S(Pardon me for any bad english)

Body:
you are missing enctype="multipart/form-data"

<form action="/process.php" method="post" enctype="multipart/form-data"></form>


问:
How to restrict my subdomain so that anyone can only access static contents like image, CSS, JS?
I have a domain and a subdomain pointing to the same site on the server. I want to use the subdomain so that it can only be used to access the static contents like image, CSS, JS. Right now anyone can access the main website using the subdomain.

Both the domains have common htaccess files.

答:
Try adding this to your .htaccess:

```<code>RewriteCond %{HTTP_HOST}  =subdomain.example.com [NC]
RewriteCond %{REQUEST_URI} !\.(jpg|jpeg|png|gif|ico|css|js|swf)$
RewriteRule ^ - [F]
</code>```

Body:
Try adding this to your .htaccess:

RewriteCond %{HTTP_HOST}  =subdomain.example.com [NC]
RewriteCond %{REQUEST_URI} !\.(jpg|jpeg|png|gif|ico|css|js|swf)$
RewriteRule ^ - [F]


问:
Change Border Color for DatePicker
I would like to change the border color for the focus state on the DatePicker control.
I took a look at the Default Style Template and didn't see any Focus State for the VisualStateManager.

The only thing I saw was a primitive control for the TextBox as follows:

```<code><controlsPrimitives:DatePickerTextBox x:Name="TextBox" SelectionBackground="{TemplateBinding SelectionBackground}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" Grid.Column="0" />
</code>```

How can I change the color for the focus state for the border for the DatePicker... I had no problem changing this color for the TextBox, ComboBox and the CheckBox controls.

Please Help!

答:
Does this work for you:</p>

```<code>public class MyDatePicker : DatePicker
{
    public MyDatePicker()
    { }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        DatePickerTextBox textBox = (DatePickerTextBox)this.GetTemplateChild("TextBox");
        textBox.GotFocus += new RoutedEventHandler(textBox_GotFocus);
        textBox.LostFocus += new RoutedEventHandler(textBox_LostFocus);
    }

    void textBox_GotFocus(object sender, RoutedEventArgs e)
    {
        (sender as DatePickerTextBox).BorderBrush = new SolidColorBrush(Colors.Red);
    }

    void textBox_LostFocus(object sender, RoutedEventArgs e)
    {
        (sender as DatePickerTextBox).ClearValue(DatePickerTextBox.BorderBrushProperty);
    }
}
</code>```

Title: Change Border Color for DatePicker

Body:
I would like to change the border color for the focus state on the DatePicker control.
I took a look at the Default Style Template and didn't see any Focus State for the VisualStateManager.

The only thing I saw was a primitive control for the TextBox as follows:

<controlsPrimitives:DatePickerTextBox x:Name="TextBox" SelectionBackground="{TemplateBinding SelectionBackground}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" Grid.Column="0" />

How can I change the color for the focus state for the border for the DatePicker... I had no problem changing this color for the TextBox, ComboBox and the CheckBox controls.

Please Help!

Body:
Does this work for you:

public class MyDatePicker : DatePicker
{
    public MyDatePicker()
    { }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        DatePickerTextBox textBox = (DatePickerTextBox)this.GetTemplateChild("TextBox");
        textBox.GotFocus += new RoutedEventHandler(textBox_GotFocus);
        textBox.LostFocus += new RoutedEventHandler(textBox_LostFocus);
    }

    void textBox_GotFocus(object sender, RoutedEventArgs e)
    {
        (sender as DatePickerTextBox).BorderBrush = new SolidColorBrush(Colors.Red);
    }

    void textBox_LostFocus(object sender, RoutedEventArgs e)
    {
        (sender as DatePickerTextBox).ClearValue(DatePickerTextBox.BorderBrushProperty);
    }
}