问:
How to use Environnement in <filter> domain
Using Odoo 10 (fetched from GitHub commit 7413b26, branch 10.0), I try to use the environnement in a search filter domain applied to a tree view. Like this:

<filter string="Metal" domain="[('attribute_id','=', self.env['ir.config_parameter'].get_param('my_module.attrib_metal', None))]" help="metal"/>
```

<p>But Odoo won't let me use <code>self</code>:</p>

<blockquote>
  <p>NameError: name 'self' is not defined</p>
</blockquote>

<hr>

<p>I also tried to filter my <code>attrib_metal</code> with Python by saving the result in a field but I don't want to store it in my database, however Odoo search requires it to be.</p>

<p>In my Python:</p>

<pre class="lang-py prettyprint-override"><code>def get_my_params(self):
    attrid = self.env['ir.config_parameter'].get_param(
            'my_module.attrib_metal', None)
    if attrid:
        for rec in self:
            setattr(rec, attrib_metal, rec.attribute_id.id == int(attrid))

attrib_metal = fields.Boolean(store=False, compute="get_cr_params")
</code>```

This code is part of an inhereted product.attribute.value model.

In my XML view:

<filter string="Metal" domain="[('attrib_metal', '=', 'True')]" help="metal"/>
```

I have tried with the store = True parameter, but this way the value is stored in the database and is only computed once, which is not what I'm looking for.

So this is not the right way of doing it.

How can one use the environnement in a <filter> domain?

答:
The domain is being evaluated in the web client (frontend/Javascript). The web client knows nothing about self. Also, the dot notation in the filters is not supported. You will need to create a new field for this as the domains are run on the javascript side and you cannot execute code there. The new field must also be stored in the database. This pattern is used all over Odoo.

use:
<field name="your_field" invisible="1" /> to bring it to your view and to keep it invisible and then

```<code><filter string="Metal" domain="[('attribute_id','=', your_field]" help="metal"/>
</code>```

Body:
Using Odoo 10 (fetched from GitHub commit 7413b26, branch 10.0), I try to use the environnement in a search filter domain applied to a tree view. Like this:

<filter string="Metal" domain="[('attribute_id','=', self.env['ir.config_parameter'].get_param('my_module.attrib_metal', None))]" help="metal"/>

But Odoo won't let me use self:

NameError: name 'self' is not defined

I also tried to filter my attrib_metal with Python by saving the result in a field but I don't want to store it in my database, however Odoo search requires it to be.

In my Python:

def get_my_params(self):
    attrid = self.env['ir.config_parameter'].get_param(
            'my_module.attrib_metal', None)
    if attrid:
        for rec in self:
            setattr(rec, attrib_metal, rec.attribute_id.id == int(attrid))

attrib_metal = fields.Boolean(store=False, compute="get_cr_params")

This code is part of an inhereted product.attribute.value model.

In my XML view:

<filter string="Metal" domain="[('attrib_metal', '=', 'True')]" help="metal"/>

I have tried with the store = True parameter, but this way the value is stored in the database and is only computed once, which is not what I'm looking for.

So this is not the right way of doing it.

How can one use the environnement in a <filter> domain?

Body:
The domain is being evaluated in the web client (frontend/Javascript). The web client knows nothing about self. Also, the dot notation in the filters is not supported. You will need to create a new field for this as the domains are run on the javascript side and you cannot execute code there. The new field must also be stored in the database. This pattern is used all over Odoo.

use:
<field name="your_field" invisible="1" /> to bring it to your view and to keep it invisible and then

<filter string="Metal" domain="[('attribute_id','=', your_field]" help="metal"/>


来源: stackexchange

问:
How to map onPress events on single svg object in React Native?
I'm currently developing a mobile application using React Native for my thesis on the University. I'm looking to create similar Interactive Map like for example here http://smudgeproof.net/siggraph.html where you have a map of inside of a building and you're able to click on each room to bring up new window with some additional information about that room.

I should be able to create this map on specific website and then show it in the up with functionality mentioned above. I was thinking about SVG to handle this stuff.

I'm able to draw svg map on screen using currently available 3rd party libraries for drawing SVG's like https://github.com/aksonov/react-native-svg-elements unfortunately none of those libraries support onpress event per svg element, to be able to show the description screen upon room click.

I should also add that rooms may have a lot of different shapes so it's not just rectangles, this makes it unable to build the map using just  elements.

I would appreciate any help, or if you guys can come up with different solution to handle this problem, I'm familiar with Javascript, but haven't done any applications for iOS in objective-c, so I'm not sure how hard it would be to write a custom module to handle this.

Thanks!

UPDATE: Just in case anyone would try to solve similar problem, I ended up displaying those svgs through WebView and handling 'press' events on each objects through injected JavaScript. Anyway thanks to all for the help! :)

答:
The react-native-sgv library provides support for onPress() events now. See the following for examples:
https://github.com/react-native-community/react-native-svg

If you would like to attach an onClick event to a group of elements, you can use the Symbol component of the svg library to link a group of elements together an attach an onPress event to any of the elements which will apply to the whole Symbol

ContentLicense: CC BY-SA 3.0


问:
Fetch on backbone isn't populate my template
I did a fetch in my collection and I did a console.log() and it's working but when I set to my template not show the values.

in my View is it:

```<code>       var reposCollection = new Sice.Collections.RepositoryList();
       reposCollection.fetch();
       this.$el.html(this.template({collection: reposCollection.models}));
</code>```

my template is it:

```<code>      <% _.each(collection, function(repos) { %>
        <tr>
          <td><%= repos.attributes.name %></td>
          <td><%= repos.attributes.description %></td>
          <td><%= repos.attributes.language %></td>
       </tr>
     <% }); %>
</code>```

I don't know what is happening!

答:
Your template is being rendered before your fetch is completed. You need to call the rendering code in the success callback of fetch:

```<code>var reposCollection = new Sice.Collections.RepositoryList();
reposCollection.fetch({
    success: (collection, response, options) => {
        this.$el.html(this.template({collection: collection.models}));
    }
});
</code>```

Backbone.Collection.prototype.fetch documentation

Body:
I did a fetch in my collection and I did a console.log() and it's working but when I set to my template not show the values.

in my View is it:

       var reposCollection = new Sice.Collections.RepositoryList();
       reposCollection.fetch();
       this.$el.html(this.template({collection: reposCollection.models}));

my template is it:

      <% _.each(collection, function(repos) { %>

          <%= repos.attributes.name %>
          <%= repos.attributes.description %>
          <%= repos.attributes.language %>

     <% }); %>

I don't know what is happening!

Body:
Your template is being rendered before your fetch is completed. You need to call the rendering code in the success callback of fetch:

var reposCollection = new Sice.Collections.RepositoryList();
reposCollection.fetch({
    success: (collection, response, options) => {
        this.$el.html(this.template({collection: collection.models}));
    }
});

Backbone.Collection.prototype.fetch documentation


问:
R get all rows that have at least one number in each decade from 0 to 99
Having the following matrix:

```<code>     [,1] [,2] [,3] [,4]  [,5]  [,6]  [,7]  [,8]  [,9]  [,10]  [,11]  [,12]
[1,]   23   14   17   10     2     6    90    45    56     25     11      9
[2,]    1   15   18   21    32    46    55    50    61     73     81     93
[3,]   56   19   98   23    42     7     8    25    61     54     22     38
</code>```

I want to get only the rows that have at least 1 number in each of 10 decades from 1 to 99
 So the result must be:

```<code>[1] False
[2] True
[3] False
</code>```

Finally we get only [2] that satisfies the condition. Can you please provide an R language function which can generate this result?

Regards,
Dimitris

答:
An alternative is to use the setqual function to check for set equality of the decades (0:9) with the contents of the row after using the integer division operator %/%.

```<code>apply(m1, 1, function(x) setequal(0:9, x %/%10))
[1] FALSE  TRUE FALSE
</code>```

Body:
Having the following matrix:

     [,1] [,2] [,3] [,4]  [,5]  [,6]  [,7]  [,8]  [,9]  [,10]  [,11]  [,12]
[1,]   23   14   17   10     2     6    90    45    56     25     11      9
[2,]    1   15   18   21    32    46    55    50    61     73     81     93
[3,]   56   19   98   23    42     7     8    25    61     54     22     38

I want to get only the rows that have at least 1 number in each of 10 decades from 1 to 99
 So the result must be:

[1] False
[2] True
[3] False

Finally we get only [2] that satisfies the condition. Can you please provide an R language function which can generate this result?

Regards,
Dimitris

Body:
An alternative is to use the setqual function to check for set equality of the decades (0:9) with the contents of the row after using the integer division operator %/%.

apply(m1, 1, function(x) setequal(0:9, x %/%10))
[1] FALSE  TRUE FALSE


问:
Tkinter grouping buttons and lables
I want to create a GUI where you specify a bunch of files for later processing (commandline parsing a dozen files is just a PITA).

So now I want to group a lable and a button for better readability.

I've tried something like that:

```<code>DC1_path_label = Label(window_fine_DC, text = "Please specify the path of DC 1:", relief=RAISED)
DC1_B = Tkinter.Button(window_fine_DC, textvariable = DC_path1, command = setDC1)
DC2_path_label = Label(window_fine_DC, text="Please specify the path of DC 2:", relief=RAISED)
DC2_B = Tkinter.Button(window_fine_DC, textvariable=DC_path2, command=setDC2)

DC1_path_label.grid(row = 0, column = 1)
DC1_B.grid(row = 1, column = 1)
DC2_path_label.grid(row = 3, column = 1)
DC2_B.grid(row = 4, column = 1)
</code>```

but it seems to have no effect, also paddings dont work that great either, since those go in all directions equally.

And while we are at it, is there a more elegant way to change a window than closing the old one, and opening a new?

Sorry if this is a stupid question, I'm fairly new with python/gui stuff...

答:
I believe what you need is to provide a tuple to your padx and/or pady.

You can specify padding for each side this way.

I use pady as an example here to show how you can provide padding on only one side. Notice how the top Label is padded at its top but the bottom button is not padded on the bottom side.

```<code>from tkinter import *

root = Tk()

DC1_path_label = Label(root, text = "Please specify the path of DC 1:", relief=RAISED)
DC1_B = Button(root)
DC2_path_label = Label(root, text="Please specify the path of DC 2:", relief=RAISED)
DC2_B = Button(root)

DC1_path_label.grid(row = 0, column = 1, pady = (10, 0))
DC1_B.grid(row = 1, column = 1, pady = (10, 0))
DC2_path_label.grid(row = 3, column = 1, pady = (10, 0))
DC2_B.grid(row = 4, column = 1, pady = (10, 0))

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

Result:

Update:

As far as changing your window there are several options for manipulating what is there and replacing the content.

You could destroy() the widgets and make new ones. Though this does not strike me as more elegant. It will allow you to keep the window open though.

There are some config options you can use to change the text of current widgets or rearrange the grid through a series of configs. Though this does not strike me as elegant either.

Title: Tkinter grouping buttons and lables

Body:
I want to create a GUI where you specify a bunch of files for later processing (commandline parsing a dozen files is just a PITA).

So now I want to group a lable and a button for better readability.

I've tried something like that:

DC1_path_label = Label(window_fine_DC, text = "Please specify the path of DC 1:", relief=RAISED)
DC1_B = Tkinter.Button(window_fine_DC, textvariable = DC_path1, command = setDC1)
DC2_path_label = Label(window_fine_DC, text="Please specify the path of DC 2:", relief=RAISED)
DC2_B = Tkinter.Button(window_fine_DC, textvariable=DC_path2, command=setDC2)

DC1_path_label.grid(row = 0, column = 1)
DC1_B.grid(row = 1, column = 1)
DC2_path_label.grid(row = 3, column = 1)
DC2_B.grid(row = 4, column = 1)

but it seems to have no effect, also paddings dont work that great either, since those go in all directions equally.

And while we are at it, is there a more elegant way to change a window than closing the old one, and opening a new?

Sorry if this is a stupid question, I'm fairly new with python/gui stuff...

Body:
I believe what you need is to provide a tuple to your padx and/or pady.

You can specify padding for each side this way.

I use pady as an example here to show how you can provide padding on only one side. Notice how the top Label is padded at its top but the bottom button is not padded on the bottom side.

from tkinter import *

root = Tk()

DC1_path_label = Label(root, text = "Please specify the path of DC 1:", relief=RAISED)
DC1_B = Button(root)
DC2_path_label = Label(root, text="Please specify the path of DC 2:", relief=RAISED)
DC2_B = Button(root)

DC1_path_label.grid(row = 0, column = 1, pady = (10, 0))
DC1_B.grid(row = 1, column = 1, pady = (10, 0))
DC2_path_label.grid(row = 3, column = 1, pady = (10, 0))
DC2_B.grid(row = 4, column = 1, pady = (10, 0))

root.mainloop()

Result:

Update:

As far as changing your window there are several options for manipulating what is there and replacing the content.

You could destroy() the widgets and make new ones. Though this does not strike me as more elegant. It will allow you to keep the window open though.

There are some config options you can use to change the text of current widgets or rearrange the grid through a series of configs. Though this does not strike me as elegant either.


问:
Unsigned long in Java
Currently, I am using signed values, -2^63 to 2^63-1. Now I need the same range (2 * 2^64), but with positive values only. I found the java documentations mentioning unsigned long, which suits this use.

I tried to declare 2^64 to a Long wrapper object, but it still loses the data, in other words, it only captures till the Long.MAX_VALUE, so I am clearly missing something.
Is BigInteger the signed long that Java supports?

Is there a definition or pointer as to how to declare and use it?

答:
Although Java has no unsigned long type, you can treat signed 64-bit two's-complement integers (i.e. long values) as unsigned if you are careful about it.

Many primitive integer operations are sign agnostic for two's-complement representations.   For example, you can use Java primitive addition, subtraction and multiplication on an unsigned number represented as a long, and get the "right" answer.

For other operations such as division and comparison, the Long class provides method like divideUnsigned and compareUnsigned that will give the correct results for unsigned numbers represented as long values.

The Long methods supporting unsigned operations were added in Java 8.  Prior to that, you could use 3rd-party libraries to achieve the same effect.  For example, the static methods in the Guava UnsignedLongs class.

Is BigInteger the signed long that Java supports?

BigInteger would be another way to represent integer values greater that Long.MAX_VALUE.  But BigInteger is a heavy-weight class.  It is unnecessary if your numbers all fall within the range 0 to 264 - 1 (inclusive).

Title: Unsigned long in Java

ContentLicense: CC BY-SA 4.0


问:
How can I pass a structure down a tree (i.e. an inherited attribute) when using Visitor pattern?
I'm using the C++ version of ANTLR4 to develop a DSL for a music product. I used to (30 years ago!) do this kind of thing by hand so it's mostly a pleasure to have something like ANTLR, particularly now that I don't have to insert code in the actual grammar definition itself.

I want to do type checking of actual vs formal args in a function call. In the grammar segment below, the 'actualParameter' can return the type of the expression. However, the 'actualParameterList' needs to return an array (say) of these types so that the code for functionCall can compare to the formal parameter list.

If I was handwriting this, the calls to visit or visitChildren would take an extra parameter after context such that I could create a new array at the appropriate place and then have child nodes fill in the details.

I suppose that instead of just calling visitChildren inside the 'visitActualParameterList' I could create the array there and manually call each child rather than just a simple visitChildren but that feels like a hack, and it becomes very sensitive to minor changes in the grammar.

Is there a better approach?

```<code>functionCall: Identifier LeftParen actualParameterList? RightParen
;

actualParameterList:
   actualParameter anotherActualParameter
;

actualParameter:
   expression
;

anotherActualParameter:
  Comma actualParameter anotherActualParameter
|
;
</code>```

答:
You're on the right path.  I would suggest something like:

```<code>functionCall: Identifier LPAREN actualParameterList RPAREN
;

actualParameterList:
    actualParameter (',' actualParameter)*
;

actualParameter:
   expression
;

LPAREN : '(';
RPAREN : ')';
</code>```

Using this, in the Visitor for actualParameterList you can check each child to see if it's of type actualParameterContext and if so, explicitly call Visit on that child, which will get you into your expression evaluation code (presumably handled in the visitor for actualParameter).  This alleviates the need, as you say, to just generically visit children.  It's very precise when you can check the type like this.

Here's an example of this pattern from my own code (in C# but surely you'll see the pattern in action):

```<code>for (int c = 0; c < context.ChildCount; c++)
{
    if (context.GetChild(c) is SystemParser.ServerContext) // make sure correct type
    {
        string serverinfo = Visit(context.GetChild(c));  // visit the specific child and save return value, string in this case
        sb.Append(serverinfo); // use result to fill array or do whatever
    }
}
</code>```

Now that you can see the pattern, back to your code.  The syntax:

```<code>actualParameter (',' actualParameter)*
</code>```

means that a parameter list has one actualParameter followed by zero or more additional ones with the * operator.  I just threw the comma in there for visual clarity.

As you suggest, Visitor is the perfect pattern for this because you can explicitly visit any node you need to.  It won't give you an array, but you can fill an array or any other necessary structure with the results of the visiting the children as you saw in the snip from my code.  My Visitor returns strings, and I just appended to a StringBuilder.  You can use the same pattern to build whatever you need.

Body:
I'm using the C++ version of ANTLR4 to develop a DSL for a music product. I used to (30 years ago!) do this kind of thing by hand so it's mostly a pleasure to have something like ANTLR, particularly now that I don't have to insert code in the actual grammar definition itself.

I want to do type checking of actual vs formal args in a function call. In the grammar segment below, the 'actualParameter' can return the type of the expression. However, the 'actualParameterList' needs to return an array (say) of these types so that the code for functionCall can compare to the formal parameter list.

If I was handwriting this, the calls to visit or visitChildren would take an extra parameter after context such that I could create a new array at the appropriate place and then have child nodes fill in the details.

I suppose that instead of just calling visitChildren inside the 'visitActualParameterList' I could create the array there and manually call each child rather than just a simple visitChildren but that feels like a hack, and it becomes very sensitive to minor changes in the grammar.

Is there a better approach?

functionCall: Identifier LeftParen actualParameterList? RightParen
;

actualParameterList:
   actualParameter anotherActualParameter
;

actualParameter:
   expression
;

anotherActualParameter:
  Comma actualParameter anotherActualParameter
|
;

Body:
You're on the right path.  I would suggest something like:

functionCall: Identifier LPAREN actualParameterList RPAREN
;

actualParameterList:
    actualParameter (',' actualParameter)*
;

actualParameter:
   expression
;

LPAREN : '(';
RPAREN : ')';

Using this, in the Visitor for actualParameterList you can check each child to see if it's of type actualParameterContext and if so, explicitly call Visit on that child, which will get you into your expression evaluation code (presumably handled in the visitor for actualParameter).  This alleviates the need, as you say, to just generically visit children.  It's very precise when you can check the type like this.

Here's an example of this pattern from my own code (in C# but surely you'll see the pattern in action):

for (int c = 0; c < context.ChildCount; c++)
{
    if (context.GetChild(c) is SystemParser.ServerContext) // make sure correct type
    {
        string serverinfo = Visit(context.GetChild(c));  // visit the specific child and save return value, string in this case
        sb.Append(serverinfo); // use result to fill array or do whatever
    }
}

Now that you can see the pattern, back to your code.  The syntax:

actualParameter (',' actualParameter)*

means that a parameter list has one actualParameter followed by zero or more additional ones with the * operator.  I just threw the comma in there for visual clarity.

As you suggest, Visitor is the perfect pattern for this because you can explicitly visit any node you need to.  It won't give you an array, but you can fill an array or any other necessary structure with the results of the visiting the children as you saw in the snip from my code.  My Visitor returns strings, and I just appended to a StringBuilder.  You can use the same pattern to build whatever you need.


问:
Visual Studio 2015 Import d3 Cannot Find Module 'd3'
I am developing an Angular project which uses d3 (v4) in some of its components. I am using Visual Studio 2015 (Update 3) and I have Typescript for Visual Studio v1.8.36.0 installed. I have Node v6.10.2 installed.

I have installed d3 both by editing my package.json file directly and by performing an npm install --save. I have "d3": "^4.9.1" listed in my package.json file.

My project uses Webpack and in my webpack.config.vendor.js file in the vendor section I have 'd3' listed.

I checked in my project's node_modules folder and within @types I can see the top level d3 folder and all the individual d3 module's type definitions. Also all of the d3 framework folders are within node_modules.

D3 is working fine, I just have no intellisense and my import setting import * as d3 from "d3"; displays an error under "d3" saying 'cannot find module d3'.

Curiously I also work on this project on a Mac laptop running Windows 7 and Visual Studio 2015 and everything is fine on that computer when I sync up the project in Team Explorer and continue working.

I have followed many suggestions to try and sort this out but nothing yet has helped. Can anyone suggest what I am missing please?

答: Eventually this problem was fixed by re-installing Typescript for Visual Studio.</p>


问:
Cannot run nodejs script in command prompt
When I try to run a node.js program in Windows command prompt by stating its location, it will invariably say:

[stated location] is not recognized as an internal or external command, operable program or batch file.

In all answers to similar questions, in all node.js manuals, it is assumed you can just run a node.js file by calling it from its location. There will always be the suggestion of trying some hello world example BEFORE establishing a server and so on.

Even if I clean the command prompt with prompt $ cmd, and then write the whole location manually, I get the same message.

When I run

```<code>echo %path%
</code>```

I get C:\Program Files\nodejs\bin

When I run

```<code>node -v
</code>```

I get v6.10.3

When I run

```<code>node a00.js
</code>```

(where a00.js is the script's name), it believes the whole path is a module, so it says it cannot recognize that module.

If I clear the command prompt with prompt $ cmd and then run node a00.js, it believes a00.js to be a module, so it says it cannot recognize that module.

答:
Your path knows where node.js is, but it does not know where a00.js is. So you need to run the command as node followed by the path to file. (copy all commands including the double quotes)

```<code>node "C:\Program Files\nodejs\a00.js"
</code>```

As an example, try this.

create a file called hello.js save it in C:\Windows\Temp\ (or where you prefer)

```<code>var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
</code>```

now open cmd and run it like this (assuming you saved it in C:\Windows\Temp\

```<code>node "c:\Windows\Temp\hello.js"
</code>```

if you run it from path, meaning you CD to the directory where the a00.js file exists, then only can you run it as `node a00.js

as an example, assuming a00.js exists in C:\Windows\Temp:

```<code>cd c:\Windows\Temp
node a00.js
</code>```

Important note when using any path, always enclose it in double quotes.

This will cause errors:

```<code>node C:\Program Files\test\a00.js
</code>```

This will work:

```<code>node "C:\Program Files\test\a00.js"
</code>```

Body:
When I try to run a node.js program in Windows command prompt by stating its location, it will invariably say:

[stated location] is not recognized as an internal or external command, operable program or batch file.

In all answers to similar questions, in all node.js manuals, it is assumed you can just run a node.js file by calling it from its location. There will always be the suggestion of trying some hello world example BEFORE establishing a server and so on.

Even if I clean the command prompt with prompt $ cmd, and then write the whole location manually, I get the same message.

When I run

echo %path%

I get C:\Program Files\nodejs\bin

When I run

node -v

I get v6.10.3

When I run

node a00.js

(where a00.js is the script's name), it believes the whole path is a module, so it says it cannot recognize that module.

If I clear the command prompt with prompt $ cmd and then run node a00.js, it believes a00.js to be a module, so it says it cannot recognize that module.

Body:
Your path knows where node.js is, but it does not know where a00.js is. So you need to run the command as node followed by the path to file. (copy all commands including the double quotes)

node "C:\Program Files\nodejs\a00.js"

As an example, try this.

create a file called hello.js save it in C:\Windows\Temp\ (or where you prefer)

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');

now open cmd and run it like this (assuming you saved it in C:\Windows\Temp\

node "c:\Windows\Temp\hello.js"

if you run it from path, meaning you CD to the directory where the a00.js file exists, then only can you run it as `node a00.js

as an example, assuming a00.js exists in C:\Windows\Temp:

cd c:\Windows\Temp
node a00.js

Important note when using any path, always enclose it in double quotes.

This will cause errors:

node C:\Program Files\test\a00.js

This will work:

node "C:\Program Files\test\a00.js"


问:
Using multiple test directorys Java / Maven
i got a Java project which has multiple test directorys at resources.

```<code>\target\test-classes
                   |___conf
                   |      |_ items...
                   |___otherdata
                          |_ items...
</code>```

I need to access \target\test-classes at it's root, so I can switch between directories since a testcase uses files from BOTH directories at once.

Tried:

```<code>File targetClassesDir = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
File targetDir = targetClassesDir.getParentFile();
</code>```

and

```<code>getClass().getResource("test-classes").getPath()
</code>```

but counldn't access the root of test-classes yet.

I've constructed a pretty shitty workaround...:

```<code>tuple4TestsuiteContainer.add(new HeaderBodyPayloadTestcase(
                                    "conf\\" + xqueries[0],
                                    getClass().getResource("/").getPath(),
                                    "xquery-testdata\\" + file.substring(file.lastIndexOf(File.separatorChar) + 1),
                                    "xquery-testdata\\" +expectedFiles[0].substring(expectedFiles[0].lastIndexOf(File.separatorChar) + 1)
                            ));
</code>```

and in the actual tester:

```<code>String xqueryFileContent = readFile(testDataBasePath + xQueryUnderTestPath, encoding);
</code>```

答:
I'm also not sure about your use case and project setup (Maven?), but in my opinion you shouldn't access any files in target/test-classes explicitly at all and load resources using the ClassLoader from resource folders.

How to get the path of src/test/resources directory in JUnit?

Body:
i got a Java project which has multiple test directorys at resources.

\target\test-classes
                   |___conf
                   |      |_ items...
                   |___otherdata
                          |_ items...

I need to access \target\test-classes at it's root, so I can switch between directories since a testcase uses files from BOTH directories at once.

Tried:

File targetClassesDir = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
File targetDir = targetClassesDir.getParentFile();

and

getClass().getResource("test-classes").getPath()

but counldn't access the root of test-classes yet.

I've constructed a pretty shitty workaround...:

tuple4TestsuiteContainer.add(new HeaderBodyPayloadTestcase(
                                    "conf\\" + xqueries[0],
                                    getClass().getResource("/").getPath(),
                                    "xquery-testdata\\" + file.substring(file.lastIndexOf(File.separatorChar) + 1),
                                    "xquery-testdata\\" +expectedFiles[0].substring(expectedFiles[0].lastIndexOf(File.separatorChar) + 1)
                            ));

and in the actual tester:

String xqueryFileContent = readFile(testDataBasePath + xQueryUnderTestPath, encoding);


问:
Uploading Attched files to temp directory before sending email
Trying to upload files attached to the mailing form to the temporary directory on the server before sending email with multiple attachments.

HTML

```<code>        <div class="file-upload-wrapper">
            <label class="file-field" data-max-files="6">
                <input type="file" name="photos" multiple>
                <span>Drag your files here or click to select your files <span>.jpg, .png and .pdf</span></span>
            </label>
            <div class="uploaded-files"></div>
        </div>
</code>```

Path to directory

```<code>$path_to_holding_directory = "/var/www/vhosts/mysite/test.mysite.com/bin/";
</code>```

bin folder has “777” permissions

PHP Script

```<code>    function rearrange( $arr ){
    foreach( $arr as $key => $all ){
        foreach( $all as $i => $val ){
            $new[$i][$key] = $val;
        }
    }
    return $new;
}

if(isset($_FILES['photos']))
{
    $_photos = rearrange($_FILES['photos']);

    foreach($_photos as $file)
    {
        $path_of_uploaded_file = $path_to_holding_directory . $file['name'];
        $tmp_path = $file["tmp_name"];

        if(is_uploaded_file($tmp_path))
        {
            if(!copy($tmp_path,$path_of_uploaded_file))
            {
                $errors .= '\n error while copying the uploaded file';
            }
        }

        print_r($file);

        $message .= $file['name'];
    }
}
</code>```

I get the following array:

```<code>Array
(
    [name] => gr-1.jpg
    [type] => image/jpeg
    [tmp_name] => /tmp/phpc7s2Ug
    [error] => 0
    [size] => 41253
)
Array
(
    [name] => gr-2.jpg
    [type] => image/jpeg
    [tmp_name] => /tmp/php6qLSeb
    [error] => 0
    [size] => 51475
)
</code>```

I am trying to do this with multiple files, but so far no success. The solution that I am trying to implement was found here enter link description here

答:
Your input field is not marked as an array:
<input type="file" name="photos" multiple>

This way it can't hold multiple file values even though you can select it using the file picker. Just name the field as photos[]. After posting you'll get an array like this:

```<code>Array
(
    [photos] => Array
        (
            [name] => Array
                (
                    [0] => image1.jpg
                    [1] => image2.gif
                )
            // ... more values
        )
)
</code>```

However, I see you're also using a drop target. I don't know what plugin it is, but if you're still facing issues I think you should refer to the creators of the plugin. If it's not a plugin but instead you created it yourself, create a separate question with code to get help.

Body:
Trying to upload files attached to the mailing form to the temporary directory on the server before sending email with multiple attachments.

HTML

                <input type="file" name="photos" multiple>
                Drag your files here or click to select your files .jpg, .png and .pdf

Path to directory

$path_to_holding_directory = "/var/www/vhosts/mysite/test.mysite.com/bin/";

bin folder has “777” permissions

PHP Script

    function rearrange( $arr ){
    foreach( $arr as $key => $all ){
        foreach( $all as $i => $val ){
            $new[$i][$key] = $val;
        }
    }
    return $new;
}

if(isset($_FILES['photos']))
{
    $_photos = rearrange($_FILES['photos']);

    foreach($_photos as $file)
    {
        $path_of_uploaded_file = $path_to_holding_directory . $file['name'];
        $tmp_path = $file["tmp_name"];

        if(is_uploaded_file($tmp_path))
        {
            if(!copy($tmp_path,$path_of_uploaded_file))
            {
                $errors .= '\n error while copying the uploaded file';
            }
        }

        print_r($file);

        $message .= $file['name'];
    }
}

I get the following array:

Array
(
    [name] => gr-1.jpg
    [type] => image/jpeg
    [tmp_name] => /tmp/phpc7s2Ug
    [error] => 0
    [size] => 41253
)
Array
(
    [name] => gr-2.jpg
    [type] => image/jpeg
    [tmp_name] => /tmp/php6qLSeb
    [error] => 0
    [size] => 51475
)

I am trying to do this with multiple files, but so far no success. The solution that I am trying to implement was found here enter link description here

Body:
Your input field is not marked as an array:
<input type="file" name="photos" multiple>

This way it can't hold multiple file values even though you can select it using the file picker. Just name the field as photos[]. After posting you'll get an array like this:

Array
(
    [photos] => Array
        (
            [name] => Array
                (
                    [0] => image1.jpg
                    [1] => image2.gif
                )
            // ... more values
        )
)

However, I see you're also using a drop target. I don't know what plugin it is, but if you're still facing issues I think you should refer to the creators of the plugin. If it's not a plugin but instead you created it yourself, create a separate question with code to get help.


问:
Android: Integrating Crashlytics to Android Library which will be distributed as AAR
We are building an Android SDK for some of our clients which will be distributed as an AAR. We want to integrate Crashlytics or some other crash reporting SDK to our SDK so that if any crash happens in our SDK, it gets reported to us(not to the client).

Our clients should be fine with adding the link of Fabric's maven repository in the project's build.gradle.

I want to understand if there is a way to do so??

Here Mike(a developer from Fabric) suggests that it is not possible and is not recommended without parent app being the deciding factor for initializing Fabric. In that case, if parent app is initializing the Crashlytics, will it work?

答:
Mike (again) from Fabric.

Let me clarify that including Fabric in an SDK that is distributed to other apps will cause issues both for the app and your SDK. Do not ship Fabric in externally distributed SDKs.


问:
span class locator is not visible/clickable - selenium
Following is the HTML for span: </p>

```<code><td class="header-logout-btn">
 <a href="logout.htm" class="btn switch-btn">
  <i class="fa fa-times"></i><span class="hidden-xs">Home</span>
 </a>
</td>
</code>```

<p>Tried with: </p>

```<code>driver.findElement(By.linkText("HOME"));
driver.findElement(By.xpath("//div[@class="header-logout-btn"]/span[@class="hidden-xs"]));
driver.findElement(By.xpath("//span"));
driver.findElement(By.className("hidden-xs"));
</code>```

答:
Try clicking on the link.

Use selectors like:

xpath:
  //a[contains(@href, 'logout')] or

  //*[@class='header-logout-btn']/a[contains(@href, 'logout')]

css:

a[href*=logout] or

.header-logout-btn a[href*=logout]

Body:
Following is the HTML for span:

  Home

Tried with:

driver.findElement(By.linkText("HOME"));
driver.findElement(By.xpath("//div[@class="header-logout-btn"]/span[@class="hidden-xs"]));
driver.findElement(By.xpath("//span"));
driver.findElement(By.className("hidden-xs"));


问:
Refreshing a div every 30 second with JavaScript
I'm trying to automatically update a div every 30 seconds.

```<code><script type="text/javascript">

    function refresh_handler() {
        function refresh() {
           $.get('/refresh/3', function(result) {
               $(".roek").innerHtml = result;
               console.log(result);
           });
        }
        setInterval(refresh, 3000); //every 5 minutes
    }

    $(document).ready(refresh_handler);

</script>
</code>```

Here I'm trying to refresh the div every 30 seconds.

```<code><div class="col-md-12">
    <div class="roek">
        @foreach ($hours as $hour)
            @if ($hour->repeat_day === "Monday")
                <p>
                    <div class="col-md-3">
                        <b> Day: </b> {{ $hour->repeat_day }} <a href="/deletehour/{{ $hour->id }}"> <span class="glyphicon glyphicon-info-sign" aria-hidden="true" style="color: cyan"></span></a> <br>

                        <b> Start: </b> {{ strftime("%H:%M", strtotime($hour->starttime))}} <br>
                        <b> End: </b> {{ strftime("%H:%M", strtotime($hour->endtime))}} <br>
                    </div>
                </p>
            @endif
        @endforeach
    </div>
</div>
</code>```

Currently it's trying to refresh the Div but it doesn't update it on the refresh.
In my web.php I have the following:

```<code>Route::get('/refresh/{id}', 'RefreshController@workhoursrefresh');
</code>```

And this is the query I'm using after the refresh:

```<code>//show all standard workhours per specific user
public function workhoursrefresh()
{
    $hours = Availability::FindAvailabilitys()->where([['user_id', '=', Auth::id()],
                                                       ['type', '=', 'standard']])
                                              ->orderBy('starttime', 'asc')
                                              ->get();
}
</code>```

答:
```<code><script type="text/javascript">

    function refresh_handler() {
        function refresh() {
            $.get('/refresh/3', function(result) {
                $(".roek").innerHtml = result;
                console.log(result);
            });
        }
        setInterval(refresh, 3000); //every 3 second for 30 second replace it with 30000
    }

    $(document).ready(refresh_handler);

</script>
</code>```

Body:
I'm trying to automatically update a div every 30 seconds.

Here I'm trying to refresh the div every 30 seconds.

        @foreach ($hours as $hour)
            @if ($hour->repeat_day === "Monday")

                         Day:  {{ $hour->repeat_day }} id }}">

                         Start:  {{ strftime("%H:%M", strtotime($hour->starttime))}}

                         End:  {{ strftime("%H:%M", strtotime($hour->endtime))}}

            @endif
        @endforeach

Currently it's trying to refresh the Div but it doesn't update it on the refresh.
In my web.php I have the following:

Route::get('/refresh/{id}', 'RefreshController@workhoursrefresh');

And this is the query I'm using after the refresh:

//show all standard workhours per specific user
public function workhoursrefresh()
{
    $hours = Availability::FindAvailabilitys()->where([['user_id', '=', Auth::id()],
                                                       ['type', '=', 'standard']])
                                              ->orderBy('starttime', 'asc')
                                              ->get();
}


问:
Looking for a Specific Cocoa Logging Framework
Lately there was a really nice Cocoa logging framework around. It had a GUI so you can log images and a nice presentation for data blobs etc. But I can't remember the name and cant find it with google.

Anyone knows which framework I'm looking for? A link to it would do it. thx.

-edit-

Its not:

cocoalumberjack

Log4Cocoa

SOLogger

答: Found It!!! It was NSLogger https://github.com/fpillet/NSLogger</p>

ContentLicense: CC BY-SA 2.5


问:
Particle swarm optimization and function with several parameters
I would like to optimize a function with several parameters using Particle swarm optimization. How can i do it? Everywhere I found this formula 1, but how can I understand this formula, I can optimize a function with only one variable. For example, I have a function with 2 parameters and I want to maximize it. How can I do it with PSO?

vi,d ← ω vi,d + φp rp (pi,d-xi,d) + φg rg (gd-xi,d)

```<code>function (x, y)
{
    return x + y
}
</code>```

答:
Since you have just 2 variable to optimize, your search space would be two dimensional. Assume that you want to optimize parameters x1 and x2. Furthermore, x1 is in the range of [a1,b1] and x2 is in the range of [a2,b2]. First you need to initialize a random population of particles (say 30 particles) into the search space boundary and assign random values to velocity vectors (V). Afterwards, you need to evaluate the fitness of the all particles and determine the best particle (Global best). Then you should perform the main upading mechanism of PSO.
This link would be helpful:
http://yarpiz.com/50/ypea102-particle-swarm-optimization </p>

Body:
I would like to optimize a function with several parameters using Particle swarm optimization. How can i do it? Everywhere I found this formula 1, but how can I understand this formula, I can optimize a function with only one variable. For example, I have a function with 2 parameters and I want to maximize it. How can I do it with PSO?

vi,d ← ω vi,d + φp rp (pi,d-xi,d) + φg rg (gd-xi,d)

function (x, y)
{
    return x + y
}


问:
FuncOne() -and FuncTwo() not working
This is my code:

```<code>if (FuncOne($valOne) -and FuncTwo($valTwo)) {
    ...
}
</code>```

When both of those functions evaluate to $false, the code within the if statement still executes. Why is that? This also does not work as expected:

```<code>if (FuncOne($valOne) -eq $true -and FuncTwo($valTwo) -eq $true) {
    ...
}
</code>```

When written this way, it works as expected.

```<code>$a = FuncOne($valOne)
$b = FuncTwo($valTwo)

if($a -and $b) {
    ...
}
</code>```

What's going on?

答:
You actualy need to place the function in parenthese in order to invoke it:

```<code>if ((FuncOne($valOne)) -and (FuncTwo($valTwo))) {
    ...
}
</code>```

Title: FuncOne() -and FuncTwo() not working

Body:
This is my code:

if (FuncOne($valOne) -and FuncTwo($valTwo)) {
    ...
}

When both of those functions evaluate to $false, the code within the if statement still executes. Why is that? This also does not work as expected:

if (FuncOne($valOne) -eq $true -and FuncTwo($valTwo) -eq $true) {
    ...
}

When written this way, it works as expected.

$a = FuncOne($valOne)
$b = FuncTwo($valTwo)

if($a -and $b) {
    ...
}

What's going on?

Body:
You actualy need to place the function in parenthese in order to invoke it:

if ((FuncOne($valOne)) -and (FuncTwo($valTwo))) {
    ...
}


问:
Symfony 3 - Validations Constraints doesnt work
I have a problem with my validations, none of my validations work.
I followed the documentation, and put the right codes, but nothing done.. Here is one of my entities for example:

```<code><?php

namespace ProjectBundle\Entity\User;

use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use ProjectBundle\Entity\Traits\BlameableEntity;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity(repositoryClass="ProjectBundle\Repository\User\UserRepository")
 * @Gedmo\SoftDeleteable(fieldName="deletedAt")
 * @ORM\Entity
 * @ORM\UniqueEntity("email")
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{
    use TimestampableEntity;
    use SoftDeleteableEntity;
    use BlameableEntity;
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @Assert\NotBlank()
     * @Assert\Length(
     *      min = 2,
     *      max = 254,
     *      minMessage = "Votre nom d'utilisateut doit comporter au minimum {{ limit }} caractères.",
     *      maxMessage = "Votre nom d'utilisateut doit comporter au maximum {{ limit }} caractères."
     * )
     *
     * @var string
     */
    protected $username;

    /**
     * @Assert\NotBlank()
     * @Assert\Length(
     *      min = 2,
     *      max = 254,
     *      minMessage = "Votre nom d'utilisateut doit comporter au minimum {{ limit }} caractères.",
     *      maxMessage = "Votre nom d'utilisateut doit comporter au maximum {{ limit }} caractères."
     * )
     *
     * @var string
     */
    protected $plainPassword;

    /**
     * @Assert\NotBlank()
     *
     * @Assert\Email(
     *     message = "L'adresse mail '{{ value }}' n'est pas valide.",
     *     checkMX = true
     * )
     *
     * @var string
     */
    protected $email;

    /**
     * @var string
     * @Assert\NotBlank()
     *
     * @ORM\Column(name="lastname", type="string", length=100)
     */
    private $lastname;

    /**
     * @var string
     * @Assert\NotBlank()
     *
     * @ORM\Column(name="firstname", type="string", length=100)
     */
    private $firstname;
</code>```

And of course this error (for example) : Integrity constraint violation: 1048 Column 'lastname' cannot be null
When i submit my form.

In my config.yml i have :  validation:      { enable_annotations: true }

And in my controller :

```<code>    /**
     * @Route("/new", name="admin_user_new")
     * @Security("has_role('ROLE_USER')")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function newAction(Request $request)
    {

        $entity = new User();
        $form = $this->createForm('ProjectBundle\Form\User\User', $entity);

        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->persist($entity);
                $em->flush();

                return $this->redirectToRoute('admin_user_show', array('id' => $entity->getId()));
            }
        }

        return $this->render('ProjectBundle:admin/User:new.html.twig', array(
            'entity' => $entity,
            'form' => $form->createView(),
        ));
    }
</code>```

On my other projects it works well, but I do not see what I forgot.

Do you have an idea ?
Thanks

答:
Add nullable = true to allow a field blank

```<code>    /**
 * @var string
 * @Assert\NotBlank()
 *
 * @ORM\Column(name="lastname", type="string", length=100, nullable = true)
 */
private $lastname;
</code>```

EDIT:

```<code>if ($form->isSubmitted()) {
        if ($form->isValid()) {

            $entity = $form->getData();
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirectToRoute('admin_user_show', array('id' => $entity->getId()));
        }
    }
</code>```

Body:
I have a problem with my validations, none of my validations work.
I followed the documentation, and put the right codes, but nothing done.. Here is one of my entities for example:

<?php

namespace ProjectBundle\Entity\User;

use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use ProjectBundle\Entity\Traits\BlameableEntity;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity(repositoryClass="ProjectBundle\Repository\User\UserRepository")
 * @Gedmo\SoftDeleteable(fieldName="deletedAt")
 * @ORM\Entity
 * @ORM\UniqueEntity("email")
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{
    use TimestampableEntity;
    use SoftDeleteableEntity;
    use BlameableEntity;
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @Assert\NotBlank()
     * @Assert\Length(
     *      min = 2,
     *      max = 254,
     *      minMessage = "Votre nom d'utilisateut doit comporter au minimum {{ limit }} caractères.",
     *      maxMessage = "Votre nom d'utilisateut doit comporter au maximum {{ limit }} caractères."
     * )
     *
     * @var string
     */
    protected $username;

    /**
     * @Assert\NotBlank()
     * @Assert\Length(
     *      min = 2,
     *      max = 254,
     *      minMessage = "Votre nom d'utilisateut doit comporter au minimum {{ limit }} caractères.",
     *      maxMessage = "Votre nom d'utilisateut doit comporter au maximum {{ limit }} caractères."
     * )
     *
     * @var string
     */
    protected $plainPassword;

    /**
     * @Assert\NotBlank()
     *
     * @Assert\Email(
     *     message = "L'adresse mail '{{ value }}' n'est pas valide.",
     *     checkMX = true
     * )
     *
     * @var string
     */
    protected $email;

    /**
     * @var string
     * @Assert\NotBlank()
     *
     * @ORM\Column(name="lastname", type="string", length=100)
     */
    private $lastname;

    /**
     * @var string
     * @Assert\NotBlank()
     *
     * @ORM\Column(name="firstname", type="string", length=100)
     */
    private $firstname;

And of course this error (for example) : Integrity constraint violation: 1048 Column 'lastname' cannot be null
When i submit my form.

In my config.yml i have :  validation:      { enable_annotations: true }

And in my controller :

    /**
     * @Route("/new", name="admin_user_new")
     * @Security("has_role('ROLE_USER')")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function newAction(Request $request)
    {

        $entity = new User();
        $form = $this->createForm('ProjectBundle\Form\User\User', $entity);

        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->persist($entity);
                $em->flush();

                return $this->redirectToRoute('admin_user_show', array('id' => $entity->getId()));
            }
        }

        return $this->render('ProjectBundle:admin/User:new.html.twig', array(
            'entity' => $entity,
            'form' => $form->createView(),
        ));
    }

On my other projects it works well, but I do not see what I forgot.

Do you have an idea ?
Thanks

Body:
Add nullable = true to allow a field blank

    /**
 * @var string
 * @Assert\NotBlank()
 *
 * @ORM\Column(name="lastname", type="string", length=100, nullable = true)
 */
private $lastname;

EDIT:

if ($form->isSubmitted()) {
        if ($form->isValid()) {

            $entity = $form->getData();
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirectToRoute('admin_user_show', array('id' => $entity->getId()));
        }
    }


问:
Android | Google PlacePicker API. OnActivityResult code not executed [Really weird behaviour]
I've a Fragment (support.v4) in a ViewPager with the which calls PlacePicker UI and then updated on a TextView. My code is as follows,

```<code>public void openPlacePicker() {
    try {
        PlacePicker.IntentBuilder intentBuilder = new PlacePicker.IntentBuilder();
        Intent intent = intentBuilder.build(getContext());
        // Start the Intent by requesting a result, identified by a request code.
        startActivityForResult(intent, PLACE_PICKER);

    } catch (GooglePlayServicesRepairableException e) {
        GooglePlayServicesUtil
                .getErrorDialog(e.getConnectionStatusCode(), getActivity(), 0);
    } catch (GooglePlayServicesNotAvailableException e) {
        Toast.makeText(getContext(), "Google Play Services is not available.",
                Toast.LENGTH_LONG)
                .show();
    }
}
</code>```

And the OnActivityResult is,

```<code> @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.i(TAG, "Request Code:" + requestCode);//This is printed
    if(requestCode == PLACE_PICKER){
        Log.d(TAG,"Reached in if()"); //Never printed
    }
    switch (requestCode) { //Never reached
        case PLACE_PICKER:
            if (resultCode == Activity.RESULT_OK) {
                final Place place = PlacePicker.getPlace(data, getContext());
                final CharSequence name = place.getName();
                //EventBus.getDefault().post(new NotifyEvent(NotifyEvent.NotifyType.PLACE_PICKED, (String) name));
            }
    }
}
</code>```

So the problem is that, the conditional statements never gets executed. The Log before if() is printed. But the Log inside the if() is not printed.

Weird thing is the android-place-picker sample from GitHub is working fine.

I have tried the following:

Clean Project

Clear Data and re-install on device

IDE clear cache and restart

Any ideas?

--EDIT--
Manifest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.apps.maps">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="com.apps.maps.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <permission android:name="com.apps.maps.permission.MAPS_RECEIVE" android:protectionLevel="signature" />
    <application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme">
        <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" />
        <activity android:name=".activity.MainActivity" android:label="@string/title_activity_maps">
        </activity>
    </application>
</manifest>
</code>```

答: I know this is an older thread but it has helped me to resolve a similar issue to the original problem.  Raman Bhavsar's 10/10/15 comment was the right question to ask.  I had forgotten to enable the Places API in the Google Developer Console, and once I did I was able to hit my breakpoint in the onActivityResult method.</p>

Body:
I've a Fragment (support.v4) in a ViewPager with the which calls PlacePicker UI and then updated on a TextView. My code is as follows,

public void openPlacePicker() {
    try {
        PlacePicker.IntentBuilder intentBuilder = new PlacePicker.IntentBuilder();
        Intent intent = intentBuilder.build(getContext());
        // Start the Intent by requesting a result, identified by a request code.
        startActivityForResult(intent, PLACE_PICKER);

    } catch (GooglePlayServicesRepairableException e) {
        GooglePlayServicesUtil
                .getErrorDialog(e.getConnectionStatusCode(), getActivity(), 0);
    } catch (GooglePlayServicesNotAvailableException e) {
        Toast.makeText(getContext(), "Google Play Services is not available.",
                Toast.LENGTH_LONG)
                .show();
    }
}

And the OnActivityResult is,

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.i(TAG, "Request Code:" + requestCode);//This is printed
    if(requestCode == PLACE_PICKER){
        Log.d(TAG,"Reached in if()"); //Never printed
    }
    switch (requestCode) { //Never reached
        case PLACE_PICKER:
            if (resultCode == Activity.RESULT_OK) {
                final Place place = PlacePicker.getPlace(data, getContext());
                final CharSequence name = place.getName();
                //EventBus.getDefault().post(new NotifyEvent(NotifyEvent.NotifyType.PLACE_PICKED, (String) name));
            }
    }
}

So the problem is that, the conditional statements never gets executed. The Log before if() is printed. But the Log inside the if() is not printed.

Weird thing is the android-place-picker sample from GitHub is working fine.

I have tried the following:

Clean Project

Clear Data and re-install on device

IDE clear cache and restart

Any ideas?

--EDIT--
Manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.apps.maps">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="com.apps.maps.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <permission android:name="com.apps.maps.permission.MAPS_RECEIVE" android:protectionLevel="signature" />
    <application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme">
        <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" />
        <activity android:name=".activity.MainActivity" android:label="@string/title_activity_maps">
        </activity>
    </application>
</manifest>


问:
Firemonkey app: monospace font in TMemo?
Is it possible to set/use a Monospace font in TMemo in a Firemonkey (developed with Delphi 10.2 Tokyo) application.

We tried:

```<code>TextSettings.Font.Family := 'Courier New';
TextSettings.Font.Family := 'Courier';
TextSettings.Font.Family := 'Monospace';
</code>```

But when we run the app in Android the text font is not monospace.

答:
I solved the issue in this way:</p>

```<code>{$IFDEF MSWINDOWS}
    Memo1.TextSettings.Font.Family := 'Courier New';
    Memo1.StyledSettings :=  Memo1.StyledSettings - [TStyledSetting.Family]
{$ENDIF}
{$IFDEF ANDROID}
    Memo1.TextSettings.Font.Family := 'monospace';
    Memo1.StyledSettings :=  Memo1.StyledSettings - [TStyledSetting.Family]
{$ENDIF}
</code>```

Body:
Is it possible to set/use a Monospace font in TMemo in a Firemonkey (developed with Delphi 10.2 Tokyo) application.

We tried:

TextSettings.Font.Family := 'Courier New';
TextSettings.Font.Family := 'Courier';
TextSettings.Font.Family := 'Monospace';

But when we run the app in Android the text font is not monospace.

Body:
I solved the issue in this way:

{$IFDEF MSWINDOWS}
    Memo1.TextSettings.Font.Family := 'Courier New';
    Memo1.StyledSettings :=  Memo1.StyledSettings - [TStyledSetting.Family]
{$ENDIF}
{$IFDEF ANDROID}
    Memo1.TextSettings.Font.Family := 'monospace';
    Memo1.StyledSettings :=  Memo1.StyledSettings - [TStyledSetting.Family]
{$ENDIF}


问:
Visual studio project dependency to other project doesn't copy exe
I have a C# solution (visual studio 2017) with two projects lets say A and B, both compiled to exe. Project A depends on project B's exe, I though a dependency to project B would solve this. However, the exe doesn't get copied automatically when build.

Does the dependencies not work for exe's ? Is the only solution to make an post build step ?

答: You can use the Post-build events ( Project properties -> Build Events ) to copy the file at the end of build.</p>


问:
PHP Search File
i m not sure on how to write a code to search for files in a folder. i have the code below to view all file from a folder call "FILES".

example of file have

```<code>abc-def.txt
ghi-jkl.txt
</code>```

so i would like to have like an input where if i enter like abc so it will search for all file which have abc in it and display out. is it possible ?

```<code>$thelist = "";
if ($handle = opendir('./files/')) {
  while (false !== ($file = readdir($handle))){
    if ($file != "." && $file != ".."){
      $thelist .= $file . '<br>';
    }
  }
  closedir($handle);
}
echo $thelist;
unset($thelist);
</code>```

i need help in it.

答:
There is a nice function glob to search by pattern:</p>

```<code>$pattern = filter_input(INPUT_POST, 'pattern', "*.txt", FILTER_SANITIZE_STRING);
foreach (glob($pattern) as $filename) {
    echo "$filename \n";
}
</code>```

Title: PHP Search File

Body:
i m not sure on how to write a code to search for files in a folder. i have the code below to view all file from a folder call "FILES".

example of file have

abc-def.txt
ghi-jkl.txt

so i would like to have like an input where if i enter like abc so it will search for all file which have abc in it and display out. is it possible ?

$thelist = "";
if ($handle = opendir('./files/')) {
  while (false !== ($file = readdir($handle))){
    if ($file != "." && $file != ".."){
      $thelist .= $file . '
';
    }
  }
  closedir($handle);
}
echo $thelist;
unset($thelist);

i need help in it.

Body:
There is a nice function glob to search by pattern:

$pattern = filter_input(INPUT_POST, 'pattern', "*.txt", FILTER_SANITIZE_STRING);
foreach (glob($pattern) as $filename) {
    echo "$filename \n";
}


问:
How to get Toolbar menu icon (Drawer opening menu) click event?
I want to do some operation when i click the menu (not a overflow menu) in Toolbar. How to detect the event of click menu or Opening DrawerLayout?

答:
```<code>toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // your stuff
    }
});
</code>```

See also Cannot catch toolbar home button click event

Body:
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // your stuff
    }
});

See also Cannot catch toolbar home button click event


问:
Google Apps Script Html Form Without Page Refresh
Currently, I am changing an app that I had built for my organization from UiService to HtmlService. This part isn't the hard part.

However, in the past iteration of the app, submitting the form obviously creates a refresh(?) or at least an elimination of the form from visibility. This was one of the biggest complaints for this app in particular for users who need to put in multiple entries at a time.

For my other apps, it was as simple as replacing the submit button with an onClick function. However, because this app Requires an attachment, I haven't found a way to have the form submit without refreshing the page. I have tried returning false; and other methods proposed for normal HTML/JavaScript based pages.

Is this a limitation with Google Apps Script HtmlService because of the Caja Sanitation or the iframe Sandbox?

答: So after doing some research, the answer was right under my nose. It was on Googles Best Practice for HtmlService.</p>


问:
Converting result of Math.sin(x) into a result for degrees in java
I would like to convert the Math.sin(x), where x in radians to a result which will give me as x in degrees not radians.

I have used the normal method and java built in method of conversion between degrees and radians,  but any argument I pass to the Math.sin() method is being treated as radians, thereby causing my conversion to be a futile effort.

I want the output of a sin Input to be given as if the input is treated in degrees not radians like the Math.sin() method does.

答:
If you want to print sin(90) degree value, you can use this code:</p>

```<code>double value = 90.0;
double radians = Math.toRadians(value);

System.out.format("The sine of %.1f degrees is %.4f%n", value, Math.sin(radians));
</code>```

Body:
If you want to print sin(90) degree value, you can use this code:

double value = 90.0;
double radians = Math.toRadians(value);

System.out.format("The sine of %.1f degrees is %.4f%n", value, Math.sin(radians));


问:
Can I wrap
 in something that doesn't influence table layout? (JSF2.0)
I have a
, and in it some
s. All is aligned as long as none
 is wrapped in
 or .

I have to wrap it because I'm using JSF and I have to render this row sometimes and sometimes not. Code is:

```<code><table>
<!-- some other TRs -->
<h:panelGroup id="wrapping">
  <h:panelGroup rendered="#{bean.render}">
    <tr>
      <th>
        Some label
      </th>
      <td>
        <h:inputText value="#{bean.value}" />
      </td>
    </tr>
  </h:panelGroup>
</h:panelGroup>
</table>
</code>```

I need the "wrapping" because when inner panelGroup is not rendered, I need some ID in HTML for ajax. I need also inner <h:panelGroup> because I have to use JSF rendered attribute somewhere, and I can't use it on
.

The problem is this way this row is wrapped in , and it is no more aligned with other rows. The same about
.

答:
Don't mix JSF and HTML tags like that. You're breaking abstractions all over the place and I bet you'll never get valid HTML that way (which is the reason why your layout breaks).

Instead of a HTML table, use a <h:panelGrid> and put the rendered attribute on the individual components of that row.

As for the ID, what do you need it for? If it's for JSF-supported Ajax, I don't think you can re-render just one row of a table. If you're doing "manual" Ajax, you could use the rowClasses attribute of the panelGrid to give one particular rendered
 a distinct class.

Title: Can I wrap <tr> in something that doesn't influence table layout? (JSF2.0)

Body:
I have a
, and in it some
s. All is aligned as long as none
 is wrapped in
 or .

I have to wrap it because I'm using JSF and I have to render this row sometimes and sometimes not. Code is:

<h:panelGroup id="wrapping">
  <h:panelGroup rendered="#{bean.render}">

        Some label

        <h:inputText value="#{bean.value}" />

  </h:panelGroup>
</h:panelGroup>

I need the "wrapping" because when inner panelGroup is not rendered, I need some ID in HTML for ajax. I need also inner <h:panelGroup> because I have to use JSF rendered attribute somewhere, and I can't use it on
.

The problem is this way this row is wrapped in , and it is no more aligned with other rows. The same about
.

Body:
Don't mix JSF and HTML tags like that. You're breaking abstractions all over the place and I bet you'll never get valid HTML that way (which is the reason why your layout breaks).

Instead of a HTML table, use a <h:panelGrid> and put the rendered attribute on the individual components of that row.

As for the ID, what do you need it for? If it's for JSF-supported Ajax, I don't think you can re-render just one row of a table. If you're doing "manual" Ajax, you could use the rowClasses attribute of the panelGrid to give one particular rendered <tr> a distinct class.


问:
JQuery disable inputs during ajax submitting
I'm creating a form using Django, JQuery and JQuery Form plugin (http://jquery.malsup.com/form/) and I want to disable my form's fields while waiting for server response. My code is:

```<code>$(document).ready(function () {
        $('#load').hide();
        $('#error').hide();
        $('#success').hide();
        var myForm = $(this).find('input'); //finding all inputs
        $('#save').live('click', function () {
            $('#save_form').ajaxSubmit({
                success:function (data, statusText, xhr, $form) {
                    alert('success');
                    $form.find('.error').remove();
                    if (data['result'] == 'success') {
                        $('#success').show("slow");
                    }
                    else if (data['result'] == 'error') {
                        $('#error').show("fast");
                        //calling procedure to show errors
                    }
                    $('#load').hide("fast");
                },
                beforeSubmit: function(arr, $form, options) {
                    $('#error').hide();
                    $('#success').hide();
                    $('#load').show("fast");
                    $(myForm).attr('disabled', true);
                    alert('before submit');
                    return true;
                },
                error: function() {
                    alert("Failed to submit!");
                    $('#load').hide("fast");
                },
                timeout: 3000,
                dataType:'json'
            });
        });
    })
</code>```

So when I press Save I see that inputs are disabled and I'm getting 'before submit' alertbox, but when I press OK all inputs become enabled even If i switch off responding server.

How can I make it work?

答:
I do think that disabling the form before submitting will stop the form submittion, but you can disable the input elementes in the form, this should give you the function you want.
eg. add a class like frmdis to every input in your form or to any other input element on the page.

```<code>$('#save').live('click', function () {

        $('.frmdis').prop('disabled', true);
        alert('before submit');

        $('#save_form').ajaxSubmit({
            success:function (data, statusText, xhr, $form) {
                $('.frmdis').prop('disabled', false);
                alert('success');
                $form.find('.error').remove();
                if (data['result'] == 'success') {
                    $('#success').show("slow");
                }
                else if (data['result'] == 'error') {
                    $('#error').show("fast");
                    //calling procedure to show errors
                }
                $('#load').hide("fast");
            },
</code>```

.
.
.

Body:
I'm creating a form using Django, JQuery and JQuery Form plugin (http://jquery.malsup.com/form/) and I want to disable my form's fields while waiting for server response. My code is:

$(document).ready(function () {
        $('#load').hide();
        $('#error').hide();
        $('#success').hide();
        var myForm = $(this).find('input'); //finding all inputs
        $('#save').live('click', function () {
            $('#save_form').ajaxSubmit({
                success:function (data, statusText, xhr, $form) {
                    alert('success');
                    $form.find('.error').remove();
                    if (data['result'] == 'success') {
                        $('#success').show("slow");
                    }
                    else if (data['result'] == 'error') {
                        $('#error').show("fast");
                        //calling procedure to show errors
                    }
                    $('#load').hide("fast");
                },
                beforeSubmit: function(arr, $form, options) {
                    $('#error').hide();
                    $('#success').hide();
                    $('#load').show("fast");
                    $(myForm).attr('disabled', true);
                    alert('before submit');
                    return true;
                },
                error: function() {
                    alert("Failed to submit!");
                    $('#load').hide("fast");
                },
                timeout: 3000,
                dataType:'json'
            });
        });
    })

So when I press Save I see that inputs are disabled and I'm getting 'before submit' alertbox, but when I press OK all inputs become enabled even If i switch off responding server.

How can I make it work?

Body:
I do think that disabling the form before submitting will stop the form submittion, but you can disable the input elementes in the form, this should give you the function you want.
eg. add a class like frmdis to every input in your form or to any other input element on the page.

$('#save').live('click', function () {

        $('.frmdis').prop('disabled', true);
        alert('before submit');

        $('#save_form').ajaxSubmit({
            success:function (data, statusText, xhr, $form) {
                $('.frmdis').prop('disabled', false);
                alert('success');
                $form.find('.error').remove();
                if (data['result'] == 'success') {
                    $('#success').show("slow");
                }
                else if (data['result'] == 'error') {
                    $('#error').show("fast");
                    //calling procedure to show errors
                }
                $('#load').hide("fast");
            },

.
.
.


问:
How to annotate Column as NOT NULL using Android Room Persistence Library
My data class looks like this

```<code>@Entity(tableName = "items")
data class Item(
        @ColumnInfo(name = "name") var name: String = "",
        @ColumnInfo(name = "room") var room: String = "",
        @ColumnInfo(name = "quantity") var quantity: String = "",
        @ColumnInfo(name = "description") var description: String = "",
        @PrimaryKey(autoGenerate = true)
        @ColumnInfo(name = "id") var id: Long = 0
)
</code>```

Room uses SQLite and SQLite supports NOT NULL columns in its database. I tried annotating columns with @NonNull but it has no effect.

Is there a way to make columns in Room Database not nullable?

答:
In order to identify exact annotation for NOT NULL I went through the list of all annotations provided at this link: android.arch.persistence.room but could not find any relevant annotation:

My assumption is that since you are using Kotlin, which by default treats a var as non-optional, all the attributes declared by you are NOT NULL. In order to declare a var as optional probably you have to use a ? operator, an example below:

```<code>var name: String // NOT NULL
var name: String? // OPTIONAL
</code>```

Updated based on comment:

I guess you are confused with NULL and empty string. NULL means no value, in the shared code you are providing a default value to each column which is an empty string and that is not equal to NULL, so even though you might not have provided a value for that attribute it is by default assigning an empty string to it.

Try removing value assignment operator and RHS value for an attribute and then insert the record without assigning value to that attribute, you should get appropriate error.

Basically, convert below statement:

```<code>@ColumnInfo(name = "name") var name: String = ""
</code>```

To

```<code>@ColumnInfo(name = "name") var name: String
</code>```

Body:
My data class looks like this

@Entity(tableName = "items")
data class Item(
        @ColumnInfo(name = "name") var name: String = "",
        @ColumnInfo(name = "room") var room: String = "",
        @ColumnInfo(name = "quantity") var quantity: String = "",
        @ColumnInfo(name = "description") var description: String = "",
        @PrimaryKey(autoGenerate = true)
        @ColumnInfo(name = "id") var id: Long = 0
)

Room uses SQLite and SQLite supports NOT NULL columns in its database. I tried annotating columns with @NonNull but it has no effect.

Is there a way to make columns in Room Database not nullable?

Body:
In order to identify exact annotation for NOT NULL I went through the list of all annotations provided at this link: android.arch.persistence.room but could not find any relevant annotation:

My assumption is that since you are using Kotlin, which by default treats a var as non-optional, all the attributes declared by you are NOT NULL. In order to declare a var as optional probably you have to use a ? operator, an example below:

var name: String // NOT NULL
var name: String? // OPTIONAL

Updated based on comment:

I guess you are confused with NULL and empty string. NULL means no value, in the shared code you are providing a default value to each column which is an empty string and that is not equal to NULL, so even though you might not have provided a value for that attribute it is by default assigning an empty string to it.

Try removing value assignment operator and RHS value for an attribute and then insert the record without assigning value to that attribute, you should get appropriate error.

Basically, convert below statement:

@ColumnInfo(name = "name") var name: String = ""

To

@ColumnInfo(name = "name") var name: String


问:
ASyncTask load GridView thumbnails loads latest file twice, then slowly loads from the top of the list
I'm using an ASyncTask to load my thumbnails in a GridView layout that I have, but when I refresh the data, the thumbnails load in an odd order. It always loads the last element first, but it renders it with the first elements thumbnail, then re-renders it with the proper thumbnail (the last elements), then it properly loads every other thumbnail from first to second-last. It also reloads the images many times and is fairly slow at loading them (16mp images however)

Here's my GridView adapter (with the ASyncTask).

```<code>public class ReceiptListAdapter extends ArrayAdapter {

    public ReceiptListAdapter(Context context, ArrayList<Receipt> receipts){
        super(context, 0, receipts);
//        getItem(1);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        // Check if an existing view is being reused, otherwise inflate the view
        ViewHolder holder;

        // Lookup view for data population
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.receipt_list_element, parent, false);
            holder = new ViewHolder();
            // Populate the data into the template view using the data object
            holder.title = (TextView) convertView.findViewById(R.id.TitleView);
            holder.date = (TextView) convertView.findViewById(R.id.DateView);
            holder.image = (ImageView) convertView.findViewById(R.id.containerImage);
            holder.spn = (ProgressBar) convertView.findViewById(R.id.spinner);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Receipt receipt = (Receipt) getItem(position);
        holder.imagePath = receipt.getFilepath();
        final int tWidth = receipt.getWidth();

        // manipulate data here...
        holder.spn.setVisibility(View.VISIBLE);
        holder.image.setVisibility(View.GONE);
        holder.title.setText(receipt.getDesc());

        new AsyncTask<ViewHolder, Void, Bitmap>() {

            private ViewHolder h;

            @Override
            protected Bitmap doInBackground(ViewHolder... t) {
                h = t[0];
                Bitmap thumb = ExifUtil.rotateBitmap(h.imagePath, ThumbnailUtils.extractThumbnail(
                        BitmapFactory.decodeFile(h.imagePath),
                        tWidth,
                        tWidth));
                return thumb;
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);

                    h.spn.setVisibility(View.GONE);
                    h.image.setVisibility(View.VISIBLE);
                    h.image.setImageBitmap(result);

            }
        }.execute(holder);

        // Return the completed view to render on screen
        return convertView;
    }

    static class ViewHolder {
        private TextView title;
        private TextView date;
        private ImageView image;
        private String imagePath;
        private ProgressBar spn;
    }

}
</code>```

答:
I have Replace your AsyncTask with Glide Library Update Your Code with
  below

```<code>public class ReceiptListAdapter extends ArrayAdapter {

        public ReceiptListAdapter(Context context, ArrayList<Receipt> receipts){
            super(context, 0, receipts);
//        getItem(1);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // Get the data item for this position
            // Check if an existing view is being reused, otherwise inflate the view
            ViewHolder holder;

            // Lookup view for data population
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.receipt_list_element, parent, false);
                holder = new ViewHolder();
                // Populate the data into the template view using the data object
                holder.title = (TextView) convertView.findViewById(R.id.TitleView);
                holder.date = (TextView) convertView.findViewById(R.id.DateView);
                holder.image = (ImageView) convertView.findViewById(R.id.containerImage);
                holder.spn = (ProgressBar) convertView.findViewById(R.id.spinner);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            Receipt receipt = (Receipt) getItem(position);
            holder.imagePath = receipt.getFilepath();
            final int tWidth = receipt.getWidth();

            // manipulate data here...
            holder.spn.setVisibility(View.VISIBLE);
            holder.image.setVisibility(View.GONE);
            holder.title.setText(receipt.getDesc());

            Glide.with(context)
                    .load(holder.imagePath)
                    .into(holder.image);

            /*new AsyncTask<ViewHolder, Void, Bitmap>() {

                private ViewHolder h;

                @Override
                protected Bitmap doInBackground(ViewHolder... t) {
                    h = t[0];
                    Bitmap thumb = ExifUtil.rotateBitmap(h.imagePath, ThumbnailUtils.extractThumbnail(
                            BitmapFactory.decodeFile(h.imagePath),
                            tWidth,
                            tWidth));
                    return thumb;
                }

                @Override
                protected void onPostExecute(Bitmap result) {
                    super.onPostExecute(result);

                    h.spn.setVisibility(View.GONE);
                    h.image.setVisibility(View.VISIBLE);
                    h.image.setImageBitmap(result);

                }
            }.execute(holder);*/

            // Return the completed view to render on screen
            return convertView;
        }

        static class ViewHolder {
            private TextView title;
            private TextView date;
            private ImageView image;
            private String imagePath;
            private ProgressBar spn;
        }

    }
</code>```

Open you build.gradle and add this dependency

```<code>compile 'com.github.bumptech.glide:glide:4.0.0-RC0'
</code>```

Body:
I'm using an ASyncTask to load my thumbnails in a GridView layout that I have, but when I refresh the data, the thumbnails load in an odd order. It always loads the last element first, but it renders it with the first elements thumbnail, then re-renders it with the proper thumbnail (the last elements), then it properly loads every other thumbnail from first to second-last. It also reloads the images many times and is fairly slow at loading them (16mp images however)

Here's my GridView adapter (with the ASyncTask).

public class ReceiptListAdapter extends ArrayAdapter {

    public ReceiptListAdapter(Context context, ArrayList<Receipt> receipts){
        super(context, 0, receipts);
//        getItem(1);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        // Check if an existing view is being reused, otherwise inflate the view
        ViewHolder holder;

        // Lookup view for data population
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.receipt_list_element, parent, false);
            holder = new ViewHolder();
            // Populate the data into the template view using the data object
            holder.title = (TextView) convertView.findViewById(R.id.TitleView);
            holder.date = (TextView) convertView.findViewById(R.id.DateView);
            holder.image = (ImageView) convertView.findViewById(R.id.containerImage);
            holder.spn = (ProgressBar) convertView.findViewById(R.id.spinner);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Receipt receipt = (Receipt) getItem(position);
        holder.imagePath = receipt.getFilepath();
        final int tWidth = receipt.getWidth();

        // manipulate data here...
        holder.spn.setVisibility(View.VISIBLE);
        holder.image.setVisibility(View.GONE);
        holder.title.setText(receipt.getDesc());

        new AsyncTask<ViewHolder, Void, Bitmap>() {

            private ViewHolder h;

            @Override
            protected Bitmap doInBackground(ViewHolder... t) {
                h = t[0];
                Bitmap thumb = ExifUtil.rotateBitmap(h.imagePath, ThumbnailUtils.extractThumbnail(
                        BitmapFactory.decodeFile(h.imagePath),
                        tWidth,
                        tWidth));
                return thumb;
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);

                    h.spn.setVisibility(View.GONE);
                    h.image.setVisibility(View.VISIBLE);
                    h.image.setImageBitmap(result);

            }
        }.execute(holder);

        // Return the completed view to render on screen
        return convertView;
    }

    static class ViewHolder {
        private TextView title;
        private TextView date;
        private ImageView image;
        private String imagePath;
        private ProgressBar spn;
    }

}

Body:
I have Replace your AsyncTask with Glide Library Update Your Code with
  below

public class ReceiptListAdapter extends ArrayAdapter {

        public ReceiptListAdapter(Context context, ArrayList<Receipt> receipts){
            super(context, 0, receipts);
//        getItem(1);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // Get the data item for this position
            // Check if an existing view is being reused, otherwise inflate the view
            ViewHolder holder;

            // Lookup view for data population
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.receipt_list_element, parent, false);
                holder = new ViewHolder();
                // Populate the data into the template view using the data object
                holder.title = (TextView) convertView.findViewById(R.id.TitleView);
                holder.date = (TextView) convertView.findViewById(R.id.DateView);
                holder.image = (ImageView) convertView.findViewById(R.id.containerImage);
                holder.spn = (ProgressBar) convertView.findViewById(R.id.spinner);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            Receipt receipt = (Receipt) getItem(position);
            holder.imagePath = receipt.getFilepath();
            final int tWidth = receipt.getWidth();

            // manipulate data here...
            holder.spn.setVisibility(View.VISIBLE);
            holder.image.setVisibility(View.GONE);
            holder.title.setText(receipt.getDesc());

            Glide.with(context)
                    .load(holder.imagePath)
                    .into(holder.image);

            /*new AsyncTask<ViewHolder, Void, Bitmap>() {

                private ViewHolder h;

                @Override
                protected Bitmap doInBackground(ViewHolder... t) {
                    h = t[0];
                    Bitmap thumb = ExifUtil.rotateBitmap(h.imagePath, ThumbnailUtils.extractThumbnail(
                            BitmapFactory.decodeFile(h.imagePath),
                            tWidth,
                            tWidth));
                    return thumb;
                }

                @Override
                protected void onPostExecute(Bitmap result) {
                    super.onPostExecute(result);

                    h.spn.setVisibility(View.GONE);
                    h.image.setVisibility(View.VISIBLE);
                    h.image.setImageBitmap(result);

                }
            }.execute(holder);*/

            // Return the completed view to render on screen
            return convertView;
        }

        static class ViewHolder {
            private TextView title;
            private TextView date;
            private ImageView image;
            private String imagePath;
            private ProgressBar spn;
        }

    }

Open you build.gradle and add this dependency

compile 'com.github.bumptech.glide:glide:4.0.0-RC0'


问:
How to clear ng-init value on button click event?
Here is my code, I want to reset items.total model.
its not working

```<code><div ng-init="items.total">
   <ul ng-repeat="x in Arr">
      <li ng-init = "items.total.carat = items.total.carat + x.Carat">{{x.Carat}}</li>
   </ul>
</div>
<label>{{items.total.carat}}</label>
<input type="button" ng-click="GetNewData()" value="FETCH">
----------------------------------------------
script :

$scope.GetNewData = function(){
   $scope.items = {};
   -- code --
};
</code>```

答:
You can put multiple calling in ng-click like following

```<code><input type="button" ng-click="GetNewData(); items.total = null;" value="FETCH">
</code>```

Adding to this you can pass items in function and clear it right there

```<code><input type="button" ng-click="GetNewData(items); items.total = null;" value="FETCH">
</code>```

Other than this you can call only method and clear it in your controller after all the operation

Like

```<code>$scope.GetNewData = function(){
   /* do necessary operation */
   $scope.items = {}; //empty it out
};
</code>```

Body:
Here is my code, I want to reset items.total model.
its not working

{{x.Carat}}

{{items.total.carat}}
<input type="button" ng-click="GetNewData()" value="FETCH">
----------------------------------------------
script :

$scope.GetNewData = function(){
   $scope.items = {};
   -- code --
};

Body:
You can put multiple calling in ng-click like following

<input type="button" ng-click="GetNewData(); items.total = null;" value="FETCH">

Adding to this you can pass items in function and clear it right there

<input type="button" ng-click="GetNewData(items); items.total = null;" value="FETCH">

Other than this you can call only method and clear it in your controller after all the operation

Like

$scope.GetNewData = function(){
   /* do necessary operation */
   $scope.items = {}; //empty it out
};


问:
Pass whole Model through ajax call
Is it possible to pass a whole Model through my jQuery's ajax call?
For know I can only get it working if i set one variable at the time.

As the code shows I pass the iVideo_ID through the ajax call. The Video object has a lot of other fields. So instead of writing all the attributes, can i pass the whole existing object (Video Model)?

```<code>$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/UpdateComment", // Controller/View
    data: { //Passing data
        iVideo_ID: '@(Model.Video.iVideo_ID)'
    }
});
</code>```

I have tried with this but it just return a Model that is null:

```<code>$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/NyMetode", // Controller/View
    data: '@(Model)'
});
</code>```

So how can i pass the whole model? Is it possible?

EDIT:
My View Model I try to pass:

```<code>public class CommentViewModel
{
   public List<Comments> Comments { get; set; }
   public List<Tasks> Tasks { get; set; }
   public Videos Video { get; set; }
   public List<VideoTaskScores> VideoTaskScores { get; set; }
}
</code>```

答:
You can use Json.stringify(model) but before implement this you you should get your Lists of model class with their last states by using jQuery.

Can you try this

```<code>// you can get your model data from view by jQuery
// your model has list objects so you should get these from view and add these into model
var model = {...}; // your object corresponds model object

$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/UpdateComment", // Controller/Action
    data: Json.stringify(model),
    contentType: "application/json"
}).done(function (res) {
    // after done insert your code here
});;
</code>```

Title: Pass whole Model through ajax call

Body:
Is it possible to pass a whole Model through my jQuery's ajax call?
For know I can only get it working if i set one variable at the time.

As the code shows I pass the iVideo_ID through the ajax call. The Video object has a lot of other fields. So instead of writing all the attributes, can i pass the whole existing object (Video Model)?

$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/UpdateComment", // Controller/View
    data: { //Passing data
        iVideo_ID: '@(Model.Video.iVideo_ID)'
    }
});

I have tried with this but it just return a Model that is null:

$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/NyMetode", // Controller/View
    data: '@(Model)'
});

So how can i pass the whole model? Is it possible?

EDIT:
My View Model I try to pass:

public class CommentViewModel
{
   public List<Comments> Comments { get; set; }
   public List<Tasks> Tasks { get; set; }
   public Videos Video { get; set; }
   public List<VideoTaskScores> VideoTaskScores { get; set; }
}

Body:
You can use Json.stringify(model) but before implement this you you should get your Lists of model class with their last states by using jQuery.

Can you try this

// you can get your model data from view by jQuery
// your model has list objects so you should get these from view and add these into model
var model = {...}; // your object corresponds model object

$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/UpdateComment", // Controller/Action
    data: Json.stringify(model),
    contentType: "application/json"
}).done(function (res) {
    // after done insert your code here
});;


问:
How can I align some text vertically in the middle of an HTML image?
I have this:
http://jsfiddle.net/8KWtH/

I would like to move the > so it is in the middle vertically of the two images.

How can i do this?

答:
I'd start by using the following instead of >.</p>

```<code>>
</code>```

Body:
I'd start by using the following instead of >.

&gt;