问:
Child Model List is Empty after DB Add in Entity Framework Core
So I am trying out Entity Framework Core, and am having trouble with my first pair of relational Models. I'm trying to use conventions to form the relationship, as follows:

The principal entity, with conventional principal key (Id) and collection navigation property (the list of Locations):

```<code>public class Site
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public int LocationCount { get; set; } = 1;
    public List<Location> Locations { get; set; } = new List<Location>();
}
</code>```

The dependent entity, with conventional foreign key (SiteId) and reference navigation property (Site):

```<code>public class Location
{
    public int Id { get; set; }
    public int SiteId { get; set; }
    public Site Site { get; set; }
    public int AreaCount { get; set; } = 1;
    public Location(Site site) { SiteId = site.Id; }
}
</code>```

And since I want every Site to already have at least one location, I put this in the Create action of the SiteController, in an attempt to create the dependents along with the principal:

```<code>[HttpPost]
public IActionResult Create(Site site)
{
    _context.Sites.Add(site);
    for (int i = 0; i < site.LocationCount; i++)
        _context.Locations.Add(new Location(site));
    _context.SaveChanges();
    return RedirectToAction("Details", new { Name = site.Name });
}
</code>```

However, on the Details view, when I try to display the Locations that were created, the list is always empty:

```<code><h2>@Model.Locations.Count Locations</h2>
@foreach (Location l in Model.Locations)
{
    <div class="row">
        <div class="col-sm-12">@l.Id</div>
    </div>
}
</code>```

Just results in:

```<code>0 Locations
</code>```

Thank you in advance for any help explaining what I've missed!

Edit: By request, here is the body of the Details action in the Site Controller, which gets the Model data for the Details View:

```<code>public IActionResult Details(string name)
{
    var model = _context.Sites.FirstOrDefault(a => a.Name == name);
    if (model == null) model = new Site();
    return View(model);
}
</code>```

Also, per one suggestion, I have fixed the problem of setting the Location.SiteId before Site.Id has a value, since the Id isn't automatically generated on the Site until after SaveChanges() is called. Unfortunately, the result (empty Locations list) is still the same:

```<code>[HttpPost]
public IActionResult Create(Site site)
{
    int nextsiteid = _context.Sites.Count() + 1;
    _context.Sites.Add(site);
    for (int i = 0; i < site.LocationCount; i++)
        _context.Locations.Add(new Location(siteid));
    _context.SaveChanges();
    return RedirectToAction("Details", new { Name = site.Name });
}
</code>```

And changed the Location constructor to use the Id instead of the instance:

```<code>public Location(int siteid) { SiteId = siteid; }
</code>```

Thanks in advance for any further suggestions!

答:
if the Lazy Loading is true. No need to loop over or navigate its child. its will save your parent and as well its child. make sure are you getting parents and its child

```<code>[HttpPost]
public IActionResult Create(Site site)
{  // debug here are you getting parent & its child ?
_context.Sites.Add(site);
   // for (int i = 0; i < site.LocationCount; i++)  // No need of it
   // _context.Locations.Add(new Location(site));   // No need of it
_context.SaveChanges();
return RedirectToAction("Details", new { Name = site.Name });
}
</code>```

Updated:
if these two tables are linked with each other & you are manually trying to add location table . Let me give you a simple , hope this will help you

```<code>[HttpPost]
public IActionResult Create(Site site)
{  // debug here are you getting parent & its child ?
_context.Sites.Add(site);
   // get the last added site id

   int? maxId=
  _context.Sites.orderbyDecending(x=>x.SiteId).FirstorDefault(x=>x.SiteId);// may be in this line typing mistake , you change it according to linq
    foreach(var i in site.Location)
    {
      // in this loop traverse the child array and override the foreign key id with last added id
       i.SiteId =maxId;
      _context.Locations.Add(i);
    }

_context.SaveChanges();
return RedirectToAction("Details", new { Name = site.Name });
}
</code>```

Body:
So I am trying out Entity Framework Core, and am having trouble with my first pair of relational Models. I'm trying to use conventions to form the relationship, as follows:

The principal entity, with conventional principal key (Id) and collection navigation property (the list of Locations):

public class Site
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public int LocationCount { get; set; } = 1;
    public List<Location> Locations { get; set; } = new List<Location>();
}

The dependent entity, with conventional foreign key (SiteId) and reference navigation property (Site):

public class Location
{
    public int Id { get; set; }
    public int SiteId { get; set; }
    public Site Site { get; set; }
    public int AreaCount { get; set; } = 1;
    public Location(Site site) { SiteId = site.Id; }
}

And since I want every Site to already have at least one location, I put this in the Create action of the SiteController, in an attempt to create the dependents along with the principal:

[HttpPost]
public IActionResult Create(Site site)
{
    _context.Sites.Add(site);
    for (int i = 0; i < site.LocationCount; i++)
        _context.Locations.Add(new Location(site));
    _context.SaveChanges();
    return RedirectToAction("Details", new { Name = site.Name });
}

However, on the Details view, when I try to display the Locations that were created, the list is always empty:

@Model.Locations.Count Locations

@foreach (Location l in Model.Locations)
{

@l.Id

}

Just results in:

0 Locations

Thank you in advance for any help explaining what I've missed!

Edit: By request, here is the body of the Details action in the Site Controller, which gets the Model data for the Details View:

public IActionResult Details(string name)
{
    var model = _context.Sites.FirstOrDefault(a => a.Name == name);
    if (model == null) model = new Site();
    return View(model);
}

Also, per one suggestion, I have fixed the problem of setting the Location.SiteId before Site.Id has a value, since the Id isn't automatically generated on the Site until after SaveChanges() is called. Unfortunately, the result (empty Locations list) is still the same:

[HttpPost]
public IActionResult Create(Site site)
{
    int nextsiteid = _context.Sites.Count() + 1;
    _context.Sites.Add(site);
    for (int i = 0; i < site.LocationCount; i++)
        _context.Locations.Add(new Location(siteid));
    _context.SaveChanges();
    return RedirectToAction("Details", new { Name = site.Name });
}

And changed the Location constructor to use the Id instead of the instance:

public Location(int siteid) { SiteId = siteid; }

Thanks in advance for any further suggestions!

Body:
if the Lazy Loading is true. No need to loop over or navigate its child. its will save your parent and as well its child. make sure are you getting parents and its child

[HttpPost]
public IActionResult Create(Site site)
{  // debug here are you getting parent & its child ?
_context.Sites.Add(site);
   // for (int i = 0; i < site.LocationCount; i++)  // No need of it
   // _context.Locations.Add(new Location(site));   // No need of it
_context.SaveChanges();
return RedirectToAction("Details", new { Name = site.Name });
}

Updated:
if these two tables are linked with each other & you are manually trying to add location table . Let me give you a simple , hope this will help you

[HttpPost]
public IActionResult Create(Site site)
{  // debug here are you getting parent & its child ?
_context.Sites.Add(site);
   // get the last added site id

   int? maxId=
  _context.Sites.orderbyDecending(x=>x.SiteId).FirstorDefault(x=>x.SiteId);// may be in this line typing mistake , you change it according to linq
    foreach(var i in site.Location)
    {
      // in this loop traverse the child array and override the foreign key id with last added id
       i.SiteId =maxId;
      _context.Locations.Add(i);
    }

_context.SaveChanges();
return RedirectToAction("Details", new { Name = site.Name });
}


来源: stackexchange

问:
how to distribute items in number of lists?
Question: How to distribute items in number of lists? following are examples:

Imagine I have a 8 lists, and 5 items. in this case list 1 to 5 will have 1 item.  rest of lists remain empty.

Now If I have 8 lists and 16 items each list will have 2 items.

If I have 8 lists and 11 items, list 1 to 3 will have two items. rest of the lists will have 1 item.

```<code>var items = new List<object>();
var containers = new List<List<object>>();

int c = -1; // indexer for container.

for(int i = 0; i < items.Count; i++)
{
    // disturbute items to containers

    if (i % (items.Count/containers.Count) == 0) c++; // this is wrong. when to increment?

    containers[c].Add(items[i]);
}
</code>```

I'm pretty sure only if statement is wrong. Its getting confusing how to handle i.

答:
If you want to isolate this behavior into something reusable and testable:

```<code>public class ListBalancer
{
    public void BalanceItemsBetweenLists<T>(
        IEnumerable<T> input,
        IEnumerable<IList<T>> targets)
    {
        var inputArray = input as T[] ?? input.ToArray();
        var targetArray = targets as IList<T>[] ?? targets.ToArray();
        var currentTargetIndex = 0;
        foreach (var item in inputArray)
        {
            targetArray[currentTargetIndex].Add(item);
            currentTargetIndex++;
            if (currentTargetIndex == targetArray.Length) currentTargetIndex = 0;
        }
    }
}

[TestClass]
public class ListBalancerTests
{
    [TestMethod]
    public void BalancesListsWhenAddingItems()
    {
        var source = Enumerable.Range(1, 11);
        var targets = Enumerable.Range(1, 8).Select(n => new List<int>()).ToArray();
        new ListBalancer().BalanceItemsBetweenLists(source, targets);

        Assert.AreEqual(2, targets[0].Count);
        Assert.AreEqual(2, targets[1].Count);
        Assert.AreEqual(2, targets[2].Count);
        Assert.AreEqual(1, targets[3].Count);
    }
}
</code>```

It seems like a little bit of extra work. But you probably found that the process of debugging when it didn't do what was expected took a little extra time, too. It might have been necessary to start a console application or some other app to test the behavior. If you write a class with a unit test you might still have to debug, but it's faster and more self-contained. You finish the one class with the one behavior, test it, and then move on.

Personally I found that once I formed the habit I could write code a little faster and with fewer bugs because I made my debugging process smaller and easier.

ContentLicense: CC BY-SA 3.0

Body:
Question: How to distribute items in number of lists? following are examples:

Imagine I have a 8 lists, and 5 items. in this case list 1 to 5 will have 1 item.  rest of lists remain empty.

Now If I have 8 lists and 16 items each list will have 2 items.

If I have 8 lists and 11 items, list 1 to 3 will have two items. rest of the lists will have 1 item.

var items = new List<object>();
var containers = new List<List<object>>();

int c = -1; // indexer for container.

for(int i = 0; i < items.Count; i++)
{
    // disturbute items to containers

    if (i % (items.Count/containers.Count) == 0) c++; // this is wrong. when to increment?

    containers[c].Add(items[i]);
}

I'm pretty sure only if statement is wrong. Its getting confusing how to handle i.

Body:
If you want to isolate this behavior into something reusable and testable:

public class ListBalancer
{
    public void BalanceItemsBetweenLists<T>(
        IEnumerable<T> input,
        IEnumerable<IList<T>> targets)
    {
        var inputArray = input as T[] ?? input.ToArray();
        var targetArray = targets as IList<T>[] ?? targets.ToArray();
        var currentTargetIndex = 0;
        foreach (var item in inputArray)
        {
            targetArray[currentTargetIndex].Add(item);
            currentTargetIndex++;
            if (currentTargetIndex == targetArray.Length) currentTargetIndex = 0;
        }
    }
}

[TestClass]
public class ListBalancerTests
{
    [TestMethod]
    public void BalancesListsWhenAddingItems()
    {
        var source = Enumerable.Range(1, 11);
        var targets = Enumerable.Range(1, 8).Select(n => new List<int>()).ToArray();
        new ListBalancer().BalanceItemsBetweenLists(source, targets);

        Assert.AreEqual(2, targets[0].Count);
        Assert.AreEqual(2, targets[1].Count);
        Assert.AreEqual(2, targets[2].Count);
        Assert.AreEqual(1, targets[3].Count);
    }
}

It seems like a little bit of extra work. But you probably found that the process of debugging when it didn't do what was expected took a little extra time, too. It might have been necessary to start a console application or some other app to test the behavior. If you write a class with a unit test you might still have to debug, but it's faster and more self-contained. You finish the one class with the one behavior, test it, and then move on.

Personally I found that once I formed the habit I could write code a little faster and with fewer bugs because I made my debugging process smaller and easier.


问:
I am working on this code to update google contacts with google forms and spreadsheet linked to it
I want this code to auto add contacts using trigger when form is submit but i get errors.
The code works properly with spreadsheet but I am not able get it work with forms.
I am kind of noob with coding.
So simple explanation would be helpful

Also contacts get add to "other" group in google contacts,is there any way to add them directly to "my contacts"?

```<code>function createHeaders() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];

  // Freezes the first row
  sheet.setFrozenRows(1);

  // Set the values we want for headers
  var values = [
    ["First Name", "Last Name", "Email", "Phone Number", "Company", "Notes"]
  ];

  // Set the range of cells
  var range = sheet.getRange("A1:F1");

  // Call the setValues method on range and pass in our values
  range.setValues(values);
}

function createContact() {
  var alreadyAdded = "Already added";
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 2;   // Number of rows to process

  // Fetch the range of cells A2:G3
  var dataRange = sheet.getRange(startRow, 1, numRows, 8)

  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
    for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var firstName = row[0]
    var lastName = row[1]
    var emailAddress = row[2]
    var phone = row[3]
    var company = row[4]
    var notes = row[5]
    var addedAlready = row[6];

      if (addedAlready != alreadyAdded) {
      // Create contact in Google Contacts
      var contact = ContactsApp.createContact(firstName, lastName, emailAddress);

      // Add values to new contact
      contact.addCompany(company, "");
      contact.addPhone(ContactsApp.Field.WORK_PHONE, phone);
      contact.setNotes(notes);
      sheet.getRange(startRow + i, 7).setValue(alreadyAdded);
      };
    };
};
</code>```

答:
I see you're trying to connect your Spreadsheet to Google Form. Check the Connecting to Google Forms

Apps Script allows you to connect Google Forms with Google Sheets
  through Forms and Spreadsheet services. This feature can automatically
  create a Google Form based on data in a spreadsheet. Apps Script also
  enables you to use triggers, such as onFormSubmit to perform a
  specific action after a user responds to the form.

you might be referring to onFormSubmit.

Here's the code demo for your reference.

Body:
I want this code to auto add contacts using trigger when form is submit but i get errors.
The code works properly with spreadsheet but I am not able get it work with forms.
I am kind of noob with coding.
So simple explanation would be helpful

Also contacts get add to "other" group in google contacts,is there any way to add them directly to "my contacts"?

function createHeaders() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];

  // Freezes the first row
  sheet.setFrozenRows(1);

  // Set the values we want for headers
  var values = [
    ["First Name", "Last Name", "Email", "Phone Number", "Company", "Notes"]
  ];

  // Set the range of cells
  var range = sheet.getRange("A1:F1");

  // Call the setValues method on range and pass in our values
  range.setValues(values);
}

function createContact() {
  var alreadyAdded = "Already added";
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 2;   // Number of rows to process

  // Fetch the range of cells A2:G3
  var dataRange = sheet.getRange(startRow, 1, numRows, 8)

  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
    for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var firstName = row[0]
    var lastName = row[1]
    var emailAddress = row[2]
    var phone = row[3]
    var company = row[4]
    var notes = row[5]
    var addedAlready = row[6];

      if (addedAlready != alreadyAdded) {
      // Create contact in Google Contacts
      var contact = ContactsApp.createContact(firstName, lastName, emailAddress);

      // Add values to new contact
      contact.addCompany(company, "");
      contact.addPhone(ContactsApp.Field.WORK_PHONE, phone);
      contact.setNotes(notes);
      sheet.getRange(startRow + i, 7).setValue(alreadyAdded);
      };
    };
};


问:
Having a non bound sampler inside an uniform branch
Lets say I have pixel shader that sometimes need to read from one sampler and sometimes needs to read from two different samplers, depending on a uniform variable

```<code>layout (set = 0, binding = 0) uniform UBO {
   ....
   bool useSecondTexture;
} ubo;
...
void main() {
   vec3 value0 = texture(sampler1, pos).rgb;
   vec3 value2 = vec3(0,0,0);
   if(ubo.useSecondTexture) {
       value2 = texture(sampler2, pos).rgb;
   }
   value0 += value2;
}
</code>```

Does the second sampler; sampler2 need to be bound to a valid texture even though the texture will not be read if useSecondTexture is false.

答:
All of the vkCmdDraw and vkCmdDispatch commands have this Valid Usage statement:

Descriptors in each bound descriptor set, specified via vkCmdBindDescriptorSets, must be valid if they are statically used by the currently bound VkPipeline object, specified via vkCmdBindPipeline

Since sampler2 is statically used, you must have a valid descriptor for it or you'll get undefined behavior.

My guess is that on some implementations, it'll work as you expect. But drivers/hardware are allowed to require that all descriptors that might be used by a pipeline are valid, and requiring them to inspect the contents of memory buffers to determine if something might be used would be very expensive.

Body:
Lets say I have pixel shader that sometimes need to read from one sampler and sometimes needs to read from two different samplers, depending on a uniform variable

layout (set = 0, binding = 0) uniform UBO {
   ....
   bool useSecondTexture;
} ubo;
...
void main() {
   vec3 value0 = texture(sampler1, pos).rgb;
   vec3 value2 = vec3(0,0,0);
   if(ubo.useSecondTexture) {
       value2 = texture(sampler2, pos).rgb;
   }
   value0 += value2;
}

Does the second sampler; sampler2 need to be bound to a valid texture even though the texture will not be read if useSecondTexture is false.


问:
Irregular crash when creating NSManagedObject out of NSSet
I have an irregular crash (1 in 5 times on devices, 4 in 5 times on Simulator). I have set an exception breakpoint and it occurs on the following line without any console information:

if let carColorSet = car.carToDisplay?.allObjects as? [Display] {
```
<p><strong>Note: <code>car.carToDisplay</code> is an NSSet</strong></p>
<p>Before I set the exception breakpoint, I would get the following info in the console when it crashed:</p>
```Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSMutableSet unionSet:]: set argument is not an NSSet'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000102e79b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00000001023d6141 objc_exception_throw + 48
    2   CoreFoundation                      0x0000000102e00051 -[NSMutableSet unionSet:] + 1041
    3   CoreData                            0x0000000101b10df8 -[_NSFaultingMutableSet willReadWithContents:] + 936
    4   CoreData                            0x0000000101af131b -[_NSFaultingMutableSet allObjects] + 27
    5   Keyboard                            0x00000001018f838e
```

Any idea here? It seems like the crash occurs when I try to turn that carToDisplay?.allObjects into an array of Display objects.

This is a keyboard extension app btw.

Thank you for any input!

答:
Problem (probably):

```<code>if let carColorSet = car.carToDisplay?.allObjects as? [Display]
</code>```

carToDisplay is a NSet
However the function allObjects returns an array

I think you are trying to do a unionSet with an array.

Update the Question:

Please update your question, the qestion doesn't state the correct line of error.

The question needs to do the following

state where the unionSet is invoked.

what the argument type of unionSet is.

ContentLicense: CC BY-SA 4.0

Body:
I have an irregular crash (1 in 5 times on devices, 4 in 5 times on Simulator). I have set an exception breakpoint and it occurs on the following line without any console information:

if let carColorSet = car.carToDisplay?.allObjects as? [Display] {

Note: car.carToDisplay is an NSSet

Before I set the exception breakpoint, I would get the following info in the console when it crashed:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSMutableSet unionSet:]: set argument is not an NSSet'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000102e79b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00000001023d6141 objc_exception_throw + 48
    2   CoreFoundation                      0x0000000102e00051 -[NSMutableSet unionSet:] + 1041
    3   CoreData                            0x0000000101b10df8 -[_NSFaultingMutableSet willReadWithContents:] + 936
    4   CoreData                            0x0000000101af131b -[_NSFaultingMutableSet allObjects] + 27
    5   Keyboard                            0x00000001018f838e

Any idea here? It seems like the crash occurs when I try to turn that carToDisplay?.allObjects into an array of Display objects.

This is a keyboard extension app btw.

Thank you for any input!

Body:
Problem (probably):

if let carColorSet = car.carToDisplay?.allObjects as? [Display]

carToDisplay is a NSet
However the function allObjects returns an array

I think you are trying to do a unionSet with an array.

Update the Question:

Please update your question, the qestion doesn't state the correct line of error.

The question needs to do the following

state where the unionSet is invoked.

what the argument type of unionSet is.


问:
How do I get text to align to around a picture on a website
I'm working on a personal website highlighting my certifications on a personal website. Part of the ToS to use the images is to place a TM in the upper right corner of each image. I'm having trouble getting the text to align where it needs to be.

This is what I have:

HTML

```<code><div id="imagesMain">
        <img src="aplus.png"> TM
        <img src="network.png"> TM
        <img src="security.png"> TM
    </div>
</code>```

CSS

```<code>#imagesMain {
 padding: 0;
    margin-left: auto;
    margin-right: auto;
    margin-top: 20px;
    text-align: center;
}

#imagesMain img {
    height: 100px;
     width: auto;
    vertical-align: middle;
}
</code>```

The end result gives this...

What I'd like is all images in a tight line and a small "TM" in the proper place. Any help would be appreciated.

答:
You should wrap images and TM-text in a DIV, make that position: relative, put the TM-text into t span, make that position: absolute with top: 0; right: 0;. For details, see my snippet below.

#imagesMain {
  padding: 0;
  margin-left: auto;
  margin-right: auto;
  margin-top: 20px;
  text-align: center;
}

#imagesMain img {
  height: 100px;
  width: auto;
}

#imagesMain div {
  display: inline-block;
  position: relative;
  height: 100px;
  width: auto;
  vertical-align: middle;
}

#imagesMain span {
  position: absolute;
  top: 0;
  right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="imagesMain">
  <div><img src="aplus.png"><span class="x">TM</span></div>
  <div><img src="network.png"><span class="x">TM</span></div>
  <div><img src="security.png"><span class="x">TM</span></div>
</div></code>```

Body:
I'm working on a personal website highlighting my certifications on a personal website. Part of the ToS to use the images is to place a TM in the upper right corner of each image. I'm having trouble getting the text to align where it needs to be.

This is what I have:

HTML

         TM
         TM
         TM

CSS

#imagesMain {
 padding: 0;
    margin-left: auto;
    margin-right: auto;
    margin-top: 20px;
    text-align: center;
}

#imagesMain img {
    height: 100px;
     width: auto;
    vertical-align: middle;
}

The end result gives this...

What I'd like is all images in a tight line and a small "TM" in the proper place. Any help would be appreciated.

Body:
You should wrap images and TM-text in a DIV, make that position: relative, put the TM-text into t span, make that position: absolute with top: 0; right: 0;. For details, see my snippet below.

#imagesMain {
  padding: 0;
  margin-left: auto;
  margin-right: auto;
  margin-top: 20px;
  text-align: center;
}

#imagesMain img {
  height: 100px;
  width: auto;
}

#imagesMain div {
  display: inline-block;
  position: relative;
  height: 100px;
  width: auto;
  vertical-align: middle;
}

#imagesMain span {
  position: absolute;
  top: 0;
  right: 0;
}

<div id="imagesMain">
  <div><img src="aplus.png"><span class="x">TM</span></div>
  <div><img src="network.png"><span class="x">TM</span></div>
  <div><img src="security.png"><span class="x">TM</span></div>
</div>


问:
How to compute the "15% of the time" randomness?
I'm looking for a decent, elegant method of calculating this simple logic.

Right now I can't think of one, it's spinning my head.

I am required to do some action only 15% of the time.

I'm used to "50% of the time" where I just mod the milliseconds of the current time and see if it's odd or even, but I don't think that's elegant.

How would I elegantly calculate "15% of the time"?  Random number generator maybe?

Pseudo-code or any language are welcome.

Hope this is not subjective, since I'm looking for the "smartest" short-hand method of doing that.

Thanks.

答:
Using modulo arithmetic you can easily do something every Xth run like so

```<code>(6 will give you ruthly 15%
</code>```

if( microtime() % 6 === ) do it

other thing:

```<code>if(rand(0,1) >= 0.15) do it
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Using modulo arithmetic you can easily do something every Xth run like so

(6 will give you ruthly 15%

if( microtime() % 6 === ) do it

other thing:

if(rand(0,1) >= 0.15) do it


问:
How i can print from more than one textfield after clicking the button just once in java
My question is how I can print from more than one JTextField in Java clicking the button once.I can call the print method but from that i can print from the specific JTextField but i want to print from more than one JTextField after clicking the button just once.Please help me.Thanks in advance.

答:
So if you want to print the text of multiple JTextFields to the console, all you really have to do is use the ".getText()" method for each JTextField. It would be best to create a method that does so.

An example using three JTextFields:

```<code>JTextfield txt1= new JTextField("Hello");
JTextfield txt2 = new JTextField("Hi");
JTextfield txt3 = new JTextField("Hey");
</code>```

Create a method that gets and prints out the text of each textfield:

```<code>public void printAllTextFields() {
   System.out.println(txt1.getText());
   System.out.println(txt2.getText());
   System.out.println(txt3.getText());
}
</code>```

Then just call this method whenever you need to in your program.

The output of this example would be:

```<code>Hello
Hi
Hey
</code>```

Body:
So if you want to print the text of multiple JTextFields to the console, all you really have to do is use the ".getText()" method for each JTextField. It would be best to create a method that does so.

An example using three JTextFields:

JTextfield txt1= new JTextField("Hello");
JTextfield txt2 = new JTextField("Hi");
JTextfield txt3 = new JTextField("Hey");

Create a method that gets and prints out the text of each textfield:

public void printAllTextFields() {
   System.out.println(txt1.getText());
   System.out.println(txt2.getText());
   System.out.println(txt3.getText());
}

Then just call this method whenever you need to in your program.

The output of this example would be:

Hello
Hi
Hey


问:
GET request in Postman sending a value in header, but not reaching REST method in Java
I'm trying to send an authentication token through the header of a Postman request (to be sent through JavaScript in the future), but I'm getting it wrong somewhere.

This is the REST method in Java:

```<code>@GET
@Produces("text/plain")
@Consumes("text/plain")
@RequestMapping(value = "/products/{id}", method = RequestMethod.GET)
public ResponseList getProducts(@PathVariable("id") String id, @HeaderParam("Authorization") String token) throws JSONException, IOException {
    System.out.println( "id" + id);
    System.out.println( "token" + token);
    [...]
    return products;
}
</code>```

So, when I use the REST method, such as this, I get the id correctly:

http://localhost:8080/service/products/Gold as a GET. The id shows correctly in the system.out as Gold.

But I'm trying to send an "Authorization" value on the header as well using Postman, and 'token' comes back as null in the system.out.

Am I using the @HeaderParam incorrectly, or maybe setting the header improperly on Postman itself?

Thanks!

答: Have you tried using @RequestHeader instead?</p>

Body:
I'm trying to send an authentication token through the header of a Postman request (to be sent through JavaScript in the future), but I'm getting it wrong somewhere.

This is the REST method in Java:

@GET
@Produces("text/plain")
@Consumes("text/plain")
@RequestMapping(value = "/products/{id}", method = RequestMethod.GET)
public ResponseList getProducts(@PathVariable("id") String id, @HeaderParam("Authorization") String token) throws JSONException, IOException {
    System.out.println( "id" + id);
    System.out.println( "token" + token);
    [...]
    return products;
}

So, when I use the REST method, such as this, I get the id correctly:

http://localhost:8080/service/products/Gold as a GET. The id shows correctly in the system.out as Gold.

But I'm trying to send an "Authorization" value on the header as well using Postman, and 'token' comes back as null in the system.out.

Am I using the @HeaderParam incorrectly, or maybe setting the header improperly on Postman itself?

Thanks!


问:
Java boolean equations as parametar of function
Lets take a look at my program. That have some imaginary .txt file with car models.

```<code>public class Car {
    private String model;

    public String getModel() {
        return this.model;
    }
}

public class Main {
    public static void Main(String[] args) {
        ArrayList<Car> cars = loadCars(path); //imaginary func and file
        String someModel = generateSomeModel(); //imaginart func

        for (Car c : cars)
            if (c.getModel.equals(someModel))
                System.out.println("Hit!");

        for (Car c : cars)
            if (!c.getModel.equals(someModel))
                System.out.println("Hit!");

    }
}
</code>```

Lets suppose that I have to go through my cars list a 100 times and compare them in if statement for some different attributes every time, that means I  will have to write 100 different for loops that will be 90% same. Is there a way to write a function that will take as a parametar Boolean equation? Something like this.

```<code>public static void printCars(Boolean equation) {
    for (Car c : cars)
        if (Boolean equation)
            System.out.println("Hit!");
}
</code>```

答:
In case you need to compare you cars with multiple attributes, you need just to override equals method for Car class.

```<code>@Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof Car) {
            Car anotherCar = (Car)obj;
            return this.model.equals(anotherCar.model) &&
                    this.color.equals(anotherCar.color) &&
                    this.year == anotherCar.year;
        }
        return false;
    }
</code>```

This way you will compare all necessary attributes in one step:

```<code>List<Car> cars = //cars list
Car someCar = //bmw car
for (Car c : cars) {
    if (c.equals(someCar)) {
        System.out.println("Hit!");
    } else {
        System.out.println("Another Hit!");
    }
}
</code>```

Body:
Lets take a look at my program. That have some imaginary .txt file with car models.

public class Car {
    private String model;

    public String getModel() {
        return this.model;
    }
}

public class Main {
    public static void Main(String[] args) {
        ArrayList<Car> cars = loadCars(path); //imaginary func and file
        String someModel = generateSomeModel(); //imaginart func

        for (Car c : cars)
            if (c.getModel.equals(someModel))
                System.out.println("Hit!");

        for (Car c : cars)
            if (!c.getModel.equals(someModel))
                System.out.println("Hit!");

    }
}

Lets suppose that I have to go through my cars list a 100 times and compare them in if statement for some different attributes every time, that means I  will have to write 100 different for loops that will be 90% same. Is there a way to write a function that will take as a parametar Boolean equation? Something like this.

public static void printCars(Boolean equation) {
    for (Car c : cars)
        if (Boolean equation)
            System.out.println("Hit!");
}

Body:
In case you need to compare you cars with multiple attributes, you need just to override equals method for Car class.

@Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof Car) {
            Car anotherCar = (Car)obj;
            return this.model.equals(anotherCar.model) &&
                    this.color.equals(anotherCar.color) &&
                    this.year == anotherCar.year;
        }
        return false;
    }

This way you will compare all necessary attributes in one step:

List<Car> cars = //cars list
Car someCar = //bmw car
for (Car c : cars) {
    if (c.equals(someCar)) {
        System.out.println("Hit!");
    } else {
        System.out.println("Another Hit!");
    }
}


问:
use multiple transform: translate(X, Y) on same element
i have an image of one of those step by step poster and i placed it in another div to hide all the excess on the poster image and hid the overflow so it would only show one step at a time.</p>

```<code>transform: translate(-23px, -40px);
transform: translate(25px, -165px);
transform: translate(5px, -325px);
transform: translate(-230px, -420px);
transform: translate(-442px, -325px);
transform: translate(-485px, -175px);
transform: translate(-440px, -40px);
transform: translate(-220px, -10px);
</code>```

答:
i'm not familiar with css animate but it was still very easy. use @keyframes and name your function then put the percent at which it runs the transform. finally just call the function you want and add animate with the property of function name, time to cycle, and number of cycles.</p>

```<code>@keyframes MARY-GO-ROUND{
   0%, 100% {transform: translate(-23px, -40px);}
   12% {transform: translate(25px, -165px);}
   24% {transform: translate(5px, -325px);}
   36% {transform: translate(-230px, -420px);}
   48% {transform: translate(-442px, -325px);}
   60% {transform: translate(-485px, -175px);}
   72% {transform: translate(-440px, -40px);}
   84% {transform: translate(-220px, -10px);}
}
img#image_go_round{
   animation: MARY-GO-ROUND 20s infinite;
}
</code>```

Body:
i have an image of one of those step by step poster and i placed it in another div to hide all the excess on the poster image and hid the overflow so it would only show one step at a time.

transform: translate(-23px, -40px);
transform: translate(25px, -165px);
transform: translate(5px, -325px);
transform: translate(-230px, -420px);
transform: translate(-442px, -325px);
transform: translate(-485px, -175px);
transform: translate(-440px, -40px);
transform: translate(-220px, -10px);

Body:
i'm not familiar with css animate but it was still very easy. use @keyframes and name your function then put the percent at which it runs the transform. finally just call the function you want and add animate with the property of function name, time to cycle, and number of cycles.

@keyframes MARY-GO-ROUND{
   0%, 100% {transform: translate(-23px, -40px);}
   12% {transform: translate(25px, -165px);}
   24% {transform: translate(5px, -325px);}
   36% {transform: translate(-230px, -420px);}
   48% {transform: translate(-442px, -325px);}
   60% {transform: translate(-485px, -175px);}
   72% {transform: translate(-440px, -40px);}
   84% {transform: translate(-220px, -10px);}
}
img#image_go_round{
   animation: MARY-GO-ROUND 20s infinite;
}


问:
Simulate arrow keys with 'j' and 'k' in an NSTableView?
I have an NSTableView with a number of rows. The allowsEmptySelection property is NO, so there is always a row selected. I can move up and down the tableview with the arrow keys as expected.

I'd like to also be able to move up and down with the 'j' and 'k' keys. I've looked at the Cocoa Event-Handling Guide, but can't figure out how to make these keys simulate the up and down arrow keys.

For what it's worth, here's what I'm currently doing. I'm not really 'simulating the arrow keys'. Rather, I'm just doing the behavior I want when 'j' and 'k' are pressed. It's fine, but I'm wondering if there is a better way...

```<code>- (void)keyDown:(NSEvent *)theEvent {
    NSInteger row = [self.tableView selectedRow];
    NSInteger numRows = [self.tableView numberOfRows];
    switch ([theEvent keyCode]) {
        case 38:   // 'j'
            if (row < numRows - 1) {
                [self.tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:row+1] byExtendingSelection:NO];
            }
            break;
        case 40:   // 'k'
            if (row > 0) {
                [self.tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:row-1] byExtendingSelection:NO];
            }
            break;
        default:
            [super keyDown:theEvent];
    }
}
</code>```

答:
Create a custom subclass of NSTableView to catch the events. Your subclass should have this method in it:

```<code>- (void)keyUp:(NSEvent *)event {
    if([event keyCode] == 26) {//J
        if([event modifierFlags] & NSShiftKeyMask) [self moveDownAndModifySelection:nil];
         else [self moveDown:nil];
    } else if([event keyCode] == 28) {//K
        if([event modifierFlags] & NSShiftKeyMask) [self moveUpAndModifySelection:nil];
         else [self moveUp:nil];
    } else [super keyUp:event];
}
</code>```

This will catch any J or K keys and tell the table view to move up or down, respectively. Also, if the shift key is pressed, this will add to the selection upwards or downwards.

If you choose to use this code, make sure you filter out if any other modifiers are pressed and pass them to super also. I did not do this to make it more readable.

Edit: How to create a false event

```<code>unichar theChar = NSUpArrowFunctionKey; //NSDownArrowFunctionKey
NSString *string = [NSString stringWithCharacters:&theChar length:1];
NSEvent *newEvent =[NSEvent keyEventWithType:NSKeyUp location:[event locationInWindow] modifierFlags:[event modifierFlags] timestamp:[event timestamp] windowNumber:[event windowNumber] context:nil/*get graphics context if you want*/ characters:string charactersIgnoringModifiers:string isARepeat:[event isARepeat] keyCode:theChar];
[super keyUp:newEvent];
</code>```

Body:
I have an NSTableView with a number of rows. The allowsEmptySelection property is NO, so there is always a row selected. I can move up and down the tableview with the arrow keys as expected.

I'd like to also be able to move up and down with the 'j' and 'k' keys. I've looked at the Cocoa Event-Handling Guide, but can't figure out how to make these keys simulate the up and down arrow keys.

For what it's worth, here's what I'm currently doing. I'm not really 'simulating the arrow keys'. Rather, I'm just doing the behavior I want when 'j' and 'k' are pressed. It's fine, but I'm wondering if there is a better way...

- (void)keyDown:(NSEvent *)theEvent {
    NSInteger row = [self.tableView selectedRow];
    NSInteger numRows = [self.tableView numberOfRows];
    switch ([theEvent keyCode]) {
        case 38:   // 'j'
            if (row < numRows - 1) {
                [self.tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:row+1] byExtendingSelection:NO];
            }
            break;
        case 40:   // 'k'
            if (row > 0) {
                [self.tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:row-1] byExtendingSelection:NO];
            }
            break;
        default:
            [super keyDown:theEvent];
    }
}

Body:
Create a custom subclass of NSTableView to catch the events. Your subclass should have this method in it:

- (void)keyUp:(NSEvent *)event {
    if([event keyCode] == 26) {//J
        if([event modifierFlags] & NSShiftKeyMask) [self moveDownAndModifySelection:nil];
         else [self moveDown:nil];
    } else if([event keyCode] == 28) {//K
        if([event modifierFlags] & NSShiftKeyMask) [self moveUpAndModifySelection:nil];
         else [self moveUp:nil];
    } else [super keyUp:event];
}

This will catch any J or K keys and tell the table view to move up or down, respectively. Also, if the shift key is pressed, this will add to the selection upwards or downwards.

If you choose to use this code, make sure you filter out if any other modifiers are pressed and pass them to super also. I did not do this to make it more readable.

Edit: How to create a false event

unichar theChar = NSUpArrowFunctionKey; //NSDownArrowFunctionKey
NSString *string = [NSString stringWithCharacters:&theChar length:1];
NSEvent *newEvent =[NSEvent keyEventWithType:NSKeyUp location:[event locationInWindow] modifierFlags:[event modifierFlags] timestamp:[event timestamp] windowNumber:[event windowNumber] context:nil/*get graphics context if you want*/ characters:string charactersIgnoringModifiers:string isARepeat:[event isARepeat] keyCode:theChar];
[super keyUp:newEvent];


问:
How to rearrange a two dimensional array
I want to assign the values in one array to another, but in a different
order. For example the original array would be:

```<code>1  2  3  4  5  6  7
8  9  10 11 12 13 14
15 16 17 18 19 20 21
</code>```

And the desired array is:

```<code>8  11 14 3 6  16 19
9  12 1  4 7  17 20
10 13 2  5 15 18 21
</code>```

How would I do this? In the code below I moved a selected row to the center, then assigned each array individually. I can't figure out a better way.

```<code>int main()
{
int decide, i, j, k;
int save[3][7];
int shuffle[3][7];
int arr[3][7] = {
                {1, 2, 3, 4, 5, 6, 7},
                {8, 9, 10, 11, 12, 13, 14},
                {15, 16, 17, 18, 19, 20, 21}
            };

printf("Select a number between 1 and 21\n\n0-GroupA (1 - 7))\n1-GroupB ( 8 - 14)\n2-GroupC (15 - 21)\n\n");

for(k = 0 ; k < 1 ; ++k)
{
    printf("Select which group the number falls into:");
    scanf("%d", &decide);

    for(j = 0 ; j < 7 ; ++j)
    {/*moves selected row to middle row of array*/
        save[0][j] = arr[1][j];
        arr[1][j] = arr[decide][j];
        arr[decide][j] = save[0][j];
    }

    /*this is a horrible method*/
    shuffle[0][0] = arr[0][0];
    shuffle[1][0] = arr[0][1];
    shuffle[2][0] = arr[0][2];
    shuffle[0][1] = arr[0][3];
    shuffle[1][1] = arr[0][4];
    shuffle[2][1] = arr[0][5];
    shuffle[0][2] = arr[0][6];
    shuffle[1][2] = arr[1][0];
    shuffle[2][2] = arr[1][1];
    shuffle[0][3] = arr[1][2];
    shuffle[1][3] = arr[1][3];
    shuffle[2][3] = arr[1][4];
    shuffle[0][4] = arr[1][5];
    shuffle[1][4] = arr[1][6];
    shuffle[2][4] = arr[2][0];
    shuffle[0][5] = arr[2][1];
    shuffle[1][5] = arr[2][2];
    shuffle[2][5] = arr[2][3];
    shuffle[0][6] = arr[2][4];
    shuffle[1][6] = arr[2][5];
    shuffle[2][6] = arr[2][6];

}
</code>```

答:
The transposition part can be done like this:

```<code>#include <stdio.h>

typedef struct Sequence2D
{
    int idx_slow;
    int idx_fast;
    int max_slow;
    int max_fast;
} Sequence2D;

static inline void next2D(Sequence2D *seq)
{
    if (++seq->idx_fast == seq->max_fast)
    {
        seq->idx_fast = 0;
        if (++seq->idx_slow == seq->max_slow)
            seq->idx_slow = 0;
    }
}

static inline void dump2D(const char *tag, int rows, int cols, int data[rows][cols])
{
    printf("%s:\n", tag);
    for (int r = 0; r < rows; r++)
    {
        for (int c = 0; c < cols; c++)
            printf("%3d", data[r][c]);
        putchar('\n');
    }
}

enum { ROWS = 3, COLS = 7 };

int main(void)
{
    int src[ROWS][COLS] =
    {
        {  1,  2,  3,  4,  5,  6,  7 },
        {  8,  9, 10, 11, 12, 13, 14 },
        { 15, 16, 17, 18, 19, 20, 21 },
    };
    int dst[ROWS][COLS];
    Sequence2D dst2D = { 0, 0, COLS, ROWS };
    Sequence2D src2D = { 0, 0, ROWS, COLS };

    dump2D("Source", ROWS, COLS, src);

    for (int i = 0; i < ROWS * COLS; i++)
    {
        dst[dst2D.idx_fast][dst2D.idx_slow] = src[src2D.idx_slow][src2D.idx_fast];
        printf("dst[%d][%d] = src[%d][%d] = %d\n",
               dst2D.idx_fast, dst2D.idx_slow,
               src2D.idx_slow, src2D.idx_fast,
               dst[dst2D.idx_fast][dst2D.idx_slow]);
        next2D(&dst2D);
        next2D(&src2D);
    }

    dump2D("Target", ROWS, COLS, dst);

    return 0;
}
</code>```

The Sequence2D structure plus the next2D() function cycle through array indexes, changing the fast index on each call of next2D() and the slow index when necessary.  This saves you writing out the sequence of 21 assignments, and immediately scales to other shapes without requiring much extra work on your part.  Indeed, it would not take much to handle all the sizes as run-time inputs instead of compile-time constants.

The output of this code is:

```<code>Source:
  1  2  3  4  5  6  7
  8  9 10 11 12 13 14
 15 16 17 18 19 20 21
dst[0][0] = src[0][0] = 1
dst[1][0] = src[0][1] = 2
dst[2][0] = src[0][2] = 3
dst[0][1] = src[0][3] = 4
dst[1][1] = src[0][4] = 5
dst[2][1] = src[0][5] = 6
dst[0][2] = src[0][6] = 7
dst[1][2] = src[1][0] = 8
dst[2][2] = src[1][1] = 9
dst[0][3] = src[1][2] = 10
dst[1][3] = src[1][3] = 11
dst[2][3] = src[1][4] = 12
dst[0][4] = src[1][5] = 13
dst[1][4] = src[1][6] = 14
dst[2][4] = src[2][0] = 15
dst[0][5] = src[2][1] = 16
dst[1][5] = src[2][2] = 17
dst[2][5] = src[2][3] = 18
dst[0][6] = src[2][4] = 19
dst[1][6] = src[2][5] = 20
dst[2][6] = src[2][6] = 21
Target:
  1  4  7 10 13 16 19
  2  5  8 11 14 17 20
  3  6  9 12 15 18 21
</code>```

If you rearrange the initial matrix (src) according to whatever arcane rules you're using before you copy the 'transpose' of src into the result (dst), then you should be able to get the result you desire.

As noted, the code can be generalized rather easily using C99 and variable-length arrays:

```<code>#include <assert.h>
#include <stdio.h>

typedef struct Sequence2D
{
    int idx_slow;
    int idx_fast;
    int max_slow;
    int max_fast;
} Sequence2D;

static inline void next2D(Sequence2D *seq)
{
    if (++seq->idx_fast == seq->max_fast)
    {
        seq->idx_fast = 0;
        if (++seq->idx_slow == seq->max_slow)
            seq->idx_slow = 0;
    }
}

static inline void dump2D(const char *tag, int rows, int cols, int data[rows][cols])
{
    printf("%s:\n", tag);
    for (int r = 0; r < rows; r++)
    {
        for (int c = 0; c < cols; c++)
            printf("%3d", data[r][c]);
        putchar('\n');
    }
}

static void transpose(int rows, int cols)
{
    assert(rows * cols < 1000000);
    int src[rows][cols];
    int dst[rows][cols];
    Sequence2D dst2D = { 0, 0, cols, rows };
    Sequence2D src2D = { 0, 0, rows, cols };
    int cells = rows * cols;
    for (int i = 0; i < cells; i++)
    {
        src[src2D.idx_slow][src2D.idx_fast] = i;
        next2D(&src2D);
    }
    /* src2D is back to its initial state! */

    dump2D("Source", rows, cols, src);

    for (int i = 0; i < cells; i++)
    {
        dst[dst2D.idx_fast][dst2D.idx_slow] = src[src2D.idx_slow][src2D.idx_fast];
        printf("dst[%d][%d] = src[%d][%d] = %d\n",
               dst2D.idx_fast, dst2D.idx_slow,
               src2D.idx_slow, src2D.idx_fast,
               dst[dst2D.idx_fast][dst2D.idx_slow]);
        next2D(&dst2D);
        next2D(&src2D);
    }

    dump2D("Target", rows, cols, dst);
}

int main(void)
{
    transpose(3, 7);
    transpose(9, 4);
    return 0;
}
</code>```

The first section of the output is the same as before; the 9x4 part looks like:

```<code>Source:
  0  1  2  3
  4  5  6  7
  8  9 10 11
 12 13 14 15
 16 17 18 19
 20 21 22 23
 24 25 26 27
 28 29 30 31
 32 33 34 35
dst[0][0] = src[0][0] = 0
dst[1][0] = src[0][1] = 1
dst[2][0] = src[0][2] = 2
dst[3][0] = src[0][3] = 3
dst[4][0] = src[1][0] = 4
dst[5][0] = src[1][1] = 5
dst[6][0] = src[1][2] = 6
dst[7][0] = src[1][3] = 7
dst[8][0] = src[2][0] = 8
dst[0][1] = src[2][1] = 9
dst[1][1] = src[2][2] = 10
dst[2][1] = src[2][3] = 11
dst[3][1] = src[3][0] = 12
dst[4][1] = src[3][1] = 13
dst[5][1] = src[3][2] = 14
dst[6][1] = src[3][3] = 15
dst[7][1] = src[4][0] = 16
dst[8][1] = src[4][1] = 17
dst[0][2] = src[4][2] = 18
dst[1][2] = src[4][3] = 19
dst[2][2] = src[5][0] = 20
dst[3][2] = src[5][1] = 21
dst[4][2] = src[5][2] = 22
dst[5][2] = src[5][3] = 23
dst[6][2] = src[6][0] = 24
dst[7][2] = src[6][1] = 25
dst[8][2] = src[6][2] = 26
dst[0][3] = src[6][3] = 27
dst[1][3] = src[7][0] = 28
dst[2][3] = src[7][1] = 29
dst[3][3] = src[7][2] = 30
dst[4][3] = src[7][3] = 31
dst[5][3] = src[8][0] = 32
dst[6][3] = src[8][1] = 33
dst[7][3] = src[8][2] = 34
dst[8][3] = src[8][3] = 35
Target:
  0  9 18 27
  1 10 19 28
  2 11 20 29
  3 12 21 30
  4 13 22 31
  5 14 23 32
  6 15 24 33
  7 16 25 34
  8 17 26 35
</code>```

Body:
I want to assign the values in one array to another, but in a different
order. For example the original array would be:

1  2  3  4  5  6  7
8  9  10 11 12 13 14
15 16 17 18 19 20 21

And the desired array is:

8  11 14 3 6  16 19
9  12 1  4 7  17 20
10 13 2  5 15 18 21

How would I do this? In the code below I moved a selected row to the center, then assigned each array individually. I can't figure out a better way.

int main()
{
int decide, i, j, k;
int save[3][7];
int shuffle[3][7];
int arr[3][7] = {
                {1, 2, 3, 4, 5, 6, 7},
                {8, 9, 10, 11, 12, 13, 14},
                {15, 16, 17, 18, 19, 20, 21}
            };

printf("Select a number between 1 and 21\n\n0-GroupA (1 - 7))\n1-GroupB ( 8 - 14)\n2-GroupC (15 - 21)\n\n");

for(k = 0 ; k < 1 ; ++k)
{
    printf("Select which group the number falls into:");
    scanf("%d", &decide);

    for(j = 0 ; j < 7 ; ++j)
    {/*moves selected row to middle row of array*/
        save[0][j] = arr[1][j];
        arr[1][j] = arr[decide][j];
        arr[decide][j] = save[0][j];
    }

    /*this is a horrible method*/
    shuffle[0][0] = arr[0][0];
    shuffle[1][0] = arr[0][1];
    shuffle[2][0] = arr[0][2];
    shuffle[0][1] = arr[0][3];
    shuffle[1][1] = arr[0][4];
    shuffle[2][1] = arr[0][5];
    shuffle[0][2] = arr[0][6];
    shuffle[1][2] = arr[1][0];
    shuffle[2][2] = arr[1][1];
    shuffle[0][3] = arr[1][2];
    shuffle[1][3] = arr[1][3];
    shuffle[2][3] = arr[1][4];
    shuffle[0][4] = arr[1][5];
    shuffle[1][4] = arr[1][6];
    shuffle[2][4] = arr[2][0];
    shuffle[0][5] = arr[2][1];
    shuffle[1][5] = arr[2][2];
    shuffle[2][5] = arr[2][3];
    shuffle[0][6] = arr[2][4];
    shuffle[1][6] = arr[2][5];
    shuffle[2][6] = arr[2][6];

}

Body:
The transposition part can be done like this:

#include <stdio.h>

typedef struct Sequence2D
{
    int idx_slow;
    int idx_fast;
    int max_slow;
    int max_fast;
} Sequence2D;

static inline void next2D(Sequence2D *seq)
{
    if (++seq->idx_fast == seq->max_fast)
    {
        seq->idx_fast = 0;
        if (++seq->idx_slow == seq->max_slow)
            seq->idx_slow = 0;
    }
}

static inline void dump2D(const char *tag, int rows, int cols, int data[rows][cols])
{
    printf("%s:\n", tag);
    for (int r = 0; r < rows; r++)
    {
        for (int c = 0; c < cols; c++)
            printf("%3d", data[r][c]);
        putchar('\n');
    }
}

enum { ROWS = 3, COLS = 7 };

int main(void)
{
    int src[ROWS][COLS] =
    {
        {  1,  2,  3,  4,  5,  6,  7 },
        {  8,  9, 10, 11, 12, 13, 14 },
        { 15, 16, 17, 18, 19, 20, 21 },
    };
    int dst[ROWS][COLS];
    Sequence2D dst2D = { 0, 0, COLS, ROWS };
    Sequence2D src2D = { 0, 0, ROWS, COLS };

    dump2D("Source", ROWS, COLS, src);

    for (int i = 0; i < ROWS * COLS; i++)
    {
        dst[dst2D.idx_fast][dst2D.idx_slow] = src[src2D.idx_slow][src2D.idx_fast];
        printf("dst[%d][%d] = src[%d][%d] = %d\n",
               dst2D.idx_fast, dst2D.idx_slow,
               src2D.idx_slow, src2D.idx_fast,
               dst[dst2D.idx_fast][dst2D.idx_slow]);
        next2D(&dst2D);
        next2D(&src2D);
    }

    dump2D("Target", ROWS, COLS, dst);

    return 0;
}

The Sequence2D structure plus the next2D() function cycle through array indexes, changing the fast index on each call of next2D() and the slow index when necessary.  This saves you writing out the sequence of 21 assignments, and immediately scales to other shapes without requiring much extra work on your part.  Indeed, it would not take much to handle all the sizes as run-time inputs instead of compile-time constants.

The output of this code is:

Source:
  1  2  3  4  5  6  7
  8  9 10 11 12 13 14
 15 16 17 18 19 20 21
dst[0][0] = src[0][0] = 1
dst[1][0] = src[0][1] = 2
dst[2][0] = src[0][2] = 3
dst[0][1] = src[0][3] = 4
dst[1][1] = src[0][4] = 5
dst[2][1] = src[0][5] = 6
dst[0][2] = src[0][6] = 7
dst[1][2] = src[1][0] = 8
dst[2][2] = src[1][1] = 9
dst[0][3] = src[1][2] = 10
dst[1][3] = src[1][3] = 11
dst[2][3] = src[1][4] = 12
dst[0][4] = src[1][5] = 13
dst[1][4] = src[1][6] = 14
dst[2][4] = src[2][0] = 15
dst[0][5] = src[2][1] = 16
dst[1][5] = src[2][2] = 17
dst[2][5] = src[2][3] = 18
dst[0][6] = src[2][4] = 19
dst[1][6] = src[2][5] = 20
dst[2][6] = src[2][6] = 21
Target:
  1  4  7 10 13 16 19
  2  5  8 11 14 17 20
  3  6  9 12 15 18 21

If you rearrange the initial matrix (src) according to whatever arcane rules you're using before you copy the 'transpose' of src into the result (dst), then you should be able to get the result you desire.

As noted, the code can be generalized rather easily using C99 and variable-length arrays:

#include <assert.h>
#include <stdio.h>

typedef struct Sequence2D
{
    int idx_slow;
    int idx_fast;
    int max_slow;
    int max_fast;
} Sequence2D;

static inline void next2D(Sequence2D *seq)
{
    if (++seq->idx_fast == seq->max_fast)
    {
        seq->idx_fast = 0;
        if (++seq->idx_slow == seq->max_slow)
            seq->idx_slow = 0;
    }
}

static inline void dump2D(const char *tag, int rows, int cols, int data[rows][cols])
{
    printf("%s:\n", tag);
    for (int r = 0; r < rows; r++)
    {
        for (int c = 0; c < cols; c++)
            printf("%3d", data[r][c]);
        putchar('\n');
    }
}

static void transpose(int rows, int cols)
{
    assert(rows * cols < 1000000);
    int src[rows][cols];
    int dst[rows][cols];
    Sequence2D dst2D = { 0, 0, cols, rows };
    Sequence2D src2D = { 0, 0, rows, cols };
    int cells = rows * cols;
    for (int i = 0; i < cells; i++)
    {
        src[src2D.idx_slow][src2D.idx_fast] = i;
        next2D(&src2D);
    }
    /* src2D is back to its initial state! */

    dump2D("Source", rows, cols, src);

    for (int i = 0; i < cells; i++)
    {
        dst[dst2D.idx_fast][dst2D.idx_slow] = src[src2D.idx_slow][src2D.idx_fast];
        printf("dst[%d][%d] = src[%d][%d] = %d\n",
               dst2D.idx_fast, dst2D.idx_slow,
               src2D.idx_slow, src2D.idx_fast,
               dst[dst2D.idx_fast][dst2D.idx_slow]);
        next2D(&dst2D);
        next2D(&src2D);
    }

    dump2D("Target", rows, cols, dst);
}

int main(void)
{
    transpose(3, 7);
    transpose(9, 4);
    return 0;
}

The first section of the output is the same as before; the 9x4 part looks like:

Source:
  0  1  2  3
  4  5  6  7
  8  9 10 11
 12 13 14 15
 16 17 18 19
 20 21 22 23
 24 25 26 27
 28 29 30 31
 32 33 34 35
dst[0][0] = src[0][0] = 0
dst[1][0] = src[0][1] = 1
dst[2][0] = src[0][2] = 2
dst[3][0] = src[0][3] = 3
dst[4][0] = src[1][0] = 4
dst[5][0] = src[1][1] = 5
dst[6][0] = src[1][2] = 6
dst[7][0] = src[1][3] = 7
dst[8][0] = src[2][0] = 8
dst[0][1] = src[2][1] = 9
dst[1][1] = src[2][2] = 10
dst[2][1] = src[2][3] = 11
dst[3][1] = src[3][0] = 12
dst[4][1] = src[3][1] = 13
dst[5][1] = src[3][2] = 14
dst[6][1] = src[3][3] = 15
dst[7][1] = src[4][0] = 16
dst[8][1] = src[4][1] = 17
dst[0][2] = src[4][2] = 18
dst[1][2] = src[4][3] = 19
dst[2][2] = src[5][0] = 20
dst[3][2] = src[5][1] = 21
dst[4][2] = src[5][2] = 22
dst[5][2] = src[5][3] = 23
dst[6][2] = src[6][0] = 24
dst[7][2] = src[6][1] = 25
dst[8][2] = src[6][2] = 26
dst[0][3] = src[6][3] = 27
dst[1][3] = src[7][0] = 28
dst[2][3] = src[7][1] = 29
dst[3][3] = src[7][2] = 30
dst[4][3] = src[7][3] = 31
dst[5][3] = src[8][0] = 32
dst[6][3] = src[8][1] = 33
dst[7][3] = src[8][2] = 34
dst[8][3] = src[8][3] = 35
Target:
  0  9 18 27
  1 10 19 28
  2 11 20 29
  3 12 21 30
  4 13 22 31
  5 14 23 32
  6 15 24 33
  7 16 25 34
  8 17 26 35


问:
Repositioning UICollectionViewCells?
I want to set the position of my UICollectionViewCell. After doing some research on it I found a post that explains the process, however in objective-c. I believe I translated it correctly however I can't get it to work.

Here's the link to the question:
How do I set the position of a UICollectionViewCell?

Here's the answer in objective-c

```<code>- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0 && indexPath.item == 2) // or whatever specific item you're trying to override
{
    UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    layoutAttributes.frame = CGRectMake(0,0,100,100); // or whatever...
    return layoutAttributes;
}
else
{
    return [super layoutAttributesForItemAtIndexPath:indexPath];
}
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *layoutAttributes = [super layoutAttributesForElementInRect:rect];
if (CGRectContainsRect(rect, CGRectMake(0, 0, 100, 100))) // replace this CGRectMake with the custom frame of your cell...
{
    UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    layoutAttributes.frame = CGRectMake(0,0,100,100); // or whatever...
    return [layoutAttributes arrayByAddingObject:layoutAttributes];
}
else
{
    return layoutAttributes;
}
}
</code>```

Here's my swift version

```<code> func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    if (indexPath.section == 0 && indexPath.item == 1) {

        let layoutAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
        layoutAttributes.frame = CGRect(x: 0, y: 0, width: 20, height: 50)
        return layoutAttributes
    }
    else
    {
}
    return layoutAttributesForItem(at:indexPath)
}

func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    let layoutAttributes = layoutAttributesForElements(in: rect)! as NSArray

    func contains(_ rect2: CGRect) -> Bool {
        if rect2 == CGRect(x: 0, y: 0, width: 2, height: 50) {
            let layoutAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            layoutAttributes.frame = CGRect(x: 0, y: 0, width: 20, height: 50) // or whatever...
            return layoutAttributes
        }
        else{
            return layoutAttributes
        }

        }
    }
</code>```

However in layoutAttributesForElements I get an error saying indexPath is an unresolved identifier...

My VC is subclassed as the following
UICollectionViewController, UICollectionViewDelegateFlowLayout,  UITextViewDelegate

Any suggestions?

If you know any other methods to reposition UICollectionViewCells that'd be great also.

EDIT

I have included a screenshot.

The red rectangle is  the cell. I want it to be on the gray line

答:
In order to do this you need to use a UIViewController and put a UICollectionView inside of it.

You can create a var like so:

```<code>lazy var collectionView : UICollectionView = {
    layout.scrollDirection = UICollectionViewScrollDirection.horizontal
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    cv.delegate = self
    cv.dataSource = self
    cv.register(UICollectionViewCell.self, forCellWithReuseIdentifier: self.cellId)
    cv.backgroundColor = UIColor.red
    return cv
}()
</code>```

Note: you will have to make your UIViewController conform to UICollectionViewDataSource & UICollectionViewDelegateFlowLayout and include required methods numberOfItemsInSection & cellForItemAt

When you want to move the UICollectionView, you can set it's frame to the new desired position by using:

```<code>self.collectionView.frame = <Your_frame>
</code>```

UICollectionViewController does not allow you to move its collection view instance.

Title: Repositioning UICollectionViewCells?

Body:
I want to set the position of my UICollectionViewCell. After doing some research on it I found a post that explains the process, however in objective-c. I believe I translated it correctly however I can't get it to work.

Here's the link to the question:
How do I set the position of a UICollectionViewCell?

Here's the answer in objective-c

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0 && indexPath.item == 2) // or whatever specific item you're trying to override
{
    UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    layoutAttributes.frame = CGRectMake(0,0,100,100); // or whatever...
    return layoutAttributes;
}
else
{
    return [super layoutAttributesForItemAtIndexPath:indexPath];
}
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *layoutAttributes = [super layoutAttributesForElementInRect:rect];
if (CGRectContainsRect(rect, CGRectMake(0, 0, 100, 100))) // replace this CGRectMake with the custom frame of your cell...
{
    UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    layoutAttributes.frame = CGRectMake(0,0,100,100); // or whatever...
    return [layoutAttributes arrayByAddingObject:layoutAttributes];
}
else
{
    return layoutAttributes;
}
}

Here's my swift version

 func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    if (indexPath.section == 0 && indexPath.item == 1) {

        let layoutAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
        layoutAttributes.frame = CGRect(x: 0, y: 0, width: 20, height: 50)
        return layoutAttributes
    }
    else
    {
}
    return layoutAttributesForItem(at:indexPath)
}

func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    let layoutAttributes = layoutAttributesForElements(in: rect)! as NSArray

    func contains(_ rect2: CGRect) -> Bool {
        if rect2 == CGRect(x: 0, y: 0, width: 2, height: 50) {
            let layoutAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            layoutAttributes.frame = CGRect(x: 0, y: 0, width: 20, height: 50) // or whatever...
            return layoutAttributes
        }
        else{
            return layoutAttributes
        }

        }
    }

However in layoutAttributesForElements I get an error saying indexPath is an unresolved identifier...

My VC is subclassed as the following
UICollectionViewController, UICollectionViewDelegateFlowLayout,  UITextViewDelegate

Any suggestions?

If you know any other methods to reposition UICollectionViewCells that'd be great also.

EDIT

I have included a screenshot.

The red rectangle is  the cell. I want it to be on the gray line

Body:
In order to do this you need to use a UIViewController and put a UICollectionView inside of it.

You can create a var like so:

lazy var collectionView : UICollectionView = {
    layout.scrollDirection = UICollectionViewScrollDirection.horizontal
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    cv.delegate = self
    cv.dataSource = self
    cv.register(UICollectionViewCell.self, forCellWithReuseIdentifier: self.cellId)
    cv.backgroundColor = UIColor.red
    return cv
}()

Note: you will have to make your UIViewController conform to UICollectionViewDataSource & UICollectionViewDelegateFlowLayout and include required methods numberOfItemsInSection & cellForItemAt

When you want to move the UICollectionView, you can set it's frame to the new desired position by using:

self.collectionView.frame = <Your_frame>

UICollectionViewController does not allow you to move its collection view instance.


问:
What is a "reference edge" in TensorBoard?
The TensorBoard UI shows something called a "Reference edge" as distinct from a data flow (Tensor) edge:

What distinguishes the former from the latter?

The documentation says that "the outgoing operation node can mutate the incoming tensor", but indicates different symbols that don't match the UI, so it's hard to tell what's meant by "incoming" and "outgoing":

For example how does this definition apply to

```<code>cs = tf.constant([1,2,3], name='const_share')
vs = tf.Variable([1,2,3], name='var_share')
tf.add(cs, vs, name='opVS1')
tf.add(vs, cs, name='opVS2')
</code>```

or to

```<code>tf.add([4],[3], name='opA')
</code>```

In both cases it just seems that the reference edge indicates that the value its tail fills the Tensor represented by the edge.

答:
I do not see any reference edges on your graph, but here is how you can easily get one:

```<code>import tensorflow as tf
a = tf.Variable(1, name="a")
b = a.assign_add(2)

with tf.Session() as sess:
    tf.summary.FileWriter('logs', sess.graph)
    sess.run(tf.global_variables_initializer())
</code>```

When you will click on a and remove it from the main graph you will see a reference edge:

In TF there are no bidirectional edges during the runtime. But there are some operations (like tf.assign_add) which return the same value as one of the input by modifying it:

ref: A mutable Tensor

So TF adds a reference edge where the operation reads the previous value, does something and rewrite it with the new value. The analogy is most probably with pointers/references. So the doc kind of makes sense:

A reference edge showing that the outgoing operation node can mutate
  the incoming tensor.

Body:
The TensorBoard UI shows something called a "Reference edge" as distinct from a data flow (Tensor) edge:

What distinguishes the former from the latter?

The documentation says that "the outgoing operation node can mutate the incoming tensor", but indicates different symbols that don't match the UI, so it's hard to tell what's meant by "incoming" and "outgoing":

For example how does this definition apply to

cs = tf.constant([1,2,3], name='const_share')
vs = tf.Variable([1,2,3], name='var_share')
tf.add(cs, vs, name='opVS1')
tf.add(vs, cs, name='opVS2')

or to

tf.add([4],[3], name='opA')

In both cases it just seems that the reference edge indicates that the value its tail fills the Tensor represented by the edge.

Body:
I do not see any reference edges on your graph, but here is how you can easily get one:

import tensorflow as tf
a = tf.Variable(1, name="a")
b = a.assign_add(2)

with tf.Session() as sess:
    tf.summary.FileWriter('logs', sess.graph)
    sess.run(tf.global_variables_initializer())

When you will click on a and remove it from the main graph you will see a reference edge:

In TF there are no bidirectional edges during the runtime. But there are some operations (like tf.assign_add) which return the same value as one of the input by modifying it:

ref: A mutable Tensor

So TF adds a reference edge where the operation reads the previous value, does something and rewrite it with the new value. The analogy is most probably with pointers/references. So the doc kind of makes sense:

A reference edge showing that the outgoing operation node can mutate
  the incoming tensor.


问:
Android master detail detail
I'm having a problem coming back from a detail page to its parent. The problem is that it's three levels and the issue is coming from the third level back to the second level.
Imagine a list of invoices. Tap on one of them and it loads the detail of the invoice with the list of line items in the invoice. Tap on a line item and it goes to a third activity with the details for that line item. The line item is launched via tap response like so...

[EDIT Added manifest info]

```<code><activity
    android:name=".InvocieListActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar">
</activity>

<activity
    android:name=".InvoiceDetailActivity"
    android:label="@string/title_activity_invoice_detail"
    android:parentActivityName=".InvoiceListActivity"
    android:theme="@style/AppTheme.NoActionBar">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.myweb.ree.InvocieListActivity"/>
</activity>

<activity
    android:name=".InvoiceItemDetailActivity"
    android:label="@string/title_activity_invoiceitem_detail"
    android:parentActivityName=".InvoiceDetailActivity"
    android:theme="@style/AppTheme.NoActionBar">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.myweb.ree.InvoiceDetailActivity"/>
</activity>

private BroadcastReceiver invoiceItemReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_INVOICEITEM_TAPPED)) {
            String invoiceItemId = intent.getStringExtra(Constants.MSG_DATA);
            if (invoiceItemId != null && invoiceItemId.length() > 0) {
                launchInvoiceItemActivity(invoiceItemId);
            }
        }
    }
};

private void launchInvoiceItemActivity(String invoiceItemId) {
    Intent intent = new Intent(this, InvoiceItemDetailActivity.class);
    intent.putExtra(ARG_InvoiceItem_ID, invoiceItemId);
    this.startActivity(intent);
}
</code>```

The invoice detail has the getSupportActionBar().setDisplayHomeAsUpEnabled(true); so that it can return to the list of invoices. The line item detail page has the same line to allow the back button to go to the invoice.

When I tap the back button on the line item detail activity it can't load the invoice because it doesn't have the invoice number that was passed in from the original list.

I understand I can override onBackPressed and create an intent that launches its parent rather than letting the framework do it. My question is will that mess up any internal view stack that the framework is keeping in the case of parent-child navigation? Is there some other way that I'm supposed to track items in a master view so it can be reloaded with the correct content when returning from a detail view?

TIA
Mike

答:
First of all it's looks like your 2nd Activity getting destroyed. That is why when you go back new instance doesn't have invoice number. To solve this problem you could save 2nd Activity state (invoice number etc) by overrding onSaveInstanceState and onRestoreInstanceState. Then you could save your 2nd activity state and restore it when goes back from 3rd.

Also you could save invoice number into SharedPreferences. But you need to update it's value each time you launch this Activity with different invoice number to keep consistency. You could do this in onCreate() or/and in onNewIntent() depending of Activity configurations. And read this value in onResume().

Title: Android master detail detail

Body:
I'm having a problem coming back from a detail page to its parent. The problem is that it's three levels and the issue is coming from the third level back to the second level.
Imagine a list of invoices. Tap on one of them and it loads the detail of the invoice with the list of line items in the invoice. Tap on a line item and it goes to a third activity with the details for that line item. The line item is launched via tap response like so...

[EDIT Added manifest info]

<activity
    android:name=".InvocieListActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar">
</activity>

<activity
    android:name=".InvoiceDetailActivity"
    android:label="@string/title_activity_invoice_detail"
    android:parentActivityName=".InvoiceListActivity"
    android:theme="@style/AppTheme.NoActionBar">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.myweb.ree.InvocieListActivity"/>
</activity>

<activity
    android:name=".InvoiceItemDetailActivity"
    android:label="@string/title_activity_invoiceitem_detail"
    android:parentActivityName=".InvoiceDetailActivity"
    android:theme="@style/AppTheme.NoActionBar">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.myweb.ree.InvoiceDetailActivity"/>
</activity>

private BroadcastReceiver invoiceItemReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_INVOICEITEM_TAPPED)) {
            String invoiceItemId = intent.getStringExtra(Constants.MSG_DATA);
            if (invoiceItemId != null && invoiceItemId.length() > 0) {
                launchInvoiceItemActivity(invoiceItemId);
            }
        }
    }
};

private void launchInvoiceItemActivity(String invoiceItemId) {
    Intent intent = new Intent(this, InvoiceItemDetailActivity.class);
    intent.putExtra(ARG_InvoiceItem_ID, invoiceItemId);
    this.startActivity(intent);
}

The invoice detail has the getSupportActionBar().setDisplayHomeAsUpEnabled(true); so that it can return to the list of invoices. The line item detail page has the same line to allow the back button to go to the invoice.

When I tap the back button on the line item detail activity it can't load the invoice because it doesn't have the invoice number that was passed in from the original list.

I understand I can override onBackPressed and create an intent that launches its parent rather than letting the framework do it. My question is will that mess up any internal view stack that the framework is keeping in the case of parent-child navigation? Is there some other way that I'm supposed to track items in a master view so it can be reloaded with the correct content when returning from a detail view?

TIA
Mike


问:
Methods that can only be called by one thread at a time
I have a function that is used by multiple threads. Because of its nature, this function should only ever called once at a time. Multiple threads calling the function at the same time could be bad.

If the function is in use by a thread, other threads should have to wait for it to be free.

My background isn't coding so I'm not sure, but I believe this is called "locking" in the jargon? I tried Googling it up but did not find a simple example for Python3.

A simplified case:

```<code>def critical_function():
    # How do I "lock" this function?
    print('critical operation that should only be run once at a time')

def threaded_function():
    while True:
        # doing stuff and then
        critical_function()

for i in range(0, 10):
    threading.Thread(target=threaded_function).start()
</code>```

答:
```<code>from threading import Lock
critical_function_lock = Lock()

def critical_function():
    with critical_function_lock:
        # How do I "lock" this function?
        print('critical operation that should only be run once at a time')
</code>```

Body:
I have a function that is used by multiple threads. Because of its nature, this function should only ever called once at a time. Multiple threads calling the function at the same time could be bad.

If the function is in use by a thread, other threads should have to wait for it to be free.

My background isn't coding so I'm not sure, but I believe this is called "locking" in the jargon? I tried Googling it up but did not find a simple example for Python3.

A simplified case:

def critical_function():
    # How do I "lock" this function?
    print('critical operation that should only be run once at a time')

def threaded_function():
    while True:
        # doing stuff and then
        critical_function()

for i in range(0, 10):
    threading.Thread(target=threaded_function).start()


问:
Eloquent orderBy except one row
I basically just want to order my results by name except for 1 row - which I want to keep at the bottom of the results.

I have the following database table:

```<code>INSERT INTO `teams` (`id`, `name`, `created_at`, `updated_at`) VALUES
(1, 'Anaheim Ducks', NULL, NULL),
(2, 'Arizona Coyotes', NULL, NULL),
(3, 'Atlanta Flames', NULL, NULL),
(4, 'Atlanta Thrashers', NULL, NULL),
(5, 'Boston Bruins', NULL, NULL),
(6, 'Buffalo Sabres', NULL, NULL),
(7, 'Calgary Flames', NULL, NULL),
(8, 'California Golden Seals', NULL, NULL),
(9, 'Carolina Hurricanes', NULL, NULL),
(10, 'Chicago Blackhawks', NULL, NULL),
(11, 'Cleveland Barons', NULL, NULL),
(12, 'Colorado Avalanche', NULL, NULL),
(13, 'Colorado Rockies', NULL, NULL),
(14, 'Columbus Blue Jackets', NULL, NULL),
(49, 'Other', NULL, NULL);
</code>```

Now, I want to use Eloquent to order these all by name, EXCEPT I want Other to be at the bottom.

I am unsure how to do this using orderBy(). How do I do this?

答:
As an alternative to @Anton's answer (and you're using Laravel 5.3+) you could make use of the partition() method:

```<code>$teams = Team::orderBy('name')->get()
    ->partition(function ($item) {
        return $item->name != 'Other';
    })->flatten();
</code>```

This will push the "Other" row to the bottom of the list whilst keeping the rest of the collection in order.

Hope this helps!

Title: Eloquent orderBy except one row

Body:
I basically just want to order my results by name except for 1 row - which I want to keep at the bottom of the results.

I have the following database table:

INSERT INTO `teams` (`id`, `name`, `created_at`, `updated_at`) VALUES
(1, 'Anaheim Ducks', NULL, NULL),
(2, 'Arizona Coyotes', NULL, NULL),
(3, 'Atlanta Flames', NULL, NULL),
(4, 'Atlanta Thrashers', NULL, NULL),
(5, 'Boston Bruins', NULL, NULL),
(6, 'Buffalo Sabres', NULL, NULL),
(7, 'Calgary Flames', NULL, NULL),
(8, 'California Golden Seals', NULL, NULL),
(9, 'Carolina Hurricanes', NULL, NULL),
(10, 'Chicago Blackhawks', NULL, NULL),
(11, 'Cleveland Barons', NULL, NULL),
(12, 'Colorado Avalanche', NULL, NULL),
(13, 'Colorado Rockies', NULL, NULL),
(14, 'Columbus Blue Jackets', NULL, NULL),
(49, 'Other', NULL, NULL);

Now, I want to use Eloquent to order these all by name, EXCEPT I want Other to be at the bottom.

I am unsure how to do this using orderBy(). How do I do this?

Body:
As an alternative to @Anton's answer (and you're using Laravel 5.3+) you could make use of the partition() method:

$teams = Team::orderBy('name')->get()
    ->partition(function ($item) {
        return $item->name != 'Other';
    })->flatten();

This will push the "Other" row to the bottom of the list whilst keeping the rest of the collection in order.

Hope this helps!


问:
jQuery UI Slider multiple events triggers
The jQuery UI slider allows events to be triggered on start, slide, change, stop (see: http://jqueryui.com/demos/slider/#events)

I need values to be shown in an input field during SLIDE, and need a form to submit on STOP.  However it seems that if the function has two even triggers, it fails to render the slider.

Here's the working code:

```<code> <script>
 $(function() {
  $( "#slider-range" ).slider({
   range: true,
   min: 50,
   step: 10,
   max: 500,
   values: [ 75, 450 ],
   slide: function( event, ui ) {
    $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] + " avg/night" );
    $( "#edit-nightlyavg-min" ).val( ui.values[ 0 ] );
    $( "#edit-nightlyavg-max" ).val( ui.values[ 1 ] );
   }
  });
  $( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) +
   " - $" + $( "#slider-range" ).slider( "values", 1 ) + " avg/night" );
  $( "#edit-nightlyavg-op" ).val( "between" );

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

Here's the non-working code:

```<code>     <script>
 $(function() {
  $( "#slider-range" ).slider({
   range: true,
   min: 50,
   step: 10,
   max: 500,
   values: [ 75, 450 ],
   slide: function( event, ui ) {
    $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] + " avg/night" );
    $( "#edit-nightlyavg-min" ).val( ui.values[ 0 ] );
    $( "#edit-nightlyavg-max" ).val( ui.values[ 1 ] );
   }
   stop: function( event, ui ) {
    $( "#views-exposed-form-location-directory-page-1" ).submit();
   }
  });
  $( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) +
   " - $" + $( "#slider-range" ).slider( "values", 1 ) + " avg/night" );
  $( "#edit-nightlyavg-op" ).val( "between" );

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

答: You forgot the , after the 'slide' function.

Body:
The jQuery UI slider allows events to be triggered on start, slide, change, stop (see: http://jqueryui.com/demos/slider/#events)

I need values to be shown in an input field during SLIDE, and need a form to submit on STOP.  However it seems that if the function has two even triggers, it fails to render the slider.

Here's the working code:

Here's the non-working code:


问:
How can i parse only the numbers from the string?
I want that in Rect.rectangles under the transform property instead to have the string "matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)" to have 2 properties like transform and transform1 and each one will have a number for example: transform "0.12345678"
         transform1 "1.12345678"

```<code>private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))
        }).ToList();
    }
</code>```

And the Rect class:

```<code>public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }
</code>```

I'm trying to use substring but getting out of range exception.

ArgumentOutOfRangeException: Cannot exceed length of string

On the line:

```<code>transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))
</code>```

The string is:

transform="matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

And i want to get only the first two numbers: 0.40438612,-0.91458836

Update:

I found also a way to do it using foreach:

```<code>private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();
        string t = null;
        foreach(Rect rect in Rect.rectangles)
        {
            if (rect.transform != null && rect.transform != "")
            {
                t = rect.transform.Substring(7, 21);
            }
        }
    }
</code>```

But i don't want to do it after the new Rect() {
I want to do the first two numbers extraction on the line:

```<code>transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
</code>```

The reason is that i have in the bottom of the code a class:

```<code>public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }
</code>```

And i want that the property transform to hold/contain the two numbers already.

And another small problem how can i extract the first two numbers if for example one of the numbers have -(minus) in the start for example if transform contain the string: "matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

If one of the two numbers have minus in the start or both of them have minus in the start the Substring(7, 21) will not work. I need somehow to get in any case the first two numbers. But the main issue is how to extract the numbers directly from the attribute already.

答:
Solution:</p>

```<code>private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();

        for(int i = 0; i < Rect.rectangles.Count; i++)
        {
            if (Rect.rectangles[i].transform != null && Rect.rectangles[i].transform != "")
            {
                Rect.rectangles[i].transform = Rect.rectangles[i].transform.Substring(7, 21);
            }
        }
     }
</code>```

Body:
I want that in Rect.rectangles under the transform property instead to have the string "matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)" to have 2 properties like transform and transform1 and each one will have a number for example: transform "0.12345678"
         transform1 "1.12345678"

private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))
        }).ToList();
    }

And the Rect class:

public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }

I'm trying to use substring but getting out of range exception.

ArgumentOutOfRangeException: Cannot exceed length of string

On the line:

transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))

The string is:

transform="matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

And i want to get only the first two numbers: 0.40438612,-0.91458836

Update:

I found also a way to do it using foreach:

private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();
        string t = null;
        foreach(Rect rect in Rect.rectangles)
        {
            if (rect.transform != null && rect.transform != "")
            {
                t = rect.transform.Substring(7, 21);
            }
        }
    }

But i don't want to do it after the new Rect() {
I want to do the first two numbers extraction on the line:

transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")

The reason is that i have in the bottom of the code a class:

public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }

And i want that the property transform to hold/contain the two numbers already.

And another small problem how can i extract the first two numbers if for example one of the numbers have -(minus) in the start for example if transform contain the string: "matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

If one of the two numbers have minus in the start or both of them have minus in the start the Substring(7, 21) will not work. I need somehow to get in any case the first two numbers. But the main issue is how to extract the numbers directly from the attribute already.

Body:
Solution:

private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();

        for(int i = 0; i < Rect.rectangles.Count; i++)
        {
            if (Rect.rectangles[i].transform != null && Rect.rectangles[i].transform != "")
            {
                Rect.rectangles[i].transform = Rect.rectangles[i].transform.Substring(7, 21);
            }
        }
     }