问:
Ruby on Rails: Are "form_for(:product, ...)" and "form_for(@product, ...)" equivalent?
Is

```<code><%= form_for(:product, :url => {:action => 'update', :id => @product.id})) do |f| %>
  ...
<% end %>
</code>```

and

```<code><%= form_for(@product, :url => {:action => 'update', :id => @product.id})) do |f| %>
  ...
<% end %>
</code>```

exactly the same ?

答:
The @product in the form_for helper ships with more features.

The :product only affects the input field's id and name. For example you have a text filed in the form:

```<code><%= form_for :product, :url => {...}　do |f| %>
  <%= f.text_field :price %>
<% end %>
</code>```

The generated html would look like:

```<code><input type="text" id="product_price" name="product[price]" />
</code>```

The id and name value is determined by the :product.to_s and the text field name.

While if you use @product, the :url is not necessary because the url would be determined according to the @product's status:

if the @product is a new record, the url would post to create

otherwise, the url would post to update

And the input filed's id and name is affected by @product's class name, so it's important when you're using single table inheritant. The input filed's value is automatically assigned with the @product's attribute value. So if you use @product, the html output would look like:

```<code><input type="text" id="product_price" name="product[price]" value="some value" />
</code>```

Assume the @product's class name is Item, then the output would change to:

```<code><input type="text" id="item_price" name="item[price]" value="some value" />
</code>```

And of course you can use both of :product and @product:

```<code><%= form_for :product, @product do |f| %>
</code>```

The :product controls input filed's name and id, and the @product controls the url and input field's value.

Body:
Is

<%= form_for(:product, :url => {:action => 'update', :id => @product.id})) do |f| %>
  ...
<% end %>

and

<%= form_for(@product, :url => {:action => 'update', :id => @product.id})) do |f| %>
  ...
<% end %>

exactly the same ?

Body:
The @product in the form_for helper ships with more features.

The :product only affects the input field's id and name. For example you have a text filed in the form:

<%= form_for :product, :url => {...}　do |f| %>
  <%= f.text_field :price %>
<% end %>

The generated html would look like:

<input type="text" id="product_price" name="product[price]" />

The id and name value is determined by the :product.to_s and the text field name.

While if you use @product, the :url is not necessary because the url would be determined according to the @product's status:

if the @product is a new record, the url would post to create

otherwise, the url would post to update

And the input filed's id and name is affected by @product's class name, so it's important when you're using single table inheritant. The input filed's value is automatically assigned with the @product's attribute value. So if you use @product, the html output would look like:

<input type="text" id="product_price" name="product[price]" value="some value" />

Assume the @product's class name is Item, then the output would change to:

<input type="text" id="item_price" name="item[price]" value="some value" />

And of course you can use both of :product and @product:

<%= form_for :product, @product do |f| %>

The :product controls input filed's name and id, and the @product controls the url and input field's value.


来源: stackexchange

问:
How to convert a PDF to grayscale from command line avoiding to be rasterized?
I'm trying to convert to grayscale this PDF: https://dl.dropboxusercontent.com/u/10351891/page-27.pdf

Ghostscript (v 9.10) with pdfwrite Device fails with a "Unable to convert color space to Gray, reverting strategy to LeaveColorUnchanged." message.

I'm able to convert it through an intermediary ps file (using gs, pdftops (v 0.24.3) or pdf2ps) but this convertion rasterize the whole PDF.
I tryed a lot of other things: normalize the PDF using qpdf (v 5.0.1) or pdftk (v 1.44), transform it to a svg file and back to a PDF via Inkscape (v 0.48.4)... nothing seems to work.

The only one solution I found (which is not suitable for me in production environment) is to use Preview on my Mac and apply a Quartz Gray Tone filter manually or with an Automator script.

Anyone find another working way to do it?
Or is it possible to normalize the PDF or fix the issue to prevent the Ghostscript message "Unable to convert color space..." or to force the color space in another way?

Thanks!

答: You can use something which I created. It gives you the option to choose the specific page numbers that you want to convert to grayscale. Handy if you don't want to grayscale the entire pdf. https://github.com/shoaibkhan94/PdfGrayscaler. </p>

ContentLicense: CC BY-SA 3.0


问:
Reading data from txt file using javascript, every 5 min
I'm trying to make the website that shows current temp at home and allows me to set the temp as I want. To read temp I use raspberry pi zero and python code to save the temp in every 5 min to the .txt file. The problem is that I need to read current temp on my website from that file in let's say very 5 min. I can use:

    <meta http-equiv="Refresh" content="s" />

But it doesn't look like a good choice so I though that I can use javascript and read data from the file. Unfortunately this function works only once no matter what I change in .txt file and refresh the web, output is still the same (looks like it save previous data to some kind of the global variable).

```<code>function readTextFile()
            {
                var rawFile = new XMLHttpRequest();
                rawFile.open("GET", 'text.txt', true);
                rawFile.onreadystatechange = function ()
            {
                if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}
</code>```

On the left side at this picture there are data from the txt file (using php), and at the alert handler are data using javascript and submit button. These data should be the same.

So the question is: Can I read from a .txt file when its dynamicly change? And if so, how can I do it or what function use to do it? I don't know javascript very well.
I will be very grateful for help.

答:
you need update your .txt file in some interval, for save changes,
after set attribute id="textarea"

```<code>//use jOuery
var interval = setInterval(function(){ myFunction() },5*60*1000); // 1000=1 second

function myFunction(){
    $.get('server_address',{param1:1,param2:2},function(response){
        //if is textarea or input
        $('#textarea').val(response);
        //if is block div, span or something else
        //$('#textarea').text(response);
    });
}
</code>```

server_address - is page where you read file content, and print them  .... if it is php, then file "write.php" with code like

```<code><?php
echo(file_get_contents('some.txt'));
</code>```

{param1:1,param2:2} - is object, with params, what you send to "server_address", like {action:'read',file:'some.txt'} or something other

response - is text what is print in page on "server_address"

Body:
I'm trying to make the website that shows current temp at home and allows me to set the temp as I want. To read temp I use raspberry pi zero and python code to save the temp in every 5 min to the .txt file. The problem is that I need to read current temp on my website from that file in let's say very 5 min. I can use:

    <meta http-equiv="Refresh" content="s" />

But it doesn't look like a good choice so I though that I can use javascript and read data from the file. Unfortunately this function works only once no matter what I change in .txt file and refresh the web, output is still the same (looks like it save previous data to some kind of the global variable).

function readTextFile()
            {
                var rawFile = new XMLHttpRequest();
                rawFile.open("GET", 'text.txt', true);
                rawFile.onreadystatechange = function ()
            {
                if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

On the left side at this picture there are data from the txt file (using php), and at the alert handler are data using javascript and submit button. These data should be the same.

So the question is: Can I read from a .txt file when its dynamicly change? And if so, how can I do it or what function use to do it? I don't know javascript very well.
I will be very grateful for help.

Body:
you need update your .txt file in some interval, for save changes,
after set attribute id="textarea"

//use jOuery
var interval = setInterval(function(){ myFunction() },5*60*1000); // 1000=1 second

function myFunction(){
    $.get('server_address',{param1:1,param2:2},function(response){
        //if is textarea or input
        $('#textarea').val(response);
        //if is block div, span or something else
        //$('#textarea').text(response);
    });
}

server_address - is page where you read file content, and print them  .... if it is php, then file "write.php" with code like

<?php
echo(file_get_contents('some.txt'));

{param1:1,param2:2} - is object, with params, what you send to "server_address", like {action:'read',file:'some.txt'} or something other

response - is text what is print in page on "server_address"


问:
Converting a VARCHAR ',96' into integer 0.96 in SQL Server
I have to do the conversion as mentioned in the title, I tried a lot of things and couldn't find the solution yet.

Any help please?

Thanks!

答:
One simple way is to replace , with dot and do convert as below:

```<code>declare @v varchar(10) = ',96'
select converT(float, replace(@v,',','.'))
</code>```

I think in your question you mentioned as integer, in this case it will be ZERO because it will take floor value and not consider the round, hence left to float and you can decide on required approach

Body:
One simple way is to replace , with dot and do convert as below:

declare @v varchar(10) = ',96'
select converT(float, replace(@v,',','.'))

I think in your question you mentioned as integer, in this case it will be ZERO because it will take floor value and not consider the round, hence left to float and you can decide on required approach


问:
using namespace System; in Visual Studio 2013
I am trying to use the Console::SetCursorPosition(int, int) method.  When I add the line using namespace System;, as shown in the C++ example from the preceding MSDN documentation, I get the error "Error: name must be a namespace name".  I have been trying stuff for a couple hours now, but frustratingly without success.  I have come across a ton of documentation for Visual Studio 2010 and 2012, but very little for 2013.  The closest I have come is Lib Files as Linker Input.  Steps 1-3 are easy enough, but step 4 is not clear to me:  "Modify the Additional Dependencies property.".  Looking at what is already there, it seems like I can just add a .lib file.  But I don't have a System.lib.

So frustrated, so confused.

How can I use the System namespace in Visual Studio 2013 Update 4 for C++?

答:
You have to set Common Language Runtime Support  (/clr) in Configuration Properties - General:

And in Configuration Properties - C/C++ - General:


问:
Adding custom header in HTTP request of prometheus
Prometheus send HTTP request to get monitor values. My custom export supports variety of clients (to monitors system status). There is a general REST API to get list of monitors:

```<code>/api/v1/monitor/find
</code>```

the output result depend on Accept attribute in header. The default accept value is application/json.

I add new mime type to support prometheus (e.g. application/prometheus) into the API.

But, how to config Prometheus to add a custom header (Accept: application/prometheus)?

答:
Prometheus doesn't support setting headers, as that would lead to users creating hard to debug endpoints. You can either use a separate endpoint or pass a parameter.

Prometheus also already has a specified mime type for scrapes, so you could use that. See https://prometheus.io/docs/instrumenting/exposition_formats/

Body:
Prometheus send HTTP request to get monitor values. My custom export supports variety of clients (to monitors system status). There is a general REST API to get list of monitors:

/api/v1/monitor/find

the output result depend on Accept attribute in header. The default accept value is application/json.

I add new mime type to support prometheus (e.g. application/prometheus) into the API.

But, how to config Prometheus to add a custom header (Accept: application/prometheus)?


问:
How to change the background colour gradient of view dynamically
I want to make a custom view for my android app which has a functionality to change its background colour "gradient".

Something like this, but the centre handle can be moved left and right using code

The catch is that I want a function something like in the view:

```<code>changeBackgroundGradient(ratio, startColour, centreColour, endColour);
</code>```

ratio (having value between 0 to 1) which is given by formula
leftValue/rightValue determining the shape of the gradient

startColour, centreColour and endColour being the colours of which the gradient consists of

How would i make this function?

Regards

答:
You can try following function. Add these functions in your activity file.

```<code>       private Drawable getGradientDrawable()
        {
            GradientDrawable gradient = new GradientDrawable();
            gradient.setGradientType(GradientDrawable.LINEAR_GRADIENT);
            gradient.setColors(new int[]{getRandomHSVColor(), getRandomHSVColor()});
            return gradient;
        }

        protected int getRandomHSVColor(){
            // Generate a random hue value between 0 to 360
            int hue = mRandom.nextInt(361);
            // We make the color depth full
            float saturation = 1.0f;
            // We make a full bright color
            float value = 1.0f;
            // We avoid color transparency
            int alpha = 255;
            // Finally, generate the color
            int color = Color.HSVToColor(alpha, new float[]{hue, saturation, value});
            // Return the color
            return color;
        }
        // Custom method to get a lighter color
        protected int getLighterColor(int color){
            float[] hsv = new float[3];
            Color.colorToHSV(color,hsv);
            hsv[2] = 0.2f + 0.8f * hsv[2];
            return Color.HSVToColor(hsv);
        }

        // Custom method to get reverse color
        protected int getReverseColor(int color){
            float[] hsv = new float[3];
            Color.RGBToHSV(
                    Color.red(color), // Red value
                    Color.green(color), // Green value
                    Color.blue(color), // Blue value
                    hsv
            );
            hsv[0] = (hsv[0] + 180) % 360;
            return Color.HSVToColor(hsv);
        }
</code>```

Than use this function like below:

your_layout_name..setBackground(getGradientDrawable());

Body:
I want to make a custom view for my android app which has a functionality to change its background colour "gradient".

Something like this, but the centre handle can be moved left and right using code

The catch is that I want a function something like in the view:

changeBackgroundGradient(ratio, startColour, centreColour, endColour);

ratio (having value between 0 to 1) which is given by formula
leftValue/rightValue determining the shape of the gradient

startColour, centreColour and endColour being the colours of which the gradient consists of

How would i make this function?

Regards

Body:
You can try following function. Add these functions in your activity file.

       private Drawable getGradientDrawable()
        {
            GradientDrawable gradient = new GradientDrawable();
            gradient.setGradientType(GradientDrawable.LINEAR_GRADIENT);
            gradient.setColors(new int[]{getRandomHSVColor(), getRandomHSVColor()});
            return gradient;
        }

        protected int getRandomHSVColor(){
            // Generate a random hue value between 0 to 360
            int hue = mRandom.nextInt(361);
            // We make the color depth full
            float saturation = 1.0f;
            // We make a full bright color
            float value = 1.0f;
            // We avoid color transparency
            int alpha = 255;
            // Finally, generate the color
            int color = Color.HSVToColor(alpha, new float[]{hue, saturation, value});
            // Return the color
            return color;
        }
        // Custom method to get a lighter color
        protected int getLighterColor(int color){
            float[] hsv = new float[3];
            Color.colorToHSV(color,hsv);
            hsv[2] = 0.2f + 0.8f * hsv[2];
            return Color.HSVToColor(hsv);
        }

        // Custom method to get reverse color
        protected int getReverseColor(int color){
            float[] hsv = new float[3];
            Color.RGBToHSV(
                    Color.red(color), // Red value
                    Color.green(color), // Green value
                    Color.blue(color), // Blue value
                    hsv
            );
            hsv[0] = (hsv[0] + 180) % 360;
            return Color.HSVToColor(hsv);
        }

Than use this function like below:

your_layout_name..setBackground(getGradientDrawable());


问:
google.gson.fromJson where classOfT is generic array
How deserialize array of generic type with gson.fromJson

public class Cache<T> {

    public void M(String json) {
        JsonArray ja = (JsonArray) new JsonParser().parse(json);
        Gson gson = new GsonBuilder().create();
        T[] items = gson.fromJson(ja, ?);
    }
}
```

<p>This not work</p>

<pre class="lang-java prettyprint-override"><code>Type t = new TypeToken<ArrayList<T>>() {}.getType();
T[] items = gson.fromJson(ja, t);
</code>```

T[] items = gson.fromJson(ja, T[].class);
```

<pre class="lang-java prettyprint-override"><code>T[] items = gson.fromJson(ja, new T[].getClass());
</code>```

答:
```<code>T[] array = (T[]) Array.newInstance(clazz, 0);
T[] result = gson.fromJson(jsonString, (Type) array.getClass());
List<T> resultList = Arrays.asList(result);
</code>```

Body:
How deserialize array of generic type with gson.fromJson

public class Cache<T> {

    public void M(String json) {
        JsonArray ja = (JsonArray) new JsonParser().parse(json);
        Gson gson = new GsonBuilder().create();
        T[] items = gson.fromJson(ja, ?);
    }
}

This not work

Type t = new TypeToken<ArrayList<T>>() {}.getType();
T[] items = gson.fromJson(ja, t);

T[] items = gson.fromJson(ja, T[].class);

T[] items = gson.fromJson(ja, new T[].getClass());


问:
How do I get a function to be called when a menu item is clicked?
In Qt, I have a menubar that looks something like this:

```<code>|File|
+-------------------+
|Do Something       |
|Do Something Else  |
+-------------------+
</code>```

I have a function doSomething that I want to be called when the user clicks on the Do Something in the file menu, and a function doSomethingElse that I similarly want to be called when the user clicks on that menu item. How would I accomplish this?

答:
Generally speaking, your menu items are QActions.  Connect the QAction signal triggered() with the doSomething() that you want called.

This is a pretty full-fledged description of how this works. But this section of the address book tutorial is good for a quick explanation.

ContentLicense: CC BY-SA 2.5

Body:
In Qt, I have a menubar that looks something like this:

|File|
+-------------------+
|Do Something       |
|Do Something Else  |
+-------------------+

I have a function doSomething that I want to be called when the user clicks on the Do Something in the file menu, and a function doSomethingElse that I similarly want to be called when the user clicks on that menu item. How would I accomplish this?


问:
How to view user privileges using windows cmd?
I am trying to view the user privileges using the command prompt in Windows.
User account & User privileges such as:

```<code>SeBatchLogonRight
SeDenyBatchLogonRight
SeInteractiveLogonRight
SeDenyInteractiveLogonRight
SeServiceLogonRight
SeDenyServiceLogonRight
SeNetworkLogonRight
SeDenyNetworkLogonRight
</code>```

I tried using ntrights but it's not working. I can't use any tool as I am trying to create an automated script for an OS audit.

答: Use whoami /priv command to list all the user privileges.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to view the user privileges using the command prompt in Windows.
User account & User privileges such as:

SeBatchLogonRight
SeDenyBatchLogonRight
SeInteractiveLogonRight
SeDenyInteractiveLogonRight
SeServiceLogonRight
SeDenyServiceLogonRight
SeNetworkLogonRight
SeDenyNetworkLogonRight

I tried using ntrights but it's not working. I can't use any tool as I am trying to create an automated script for an OS audit.


问:
Is it a good practice to use Runtime.getRuntime().gc() method in onDestroy() of an Activity?
onDestroy() method of an Activity does not reduces my memory usage. I am allocating some memory onCreate() of an Activity, but onDestroy() of that same activity does not de-allocates the memory as seen in the Android Monitor.

So, I was using the Runtime.getRuntime().gc() method to clear the memory manually. I was calling it in onDestroy() method.

Is it a good practice ?

答:
I was using the Runtime.getRuntime().gc() method to clear the memory manually

That does not "clear the memory".

When I am opening a new activity, the memory allocation takes place. If I go back and forth, the memory keeps stacking up

Then you have some form of memory leak. Use the development tools to determine where the problem is coming from.


问:
Calling Tkinter root.quit() causes kernel and window to stop responding
```<code>import Tkinter as Tk

root = Tk.Tk()

def generate():
    root.quit()

label1 = Tk.Label(root, text="Map Width:")
label2 = Tk.Label(root, text="Map Height:")
label3 = Tk.Label(root, text="Lake Size:")
e1 = Tk.Entry(root)
e2 = Tk.Entry(root)
e3 = Tk.Entry(root)
button1 = Tk.Button(root, text="Generate", command=generate)
label1.grid(row=0, column=0)
label2.grid(row=1, column=0)
label3.grid(row=2, column=0)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
button1.grid(row=3, column=1)

root.mainloop()
</code>```

This is a snippet from a larger project, with the remaining function of generate() removed for simplicity's sake. With the above code, a window is successfully created with three labels, three corresponding entry fields and a single button. The generate button is intended to call the function generate() which in turn creates a map object based on other code, and then calls root.quit().

However, when the button is pressed, the window stops responding and the python kernel repeatedly prints the message:

```<code>It seems the kernel died unexpectedly. Use 'Restart kernel' to continue using this console.
</code>```

I'm sure it's a minor mistake, but if anyone could show me where I went wrong I'd be very grateful.

答:
Use root.destroy() instead of root.quit()

root.quit() from my understanding this is better used when you have other code after your main loop you want to run.

```<code>"""Quit the Tcl interpreter. All widgets will be destroyed."""
</code>```

root.destroy() will destroy everything inside your main loop. and should be used to exit a program.

This is a quote from the method in the tkinter library.

```<code>"""Destroy this and all descendants widgets. This will
        end the application of this Tcl interpreter."""
</code>```

Body:
import Tkinter as Tk

root = Tk.Tk()

def generate():
    root.quit()

label1 = Tk.Label(root, text="Map Width:")
label2 = Tk.Label(root, text="Map Height:")
label3 = Tk.Label(root, text="Lake Size:")
e1 = Tk.Entry(root)
e2 = Tk.Entry(root)
e3 = Tk.Entry(root)
button1 = Tk.Button(root, text="Generate", command=generate)
label1.grid(row=0, column=0)
label2.grid(row=1, column=0)
label3.grid(row=2, column=0)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
button1.grid(row=3, column=1)

root.mainloop()

This is a snippet from a larger project, with the remaining function of generate() removed for simplicity's sake. With the above code, a window is successfully created with three labels, three corresponding entry fields and a single button. The generate button is intended to call the function generate() which in turn creates a map object based on other code, and then calls root.quit().

However, when the button is pressed, the window stops responding and the python kernel repeatedly prints the message:

It seems the kernel died unexpectedly. Use 'Restart kernel' to continue using this console.

I'm sure it's a minor mistake, but if anyone could show me where I went wrong I'd be very grateful.

Body:
Use root.destroy() instead of root.quit()

root.quit() from my understanding this is better used when you have other code after your main loop you want to run.

"""Quit the Tcl interpreter. All widgets will be destroyed."""

root.destroy() will destroy everything inside your main loop. and should be used to exit a program.

This is a quote from the method in the tkinter library.

"""Destroy this and all descendants widgets. This will
        end the application of this Tcl interpreter."""


问:
fix the showing gif in Java swing
I want to show a gif in java swing.

For show gif I use from these code but in both of them the gif is not moving and it like as an image is static.

first code:

```<code>void showGif() {
    try {
        JPanel panel = new JPanel();
        BufferedImage bufferedImage = ImageIO.read(new File("address of gif");
        Icon icon = new ImageIcon(bufferedImage);
        JLabel label = new JLabel(icon);
        label.setVisible(true);
        panel.add(label);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

second code:

```<code> void showGif() {
    try {
        ImageIcon imageIcon;
        BufferedImage bufferedImage = ImageIO.read(new File("address of gif"));
        imageIcon = new ImageIcon(bufferedImage);
        JLabel label = new JLabel(imageIcon);
        JPanel panel = new JPanel();
        label.setVisible(true);
        panel.add(label, TOP_ALIGNMENT);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

please help me to show gif correctly.

答:
You ImageIcon in this case will be showing just the first frame of the GIF.

You can add the GIF to a JLabel, which you can add to the JPanel. Check this out for further help.

Title: fix the showing gif in Java swing

Body:
I want to show a gif in java swing.

For show gif I use from these code but in both of them the gif is not moving and it like as an image is static.

first code:

void showGif() {
    try {
        JPanel panel = new JPanel();
        BufferedImage bufferedImage = ImageIO.read(new File("address of gif");
        Icon icon = new ImageIcon(bufferedImage);
        JLabel label = new JLabel(icon);
        label.setVisible(true);
        panel.add(label);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

second code:

 void showGif() {
    try {
        ImageIcon imageIcon;
        BufferedImage bufferedImage = ImageIO.read(new File("address of gif"));
        imageIcon = new ImageIcon(bufferedImage);
        JLabel label = new JLabel(imageIcon);
        JPanel panel = new JPanel();
        label.setVisible(true);
        panel.add(label, TOP_ALIGNMENT);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

please help me to show gif correctly.


问:
Share data between two JVMs when application is clustered
I am working on a spring-boot application, which can be clustered into many instances.

The sessions data are stored and handled by Spring Session + Hazelcast, but the problem is for the cases like this one. I have a class that contains a Set of objects:

```<code>@ServerEndpoint(value="/chat/{username}")
public class ChatEndpoint {

    private Session session;
    private static Set<ChatEndpoint> chatEndpoints
      = new CopyOnWriteArraySet<>();
    private static HashMap<String, String> users = new HashMap<>();

    @OnOpen
    public void onOpen(
      ....
    }

    @OnMessage
    public void onMessage(Session session, Message message)
      throws IOException {
      ....
    }
   ....
}
</code>```

In this case, the data is available locally on every instance of the JVM. How can I make this data shared between all the JVMs ?

答:
As you have Hazelcast already available in your tech stack, use the caching facility of Hazelcast:

Hazelcast is the leading in-memory data grid solution. Its java
  caching solution enables organizations to predictably scale
  mission-critical enterprise applications by providing in-memory access
  to frequently used data. Hazelcast stores frequently accessed data
  in-memory and across an elastically scalable data grid. This enables
  any network of machines to dynamically cluster and pool both memory
  and processors to accelerate application performance.

You can put the set of data to a cache created with Hazelcast, and access the data on other nodes in the cluster.

Body:
I am working on a spring-boot application, which can be clustered into many instances.

The sessions data are stored and handled by Spring Session + Hazelcast, but the problem is for the cases like this one. I have a class that contains a Set of objects:

@ServerEndpoint(value="/chat/{username}")
public class ChatEndpoint {

    private Session session;
    private static Set<ChatEndpoint> chatEndpoints
      = new CopyOnWriteArraySet<>();
    private static HashMap<String, String> users = new HashMap<>();

    @OnOpen
    public void onOpen(
      ....
    }

    @OnMessage
    public void onMessage(Session session, Message message)
      throws IOException {
      ....
    }
   ....
}

In this case, the data is available locally on every instance of the JVM. How can I make this data shared between all the JVMs ?


问:
how to convert entire dataframe values to float in pandas
My question is similar to this one.

I want to convert all the values in the dataframe to float type. But what is need more is to ignore the rows where such conversions cannot happen.

For example, given a string '0.9', it will be converted to float successfully but a string like 'why' will through an error. I want to remove all such rows in the dataframe which would come under the error case.

答:
Try this:

```<code>df = df.apply(pd.to_numeric, errors='coerce')
</code>```

From docs:

errors : {‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’

If ‘raise’, then invalid parsing will raise an exception

If ‘coerce’, then invalid parsing will be set as NaN

If ‘ignore’, then invalid parsing will return the input

Body:
Try this:

df = df.apply(pd.to_numeric, errors='coerce')

From docs:

errors : {‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’

If ‘raise’, then invalid parsing will raise an exception

If ‘coerce’, then invalid parsing will be set as NaN

If ‘ignore’, then invalid parsing will return the input


问:
display message on success return in ajax with jquery problem
i am using ajax with jquery .i have written this code:

```<code>   $.ajax({url:"myurl.php",
           data:datastr,
           type:"POST",
           success:function(data){
                      $("#msgbx").text(data);
           }
    });
</code>```

it done what i want at the backend but doesn't show the return message in div with #msgbx id.

what is the problem?

答:
The problem may be related to the formatting or encoding of your returned JSON object, or it may be a failure on the server that occurs after all your other processing is done, but immediately before you return your data.

Without seeing any other code, try looking at the console window in either Firebug or Chrome's web development tools to see what your server is responding with.  You should see an Ajax POST method logged to the console window.  Assuming you don't have an error code shown there, check to see what sort of data is being returned (or if any is being returned at all).

If you are getting data back from the server, your problem is in how you're displaying that on the page / inserting it into the DOM.  If on the other hand you aren't returning anything, you'll need to check your PHP code to see where other problems might exist in your logic.

Feel free to add more to your post so we can give more specific answers.

Body:
i am using ajax with jquery .i have written this code:

   $.ajax({url:"myurl.php",
           data:datastr,
           type:"POST",
           success:function(data){
                      $("#msgbx").text(data);
           }
    });

it done what i want at the backend but doesn't show the return message in div with #msgbx id.

what is the problem?


问:
Swift 3 UISwitch in TableViewCell loses State when scrolling
That's weird: I just set up a new Single-View iOS Project and put a TableView into the Main.storyboard. In this TableView I put a TableViewCell and into this Cell, I put an UILabel and an UISwitch.
For this TableViewCell I created a CocoaTouchClass MyTableViewCell and set this for the TableViewCell's Class in Interfacebuilder.
I connected Outlets for the UILabel and UISwitch to MyTableViewCell, as well as an action for the switch.
Also I connected the TableView's dataSource and delegate to the ViewController.

So, as I think, basic stuff for setting up a table.

My ViewController looks like this:

```<code>class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var tableData = [[String: Bool]]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for index in 1...40 {
        self.tableData.append([String(index): index%2 == 0])
    }
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.tableData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) as! MyTableViewCell
    let object = tableData[indexPath.row].first!

    cell.myLabel.text = object.key
    cell.mySwitch.setOn(object.value, animated: false)

    return cell
}
</code>```

}

So, I populate the Table with some Rows of Data and switch every second UISwitch to on.

The MyTableViewCell-Class is nothing special as well:

```<code>class MyTableViewCell: UITableViewCell {
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var mySwitch: UISwitch!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

@IBAction func switched(_ sender: UISwitch) {
    print("Switched: \(sender.isOn)")
}
</code>```

}

Ok, fire up the iOS-Simulator and I see the Table as expected. 40 Table-Lines don't fit on one screen, so the TableView makes itself scrollable.

Now: when I change the state of one UISwitch, and drag the TableView so the changed UISwitch gets out of view and then drag the TableView so the changed UISwitch gets visible again, it is changed back to its initial state.
The Switch-event gets fired like it should.

So, what am I doing wrong? Am I missing something?

I recorded a 4-seconds-Screencast to demonstrate, what's going on:
http://b-bereich.de/download/swiftSwitch.mov

答: I think you need to have your IBAction change the Bool each time you flip the switch. Currently the switch changes the UI but not the underlying Bool so the cellForRowAt method uses the currently saved value when the cell scrolls back on screen.

Body:
That's weird: I just set up a new Single-View iOS Project and put a TableView into the Main.storyboard. In this TableView I put a TableViewCell and into this Cell, I put an UILabel and an UISwitch.
For this TableViewCell I created a CocoaTouchClass MyTableViewCell and set this for the TableViewCell's Class in Interfacebuilder.
I connected Outlets for the UILabel and UISwitch to MyTableViewCell, as well as an action for the switch.
Also I connected the TableView's dataSource and delegate to the ViewController.

So, as I think, basic stuff for setting up a table.

My ViewController looks like this:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var tableData = [[String: Bool]]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for index in 1...40 {
        self.tableData.append([String(index): index%2 == 0])
    }
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.tableData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) as! MyTableViewCell
    let object = tableData[indexPath.row].first!

    cell.myLabel.text = object.key
    cell.mySwitch.setOn(object.value, animated: false)

    return cell
}

}

So, I populate the Table with some Rows of Data and switch every second UISwitch to on.

The MyTableViewCell-Class is nothing special as well:

class MyTableViewCell: UITableViewCell {
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var mySwitch: UISwitch!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

@IBAction func switched(_ sender: UISwitch) {
    print("Switched: \(sender.isOn)")
}

}

Ok, fire up the iOS-Simulator and I see the Table as expected. 40 Table-Lines don't fit on one screen, so the TableView makes itself scrollable.

Now: when I change the state of one UISwitch, and drag the TableView so the changed UISwitch gets out of view and then drag the TableView so the changed UISwitch gets visible again, it is changed back to its initial state.
The Switch-event gets fired like it should.

So, what am I doing wrong? Am I missing something?

I recorded a 4-seconds-Screencast to demonstrate, what's going on:
http://b-bereich.de/download/swiftSwitch.mov


问:
How can a map be used to search the list of employe objects on the basis of different parameters?
I was asked this question in an interview today to which I explained the best to my abilities. But I still don't understand if this is the correct answer.

There is a cache which has Employee object as the key. The cache is populated with data from the database. Now there is a UI where we can enter either or all of the 3 attributes from the Employee object- name, ID and date of joining. Now this search would lead to multiple matching results.  To achieve this we need to check in the cache for the data.

To this I replied saying that my map would be of the structure - >. for the same EmployeeDetails object ,
 I will have multiple keys in the map(EmployeeDetails class is the object which contains complete detail of the Employee including address etc. Employee object just has 3 attributes - name, ID and date of joining.).

One of the objects with only name populated. The other with ID populated and the third one with date of joining populated. And now with the combination of attributes. So the map will be having the following keys -
Employee object with only the name populated -> Value would be list of of all the Employee objects with the same name.
Employee object with only the ID populated ->  Value would be list of of all the Employee objects with the same ID. Ideally the list size in this case should be 1.
Employee objects with only the Date Of Joining -> List of all the employee objects with the same date of joining.

Similarly there would be number of other Employee objects. For one such employee , all the three attributes - name , ID and date of joining would be populated.

In this way, I could have achieved the requirement to display all the employee results in case only some of the attributes out of name, ID and value is set on the UI.

I just want to understand if this is the correct way to achieve the outcome (display of list of matching results on the UI). Since I did not get selected, I believe there is something else which I possibly missed!

答:
A reasonable short answer is to maintain 3 separate maps for each of the 3 fields, with each one mapping from each field value to the list of employees with that value for the field.

To perform a lookup, retrieve the lists for each of the values that the user specified, and then (if you have more than one criteria) iterate through the shortest one to filter out employees that don't match the other criteria.

In the cases where you have more than one criteria, one of them has to be name or ID.  In real life, the lists for these fields will be very short, so you won't have to iterate through any large collections.

This solution essentially uses the maps as indexes and implements the query like a relational DB.  If you were to mention that in an interview, you would get extra points, but you'd need to be able to back it up.


问:
Android : Webview opening pdf url outside app
I am trying to open pdf url using google docs but for API level 21 and above that pdf opens in mobile browser and for below 21 it does not open.
When I set any website url to same webview it opens perfectly inside the app.

What is exact problem?

Please help.

This is my webview Code :

```<code>WebView webviewPDF = (WebView) view.findViewById(R.id.resource8_9_webview);
        webviewPDF.loadUrl(strUrl);
        WebSettings webSettings = webviewPDF.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setUseWideViewPort(true);
        webviewPDF.setWebChromeClient(new WebChromeClient());
        webviewPDF.clearSslPreferences();
</code>```

答:
this is the answer to your question:</p>

```<code>WebView webview = FindViewById<WebView>(Resource.Id.webView1);
        urlPdf = ("pdf url example ");
        WebSettings settings = webview.Settings;
        settings.JavaScriptEnabled = true;
        webview.LoadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + urlPdf);
</code>```

Body:
I am trying to open pdf url using google docs but for API level 21 and above that pdf opens in mobile browser and for below 21 it does not open.
When I set any website url to same webview it opens perfectly inside the app.

What is exact problem?

Please help.

This is my webview Code :

WebView webviewPDF = (WebView) view.findViewById(R.id.resource8_9_webview);
        webviewPDF.loadUrl(strUrl);
        WebSettings webSettings = webviewPDF.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setUseWideViewPort(true);
        webviewPDF.setWebChromeClient(new WebChromeClient());
        webviewPDF.clearSslPreferences();

Body:
this is the answer to your question:

WebView webview = FindViewById<WebView>(Resource.Id.webView1);
        urlPdf = ("pdf url example ");
        WebSettings settings = webview.Settings;
        settings.JavaScriptEnabled = true;
        webview.LoadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + urlPdf);


问:
How to replace any text between html tags
i have text between html tags. For example:

```<code><td>vip</td>
</code>```

I will have any text between tags
How can i cut any text from these tags and put any text between these tags.
I need to do it via bash/shell.
How can i do this ?
First of all, i tried to get this text, but without success
sed -n "//,/<\/td>/p" test.txt. But in a result i have
vip	. but according to documentation, i should get only vip

答:
You can use this to get the value vip

```<code>sed -e 's,.*<td>\([^<]*\)</td>.*,\1,g'
</code>```

Body:
i have text between html tags. For example:

vip

I will have any text between tags
How can i cut any text from these tags and put any text between these tags.
I need to do it via bash/shell.
How can i do this ?
First of all, i tried to get this text, but without success
sed -n "//,/<\/td>/p" test.txt. But in a result i have
vip	. but according to documentation, i should get only vip

Body:
You can use this to get the value vip

sed -e 's,.*<td>\([^<]*\)</td>.*,\1,g'


问:
XML String parsing in Android?
I use the following code to parse the XML file.

```<code>DocumentBuilderFactory factory;
DocumentBuilder builder;
InputStream is;
Document dom;
try {
    factory = DocumentBuilderFactory.newInstance();
    is = new FileInputStream(strFileName);
    builder = factory.newDocumentBuilder();

    dom = builder.parse(is);
}
catch(Exception e){}
</code>```

Instead of XML file is there any way to parse the String.

```<code>String xml="<?xml version="1.0"?> <name> Application</name> <demo> Demo </demo> </xml>";
</code>```

答:
You can convert your string to an InputStream using ByteArrayInputStream:</p>

```<code>String xml ="valid xml here";
InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));

dom = builder.parse(is);
</code>```

Title: XML String parsing in Android?

Body:
I use the following code to parse the XML file.

DocumentBuilderFactory factory;
DocumentBuilder builder;
InputStream is;
Document dom;
try {
    factory = DocumentBuilderFactory.newInstance();
    is = new FileInputStream(strFileName);
    builder = factory.newDocumentBuilder();

    dom = builder.parse(is);
}
catch(Exception e){}

Instead of XML file is there any way to parse the String.

String xml="<?xml version="1.0"?> <name> Application</name> <demo> Demo </demo> </xml>";

Body:
You can convert your string to an InputStream using ByteArrayInputStream:

String xml ="valid xml here";
InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));

dom = builder.parse(is);


问:
Optimizing multiple output variables of a function in Python
I'm currently working on an algorithm that determines the cost of a wind turbine support structure. The algorithm I'm writing needs to optimize the weight of an initial input support structure so that the stress levels will not exceed but be near to the failure criteria of the properties of the materials used. Another requirement is that the natural frequency of the structure needs to be bounded between 2 values. To optimize the structure 4 variables can be altered.

Can I use a function from the Scipy.Optimize library that optimizes the weight of this structure using several design parameters, but keeps into account the natural frequency and the maximum stress value in the support structure?

The function I'm optimizing looks like this:

```<code>def func(self, x):
    self.properties.D_mp = x[0]                    # Set a new diameter for the monopile
    self.properties.Dtrat_tower = x[1]             # Set a new thickness ratio for the tower
    self.properties.Dtrat_tp = x[2]                # Set a new thickness ratio for the transition piece
    self.properties.Dtrat_mud = x[3]               # Set a new thickness ratio for the mudline region of the monopile

    self.UpdateAll()                               # Update the support structure based on the changes in variables above

    eig = self.GetEigenFrequency()                 # Get the natural frequency
    maxUtil = self.GetMaximumUtilisationFactor()   # Get the maximum utilisation ratio on the structure (more than 1 means stress is higher than maximum allowed)

    # Natural frequency of 0.25 and utilisation ratio of 1 are ideal
    # Create some penalty...
    penalty = (100000 * abs((eig - 0.25)))
    penalty +=  (100000 * abs(maxUtil - 1))

    return self.GetTotalMass() + penalty
</code>```

Thanks in advance!

答:
You can use the leastsq function of spicy.optimize.

In my case it was to fit an exponential function with two variables :

```<code>def func_exp(p, x, z):
# exponential function with multiple parameters
    a, b, c, d, t, t2 = p[0], p[1], p[2], p[3], p[4], p[5]
    return a*np.exp(b + pow(x,c)*t + pow(z,d)*t2)
</code>```

But to use the leastsq function you need to create an error function, this this one you'll optimize.

```<code>def err(p, x,z, y):
# error function compare the previous to the estimate to
    return func_exp(p, x,z) - y
# minimise the residuals
</code>```

To use it :

```<code>p0=[1e4,-1e-3,1,1,-1e-2, -1e-6]
# First parameters
pfit_fin, pcov, infodict, errmsg, success = leastsq(err, p0, args=(X,Y,Z), full_output=1, epsfcn=0.000001)
</code>```

So that's return the best parameters, to generate the results :

```<code>Y_2= func_exp(pfit_fin, X,Y)
</code>```

I hope that will help you,

Chris.

Body:
I'm currently working on an algorithm that determines the cost of a wind turbine support structure. The algorithm I'm writing needs to optimize the weight of an initial input support structure so that the stress levels will not exceed but be near to the failure criteria of the properties of the materials used. Another requirement is that the natural frequency of the structure needs to be bounded between 2 values. To optimize the structure 4 variables can be altered.

Can I use a function from the Scipy.Optimize library that optimizes the weight of this structure using several design parameters, but keeps into account the natural frequency and the maximum stress value in the support structure?

The function I'm optimizing looks like this:

def func(self, x):
    self.properties.D_mp = x[0]                    # Set a new diameter for the monopile
    self.properties.Dtrat_tower = x[1]             # Set a new thickness ratio for the tower
    self.properties.Dtrat_tp = x[2]                # Set a new thickness ratio for the transition piece
    self.properties.Dtrat_mud = x[3]               # Set a new thickness ratio for the mudline region of the monopile

    self.UpdateAll()                               # Update the support structure based on the changes in variables above

    eig = self.GetEigenFrequency()                 # Get the natural frequency
    maxUtil = self.GetMaximumUtilisationFactor()   # Get the maximum utilisation ratio on the structure (more than 1 means stress is higher than maximum allowed)

    # Natural frequency of 0.25 and utilisation ratio of 1 are ideal
    # Create some penalty...
    penalty = (100000 * abs((eig - 0.25)))
    penalty +=  (100000 * abs(maxUtil - 1))

    return self.GetTotalMass() + penalty

Thanks in advance!

Body:
You can use the leastsq function of spicy.optimize.

In my case it was to fit an exponential function with two variables :

def func_exp(p, x, z):
# exponential function with multiple parameters
    a, b, c, d, t, t2 = p[0], p[1], p[2], p[3], p[4], p[5]
    return a*np.exp(b + pow(x,c)*t + pow(z,d)*t2)

But to use the leastsq function you need to create an error function, this this one you'll optimize.

def err(p, x,z, y):
# error function compare the previous to the estimate to
    return func_exp(p, x,z) - y
# minimise the residuals

To use it :

p0=[1e4,-1e-3,1,1,-1e-2, -1e-6]
# First parameters
pfit_fin, pcov, infodict, errmsg, success = leastsq(err, p0, args=(X,Y,Z), full_output=1, epsfcn=0.000001)

So that's return the best parameters, to generate the results :

Y_2= func_exp(pfit_fin, X,Y)

I hope that will help you,

Chris.


问:
Unable to get result from stdout with subprocess
I need to get the result being displayed in the console after issuing a command.

e.g.: H:/path/to/openssl.exe x509 -in H:/path/to/cert.pem -noout -subject

This command produces values of an encrypted certificate when placed in an opened cmd.exe but I am unable to get the same result as a returned variable using the subprocess module.

So far I have attempted (where cmd is the e.g. above):

```<code># checking if output is going to stderr
out = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
# attempt with Popen
out = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()[0]
# attempt with Popen not using communicate()
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
out = p.stdout.read()
</code>```

All the print (out) values are b''.

I have even broken the cmd into multiple args for both check_output() and Popen() such that it would look like: ["H:/path/to/openssl.exe", "x509 -in H:/path/to/cert.pem -noout -subject"].

I do have an alternative method to achieve the result, but that requires running a .bat file that contains the command: start cmd /k "... > H:/path/to/temp.txt" where the ... is the command in question here. This redirects the .exe output to a temp file (for security purposes) which I delete after reading contents into a variable.

Supporting information:

If the first part of the command is run (the .exe) it opens custom console for that program. The remainder of the command is executed in that console and then that console closes. However if the whole command series is used in a cmd.exe console, the output is displayed in that console. Hence why the use of " " in my alternate method of a .bat as it issues it to the open console as a whole command.

Use of subprocess.Popen(["cmd.exe"]) opens a console at C:\Python36> and I can issue the command in question and get the exact result I want. I cannot seem to grab it pythonically though. However, subprocess.Popen(["cmd.exe", "H:/path/to/openssl.exe"]) does not execute the second command; opens a console but does not start the .exe console.

Update:

I was able to get a result, but I don't like how I got there. Is there a shorter way to do the following:

```<code>p = subprocess.Popen("H:/path/to/openssl.exe", stdin=PIPE, stdout=PIPE)
# b for byte-type requirement
p.stdin.write(b"x509 -in H:/path/to/cert.pem -noout -subject")
p.stdin.close()
out = p.stdout.read()
</code>```

I can also produce the result with:

p = os.popen("start cmd /k H:/path/to/openssl.exe -in H:/path/to/cert.pem -noout -subject")

Tried to add .read() to the above, but prints a blank line

答:
i am not used to use python on windows, but try the following. Don't use shell=True, instead try with this cmd:

```<code>cmd = ["H:/path/to/openssl.exe", "x509", "-in", "H:/path/to/cert.pem", "-noout", "-subject"]
</code>```

Body:
I need to get the result being displayed in the console after issuing a command.

e.g.: H:/path/to/openssl.exe x509 -in H:/path/to/cert.pem -noout -subject

This command produces values of an encrypted certificate when placed in an opened cmd.exe but I am unable to get the same result as a returned variable using the subprocess module.

So far I have attempted (where cmd is the e.g. above):

# checking if output is going to stderr
out = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
# attempt with Popen
out = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()[0]
# attempt with Popen not using communicate()
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
out = p.stdout.read()

All the print (out) values are b''.

I have even broken the cmd into multiple args for both check_output() and Popen() such that it would look like: ["H:/path/to/openssl.exe", "x509 -in H:/path/to/cert.pem -noout -subject"].

I do have an alternative method to achieve the result, but that requires running a .bat file that contains the command: start cmd /k "... > H:/path/to/temp.txt" where the ... is the command in question here. This redirects the .exe output to a temp file (for security purposes) which I delete after reading contents into a variable.

Supporting information:

If the first part of the command is run (the .exe) it opens custom console for that program. The remainder of the command is executed in that console and then that console closes. However if the whole command series is used in a cmd.exe console, the output is displayed in that console. Hence why the use of " " in my alternate method of a .bat as it issues it to the open console as a whole command.

Use of subprocess.Popen(["cmd.exe"]) opens a console at C:\Python36> and I can issue the command in question and get the exact result I want. I cannot seem to grab it pythonically though. However, subprocess.Popen(["cmd.exe", "H:/path/to/openssl.exe"]) does not execute the second command; opens a console but does not start the .exe console.

Update:

I was able to get a result, but I don't like how I got there. Is there a shorter way to do the following:

p = subprocess.Popen("H:/path/to/openssl.exe", stdin=PIPE, stdout=PIPE)
# b for byte-type requirement
p.stdin.write(b"x509 -in H:/path/to/cert.pem -noout -subject")
p.stdin.close()
out = p.stdout.read()

I can also produce the result with:

p = os.popen("start cmd /k H:/path/to/openssl.exe -in H:/path/to/cert.pem -noout -subject")

Tried to add .read() to the above, but prints a blank line

Body:
i am not used to use python on windows, but try the following. Don't use shell=True, instead try with this cmd:

cmd = ["H:/path/to/openssl.exe", "x509", "-in", "H:/path/to/cert.pem", "-noout", "-subject"]


问:
Slow performance of Kendo Grid in IE11
I've been using latest Kendo grid for ASP.NET MVC.

Data table specs are like this,

columns --> 25 to 35.

rows --> anywhere between 1500 to 5000.

client side paging --> 20 rows

Issue is, when I'm doing the scrolling, IE 11 takes upto 1s to display data depending on screen resolution and grid content height. Which causes the UI glitch.

When I ran IE UI Responsiveness from Dev Tools, I got the below results.

I get that whenever user does scrolling, browsers have to render the rows and it takes a bit time. But IE 11 takes it to a whole new level. The moment it has to process 3-4 more rows, it starts acting jumpy and glitchy.

I did the testing in Chrome (& opera), Firefox. In which performace was very decent.

I tried to refractor CSS to reduce styling, but there's very little bit change I could afford.

Please let me know what is the next step? Should I keep calm and blame IE?

答:
There's an issue with a file named angular-material.css which causes a slow scroll like you describe. I've seen several places, like this one, that state removing the file or several lines in it solved the problem.

Are you using angular in your project? If you do, see if you have this file and try to remove it.

Title: Slow performance of Kendo Grid in IE11


问:
able to select a button in python based gui when a process is running
i am new to python,i have been tying to run a executable file using python tkinter, by pressing a button the executable will run using os.system and stopping it by pressing another button i have written a c code to stop the executable using kill command and running the executable in the python gui ,but once the process runs am unable to click the other button.how to stop it,i have pasted my code below, kindly help me to solve this</p>

```<code>from Tkinter import *
import os
import sys

def init():
    os.system('./a.out')

def lena():
    os.system('./test')

WINDOW_W = 300
WINDOW_H = 80

def createDisplay():
 global tk
 global btn
 # create the tk window - within which
 # everything else will be built.
 tk = Tk()
  #Add a canvas area ready for drawing on
 canvas = Canvas(tk, width=WINDOW_W, height=WINDOW_H)
 canvas.pack()
 #Add an exit button
 btn = Button(tk, text="lena", command=lena)
 btn.pack()

 btn1 = Button(tk, text="optimist", command=lambda:os.system('./optimist'))
 btn1.pack()
 btn2 = Button(tk, text="text",command=init)
 btn2.pack()
 btn3 = Button(tk, text="exit", command=terminate)
 btn3.pack()
 # Start the tk main-loop (this updates the tk display)
 tk.mainloop()

def terminate():
 global tk
 tk.destroy()

def main():
 createDisplay()

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

答:
os.system is a blocking function, nothing else will happen in your program until the command you have called finishes.

Consider using subprocess instead

```<code>import subprocess
subprocess.Popen('./test')
</code>```

Using subprocess, the script you call will run in the background as a separate process.

Body:
i am new to python,i have been tying to run a executable file using python tkinter, by pressing a button the executable will run using os.system and stopping it by pressing another button i have written a c code to stop the executable using kill command and running the executable in the python gui ,but once the process runs am unable to click the other button.how to stop it,i have pasted my code below, kindly help me to solve this

from Tkinter import *
import os
import sys

def init():
    os.system('./a.out')

def lena():
    os.system('./test')

WINDOW_W = 300
WINDOW_H = 80

def createDisplay():
 global tk
 global btn
 # create the tk window - within which
 # everything else will be built.
 tk = Tk()
  #Add a canvas area ready for drawing on
 canvas = Canvas(tk, width=WINDOW_W, height=WINDOW_H)
 canvas.pack()
 #Add an exit button
 btn = Button(tk, text="lena", command=lena)
 btn.pack()

 btn1 = Button(tk, text="optimist", command=lambda:os.system('./optimist'))
 btn1.pack()
 btn2 = Button(tk, text="text",command=init)
 btn2.pack()
 btn3 = Button(tk, text="exit", command=terminate)
 btn3.pack()
 # Start the tk main-loop (this updates the tk display)
 tk.mainloop()

def terminate():
 global tk
 tk.destroy()

def main():
 createDisplay()

if __name__ == '__main__':
 main()

Body:
os.system is a blocking function, nothing else will happen in your program until the command you have called finishes.

Consider using subprocess instead

import subprocess
subprocess.Popen('./test')

Using subprocess, the script you call will run in the background as a separate process.


问:
Angular2 Firebase phone number authentication
Can anyone tell me the complete code for Angular2 Firebase phone number authentication? I am not getting it from Google. </p>

答:
Please check the official documentation of Authentication with Firebase with a Phone Number here.

And if you are using the AngularFire2 library, here is David East's answer on this issue:

We decided to not wrap auth methods and instead provide a way to inject Firebase Auth instead, once we upgrade to 4.0 they will be available for injection.


问:
Place some nodes of the same network on GPU and others on CPU?
When defining a network in Caffe/Caffe2, can you place some of the nodes on the CPU and others on GPU? If so, how? </p>

<p>(If your answer pertains a specific version of Caffe, please specify which)</p>

答: No, it's not possible. If you look at the solver.prototxt file you'll notice that you may specify the mode as either CPU or GPU, but not both. The reason for keeping this kind of execution structure is to maintain efficiency. The data generated by each layer of a CNN maybe in megabytes. If you keep part of the network on the CPU and part of it on the GPU, you'll need to transfer huge chunks of data to and fro between the devices. This will add a huge overhead which will completely undo the leverage given by the GPU. So, it is more efficient to train the entire network on the CPU rather than the CPU-GPU combination. Also note that the GPU is connected with the CPU via a PCIe interface which is significantly slower than the internal CPU bus. So data transfer between the devices is really expensive. That's one of the reasons why larger batch sizes are preferred for training CNNs as a bunch of images can sent to the GPU at once, avoiding repetitive memory reads and writes.

Body:
When defining a network in Caffe/Caffe2, can you place some of the nodes on the CPU and others on GPU? If so, how?

(If your answer pertains a specific version of Caffe, please specify which)


问:
Can SSIS create output spreadsheet based on value of field in Input
A department in my company gets a report every day as a a spreadsheet of invalid debit cards. It can contain 0 to hundreds of different clients. The client ID is a column on the spreadsheet. They have to take the records for Client A, make a spreadsheet called, say Client_A_20170602.xlsx and email that to client A. Then they have to do the same for client B. If there are just a few clients then it is not a big deal to do it manually, but today they had 115 different clients. They want to know if I can write an SSIS package that will automate this process.

I could bring the spreadsheet into an SQL table, do a SELECT DISTINCT on the Client ID, put the results into a temp table, go through each client on the temp table, get their records, and put them into a date stamped table. I could then (back in SSIS) use a FOR EACH loop to look for files that contain the date stamp and write them out to spreadsheets.

Can this work? Can somebody suggest a better solution?

Thanks,

Dick

答: Another solution would be an SSRS Report with each client getting a subscription that emails them their data.</p>


问:
Getting an error when trying to retrieve the image stored in the database in my Ruby On Rails Application
I'm developing an online store application with rails.And in that i have included a paperclip gem to store images of the items.The image gets successfully stored to the database but when i'm trying to retrieve the image with it's show view i am getting an error saying that

```<code>> undefined method `image?' for #<Item:0x007f805b7a9d50>
Extracted source (around line #19):

            <div>
                <% if @item.image? %>
                    <% image_tag @item.image.url%>
                    <br>
                <%end%>
            </div><br>
</code>```

This is my code in the view to submit the image

```<code>       `<div>
            <%=f.label :image %>
            <%=f.file_field :image %><br><br>
        </div>
        <div>`
</code>```

This is the migration file for the image storing on the table

```<code>`class AddImageToItems < ActiveRecord::Migration[5.0]
  def self.up
    add_column :items, :image_file_name, :string
    add_column :items, :image_content_type, :string
    add_column :items, :image_file_size, :integer
    add_column :items, :image_updated_at, :datetime
  end

  def self.down
    remove_column :items, :image_file_name
    remove_column :items, :image_content_type
    remove_column :items, :image_file_size
    remove_column :items, :image_updated_at
  end
end
`
</code>```

This is the code for the show view

```<code>  `<div class="well">
        <h3> Item  :  <%= @item.title %>  </h3>
    </div>
    <div>
        <i>Quantity : </i><%= @item.qty %>
    </div>
    <div>
        <i>Price  : RS </i><%= @item.price %>
    </div><br>
    <div>
        <% if @item.image? %>
            <% image_tag @item.image.url%>
            <br>
        <%end%>
   </div>`
</code>```

This is my show method on the items controller

```<code>def show
    @item =Item.find(params[:id])
end
</code>```

答:
You are trying to use a method image? which you have not defined for your @item.

Try the following code

```<code><% if @item.image.url %>
  <%= image_tag @item.image.url %>
  <br>
<% end %>
</code>```

Body:
I'm developing an online store application with rails.And in that i have included a paperclip gem to store images of the items.The image gets successfully stored to the database but when i'm trying to retrieve the image with it's show view i am getting an error saying that

> undefined method `image?' for #<Item:0x007f805b7a9d50>
Extracted source (around line #19):

                <% if @item.image? %>
                    <% image_tag @item.image.url%>

                <%end%>

This is my code in the view to submit the image

       `

            <%=f.label :image %>
            <%=f.file_field :image %>

`

This is the migration file for the image storing on the table

`class AddImageToItems < ActiveRecord::Migration[5.0]
  def self.up
    add_column :items, :image_file_name, :string
    add_column :items, :image_content_type, :string
    add_column :items, :image_file_size, :integer
    add_column :items, :image_updated_at, :datetime
  end

  def self.down
    remove_column :items, :image_file_name
    remove_column :items, :image_content_type
    remove_column :items, :image_file_size
    remove_column :items, :image_updated_at
  end
end
`

This is the code for the show view

  `

 Item  :  <%= @item.title %>

        Quantity : <%= @item.qty %>

        Price  : RS <%= @item.price %>

        <% if @item.image? %>
            <% image_tag @item.image.url%>

        <%end%>

`

This is my show method on the items controller

def show
    @item =Item.find(params[:id])
end

Body:
You are trying to use a method image? which you have not defined for your @item.

Try the following code

<% if @item.image.url %>
  <%= image_tag @item.image.url %>
  <br>
<% end %>


问:
Rails API - Voting app, associations
So, I am developing a small voting app. I am using Rails, but as JSON API-only.
I want to create voters table for every voting - so that every voting has the same voters (this is app for local community in which voters will remain mostly 'static'), but it would be nice to have an 'presence list' for every voting.

I have created controllers - scores and voters. Now:

How would you do it to include always the same list of voters, but with boolean presence? I have added voter_presence: boolean, as well added something like that to routes:

```<code>Rails.application.routes.draw do
  resources :scores do
    resources :voters
  end
end
</code>```

And it should do the trick with associations - but I still have a  "every score the same list" problem.

答:
```<code>class Score < ActiveRecord::Base
  has_and_belongs_to_many :voters
  attr_accessor :excluded_voter_ids
  after_create :add_voters

  ... other code ...

  def add_voters
    Voter.where().not(id: excluded_voter_ids).find_each do |voter|
      self.voters << voter
    end
  end
end
</code>```

<p>You will also need to follow the instructions here for setting up the HABTM association </p>

Title: Rails API - Voting app, associations

Body:
So, I am developing a small voting app. I am using Rails, but as JSON API-only.
I want to create voters table for every voting - so that every voting has the same voters (this is app for local community in which voters will remain mostly 'static'), but it would be nice to have an 'presence list' for every voting.

I have created controllers - scores and voters. Now:

How would you do it to include always the same list of voters, but with boolean presence? I have added voter_presence: boolean, as well added something like that to routes:

Rails.application.routes.draw do
  resources :scores do
    resources :voters
  end
end

And it should do the trick with associations - but I still have a  "every score the same list" problem.

Body:
class Score < ActiveRecord::Base
  has_and_belongs_to_many :voters
  attr_accessor :excluded_voter_ids
  after_create :add_voters

  ... other code ...

  def add_voters
    Voter.where().not(id: excluded_voter_ids).find_each do |voter|
      self.voters << voter
    end
  end
end

You will also need to follow the instructions here for setting up the HABTM association


问:
How to open a menu with Long hold or Right click in Angular2
I am playing around with angular 2. I want to open a menu with 2,3 options on a mobile as well as on a pc.

What i need is, when i long hold or right click above the div with class container , i want a menu to be opened like this -

HTML code as follows:

```<code><div class="container"   id="main-wrapper" >
  <section class="intro">
  <div class="content" >
    <h1 [contentEditable]="contentEditable" >You can create full screen sections without javascript.</h1>
    <p [contentEditable]="contentEditable">The height is set to 90vh, that means 90% height.</p>
 </div>
</section>
</div>
</code>```

explore.ts

```<code>rightClickMenu(){
// What should i write in this function to get a menu as explained.
}
</code>```

and where should I call this menu, please guide.

答:
calculate the time between mouse up event and mouse down event if the time is > `time-specified then show the menu.

in the component

```<code>timeInterval:int =0
var k;
doMouseDown()
{
   timeInterval=0;
   k=setInterval(function(){
   timeInterval++;
},1000);
}

doMouseUp()
{
  clearInterval(k);
  if(timeInterval >15) // replace 15 with your time for long hold)
  {
   //open menu
  }
  else
  {
   //show for short hold
  }
}
</code>```

Body:
I am playing around with angular 2. I want to open a menu with 2,3 options on a mobile as well as on a pc.

What i need is, when i long hold or right click above the div with class container , i want a menu to be opened like this -

HTML code as follows:

You can create full screen sections without javascript.

The height is set to 90vh, that means 90% height.

explore.ts

rightClickMenu(){
// What should i write in this function to get a menu as explained.
}

and where should I call this menu, please guide.

Body:
calculate the time between mouse up event and mouse down event if the time is > `time-specified then show the menu.

in the component

timeInterval:int =0
var k;
doMouseDown()
{
   timeInterval=0;
   k=setInterval(function(){
   timeInterval++;
},1000);
}

doMouseUp()
{
  clearInterval(k);
  if(timeInterval >15) // replace 15 with your time for long hold)
  {
   //open menu
  }
  else
  {
   //show for short hold
  }
}


问:
type safety - all_of/ any_of/ none_of for std::tuple
So I started to implement some algorithms that mimic the behaviour of the STL algorithms but with a heterogeneous container a.k.a std::tuple.

```<code>template<typename UnaryPredicate, typename Tuple>
bool all_of(UnaryPredicate&& p, Tuple&& t) noexcept
{
    return std::apply([&p](auto&& ...xs){ return (p(std::forward<decltype(xs)>(xs)) && ...); }, std::forward<Tuple>(t));
}

template<typename UnaryPredicate, typename Tuple>
bool any_of(UnaryPredicate&& p, Tuple&& t) noexcept
{
    return std::apply([&p](auto&& ...xs){ return (p(std::forward<decltype(xs)>(xs)) || ...); }, std::forward<Tuple>(t));
}

template<typename UnaryPredicate, typename Tuple>
bool none_of(UnaryPredicate&& p, Tuple&& t) noexcept
{
    return std::apply([&p](auto&& ...xs){ return !(p(std::forward<decltype(xs)>(xs)) || ...); }, std::forward<Tuple>(t));
}
</code>```

All of these work fine if you use a UnaryPredicate that returns a boolean. But what if it doesn't? How can ensure that UnaryPredicate returns a boolean when it's invoked with each of the elements of the tuple? Also how can I check if UnaryPredicate actually doesn't throw any exceptions.

I know there are type traits like 'is_nothrow_invocable' and 'invoke_result', but all of these require the types of the elements the tuple contains. Do I really have to use the "algorithm_impl" pattern?

```<code>namespace impl
{
    template<typename UnaryPredicate, typename Tuple, auto ...Is>
    bool all_of_impl(UnaryPredicate&& p, Tuple&& t, std::index_sequence<Is...>) noexcept
    {
        return std::apply([&p](auto&& ...xs){ return (p(std::forward<decltype(xs)>(xs)) && ...); }, std::forward<Tuple>(t));
    }
}

template<typename UnaryPredicate, typename Tuple>
bool all_of(UnaryPredicate&& p, Tuple&& t) noexcept
{
    return impl::all_of_impl(std::forward<UnaryPredicate>(p), std::forward<Tuple>(t), std::make_index_sequence<std::tuple_size_v<std::decay_t<Tuple>>>{});
}
</code>```

Now I can do something like this:

```<code>std::enable_if_t<std::conjunction_v<std::is_same<std::invoke_result_t<std::decay_t<UnaryPredicate>, std::tuple_element_t<Is, std::decay_t<Tuple>>>, bool>...>, bool>
</code>```

But is that really the way to go?

EDIT :

Okay as always I overcomplicated things. I think I found an acceptable solution:

```<code>template<typename UnaryPredicate, typename Tuple>
struct helper;

template<typename UnaryPredicate, typename Tuple>
struct helper2;

template<typename UnaryPredicate, typename ...Ts>
struct helper<UnaryPredicate, std::tuple<Ts...>>
    : std::bool_constant<std::conjunction_v<std::is_same<bool, std::invoke_result_t<std::decay_t<UnaryPredicate>, std::decay_t<Ts>>>...>>
{};

template<typename UnaryPredicate, typename ...Ts>
struct helper2<UnaryPredicate, std::tuple<Ts...>>
    : std::bool_constant<std::conjunction_v<std::is_nothrow_invocable<std::decay_t<UnaryPredicate>, std::decay_t<Ts>>...>>
{};

template<typename UnaryPredicate, typename Tuple>
inline constexpr auto helper_v{ helper<UnaryPredicate, Tuple>::value };

template<typename UnaryPredicate, typename Tuple>
inline constexpr auto helper2_v{ helper2<UnaryPredicate, Tuple>::value };

template<typename UnaryPredicate, typename Tuple>
std::enable_if_t<helper_v<UnaryPredicate, Tuple>, bool> all_of(UnaryPredicate&& p, Tuple&& t) noexcept(helper2_v<UnaryPredicate, Tuple>)
{
    return std::apply([&p](auto&& ...xs){ return (p(std::forward<decltype(xs)>(xs)) && ...); }, std::forward<Tuple>(t));
}

template<typename UnaryPredicate, typename Tuple>
std::enable_if_t<helper_v<UnaryPredicate, Tuple>, bool> any_of(UnaryPredicate&& p, Tuple&& t) noexcept(helper2_v<UnaryPredicate, Tuple>)
{
    return std::apply([&p](auto&& ...xs){ return (p(std::forward<decltype(xs)>(xs)) || ...); }, std::forward<Tuple>(t));
}

template<typename UnaryPredicate, typename Tuple>
std::enable_if_t<helper_v<UnaryPredicate, Tuple>, bool> none_of(UnaryPredicate&& p, Tuple&& t) noexcept(helper2_v<UnaryPredicate, Tuple>)
{
    return std::apply([&p](auto&& ...xs){ return !(p(std::forward<decltype(xs)>(xs)) || ...); }, std::forward<Tuple>(t));
}
</code>```

答:
I found an even better solution than my previous edit :)</p>

```<code>#include <functional>
#include <iostream>
#include <tuple>
#include <type_traits>
#include <utility>

template<typename UnaryFunction, typename ...Types>
constexpr std::enable_if_t<std::conjunction_v<std::is_same<std::invoke_result_t<UnaryFunction, Types>, bool>...>, bool> AllOf(UnaryFunction&& p, std::tuple<Types...>&& t) noexcept(std::conjunction_v<std::is_nothrow_invocable<UnaryFunction, Types>...>)
{
    return std::apply([&](auto&& ...xs) constexpr { return (p(std::forward<decltype(xs)>(xs)) && ...); }, std::forward<std::tuple<Types...>>(t));
}

template<typename UnaryFunction, typename ...Types>
constexpr std::enable_if_t<std::conjunction_v<std::is_same<std::invoke_result_t<UnaryFunction, Types>, bool>...>, bool> AnyOf(UnaryFunction&& p, std::tuple<Types...>&& t) noexcept(std::conjunction_v<std::is_nothrow_invocable<UnaryFunction, Types>...>)
{
    return std::apply([&](auto&& ...xs) constexpr { return (p(std::forward<decltype(xs)>(xs)) || ...); }, std::forward<std::tuple<Types...>>(t));
}

template<typename UnaryFunction, typename ...Types>
constexpr std::enable_if_t<std::conjunction_v<std::is_same<std::invoke_result_t<UnaryFunction, Types>, bool>...>, bool> NoneOf(UnaryFunction&& p, std::tuple<Types...>&& t) noexcept(std::conjunction_v<std::is_nothrow_invocable<UnaryFunction, Types>...>)
{
    return std::apply([&](auto&& ...xs) constexpr { return !(p(std::forward<decltype(xs)>(xs)) || ...); }, std::forward<std::tuple<Types...>>(t));
}

int main()
{
    std::cout
        << std::boolalpha
        << AllOf([](auto&& x){ return x; }, std::make_tuple(true, true, true)) << "\n"
        << AnyOf([](auto&& x){ return x; }, std::make_tuple(false, false, true)) << "\n"
        << NoneOf([](auto&& x){ return x; }, std::make_tuple(false, false, false)) << "\n";
}
</code>```

Body:
So I started to implement some algorithms that mimic the behaviour of the STL algorithms but with a heterogeneous container a.k.a std::tuple.

template<typename UnaryPredicate, typename Tuple>
bool all_of(UnaryPredicate&& p, Tuple&& t) noexcept
{
    return std::apply([&p](auto&& ...xs){ return (p(std::forward<decltype(xs)>(xs)) && ...); }, std::forward<Tuple>(t));
}

template<typename UnaryPredicate, typename Tuple>
bool any_of(UnaryPredicate&& p, Tuple&& t) noexcept
{
    return std::apply([&p](auto&& ...xs){ return (p(std::forward<decltype(xs)>(xs)) || ...); }, std::forward<Tuple>(t));
}

template<typename UnaryPredicate, typename Tuple>
bool none_of(UnaryPredicate&& p, Tuple&& t) noexcept
{
    return std::apply([&p](auto&& ...xs){ return !(p(std::forward<decltype(xs)>(xs)) || ...); }, std::forward<Tuple>(t));
}

All of these work fine if you use a UnaryPredicate that returns a boolean. But what if it doesn't? How can ensure that UnaryPredicate returns a boolean when it's invoked with each of the elements of the tuple? Also how can I check if UnaryPredicate actually doesn't throw any exceptions.

I know there are type traits like 'is_nothrow_invocable' and 'invoke_result', but all of these require the types of the elements the tuple contains. Do I really have to use the "algorithm_impl" pattern?

namespace impl
{
    template<typename UnaryPredicate, typename Tuple, auto ...Is>
    bool all_of_impl(UnaryPredicate&& p, Tuple&& t, std::index_sequence<Is...>) noexcept
    {
        return std::apply([&p](auto&& ...xs){ return (p(std::forward<decltype(xs)>(xs)) && ...); }, std::forward<Tuple>(t));
    }
}

template<typename UnaryPredicate, typename Tuple>
bool all_of(UnaryPredicate&& p, Tuple&& t) noexcept
{
    return impl::all_of_impl(std::forward<UnaryPredicate>(p), std::forward<Tuple>(t), std::make_index_sequence<std::tuple_size_v<std::decay_t<Tuple>>>{});
}

Now I can do something like this:

std::enable_if_t<std::conjunction_v<std::is_same<std::invoke_result_t<std::decay_t<UnaryPredicate>, std::tuple_element_t<Is, std::decay_t<Tuple>>>, bool>...>, bool>

But is that really the way to go?

EDIT :

Okay as always I overcomplicated things. I think I found an acceptable solution:

template<typename UnaryPredicate, typename Tuple>
struct helper;

template<typename UnaryPredicate, typename Tuple>
struct helper2;

template<typename UnaryPredicate, typename ...Ts>
struct helper<UnaryPredicate, std::tuple<Ts...>>
    : std::bool_constant<std::conjunction_v<std::is_same<bool, std::invoke_result_t<std::decay_t<UnaryPredicate>, std::decay_t<Ts>>>...>>
{};

template<typename UnaryPredicate, typename ...Ts>
struct helper2<UnaryPredicate, std::tuple<Ts...>>
    : std::bool_constant<std::conjunction_v<std::is_nothrow_invocable<std::decay_t<UnaryPredicate>, std::decay_t<Ts>>...>>
{};

template<typename UnaryPredicate, typename Tuple>
inline constexpr auto helper_v{ helper<UnaryPredicate, Tuple>::value };

template<typename UnaryPredicate, typename Tuple>
inline constexpr auto helper2_v{ helper2<UnaryPredicate, Tuple>::value };

template<typename UnaryPredicate, typename Tuple>
std::enable_if_t<helper_v<UnaryPredicate, Tuple>, bool> all_of(UnaryPredicate&& p, Tuple&& t) noexcept(helper2_v<UnaryPredicate, Tuple>)
{
    return std::apply([&p](auto&& ...xs){ return (p(std::forward<decltype(xs)>(xs)) && ...); }, std::forward<Tuple>(t));
}

template<typename UnaryPredicate, typename Tuple>
std::enable_if_t<helper_v<UnaryPredicate, Tuple>, bool> any_of(UnaryPredicate&& p, Tuple&& t) noexcept(helper2_v<UnaryPredicate, Tuple>)
{
    return std::apply([&p](auto&& ...xs){ return (p(std::forward<decltype(xs)>(xs)) || ...); }, std::forward<Tuple>(t));
}

template<typename UnaryPredicate, typename Tuple>
std::enable_if_t<helper_v<UnaryPredicate, Tuple>, bool> none_of(UnaryPredicate&& p, Tuple&& t) noexcept(helper2_v<UnaryPredicate, Tuple>)
{
    return std::apply([&p](auto&& ...xs){ return !(p(std::forward<decltype(xs)>(xs)) || ...); }, std::forward<Tuple>(t));
}

Body:
I found an even better solution than my previous edit :)

#include <functional>
#include <iostream>
#include <tuple>
#include <type_traits>
#include <utility>

template<typename UnaryFunction, typename ...Types>
constexpr std::enable_if_t<std::conjunction_v<std::is_same<std::invoke_result_t<UnaryFunction, Types>, bool>...>, bool> AllOf(UnaryFunction&& p, std::tuple<Types...>&& t) noexcept(std::conjunction_v<std::is_nothrow_invocable<UnaryFunction, Types>...>)
{
    return std::apply([&](auto&& ...xs) constexpr { return (p(std::forward<decltype(xs)>(xs)) && ...); }, std::forward<std::tuple<Types...>>(t));
}

template<typename UnaryFunction, typename ...Types>
constexpr std::enable_if_t<std::conjunction_v<std::is_same<std::invoke_result_t<UnaryFunction, Types>, bool>...>, bool> AnyOf(UnaryFunction&& p, std::tuple<Types...>&& t) noexcept(std::conjunction_v<std::is_nothrow_invocable<UnaryFunction, Types>...>)
{
    return std::apply([&](auto&& ...xs) constexpr { return (p(std::forward<decltype(xs)>(xs)) || ...); }, std::forward<std::tuple<Types...>>(t));
}

template<typename UnaryFunction, typename ...Types>
constexpr std::enable_if_t<std::conjunction_v<std::is_same<std::invoke_result_t<UnaryFunction, Types>, bool>...>, bool> NoneOf(UnaryFunction&& p, std::tuple<Types...>&& t) noexcept(std::conjunction_v<std::is_nothrow_invocable<UnaryFunction, Types>...>)
{
    return std::apply([&](auto&& ...xs) constexpr { return !(p(std::forward<decltype(xs)>(xs)) || ...); }, std::forward<std::tuple<Types...>>(t));
}

int main()
{
    std::cout
        << std::boolalpha
        << AllOf([](auto&& x){ return x; }, std::make_tuple(true, true, true)) << "\n"
        << AnyOf([](auto&& x){ return x; }, std::make_tuple(false, false, true)) << "\n"
        << NoneOf([](auto&& x){ return x; }, std::make_tuple(false, false, false)) << "\n";
}


问:
C Function to Convert float to byte array
I'm trying to make a function that will accept a float variable and convert it into a byte array. I found a snippet of code that works, but would like to reuse it in a function if possible.

I'm also working with the Arduino environment, but I understand that it accepts most C language.

Currently works:

```<code>float_variable = 1.11;
byte bytes_array[4];

*((float *)bytes_array) = float_variable;
</code>```

What can I change here to make this function work?

```<code>float float_test = 1.11;
byte bytes[4];

// Calling the function
float2Bytes(&bytes,float_test);

// Function
void float2Bytes(byte* bytes_temp[4],float float_variable){
     *(float*)bytes_temp = float_variable;
}
</code>```

I'm not so familiar with pointers and such, but I read that (float) is using casting or something?

Any help would be greatly appreciated!

Cheers

*EDIT: SOLVED

Here's my final function that works in Arduino for anyone who finds this. There are more efficient solutions in the answers below, however I think this is okay to understand.

Function: converts input float variable to byte array

```<code>void float2Bytes(float val,byte* bytes_array){
  // Create union of shared memory space
  union {
    float float_variable;
    byte temp_array[4];
  } u;
  // Overite bytes of union with float variable
  u.float_variable = val;
  // Assign bytes to input array
  memcpy(bytes_array, u.temp_array, 4);
}
</code>```

Calling the function

```<code>float float_example = 1.11;
byte bytes[4];

float2Bytes(float_example,&bytes[0]);
</code>```

Thanks for everyone's help, I've learnt so much about pointers and referencing in the past 20 minutes, Cheers Stack Overflow!

答:
this seems to work also

```<code>#include <stddef.h>
#include <stdint.h>
#include <string.h>

float fval = 1.11;
size_t siz;
siz = sizeof(float);

uint8_t ures[siz];

memcpy (&ures, &fval, siz);
</code>```

then

```<code>float utof;
memcpy (&utof, &ures, siz);
</code>```

also for double

```<code>double dval = 1.11;
siz = sizeof(double);

uint8_t ures[siz];

memcpy (&ures, &dval, siz);
</code>```

then

```<code>double utod;
memcpy (&utod, &ures, siz);
</code>```

Body:
I'm trying to make a function that will accept a float variable and convert it into a byte array. I found a snippet of code that works, but would like to reuse it in a function if possible.

I'm also working with the Arduino environment, but I understand that it accepts most C language.

Currently works:

float_variable = 1.11;
byte bytes_array[4];

*((float *)bytes_array) = float_variable;

What can I change here to make this function work?

float float_test = 1.11;
byte bytes[4];

// Calling the function
float2Bytes(&bytes,float_test);

// Function
void float2Bytes(byte* bytes_temp[4],float float_variable){
     *(float*)bytes_temp = float_variable;
}

I'm not so familiar with pointers and such, but I read that (float) is using casting or something?

Any help would be greatly appreciated!

Cheers

*EDIT: SOLVED

Here's my final function that works in Arduino for anyone who finds this. There are more efficient solutions in the answers below, however I think this is okay to understand.

Function: converts input float variable to byte array

void float2Bytes(float val,byte* bytes_array){
  // Create union of shared memory space
  union {
    float float_variable;
    byte temp_array[4];
  } u;
  // Overite bytes of union with float variable
  u.float_variable = val;
  // Assign bytes to input array
  memcpy(bytes_array, u.temp_array, 4);
}

Calling the function

float float_example = 1.11;
byte bytes[4];

float2Bytes(float_example,&bytes[0]);

Thanks for everyone's help, I've learnt so much about pointers and referencing in the past 20 minutes, Cheers Stack Overflow!

Body:
this seems to work also

#include <stddef.h>
#include <stdint.h>
#include <string.h>

float fval = 1.11;
size_t siz;
siz = sizeof(float);

uint8_t ures[siz];

memcpy (&ures, &fval, siz);

then

float utof;
memcpy (&utof, &ures, siz);

also for double

double dval = 1.11;
siz = sizeof(double);

uint8_t ures[siz];

memcpy (&ures, &dval, siz);

then

double utod;
memcpy (&utod, &ures, siz);


问:
Initialize function by file contents at compile time
Is there a way to initialize a function

```<code>someText :: Text
</code>```

which value will be stored in a file available at compile time?

I thought I could use TH for that, but for now I just found

```<code>embedFile :: FilePath -> Q Exp
runQ :: Quasi m => Q a -> m a
</code>```

I can only unwrap Q into IO:

```<code>instance Quasi IO
instance Quasi Q
</code>```

I guess I need Identity instance of Quasi, but there is no one.

答:
# foo.txt
barbazblub
```

<pre class="lang-hs prettyprint-override"><code>module FileText where
import Language.Haskell.TH

fileText :: FilePath -> Q Exp
fileText fp = LitE . StringL <$> runIO (readFile fp)
</code>```

{-# LANGUAGE TemplateHaskell #-}
module Foo where

import FileText

main = putStrLn $(fileText "foo.txt")
```

<pre class="lang-none prettyprint-override"><code>$ runhaskell Foo.hs
barbazblub
</code>```

Body:
Is there a way to initialize a function

someText :: Text

which value will be stored in a file available at compile time?

I thought I could use TH for that, but for now I just found

embedFile :: FilePath -> Q Exp
runQ :: Quasi m => Q a -> m a

I can only unwrap Q into IO:

instance Quasi IO
instance Quasi Q

I guess I need Identity instance of Quasi, but there is no one.

Body:
# foo.txt
barbazblub

module FileText where
import Language.Haskell.TH

fileText :: FilePath -> Q Exp
fileText fp = LitE . StringL <$> runIO (readFile fp)

{-# LANGUAGE TemplateHaskell #-}
module Foo where

import FileText

main = putStrLn $(fileText "foo.txt")

$ runhaskell Foo.hs
barbazblub


问:
how to hide footer when i scroll the page and appears when i stop in ionic 2
I want to hide the footer when user scroll the page up or down. and it again appears when it stops scrolling in ionic2. I did not find the correct answer anywhere. My code is as below</p>

```<code><ion-content>
 <ion-list>
 <ion-item *ngFor=" let grocery of groceries">
    {{grocery}}
 </ion-item>
 </ion-list>
</ion-content>

<ion-footer>What is the time?</ion-footer>
</code>```

```<code>export class HomePage {
 groceries:any;
 products:any;
 demos:any;
 content:any
 constructor(public navCtrl: NavController) {
  this.groceries = [
           'Bread',
           'Milk',
           'Cheese',
           'Snacks',
           'Apples',
           'Bananas',
           'Peanut Butter',
           'Chocolate',
           'Avocada',
           'Vegemite',
           'Muffins',
           'Paper towels',
          ];
    }
 }
</code>```

答:
A footer by definition sticks at the bottom. and I do not think you can change it.I have encountered the same problem.I solved the problem like this.And the worked for me

sample

```<code><ion-content>
    <ion-list>
       <ion-item *ngFor=" let grocery of groceries">
           {{grocery}}
       </ion-item>
     </ion-list>

     <ion-row>
       <ion-col>
         What is the time?
       </ion-col>
     </ion-row>

</ion-content>
</code>```

Body:
I want to hide the footer when user scroll the page up or down. and it again appears when it stops scrolling in ionic2. I did not find the correct answer anywhere. My code is as below

<ion-content>
 <ion-list>
 <ion-item *ngFor=" let grocery of groceries">
    {{grocery}}
 </ion-item>
 </ion-list>
</ion-content>

<ion-footer>What is the time?</ion-footer>

export class HomePage {
 groceries:any;
 products:any;
 demos:any;
 content:any
 constructor(public navCtrl: NavController) {
  this.groceries = [
           'Bread',
           'Milk',
           'Cheese',
           'Snacks',
           'Apples',
           'Bananas',
           'Peanut Butter',
           'Chocolate',
           'Avocada',
           'Vegemite',
           'Muffins',
           'Paper towels',
          ];
    }
 }

Body:
A footer by definition sticks at the bottom. and I do not think you can change it.I have encountered the same problem.I solved the problem like this.And the worked for me

sample

<ion-content>
    <ion-list>
       <ion-item *ngFor=" let grocery of groceries">
           {{grocery}}
       </ion-item>
     </ion-list>

     <ion-row>
       <ion-col>
         What is the time?
       </ion-col>
     </ion-row>

</ion-content>