问:
Debugging HTML element change upon initial page load by some javascript function, but unable to find it.
I know chrome has a javascript debugger where you can set break points in the HTML if anything gets modified, but your only able to do this when the page has already loaded. I'm trying to figure out how an element is being assigned a inline style upon initial page load. I've tried to search in files for the class but nothing shows up. I'm not sure how I can trace where this is being set. The view source doesn't show any inline-style, so it must be from a js file.

How would one debug this?

答:
The only thing I can suggest is:

Set an event listener breakpoint on Script > Script First Statement.

Reload the page. DevTools pauses on the first line of the first script that executes.

Now, go back to the Elements panel, and place a subtree modification DOM breakpoint on . DevTools pauses whenever any node is modified. Or, if your target node was declared in the HTML and already exists on the page, then set the DOM breakpoint directly on the target node.

Keep pressing Resume Script Execution until you find the line of code that modifies your node. Every time you press Resume Script Execution, the scripts only execute until another node is modified.

This bypasses the DevTools limitation of DOM breakpoints not working on page load, because the page has technically started to run by the time you set the DOM breakpoint.

This seems like a pretty core use-case, though. DOM breakpoints on individual nodes don't work on page load, as you mentioned. Neither do DOM mutation event listener breakpoints. I'll put in a feature request to handle this, one way or another.

Body:
The only thing I can suggest is:

Set an event listener breakpoint on Script > Script First Statement.

Reload the page. DevTools pauses on the first line of the first script that executes.

Now, go back to the Elements panel, and place a subtree modification DOM breakpoint on <body>. DevTools pauses whenever any node is modified. Or, if your target node was declared in the HTML and already exists on the page, then set the DOM breakpoint directly on the target node.

Keep pressing Resume Script Execution until you find the line of code that modifies your node. Every time you press Resume Script Execution, the scripts only execute until another node is modified.

This bypasses the DevTools limitation of DOM breakpoints not working on page load, because the page has technically started to run by the time you set the DOM breakpoint.

This seems like a pretty core use-case, though. DOM breakpoints on individual nodes don't work on page load, as you mentioned. Neither do DOM mutation event listener breakpoints. I'll put in a feature request to handle this, one way or another.


来源: stackexchange

问:
can't insert into database (webservice)
I am creating a web service which will be called from an android app. Actually I am trying to do an insert into my database but i can't figure out why it is not working. Here is my code, with some tests I have made in order to find the bug :

```<code><?php
    $con = mysqli_connect("localhost", "xxx", "xxx", "xxx");

    /* here is the original code that I commented in order to do my tests
    $mail = $_POST["mail"];
    $mdp = $_POST["mdp"];
    $nom = $_POST["nom"];
    $prenom = $_POST["prenom"];
    $dateNaissance = $_POST["dateNaissance"];
    */
    $mail = "test@mail.fr";
    $mdp = "test";
    $nom = "test";
    $prenom = "test";
    $dateNaissance = "2000/01/01";

    $statement = mysqli_prepare($con, "INSERT INTO utilisateur (mail, mdp, nom, prenom, dateNaissance) VALUES (?, ?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "sssss", $mail, $mdp, $nom, $prenom, $dateNaissance);
    mysqli_stmt_execute($statement);

    $query = "SELECT * FROM utilisateur";
    $result2 = mysqli_query($con, $query);
    $final = mysqli_fetch_row($result2);

    print_r($final);
?>
</code>```

The SELECT request returns me the row I have in my utilisateur table so I suppose it's not a problem of connection.

Moreover, mysqli_stmt_execute($statement) returns 1... So if i'm not wrong it's supposed to mean that my request worked ? Anyway, nothing is inserted.

I'm hosting my database with 000webhost, don't know if this will help... I'm starting developing so everything is not crystal clear.

Hope that I was understandable and that you'll enlighten me!

答:
I found what was wrong : everything was working really well... But i was connecting to the wrong database. Indeed I began my project in localhost and then used 000webhost hosting. I got confused since it was written "server : localhost" in the two phpMyAdmin interfaces and also because I had the exact same table in the two databases. </p>

<p>Thanks for the answers that still made me learn. </p>

ContentLicense: CC BY-SA 3.0

Title: can't insert into database (webservice)

Body:
I am creating a web service which will be called from an android app. Actually I am trying to do an insert into my database but i can't figure out why it is not working. Here is my code, with some tests I have made in order to find the bug :

<?php
    $con = mysqli_connect("localhost", "xxx", "xxx", "xxx");

    /* here is the original code that I commented in order to do my tests
    $mail = $_POST["mail"];
    $mdp = $_POST["mdp"];
    $nom = $_POST["nom"];
    $prenom = $_POST["prenom"];
    $dateNaissance = $_POST["dateNaissance"];
    */
    $mail = "test@mail.fr";
    $mdp = "test";
    $nom = "test";
    $prenom = "test";
    $dateNaissance = "2000/01/01";

    $statement = mysqli_prepare($con, "INSERT INTO utilisateur (mail, mdp, nom, prenom, dateNaissance) VALUES (?, ?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "sssss", $mail, $mdp, $nom, $prenom, $dateNaissance);
    mysqli_stmt_execute($statement);

    $query = "SELECT * FROM utilisateur";
    $result2 = mysqli_query($con, $query);
    $final = mysqli_fetch_row($result2);

    print_r($final);
?>

The SELECT request returns me the row I have in my utilisateur table so I suppose it's not a problem of connection.

Moreover, mysqli_stmt_execute($statement) returns 1... So if i'm not wrong it's supposed to mean that my request worked ? Anyway, nothing is inserted.

I'm hosting my database with 000webhost, don't know if this will help... I'm starting developing so everything is not crystal clear.

Hope that I was understandable and that you'll enlighten me!

Body:
I found what was wrong : everything was working really well... But i was connecting to the wrong database. Indeed I began my project in localhost and then used 000webhost hosting. I got confused since it was written "server : localhost" in the two phpMyAdmin interfaces and also because I had the exact same table in the two databases.

Thanks for the answers that still made me learn.


问:
LINQ Order by column x and if empty take column y
I'm building a simple messaging system with the following data model:

```<code>public partial class Conversation
{
    public Conversation()
    {
        this.Messages = new HashSet<Message>();
        this.Customers = new HashSet<Customer>();
        this.MessagingHubConnections = new HashSet<MessagingHubConnection>();
    }

    public int Id { get; set; }
    public int BoatId { get; set; }
    public System.DateTime TimeCreated { get; set; }

    public virtual ICollection<Message> Messages { get; set; }
    public virtual Boat Boat { get; set; }
    public virtual ICollection<Customer> Customers { get; set; }
    public virtual ICollection<MessagingHubConnection> MessagingHubConnections { get; set; }
}

public partial class Message
{
    public int Id { get; set; }
    public int ConversationId { get; set; }
    public string Text { get; set; }
    public bool IsRead { get; set; }
    public System.DateTime TimeSend { get; set; }
    public int CustomerId { get; set; }

    public virtual Conversation Conversation { get; set; }
    public virtual Customer Customer { get; set; }
}
</code>```

When a customer opens his account dashboard, I want to display a list of all the conversations. This should be ordered according to the following rule: The first conversation in the list is the one with a message with the latest Message.TimeSent. If the conversation has no messages, it has to pick the Conversation.TimeCreated.
The code below is what I have right now but this is obviously not working when a Conversation has no messages. The variable conversations in the code below is an IQueryable<Conversation>.

```<code>var orderedConversations = conversations.OrderByDescending(c => c.Messages.Max(m => m.TimeSend));
</code>```

Anyone who can help me out?

答:
By projecting the TimeSend into DateTime? before Max()-ing it, you can obtain a (DateTime?)null when the collection is empty instead of getting an InvalidOperationException. And then, you can null-coalesce this result with TimeCreated:

```<code>var orderedConversations = conversations
    .OrderByDescending(c =>
        c.Messages
            .Select<Message, DateTime?>(x => x.TimeSend)
            .OrderByDescending(x => x)
            .FirstOrDefault() ??
        c.TimeCreated);
</code>```

Body:
I'm building a simple messaging system with the following data model:

public partial class Conversation
{
    public Conversation()
    {
        this.Messages = new HashSet<Message>();
        this.Customers = new HashSet<Customer>();
        this.MessagingHubConnections = new HashSet<MessagingHubConnection>();
    }

    public int Id { get; set; }
    public int BoatId { get; set; }
    public System.DateTime TimeCreated { get; set; }

    public virtual ICollection<Message> Messages { get; set; }
    public virtual Boat Boat { get; set; }
    public virtual ICollection<Customer> Customers { get; set; }
    public virtual ICollection<MessagingHubConnection> MessagingHubConnections { get; set; }
}

public partial class Message
{
    public int Id { get; set; }
    public int ConversationId { get; set; }
    public string Text { get; set; }
    public bool IsRead { get; set; }
    public System.DateTime TimeSend { get; set; }
    public int CustomerId { get; set; }

    public virtual Conversation Conversation { get; set; }
    public virtual Customer Customer { get; set; }
}

When a customer opens his account dashboard, I want to display a list of all the conversations. This should be ordered according to the following rule: The first conversation in the list is the one with a message with the latest Message.TimeSent. If the conversation has no messages, it has to pick the Conversation.TimeCreated.
The code below is what I have right now but this is obviously not working when a Conversation has no messages. The variable conversations in the code below is an IQueryable<Conversation>.

var orderedConversations = conversations.OrderByDescending(c => c.Messages.Max(m => m.TimeSend));

Anyone who can help me out?

Body:
By projecting the TimeSend into DateTime? before Max()-ing it, you can obtain a (DateTime?)null when the collection is empty instead of getting an InvalidOperationException. And then, you can null-coalesce this result with TimeCreated:

var orderedConversations = conversations
    .OrderByDescending(c =>
        c.Messages
            .Select<Message, DateTime?>(x => x.TimeSend)
            .OrderByDescending(x => x)
            .FirstOrDefault() ??
        c.TimeCreated);


问:
Is there any benefit to using getters/setters inside a class for its own fields?
Usually, in my own projects I use getters and setters for any field access, and I followed to do the same on my job. Some time ago, the tech lead of our project asked me why I was doing that and why is this better than just using fields themselves (with an option of declaring them protected if they needed to be accessed by subclasses). I couldn't come up with a clear answer.

So, are there any reasons to using getters and setters inside a class for class' own fields, or is it better to use fields directly?

答:
You want to declare them as public  getters and setters, and private fields.  This means external classes (not subclasses) who want to modify the variables all do so through the setters, and get them through the getters. The benefit of this is that if you want to control how or what condition they get or set them, or want to add information or even print debug, it means you only have to put it in the getters and setters.

There's a really good explanation of the benefits on stackoverflow actually:

In Java, difference between default, public, protected, and private

Of course, only make methods when they're actually needed, and similarly, only public when needed by external classes.

Hope that helps the defense!

ContentLicense: CC BY-SA 2.5


问:
Writing a DLL in Fortran/calling from Excel
I'm trying to write some numeric functionality in Fortran that can be later accessed in Excel. I'm using Office 2013 (64-bit), Visual Studio 2015 "Community" and Intel Fortran (Intel Parallel Studio XE 2017); and I'm able to correctly compile executable programs. I'm also able to generate DLL files, which I presume to be correct.

Here's a minimal Fortran code example I've worked out from this tip:

```<code>function id(x)
    !DEC$ ATTRIBUTES DLLEXPORT :: id
    integer :: id, x
    id = x
    return
end function
</code>```

and I have this on the Excel side under the VBA code for Sheet1:

```<code>Option Explicit
Option Base 1
Public Declare PtrSafe _
    Function id Lib "mydll.dll" _
    (ByVal x As Integer) As Integer
</code>```

By doing this, I manage to have the formula bar in Excel to autocomplete the function name, but evaluating any instance causes the cell to briefly flash 0 and then turn #VALUE!.

I've tried a number of things in combinatorial/cargo cult fashion: use ByRef instead of ByVal, have functions use only integers or single-precision (real*4) or double-precision (real*8) floats and then things that make even less sense.

I have finally ran out of random key combinations to mash, and there are very few sources covering this exact use case. If I must boil this down to something more precise than "what to do next":

Am I having problems because of numeric types or something related to an "impedance mismatch" between the Fortran and Excel worlds?

Am I instead missing necessary boilerplate, glue code and such?

答:
Here is the snippet from Intel visual Fortran help files.

```<code>subroutine FortranCall (r1, num)
    !DEC$ ATTRIBUTES DLLEXPORT, STDCALL, REFERENCE, ALIAS:"FortranCall" :: FortranCall
    integer, intent(in) :: r1
    character(10), intent(out) :: num
    !DEC$ ATTRIBUTES REFERENCE :: num

    num = ''
    write (num,'(i0)') r1 * 2

return
end subroutine FortranCall
</code>```

And on the excel side they used:

```<code>Declare Sub FortranCall Lib "C:\Temp\Fcall.dll" (r1 As Long, ByVal num As String)
</code>```

It will be good to get more examples with different inputs and outputs to help users.

Body:
I'm trying to write some numeric functionality in Fortran that can be later accessed in Excel. I'm using Office 2013 (64-bit), Visual Studio 2015 "Community" and Intel Fortran (Intel Parallel Studio XE 2017); and I'm able to correctly compile executable programs. I'm also able to generate DLL files, which I presume to be correct.

Here's a minimal Fortran code example I've worked out from this tip:

function id(x)
    !DEC$ ATTRIBUTES DLLEXPORT :: id
    integer :: id, x
    id = x
    return
end function

and I have this on the Excel side under the VBA code for Sheet1:

Option Explicit
Option Base 1
Public Declare PtrSafe _
    Function id Lib "mydll.dll" _
    (ByVal x As Integer) As Integer

By doing this, I manage to have the formula bar in Excel to autocomplete the function name, but evaluating any instance causes the cell to briefly flash 0 and then turn #VALUE!.

I've tried a number of things in combinatorial/cargo cult fashion: use ByRef instead of ByVal, have functions use only integers or single-precision (real*4) or double-precision (real*8) floats and then things that make even less sense.

I have finally ran out of random key combinations to mash, and there are very few sources covering this exact use case. If I must boil this down to something more precise than "what to do next":

Am I having problems because of numeric types or something related to an "impedance mismatch" between the Fortran and Excel worlds?

Am I instead missing necessary boilerplate, glue code and such?

Body:
Here is the snippet from Intel visual Fortran help files.

subroutine FortranCall (r1, num)
    !DEC$ ATTRIBUTES DLLEXPORT, STDCALL, REFERENCE, ALIAS:"FortranCall" :: FortranCall
    integer, intent(in) :: r1
    character(10), intent(out) :: num
    !DEC$ ATTRIBUTES REFERENCE :: num

    num = ''
    write (num,'(i0)') r1 * 2

return
end subroutine FortranCall

And on the excel side they used:

Declare Sub FortranCall Lib "C:\Temp\Fcall.dll" (r1 As Long, ByVal num As String)

It will be good to get more examples with different inputs and outputs to help users.


问:
Tumblr's share-button script doesn't work
In a rails app I have a Tumblr share button:

```<code><a href="<%= "https://www.tumblr.com/widgets/share/tool?canonicalUrl=#{tips_and_trick_url(tip)}" %>" data-title="<%= tip.title %>" data-content="<%= tip.content %>" target="_blank">
</code>```

As it is said in documentation, I have to include  after  tag. Clicking on the share button it takes me to a new tab, but as I understand, a pop-up window should appear. So, the question is how to reach the desired result, to make a pop-up window appear? Thanks.

答:
On pages that include the JavaScript code of our "Share" button (listed below), this button is a binding tag with the tumblr-share-button: class tumblr-share-button:

It seems you are missing the class attribute:

```<code><a class="tumblr-share-button" href="<%= "https://www.tumblr.com/widgets/share/tool?canonicalUrl=#{tips_and_trick_url(tip)}" %>" data-title="<%= tip.title %>" data-content="<%= tip.content %>"></a>
</code>```

Source: https://translate.googleusercontent.com/translate_c?depth=1&hl=en&ie=UTF8&prev=_t&rurl=translate.google.co.uk&sl=auto&sp=nmt4&tl=en&u=https://www.tumblr.com/docs/ru/share_button&usg=ALkJrhg99ccfkG9zPv8gj6gxiMFxalMUGA

Body:
In a rails app I have a Tumblr share button:

<a href="<%= "https://www.tumblr.com/widgets/share/tool?canonicalUrl=#{tips_and_trick_url(tip)}" %>" data-title="<%= tip.title %>" data-content="<%= tip.content %>" target="_blank">

As it is said in documentation, I have to include  after  tag. Clicking on the share button it takes me to a new tab, but as I understand, a pop-up window should appear. So, the question is how to reach the desired result, to make a pop-up window appear? Thanks.

Body:
On pages that include the JavaScript code of our "Share" button (listed below), this button is a binding tag with the tumblr-share-button: class tumblr-share-button:

It seems you are missing the class attribute:

<a class="tumblr-share-button" href="<%= "https://www.tumblr.com/widgets/share/tool?canonicalUrl=#{tips_and_trick_url(tip)}" %>" data-title="<%= tip.title %>" data-content="<%= tip.content %>"></a>

Source: https://translate.googleusercontent.com/translate_c?depth=1&hl=en&ie=UTF8&prev=_t&rurl=translate.google.co.uk&sl=auto&sp=nmt4&tl=en&u=https://www.tumblr.com/docs/ru/share_button&usg=ALkJrhg99ccfkG9zPv8gj6gxiMFxalMUGA


问:
TimeoutException using selenium with python
I'm getting TimeoutException when using this code to get the fill in the CardNum textbox with a number

```<code>CardNUM = WebDriverWait(browser,   10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="number"]')))
CardNUM.send_keys(cardNum)
</code>```

Xpath is taken directly from right clicking and inspecting the textbox and copying the XPATH for the block

```<code><input autocomplete="cc-number" id="number" name="number" type="tel" aria-describedby="error-for-number" data-current-field="number" class="input-placeholder-color--lvl-30" placeholder="Card number" style="color: rgb(151, 151, 151); font-family: "Helvetica Neue"; padding: 0.94em 0.8em; transition: padding 0.2s ease-out;">
</code>```

Is there something else I need to do to be able to fill in the box, for example is the text box hidden and is there some manipulation that I would need to do beforehand to be able to find the text box?

答: Most likely the element is inside an IFRAME, especially since it seems to be a credit card number. The payment portion of payment pages are typically in an IFRAME for security. Try switching to the IFRAME first then your code should work.</p>

Body:
I'm getting TimeoutException when using this code to get the fill in the CardNum textbox with a number

CardNUM = WebDriverWait(browser,   10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="number"]')))
CardNUM.send_keys(cardNum)

Xpath is taken directly from right clicking and inspecting the textbox and copying the XPATH for the block

<input autocomplete="cc-number" id="number" name="number" type="tel" aria-describedby="error-for-number" data-current-field="number" class="input-placeholder-color--lvl-30" placeholder="Card number" style="color: rgb(151, 151, 151); font-family: "Helvetica Neue"; padding: 0.94em 0.8em; transition: padding 0.2s ease-out;">

Is there something else I need to do to be able to fill in the box, for example is the text box hidden and is there some manipulation that I would need to do beforehand to be able to find the text box?


问:
undefined symbol: PySlice_AdjustIndices when importing PyTorch
I am trying to use PyTorch, and I think there is some version of something that isn't lining up.

From what little I can suss out, it seems that there are some functions in the newest version of PyTorch (?) that can't be accessed on my system. I suspect it has something to do with Python version 3.6.1 as opposed to 3.6.0. But I can't figure it out. If anyone has any advice on what I can do to rectify this error:

```<code>/home/ubuntu/nbs/torch_utils.py in <module>()
----> 1 import torch
      2 import torch.nn as nn
      3 import torch.nn.parallel
      4 import torch.utils.data
      5 from torch import optim

/home/ubuntu/anaconda3/lib/python3.6/site-packages/torch/__init__.py in <module>()
     51 sys.setdlopenflags(_dl_flags.RTLD_GLOBAL | _dl_flags.RTLD_NOW)
     52
---> 53 from torch._C import *
     54
     55 __all__ += [name for name in dir(_C)

ImportError: /home/ubuntu/anaconda3/lib/python3.6/site-packages/torch/_C.cpython-36m-x86_64-linux-gnu.so: undefined symbol: PySlice_AdjustIndices
</code>```

Here's the details on my system:

I am running Ubuntu on AWS, Ubuntu 16.04.2 LTS

my Cuda info is Cuda compilation tools, release 8.0, V8.0.61

I have Anaconda, conda 4.3.15

My python version is Python 3.6.0 :: Anaconda custom (64-bit)

Thanks.

答:
this is now fixed if you reinstall pytorch via conda:

conda install pytorch torchvision -c soumith

Body:
I am trying to use PyTorch, and I think there is some version of something that isn't lining up.

From what little I can suss out, it seems that there are some functions in the newest version of PyTorch (?) that can't be accessed on my system. I suspect it has something to do with Python version 3.6.1 as opposed to 3.6.0. But I can't figure it out. If anyone has any advice on what I can do to rectify this error:

/home/ubuntu/nbs/torch_utils.py in <module>()
----> 1 import torch
      2 import torch.nn as nn
      3 import torch.nn.parallel
      4 import torch.utils.data
      5 from torch import optim

/home/ubuntu/anaconda3/lib/python3.6/site-packages/torch/__init__.py in <module>()
     51 sys.setdlopenflags(_dl_flags.RTLD_GLOBAL | _dl_flags.RTLD_NOW)
     52
---> 53 from torch._C import *
     54
     55 __all__ += [name for name in dir(_C)

ImportError: /home/ubuntu/anaconda3/lib/python3.6/site-packages/torch/_C.cpython-36m-x86_64-linux-gnu.so: undefined symbol: PySlice_AdjustIndices

Here's the details on my system:

I am running Ubuntu on AWS, Ubuntu 16.04.2 LTS

my Cuda info is Cuda compilation tools, release 8.0, V8.0.61

I have Anaconda, conda 4.3.15

My python version is Python 3.6.0 :: Anaconda custom (64-bit)

Thanks.


问:
sql one-to-one join / match
hello I need solution for this kind of problem:

sample:
tblPeople:

```<code> - id   Value  carColor
 1. Pid1  boy1  blue
 2. Pid2  boy2  blue
 3. Pid3  boy3  blue
 4. Pid4  girl1 red
 5. Pid5  girl2 red
</code>```

tblCars:

```<code> - id   Value
 1. Cid1  blue
 2. Cid2  blue
 3. Cid3  red
 4. Cid4  red
 5. Cid5  red
</code>```

condition:
 - boys can use only blue cars but girls - red only
 - people can use 1 car only, car fits 1 person only

distribute cars between people

expected result(s):

```<code> 1. Pid1  boy1 Cid1 blue
 2. Pid2  boy2 Cid2 blue
 3. Pid3  boy3 (no enough blue car - skipping)
 4. Pid4  girl1 Cid3 red
 5. Pid5  girl2 Cid4 red
</code>```

or

```<code> 1. Pid1  boy1 Cid2 blue
 2. Pid2  boy2 Cid1 blue
 3. Pid3  boy3 (no enough blue car - skipping)
 4. Pid4  girl1 Cid5 red
 5. Pid5  girl2 Cid3 red
</code>```

for now I'm using select top 1 on join in cycle with marking chosen records to remove it in next matching, but it takes lot of time ...

can anyone help with it?
thanks

答:
You can do this by enumerating the cars and enumerating the people, and then doing a join:

```<code>select p.*, c.*
from (select p.*,
             row_number() over (partition by gender order by gender) as seqnum
      from tblPeople p
     ) p left join
     (select c.*,
             row_number() over (partition by color order by color) as seqnum
      from cars c
     ) c
     on p.seqnum = c.seqnum and
        ( (p.gender = 'boy' and c.color = 'blue') or
          (p.gender = 'girl' and c.color = 'red')
        ) ;
</code>```

This should be much, much faster than your current method.

Note:  You can use newid() for ordering if you want to randomize the assignment each time you run the query.

Title: sql one-to-one join / match

Body:
hello I need solution for this kind of problem:

sample:
tblPeople:

 - id   Value  carColor
 1. Pid1  boy1  blue
 2. Pid2  boy2  blue
 3. Pid3  boy3  blue
 4. Pid4  girl1 red
 5. Pid5  girl2 red

tblCars:

 - id   Value
 1. Cid1  blue
 2. Cid2  blue
 3. Cid3  red
 4. Cid4  red
 5. Cid5  red

condition:
 - boys can use only blue cars but girls - red only
 - people can use 1 car only, car fits 1 person only

distribute cars between people

expected result(s):

 1. Pid1  boy1 Cid1 blue
 2. Pid2  boy2 Cid2 blue
 3. Pid3  boy3 (no enough blue car - skipping)
 4. Pid4  girl1 Cid3 red
 5. Pid5  girl2 Cid4 red

or

 1. Pid1  boy1 Cid2 blue
 2. Pid2  boy2 Cid1 blue
 3. Pid3  boy3 (no enough blue car - skipping)
 4. Pid4  girl1 Cid5 red
 5. Pid5  girl2 Cid3 red

for now I'm using select top 1 on join in cycle with marking chosen records to remove it in next matching, but it takes lot of time ...

can anyone help with it?
thanks

Body:
You can do this by enumerating the cars and enumerating the people, and then doing a join:

select p.*, c.*
from (select p.*,
             row_number() over (partition by gender order by gender) as seqnum
      from tblPeople p
     ) p left join
     (select c.*,
             row_number() over (partition by color order by color) as seqnum
      from cars c
     ) c
     on p.seqnum = c.seqnum and
        ( (p.gender = 'boy' and c.color = 'blue') or
          (p.gender = 'girl' and c.color = 'red')
        ) ;

This should be much, much faster than your current method.

Note:  You can use newid() for ordering if you want to randomize the assignment each time you run the query.


问:
How to embed images in email
I need to embed an image in e-mail. How do I do it?

I do not want to use third party tool, nor am I interested in language specific answer (but it is PHP, in case you are wondering).

I am merely interested in format of resulting e-mail body.

答:
As you are aware, everything passed as email message has to be textualized.

You must create an email with a multipart/mime message.

If you're adding a physical image, the image must be base 64 encoded and assigned a Content-ID (cid). If it's an URL, then the  tag is sufficient (the url of the image must be linked to a Source ID).

A Typical email example will look like this:

```<code>From: foo1atbar.net
To: foo2atbar.net
Subject: A simple example
Mime-Version: 1.0
Content-Type: multipart/related; boundary="boundary-example"; type="text/html"

--boundary-example
Content-Type: text/html; charset="US-ASCII"

... text of the HTML document, which might contain a URI
referencing a resource in another body part, for example
through a statement such as:
<IMG SRC="cid:foo4atfoo1atbar.net" ALT="IETF logo">

--boundary-example
Content-Location: CID:somethingatelse ; this header is disregarded
Content-ID: <foo4atfoo1atbar.net>
Content-Type: IMAGE/GIF
Content-Transfer-Encoding: BASE64

R0lGODlhGAGgAPEAAP/////ZRaCgoAAAACH+PUNv
cHlyaWdodCAoQykgMTk5LiBVbmF1dGhvcml6ZWQgZHV
wbGljYXRpb24gcHJvaGliaXRlZC4A etc...

--boundary-example--
</code>```

As you can see, the Content-ID: <foo4atfoo1atbar.net> ID is matched to the  at SRC="cid:foo4atfoo1atbar.net". That way, the client browser will render your image as a content and not as an attachement.

Title: How to embed images in email

Body:
As you are aware, everything passed as email message has to be textualized.

You must create an email with a multipart/mime message.

If you're adding a physical image, the image must be base 64 encoded and assigned a Content-ID (cid). If it's an URL, then the <img /> tag is sufficient (the url of the image must be linked to a Source ID).

A Typical email example will look like this:

From: foo1atbar.net
To: foo2atbar.net
Subject: A simple example
Mime-Version: 1.0
Content-Type: multipart/related; boundary="boundary-example"; type="text/html"

--boundary-example
Content-Type: text/html; charset="US-ASCII"

... text of the HTML document, which might contain a URI
referencing a resource in another body part, for example
through a statement such as:
<IMG SRC="cid:foo4atfoo1atbar.net" ALT="IETF logo">

--boundary-example
Content-Location: CID:somethingatelse ; this header is disregarded
Content-ID: <foo4atfoo1atbar.net>
Content-Type: IMAGE/GIF
Content-Transfer-Encoding: BASE64

R0lGODlhGAGgAPEAAP/////ZRaCgoAAAACH+PUNv
cHlyaWdodCAoQykgMTk5LiBVbmF1dGhvcml6ZWQgZHV
wbGljYXRpb24gcHJvaGliaXRlZC4A etc...

--boundary-example--

As you can see, the Content-ID: <foo4atfoo1atbar.net> ID is matched to the <IMG> at SRC="cid:foo4atfoo1atbar.net". That way, the client browser will render your image as a content and not as an attachement.

ContentLicense: CC BY-SA 4.0


问:
H5Screate_simple throws exception: dims rank is invalid
I just started experimenting with HDF5 to see if I can use it in a new project.  I'm getting the following exception from a call to H5Screate_simple: dims rank is invalid.

I'm developing in Eclipse with Scala with Maven on OS X.  I'm using this example to build my test.  Here is the failing snippet:

```<code>def failTest() {
    val rank: Int = 2
    val dimSizes = Array[Long](1, 1)
    val maxDimSizes = Array[Long](1, 1)

    val dataSpaceID = H5.H5Screate_simple(rank, dimSizes, maxDimSizes)
}
</code>```

Searching for the error message I found the code that throws the exception here, see line 81.  This indicates the length of the dimSizes array does not match the value of rank, but in the snippet above the both are obviously 2.  I wondered if this could be some problem with the Array object in Scala (though I've never had problem passing arrays to java functions before).  So I wrote a test snippet in Java ...

```<code>public static void failTest() throws Exception {
    int rank = 2;
    long[] dims = { 1, 1 };
    long[] mdims = { 1, 1 };

    long dataSpaceID = H5.H5Screate_simple(rank, dims, mdims);

}
</code>```

I get the same exception.  It all seems pretty straight forward, but I can't see any problem.  Can anyone help on this?

答:
The problem was due to an out of data package.  I setup my pom.xml to fetch the package from maven central, but the latest version posted there is 2.6.1 from 2010.  The latest version is 3.2.1.  For some reason they are not maintaining it at maven central.  I downloaded the latest from here.

I manually installed the jar in my maven repository with:

```<code>mvn install:install-file -Dfile=jarhdf5-3.2.1.jar -DgroupId=org.hdfgroup -DartifactId=hdf-java -Dversion=3.2.1 -Dpackaging=jar
</code>```

Then updated my pom.xml with

```<code>    <dependency>
        <groupId>org.hdfgroup</groupId>
        <artifactId>hdf-java</artifactId>
        <version>3.2.1</version>
    </dependency>
</code>```

The download from hdfgroup was described as an installer, but it didn't seem to actually install anything.  So I also had to install the native library manually with:

```<code>ln -sf /<path_to_package>/HDFJAVA/3.2.1/lib/libjhdf.3.2.1.dylib /usr/local/lib/libjhdf.3.2.1.dylib
ln -sf /<path_to_package>/HDFJAVA/3.2.1/lib/libjhdf.3.2.1.dylib /usr/local/lib/libjhdf5.dylib
</code>```

Body:
I just started experimenting with HDF5 to see if I can use it in a new project.  I'm getting the following exception from a call to H5Screate_simple: dims rank is invalid.

I'm developing in Eclipse with Scala with Maven on OS X.  I'm using this example to build my test.  Here is the failing snippet:

def failTest() {
    val rank: Int = 2
    val dimSizes = Array[Long](1, 1)
    val maxDimSizes = Array[Long](1, 1)

    val dataSpaceID = H5.H5Screate_simple(rank, dimSizes, maxDimSizes)
}

Searching for the error message I found the code that throws the exception here, see line 81.  This indicates the length of the dimSizes array does not match the value of rank, but in the snippet above the both are obviously 2.  I wondered if this could be some problem with the Array object in Scala (though I've never had problem passing arrays to java functions before).  So I wrote a test snippet in Java ...

public static void failTest() throws Exception {
    int rank = 2;
    long[] dims = { 1, 1 };
    long[] mdims = { 1, 1 };

    long dataSpaceID = H5.H5Screate_simple(rank, dims, mdims);

}

I get the same exception.  It all seems pretty straight forward, but I can't see any problem.  Can anyone help on this?

Body:
The problem was due to an out of data package.  I setup my pom.xml to fetch the package from maven central, but the latest version posted there is 2.6.1 from 2010.  The latest version is 3.2.1.  For some reason they are not maintaining it at maven central.  I downloaded the latest from here.

I manually installed the jar in my maven repository with:

mvn install:install-file -Dfile=jarhdf5-3.2.1.jar -DgroupId=org.hdfgroup -DartifactId=hdf-java -Dversion=3.2.1 -Dpackaging=jar

Then updated my pom.xml with

    <dependency>
        <groupId>org.hdfgroup</groupId>
        <artifactId>hdf-java</artifactId>
        <version>3.2.1</version>
    </dependency>

The download from hdfgroup was described as an installer, but it didn't seem to actually install anything.  So I also had to install the native library manually with:

ln -sf /<path_to_package>/HDFJAVA/3.2.1/lib/libjhdf.3.2.1.dylib /usr/local/lib/libjhdf.3.2.1.dylib
ln -sf /<path_to_package>/HDFJAVA/3.2.1/lib/libjhdf.3.2.1.dylib /usr/local/lib/libjhdf5.dylib


问:
Getting rows from a database query into an array in CodeIgniter
So I have the following database table called "relacionproveedorfamilia"

```<code>-----------------------------
| idProveedor | idFamilia   |
-----------------------------
|      5      |      1      |
-----------------------------
|      5      |      2      |
-----------------------------
|      6      |      2      |
-----------------------------
</code>```

I use a function where I provide the value for idProveedor and it should return an array with the idFamilia values that belong to the provided idProveedor.

For example, this is the query to get all idFamilia for idProveedor = 5

```<code>SELECT idFamilia FROM relacionproveedorfamilia WHERE idProveedor = 5;
</code>```

The result of the query is:

```<code>---------------
| idFamilia   |
---------------
|      1      |
---------------
|      2      |
---------------
</code>```

I am trying to get the query result into an array, so I can display the contents in my view.

In my model Proveedormodel I have the following function, which I've coded by checking other similar questions in this site.

```<code>public function obtenerIdFamiliaProveedor($idProveedor){
     $query = $this->db->select('idFamilia')->from('relacionproveedorfamilia')->where('idProveedor', $idProveedor);
     $arrayFamilias = array();

     while($row = mysql_fetch_assoc($query)){
         $arrayFamilias[] = $row;
     }

     return $arrayFamilias;
 }
</code>```

But in my view I am getting the error message:

```<code>Message: mysql_fetch_assoc() expects parameter 1 to be resource, object given
</code>```

How could I fix this?

答:
You are mixing codeigniter Query builder class with mysql_ functions. Why are you doing this?

You have to change your code:

```<code>while($row = mysql_fetch_assoc($query)){
</code>```

to this:

```<code>foreach ($query->result_array() as $row)
</code>```

And you need to add get method at the end of your query:

```<code>$query = $this->db->select('idFamilia')->from('relacionproveedorfamilia')->where('idProveedor', $idProveedor)->get();
</code>```

Body:
So I have the following database table called "relacionproveedorfamilia"

-----------------------------
| idProveedor | idFamilia   |
-----------------------------
|      5      |      1      |
-----------------------------
|      5      |      2      |
-----------------------------
|      6      |      2      |
-----------------------------

I use a function where I provide the value for idProveedor and it should return an array with the idFamilia values that belong to the provided idProveedor.

For example, this is the query to get all idFamilia for idProveedor = 5

SELECT idFamilia FROM relacionproveedorfamilia WHERE idProveedor = 5;

The result of the query is:

---------------
| idFamilia   |
---------------
|      1      |
---------------
|      2      |
---------------

I am trying to get the query result into an array, so I can display the contents in my view.

In my model Proveedormodel I have the following function, which I've coded by checking other similar questions in this site.

public function obtenerIdFamiliaProveedor($idProveedor){
     $query = $this->db->select('idFamilia')->from('relacionproveedorfamilia')->where('idProveedor', $idProveedor);
     $arrayFamilias = array();

     while($row = mysql_fetch_assoc($query)){
         $arrayFamilias[] = $row;
     }

     return $arrayFamilias;
 }

But in my view I am getting the error message:

Message: mysql_fetch_assoc() expects parameter 1 to be resource, object given

How could I fix this?

Body:
You are mixing codeigniter Query builder class with mysql_ functions. Why are you doing this?

You have to change your code:

while($row = mysql_fetch_assoc($query)){

to this:

foreach ($query->result_array() as $row)

And you need to add get method at the end of your query:

$query = $this->db->select('idFamilia')->from('relacionproveedorfamilia')->where('idProveedor', $idProveedor)->get();


问:
How to test AngularJS component that use promise?
I have the following component that I want to unit test.

```<code>myApp.component('myComponent', {
  controller: function($q) {
    let serviceDummy = $q((resolve, reject) => resolve(42));
    this.number = 0;
    this.$onInit = () => {
      serviceDummy.then((res) => {this.number = res; });
      serviceDummy.then(console.log);
    }
  },
  template: '<p>The answer is {{$ctrl.number}}</p>'
});
</code>```

This is my test:

```<code>describe('myComponent', function() {
  var controller;
  beforeEach(function() {
    module('myApp');
  });
  beforeEach(inject(function($componentController) {
    controller = $componentController('myComponent', null);
  }));

  it('should set the number', function() {
    controller.$onInit();
    expect(controller.number).toBe(42);
  });
});
</code>```

The component works well but the test failed.
Here is a fiddle

答:
First return the promise created by the function under test.

```<code>this.$onInit = () => {
    //vvvv RETURN promise
    return serviceDummy.then((res) => {this.number = res; });
}
</code>```

Then use then done function that Jasmine provides as an argument to the test handler of the it method:

```<code>  it('should set the number to 42', function testHandler(done) {
    var p = controller.$onInit();
    p.then(function() {
      expect(controller.number).toBe(42);
      done();
    });
    _rootScope.$apply();
  });
</code>```

The DEMO on JSFiddle

Body:
I have the following component that I want to unit test.

myApp.component('myComponent', {
  controller: function($q) {
    let serviceDummy = $q((resolve, reject) => resolve(42));
    this.number = 0;
    this.$onInit = () => {
      serviceDummy.then((res) => {this.number = res; });
      serviceDummy.then(console.log);
    }
  },
  template: '
The answer is {{$ctrl.number}}
'
});

This is my test:

describe('myComponent', function() {
  var controller;
  beforeEach(function() {
    module('myApp');
  });
  beforeEach(inject(function($componentController) {
    controller = $componentController('myComponent', null);
  }));

  it('should set the number', function() {
    controller.$onInit();
    expect(controller.number).toBe(42);
  });
});

The component works well but the test failed.
Here is a fiddle

Body:
First return the promise created by the function under test.

this.$onInit = () => {
    //vvvv RETURN promise
    return serviceDummy.then((res) => {this.number = res; });
}

Then use then done function that Jasmine provides as an argument to the test handler of the it method:

  it('should set the number to 42', function testHandler(done) {
    var p = controller.$onInit();
    p.then(function() {
      expect(controller.number).toBe(42);
      done();
    });
    _rootScope.$apply();
  });

The DEMO on JSFiddle


问:
from NSFetchedResults objectAtIndex:0 returning 0
I've been banging my head on this one specific issue for about 2 hours now, reading through documentation and examples and I just can't wrap my head around it. I have core data models Person and Photo, and they're linked. I'm trying to display a UITableView with the contents and

```<code>-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
</code>```

keeps returning 0. Here is the relevant code.
I know there is data in my core data because I can look at it with sqlite in terminal.

AppDelegate.h

```<code>@interface PaparazziAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;

    UITabBarController *tabController;
    UINavigationController *mainNavController;
    UINavigationController *recentsNavController;
    PersonListViewController  *personListView;
    PhotoListViewController *recentsList;
    PhotoDetailViewController *photoDetail;

    FlickrFetcher *fetcher;
    NSManagedObjectContext *currentContext;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@property (nonatomic, retain) IBOutlet UITabBarController *tabController;
@property (nonatomic, retain) IBOutlet UINavigationController *mainNavController, *recentsNavController;

@end
</code>```

AppDelegate.m

```<code>#import "PaparazziAppDelegate.h"

@implementation PaparazziAppDelegate

@synthesize window;
@synthesize tabController, mainNavController, recentsNavController;

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Setup the database instances for access.
    fetcher = [FlickrFetcher sharedInstance];

    // Check to see if the database exists, if not, load the plist and populate.
    if ([fetcher databaseExists])
        NSLog(@"I'm here!");
    else {
        NSLog(@"No database yet!");

        currentContext = [fetcher managedObjectContext];

        /* -- REMOVED FOR READABILITY --
        A chunk of code for creating fresh data from a plist if the database doesn't yet exist.
        I know this part works because I can see the data using the terminal */

        [currentContext release];
    }
    // End of the plist loading and database creation.

    personListView = [[PersonListViewController alloc] initWithStyle:UITableViewStylePlain];
    personListView.title = @"Contacts";
    [mainNavController pushViewController:personListView animated:NO];
    [personListView release];

    recentsList = [[PhotoListViewController alloc] initWithNibName:@"PhotoListViewController" bundle:[NSBundle mainBundle]];
    recentsList.title = @"Recents";
    [recentsNavController pushViewController:recentsList animated:NO];
    [recentsList release];

    // setting up view icons
    UITabBarItem *contactsIcon = [[UITabBarItem alloc]
                          initWithTabBarSystemItem:UITabBarSystemItemContacts tag:0];
    mainNavController.tabBarItem = contactsIcon;
    [contactsIcon release];
    UITabBarItem *recentsIcon = [[UITabBarItem alloc]
                                  initWithTabBarSystemItem:UITabBarSystemItemRecents tag:0];
    recentsNavController.tabBarItem = recentsIcon;
    [recentsIcon release];

    [self.window addSubview:tabController.view];

    // Override point for customization after application launch.

    [self.window makeKeyAndVisible];

    return YES;
}

- (void)dealloc {
    [window release];
    [tabController release];
    [mainNavController release];
    [recentsNavController release];

    [fetcher release];

    [super dealloc];
}

@end
</code>```

PersonListViewController.h

```<code>#import <UIKit/UIKit.h>
#import "FlickrFetcher.h"
#import "Person.h"
#import "Photo.h"

@interface PersonListViewController : UITableViewController {
    NSArray *listOfPeople;

    FlickrFetcher *fetcher;
    NSManagedObjectContext *currentContext;
    NSFetchedResultsController *fetchedResultsController;
}

@property (nonatomic, retain) NSArray *listOfPeople;
@property (nonatomic, retain) NSManagedObjectContext *currentContext;
@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;

@end
</code>```

And the trouble file, PersonListViewController.m

```<code>#import "PersonListViewController.h"

@implementation PersonListViewController

@synthesize listOfPeople, currentContext, fetchedResultsController;

#pragma mark -
#pragma mark Initialization

- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization.
        fetcher = [FlickrFetcher sharedInstance];
        currentContext = [fetcher managedObjectContext];

        fetchedResultsController = [fetcher fetchedResultsControllerForEntity:@"Person" withPredicate:nil];
    }
    return self;
}

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"Contacts";
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    Person *person = [fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = [person name];

    // Configure the cell...

    return cell;
}

#pragma mark -
#pragma mark Memory management

- (void)dealloc {
    [super dealloc];
}

@end
</code>```

I have a feeling I'm missing something simple or 1 off, but I just can't seem to find it.
[FlickrFetcher sharedInstance] returns a singleton, if I toss a few breakpoints into each .m file, I can see that the object id of *fetcher in each area is the same.

答: As an aside - you might consider initialising your fetchedResultsController in viewDidLoad rather than initWithStyle:, then you can drop it in viewDidUnload and hence free up some memory if the OS needs to unload the view controller.

Body:
I've been banging my head on this one specific issue for about 2 hours now, reading through documentation and examples and I just can't wrap my head around it. I have core data models Person and Photo, and they're linked. I'm trying to display a UITableView with the contents and

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

keeps returning 0. Here is the relevant code.
I know there is data in my core data because I can look at it with sqlite in terminal.

AppDelegate.h

@interface PaparazziAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;

    UITabBarController *tabController;
    UINavigationController *mainNavController;
    UINavigationController *recentsNavController;
    PersonListViewController  *personListView;
    PhotoListViewController *recentsList;
    PhotoDetailViewController *photoDetail;

    FlickrFetcher *fetcher;
    NSManagedObjectContext *currentContext;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@property (nonatomic, retain) IBOutlet UITabBarController *tabController;
@property (nonatomic, retain) IBOutlet UINavigationController *mainNavController, *recentsNavController;

@end

AppDelegate.m

#import "PaparazziAppDelegate.h"

@implementation PaparazziAppDelegate

@synthesize window;
@synthesize tabController, mainNavController, recentsNavController;

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Setup the database instances for access.
    fetcher = [FlickrFetcher sharedInstance];

    // Check to see if the database exists, if not, load the plist and populate.
    if ([fetcher databaseExists])
        NSLog(@"I'm here!");
    else {
        NSLog(@"No database yet!");

        currentContext = [fetcher managedObjectContext];

        /* -- REMOVED FOR READABILITY --
        A chunk of code for creating fresh data from a plist if the database doesn't yet exist.
        I know this part works because I can see the data using the terminal */

        [currentContext release];
    }
    // End of the plist loading and database creation.

    personListView = [[PersonListViewController alloc] initWithStyle:UITableViewStylePlain];
    personListView.title = @"Contacts";
    [mainNavController pushViewController:personListView animated:NO];
    [personListView release];

    recentsList = [[PhotoListViewController alloc] initWithNibName:@"PhotoListViewController" bundle:[NSBundle mainBundle]];
    recentsList.title = @"Recents";
    [recentsNavController pushViewController:recentsList animated:NO];
    [recentsList release];

    // setting up view icons
    UITabBarItem *contactsIcon = [[UITabBarItem alloc]
                          initWithTabBarSystemItem:UITabBarSystemItemContacts tag:0];
    mainNavController.tabBarItem = contactsIcon;
    [contactsIcon release];
    UITabBarItem *recentsIcon = [[UITabBarItem alloc]
                                  initWithTabBarSystemItem:UITabBarSystemItemRecents tag:0];
    recentsNavController.tabBarItem = recentsIcon;
    [recentsIcon release];

    [self.window addSubview:tabController.view];

    // Override point for customization after application launch.

    [self.window makeKeyAndVisible];

    return YES;
}

- (void)dealloc {
    [window release];
    [tabController release];
    [mainNavController release];
    [recentsNavController release];

    [fetcher release];

    [super dealloc];
}

@end

PersonListViewController.h

#import <UIKit/UIKit.h>
#import "FlickrFetcher.h"
#import "Person.h"
#import "Photo.h"

@interface PersonListViewController : UITableViewController {
    NSArray *listOfPeople;

    FlickrFetcher *fetcher;
    NSManagedObjectContext *currentContext;
    NSFetchedResultsController *fetchedResultsController;
}

@property (nonatomic, retain) NSArray *listOfPeople;
@property (nonatomic, retain) NSManagedObjectContext *currentContext;
@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;

@end

And the trouble file, PersonListViewController.m

#import "PersonListViewController.h"

@implementation PersonListViewController

@synthesize listOfPeople, currentContext, fetchedResultsController;

#pragma mark -
#pragma mark Initialization

- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization.
        fetcher = [FlickrFetcher sharedInstance];
        currentContext = [fetcher managedObjectContext];

        fetchedResultsController = [fetcher fetchedResultsControllerForEntity:@"Person" withPredicate:nil];
    }
    return self;
}

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"Contacts";
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    Person *person = [fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = [person name];

    // Configure the cell...

    return cell;
}

#pragma mark -
#pragma mark Memory management

- (void)dealloc {
    [super dealloc];
}

@end

I have a feeling I'm missing something simple or 1 off, but I just can't seem to find it.
[FlickrFetcher sharedInstance] returns a singleton, if I toss a few breakpoints into each .m file, I can see that the object id of *fetcher in each area is the same.


问:
Can I search existing IAM policies for a specific action?
In AWS IAM is there a way, either by scripting or in the web console, to find which existing policies contain a given action?

For example, I want to allow role myRole to have access to the DescribeTags action on all of my EC2 instances. I know I can create my own policy with an appropriate rule, but would like to use an existing Amazon policy if such a thing exists.

答:
This is an old post, but it may help someone...  Despite what others have said, you can do this. It just requires a bit of scripting.

You can do the following with the AWS CLI.

Get the ARNs of the policies and store in the policies_arn array.

mapfile -t policies_arn < <(aws iam list-policies --query 'Policies[*].[Arn]' --output text)

Get the VersionIds for each policy and store in the policies_ver array.

mapfile -t policies_ver < <(aws iam list-policies --query 'Policies[*].[DefaultVersionId]' --output text)

Use a for loop to loop through each policy and store the policy document in policies.txt

for (( i=0; i<${#policies_arn[@]}; i++ )); do echo ${policies_arn[i]} >> policies.txt && aws iam get-policy-version --policy-arn ${policies_arn[i]} --version-id ${policies_ver[i]} --output json >> policies.txt; done

Open up policies.txt in a text editor and search for your action.

Note: Depending on your CLI configuration, you may or may not need the --output text parameter. However, the output must be text (not JSON) in order for this to work.

From there, you can turn that into a .sh shell script easily enough.

Sample Output:

```<code>arn:aws:iam::123456789012:policy/DenyAllAccess
{
    "PolicyVersion": {
        "CreateDate": "2016-12-06T18:40:51Z",
        "VersionId": "v1",
        "Document": {
            "Statement": [
                {
                    "Action": "*",
                    "Effect": "Deny",
                    "Resource": "*"
                }
            ],
            "Version": "2012-10-17"
        },
        "IsDefaultVersion": true
    }
}
</code>```

Cheers!

Body:
This is an old post, but it may help someone...  Despite what others have said, you can do this. It just requires a bit of scripting.

You can do the following with the AWS CLI.

Get the ARNs of the policies and store in the policies_arn array.

mapfile -t policies_arn < <(aws iam list-policies --query 'Policies[*].[Arn]' --output text)

Get the VersionIds for each policy and store in the policies_ver array.

mapfile -t policies_ver < <(aws iam list-policies --query 'Policies[*].[DefaultVersionId]' --output text)

Use a for loop to loop through each policy and store the policy document in policies.txt

for (( i=0; i<${#policies_arn[@]}; i++ )); do echo ${policies_arn[i]} >> policies.txt && aws iam get-policy-version --policy-arn ${policies_arn[i]} --version-id ${policies_ver[i]} --output json >> policies.txt; done

Open up policies.txt in a text editor and search for your action.

Note: Depending on your CLI configuration, you may or may not need the --output text parameter. However, the output must be text (not JSON) in order for this to work.

From there, you can turn that into a .sh shell script easily enough.

Sample Output:

arn:aws:iam::123456789012:policy/DenyAllAccess
{
    "PolicyVersion": {
        "CreateDate": "2016-12-06T18:40:51Z",
        "VersionId": "v1",
        "Document": {
            "Statement": [
                {
                    "Action": "*",
                    "Effect": "Deny",
                    "Resource": "*"
                }
            ],
            "Version": "2012-10-17"
        },
        "IsDefaultVersion": true
    }
}

Cheers!


问:
Java Help User Input To Break While Loop
I just made a simple math tutor game but I can't seem to figure out how to break it with a user input. This is what I got so far any help is appreciated.  I now know about comparing strings using .equals but i keep getting errors.

"The method nextString() is undefined for the type Scanner"

and

"Exception in thread "main" InputMismatchException
    at throwFor(Unknown Source)
    at next(Unknown Source)
    at nextDouble(Unknown Source)".

Here is my code:

```<code>  import java.util.Scanner;
  public class HomeWork{

  public static void main(String[] args)  {

   while (true)
{

    Scanner console =new Scanner(System.in);

    double correctAnswer;

    double userResponse;

    String SecondResponse;

    String end = "stop";

    int n1 = (int)(10 * Math.random() + 1);

    int n2 = (int)(10 * Math.random() + 1);

    int operator = (int) (4 * Math.random() + 1);

    if  (operator == 1){

        correctAnswer = n1 + n2;

        System.out.println("What is " + n1 +    " + "    + n2  + " ?");
 } else if ( operator == 2){

        correctAnswer = n1 - n2;

        System.out.println("What is " + n1 +    " - "   + n2 + " ?");

    }  else if ( operator == 3) {

    correctAnswer = n1 * n2;

        System.out.println("What is " + n1 +    " * "   + n2 + " ?");

    }   else {

         correctAnswer = n1 / n2;

        System.out.println("What is " + n1 +    " / "   + n2 + " ?");

    }

    userResponse = console.nextDouble();

    if (userResponse == correctAnswer){
        System.out.println("You got the correct answer!");
        } else {

            System.out.println("Sorry but the correct answer is:" + correctAnswer);

        }

    SecondResponse = console.nextString();

    if(end.equals(SecondResponse))
        System.out.println("End of Program");
        break;

    }
}
}
</code>```

答:
Many problems:

Your very last if... Is missing { braces }!

Because of that your break statement lives in the wrong place, as only that print statement is affected by the if condition.

Then: scanner has in deed no method nextString(). There is only next() for strings!

Don't make assumptions about what methods exist in a class. Consult the javadoc instead, especially when the compiler already gives you a hint that your assumption is not rooted in reality.

Body:
I just made a simple math tutor game but I can't seem to figure out how to break it with a user input. This is what I got so far any help is appreciated.  I now know about comparing strings using .equals but i keep getting errors.

"The method nextString() is undefined for the type Scanner"

and

"Exception in thread "main" InputMismatchException
    at throwFor(Unknown Source)
    at next(Unknown Source)
    at nextDouble(Unknown Source)".

Here is my code:

  import java.util.Scanner;
  public class HomeWork{

  public static void main(String[] args)  {

   while (true)
{

    Scanner console =new Scanner(System.in);

    double correctAnswer;

    double userResponse;

    String SecondResponse;

    String end = "stop";

    int n1 = (int)(10 * Math.random() + 1);

    int n2 = (int)(10 * Math.random() + 1);

    int operator = (int) (4 * Math.random() + 1);

    if  (operator == 1){

        correctAnswer = n1 + n2;

        System.out.println("What is " + n1 +    " + "    + n2  + " ?");
 } else if ( operator == 2){

        correctAnswer = n1 - n2;

        System.out.println("What is " + n1 +    " - "   + n2 + " ?");

    }  else if ( operator == 3) {

    correctAnswer = n1 * n2;

        System.out.println("What is " + n1 +    " * "   + n2 + " ?");

    }   else {

         correctAnswer = n1 / n2;

        System.out.println("What is " + n1 +    " / "   + n2 + " ?");

    }

    userResponse = console.nextDouble();

    if (userResponse == correctAnswer){
        System.out.println("You got the correct answer!");
        } else {

            System.out.println("Sorry but the correct answer is:" + correctAnswer);

        }

    SecondResponse = console.nextString();

    if(end.equals(SecondResponse))
        System.out.println("End of Program");
        break;

    }
}
}


问:
How to update recyclerView from web service periodically without leaking memory
My application makes a webservice call using volley, in order to update recyclerView every 10 seconds. Besides memory usage increase in 10 seconds constantly until it hits the max heap size. Then GC starts doing its job, but the memory usage does not come back down like at the beginning.
Using Eclipse MAT or Android Studio analyzer tasks, I could'nt find a single leak in my code.

I want to know that if there are suspects of leaking in my code. Any help will be appreciated.

Below I have 3 classes:

EventService send a message to MainActivity using sendBroadcast() in every 10 seconds.

MainActiviy will get message from EventService using BroadcastReceiver and calls update operation within its Fragment

EventListFragment, which is inside the MainActivity, contains a RecyclerView, that needs to be updated.

Here is my EventService:

```<code>public class EventService extends Service {
    private volatile boolean isCanceled = false;
    public static final String KEY_MESSAGE = "connection";
    public EventService() {}

       @Override
public int onStartCommand(final Intent intent, int flags, int startId) {
    Runnable r = new Runnable() {
        @Override
        public void run() {
            while (!isCanceled) {
                try {
                    Intent i = new Intent("android.intent.action.MAIN");
                    AppController.getInstance().cancelPendingRequests("json_obj_req");
                    i.putExtra(KEY_MESSAGE, MESSAGE);
                    sendBroadcast(i);
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    Thread eventThread = new Thread(r);
    eventThread.start();
    return Service.START_STICKY;
}

    @Override
    public void onDestroy() {
        isCanceled = true;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}
</code>```

Here is my MainActivity:

```<code>public class MainActivity extends AppCompatActivity {
    private Intent intent;
    private BroadcastReceiver mReceiver;
    private EventListFragment eventListFragment;
    private IntentFilter intentFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private void setView() {
        eventListFragment = (EventListFragment) getSupportFragmentManager().findFragmentById(R.id.frgEventList);
    }

    @Override
    protected void onResume() {
        intent = new Intent(this, EventService.class);
        mReceiver = new MyReceiver(eventListFragment);
        this.registerReceiver(mReceiver, intentFilter);
        intent = new Intent(this, EventService.class);
        startService(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopService(intent);
        unregisterReceiver(mReceiver);
    }

    private static class MyReceiver extends BroadcastReceiver {
        private WeakReference<EventListFragment> eventListFragment = null;
        public MyReceiver(EventListFragment eventFragment) {
            this.eventListFragment = new WeakReference<>(eventFragment);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String mssg = intent.getStringExtra(KEY_MESSAGE);
            EventListFragment eventFragment = eventListFragment.get();
            if (mssg.equals(MESSAGE) && eventFragment != null) {
               //Update recyclerView
                eventFragment.eventToList();
            }
        }
    }
}
</code>```

And here is my EventListFragment:

```<code>public class EventListFragment extends Fragment {

    private View view;
    private RecyclerView recyclerView;
    private LinearLayoutManager mLayoutManager;
    private EventAdapter eventAdapter;
    private RequestData requestData;
    private ArrayList<EventModel> eventList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_event_list, container, false);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        setView();
        setControl();
    }

    private void setView() {
        recyclerView = (RecyclerView) view.findViewById(R.id.frg_recycler_view);
    }

    private void setControl() {
        if (eventAdapter == null && mLayoutManager == null) {
            eventList = new ArrayList<>();
            eventAdapter = new EventAdapter(getActivity().getApplicationContext(), eventList);
            mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
            recyclerView.setLayoutManager(mLayoutManager);
            recyclerView.setHasFixedSize(true);
            recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
            recyclerView.setAdapter(eventAdapter);
        }

        recyclerView.addOnItemTouchListener(new RecyclerItemListener(getActivity().getApplicationContext(), recyclerView, new RecyclerItemListener.RecyclerTouchListener() {
            @Override
            public void onClickItem(View v, int position) {
              EventModel model = eventList.get(position);
                SQLiteHandler db = SQLiteHandler.getInstance(getActivity().getApplicationContext());
                //some instances
            }

            @Override
            public void onLongClickItem(View v, int position) {

            }
        }));
    }
//make service call
    public void eventToList() {
        if (requestData == null) {
            requestData = new RequestData(getActivity());
        }
        final ArrayList<EventModel> newList = new ArrayList<>(); //are you leaking?
        requestData.getEventToday(new RequestData.VolleyCallback() {
            @Override
            public void onSuccess(JSONObject result) {
                for (int i = 0; i < result.length(); i++) {
                    try {

                        JSONObject item = result.getJSONObject(Integer.toString(i));
                        EventModel eventModel = new EventModel();
                        String title = item.getString("title");
                        String start = item.getString("start");
                        String end = item.getString("end");
                        String date = item.getString("date");
                        eventModel.setDate(date);
                        eventModel.setStartTime(start);
                        eventModel.setEndTime(end);
                        eventModel.setTitle(title);
                        newList.add(eventModel);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                eventAdapter.update(newList);

            }
        });

    }
}
</code>```

Many thanks!

答:
First of all, a design consideration: is it necessary to call web service every 10 seconds? Do you know when/how often server data changes?

Every time you read data from web server, application have to do a lot of work: you create many object, update the adapter etc. Moreover, think about network traffic, you use network every 10 seconds.

There are somethings you can do:

Increment wait time: in this way, you reduce the number of created object/per seconds.

Reduce local reference for temporary objects (see following code)

Check if recycler view's adapter, before add new values, the old ones was correctly deferred.

Evaluate if it is possible to use technology to push data, you to avoid data polling. You can see GCM.

For consideration #2, i try rewrite eventToList method:

```<code>public void eventToList() {
  if (requestData == null) {
    requestData = new RequestData(getActivity());
  }
  requestData.getEventToday(new RequestData.VolleyCallback() {
    @Override
    public void onSuccess(JSONObject result) {
      ArrayList<EventModel> newList = new ArrayList<>();
      JSONObject item;
      EventModel eventModel;
      String title;
      String start;
      String end;
      String date;
      for (int i = 0; i < result.length(); i++) {
        try {
          item = result.getJSONObject(Integer.toString(i));
          eventModel = new EventModel();
          title = item.getString("title");
          start = item.getString("start");
          end = item.getString("end");
          date = item.getString("date");
          eventModel.setDate(date);
          eventModel.setStartTime(start);
          eventModel.setEndTime(end);
          eventModel.setTitle(title);
          newList.add(eventModel);
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }
      eventAdapter.update(newList);
    }
 });
</code>```

}

Body:
My application makes a webservice call using volley, in order to update recyclerView every 10 seconds. Besides memory usage increase in 10 seconds constantly until it hits the max heap size. Then GC starts doing its job, but the memory usage does not come back down like at the beginning.
Using Eclipse MAT or Android Studio analyzer tasks, I could'nt find a single leak in my code.

I want to know that if there are suspects of leaking in my code. Any help will be appreciated.

Below I have 3 classes:

EventService send a message to MainActivity using sendBroadcast() in every 10 seconds.

MainActiviy will get message from EventService using BroadcastReceiver and calls update operation within its Fragment

EventListFragment, which is inside the MainActivity, contains a RecyclerView, that needs to be updated.

Here is my EventService:

public class EventService extends Service {
    private volatile boolean isCanceled = false;
    public static final String KEY_MESSAGE = "connection";
    public EventService() {}

       @Override
public int onStartCommand(final Intent intent, int flags, int startId) {
    Runnable r = new Runnable() {
        @Override
        public void run() {
            while (!isCanceled) {
                try {
                    Intent i = new Intent("android.intent.action.MAIN");
                    AppController.getInstance().cancelPendingRequests("json_obj_req");
                    i.putExtra(KEY_MESSAGE, MESSAGE);
                    sendBroadcast(i);
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    Thread eventThread = new Thread(r);
    eventThread.start();
    return Service.START_STICKY;
}

    @Override
    public void onDestroy() {
        isCanceled = true;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}

Here is my MainActivity:

public class MainActivity extends AppCompatActivity {
    private Intent intent;
    private BroadcastReceiver mReceiver;
    private EventListFragment eventListFragment;
    private IntentFilter intentFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private void setView() {
        eventListFragment = (EventListFragment) getSupportFragmentManager().findFragmentById(R.id.frgEventList);
    }

    @Override
    protected void onResume() {
        intent = new Intent(this, EventService.class);
        mReceiver = new MyReceiver(eventListFragment);
        this.registerReceiver(mReceiver, intentFilter);
        intent = new Intent(this, EventService.class);
        startService(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopService(intent);
        unregisterReceiver(mReceiver);
    }

    private static class MyReceiver extends BroadcastReceiver {
        private WeakReference<EventListFragment> eventListFragment = null;
        public MyReceiver(EventListFragment eventFragment) {
            this.eventListFragment = new WeakReference<>(eventFragment);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String mssg = intent.getStringExtra(KEY_MESSAGE);
            EventListFragment eventFragment = eventListFragment.get();
            if (mssg.equals(MESSAGE) && eventFragment != null) {
               //Update recyclerView
                eventFragment.eventToList();
            }
        }
    }
}

And here is my EventListFragment:

public class EventListFragment extends Fragment {

    private View view;
    private RecyclerView recyclerView;
    private LinearLayoutManager mLayoutManager;
    private EventAdapter eventAdapter;
    private RequestData requestData;
    private ArrayList<EventModel> eventList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_event_list, container, false);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        setView();
        setControl();
    }

    private void setView() {
        recyclerView = (RecyclerView) view.findViewById(R.id.frg_recycler_view);
    }

    private void setControl() {
        if (eventAdapter == null && mLayoutManager == null) {
            eventList = new ArrayList<>();
            eventAdapter = new EventAdapter(getActivity().getApplicationContext(), eventList);
            mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
            recyclerView.setLayoutManager(mLayoutManager);
            recyclerView.setHasFixedSize(true);
            recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
            recyclerView.setAdapter(eventAdapter);
        }

        recyclerView.addOnItemTouchListener(new RecyclerItemListener(getActivity().getApplicationContext(), recyclerView, new RecyclerItemListener.RecyclerTouchListener() {
            @Override
            public void onClickItem(View v, int position) {
              EventModel model = eventList.get(position);
                SQLiteHandler db = SQLiteHandler.getInstance(getActivity().getApplicationContext());
                //some instances
            }

            @Override
            public void onLongClickItem(View v, int position) {

            }
        }));
    }
//make service call
    public void eventToList() {
        if (requestData == null) {
            requestData = new RequestData(getActivity());
        }
        final ArrayList<EventModel> newList = new ArrayList<>(); //are you leaking?
        requestData.getEventToday(new RequestData.VolleyCallback() {
            @Override
            public void onSuccess(JSONObject result) {
                for (int i = 0; i < result.length(); i++) {
                    try {

                        JSONObject item = result.getJSONObject(Integer.toString(i));
                        EventModel eventModel = new EventModel();
                        String title = item.getString("title");
                        String start = item.getString("start");
                        String end = item.getString("end");
                        String date = item.getString("date");
                        eventModel.setDate(date);
                        eventModel.setStartTime(start);
                        eventModel.setEndTime(end);
                        eventModel.setTitle(title);
                        newList.add(eventModel);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                eventAdapter.update(newList);

            }
        });

    }
}

Many thanks!

Body:
First of all, a design consideration: is it necessary to call web service every 10 seconds? Do you know when/how often server data changes?

Every time you read data from web server, application have to do a lot of work: you create many object, update the adapter etc. Moreover, think about network traffic, you use network every 10 seconds.

There are somethings you can do:

Increment wait time: in this way, you reduce the number of created object/per seconds.

Reduce local reference for temporary objects (see following code)

Check if recycler view's adapter, before add new values, the old ones was correctly deferred.

Evaluate if it is possible to use technology to push data, you to avoid data polling. You can see GCM.

For consideration #2, i try rewrite eventToList method:

public void eventToList() {
  if (requestData == null) {
    requestData = new RequestData(getActivity());
  }
  requestData.getEventToday(new RequestData.VolleyCallback() {
    @Override
    public void onSuccess(JSONObject result) {
      ArrayList<EventModel> newList = new ArrayList<>();
      JSONObject item;
      EventModel eventModel;
      String title;
      String start;
      String end;
      String date;
      for (int i = 0; i < result.length(); i++) {
        try {
          item = result.getJSONObject(Integer.toString(i));
          eventModel = new EventModel();
          title = item.getString("title");
          start = item.getString("start");
          end = item.getString("end");
          date = item.getString("date");
          eventModel.setDate(date);
          eventModel.setStartTime(start);
          eventModel.setEndTime(end);
          eventModel.setTitle(title);
          newList.add(eventModel);
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }
      eventAdapter.update(newList);
    }
 });

}


答:
The most obvious answer is side effects:

```<code>int getCost()
{
    if (cost == null) {
        calculateCost();
    }

    return cost;
}
</code>```

If you need the cost, use getCost(). If you want to see if cost has been calculated, use cost.

Title: Is there any benefit to using getters/setters inside a class for its own fields?

Body:
Usually, in my own projects I use getters and setters for any field access, and I followed to do the same on my job. Some time ago, the tech lead of our project asked me why I was doing that and why is this better than just using fields themselves (with an option of declaring them protected if they needed to be accessed by subclasses). I couldn't come up with a clear answer.

So, are there any reasons to using getters and setters inside a class for class' own fields, or is it better to use fields directly?

Body:
The most obvious answer is side effects:

int getCost()
{
    if (cost == null) {
        calculateCost();
    }

    return cost;
}

If you need the cost, use getCost(). If you want to see if cost has been calculated, use cost.


问:
Good Values for Knuth's multiplication method - Hashing
Any guesses what are good values for the "c"?

```<code>// h(k) = ⌊(m · (k · c − ⌊k · c⌋)⌋
return (int) Math.floor(distinctElements * (key * c - Math.floor(key * c)));
</code>```

I have found the this one: (Math.sqrt(5)-1)/2)

However are there any other good choices known?

Kind regards

答:
The value you've found is the number known as phi (φ), the golden ratio. It's not actually correct to use that... what you should be using is its multiplicative inverse, φ^-1. φ^-1 and φ^-2 have the special property of tending to optimally spread out the hash values regardless of the range of your inputs.

However, for sufficiently large range, pretty much any irrational number will do.

Body:
Any guesses what are good values for the "c"?

// h(k) = ⌊(m · (k · c − ⌊k · c⌋)⌋
return (int) Math.floor(distinctElements * (key * c - Math.floor(key * c)));

I have found the this one: (Math.sqrt(5)-1)/2)

However are there any other good choices known?

Kind regards


问:
Merging lists of different sizes in clojure
I have 2 lists

s = [1 2 3 4 5]

and

p = [:a :b :c :d :e :f :h :i :j :k :l :m]

I would like to take N elements from p where N is a random number between 1 to K and create a mapping from s to these N elements from p.

the resulting mapping could be something like

((1 :a) (1 :b) (1 :c) (2 :d) (2 :e) (3 :f) (4 :h) (4 :i) (5 :j) (5 :k) (5 :l))

for K=3.

it's fine if not all the elements in p are used but there are enough elements to cover the case where N is max for all elements in s.

I've come up with this but it's missing the take random N elements part and assigns an (almost) equal number of elements to each element in s

(partition 2 (interleave (cycle s) (shuffle p))))

this results in

((1 :d) (2 :f) (3 :h) (4 :e) (5 :l) (1 :b) (2 :k) (3 :a) (4 :j) (5 :g) (1 :i) (2 :c) (3 :m))

UPDATE:
Let me add some more context to the question for a better understanding.
I'm trying to generate a galaxy where each star will have 1 to N planets in it's system. The s list contains the ids of the stars, and the p list contains the ids of planets. I would like to map planet ids to star ids so each system has 1 to N random planets in the system.

答:
I hope I understood your question correctly:

```<code>(def s [1 2 3 4 5])
(def p [:a :b :c :d :e :f :h :i :j :k :l :m])
(def k 3)

;; concatenate corresponding elements from two sequences into 2-element vectors
(map vector
     ;; generate a sequence of elements from s each duplicated 1 to k times
     (mapcat #(repeat (inc (rand-int k)) %) s)
     ;; generate infinite shuffled seq of elements from p
     (cycle (shuffle p)))
</code>```

Example output:

```<code>([1 :f] [2 :j] [2 :b] [3 :m] [3 :a] [4 :i] [5 :l] [5 :c] [5 :e])
</code>```

Body:
I hope I understood your question correctly:

(def s [1 2 3 4 5])
(def p [:a :b :c :d :e :f :h :i :j :k :l :m])
(def k 3)

;; concatenate corresponding elements from two sequences into 2-element vectors
(map vector
     ;; generate a sequence of elements from s each duplicated 1 to k times
     (mapcat #(repeat (inc (rand-int k)) %) s)
     ;; generate infinite shuffled seq of elements from p
     (cycle (shuffle p)))

Example output:

([1 :f] [2 :j] [2 :b] [3 :m] [3 :a] [4 :i] [5 :l] [5 :c] [5 :e])


问:
Unable to run cygwin in Windows Docker Container
I've been working with Docker for Windows, attempting to create a Windows Container that can run cygwin as the shell within the container itself. I haven't had any luck getting this going yet. Here's the Dockerfile that I've been messing with.

```<code># escape=`
FROM microsoft/windowsservercore

SHELL ["powershell", "-command"]

RUN Invoke-WebRequest https://chocolatey.org/install.ps1 -UseBasicParsing | Invoke-Expression
RUN choco install cygwin -y
RUN refreshenv
RUN [Environment]::SetEnvironmentVariable('Path', $env:Path + ';C:\tools\cygwin\bin', [EnvironmentVariableTarget]::Machine)
</code>```

I've tried setting the ENTRYPOINT and CMD to try and get into cygwin, but neither seems to do anything. I've also attached to the container with docker run -it and fired off the cygwin command to get into the shell, but it doesn't appear to do anything. I don't get an error, it just returns to the command prompt as if nothing happened.

Is it possible to run another shell in the Windows Container, or am I just doing something incorrectly?

Thanks!

答:
You don't "attach" to a container with docker run: you start a container with it.

In your case, as seen here, docker run -it is the right approach.

You can try as an entry point using c:\cygwin\bin\bash, as seen in this issue.

As commented in issue 32330:

Don't get me wrong, cygwin should work in Docker Windows containers.

But, it's also a little paradoxical that containers were painstakingly wrought into Windows, modeled on containers on Linux, only for people to then want to run Linux-utils in these newly minted Docker Windows containers...

That same issue is still unresolved, with new case seen in May and June 2018:

We have an environment that compiles with Visual Studio but still we want to use git and some very useful commands taken from linux.

  Also we use of-the-shelve utilities (e.g. git-repo) that uses linux commands (e.g. curl, grep,...)

Some builds require Cygwin like ICU (a cross-platform Unicode based globalization library), and worst: our builds require building it from source.

You can see an example of a crash in MSYS2-packages issue 1239:

```<code>Step 5/5 : RUN "C:\\msys64\\usr\\bin\\ls.exe"
 ---> Running in 5d7867a1f8da
The command 'cmd /S /C "C:\\msys64\\usr\\bin\\ls.exe"' returned a non-zero code: 3221225794
</code>```

This can get more information on the crash:

```<code>PS C:\msys64\usr\bin>
  Get-EventLog -Index 28,29,30 -LogName "Application" | Format-List -Property *
</code>```

The workaround was:

```<code>PS > xcopy /S C:\Git C:\Git_Copy
PS > C:\Git_Copy\usr\bin\sh.exe --version > v.txt
PS > type v.txt
</code>```

As mentioned in that thread, the output gets lost somewhere in the container, thus sending it to a text file.

Body:
I've been working with Docker for Windows, attempting to create a Windows Container that can run cygwin as the shell within the container itself. I haven't had any luck getting this going yet. Here's the Dockerfile that I've been messing with.

# escape=`
FROM microsoft/windowsservercore

SHELL ["powershell", "-command"]

RUN Invoke-WebRequest https://chocolatey.org/install.ps1 -UseBasicParsing | Invoke-Expression
RUN choco install cygwin -y
RUN refreshenv
RUN [Environment]::SetEnvironmentVariable('Path', $env:Path + ';C:\tools\cygwin\bin', [EnvironmentVariableTarget]::Machine)

I've tried setting the ENTRYPOINT and CMD to try and get into cygwin, but neither seems to do anything. I've also attached to the container with docker run -it and fired off the cygwin command to get into the shell, but it doesn't appear to do anything. I don't get an error, it just returns to the command prompt as if nothing happened.

Is it possible to run another shell in the Windows Container, or am I just doing something incorrectly?

Thanks!

Body:
You don't "attach" to a container with docker run: you start a container with it.

In your case, as seen here, docker run -it is the right approach.

You can try as an entry point using c:\cygwin\bin\bash, as seen in this issue.

As commented in issue 32330:

Don't get me wrong, cygwin should work in Docker Windows containers.

But, it's also a little paradoxical that containers were painstakingly wrought into Windows, modeled on containers on Linux, only for people to then want to run Linux-utils in these newly minted Docker Windows containers...

That same issue is still unresolved, with new case seen in May and June 2018:

We have an environment that compiles with Visual Studio but still we want to use git and some very useful commands taken from linux.

  Also we use of-the-shelve utilities (e.g. git-repo) that uses linux commands (e.g. curl, grep,...)

Some builds require Cygwin like ICU (a cross-platform Unicode based globalization library), and worst: our builds require building it from source.

You can see an example of a crash in MSYS2-packages issue 1239:

Step 5/5 : RUN "C:\\msys64\\usr\\bin\\ls.exe"
 ---> Running in 5d7867a1f8da
The command 'cmd /S /C "C:\\msys64\\usr\\bin\\ls.exe"' returned a non-zero code: 3221225794

This can get more information on the crash:

PS C:\msys64\usr\bin>
  Get-EventLog -Index 28,29,30 -LogName "Application" | Format-List -Property *

The workaround was:

PS > xcopy /S C:\Git C:\Git_Copy
PS > C:\Git_Copy\usr\bin\sh.exe --version > v.txt
PS > type v.txt

As mentioned in that thread, the output gets lost somewhere in the container, thus sending it to a text file.


答:
but i keep getting an error. "The method nextString() is undefined for
  the type Scanner"

change this:

```<code>SecondResponse = console.nextString();
</code>```

to this:

```<code>SecondResponse = console.next();
</code>```

Also, make sure you open and close the braces properly:

```<code>if(end.equals(SecondResponse)) {
     System.out.println("End of Program");
     break;
}
</code>```

Title: Java Help User Input To Break While Loop

Body:
but i keep getting an error. "The method nextString() is undefined for
  the type Scanner"

change this:

SecondResponse = console.nextString();

to this:

SecondResponse = console.next();

Also, make sure you open and close the braces properly:

if(end.equals(SecondResponse)) {
     System.out.println("End of Program");
     break;
}


问:
Vue.js hiding of items outside current viewport
I'm making an e-commerce type menu in Vue.js, with items which are divs that contain a fair amount of functionality and images. Performance is fairly good when rendering about 200 of these items, but when more than that many are added the site begins to perform sluggishly.

What's the best way to conditionally hide or remove Vue elements from the DOM if they are outside the current scrollable view (like ScrollViews in iOS)? Are there any plugins or libraries that can help with the performance of long lists of data items in Vue.js?

Thanks!

答:
I've made a demo snippet using the package I mentioned in my comment.

I've made a "signal" item that acts as the watcher. When the "signal" item leaves the viewport, the "complex-stuff" is no longer rendered. I did it this way so you can see the "complex-stuff" disappear. When the "signal" scrolls back into view, the "complex-stuff" is rendered.

You could just put the watcher on the widget root element and things will only be hidden when the whole widget is out of view. You don't want to put the v-if on the root element, though, or it will never come back once it goes away.

const containerMonitor = scrollMonitor.createContainer(document.body);

new Vue({
  el: '#app',
  data: {
    ids: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
  },
  components: {
    widget: {
      template: '#widget-template',
      props: ['id'],
      data() {
        return {
          visible: true
        };
      },
      mounted() {
        const elementWatcher = containerMonitor.create(this.$el.querySelector('.signal'));

        elementWatcher.enterViewport(() => {
          this.visible = true;
        });
        elementWatcher.exitViewport(() => {
          this.visible = false;
        });
      }
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.widget-container {
  height: 200px;
  margin: 10px;
  background-color: #f0f0f0;
  display: flex;
  flex-flow: row wrap;
}

.signal {
  height: 10px;
  width: 10px;
  margin: 30px;
  background-color: red;
  border: thin solid blue;
}

.complex-stuff {
  flex-basis: 100%;
  padding: 15px;
}</code>```

<template id="widget-template">

      This is widget {{id}}.
      Blah blah blah.

</template>

  Widgets below:
  <widget v-for="id in ids" :id="id"></widget>
  :widgets above

```

Body:
I've made a demo snippet using the package I mentioned in my comment.

I've made a "signal" item that acts as the watcher. When the "signal" item leaves the viewport, the "complex-stuff" is no longer rendered. I did it this way so you can see the "complex-stuff" disappear. When the "signal" scrolls back into view, the "complex-stuff" is rendered.

You could just put the watcher on the widget root element and things will only be hidden when the whole widget is out of view. You don't want to put the v-if on the root element, though, or it will never come back once it goes away.

const containerMonitor = scrollMonitor.createContainer(document.body);

new Vue({
  el: '#app',
  data: {
    ids: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
  },
  components: {
    widget: {
      template: '#widget-template',
      props: ['id'],
      data() {
        return {
          visible: true
        };
      },
      mounted() {
        const elementWatcher = containerMonitor.create(this.$el.querySelector('.signal'));

        elementWatcher.enterViewport(() => {
          this.visible = true;
        });
        elementWatcher.exitViewport(() => {
          this.visible = false;
        });
      }
    }
  }
});

.widget-container {
  height: 200px;
  margin: 10px;
  background-color: #f0f0f0;
  display: flex;
  flex-flow: row wrap;
}

.signal {
  height: 10px;
  width: 10px;
  margin: 30px;
  background-color: red;
  border: thin solid blue;
}

.complex-stuff {
  flex-basis: 100%;
  padding: 15px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<script src="https://rawgit.com/stutrek/scrollMonitor/master/scrollMonitor.js"></script>

<template id="widget-template">
  <div class="widget-container">
    <div class="signal">
    </div>
    <div v-if="visible" class="complex-stuff">
      This is widget {{id}}.
      Blah blah blah.
    </div>
  </div>
</template>

<div id="app">
  Widgets below:
  <widget v-for="id in ids" :id="id"></widget>
  :widgets above
</div>


问:
How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops
How can I use regular expressions in Excel and take advantage of Excel's powerful grid-like setup for data manipulation?

In-cell function to return a matched pattern or replaced value in a string.

Sub to loop through a column of data and extract matches to adjacent cells.

What setup is necessary?

What are Excel's special characters for Regular expressions?

I understand Regex is not ideal for many situations (To use or not to use regular expressions?) since excel can use Left, Mid, Right, Instr type commands for similar manipulations.

答:
Expanding on patszim's answer for those in a rush.

Open Excel workbook.

Alt+F11 to open VBA/Macros window.

Add reference to regex under Tools then References

and selecting Microsoft VBScript Regular Expression 5.5

Insert a new module (code needs to reside in the module otherwise it doesn't work).

In the newly inserted module,

add the following code:

```<code>Function RegxFunc(strInput As String, regexPattern As String) As String
    Dim regEx As New RegExp
    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .pattern = regexPattern
    End With

    If regEx.Test(strInput) Then
        Set matches = regEx.Execute(strInput)
        RegxFunc = matches(0).Value
    Else
        RegxFunc = "not matched"
    End If
End Function
</code>```

The regex pattern is placed in one of the cells and absolute referencing is used on it.

Function will be tied to workbook that its created in.

If there's a need for it to be used in different workbooks, store the function in Personal.XLSB

Body:
Expanding on patszim's answer for those in a rush.

Open Excel workbook.

Alt+F11 to open VBA/Macros window.

Add reference to regex under Tools then References

and selecting Microsoft VBScript Regular Expression 5.5

Insert a new module (code needs to reside in the module otherwise it doesn't work).

In the newly inserted module,

add the following code:

Function RegxFunc(strInput As String, regexPattern As String) As String
    Dim regEx As New RegExp
    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .pattern = regexPattern
    End With

    If regEx.Test(strInput) Then
        Set matches = regEx.Execute(strInput)
        RegxFunc = matches(0).Value
    Else
        RegxFunc = "not matched"
    End If
End Function

The regex pattern is placed in one of the cells and absolute referencing is used on it.

Function will be tied to workbook that its created in.

If there's a need for it to be used in different workbooks, store the function in Personal.XLSB