问:
android - save image into gallery
i have an app with a gallery of images and i want that the user can save it into his own gallery.
I've created an option menu with a single voice "save" to allow that but the problem is...how can i save the image into the gallery?

this is my code:

```<code>@Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle item selection
            switch (item.getItemId()) {
            case R.id.menuFinale:

                imgView.setDrawingCacheEnabled(true);
                Bitmap bitmap = imgView.getDrawingCache();
                File root = Environment.getExternalStorageDirectory();
                File file = new File(root.getAbsolutePath()+"/DCIM/Camera/img.jpg");
                try
                {
                    file.createNewFile();
                    FileOutputStream ostream = new FileOutputStream(file);
                    bitmap.compress(CompressFormat.JPEG, 100, ostream);
                    ostream.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

                return true;
            default:
                return super.onOptionsItemSelected(item);
            }
        }
</code>```

i'm not sure of this part of code:

```<code>File root = Environment.getExternalStorageDirectory();
                File file = new File(root.getAbsolutePath()+"/DCIM/Camera/img.jpg");
</code>```

is it correct to save into the gallery?
unfortunately the code doesn't work :(

答:
```<code> String filePath="/storage/emulated/0/DCIM"+app_name;
    File dir=new File(filePath);
    if(!dir.exists()){
        dir.mkdir();
    }
</code>```

This code is in onCreate method.This code is for creating a directory of app_name.
Now,this directory can be accessed using default file manager app in android.
Use this string filePath wherever required to set your destination folder.
I am sure this method works on Android 7 too because I tested on it.Hence,it can work on other versions of android too.

Title: android - save image into gallery

Body:
i have an app with a gallery of images and i want that the user can save it into his own gallery.
I've created an option menu with a single voice "save" to allow that but the problem is...how can i save the image into the gallery?

this is my code:

@Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle item selection
            switch (item.getItemId()) {
            case R.id.menuFinale:

                imgView.setDrawingCacheEnabled(true);
                Bitmap bitmap = imgView.getDrawingCache();
                File root = Environment.getExternalStorageDirectory();
                File file = new File(root.getAbsolutePath()+"/DCIM/Camera/img.jpg");
                try
                {
                    file.createNewFile();
                    FileOutputStream ostream = new FileOutputStream(file);
                    bitmap.compress(CompressFormat.JPEG, 100, ostream);
                    ostream.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

                return true;
            default:
                return super.onOptionsItemSelected(item);
            }
        }

i'm not sure of this part of code:

File root = Environment.getExternalStorageDirectory();
                File file = new File(root.getAbsolutePath()+"/DCIM/Camera/img.jpg");

is it correct to save into the gallery?
unfortunately the code doesn't work :(

Body:
 String filePath="/storage/emulated/0/DCIM"+app_name;
    File dir=new File(filePath);
    if(!dir.exists()){
        dir.mkdir();
    }

This code is in onCreate method.This code is for creating a directory of app_name.
Now,this directory can be accessed using default file manager app in android.
Use this string filePath wherever required to set your destination folder.
I am sure this method works on Android 7 too because I tested on it.Hence,it can work on other versions of android too.


来源: stackexchange

问:
Create SQL table with the data from another table
How do I create a table using data which is already present in another table (copy of table)?</p>

答:
if u want  exact schema of existing table to new table  and all values of existing table want to be inserted into your new table then execute below two queries :

```<code>create table new_table_name like Old_table_name;

select * into new_table_name from Old_table_name;
</code>```

LIKE works only for base tables, not for views.

If the original table is a TEMPORARY table, CREATE TABLE ... LIKE does not preserve TEMPORARY. To create a TEMPORARY destination table, use CREATE TEMPORARY TABLE ... LIKE.

 for more details click here

ContentLicense: CC BY-SA 2.5

Body:
if u want  exact schema of existing table to new table  and all values of existing table want to be inserted into your new table then execute below two queries :

create table new_table_name like Old_table_name;

select * into new_table_name from Old_table_name;

LIKE works only for base tables, not for views.

If the original table is a TEMPORARY table, CREATE TABLE ... LIKE does not preserve TEMPORARY. To create a TEMPORARY destination table, use CREATE TEMPORARY TABLE ... LIKE.

 for more details click here

ContentLicense: CC BY-SA 3.0


问:
Sorting clockwise polygon points in MATLAB
I have 2 vectors that are x and y coordinates of the 8 vertexes of a polygon

x=[5 5 7 7 9 9 5 7]

y=[8 6 6 8 6 8 10 10]

I wanna sort them (clockwise) to obtain the right vectors (to draw the polygon correctly)

x=[5 7 9 9 7 7 5 5]

y=[6 6 6 8 8 10 10 8]

答:
I tried the solutions by @ben-voight and @mclafee, but I think they are sorting the wrong way.

When using atan2 the angles are stated in the following way:

Matlab Atan2

The angle is positive for counter-clockwise angles (upper half-plane,
  y > 0), and negative for clockwise angles (lower half-plane, y < 0).

Wikipedia Atan2

This means that using ascending sort() of Numpy or Matlab will progress counterclockwise.

This can be verified using the Shoelace equation

Wikipedia Shoelace

Python Shoelace

So, adjusting the answers mentioned above to use descending sorting the correct solution in Matlab is

```<code>cx = mean(x);
cy = mean(y);
a = atan2(y - cy, x - cx);
[~, order] = sort(a, 'descend');
x = x(order);
y = y(order);
</code>```

The solution in numpy is

```<code>import numpy as np

def clockwise(points):
    x = points[0,:]
    y = points[1,:]
    cx = np.mean(x)
    cy = np.mean(y)
    a = np.arctan2(y - cy, x - cx)
    order = a.ravel().argsort()[::-1]
    x = x[order]
    y = y[order]
    return np.vstack([x,y])

pts = np.array([[7, 2, 2, 7],
                [5, 1, 5, 1]])

clockwise(pts)

pts = np.array([[1.0, 1.0],
                [-1.0, -1.0],
                [1.0, -1.0],
                [-1.0, 1.0]]).transpose()

clockwise(pts)
</code>```

Output:

```<code>[[7 2 2 7]
 [5 1 5 1]]

[[2 7 7 2]
 [5 5 1 1]]

[[ 1. -1.  1. -1.]
 [ 1. -1. -1.  1.]]

[[-1.  1.  1. -1.]
 [ 1.  1. -1. -1.]]
</code>```

Please notice the [::-1] used to invert arrays / lists.

Body:
I tried the solutions by @ben-voight and @mclafee, but I think they are sorting the wrong way.

When using atan2 the angles are stated in the following way:

Matlab Atan2

The angle is positive for counter-clockwise angles (upper half-plane,
  y > 0), and negative for clockwise angles (lower half-plane, y < 0).

Wikipedia Atan2

This means that using ascending sort() of Numpy or Matlab will progress counterclockwise.

This can be verified using the Shoelace equation

Wikipedia Shoelace

Python Shoelace

So, adjusting the answers mentioned above to use descending sorting the correct solution in Matlab is

cx = mean(x);
cy = mean(y);
a = atan2(y - cy, x - cx);
[~, order] = sort(a, 'descend');
x = x(order);
y = y(order);

The solution in numpy is

import numpy as np

def clockwise(points):
    x = points[0,:]
    y = points[1,:]
    cx = np.mean(x)
    cy = np.mean(y)
    a = np.arctan2(y - cy, x - cx)
    order = a.ravel().argsort()[::-1]
    x = x[order]
    y = y[order]
    return np.vstack([x,y])

pts = np.array([[7, 2, 2, 7],
                [5, 1, 5, 1]])

clockwise(pts)

pts = np.array([[1.0, 1.0],
                [-1.0, -1.0],
                [1.0, -1.0],
                [-1.0, 1.0]]).transpose()

clockwise(pts)

Output:

[[7 2 2 7]
 [5 1 5 1]]

[[2 7 7 2]
 [5 5 1 1]]

[[ 1. -1.  1. -1.]
 [ 1. -1. -1.  1.]]

[[-1.  1.  1. -1.]
 [ 1.  1. -1. -1.]]

Please notice the [::-1] used to invert arrays / lists.


问:
YAML/ANSIBLE -> save variable key and value to new variable
I'm working on a small ansible project for myself.

I have a main.yml in the defaults folder of my role.

Structure:

```<code>master-folder
 `- roles
     `- some_role
         |- tasks
         |   `- main.yml
         `- defaults
             `- main.yml
</code>```

Now...
In my some_variables.yml I have a dictionary with 2 vars.

```<code>parent_var:
  child_var: bob
  child_two_var: bobby
</code>```

in my main.yml task I want to get the key and value so (child_var: bob) and write it to another file.

What I need help with, is with getting the key and value from the main.yml in the defaults folder.

答:
Any variable defined in the defaults/*.yml is accessible from any task of the role with {{tree.to.variable}}.

So in your case, you can simply access the {{parent_var}}.

If you want to loop over keys and values, you can use the with_dict loop.

```<code>- lineinfile:
    line: "Value for '{{ item.key }}' is '{{ item.value }}'"
    dest: /tmp/test/file1
  with_dict: "{{ parent_var }}"
</code>```

If you need to loop in a template, there is the {% for %} in jinja2.

```<code>- copy:
    dest: /tmp/test/file
    content: |
      {% for k,v in parent_var.iteritems() %}
      Value for '{{ k }}' is '{{ v }}'
      {% endfor %}
</code>```

Body:
I'm working on a small ansible project for myself.

I have a main.yml in the defaults folder of my role.

Structure:

master-folder
 `- roles
     `- some_role
         |- tasks
         |   `- main.yml
         `- defaults
             `- main.yml

Now...
In my some_variables.yml I have a dictionary with 2 vars.

parent_var:
  child_var: bob
  child_two_var: bobby

in my main.yml task I want to get the key and value so (child_var: bob) and write it to another file.

What I need help with, is with getting the key and value from the main.yml in the defaults folder.

Body:
Any variable defined in the defaults/*.yml is accessible from any task of the role with {{tree.to.variable}}.

So in your case, you can simply access the {{parent_var}}.

If you want to loop over keys and values, you can use the with_dict loop.

- lineinfile:
    line: "Value for '{{ item.key }}' is '{{ item.value }}'"
    dest: /tmp/test/file1
  with_dict: "{{ parent_var }}"

If you need to loop in a template, there is the {% for %} in jinja2.

- copy:
    dest: /tmp/test/file
    content: |
      {% for k,v in parent_var.iteritems() %}
      Value for '{{ k }}' is '{{ v }}'
      {% endfor %}


问:
Load javascript state from rendered elements
Just wanted to know is there any javascript framework or lib that could load part of initial state from existing DOM elements.

Could reactjs or vuejs do things like this?

So to be perfectly clear i want to render page on server and mark some elements to be part of the model. The idea is to be able to render html with some important data so search engines could get it without js. Regular use would have exactly the same page but once js kicks in, I want it to get data from marked fields and add to current state.

i.e.

```<code><h1 x-marker="pageTitle">Page Title</h1>
<h2>{{ subtitle }}</h2>

var state = {
    subtitle: 'This is subtitle',
}
</code>```

search engine sees this:

```<code><h1>Page Title</h1>
<h2>{{subtitle}}</h2>
</code>```

regular user sees this:

```<code><h1>Page Title</h1>
<h2>This is subtitle</h2>
</code>```

BUT state should be

```<code>var state = {
    pageTitle: 'Page Title',
    subtitle: 'This is subtitle',
}
</code>```

So I want it to initially pull data from x-marker and after that maintain state of that element.

I could implement this kind of thing myself, just wanted to check does something like this already exists.

答:
Like the crazy nastyass honeybadger, vue doesn't care. You can do whatever you like (read the dom, substitute), so long as you do it before you instantiate the vue.

This fiddle shows your scenario working fine. The idea strikes me as a little louche, and certainly server-side rendering is the preferred way of dealing with this. Vue also has server-side rendering, but you could be forgiven for taking fright. If this gets you out of a hole, go for it. As they say, be good, and if you can't be good, be careful :-)

HTML

```<code><div id="crazyNastyass">
  <h1 id="pageTitle">Page Title</h1>
  <h2>{{state.subtitle}}</h2>
</div>
</code>```

JS

```<code>var state = {
    pageTitle:null,
    subtitle: 'This is subtitle'
}

var titleNode = document.getElementById('pageTitle');
state.pageTitle = titleNode.innerHTML;
titleNode.innerHTML = '{{state.pageTitle}}'

var vm = new Vue({
  el: '#crazyNastyass',
  data: {state:state}
})
</code>```

Body:
Just wanted to know is there any javascript framework or lib that could load part of initial state from existing DOM elements.

Could reactjs or vuejs do things like this?

So to be perfectly clear i want to render page on server and mark some elements to be part of the model. The idea is to be able to render html with some important data so search engines could get it without js. Regular use would have exactly the same page but once js kicks in, I want it to get data from marked fields and add to current state.

i.e.

Page Title

{{ subtitle }}

var state = {
    subtitle: 'This is subtitle',
}

search engine sees this:

Page Title

{{subtitle}}

regular user sees this:

Page Title

This is subtitle

BUT state should be

var state = {
    pageTitle: 'Page Title',
    subtitle: 'This is subtitle',
}

So I want it to initially pull data from x-marker and after that maintain state of that element.

I could implement this kind of thing myself, just wanted to check does something like this already exists.

Body:
Like the crazy nastyass honeybadger, vue doesn't care. You can do whatever you like (read the dom, substitute), so long as you do it before you instantiate the vue.

This fiddle shows your scenario working fine. The idea strikes me as a little louche, and certainly server-side rendering is the preferred way of dealing with this. Vue also has server-side rendering, but you could be forgiven for taking fright. If this gets you out of a hole, go for it. As they say, be good, and if you can't be good, be careful :-)

HTML

<div id="crazyNastyass">
  <h1 id="pageTitle">Page Title</h1>
  <h2>{{state.subtitle}}</h2>
</div>

JS

var state = {
    pageTitle:null,
    subtitle: 'This is subtitle'
}

var titleNode = document.getElementById('pageTitle');
state.pageTitle = titleNode.innerHTML;
titleNode.innerHTML = '{{state.pageTitle}}'

var vm = new Vue({
  el: '#crazyNastyass',
  data: {state:state}
})

ContentLicense: CC BY-SA 4.0


问:
Is there any restful api for postgresql?
Im trying to develop a web app using angularjs, restangular and postgresql, im using ubuntu and xampp for development. I found ArrestDB, a restful api for postgresql. In its documentation,

# Get all rows from the "customers" table where the "country" field matches "Australia" (LIKE)
GET http://api.example.com/customers/country/Australia/

https://github.com/alixaxel/ArrestDB

While in restangular documentation,

```<code>// Just ONE GET to /accounts/123/buildings/456
Restangular.one('accounts', 123).one('buildings', 456).get()
</code>```

https://github.com/mgonto/restangular

Do you guys know a free RESTful api for postgresql that works well with restangular?

ArrestDB interprets api/{Table}/{Field}/{....} while Restangular interprets api/{table}/{id}/{relations table}. I also tried api/{table}/{id}/{relations table} in ArrestDB but I get error 404.

I also found Postgrest in github but its in haskel, and i'm not familiar with haskel.

Thanks...

答: Postgrest seems to be a very viable choice. There is no knowledge of Haskell required to interact with it.</p>

Body:
Im trying to develop a web app using angularjs, restangular and postgresql, im using ubuntu and xampp for development. I found ArrestDB, a restful api for postgresql. In its documentation,

# Get all rows from the "customers" table where the "country" field matches "Australia" (LIKE)
GET http://api.example.com/customers/country/Australia/

https://github.com/alixaxel/ArrestDB

While in restangular documentation,

// Just ONE GET to /accounts/123/buildings/456
Restangular.one('accounts', 123).one('buildings', 456).get()

https://github.com/mgonto/restangular

Do you guys know a free RESTful api for postgresql that works well with restangular?

ArrestDB interprets api/{Table}/{Field}/{....} while Restangular interprets api/{table}/{id}/{relations table}. I also tried api/{table}/{id}/{relations table} in ArrestDB but I get error 404.

I also found Postgrest in github but its in haskel, and i'm not familiar with haskel.

Thanks...


问:
How to create a selector ID from a variable
In my HTML document, I want to have 9 checkboxes. When a checkbox is selected, I want a corresponding block of text to show. I'm trying to create a single function for this, that uses a parameter to select the corresponding box, but I've been unsuccesfull so far. I'm not experienced with HTML of jQuery at all, so I've got no idea what the problem is.

The code I currently have is as follows:

$(document).ready(function() {
    for ($i = 0; $i < 9; $i++) {
        $("input[name=checkbox" + $i + "]").click(function () {
            $('#box' + $i).toggle();
        });
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox1" value="alpha"> Checkbox 1 <br>
<input type="checkbox" name="checkbox2" value="beta"> Checkbox 2 <br>

<div id = "box1" style="display:none">Checkbox 1 is selected</div>
<div id = "box2" style="display:none">Checkbox 2 is selected</div></code>```

Can anyone please help me understand why the .toggle doesn't work correctly?

答:
```<code>$(document).ready(function() {
$("input[type='checkbox']").click(function(){
  alert("Checkbox "+$(this).index()+" is selected!");
 });
});
</code>```

It is not viable to use for loop like that. Use "this" selector to fetch current clicked checkbox with click function applied on all checkboxes.

UPDATE
You are applying for loop to 9 checkboxes which means you are adding similar code 9 times in your DOM which is not necessary.
If you don't want them to function for other checkboxes then apply a class to desired checkboxes and access by class. index(".checkbox_class") will give you the index of checkbox from checkboxes of class only. It will not count
 tags in between :)

```<code> $(document).ready(function() {
    $(".checkbox_class").click(function(){
      alert("Checkbox "+$(this).index(".checkbox_class")+" is selected!");
     });
    });
</code>```

Body:
In my HTML document, I want to have 9 checkboxes. When a checkbox is selected, I want a corresponding block of text to show. I'm trying to create a single function for this, that uses a parameter to select the corresponding box, but I've been unsuccesfull so far. I'm not experienced with HTML of jQuery at all, so I've got no idea what the problem is.

The code I currently have is as follows:

$(document).ready(function() {
    for ($i = 0; $i < 9; $i++) {
        $("input[name=checkbox" + $i + "]").click(function () {
            $('#box' + $i).toggle();
        });
    }
});

<input type="checkbox" name="checkbox1" value="alpha"> Checkbox 1

<input type="checkbox" name="checkbox2" value="beta"> Checkbox 2

Checkbox 1 is selected

Checkbox 2 is selected

Can anyone please help me understand why the .toggle doesn't work correctly?

Body:
$(document).ready(function() {
$("input[type='checkbox']").click(function(){
  alert("Checkbox "+$(this).index()+" is selected!");
 });
});

It is not viable to use for loop like that. Use "this" selector to fetch current clicked checkbox with click function applied on all checkboxes.

UPDATE
You are applying for loop to 9 checkboxes which means you are adding similar code 9 times in your DOM which is not necessary.
If you don't want them to function for other checkboxes then apply a class to desired checkboxes and access by class. index(".checkbox_class") will give you the index of checkbox from checkboxes of class only. It will not count <br> tags in between :)

 $(document).ready(function() {
    $(".checkbox_class").click(function(){
      alert("Checkbox "+$(this).index(".checkbox_class")+" is selected!");
     });
    });


问:
Google OAuth Redirect Uri Mismatch (authorization_code)
I am having a problem to understand the correct purpose of the redirect uri. Following the Google tutorial the javascript API allows me to get a authorizationCode without any redirect URI at all.

Then I send this code to my server and try to call the /token endpoint with this code. But then it will return a "redirect URI mismatch" which probably means that I need to define the same redirect_uri for this endpoint than I did with the javascript API. My only problem is that I dont specify any on my website.

Anyone knows how to correctly use them?

The flow I am trying to achieve is the following:
- Javascript website asks user for permission, getting the authorization code
- Code is sent to my server
- Server receives access/refresh token with this code and stores it safely

答:
"The flow I am trying to achieve is the following: - Javascript website asks user for permission, getting the authorization code - Code is sent to my server - Server receives access/refresh token with this code and stores it safely"

This can't be done. Google will not issue an Auth Code to a JavaScript client. To do so would be a major security problem. You will need to write server code to request offline access, which will get you the Auth Code and Refresh Token you're looking for.

Your app can still be a JavaScript SPA (if that's what you're aiming for), but you'll need to serve the app from an app-server (Java, PHP, etc) to handle the offline aspects of the auth.

As an alternative, you can do the whole thing in JavaScript, but you will not have a Refresh Token. If your app is solely JS, that shouldn't be a problem and will be transparent to the user. The gapi library deals with obtaining Access Tokens as needed.


问:
Why Jboss drool rules expiring before timing
I am facing issue rule is not considering time, date is working fine  </p>

```<code>rule "My Rule"
    no-loop true
    dialect "mvel"
    date-effective "05-JUN-2017 05:00" #after midnight
    date-expires "07-JUL-2017 05:00"   #before 23:59.59 on 6th July

when
   eval ( true )
then
    log.debug( "My rule executed" );
end
</code>```

答:
We can find in the code:

```<code>DEFAULT_FORMAT_MASK = "dd-MMM-yyyy";
</code>```

which is the default if the drools.dateformat property isn't set. Use a String value that is valid according to the specs of java.text.SimpleDateFormat to set the property.

Body:
I am facing issue rule is not considering time, date is working fine

rule "My Rule"
    no-loop true
    dialect "mvel"
    date-effective "05-JUN-2017 05:00" #after midnight
    date-expires "07-JUL-2017 05:00"   #before 23:59.59 on 6th July

when
   eval ( true )
then
    log.debug( "My rule executed" );
end

Body:
We can find in the code:

DEFAULT_FORMAT_MASK = "dd-MMM-yyyy";

which is the default if the drools.dateformat property isn't set. Use a String value that is valid according to the specs of java.text.SimpleDateFormat to set the property.


问:
How to track system's clock?
Situation:
I need to create a program that shows current date and updates some date(that is NOT CURRENT date,it is past date) according to current time(for example after 23:59,date refreshs). In other words,it is simple application,that shows date in the past and time.

What did I try?
I have found TextClock for this. It can show current time,but I cannot track over it.

So what can I do? I need to create my own clock class or use Timer and TimerTask? Do I need a Service?

答:
I think, if I understand you correctly, you're on the right path.  I wasn't familiar that there was even a TextClock view, but it looks pretty basic and will just work for displaying the current time.

Instead, maybe use a TimerTask to update the UI every second, or so, and set one TextView with the current time and another with your other time that's an offset of the current time (current = new Calendar(); current.add(Calendar.MINUTE, 1); )

You could use TimerTask, and that'd be pretty easy compared to rolling your own thread or using an AsyncTask.  Get the current time, set it to one text view, manipulate that time variable and set it to the other text view.

Title: How to track system's clock?


问:
How to request a random row in SQL?
How can I request a random row (or as close to truly random as possible) in pure SQL?</p>

答:
```<code>ORDER BY NEWID()
</code>```

takes 7.4 milliseconds

```<code>WHERE num_value >= RAND() * (SELECT MAX(num_value) FROM table)
</code>```

takes 0.0065 milliseconds!

I will definitely go with latter method.

OwnerDisplayName: sverrejoh

Title: How to request a random row in SQL?

LastEditorDisplayName: Yaakov Ellis

Body:
ORDER BY NEWID()

takes 7.4 milliseconds

WHERE num_value >= RAND() * (SELECT MAX(num_value) FROM table)

takes 0.0065 milliseconds!

I will definitely go with latter method.


问:
BeautifulSoup find_all() don't return XML
I'm using the BeautifulSoup find_all() to get all the xmlo tags.

But when I try to iterate the method return, its a String!

I want all "GarantidorFielDepositario"(I get this with find_all()) tags and I want read the values from all children tags(like "TipoGarantidorFielDepositario","PrincipalGarantidor" and so on). tag after tag

```<code>(...)
  <fun:QtdMoeda>1</fun:QtdMoeda>
  <!--Optional:-->
  <fun:Observacao>teste</fun:Observacao>
  <!--Optional:-->
  <fun:GarantidorFielDepositario>
     <!--Zero or more repetitions:-->
     <fun:GarantidorFielDepositario>
          <fun:TipoGarantidorFielDepositario>G</fun:TipoGarantidorFielDepositario>
          <!--Optional:-->
          <fun:CPFCNPJGarantidorFielDepositario>003.570.739-91</fun:CPFCNPJGarantidorFielDepositario>
          <!--Optional:-->
          <fun:PrincipalGarantidor>N</fun:PrincipalGarantidor>
          </fun:GarantidorFielDepositario>
   </fun:GarantidorFielDepositario>
</fun:GarantiaSaida>
</code>```

in first moment, I just want print the children tags, but When I try, it dont show anything, and i think its because find_all() return a String, not an XML.

```<code>for cada in rootxml.find_all(retornoForEachVar):
    print '------'
    print cada.tag
</code>```

For exemple, in this case, the variable "retornoForEachVar" has the value "GarantidorFielDepositario" and give to me all "GarantidorFielDepositario" tags. but the print cada.tag shows "none" in the screen.

Can find_all() bring me a XML Value?
do I have to parse the result to XML?

答:
TO print the children, can do </p>

```<code>for cada in rootxml.find_all(retornoForEachVar):
    children = cada.findChildren()
    for child in children:
        print child
</code>```

Body:
I'm using the BeautifulSoup find_all() to get all the xmlo tags.

But when I try to iterate the method return, its a String!

I want all "GarantidorFielDepositario"(I get this with find_all()) tags and I want read the values from all children tags(like "TipoGarantidorFielDepositario","PrincipalGarantidor" and so on). tag after tag

(...)
  <fun:QtdMoeda>1</fun:QtdMoeda>

  <fun:Observacao>teste</fun:Observacao>

  <fun:GarantidorFielDepositario>

     <fun:GarantidorFielDepositario>
          <fun:TipoGarantidorFielDepositario>G</fun:TipoGarantidorFielDepositario>

          <fun:CPFCNPJGarantidorFielDepositario>003.570.739-91</fun:CPFCNPJGarantidorFielDepositario>

          <fun:PrincipalGarantidor>N</fun:PrincipalGarantidor>
          </fun:GarantidorFielDepositario>
   </fun:GarantidorFielDepositario>
</fun:GarantiaSaida>

in first moment, I just want print the children tags, but When I try, it dont show anything, and i think its because find_all() return a String, not an XML.

for cada in rootxml.find_all(retornoForEachVar):
    print '------'
    print cada.tag

For exemple, in this case, the variable "retornoForEachVar" has the value "GarantidorFielDepositario" and give to me all "GarantidorFielDepositario" tags. but the print cada.tag shows "none" in the screen.

Can find_all() bring me a XML Value?
do I have to parse the result to XML?

Body:
TO print the children, can do

for cada in rootxml.find_all(retornoForEachVar):
    children = cada.findChildren()
    for child in children:
        print child


问:
Changing the name of the file to folder name
I have some files and I want to change names to their folder names. However, the problem is that sometimes they are located in main folder and sometimes in subfolders.
For instance lets assume that "Es" is the main directory
Then I have three options:

```<code>Es--> France---_-2011 --> import.csv
Es--> Italy---_-2012 --> files --> import.csv
Es -->France---_-2012 --> files --> recent --> import.csv
</code>```

And my desired outputs are: France----2011.csv for the first one, Italy----2012.csv for the second and France---_-2012.csv for the third one

I have something like this:

```<code># Core settings

rootdir = 'C:\\Users\\es\\den'
extension = ".zip"

for root, dirs, files in os.walk(rootdir):
    if not root.endswith(extension):
        new_list = []
        for file in files:
            if file.endswith(".csv"):
                os.chdir(root)
                print(root)
                add_id = root.split("---_-")[1]
                add_id = add_id.split("\\")[0]
                print(add_id)
</code>```

How I could do that ?

答:
Join path (ref)

```<code>full_path = os.path.join(root, file)
# C:\\Users\\Es\\France-----2011\\import.csv
</code>```

Get relative path (ref)

```<code>rel_path = os.path.relpath(full_path, rootdir)
# France-----2011\\import.csv
</code>```

Split THE directory (ref)

```<code>the_dir_name = rel_path.split(os.sep)[0]
# France-----2011
</code>```

Rename (ref)

```<code>new_filename = the_dir_name + ".csv"
os.rename(full_path, os.path.join(root, new_filename))
# rename C:\\Users\\Es\\France-----2011\\import.csv
# to     C:\\Users\\Es\\France-----2011\\France-----2011.csv
</code>```

Body:
I have some files and I want to change names to their folder names. However, the problem is that sometimes they are located in main folder and sometimes in subfolders.
For instance lets assume that "Es" is the main directory
Then I have three options:

Es--> France---_-2011 --> import.csv
Es--> Italy---_-2012 --> files --> import.csv
Es -->France---_-2012 --> files --> recent --> import.csv

And my desired outputs are: France----2011.csv for the first one, Italy----2012.csv for the second and France---_-2012.csv for the third one

I have something like this:

# Core settings

rootdir = 'C:\\Users\\es\\den'
extension = ".zip"

for root, dirs, files in os.walk(rootdir):
    if not root.endswith(extension):
        new_list = []
        for file in files:
            if file.endswith(".csv"):
                os.chdir(root)
                print(root)
                add_id = root.split("---_-")[1]
                add_id = add_id.split("\\")[0]
                print(add_id)

How I could do that ?

Body:
Join path (ref)

full_path = os.path.join(root, file)
# C:\\Users\\Es\\France-----2011\\import.csv

Get relative path (ref)

rel_path = os.path.relpath(full_path, rootdir)
# France-----2011\\import.csv

Split THE directory (ref)

the_dir_name = rel_path.split(os.sep)[0]
# France-----2011

Rename (ref)

new_filename = the_dir_name + ".csv"
os.rename(full_path, os.path.join(root, new_filename))
# rename C:\\Users\\Es\\France-----2011\\import.csv
# to     C:\\Users\\Es\\France-----2011\\France-----2011.csv


问:
Who can tell me what's wrong with this RPGLE-array?
In have a printer file that looks somewhat like this:

```<code>Customer-data                 Units01 Units02 ....... Units11
-------------------------------------------------------------
Name/address/zip/....         Count01 Count02 ....... Count11
Name/address/zip/....         Count01 Count02 ....... Count11
:    :       :   :            :       :       :       :
Name/address/zip/....         Count01 Count02 ....... Count11
                              ------- ------- ------- -------
Totals                        Total01 Total02 ....... Total11
</code>```

The Units, Count and Total fields are mapped into data structures overlayed with an array definition like this:

```<code>0014.00 D UNITSDS         DS
0015.00 D   UNITS01
0016.00 D   UNITS02
:       :   :
0024.00 D   UNITS10
0025.00 D   UNITS11
0026.00 D  UNITSAR                            LIKE(UNITS) DIM(11)
0026.00 D                                     OVERLAY(UNITSDS)
:       D*-------------------------------------------------------
0034.00 D COUNTDS         DS
0035.00 D   COUNT01
0036.00 D   COUNT02
:       :   :
0044.00 D   COUNT10
0045.00 D   COUNT11
0046.00 D  COUNTAR                            LIKE(COUNT) DIM(11)
0046.00 D                                     OVERLAY(COUNTDS)
:       D*-------------------------------------------------------
0054.00 D TOTALDS         DS
0055.00 D   TOTAL01
0056.00 D   TOTAL02
:       :   :
0064.00 D   TOTAL10
0065.00 D   TOTAL11
0066.00 D  TOTALAR                            LIKE(TOTAL) DIM(11)
0066.00 D                                     OVERLAY(TOTALDS)
</code>```

When I process a WRITE on the details line in the printer file after some processing I get a "Decimal data error".

I was very much surprised that it appears that the arrays COUNTAR and TOTALAR have data type "Packed" although all previous defined variables COUNT, COUNTnn, TOTAL and TOTALnn are "Zoned" and the data structures COUNTDS and TOTALDS are "Char".

Packed data was mapped in the output buffer for the printer file causing the "Decimal data error".

Why are these arrays suddenly in "Packed" data format?

答:
Data structures all always character, since RPG doesn't have a BYTE data type.

You don't seem to be defining the subfields here, so they must be picking up there size and type from someplace else.  Likely, the printer file.  Has the printer file changed perhaps?

I suspect this isn't a zoned vs packed issue.  But would need to see the rest of the definitions and the cross reference from the compile listing to really know what's going on.

Instead, it's likely due to the fact that the DS is not initialized.

From the manual

When the INZ parameter is not specified:

   - Static standalone fields and subfields of initialized data structures are initialized to their RPG default initial values (for
  example, blanks for character, 0 for numeric).

   - Subfields of uninitialized data structures (INZ not specified on the definition specification for the data structure) are initialized
  to blanks (regardless of their data type).

Since you don't have the INZ keyword on your DS, they are considered uninitialized and all the subfields of your DS are set to blanks.  Which or course are not valid numbers.

If the report normally runs ok, and prints data in all 11 columns.  You could be seeing an error now if you're trying to run the report in such a way that not all 11 subfields are being loaded; thus leaving some with blanks.  When the system tries to move the data to the output buffer of printer file, you get the decimal data error.

In short, add the INZ keyword to your DS.

```<code>D COUNTDS         DS                  INZ
</code>```

Body:
In have a printer file that looks somewhat like this:

Customer-data                 Units01 Units02 ....... Units11
-------------------------------------------------------------
Name/address/zip/....         Count01 Count02 ....... Count11
Name/address/zip/....         Count01 Count02 ....... Count11
:    :       :   :            :       :       :       :
Name/address/zip/....         Count01 Count02 ....... Count11
                              ------- ------- ------- -------
Totals                        Total01 Total02 ....... Total11

The Units, Count and Total fields are mapped into data structures overlayed with an array definition like this:

0014.00 D UNITSDS         DS
0015.00 D   UNITS01
0016.00 D   UNITS02
:       :   :
0024.00 D   UNITS10
0025.00 D   UNITS11
0026.00 D  UNITSAR                            LIKE(UNITS) DIM(11)
0026.00 D                                     OVERLAY(UNITSDS)
:       D*-------------------------------------------------------
0034.00 D COUNTDS         DS
0035.00 D   COUNT01
0036.00 D   COUNT02
:       :   :
0044.00 D   COUNT10
0045.00 D   COUNT11
0046.00 D  COUNTAR                            LIKE(COUNT) DIM(11)
0046.00 D                                     OVERLAY(COUNTDS)
:       D*-------------------------------------------------------
0054.00 D TOTALDS         DS
0055.00 D   TOTAL01
0056.00 D   TOTAL02
:       :   :
0064.00 D   TOTAL10
0065.00 D   TOTAL11
0066.00 D  TOTALAR                            LIKE(TOTAL) DIM(11)
0066.00 D                                     OVERLAY(TOTALDS)

When I process a WRITE on the details line in the printer file after some processing I get a "Decimal data error".

I was very much surprised that it appears that the arrays COUNTAR and TOTALAR have data type "Packed" although all previous defined variables COUNT, COUNTnn, TOTAL and TOTALnn are "Zoned" and the data structures COUNTDS and TOTALDS are "Char".

Packed data was mapped in the output buffer for the printer file causing the "Decimal data error".

Why are these arrays suddenly in "Packed" data format?

Body:
Data structures all always character, since RPG doesn't have a BYTE data type.

You don't seem to be defining the subfields here, so they must be picking up there size and type from someplace else.  Likely, the printer file.  Has the printer file changed perhaps?

I suspect this isn't a zoned vs packed issue.  But would need to see the rest of the definitions and the cross reference from the compile listing to really know what's going on.

Instead, it's likely due to the fact that the DS is not initialized.

From the manual

When the INZ parameter is not specified:

   - Static standalone fields and subfields of initialized data structures are initialized to their RPG default initial values (for
  example, blanks for character, 0 for numeric).

   - Subfields of uninitialized data structures (INZ not specified on the definition specification for the data structure) are initialized
  to blanks (regardless of their data type).

Since you don't have the INZ keyword on your DS, they are considered uninitialized and all the subfields of your DS are set to blanks.  Which or course are not valid numbers.

If the report normally runs ok, and prints data in all 11 columns.  You could be seeing an error now if you're trying to run the report in such a way that not all 11 subfields are being loaded; thus leaving some with blanks.  When the system tries to move the data to the output buffer of printer file, you get the decimal data error.

In short, add the INZ keyword to your DS.

D COUNTDS         DS                  INZ


问:
pandoc.exe: Unknown writer: markdown (when called from Java)
I put pandoc on a Windows network drive. The following call succeeds in the command line:

```<code>P:\Maven\pandoc\pandoc-1.19.2.1-windows\pandoc.exe -t markdown C:\devel\ContiMars2\workspace\compareABM\docs\release-notes-utf8.html
</code>```

but when starting it from Java using ProcessBuilder,

```<code>List<String> command = new ArrayList<>();
command.add("P:\\Maven\\pandoc\\pandoc-1.19.2.1-windows\\pandoc.exe");
command.add("-t markdown");
command.add("C:\devel\ContiMars2\workspace\compareABM\docs\release-notes-utf8.html");
ProcessBuilder pb = new ProcessBuilder(command);
</code>```

I get:

```<code>pandoc.exe: Unknown writer:  markdown
</code>```

Any idea why?

答: This is just the usual problem with spaces in commands that are given to ProcessBuilder. If you write --to=markdown instead of -t markdown, everything is fine.

Body:
I put pandoc on a Windows network drive. The following call succeeds in the command line:

P:\Maven\pandoc\pandoc-1.19.2.1-windows\pandoc.exe -t markdown C:\devel\ContiMars2\workspace\compareABM\docs\release-notes-utf8.html

but when starting it from Java using ProcessBuilder,

List<String> command = new ArrayList<>();
command.add("P:\\Maven\\pandoc\\pandoc-1.19.2.1-windows\\pandoc.exe");
command.add("-t markdown");
command.add("C:\devel\ContiMars2\workspace\compareABM\docs\release-notes-utf8.html");
ProcessBuilder pb = new ProcessBuilder(command);

I get:

pandoc.exe: Unknown writer:  markdown

Any idea why?


问:
Is there a way to make my background iPhone app to go foreground?
Is there a way to make my background iPhone app to go foreground?

Tnx.

答:
Not for your app, but the user could do it.
You could schedule a UILocalNotification to inform the user that you are done with your task or whatever.</p>


问:
Yii2 GridView cannot set column width
this is the first time I am using the Yii2 GridView Widget. I have tried setting a column's width after reading some answers here on stackoverflow, but it just won't work for me and I would love it if the columns had different widths (especially the first one).

I have tried setting the width using 'contentOptions' directly for the first column and also with an external CSS file for the product name column.

Can someone please tell me if there is an alternative or if there is something I am doing wrong?

```<code> <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        [
            'class' => 'yii\grid\SerialColumn',
            'contentOptions' => ['style' => 'max-width:20px;'],
        ],

        [
            'format' => 'raw',
            'label' => 'Image',
            'value' => function ($data) {
                $url = $data->imgSrc;
                return Html::img($url, ['width' => '40px']);
            },
        ],

        [
            'attribute' => 'name',
            'format' => 'raw',
            'label' => 'Product name',
            'contentOptions' => function ($model, $key, $index, $column) {
                return ['class' => 'tbl_name'];
            },
        ],
    ],
]); ?>
</code>```

答:
I simple but functional solution is to create a CSS setting a max-width for the columns. The !important flag is to ensure that this property doesn't get overrriden.

```<code>td {
  max-width: 800px;
  white-space: normal !important;
}
</code>```

Then, you just register it in your view.

```<code>$this->registerCssFile('css/tableColumnMaxWidht.css');
</code>```

We have and example of this table working in this image here.

Title: Yii2 GridView cannot set column width

Body:
this is the first time I am using the Yii2 GridView Widget. I have tried setting a column's width after reading some answers here on stackoverflow, but it just won't work for me and I would love it if the columns had different widths (especially the first one).

I have tried setting the width using 'contentOptions' directly for the first column and also with an external CSS file for the product name column.

Can someone please tell me if there is an alternative or if there is something I am doing wrong?

 <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        [
            'class' => 'yii\grid\SerialColumn',
            'contentOptions' => ['style' => 'max-width:20px;'],
        ],

        [
            'format' => 'raw',
            'label' => 'Image',
            'value' => function ($data) {
                $url = $data->imgSrc;
                return Html::img($url, ['width' => '40px']);
            },
        ],

        [
            'attribute' => 'name',
            'format' => 'raw',
            'label' => 'Product name',
            'contentOptions' => function ($model, $key, $index, $column) {
                return ['class' => 'tbl_name'];
            },
        ],
    ],
]); ?>

Body:
I simple but functional solution is to create a CSS setting a max-width for the columns. The !important flag is to ensure that this property doesn't get overrriden.

td {
  max-width: 800px;
  white-space: normal !important;
}

Then, you just register it in your view.

$this->registerCssFile('css/tableColumnMaxWidht.css');

We have and example of this table working in this image here.


问:
How to run non-Caffe model in Caffe
I want to run inference using some ConvNet on Caffe. The only issue is I already have the weights and bias in raw format and I don't want to re-train it on Caffe.

Now Caffe requires two input file:

.prototxt (for Network info)

.caffemodel (for weights and bias)

Here .prototxt file can be generated easily, but is it possible to generate .caffemodel using raw weights and bias?

答:
The process of manually manipulating a Caffe model is called Net Surgery.

Specifically, net.params() allows you to access the net's parameters directly.

Title: How to run non-Caffe model in Caffe


问:
How to get a value in ng-repeat without ng-model?
I am using ng-repeat for iterating a list of objects. When the user selects an option, I want that object, not a single value. ng-model only seems to give me the id.

答:
You should hold the id and value in an object:

HTML:

```<code><div ng-app="myapp" ng-controller="FirstCtrl">
    <select class="form-control selectpicker"  data-live-search="true"   ng-model="subappData"  id="subapplicationid" style="height: 21px;width: 300px;-moz-margin-start: 132px;margin-left: 138px;margin-top: 2px;-moz-margun-start: 132px;">
         <option value="">Select</option>
      <option  ng-repeat='subapp in subapplicationList | filter:query' data-select-watcher data-last="{{$last}}" value = "{{subapp.ID}}"> <a href="#"> {{subapp.ID}} - {{subapp.DESCRIPCION}} </a> </option>
               </select>
    <div>
   <div>
    <button  ng-click="whenClick()">Click</button>
   </div>
    </div>
</div>
</code>```

JavaScript:

```<code>var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
   $scope.subapplicationList = [
  {"ID" :  9 ,"DESCRIPCION" : "a","value" : 24 },
  {"ID" :  1 ,"DESCRIPCION" : "b","value" : 7 },
  {"ID" :  2 ,"DESCRIPCION" : "c","value" : 12 },
  {"ID" :  3 ,"DESCRIPCION" : "d","value" : 2 },
  ];
   $scope.whenClick = function() {
   alert(JSON.stringify($scope.subappData));
  };
});
myapp.directive('selectWatcher', function ($timeout) {
    return {
        link: function (scope, element, attr) {
            var last = attr.last;
            if (last === "true") {
                $timeout(function () {
                    $(element).parent().selectpicker('val', 1);
                    $(element).parent().selectpicker('refresh');

                });
            }
        }
    };
});
</code>```

Working code: jsfiddle

Body:
You should hold the id and value in an object:

HTML:

<div ng-app="myapp" ng-controller="FirstCtrl">
    <select class="form-control selectpicker"  data-live-search="true"   ng-model="subappData"  id="subapplicationid" style="height: 21px;width: 300px;-moz-margin-start: 132px;margin-left: 138px;margin-top: 2px;-moz-margun-start: 132px;">
         <option value="">Select</option>
      <option  ng-repeat='subapp in subapplicationList | filter:query' data-select-watcher data-last="{{$last}}" value = "{{subapp.ID}}"> <a href="#"> {{subapp.ID}} - {{subapp.DESCRIPCION}} </a> </option>
               </select>
    <div>
   <div>
    <button  ng-click="whenClick()">Click</button>
   </div>
    </div>
</div>

JavaScript:

var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
   $scope.subapplicationList = [
  {"ID" :  9 ,"DESCRIPCION" : "a","value" : 24 },
  {"ID" :  1 ,"DESCRIPCION" : "b","value" : 7 },
  {"ID" :  2 ,"DESCRIPCION" : "c","value" : 12 },
  {"ID" :  3 ,"DESCRIPCION" : "d","value" : 2 },
  ];
   $scope.whenClick = function() {
   alert(JSON.stringify($scope.subappData));
  };
});
myapp.directive('selectWatcher', function ($timeout) {
    return {
        link: function (scope, element, attr) {
            var last = attr.last;
            if (last === "true") {
                $timeout(function () {
                    $(element).parent().selectpicker('val', 1);
                    $(element).parent().selectpicker('refresh');

                });
            }
        }
    };
});

Working code: jsfiddle


问:
How do I use web2py smart_query for a GET request?
So I'm trying to use smart_query in web2py to find specific values in a db, but the only explanation I can find is in the web2py book and it's not very clear. The example GET request from the book is formatted like this:

```<code>def GET(search):
    try:
        rows = db.smart_query([db.person, db.pet], search).select()
        return dict(result=rows)
    except:
        ...
</code>```

I'm confused as to what values I would put in place of db.person and db.pet. Here is what the book says on it:

```<code>The method db.smart_query takes two arguments:
    a list of field or table that should be allowed in the query
    a string containing the query expressed in natural language
</code>```

I'm thinking the first value would be the database I'm searching, but then I don't know what the second value would be. The book makes it sound like it should be the string I'm searching for, but I think that that's what the variable search is for.

Could someone please help me understand what exactly each argument is supposed to do?

答:
The first argument to smart_query is a list of DAL Table and/or Field objects (a Table object in the list will simply be expanded to include all of the table's fields). This list determines which fields can be included in the query.

The second argument is the query itself, which can include field names and comparison operators (and their natural language counterparts) as well as "and" and "or" to expression conjunctions and disjunctions. For an idea of what is allowed, you can examine the relevant code here.

The SQLFORM.grid advanced search widget generates queries that are ultimately parsed by smart_query, so to get a better idea of how to generate such queries, try creating a test SQLFORM.grid and play with the search widget in the UI to see the queries it generates.

Body:
So I'm trying to use smart_query in web2py to find specific values in a db, but the only explanation I can find is in the web2py book and it's not very clear. The example GET request from the book is formatted like this:

def GET(search):
    try:
        rows = db.smart_query([db.person, db.pet], search).select()
        return dict(result=rows)
    except:
        ...

I'm confused as to what values I would put in place of db.person and db.pet. Here is what the book says on it:

The method db.smart_query takes two arguments:
    a list of field or table that should be allowed in the query
    a string containing the query expressed in natural language

I'm thinking the first value would be the database I'm searching, but then I don't know what the second value would be. The book makes it sound like it should be the string I'm searching for, but I think that that's what the variable search is for.

Could someone please help me understand what exactly each argument is supposed to do?


问:
How to open print dialog box when clicked on print report instead of saving/downloading it to our computer in Odoo 10
I want to print a report which should not directly download/save to my computer instead it should open a print dialog box. Say suppose my report type is HTML. This is with Odoo Community ver10.</p>

答:
First, create the record of the ir.values

```<code><record model="ir.values" id="ir_values_sale_order">
           <field name="key2" eval="'client_print_multi'"/>
           <field name="model" eval="'sale.order'"/>
           <field name="name">Open Form</field>
           <field name="value" eval="'ir.actions.act_window,%d'%action_report_wizard"/>
    </record>
</code>```

It will create the menu item on the print option on the top.

In it i metioned

```<code> <field name="model" eval="'sale.order'"/>
</code>```

So, It will create a menu on the sale order list view.

Also you can see in about record

```<code><field name="value" eval="'ir.actions.act_window,%d'%action_report_wizard"/>
</code>```

We have our action of the form which we want to open on click.

You can specify your own action's external id here instead of action_report_wizard

And i hope that you have some fields and button on that form view to print the report.

eg.
Action and Form view :

```<code><record id="action_report_wizard" model="ir.actions.act_window">
        <field name="name">Report</field>
        <field name="res_model">sale.order</field>
        <field name="view_type">form</field>
        <field name="view_mode">form</field>
        <field name="view_id" ref="view_report_wizard_form"/>
        <field name="target">new</field>
    </record>
    <record id="view_report_wizard_form" model="ir.ui.view">
                <field name="name">view.report.wizard.form</field>
                <field name="model">sale.order</field>
                <field name="type">form</field>
                <field name="arch" type="xml">
                    <form string="Report">
                        <group cols="4" colspan="2">
                         <!-- Some fields may be for filter -->
                        </group>
                        <footer>
                            <button  icon="gtk-cancel" special="cancel" string="Cancel"/>
                            <button  icon="gtk-apply" name="print_report" string="Print Report" type="object"/>
                        </footer>
                    </form>
            </field>
        </record>
</code>```

And on click of the Print Report it will call the method print_report where you can return the report as you say you have html report.

```<code>@api.multi
def print_report(self):
    # RETURN YOUR REPORT
</code>```

I hope this will help you.

Body:
First, create the record of the ir.values

<record model="ir.values" id="ir_values_sale_order">
           <field name="key2" eval="'client_print_multi'"/>
           <field name="model" eval="'sale.order'"/>
           <field name="name">Open Form</field>
           <field name="value" eval="'ir.actions.act_window,%d'%action_report_wizard"/>
    </record>

It will create the menu item on the print option on the top.

In it i metioned

 <field name="model" eval="'sale.order'"/>

So, It will create a menu on the sale order list view.

Also you can see in about record

<field name="value" eval="'ir.actions.act_window,%d'%action_report_wizard"/>

We have our action of the form which we want to open on click.

You can specify your own action's external id here instead of action_report_wizard

And i hope that you have some fields and button on that form view to print the report.

eg.
Action and Form view :

<record id="action_report_wizard" model="ir.actions.act_window">
        <field name="name">Report</field>
        <field name="res_model">sale.order</field>
        <field name="view_type">form</field>
        <field name="view_mode">form</field>
        <field name="view_id" ref="view_report_wizard_form"/>
        <field name="target">new</field>
    </record>
    <record id="view_report_wizard_form" model="ir.ui.view">
                <field name="name">view.report.wizard.form</field>
                <field name="model">sale.order</field>
                <field name="type">form</field>
                <field name="arch" type="xml">
                    <form string="Report">
                        <group cols="4" colspan="2">
                         <!-- Some fields may be for filter -->
                        </group>
                        <footer>
                            <button  icon="gtk-cancel" special="cancel" string="Cancel"/>
                            <button  icon="gtk-apply" name="print_report" string="Print Report" type="object"/>
                        </footer>
                    </form>
            </field>
        </record>

And on click of the Print Report it will call the method print_report where you can return the report as you say you have html report.

@api.multi
def print_report(self):
    # RETURN YOUR REPORT

I hope this will help you.


问:
How to move the last column "option" to the first column
How could I move to first column my last option column ?
I have servals columns, and I have to scroll a loooooong time to get those options.

答:
This is controlled by this directive:
https://docs.phpmyadmin.net/en/latest/config.html#cfg_RowActionLinks

So yours must be set to 'right' and you should try 'left'. Also, it can be set per-user so visit Parameters from the main page.


问:
html5 tel link fired twice on iOS
I'm facing a weird problem with a tel link in my Ionic cross-platform application.
When I click on the link, the iOS confirmation ('cancel' or 'call') is opened but few seconds after, it pops a second time.

```<code><a ng-click="vm.trackPhoneCall()"
   data-rel="external"
   href="tel:{{ vm.intervention.client.phone }}"
   class="row button button-positive ion-ios-telephone">
     <br/>Appeler
</a>
</code>```

How can I avoid this behaviour ?

It seems like the button is still pressed when the confirmation pops the second time.

答:
I finally found the solution ! Just add the attribute data-tap-disabled="true" to the div. Unfortunately, I still don't know what interfered with ionic tap system in this code.</p>

```<code><a data-tap-disabled="true"
   ng-click="vm.trackPhoneCall()"
   data-rel="external"
   href="tel:{{ vm.intervention.client.phone }}"
   class="row button button-positive ion-ios-telephone">
     <br/>Appeler
</a>
</code>```

Title: html5 tel link fired twice on iOS

Body:
I'm facing a weird problem with a tel link in my Ionic cross-platform application.
When I click on the link, the iOS confirmation ('cancel' or 'call') is opened but few seconds after, it pops a second time.

Appeler

How can I avoid this behaviour ?

It seems like the button is still pressed when the confirmation pops the second time.

Body:
I finally found the solution ! Just add the attribute data-tap-disabled="true" to the div. Unfortunately, I still don't know what interfered with ionic tap system in this code.

<a data-tap-disabled="true"
   ng-click="vm.trackPhoneCall()"
   data-rel="external"
   href="tel:{{ vm.intervention.client.phone }}"
   class="row button button-positive ion-ios-telephone">
     <br/>Appeler
</a>


问:
Flickering on bitmap-based video player
I'm trying to put together a simple video player for videos stored in RAW format. These videos are optionally passed through a convolution filter. My CWinApp class has three relevant methods. First, when a video is selected and placed in the pointer viewingVideo, I allocate two bitmaps:

```<code>void CMyApp::setBitmaps() {
    if (viewingVideo == NULL)
        return;

    bmp1 = CreateDIBSection(dc, viewingVideo->bmi, DIB_RGB_COLORS, NULL, NULL, 0);
    bmp2 = CreateDIBSection(dc, viewingVideo->bmi, DIB_RGB_COLORS, NULL, NULL, 0);
}
</code>```

Then, when the user presses play, I initialize timers that call the following two methods ever 33 ms, for 30 fps playback:

```<code>void CMyApp::updateVideoFrame() {
    if (viewingVideo == NULL)
        return;

    if (viewingKernel != NULL) {
        applyKernelFFT(viewingKernel, viewingVideo, currentFrame);
    }

    if (viewingKernel == NULL)
        SetDIBits(dc, bmpToggle ? bmp2 : bmp1, 0, viewingVideo->height, (char*)(viewingVideo->data) + currentFrame*viewingVideo->bpp*viewingVideo->width*viewingVideo->height, viewingVideo->bmi, DIB_RGB_COLORS);
    else
        SetDIBits(dc, bmpToggle ? bmp2 : bmp1, 0, viewingVideo->height, (char*)(viewingVideo->filtered_data), viewingVideo->bmi, DIB_RGB_COLORS);
    bmpToggle = !bmpToggle;
}

void CMyApp::updateVideoScreen() {
    CMyView* view = CMyView::GetView(); //returns the active view
    view->m_Video.SetBitmap(bmpToggle ? bmp1 : bmp2);
    CRect update;
    view->m_Video.GetWindowRect(&update);
    view->ScreenToClient(&update);
    //update.DeflateRect(update.Width()/2-1, update.Height()/2 - 1);
    InvalidateRect(*AfxGetMainWnd(), update, FALSE);
}
</code>```

At any given time, the methods should be using different bitmaps. There's quite a bit of flickering on the screen when I start these timers. When I uncomment the DeflateRect call, making update a 2x2 pixel rectangle, it becomes clear that there are actually two sources of flickering: sometimes the entire picture flickers, and sometimes only the 2x2 rectangle in the center.

I've tried the common fixes suggested elsewhere, like handing WM_ERASEBKGND in CMyView. This hasn't helped. How can I prevent this flickering?

答:
For anyone else who wants to remove the epilepsy warning from their software, here's what it took to fix the flickering. Adrian McCarthy's suggestion was exactly right. In updateVideoScreen, I replaced view->m_Video.SetBitmap(bmpToggle ? bmp1 : bmp2); with SelectObject(dc, bmpToggle ? bmp1 : bmp2);, so the bitmap data is sent to my memory DC and not to the control. Then I overrode OnPaint() to call BitBlt to write the bitmap to the screen where the video control would have been:

```<code>void CMTFBoostView::OnPaint()
{
    CRect rect;
    m_Video.GetWindowRect(&rect);
    ScreenToClient(&rect);

    video* v = ((CMTFBoostApp*)AfxGetApp())->viewingVideo;
    CDC* src = ((CMTFBoostApp*)AfxGetApp())->cdc;

    CDC* dc = GetDC();
    if (v != NULL && dc->RectVisible(rect)) {
        dc->BitBlt(rect.left, rect.top, v->width, v->height, src, 0, 0, SRCCOPY);
    }
    ReleaseDC(dc);
    CFormView::OnPaint();
}
</code>```

The first few lines are a bit of a hack to put the video where I had it before - it would probably be cleaner to remove the CStatic control from the view altogether. Regardless, this displays the video with no flickering.

Title: Flickering on bitmap-based video player

Body:
I'm trying to put together a simple video player for videos stored in RAW format. These videos are optionally passed through a convolution filter. My CWinApp class has three relevant methods. First, when a video is selected and placed in the pointer viewingVideo, I allocate two bitmaps:

void CMyApp::setBitmaps() {
    if (viewingVideo == NULL)
        return;

    bmp1 = CreateDIBSection(dc, viewingVideo->bmi, DIB_RGB_COLORS, NULL, NULL, 0);
    bmp2 = CreateDIBSection(dc, viewingVideo->bmi, DIB_RGB_COLORS, NULL, NULL, 0);
}

Then, when the user presses play, I initialize timers that call the following two methods ever 33 ms, for 30 fps playback:

void CMyApp::updateVideoFrame() {
    if (viewingVideo == NULL)
        return;

    if (viewingKernel != NULL) {
        applyKernelFFT(viewingKernel, viewingVideo, currentFrame);
    }

    if (viewingKernel == NULL)
        SetDIBits(dc, bmpToggle ? bmp2 : bmp1, 0, viewingVideo->height, (char*)(viewingVideo->data) + currentFrame*viewingVideo->bpp*viewingVideo->width*viewingVideo->height, viewingVideo->bmi, DIB_RGB_COLORS);
    else
        SetDIBits(dc, bmpToggle ? bmp2 : bmp1, 0, viewingVideo->height, (char*)(viewingVideo->filtered_data), viewingVideo->bmi, DIB_RGB_COLORS);
    bmpToggle = !bmpToggle;
}

void CMyApp::updateVideoScreen() {
    CMyView* view = CMyView::GetView(); //returns the active view
    view->m_Video.SetBitmap(bmpToggle ? bmp1 : bmp2);
    CRect update;
    view->m_Video.GetWindowRect(&update);
    view->ScreenToClient(&update);
    //update.DeflateRect(update.Width()/2-1, update.Height()/2 - 1);
    InvalidateRect(*AfxGetMainWnd(), update, FALSE);
}

At any given time, the methods should be using different bitmaps. There's quite a bit of flickering on the screen when I start these timers. When I uncomment the DeflateRect call, making update a 2x2 pixel rectangle, it becomes clear that there are actually two sources of flickering: sometimes the entire picture flickers, and sometimes only the 2x2 rectangle in the center.

I've tried the common fixes suggested elsewhere, like handing WM_ERASEBKGND in CMyView. This hasn't helped. How can I prevent this flickering?

Body:
For anyone else who wants to remove the epilepsy warning from their software, here's what it took to fix the flickering. Adrian McCarthy's suggestion was exactly right. In updateVideoScreen, I replaced view->m_Video.SetBitmap(bmpToggle ? bmp1 : bmp2); with SelectObject(dc, bmpToggle ? bmp1 : bmp2);, so the bitmap data is sent to my memory DC and not to the control. Then I overrode OnPaint() to call BitBlt to write the bitmap to the screen where the video control would have been:

void CMTFBoostView::OnPaint()
{
    CRect rect;
    m_Video.GetWindowRect(&rect);
    ScreenToClient(&rect);

    video* v = ((CMTFBoostApp*)AfxGetApp())->viewingVideo;
    CDC* src = ((CMTFBoostApp*)AfxGetApp())->cdc;

    CDC* dc = GetDC();
    if (v != NULL && dc->RectVisible(rect)) {
        dc->BitBlt(rect.left, rect.top, v->width, v->height, src, 0, 0, SRCCOPY);
    }
    ReleaseDC(dc);
    CFormView::OnPaint();
}

The first few lines are a bit of a hack to put the video where I had it before - it would probably be cleaner to remove the CStatic control from the view altogether. Regardless, this displays the video with no flickering.


问:
Unknown attribute type (Object) for attribute data
JSP Page error. How to solve the "Unknown attribute type (Object) for attribute data." ERROR.
and the error point to

">
Below is my JSP code.

```<code><%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="kendo" uri="http://www.kendoui.com/jsp/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link href="resources/styles/kendo.common.min.css" rel="stylesheet"
    type="text/css" />
<link href="resources/styles/kendo.default.min.css" rel="stylesheet"
    type="text/css" />

<script src="resources/js/jquery.min.js"></script>
<script src="resources/js/kendo.web.min.js"></script>

</head>
<body>
<%
    List<String> data = new ArrayList<String>();
    data.add("adaf");
    data.add("bdfa");
    data.add("cdasf");
%>

<div class="container">
<div class="row">
<kendo:dropDownList name="things">
    <kendo:dataSource data="<%=data %>">
    </kendo:dataSource>
</kendo:dropDownList>
</div>
</div>
</body>
</html>
</code>```

ERROR Message:

```<code>SEVERE: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: /index.jsp(32,1) Unknown attribute type (Object) for attribute data.
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:236)
    at org.apache.jasper.compiler.Validator$ValidateVisitor.checkXmlAttributes(Validator.java:1199)
    at org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:846)
    at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1530)
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
    at org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:865)
    at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1530)
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
    at org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2417)
    at org.apache.jasper.compiler.Node$Root.accept(Node.java:495)
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    at org.apache.jasper.compiler.Validator.validateExDirectives(Validator.java:1763)
    at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:198)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:354)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:334)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:321)
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:592)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:328)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Unknown Source)
</code>```

My Environment:
Tomcat 6.0
JDK1.7

答: Old version of JAR causing the issue.</p>

Body:
JSP Page error. How to solve the "Unknown attribute type (Object) for attribute data." ERROR.
and the error point to

">
Below is my JSP code.

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="kendo" uri="http://www.kendoui.com/jsp/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link href="resources/styles/kendo.common.min.css" rel="stylesheet"
    type="text/css" />
<link href="resources/styles/kendo.default.min.css" rel="stylesheet"
    type="text/css" />

<%
    List<String> data = new ArrayList<String>();
    data.add("adaf");
    data.add("bdfa");
    data.add("cdasf");
%>

<kendo:dropDownList name="things">
    <kendo:dataSource data="<%=data %>">
    </kendo:dataSource>
</kendo:dropDownList>

ERROR Message:

SEVERE: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: /index.jsp(32,1) Unknown attribute type (Object) for attribute data.
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:236)
    at org.apache.jasper.compiler.Validator$ValidateVisitor.checkXmlAttributes(Validator.java:1199)
    at org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:846)
    at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1530)
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
    at org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:865)
    at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1530)
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
    at org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2417)
    at org.apache.jasper.compiler.Node$Root.accept(Node.java:495)
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    at org.apache.jasper.compiler.Validator.validateExDirectives(Validator.java:1763)
    at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:198)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:354)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:334)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:321)
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:592)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:328)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Unknown Source)

My Environment:
Tomcat 6.0
JDK1.7

Body: Old version of JAR causing the issue.


问:
How to set some spaces before a link without moving the link position?
I need to higlight a div 5 pixels before its current position on mouse over. That is to say if the user passes the pointer over it the div would be highlighted 5 pixels before, but without changing its content position.

.container {
  width: 100%;
  &:hover {
    background-color: rgba(0, 0, 0, 0.1);
    position: relative;
    padding-left: 5px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  Click me!
</div></code>```

On mouse over it highlights but the "Click me!" message moves 5 pixels to the right. How can I achieve this?

答:
Try this SCSS

```<code>.container {
  width: 100%;

  &:hover {
    background-color: rgba(0, 0, 0, 0.1);
    position: relative;
    padding-left: 5px;
    a{
    margin-left:-5px;
     }
  }
}
</code>```

Link for reference

hope this helps..

Body:
I need to higlight a div 5 pixels before its current position on mouse over. That is to say if the user passes the pointer over it the div would be highlighted 5 pixels before, but without changing its content position.

.container {
  width: 100%;
  &:hover {
    background-color: rgba(0, 0, 0, 0.1);
    position: relative;
    padding-left: 5px;
  }
}

  Click me!

On mouse over it highlights but the "Click me!" message moves 5 pixels to the right. How can I achieve this?

Body:
Try this SCSS

.container {
  width: 100%;

  &:hover {
    background-color: rgba(0, 0, 0, 0.1);
    position: relative;
    padding-left: 5px;
    a{
    margin-left:-5px;
     }
  }
}

Link for reference

hope this helps..


问:
igakit windows 10 64bit installation (with python 2.7) error lnk2019
I'm trying to install igakit python extension as part of installing all required dependencies for sfepy package as mentioned in their installation guide page http://sfepy.org/doc-devel/installation.html#requirements .

Sadly, there's no wheel file for it to run using pip.

My installation process was (and still) full of errors to appear and they were 2-phase long, but I will describe only the current phase.

Phase #2: Installed software:-

1-Python 2.7.13 (64-bit)

2-Microsoft Visual C++ for Python 2.7

3-Microsoft Visual C++ 2010 x64 Redistributable

4-Microsoft Visual C++ 2010 x86 Redistributable

5-MinGW-w64 & Msys2 installed as described in this site https://computingabdn.com/softech/mingw-howto-install-gcc-for-windows/ .

When I hit

```<code>    python setup.py install --user
</code>```

on to the downloaded top level directory of igakit in command prompt this error comes up

```<code>    igalibmodule.obj : warning LNK4197: export 'initigalib' specified multiple times; using first specification
Creating library build\temp.win-amd64-2.7\Release\build\src.win-amd64-2.7\igakit\igalib.lib and object build\temp.win-amd64-2.7\Release\build\src.win-amd64-2.7\igakit\igalib.exp
igalib.o : error LNK2019: unresolved external symbol _gfortran_internal_pack referenced in function __bspline_MOD_removeknot
igalib.o : error LNK2019: unresolved external symbol _gfortran_matmul_r8 referenced in function __bspeval_MOD_interpolate
igalib.o : error LNK2019: unresolved external symbol _gfortran_stop_string referenced in function __bsp_MOD_hessian3
build\lib.win-amd64-2.7\igakit\igalib.pyd : fatal error LNK1120: 3 unresolved externals
</code>```

I've also googled this problem before and found that this problem could be caused from a declared but not defined external variable or function, but sadly as I just have little programming experience, and as googling results are mainly devoted to visual studio (which isn't installed in my computer) I can't push further to grab the source of this issue.

Any help ?

答:
According to the answers here from what the repository owner sincerely gave to me, to resolve the problem you need to:-

At the top level directory open the file setup.cfg then add the following

```<code>[build]
#debug = 0
compiler = mingw32

[build_ext]
libraries = gfortran # or maybe libgfortran?
</code>```

2- save the file then try again hitting python setup.py install --user.

Notes before implementing the solution:-

1- If you wish to install it in the Python system location, hit python setup.py install without the --user flag.

2-If you didn't solve the ((Unable to find vcvarsall.bat)) yet, go and search using the search engine within you 'windows explorer' window the C:\ partition for the file vcvarsall.bat, then get its location.

Then, open the file msvc9compiler.py (search for it in C:\Python27), look for the function query_vcvarsall, and within it look for the variable vcvarsall, then assign the full path of vcvarsall.bat to it.

Body:
I'm trying to install igakit python extension as part of installing all required dependencies for sfepy package as mentioned in their installation guide page http://sfepy.org/doc-devel/installation.html#requirements .

Sadly, there's no wheel file for it to run using pip.

My installation process was (and still) full of errors to appear and they were 2-phase long, but I will describe only the current phase.

Phase #2: Installed software:-

1-Python 2.7.13 (64-bit)

2-Microsoft Visual C++ for Python 2.7

3-Microsoft Visual C++ 2010 x64 Redistributable

4-Microsoft Visual C++ 2010 x86 Redistributable

5-MinGW-w64 & Msys2 installed as described in this site https://computingabdn.com/softech/mingw-howto-install-gcc-for-windows/ .

When I hit

    python setup.py install --user

on to the downloaded top level directory of igakit in command prompt this error comes up

    igalibmodule.obj : warning LNK4197: export 'initigalib' specified multiple times; using first specification
Creating library build\temp.win-amd64-2.7\Release\build\src.win-amd64-2.7\igakit\igalib.lib and object build\temp.win-amd64-2.7\Release\build\src.win-amd64-2.7\igakit\igalib.exp
igalib.o : error LNK2019: unresolved external symbol _gfortran_internal_pack referenced in function __bspline_MOD_removeknot
igalib.o : error LNK2019: unresolved external symbol _gfortran_matmul_r8 referenced in function __bspeval_MOD_interpolate
igalib.o : error LNK2019: unresolved external symbol _gfortran_stop_string referenced in function __bsp_MOD_hessian3
build\lib.win-amd64-2.7\igakit\igalib.pyd : fatal error LNK1120: 3 unresolved externals

I've also googled this problem before and found that this problem could be caused from a declared but not defined external variable or function, but sadly as I just have little programming experience, and as googling results are mainly devoted to visual studio (which isn't installed in my computer) I can't push further to grab the source of this issue.

Any help ?

Body:
According to the answers here from what the repository owner sincerely gave to me, to resolve the problem you need to:-

At the top level directory open the file setup.cfg then add the following

[build]
#debug = 0
compiler = mingw32

[build_ext]
libraries = gfortran # or maybe libgfortran?

2- save the file then try again hitting python setup.py install --user.

Notes before implementing the solution:-

1- If you wish to install it in the Python system location, hit python setup.py install without the --user flag.

2-If you didn't solve the ((Unable to find vcvarsall.bat)) yet, go and search using the search engine within you 'windows explorer' window the C:\ partition for the file vcvarsall.bat, then get its location.

Then, open the file msvc9compiler.py (search for it in C:\Python27), look for the function query_vcvarsall, and within it look for the variable vcvarsall, then assign the full path of vcvarsall.bat to it.


问:
what type should i put in a function definition when using a vector<double>?
I have a function, prototyped as below:

```<code>double gradeCalc (double midterm, double final, const vector<double>& hwGrades);
</code>```

in my code I pass the variable homework, declared as

```<code>vector<double> homework;
</code>```

into the third argument. I get the below error:

```<code>undefined reference to `gradeCalc(double, double, std::vector<double, std::allocator<double> >)'
</code>```

In the textbook I'm working from, the function prototype is the same, yet there is no mention of this error. It seems the type of homework is not what I thought it was. What have I done wrong? (and what is an allocator for that matter?)

edit
full function definition below as requested:

```<code>double gradeCalc (double midterm, double final, const vector<double> & hwGrades) {
    if (hwGrades.size() == 0) {
    throw domain_error("homework grades list empty");
    }

    double median = vdMedian(hwGrades);
    return 0.2 * midterm + 0.4 * final + 0.4 * median;
}
</code>```

edit #2
found. silly typographical error. would still be interested to know what an allocator is. happy to ask in a seperate question.

答:
The vector template is defined as

```<code>template<class _Ty, class _Alloc = allocator<_Ty> >
class vector: public _Vector_alloc<_Vec_base_types<_Ty, _Alloc> >
</code>```

Note the deafult value for the second template parameter.

So when you write this

```<code>std::vector<double> homework;
</code>```

it's actually the same as

```<code>std::vector<double, std::allocator<double>> homework;
</code>```

Body:
I have a function, prototyped as below:

double gradeCalc (double midterm, double final, const vector<double>& hwGrades);

in my code I pass the variable homework, declared as

vector<double> homework;

into the third argument. I get the below error:

undefined reference to `gradeCalc(double, double, std::vector<double, std::allocator<double> >)'

In the textbook I'm working from, the function prototype is the same, yet there is no mention of this error. It seems the type of homework is not what I thought it was. What have I done wrong? (and what is an allocator for that matter?)

edit
full function definition below as requested:

double gradeCalc (double midterm, double final, const vector<double> & hwGrades) {
    if (hwGrades.size() == 0) {
    throw domain_error("homework grades list empty");
    }

    double median = vdMedian(hwGrades);
    return 0.2 * midterm + 0.4 * final + 0.4 * median;
}

edit #2
found. silly typographical error. would still be interested to know what an allocator is. happy to ask in a seperate question.

Body:
The vector template is defined as

template<class _Ty, class _Alloc = allocator<_Ty> >
class vector: public _Vector_alloc<_Vec_base_types<_Ty, _Alloc> >

Note the deafult value for the second template parameter.

So when you write this

std::vector<double> homework;

it's actually the same as

std::vector<double, std::allocator<double>> homework;


问:
C# LINQ OrderBy several clauses
I'm currently working on an application in ASP.NET MVC 4.5. I need to write a LINQ query to order a list of Projects by different StatusIds.

Given is a list of Projects with this ViewModel:

```<code>public class ProjectVm
{
   public int ProjectId { get; set; }
   public string Title { get; set; }
   public Status StatusId { get; set; }
}
</code>```

My project status enum:

```<code>public enum Status : byte
{
    Draft = 1,
    Pending = 2,
    Validated = 3,
    Refused = 4
}
</code>```

The idea is to bring the List<ProjectVm> in a certain order, thus first ordered by 1 Draft, second by 2 Pending, third by 4 Refused and fourth by 3 Validated.

My current query looks like this:

```<code>projects = projects.OrderBy(x => x.StatusId).ToList();
</code>```

Unfortunately this query doesn't respect the desired order (4 comes before 3).

Do you know how to apply a condition on this query to bring the projects into the right order (1, 2, 4, 3) ?

Thanks!

答:
Try this   </p>

```<code>var projectList= projects.OrderBy(x => (int)x.StatusId).ToList();
</code>```

Title: C# LINQ OrderBy several clauses

Body:
I'm currently working on an application in ASP.NET MVC 4.5. I need to write a LINQ query to order a list of Projects by different StatusIds.

Given is a list of Projects with this ViewModel:

public class ProjectVm
{
   public int ProjectId { get; set; }
   public string Title { get; set; }
   public Status StatusId { get; set; }
}

My project status enum:

public enum Status : byte
{
    Draft = 1,
    Pending = 2,
    Validated = 3,
    Refused = 4
}

The idea is to bring the List<ProjectVm> in a certain order, thus first ordered by 1 Draft, second by 2 Pending, third by 4 Refused and fourth by 3 Validated.

My current query looks like this:

projects = projects.OrderBy(x => x.StatusId).ToList();

Unfortunately this query doesn't respect the desired order (4 comes before 3).

Do you know how to apply a condition on this query to bring the projects into the right order (1, 2, 4, 3) ?

Thanks!

Body:
Try this

var projectList= projects.OrderBy(x => (int)x.StatusId).ToList();


问:
windows update is causing my custom service to hang
I am using visual studio professional 2015, c# .net framework 4.
I have created a service for windows that sends and receives data on the serial port.  It is intended to start when the computer starts and shutdown when the computer is shutdown.  It should not hang or stop otherwise.

I have been running tests and find that when windows does an update it causes my service to hang.  I have no idea how to debug this hang.

I would appreciate any ideas on how to start tracking down this bug.

thanks.

答:
Here's something that might help.

When I write a service, I typically add an event handler to this AppDomain event called UnhandledException.

It's sort of a catch-all exception handler and has come in handy on a number of occassions and helps you improve your error handling, in general.

```<code>// Add this code to the Service Start method or the constructor

AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

// Then add this method to your service class, it will be invoked when
// your code encounters an exception that is not trapped by a try/catch/finally

private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    var ex = e.ExceptionObject as Exception;
    Trace.TraceError("Unhandled Exception occurred in service: {0}", ex);
}
</code>```

Feel free to replace the Trace logging with your own logging framework if necessary.

Hope this helps.

Body:
Here's something that might help.

When I write a service, I typically add an event handler to this AppDomain event called UnhandledException.

It's sort of a catch-all exception handler and has come in handy on a number of occassions and helps you improve your error handling, in general.

// Add this code to the Service Start method or the constructor

AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

// Then add this method to your service class, it will be invoked when
// your code encounters an exception that is not trapped by a try/catch/finally

private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    var ex = e.ExceptionObject as Exception;
    Trace.TraceError("Unhandled Exception occurred in service: {0}", ex);
}

Feel free to replace the Trace logging with your own logging framework if necessary.

Hope this helps.


问:
Override Django Render Methods
With the following renderer...

```<code>from django.shortcuts import render
...
return render(request, 'template.html', {'context':context,})
</code>```

Is it possible to override the render classe's methods so that I can in certain circumstances interpret template tags myself for example if I find a tag consisting of a certain format such as...

```<code>{% url 'website' page.slug %}
</code>```

I could point it to...

```<code>/theme/theme-1/page.html
</code>```

or

```<code>/theme/theme-2/page.html
</code>```

depending on extranious settings.

答:
The render method is just a shortcut for:

```<code>template = loader.get_template(''template.html')
context = {
    ...,
}
return HttpResponse(template.render(context, request))
</code>```

Therefore, it is not the correct place to try to change the behaviour of the url tag.

For the example you have given, it looks like the website should be a variable that holds theme-1 or theme-2. You can then pass the variable to the url tag instead of the string 'website'.

```<code>{% url website page.slug %}
</code>```

If that is not possible, you could create a custom template tag my_url that returns the correct url depending on your settings.

Title: Override Django Render Methods

Body:
With the following renderer...

from django.shortcuts import render
...
return render(request, 'template.html', {'context':context,})

Is it possible to override the render classe's methods so that I can in certain circumstances interpret template tags myself for example if I find a tag consisting of a certain format such as...

{% url 'website' page.slug %}

I could point it to...

/theme/theme-1/page.html

or

/theme/theme-2/page.html

depending on extranious settings.

Body:
The render method is just a shortcut for:

template = loader.get_template(''template.html')
context = {
    ...,
}
return HttpResponse(template.render(context, request))

Therefore, it is not the correct place to try to change the behaviour of the url tag.

For the example you have given, it looks like the website should be a variable that holds theme-1 or theme-2. You can then pass the variable to the url tag instead of the string 'website'.

{% url website page.slug %}

If that is not possible, you could create a custom template tag my_url that returns the correct url depending on your settings.


问:
Microservice Versioning
What is the best practice to adapt for versioning in a Microservice Based Architecture, in terms of supporting multiple versioned deployment of the same service during runtime and how the consumers would be able to use different versions?
1) If we use Routing based Versioning as one of the approaches mentioned here
then I guess we would have the following drawbacks

Internal Services have to go through Reverse Proxy for consumption.

Consumers always have to be aware of the required versioning.

Is it a best practice to expose the version information to consumers?

In any case, as I feel, the following always applies:

For MAJOR version change, the consumers have to be changed.

For MINOR version change (backwards compatible), only the consumer(s) that requires the added functionality needs to change.

For PATCH version change, it's optional and would probably be seamless for any consumers to make use of it.

What kind of Microservice versioning strategy can help us in enabling the above?

NOTE - Please feel free to let me know if this needs to be split in multiple questions.

答:
There is no best practice. It's going to depend on how versioning should work in your specific case.

Shawn Wildermuth discussed about api versioning in a pluralsight video. Not sure about your microservice implementation details, but if you are using rest api, you may try the versioning the actual payload

You could also do this with an Accept header. Accept allows for you to
  annotate the Accept header with a version type against the API you
  want to look at. And you can also do this with content type as well.
  The application/vnd for vendor specifies the version of the returning
  data,  so that when the application then sends it, it knows what
  version of the payload it is. And this is an important technique in
  versioning, because you have to version both the API, the actual URI
  calls, as well as the shape of the data that's coming back.

If you find a mechanism that works well in your environment and with your customers and users, go ahead and use that.

Title: Microservice Versioning


问:
Adding a Team Project Collection in TFS2010
I’m trying to add a team project collection to a TFS2010 instance.  The instance already has project collections set-up and in use, but when I try to add another I get warnings from the Data Tier Configuration.  The warnings are as follows:

```<code>TF255153: Service is not set to start automatically: SQL Server Database Services:

TF255437: An error occurred while querying the Windows Management Instrumentation (WMI) interface on the following computer: MYTFSSERVER.  The following error message was received: .

TF255437: An error occurred while querying the Windows Management Instrumentation (WMI) interface on the following computer: MYTFSSERVER.  The following error message was received: .
</code>```

(TF255437 is reported twice)

I’ve had a good look around, and found a couple of articles that implied TF255437 is caused by WMI compatibility not being enabled in IIS (TFS2010 is running on IIS7.5).  However, this is enabled as far as I can tell.

Has anyone come across either of these errors before?  The admin console seems happy for me to create the TPC regardless, but without understanding the errors fully, I’m reluctant to do so.

答: This was all caused by the "SQL Server Agent" service not being started on the server.</p>

Body:
I’m trying to add a team project collection to a TFS2010 instance.  The instance already has project collections set-up and in use, but when I try to add another I get warnings from the Data Tier Configuration.  The warnings are as follows:

TF255153: Service is not set to start automatically: SQL Server Database Services:

TF255437: An error occurred while querying the Windows Management Instrumentation (WMI) interface on the following computer: MYTFSSERVER.  The following error message was received: .

TF255437: An error occurred while querying the Windows Management Instrumentation (WMI) interface on the following computer: MYTFSSERVER.  The following error message was received: .

(TF255437 is reported twice)

I’ve had a good look around, and found a couple of articles that implied TF255437 is caused by WMI compatibility not being enabled in IIS (TFS2010 is running on IIS7.5).  However, this is enabled as far as I can tell.

Has anyone come across either of these errors before?  The admin console seems happy for me to create the TPC regardless, but without understanding the errors fully, I’m reluctant to do so.