问:
Firefox Web Extensions APIS for Multiple Monitor and Full Screen
Firefox Quantum finally released on November 14, 2017. Quoting from this link:

In the past, you could develop Firefox extensions using one of three different systems: XUL/XPCOM overlays, bootstrapped extensions, or the Add-on SDK. By the end of November 2017, WebExtensions APIs will be the only way to develop Firefox extensions, and the other systems will be deprecated.

Using Firefox 57 Quantum and Web Extensions APIs, I want to make an extension that is capable of running on multiple screens. This extension would be used to show multiple screens dashboards.

The idea of it was so simple. If two or more screens are detected, every Firefox starting up then opens a new window for every monitor in full screen mode. I can do full screen, but facing issues to open on another monitor and detect how many monitors are attached.

Using browser.windows API to create another new tab, here's some snippet code:

```<code>getCurrentWindow().then((currentWindow) => {
  let mirror1 = browser.windows.create({
    url: "http://172.20.12.211:8080/ivi",
    state: "fullscreen"
  });

  mirror1.then(() => {
    browser.windows.remove(currentWindow.id);

    var updateInfo = {
      state: "fullscreen"
    };

    let mirror2 = browser.windows.create({
      url: "http://172.20.12.211:8080/ivi",
      state: "fullscreen"
    });

    mirror2.then((nextWindow) => {
      var updateInfo = {
        left: 1366
      };

      browser.windows.update(nextWindow.id, updateInfo);
    });

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

Obviously, my solution above is hard-coded for two monitors and sets left parameter to 1366 px, hence this solution will not work properly if the screen resolution not equal to 1366x768 or if there are more than two monitors attached.

Thus, is there any API or better approach to detect how many monitors are attached and also check their resolution? Does Web Extension APIs have a feature for detecting multiple monitors and resolution values? If not, what are possible workarounds?

答:
There are no readily available extension APIs that answer your questions, but there are enough building blocks to answer the question in an other way.

The position of the current window relative to the display is available via:

window.screenX - https://developer.mozilla.org/en-US/docs/Web/API/Window/screenX

window.screenY - https://developer.mozilla.org/en-US/docs/Web/API/Window/screenY

The size of the display on which the window is being displayed can be retrieved via:

screen.width - https://developer.mozilla.org/en-US/docs/Web/API/Screen/width

screen.height - https://developer.mozilla.org/en-US/docs/Web/API/Screen/height

Firefox even offers the ability to read the position of the current display relative to all other displays. If you have two displays and the current screen is virtually at the right of the other screen, then the non-standard Firefox-only screen.left property has a non-zero value.

sreen.left - https://developer.mozilla.org/en-US/docs/Web/API/Screen/left

sreen.top - https://developer.mozilla.org/en-US/docs/Web/API/Screen/top

NOTE: When the privacy.resistFingerprinting preference is turned on in Firefox, all of the above APIs return dummy values. You can still query the window size and position through the chrome.windows.get extension API though.

If you create a dummy window and move it around on the screen, then you can use the above APIs to infer information about the screens, and ultimately construct a full view of the available displays and sizes. Here is a sample extension to print the above information. You can click on the button to open a window, and then manually move the window around.

This can be automated by opening a very narrow popup and move that around with chrome.windows.update. If the left/top offset is too large, then the window will stick to the edge of the screen (e.g. if you pass 99999 as a left offset to a window of width 100 on a screen that is 1024px wide, then the left offset becomes 924).

manifest.json

{
    "name": "Display info",
    "version": "1",
    "manifest_version": 2,
    "background": {
        "scripts": ["background.js"]
    },
    "browser_action": {
        "default_title": "Open popup to display info"
    }
}
```

<h3><code>background.js</code></h3>

<pre class="lang-html prettyprint-override"><code>chrome.browserAction.onClicked.addListener(function() {
    chrome.windows.create({
        url: chrome.runtime.getURL('/display.html'),
    });
});
</code>```

display.html

<meta charset="utf-8">

```

<h3><code>display.js</code></h3>

<pre class="lang-html prettyprint-override"><code>setInterval(function() {
    document.body.textContent =
        '\nWindow offset: ' + window.screenX + ',' + window.screenY +
        '\nScreen size  : ' + screen.width + 'x' + screen.height +
        '\nScreen offset: ' + screen.left + ',' + screen.top;
    chrome.windows.get(chrome.windows.WINDOW_ID_CURRENT, function(win) {
        document.body.insertAdjacentText('beforeend',
            '\nExtension window offset : ' + win.left + ',' + win.top);
    });
}, 200);
</code>```

The above APIs are not specific to extensions. You can also run the following snippet and move the window around to see the values.

```

Body:
Firefox Quantum finally released on November 14, 2017. Quoting from this link:

In the past, you could develop Firefox extensions using one of three different systems: XUL/XPCOM overlays, bootstrapped extensions, or the Add-on SDK. By the end of November 2017, WebExtensions APIs will be the only way to develop Firefox extensions, and the other systems will be deprecated.

Using Firefox 57 Quantum and Web Extensions APIs, I want to make an extension that is capable of running on multiple screens. This extension would be used to show multiple screens dashboards.

The idea of it was so simple. If two or more screens are detected, every Firefox starting up then opens a new window for every monitor in full screen mode. I can do full screen, but facing issues to open on another monitor and detect how many monitors are attached.

Using browser.windows API to create another new tab, here's some snippet code:

getCurrentWindow().then((currentWindow) => {
  let mirror1 = browser.windows.create({
    url: "http://172.20.12.211:8080/ivi",
    state: "fullscreen"
  });

  mirror1.then(() => {
    browser.windows.remove(currentWindow.id);

    var updateInfo = {
      state: "fullscreen"
    };

    let mirror2 = browser.windows.create({
      url: "http://172.20.12.211:8080/ivi",
      state: "fullscreen"
    });

    mirror2.then((nextWindow) => {
      var updateInfo = {
        left: 1366
      };

      browser.windows.update(nextWindow.id, updateInfo);
    });

  });
});

Obviously, my solution above is hard-coded for two monitors and sets left parameter to 1366 px, hence this solution will not work properly if the screen resolution not equal to 1366x768 or if there are more than two monitors attached.

Thus, is there any API or better approach to detect how many monitors are attached and also check their resolution? Does Web Extension APIs have a feature for detecting multiple monitors and resolution values? If not, what are possible workarounds?

Body:
There are no readily available extension APIs that answer your questions, but there are enough building blocks to answer the question in an other way.

The position of the current window relative to the display is available via:

window.screenX - https://developer.mozilla.org/en-US/docs/Web/API/Window/screenX

window.screenY - https://developer.mozilla.org/en-US/docs/Web/API/Window/screenY

The size of the display on which the window is being displayed can be retrieved via:

screen.width - https://developer.mozilla.org/en-US/docs/Web/API/Screen/width

screen.height - https://developer.mozilla.org/en-US/docs/Web/API/Screen/height

Firefox even offers the ability to read the position of the current display relative to all other displays. If you have two displays and the current screen is virtually at the right of the other screen, then the non-standard Firefox-only screen.left property has a non-zero value.

sreen.left - https://developer.mozilla.org/en-US/docs/Web/API/Screen/left

sreen.top - https://developer.mozilla.org/en-US/docs/Web/API/Screen/top

NOTE: When the privacy.resistFingerprinting preference is turned on in Firefox, all of the above APIs return dummy values. You can still query the window size and position through the chrome.windows.get extension API though.

If you create a dummy window and move it around on the screen, then you can use the above APIs to infer information about the screens, and ultimately construct a full view of the available displays and sizes. Here is a sample extension to print the above information. You can click on the button to open a window, and then manually move the window around.

This can be automated by opening a very narrow popup and move that around with chrome.windows.update. If the left/top offset is too large, then the window will stick to the edge of the screen (e.g. if you pass 99999 as a left offset to a window of width 100 on a screen that is 1024px wide, then the left offset becomes 924).

manifest.json

{
    "name": "Display info",
    "version": "1",
    "manifest_version": 2,
    "background": {
        "scripts": ["background.js"]
    },
    "browser_action": {
        "default_title": "Open popup to display info"
    }
}

background.js

chrome.browserAction.onClicked.addListener(function() {
    chrome.windows.create({
        url: chrome.runtime.getURL('/display.html'),
    });
});

display.html

<meta charset="utf-8">
<body style="white-space:pre">
<script src="display.js"></script>

display.js

setInterval(function() {
    document.body.textContent =
        '\nWindow offset: ' + window.screenX + ',' + window.screenY +
        '\nScreen size  : ' + screen.width + 'x' + screen.height +
        '\nScreen offset: ' + screen.left + ',' + screen.top;
    chrome.windows.get(chrome.windows.WINDOW_ID_CURRENT, function(win) {
        document.body.insertAdjacentText('beforeend',
            '\nExtension window offset : ' + win.left + ',' + win.top);
    });
}, 200);

The above APIs are not specific to extensions. You can also run the following snippet and move the window around to see the values.

<body style="white-space:pre">
<script>
setInterval(function() {
    document.body.textContent =
        '\nWindow offset: ' + window.screenX + ',' + window.screenY +
        '\nScreen size  : ' + screen.width + 'x' + screen.height +
        '\nScreen offset: ' + screen.left + ',' + screen.top;
}, 200);
</script>


来源: stackexchange

问:
Finding duplicate values only for 2 highest values in a dict
Code:

```<code>candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 17, 'd': 23, 'e': 0}

print(candidates_and_fp_votes)
final_vals = [a for a, b in candidates_and_fp_votes.items() if
              list(candidates_and_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in final_vals:
    print(i)
print(final_vals)

if not final_vals:
    print("No tiebreaker sys required")
else:
    print("Tie-breaker required")
</code>```

Currently, this outputs "Tie-breaker required" as 'b' and 'e' have a value of 0.
I would like this so it only finds duplicates that affect the highest or second highest value.
Eg:

Right now, it should print "No tiebreaker sys required because even if there is a duplicate with 'b' and 'e' it is not
a duplicate with the second and highest values '25' and '23'

if the dict to be = {'a': 25, 'b': 0, 'c': 23, 'd': 23, 'e': 0}
it would print out "Tie-breaker required as it is affecting the 2nd highest value - 23.

Also, I just had a little change in mind, if the highest score is duplicating with a number but this number does not duplicate with the second highest, it would just output "No tiebreaker sys required"

How can I do this?

Thanks in advance.

答:
You can use heapq.nlargest to find the three largest values and then inspect them:

```<code>import heapq
max3 = heapq.nlargest(3, candidates_and_fp_votes.values())
</code>```

max3 will now contain the three largest values (preserving multiple occurrences) in descending order. The rest should be easy.

ContentLicense: CC BY-SA 3.0

Body:
Code:

candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 17, 'd': 23, 'e': 0}

print(candidates_and_fp_votes)
final_vals = [a for a, b in candidates_and_fp_votes.items() if
              list(candidates_and_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in final_vals:
    print(i)
print(final_vals)

if not final_vals:
    print("No tiebreaker sys required")
else:
    print("Tie-breaker required")

Currently, this outputs "Tie-breaker required" as 'b' and 'e' have a value of 0.
I would like this so it only finds duplicates that affect the highest or second highest value.
Eg:

Right now, it should print "No tiebreaker sys required because even if there is a duplicate with 'b' and 'e' it is not
a duplicate with the second and highest values '25' and '23'

if the dict to be = {'a': 25, 'b': 0, 'c': 23, 'd': 23, 'e': 0}
it would print out "Tie-breaker required as it is affecting the 2nd highest value - 23.

Also, I just had a little change in mind, if the highest score is duplicating with a number but this number does not duplicate with the second highest, it would just output "No tiebreaker sys required"

How can I do this?

Thanks in advance.

Body:
You can use heapq.nlargest to find the three largest values and then inspect them:

import heapq
max3 = heapq.nlargest(3, candidates_and_fp_votes.values())

max3 will now contain the three largest values (preserving multiple occurrences) in descending order. The rest should be easy.


问:
Convert mimetype to file extension
how to convert mimetype to file extension in xcode
for example i have this code

```<code>File Extension     MIME Type

aifc                audio/x-aiff
avi                 video/x-msvideo
gz                  application/x-gzip
jpg                 image/jpeg
</code>```

Xcode

```<code>- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
        NSString *mime      = [response MIMEType];
        NSString *extension = @"" // how to covert it ?!
}
</code>```

答:
Swift 4:

Import CoreServices

```<code>response.mimeType // is Optional<String> - some : "audio/mpeg"
</code>```

And how to get mp3 is:

```<code>guard let mime = response.mimeType,
      let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mime as CFString, nil),
      let ext = UTTypeCopyPreferredTagWithClass(uti.takeRetainedValue(), kUTTagClassFilenameExtension) else {
   return
}

ext.takeRetainedValue() // is "mp3"
</code>```

PD: Consider that Xcode won't get extensions of unknown file like .Storyboard or .cert in this case will exit in the Guard return.

Title: Convert mimetype to file extension

Body:
how to convert mimetype to file extension in xcode
for example i have this code

File Extension     MIME Type

aifc                audio/x-aiff
avi                 video/x-msvideo
gz                  application/x-gzip
jpg                 image/jpeg

Xcode

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
        NSString *mime      = [response MIMEType];
        NSString *extension = @"" // how to covert it ?!
}

Body:
Swift 4:

Import CoreServices

response.mimeType // is Optional<String> - some : "audio/mpeg"

And how to get mp3 is:

guard let mime = response.mimeType,
      let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mime as CFString, nil),
      let ext = UTTypeCopyPreferredTagWithClass(uti.takeRetainedValue(), kUTTagClassFilenameExtension) else {
   return
}

ext.takeRetainedValue() // is "mp3"

PD: Consider that Xcode won't get extensions of unknown file like .Storyboard or .cert in this case will exit in the Guard return.

ContentLicense: CC BY-SA 4.0


问:
Read Int32 from binary at specific position
I have a memorystream reading a specific part of my data. From the binary I want one ReadInt32 value from position 5-8. How do I achieve this in:</p>

```<code>using (var reader = new BinaryReader(stream))
{

  somebyte1
  somebyte2
  somebyte3

  //get only this value
  int v = reader.ReadInt32;

}
</code>```

答:
Move the base stream to the position you want to read from:</p>

```<code>stream.Seek(4, SeekOrigin.Begin);

using (var reader = new BinaryReader(stream))
{
    int v = reader.ReadInt32;
}
</code>```

Body:
I have a memorystream reading a specific part of my data. From the binary I want one ReadInt32 value from position 5-8. How do I achieve this in:

using (var reader = new BinaryReader(stream))
{

  somebyte1
  somebyte2
  somebyte3

  //get only this value
  int v = reader.ReadInt32;

}

Body:
Move the base stream to the position you want to read from:

stream.Seek(4, SeekOrigin.Begin);

using (var reader = new BinaryReader(stream))
{
    int v = reader.ReadInt32;
}


问:
Printing a list after having removed adjacent duplicate elements
```<code>new_list = []

i = 0

def remove_adjacent(nums):
    global i
    while i < len(nums) - 1:
        if nums[i] != nums[i+1]:
            new_list.append(nums[i])
        else:
            i += 1
            remove_adjacent(nums[i:])
            return
    i += 1

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

remove_adjacent(l)

print new_list
</code>```

Question: Given a list of numbers, return a list where all adjacent == elements have been reduced to a single element, so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or modify the passed in list.

Issue: The final list printed consists of [1, 2, 3, 5] instead of [1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]

答:
I made a function where it get a list and iterate over its items, then it adds the items that aren't the same as the items already added to the list in the previous iteration.</p>

```<code>l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]  # List that we want to change

def remove_adjacent(l):             # Define a new function and accept an argument: the list to check.
    new = [l[0]]                    # Make a new list (temporal) and assing like it's first item the first item of the main list. It's the same as new = [] and new.append(l[0]).
    for item in l[1:]:              # We iterate across the list, but we don't iterate on the first item because we've alreaday added it to the list, if you want you can delete the slice in [1:] since it will only make the iteration a really small fraction more slowly.
        if new[-1] != item:         # We check if the new item is the same as the last item added to the new list, if not, we add it.
            new.append(item)        # We add the item to the new list.
    return new                      # We return the list.

print(remove_adjacent(l))           # We check it.
# [1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]
</code>```

Body:
new_list = []

i = 0

def remove_adjacent(nums):
    global i
    while i < len(nums) - 1:
        if nums[i] != nums[i+1]:
            new_list.append(nums[i])
        else:
            i += 1
            remove_adjacent(nums[i:])
            return
    i += 1

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

remove_adjacent(l)

print new_list

Question: Given a list of numbers, return a list where all adjacent == elements have been reduced to a single element, so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or modify the passed in list.

Issue: The final list printed consists of [1, 2, 3, 5] instead of [1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]

Body:
I made a function where it get a list and iterate over its items, then it adds the items that aren't the same as the items already added to the list in the previous iteration.

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]  # List that we want to change

def remove_adjacent(l):             # Define a new function and accept an argument: the list to check.
    new = [l[0]]                    # Make a new list (temporal) and assing like it's first item the first item of the main list. It's the same as new = [] and new.append(l[0]).
    for item in l[1:]:              # We iterate across the list, but we don't iterate on the first item because we've alreaday added it to the list, if you want you can delete the slice in [1:] since it will only make the iteration a really small fraction more slowly.
        if new[-1] != item:         # We check if the new item is the same as the last item added to the new list, if not, we add it.
            new.append(item)        # We add the item to the new list.
    return new                      # We return the list.

print(remove_adjacent(l))           # We check it.
# [1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]


答:
If the 2nd highest value in candidates_and_fp_votes is having a tie, then it prints "Tie-breaker required".

```<code>#candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 17, 'd': 23, 'e': 0}

candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 23, 'd': 23, 'e': 0}
    print(candidates_and_fp_votes)
final_vals = [ b for a, b in candidates_and_fp_votes.items() if list(candidates_and_fp_votes.values()).count(b) > 1]
dup=sorted(set(final_vals), reverse=True)

act=sorted(set(list(candidates_and_fp_votes.values())), reverse=True)

print("duplicates: ", dup)
print("actual:     ", act)

if dup:
    if dup[0] == act[0]:
        del act[0]
        del dup[0]

if dup:
    if dup[0] == act[0] or dup[0] == act[1]:
        print("Tie breaker required")
    else:
        print("No tie breaker required")
else:
    print("No tie breaker required")
</code>```

Title: Finding duplicate values only for 2 highest values in a dict

Body:
If the 2nd highest value in candidates_and_fp_votes is having a tie, then it prints "Tie-breaker required".

#candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 17, 'd': 23, 'e': 0}

candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 23, 'd': 23, 'e': 0}
    print(candidates_and_fp_votes)
final_vals = [ b for a, b in candidates_and_fp_votes.items() if list(candidates_and_fp_votes.values()).count(b) > 1]
dup=sorted(set(final_vals), reverse=True)

act=sorted(set(list(candidates_and_fp_votes.values())), reverse=True)

print("duplicates: ", dup)
print("actual:     ", act)

if dup:
    if dup[0] == act[0]:
        del act[0]
        del dup[0]

if dup:
    if dup[0] == act[0] or dup[0] == act[1]:
        print("Tie breaker required")
    else:
        print("No tie breaker required")
else:
    print("No tie breaker required")


问:
How to calculate Normalized Gini Coefficient in tensorflow
I am trying to calculate Normalized Gini Coefficient in tensorflow but am unable to do so. I have the below python code for the same executed in numpy but I want to implement it using tensorflow. If any ideas, please help.
I will be having actual with the tensor shape (1,?) and pred with tensor shape (1,?)

Python Code:

```<code>def gini(actual, pred, cmpcol = 0, sortcol = 1):
     assert( len(actual) == len(pred) )
     all = np.asarray(np.c_[ actual, pred, np.arange(len(actual)) ], dtype=np.float)
     all = all[ np.lexsort((all[:,2], -1*all[:,1])) ]
     totalLosses = all[:,0].sum()
     giniSum = all[:,0].cumsum().sum() / totalLosses

     giniSum -= (len(actual) + 1) / 2.
     return giniSum / len(actual)

 def gini_normalized(a, p):
     return gini(a, p) / gini(a, a)
</code>```

答:
Here's a working solution.</p>

```<code>def gini(actual, pred):
    n = tf.shape(actual)[1]
    indices = tf.reverse(tf.nn.top_k(pred, k=n)[1], axis=[1])[0]
    a_s = tf.gather(tf.transpose(actual), tf.transpose(indices))
    a_c = tf.cumsum(a_s)
    giniSum = tf.reduce_sum(a_c) / tf.reduce_sum(a_s)
    giniSum = tf.subtract(giniSum, tf.divide(tf.to_float(n + 1), tf.constant(2.)))
    return giniSum / tf.to_float(n)

def gini_normalized(a, p):
    return gini(a, p) / gini(a, a)
</code>```

Body:
I am trying to calculate Normalized Gini Coefficient in tensorflow but am unable to do so. I have the below python code for the same executed in numpy but I want to implement it using tensorflow. If any ideas, please help.
I will be having actual with the tensor shape (1,?) and pred with tensor shape (1,?)

Python Code:

def gini(actual, pred, cmpcol = 0, sortcol = 1):
     assert( len(actual) == len(pred) )
     all = np.asarray(np.c_[ actual, pred, np.arange(len(actual)) ], dtype=np.float)
     all = all[ np.lexsort((all[:,2], -1*all[:,1])) ]
     totalLosses = all[:,0].sum()
     giniSum = all[:,0].cumsum().sum() / totalLosses

     giniSum -= (len(actual) + 1) / 2.
     return giniSum / len(actual)

 def gini_normalized(a, p):
     return gini(a, p) / gini(a, a)

Body:
Here's a working solution.

def gini(actual, pred):
    n = tf.shape(actual)[1]
    indices = tf.reverse(tf.nn.top_k(pred, k=n)[1], axis=[1])[0]
    a_s = tf.gather(tf.transpose(actual), tf.transpose(indices))
    a_c = tf.cumsum(a_s)
    giniSum = tf.reduce_sum(a_c) / tf.reduce_sum(a_s)
    giniSum = tf.subtract(giniSum, tf.divide(tf.to_float(n + 1), tf.constant(2.)))
    return giniSum / tf.to_float(n)

def gini_normalized(a, p):
    return gini(a, p) / gini(a, a)


问:
What's the easiest way to implement collision detection in an XNA Game w/ C#?
I'm basically working on a Pong clone, and I wanted to add collision. The way I wanted it to work, is that the paddles would each be divided into 4 sections (not visually), and the ball will react differently depending on which section it hits.

As far as collision goes, I only know rectangle collision, and that's basically the entire paddle as a whole. I do not know how to make it so the paddle has 4 possible points of collision with different reactions.

答:
Just break paddle into 4 pieces, and keep it as one piece :)

Collide method returns -1 if rects do not collide, or a first index of collision.

CollideIndex method returns IEnumerable indexes of collided rects. ;)

```<code>Paddle p;
World w;
Ball b;

Rect[] paddleSections = new Rect[]
{
  p.Section[0],
  p.Section[1],
  p.Section[2],
  p.Section[3],
}

Rect[] worldSections = new Rect[]
{
  new Rect(p.Top, p.Left, p.Right, p.Bottom) // just simple world, for example
}

Rect[] ballSections = new Rect[]
{
  new Rect(p.Top, p.Left, p.Right, p.Bottom) // just one ball piece, for example
}

Rect[] bricksSection = GetBrickRects();

int index = 0;
if ((index = Collide(ballSections, worldSections) != -1)
{
    foreach(int collideIndex in CollideIndex(ballSection[index], worldSection)
    {
        // worldSection[collideIndex] intersects ballSections[index]
        ...
        // something goes up here
    }
}
</code>```

Call your favorite algorithm against balls, walls, bricks.

Do not forget to send me a copy of your game!

ContentLicense: CC BY-SA 2.5

Body:
Just break paddle into 4 pieces, and keep it as one piece :)

Collide method returns -1 if rects do not collide, or a first index of collision.

CollideIndex method returns IEnumerable indexes of collided rects. ;)

Paddle p;
World w;
Ball b;

Rect[] paddleSections = new Rect[]
{
  p.Section[0],
  p.Section[1],
  p.Section[2],
  p.Section[3],
}

Rect[] worldSections = new Rect[]
{
  new Rect(p.Top, p.Left, p.Right, p.Bottom) // just simple world, for example
}

Rect[] ballSections = new Rect[]
{
  new Rect(p.Top, p.Left, p.Right, p.Bottom) // just one ball piece, for example
}

Rect[] bricksSection = GetBrickRects();

int index = 0;
if ((index = Collide(ballSections, worldSections) != -1)
{
    foreach(int collideIndex in CollideIndex(ballSection[index], worldSection)
    {
        // worldSection[collideIndex] intersects ballSections[index]
        ...
        // something goes up here
    }
}

Call your favorite algorithm against balls, walls, bricks.

Do not forget to send me a copy of your game!


问:
ReferenceError : By is not defined - webdriverIO
Code :

```<code>var assert = require('assert');
describe('webdriver.io api page', function() {
    it('should open login page', function () {
        browser.url('/login');
        browser.pause(10000);
})

it('Should enter login details and submit', function() {

    browser.pause(10000);
    browser.element(By.xpath("//input[@type='text' and @aria-label='user name']")).sendKeys("mikestr");

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

I am new to webdriverIO and trying to locate username textbox using xpath but it throws me error. I look around many webdriverIO material but did not get solution for this yet.

答:
WebdriverIO's Selectors are different than Selenium Webdriver. It will accept the String value for either "XPath" or "CSS" selectors. The "By is not defined" Error you're seeing is because it's looking for a "String" value of a selector.

Documentation:
http://webdriver.io/guide/usage/selectors.html#CSS-Query-Selector

In your situation you would only need to pass something like:

```<code>browser.element('"//input[@type='text' and @aria-label='user name']"')
       .setValue('mikestr')
</code>```

Alternatively you could set the variable and pass a variable like:

```<code>var XPath = "//input[@type='text' and @aria-label='user name']"
browser.element(XPath).setValue('mikestr')
</code>```

Body:
Code :

var assert = require('assert');
describe('webdriver.io api page', function() {
    it('should open login page', function () {
        browser.url('/login');
        browser.pause(10000);
})

it('Should enter login details and submit', function() {

    browser.pause(10000);
    browser.element(By.xpath("//input[@type='text' and @aria-label='user name']")).sendKeys("mikestr");

})
});

I am new to webdriverIO and trying to locate username textbox using xpath but it throws me error. I look around many webdriverIO material but did not get solution for this yet.

Body:
WebdriverIO's Selectors are different than Selenium Webdriver. It will accept the String value for either "XPath" or "CSS" selectors. The "By is not defined" Error you're seeing is because it's looking for a "String" value of a selector.

Documentation:
http://webdriver.io/guide/usage/selectors.html#CSS-Query-Selector

In your situation you would only need to pass something like:

browser.element('"//input[@type='text' and @aria-label='user name']"')
       .setValue('mikestr')

Alternatively you could set the variable and pass a variable like:

var XPath = "//input[@type='text' and @aria-label='user name']"
browser.element(XPath).setValue('mikestr')


问:
Limit the number of charaters in a JSF datatable column
im using JSF for J2EE projet and im looking how to limit the numbers of characters in a datatable column (h:colum; p:column).
Thanks for your help and have a nice day.</p>

答:
I guess you want that large text don't break in new row. My recommendation is use css:

```<code><p:column headerText="My column" styleClass="single-line">
    <h:outputText value="#{largeTextProperty}" />
</p:column>

.single-line {
    text-wrap: none;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
</code>```

Body:
I guess you want that large text don't break in new row. My recommendation is use css:

<p:column headerText="My column" styleClass="single-line">
    <h:outputText value="#{largeTextProperty}" />
</p:column>

.single-line {
    text-wrap: none;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}


问:
Best practices and examples on how to organize object oriented javascript?
I am a newbie to JavaScript and programming in general. I've started creating my first web app and I would like to rewrite it using an object oriented approach. I've read some articles and book chapters on object oriented JS about how to simulate namespaces, the module pattern and so, but I am having a hard time thinking about how to organize my code inside objects, hope you can help me with this or point me in the right direction to some examples or best practices.

I was thinking to organize it sort of like jQuery with a namespace (called app maybe) and all my app functions inside it, for example app.func1, app.func2, however I have other functions which are used inside those which are like utilities and I would like them to have another name, maybe something like app.util.func... Also my code creates custom objects inside my app, but I don't know where is the right place to put them and their constructors inside my namespace.

Any suggestions, ideas, best practices, templates, or examples on how to organize object oriented javascript? Examples on creating simple library like code would be great.

Thanks in advance!

答:
I've read some articles and book chapters on object oriented JS about how to simulate namespaces, ...

I wouldn't simulate classical OO paradigms in JavaScript. You should stick with what's natural for JavaScript.

Don't do classical inheritance. Use prototypal inheritance or no inheritance at all: Composition/decoration look a lot nicer than inheritance in JavaScript.

You don't need namespaces. They cause unnecessary indirection and cause enterprisey code clutter. Use a good module pattern that hides your functions and variables inside closures.

Try a module loader like RequireJS. You can hide your modules in their own files and closures and let RequireJS do dependency injection magic for you.

Organizing JS application files is a very broad topic. You could organize your classes based on separation of concerns by using paradigms like MVC or MVP. In terms of project organization, building your application on Maven (and following its conventions) could be an option.

Since your question has been at a very high level, I just wanted to throw in some ideas and keywords that you may want to Google and read up on. Maybe after some research and trials and tribulations, you can come back and ask about more specific problems.


问:
C3 Timeseries - show x ticks only every 15 minutes
I'm using C3 to generate an hour worth of measurments. It is updated every minute and oldest metric pops out of dataset and is replaced by new. So at any given time I have data for the last 60 minutes.

I would like to show the x value only on :00, :15, :30, :45 minutes. With count I can limit number of ticks to 4 but it starts from the chart creation time.

```<code>x: {
  type: 'timeseries',
  tick: {
    //fit: true,
    //count: 4,
    format: '%H:%M'
  }
}
</code>```

This is not the full example but will do:
http://jsfiddle.net/ht2nrmg7/4/

答:
You can set the exact values of the ticks that will be displayed in the chart, I'm relying on momentjs which has an awesome way to add/substract duration to a given date.

c3 chart tick for x axis

```<code>tick: {
  format: '%H:%M',
  rotate: -90,
  values: this.every(15, 'minutes')
}
</code>```

Date array generator based on momentJS

```<code>every(increment, unit) {
  const startDate = ...; //<-- Your initial date
  const stopDate = ...;  //<-- Your stop date

  let ticks = [];
  let currentDate = startDate;

  while (currentDate <= stopDate) {
    ticks.push(currentDate)
    //Note the format part has to match you data.xFormat pattern
    currentDate = moment(currentDate).add(increment, unit).format('Y-MM-DD HH:mm:ss');
  }

  return ticks;
}
</code>```

Body:
I'm using C3 to generate an hour worth of measurments. It is updated every minute and oldest metric pops out of dataset and is replaced by new. So at any given time I have data for the last 60 minutes.

I would like to show the x value only on :00, :15, :30, :45 minutes. With count I can limit number of ticks to 4 but it starts from the chart creation time.

x: {
  type: 'timeseries',
  tick: {
    //fit: true,
    //count: 4,
    format: '%H:%M'
  }
}

This is not the full example but will do:
http://jsfiddle.net/ht2nrmg7/4/

Body:
You can set the exact values of the ticks that will be displayed in the chart, I'm relying on momentjs which has an awesome way to add/substract duration to a given date.

c3 chart tick for x axis

tick: {
  format: '%H:%M',
  rotate: -90,
  values: this.every(15, 'minutes')
}

Date array generator based on momentJS

every(increment, unit) {
  const startDate = ...; //<-- Your initial date
  const stopDate = ...;  //<-- Your stop date

  let ticks = [];
  let currentDate = startDate;

  while (currentDate <= stopDate) {
    ticks.push(currentDate)
    //Note the format part has to match you data.xFormat pattern
    currentDate = moment(currentDate).add(increment, unit).format('Y-MM-DD HH:mm:ss');
  }

  return ticks;
}


问:
R ggsurvplot fixing ratio
Im at preparing the last plots for submission but cant get the last things correct. What i want to do is making the plot square and having the risk table follow it size.

I'm using this code
 ggsurvplot(survfit(Surv(time,event) ~ "(hidden)"), risk.table = T, legend.labs = c("(hidden)","(hidden)"), pval = T, xlab = "Days", ylab= "Cum Survival", xlim = c(0,1000), break.x.by = c(200), surv.plot.height = 2,ggtheme = theme(aspect.ratio = 1)) for my survival plot.

But what a get is a square plot but also a square risk table. Any ideas on how to make the code not apply to the risk table?

Sincerely

答:
To fix the awkward aspect ratio one can specify tables.theme in the call to ggsurvplot. Example:

```<code>library(survminer)
library(survival)

ggsurvplot(survfit(Surv(time, status)~ sex, data = lung), risk.table = T,
           legend.labs = c("M" ,"F"),
           pval = T,
           xlab = "Days",
           ylab= "Cum Survival",
           xlim = c(0,1000),
           break.x.by = c(200),
           surv.plot.height = 2,
           ggtheme = theme(aspect.ratio = 1),
           tables.theme =  theme(aspect.ratio = 0.2))
</code>```

Title: R ggsurvplot fixing ratio

Body:
To fix the awkward aspect ratio one can specify tables.theme in the call to ggsurvplot. Example:

library(survminer)
library(survival)

ggsurvplot(survfit(Surv(time, status)~ sex, data = lung), risk.table = T,
           legend.labs = c("M" ,"F"),
           pval = T,
           xlab = "Days",
           ylab= "Cum Survival",
           xlim = c(0,1000),
           break.x.by = c(200),
           surv.plot.height = 2,
           ggtheme = theme(aspect.ratio = 1),
           tables.theme =  theme(aspect.ratio = 0.2))


问:
'No such file or directory', but can 'stat' the file
I am able to stat a file or see it with ls, but any other command fails to read the file:

```<code>edcc@dev3:~$ stat /var/www/ihec/tracks/Blueprint/hg19/56880.Blueprint.ERS487362.H3K4me3.signal_unstranded.bigWig
  File: '/var/www/ihec/tracks/Blueprint/hg19/56880.Blueprint.ERS487362.H3K4me3.signal_unstranded.bigWig' -> '/home/genomicdata/ihec_datasets/2017-10/wp10/hg19/0e1deb1cb52cf13a3663f163f9ac6285'
  Size: 82          Blocks: 1          IO Block: 512    symbolic link
Device: 917ah/37242d    Inode: 208798      Links: 1
Access: (0777/lrwxrwxrwx)  Uid: ( 1003/    edcc)   Gid: ( 1003/    edcc)
Access: 2017-11-15 12:43:13.802444330 -0500
Modify: 2017-10-18 14:03:37.711749034 -0400
Change: 2017-10-18 14:03:37.711749034 -0400
 Birth: -

edcc@dev3:~$ cat /var/www/ihec/tracks/Blueprint/hg19/56880.Blueprint.ERS487362.H3K4me3.signal_unstranded.bigWig
cat: /var/www/ihec/tracks/Blueprint/hg19/56880.Blueprint.ERS487362.H3K4me3.signal_unstranded.bigWig: No such file or directory
</code>```

Any idea why it is happening?

答: It's a symlink pointing to an unexistent file.</p>

Body:
I am able to stat a file or see it with ls, but any other command fails to read the file:

edcc@dev3:~$ stat /var/www/ihec/tracks/Blueprint/hg19/56880.Blueprint.ERS487362.H3K4me3.signal_unstranded.bigWig
  File: '/var/www/ihec/tracks/Blueprint/hg19/56880.Blueprint.ERS487362.H3K4me3.signal_unstranded.bigWig' -> '/home/genomicdata/ihec_datasets/2017-10/wp10/hg19/0e1deb1cb52cf13a3663f163f9ac6285'
  Size: 82          Blocks: 1          IO Block: 512    symbolic link
Device: 917ah/37242d    Inode: 208798      Links: 1
Access: (0777/lrwxrwxrwx)  Uid: ( 1003/    edcc)   Gid: ( 1003/    edcc)
Access: 2017-11-15 12:43:13.802444330 -0500
Modify: 2017-10-18 14:03:37.711749034 -0400
Change: 2017-10-18 14:03:37.711749034 -0400
 Birth: -

edcc@dev3:~$ cat /var/www/ihec/tracks/Blueprint/hg19/56880.Blueprint.ERS487362.H3K4me3.signal_unstranded.bigWig
cat: /var/www/ihec/tracks/Blueprint/hg19/56880.Blueprint.ERS487362.H3K4me3.signal_unstranded.bigWig: No such file or directory

Any idea why it is happening?


问:
C# EF DefaultIfEmpty with Where().Select()
Is there a way similar to what we can do with linq for left outer join with method based query syntax.

e.g.

```<code>var a = from m in context.MainClass
        join r in context.RefClass on m.RefID equals r.ID into joinedent
        from j in joinedent.DefaultIfEmpty()
        select new { m.Name , j.TypeName }
</code>```

Can I convert this into method based syntax with navigation property default if null

```<code>var a = context.MainClass.Select(x=> new {
               m.Name
               m.RefClass.TypeName // here need default if RefClass is null
        })
</code>```

I can do like (m.RefClass != null)?m.RefClass.TypeName:""   but would like to know if there is a proper way to do this like in above linq.

Thanks

答:
Can you try using Include?

```<code>var a = context.MainClass.Include("RefClass")
                         .Select(x => new {
                             m.Name
                             m.RefClass.TypeName // here need default if RefClass is null
                         })
</code>```

Body:
Is there a way similar to what we can do with linq for left outer join with method based query syntax.

e.g.

var a = from m in context.MainClass
        join r in context.RefClass on m.RefID equals r.ID into joinedent
        from j in joinedent.DefaultIfEmpty()
        select new { m.Name , j.TypeName }

Can I convert this into method based syntax with navigation property default if null

var a = context.MainClass.Select(x=> new {
               m.Name
               m.RefClass.TypeName // here need default if RefClass is null
        })

I can do like (m.RefClass != null)?m.RefClass.TypeName:""   but would like to know if there is a proper way to do this like in above linq.

Thanks

Body:
Can you try using Include?

var a = context.MainClass.Include("RefClass")
                         .Select(x => new {
                             m.Name
                             m.RefClass.TypeName // here need default if RefClass is null
                         })


问:
Laravel models to implement one to many and many to many in single query
i have this table structure, project has one to many relation with rewards , rewards and shipping has many to many relation with pivot table reward_ship.

```<code>projects       rewards         shipping       reward_ship
---------      --------        --------       ------------
id             id              id             id
title          amount          location       reward_id
amount         project_id      name           ship_id
</code>```

i am trying to extract one particular project details with all other associate tables data(rewards and shipping data using reward_ship table) in one query.

These is how i am trying

Projects Model

```<code>    class Rewards extends Model {
         public function projs(){
              return $this->hasMany('App\Rewards');
          }
         public function rewds(){
              return $this->belongsToMany('App\Shipping')
              ->withPivot('reward_ship', 'ship_id', 'reward_id');
         }
         public function shiplc(){
               return $this->belongsToMany('App\Rewards')
               ->withPivot('reward_ship', 'ship_id', 'reward_id');
         }
      }
class Rewards extends Model {
    public function proj() {
        return $this->belongsTo('App\Projects');
    }
}
</code>```

Controller api class

```<code>Route::get('projects/{id}', function($id) {
$p = Projects::find($id);
$getd = Rewards::with('proj')
    ->where('rewards.project_id', '=', $p->id)
    ->get();
 });
</code>```

it doesn't work.
i search and tried many related model base query in larvel.
i know my implementation are wrong. Please suggest me to work out.

答:
You can use Laravel 5.5 new feature API Resources.

It helps you to format the output of objects such as models or collections, to display attributes and also relationships.

So, you could do something like this in your ItemResource:

    <?php

    namespace App\Http\Resources;

    use Illuminate\Http\Resources\Json\Resource;

    class Project extends Resource
    {
        /**
         * Transform the resource into an array.
         *
         * @param  \Illuminate\Http\Request
         * @return array
         */
        public function toArray($request)
        {
            return [
                'project_id' => $this->project_id,
                'title' => $this->title,
                'amount' => $this->amount,
                // To access relationship attributes:
                'rewards' => $this->rewards->load('shippings'),
            ];
        }
    }
```

<p>Then in your controller, you just need to create a new Resource instance and pass the item object that you want to return:</p>

<pre class="lang-php prettyprint-override"><code>use App\Http\Resources\Project as ProjectResource;

// some code

    /**
     * Show a single formatted resource.
     *
     * @param Project $project
     * @return ProjectResource
     */
    public function show($project)
    {
        return new ProjectResource($project);
    }

// the rest of your code
</code>```

The output should be the expected.

Body:
i have this table structure, project has one to many relation with rewards , rewards and shipping has many to many relation with pivot table reward_ship.

projects       rewards         shipping       reward_ship
---------      --------        --------       ------------
id             id              id             id
title          amount          location       reward_id
amount         project_id      name           ship_id

i am trying to extract one particular project details with all other associate tables data(rewards and shipping data using reward_ship table) in one query.

These is how i am trying

Projects Model

    class Rewards extends Model {
         public function projs(){
              return $this->hasMany('App\Rewards');
          }
         public function rewds(){
              return $this->belongsToMany('App\Shipping')
              ->withPivot('reward_ship', 'ship_id', 'reward_id');
         }
         public function shiplc(){
               return $this->belongsToMany('App\Rewards')
               ->withPivot('reward_ship', 'ship_id', 'reward_id');
         }
      }
class Rewards extends Model {
    public function proj() {
        return $this->belongsTo('App\Projects');
    }
}

Controller api class

Route::get('projects/{id}', function($id) {
$p = Projects::find($id);
$getd = Rewards::with('proj')
    ->where('rewards.project_id', '=', $p->id)
    ->get();
 });

it doesn't work.
i search and tried many related model base query in larvel.
i know my implementation are wrong. Please suggest me to work out.

Body:
You can use Laravel 5.5 new feature API Resources.

It helps you to format the output of objects such as models or collections, to display attributes and also relationships.

So, you could do something like this in your ItemResource:

    <?php

    namespace App\Http\Resources;

    use Illuminate\Http\Resources\Json\Resource;

    class Project extends Resource
    {
        /**
         * Transform the resource into an array.
         *
         * @param  \Illuminate\Http\Request
         * @return array
         */
        public function toArray($request)
        {
            return [
                'project_id' => $this->project_id,
                'title' => $this->title,
                'amount' => $this->amount,
                // To access relationship attributes:
                'rewards' => $this->rewards->load('shippings'),
            ];
        }
    }

Then in your controller, you just need to create a new Resource instance and pass the item object that you want to return:

use App\Http\Resources\Project as ProjectResource;

// some code

    /**
     * Show a single formatted resource.
     *
     * @param Project $project
     * @return ProjectResource
     */
    public function show($project)
    {
        return new ProjectResource($project);
    }

// the rest of your code

The output should be the expected.


问:
How to show the diff specific to a named branch in mercurial
Assuming I have a named branch foo with two commits a, b:

```<code>      a       b       c
------o-------o-------o------- # default
       \          d         e
        ----------o---------o  # branch foo
</code>```

I want to see the diff between a and e (a not included). I could of course use the revision id, but that's not very practical. In git, one can just do git diff master..foo. How can I do the same in hg ?

答:
You can do it using revsets.

In your specific example I think you could get a list of of just d and e using:

```<code>hg log -r "branch('foo') - branch('default')"
</code>```

where that - is defined as:

```<code>"x - y"
      Changesets in x but not in y.
</code>```

Getting the diff from a to e could be done as:

```<code>hg diff -r "ancestor(default, foo)" -r foo
</code>```

though there's possibly a shorthand for that I'm not seeing.

Body:
Assuming I have a named branch foo with two commits a, b:

      a       b       c
------o-------o-------o------- # default
       \          d         e
        ----------o---------o  # branch foo

I want to see the diff between a and e (a not included). I could of course use the revision id, but that's not very practical. In git, one can just do git diff master..foo. How can I do the same in hg ?

Body:
You can do it using revsets.

In your specific example I think you could get a list of of just d and e using:

hg log -r "branch('foo') - branch('default')"

where that - is defined as:

"x - y"
      Changesets in x but not in y.

Getting the diff from a to e could be done as:

hg diff -r "ancestor(default, foo)" -r foo

though there's possibly a shorthand for that I'm not seeing.


答:
Project.php

```<code>class Project extends Model {
    public function rewards() {
        return this->hasMany(Reward::class, 'project_id', 'id');
    }
}
</code>```

Reward.php

```<code>class Reward extends Shipping {
    public function shipping(){
        return $this->belongsToMany(Shipping::class, 'reward_ship', 'reward_id', 'ship_id');
    }

    public function project(){
        return $this->belongsTo(Project::class);
    }
}
</code>```

You can retrieve it like this:

```<code>$projectDetails = Project::where('id', $projectId)
                             ->with(['rewards', 'rewards.shipping'])->get();
</code>```

Title: Laravel models to implement one to many and many to many in single query

Body:
Project.php

class Project extends Model {
    public function rewards() {
        return this->hasMany(Reward::class, 'project_id', 'id');
    }
}

Reward.php

class Reward extends Shipping {
    public function shipping(){
        return $this->belongsToMany(Shipping::class, 'reward_ship', 'reward_id', 'ship_id');
    }

    public function project(){
        return $this->belongsTo(Project::class);
    }
}

You can retrieve it like this:

$projectDetails = Project::where('id', $projectId)
                             ->with(['rewards', 'rewards.shipping'])->get();


问:
Having case multiple conditions in SQL Server 2014
I have a table 'FinancialTrans' where only 3 of those fields are needed.

```<code>AcctID  TransTypeCode   DateOfTrans  Field 4  Field 5  Field 6....
123     TOLL            2016-06-06
123     TOLL            2016-06-02
123     TOLL            2016-04-28
123     PYMT            2016-03-11
123     TOLL            2015-12-22
123     TOLL            2015-12-22
</code>```

What I need:

I only need account numbers where there are No Tolls AND No Pymt in the last 2 years.

My attempt at the code:

I know I need a Having clause but not quite sure how to write it.

Perhaps, a NOT Exist?

```<code>SELECT [AcctID]
      ,[TransTypeCode]
      ,[TransDate]

 FROM [FinancialTrans]

 WHERE (
        (TransTypeCode = 'TOLL' AND Max(TransDate) <= DATEADD(year, -2, GETDATE()))
     OR (TransTypeCode = 'PYMT' AND Max(TransDate) <= DATEADD(year, -2, GETDATE()))
       )

 GROUP BY AcctID, TransTypeCode, TransDate
</code>```

The challenge I'm facing is that I want account numbers where there is NEITHER a toll NOR a payment in the past two years.
I'm getting account numbers that have no tolls in the past two years but has a payment in the past two years.

Question: How do I ensure I get account numbers that doesn't have BOTH in the past two years?
This question is different from an earlier question asked because the requirements have now changed.

答:
You can use group by and having:

```<code>SELECT [AcctID]
FROM [FinancialTrans]
GROUP BY [AcctID]
HAVING MAX(CASE WHEN TransTypeCode = 'TOLL' THEN TransDate END) <= DATEADD(year, -2, GETDATE()) AND
       MAX(CASE WHEN TransTypeCode = 'PYMT' THEN TransDate END) <= DATEADD(year, -2, GETDATE()) ;
</code>```

That above actually requires that there be both types of transactions.  It might be better to do:

```<code>SELECT [AcctID]
FROM [FinancialTrans]
GROUP BY [AcctID]
HAVING SUM(CASE WHEN TransTypeCode IN ('TOLL', 'PYMT') AND TransDate > DATEADD(year, -2, GETDATE())
                THEN 1 ELSE 0
           END) = 0;
</code>```

Body:
I have a table 'FinancialTrans' where only 3 of those fields are needed.

AcctID  TransTypeCode   DateOfTrans  Field 4  Field 5  Field 6....
123     TOLL            2016-06-06
123     TOLL            2016-06-02
123     TOLL            2016-04-28
123     PYMT            2016-03-11
123     TOLL            2015-12-22
123     TOLL            2015-12-22

What I need:

I only need account numbers where there are No Tolls AND No Pymt in the last 2 years.

My attempt at the code:

I know I need a Having clause but not quite sure how to write it.

Perhaps, a NOT Exist?

SELECT [AcctID]
      ,[TransTypeCode]
      ,[TransDate]

 FROM [FinancialTrans]

 WHERE (
        (TransTypeCode = 'TOLL' AND Max(TransDate) <= DATEADD(year, -2, GETDATE()))
     OR (TransTypeCode = 'PYMT' AND Max(TransDate) <= DATEADD(year, -2, GETDATE()))
       )

 GROUP BY AcctID, TransTypeCode, TransDate

The challenge I'm facing is that I want account numbers where there is NEITHER a toll NOR a payment in the past two years.
I'm getting account numbers that have no tolls in the past two years but has a payment in the past two years.

Question: How do I ensure I get account numbers that doesn't have BOTH in the past two years?
This question is different from an earlier question asked because the requirements have now changed.

Body:
You can use group by and having:

SELECT [AcctID]
FROM [FinancialTrans]
GROUP BY [AcctID]
HAVING MAX(CASE WHEN TransTypeCode = 'TOLL' THEN TransDate END) <= DATEADD(year, -2, GETDATE()) AND
       MAX(CASE WHEN TransTypeCode = 'PYMT' THEN TransDate END) <= DATEADD(year, -2, GETDATE()) ;

That above actually requires that there be both types of transactions.  It might be better to do:

SELECT [AcctID]
FROM [FinancialTrans]
GROUP BY [AcctID]
HAVING SUM(CASE WHEN TransTypeCode IN ('TOLL', 'PYMT') AND TransDate > DATEADD(year, -2, GETDATE())
                THEN 1 ELSE 0
           END) = 0;


问:
RegisterBundles is losing Bootstrap after send project to IIS?
I'm creating an ASP.Net MVC project using VS2013 and I am using the Bootstrap to make the layout styles. I'm using the RegisterBundles to register my CSS and JS. The problem is while I'm developing the styles works very well, but, after compile and send the project to a IIS Server it stop to work and seems lose the styles. I don't know why it is happening.

Notice, using VS2013 I make start the project to test and it start using the IIS Express of VS2013 then it works very well, but after compile and send the project to IIS Server it stop to work.

I already have the Static Content role enabled on IIS, but it still doesn't works too.

How could I fix this problem ?

BundleConfig

```<code>public class BundleConfig{
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles){

            /************************* BOOTSTRAP ***********************************/
            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                                         "~/Scripts/bootstrap.js"));

            bundles.Add(new StyleBundle("~/Content/bootstrap").Include(
                                        "~/Content/bootstrap.css",
                                        "~/Content/bootstrap-theme.css"
                                        ));
            //********************************************************************/

            /******************************** DATETIME PICKER ********************/
            bundles.Add(new StyleBundle("~/Content/datetimepicker").Include(
                                        "~/Content/bootstrap-datetimepicker.css"
                                        ));
            //********************************************************************/

            /*************************** SELECT2 *********************************/
            bundles.Add(new StyleBundle("~/Content/select2").Include(
                                        "~/Content/select2-bootstrap.css",
                                        "~/Content/select2.css"
                                        ));
            /*******************************************************************/

            /*************************** Lightbox Image Gallery *********************************/
            bundles.Add(new StyleBundle("~/Content/lightbox").Include(
                                        "~/Content/lightbox.css"
                                        ));
            /*******************************************************************/

            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*",
                        "~/Scripts/CustomValidacoes.js"));

            bundles.Add(new ScriptBundle("~/bundles/Mascaras").Include(
                        "~/Scripts/Mascaras/jquery.mask.js",
                        "~/Scripts/Mascaras/Mascaras.js"));

            //Datetimepicker
            bundles.Add(new ScriptBundle("~/bundles/Datetimepicker").Include(
                        "~/Scripts/moment.js",
                        "~/Scripts/moment-with-locales.js",
                        "~/Scripts/moment_locale_pt-br.js",
                        "~/Scripts/bootstrap-datetimepicker.js"
                        ));

            //Lightbox
            bundles.Add(new ScriptBundle("~/bundles/Lightbox").Include(
                        "~/Scripts/lightbox.js"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

            bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                        "~/Content/themes/base/jquery.ui.core.css",
                        "~/Content/themes/base/jquery.ui.resizable.css",
                        "~/Content/themes/base/jquery.ui.selectable.css",
                        "~/Content/themes/base/jquery.ui.accordion.css",
                        "~/Content/themes/base/jquery.ui.autocomplete.css",
                        "~/Content/themes/base/jquery.ui.button.css",
                        "~/Content/themes/base/jquery.ui.dialog.css",
                        "~/Content/themes/base/jquery.ui.slider.css",
                        "~/Content/themes/base/jquery.ui.tabs.css",
                        "~/Content/themes/base/jquery.ui.datepicker.css",
                        "~/Content/themes/base/jquery.ui.progressbar.css",
                        "~/Content/themes/base/jquery.ui.theme.css"));

        }
    }
</code>```

Layout HTML

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - InvestimentosUSA.com</title>
    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/bootstrap")
    @Styles.Render("~/Content/CustomStyle.css")
    @Styles.Render("~/Content/datetimepicker")
    @Styles.Render("~/Content/select2")
    @Styles.Render("~/Content/lightbox")
    <script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyA8JZPv2N9bE0OQABj6hKO9QZb0kH32lHo"></script>

</head>
<body>
    <!--/layout pagina principal-->
    @Html.Partial("_Loading")
    @Html.Partial("_Header")
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                @RenderBody()
            </div>
        </div>
    </div>
    @Html.Partial("_Footer")

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/modernizr")

    @Scripts.Render("~/Scripts/PersistObjects/Usuarios/LoginUsuario.js")
    @RenderSection("scripts", required: false)
</body>
</html>
</code>```

答: I solved the problem. It was happening because I was compiling on Release and then I made compile on Debug and it finally it worked as I wanted. </p>

Body:
I'm creating an ASP.Net MVC project using VS2013 and I am using the Bootstrap to make the layout styles. I'm using the RegisterBundles to register my CSS and JS. The problem is while I'm developing the styles works very well, but, after compile and send the project to a IIS Server it stop to work and seems lose the styles. I don't know why it is happening.

Notice, using VS2013 I make start the project to test and it start using the IIS Express of VS2013 then it works very well, but after compile and send the project to IIS Server it stop to work.

I already have the Static Content role enabled on IIS, but it still doesn't works too.

How could I fix this problem ?

BundleConfig

public class BundleConfig{
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles){

            /************************* BOOTSTRAP ***********************************/
            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                                         "~/Scripts/bootstrap.js"));

            bundles.Add(new StyleBundle("~/Content/bootstrap").Include(
                                        "~/Content/bootstrap.css",
                                        "~/Content/bootstrap-theme.css"
                                        ));
            //********************************************************************/

            /******************************** DATETIME PICKER ********************/
            bundles.Add(new StyleBundle("~/Content/datetimepicker").Include(
                                        "~/Content/bootstrap-datetimepicker.css"
                                        ));
            //********************************************************************/

            /*************************** SELECT2 *********************************/
            bundles.Add(new StyleBundle("~/Content/select2").Include(
                                        "~/Content/select2-bootstrap.css",
                                        "~/Content/select2.css"
                                        ));
            /*******************************************************************/

            /*************************** Lightbox Image Gallery *********************************/
            bundles.Add(new StyleBundle("~/Content/lightbox").Include(
                                        "~/Content/lightbox.css"
                                        ));
            /*******************************************************************/

            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*",
                        "~/Scripts/CustomValidacoes.js"));

            bundles.Add(new ScriptBundle("~/bundles/Mascaras").Include(
                        "~/Scripts/Mascaras/jquery.mask.js",
                        "~/Scripts/Mascaras/Mascaras.js"));

            //Datetimepicker
            bundles.Add(new ScriptBundle("~/bundles/Datetimepicker").Include(
                        "~/Scripts/moment.js",
                        "~/Scripts/moment-with-locales.js",
                        "~/Scripts/moment_locale_pt-br.js",
                        "~/Scripts/bootstrap-datetimepicker.js"
                        ));

            //Lightbox
            bundles.Add(new ScriptBundle("~/bundles/Lightbox").Include(
                        "~/Scripts/lightbox.js"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

            bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                        "~/Content/themes/base/jquery.ui.core.css",
                        "~/Content/themes/base/jquery.ui.resizable.css",
                        "~/Content/themes/base/jquery.ui.selectable.css",
                        "~/Content/themes/base/jquery.ui.accordion.css",
                        "~/Content/themes/base/jquery.ui.autocomplete.css",
                        "~/Content/themes/base/jquery.ui.button.css",
                        "~/Content/themes/base/jquery.ui.dialog.css",
                        "~/Content/themes/base/jquery.ui.slider.css",
                        "~/Content/themes/base/jquery.ui.tabs.css",
                        "~/Content/themes/base/jquery.ui.datepicker.css",
                        "~/Content/themes/base/jquery.ui.progressbar.css",
                        "~/Content/themes/base/jquery.ui.theme.css"));

        }
    }

Layout HTML

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - InvestimentosUSA.com</title>
    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/bootstrap")
    @Styles.Render("~/Content/CustomStyle.css")
    @Styles.Render("~/Content/datetimepicker")
    @Styles.Render("~/Content/select2")
    @Styles.Render("~/Content/lightbox")

    @Html.Partial("_Loading")
    @Html.Partial("_Header")

                @RenderBody()

    @Html.Partial("_Footer")

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/modernizr")

    @Scripts.Render("~/Scripts/PersistObjects/Usuarios/LoginUsuario.js")
    @RenderSection("scripts", required: false)


问:
Having trouble with making embeded video responsive
I have made the video responsive, but as you can see when the browser is fully stretched, the width to height ratio is reversed. The iframe is narrow and tall, but when the browser is shrunk and the video goes underneath the text, the ratio corrects itself. How can I fix the ratio in the stretched browser? Here is my code.

.video-responsive {
  overflow: hidden;
  padding-bottom: 56.25%;
  position: relative;
  height: 0;
}

.video-responsive iframe {
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
  position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="section1">
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-6 section1Text">
        <h2 class="text-center">What We Have to Offer</h2>
        <p class="text-center">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel massa iaculis, posuere augue et, pharetra ipsum. Suspendisse metus ex, pellentesque id dolor in, vehicula varius tortor. Nam auctor ante nisi.</p>
      </div>
      <div class="video-responsive">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/bsY2GdBEvSA?showinfo=0" frameborder="0" allowfullscreen></iframe>
      </div>
    </div>
  </div>
</section></code>```

答:
I would like to know how to have the video placed besides the text on the right, in the same row.

You can achieve this using a display: flex; on your row class div. Then, setting the flex-direction to row.

How can I fix the ratio in the stretched browser?

EDIT:

To fill the container while keeping the dimensions of your iframe, use the display: flex property on the .video-responsive div and flex-basis: 100%; on the iframe:

.row {
  display: flex;
  flex-direction: row;
  background: hotpink;
}

.video-responsive {
  flex-basis: 50%;
  min-height: 100vh;
  display: flex;
  background: teal;
}

.video-responsive iframe {
  flex-basis: 100%;
}

.section1Text {
  flex-basis: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="section1">
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-6 section1Text">
        <h2 class="text-center">What We Have to Offer</h2>
        <p class="text-center">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel massa iaculis, posuere augue et, pharetra ipsum. Suspendisse metus ex, pellentesque id dolor in, vehicula varius tortor. Nam auctor ante nisi.</p>
      </div>
      <div class="video-responsive">
        <iframe src="https://www.youtube.com/embed/bsY2GdBEvSA?showinfo=0" frameborder="0" allowfullscreen></iframe>
      </div>
    </div>
  </div>
</section></code>```

note that I've removed the dimensions of the video in the HTML, not sure if that's useful or not...

Here is a full reference of CSS Flexbox.

Hope I got it right :)

Body:
I have made the video responsive, but as you can see when the browser is fully stretched, the width to height ratio is reversed. The iframe is narrow and tall, but when the browser is shrunk and the video goes underneath the text, the ratio corrects itself. How can I fix the ratio in the stretched browser? Here is my code.

.video-responsive {
  overflow: hidden;
  padding-bottom: 56.25%;
  position: relative;
  height: 0;
}

.video-responsive iframe {
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
  position: absolute;
}

What We Have to Offer

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel massa iaculis, posuere augue et, pharetra ipsum. Suspendisse metus ex, pellentesque id dolor in, vehicula varius tortor. Nam auctor ante nisi.

Body:
I would like to know how to have the video placed besides the text on the right, in the same row.

You can achieve this using a display: flex; on your row class div. Then, setting the flex-direction to row.

How can I fix the ratio in the stretched browser?

EDIT:

To fill the container while keeping the dimensions of your iframe, use the display: flex property on the .video-responsive div and flex-basis: 100%; on the iframe:

.row {
  display: flex;
  flex-direction: row;
  background: hotpink;
}

.video-responsive {
  flex-basis: 50%;
  min-height: 100vh;
  display: flex;
  background: teal;
}

.video-responsive iframe {
  flex-basis: 100%;
}

.section1Text {
  flex-basis: 50%;
}

<section class="section1">
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-6 section1Text">
        <h2 class="text-center">What We Have to Offer</h2>
        <p class="text-center">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel massa iaculis, posuere augue et, pharetra ipsum. Suspendisse metus ex, pellentesque id dolor in, vehicula varius tortor. Nam auctor ante nisi.</p>
      </div>
      <div class="video-responsive">
        <iframe src="https://www.youtube.com/embed/bsY2GdBEvSA?showinfo=0" frameborder="0" allowfullscreen></iframe>
      </div>
    </div>
  </div>
</section>

note that I've removed the dimensions of the video in the HTML, not sure if that's useful or not...

Here is a full reference of CSS Flexbox.

Hope I got it right :)


答:
You have to fix the relationships that you have :

Projects Model :

```<code>public function rewards(){
    return $this->hasMany('App\Rewards');
}
</code>```

Rewards Model :

```<code>public function projects() {
    return $this->belongsTo('App\Projects');
}

public function shippings(){
    return $this->belongsToMany('App\Shipping','reward_ship', 'reward_id', 'ship_id');
}
</code>```

Shipping model:

```<code>public function rewards(){
    return $this->belongsToMany('App\Rewards','reward_ship', 'ship_id', 'reward_id');
}
</code>```

After that you can call the relationships in the controller to eager load the wanted elements like this :

```<code>$project = Projects::with('rewards.shippings')
                    ->where('id', $project_id)
                    ->get();
</code>```

And in the view you can loop over the rewards then get the shippings like this :

```<code>@foreach ($project->rewards as $reward)
    <p>This is a reword {{ $reward->amount }}</p>
    @foreach ($reward->shippings as $shipping)
        <p>This is a shipping {{ $shipping->name }}</p>
    @endforeach
@endforeach
</code>```

Body:
You have to fix the relationships that you have :

Projects Model :

public function rewards(){
    return $this->hasMany('App\Rewards');
}

Rewards Model :

public function projects() {
    return $this->belongsTo('App\Projects');
}

public function shippings(){
    return $this->belongsToMany('App\Shipping','reward_ship', 'reward_id', 'ship_id');
}

Shipping model:

public function rewards(){
    return $this->belongsToMany('App\Rewards','reward_ship', 'ship_id', 'reward_id');
}

After that you can call the relationships in the controller to eager load the wanted elements like this :

$project = Projects::with('rewards.shippings')
                    ->where('id', $project_id)
                    ->get();

And in the view you can loop over the rewards then get the shippings like this :

@foreach ($project->rewards as $reward)
    <p>This is a reword {{ $reward->amount }}</p>
    @foreach ($reward->shippings as $shipping)
        <p>This is a shipping {{ $shipping->name }}</p>
    @endforeach
@endforeach


问:
Putting together Geolocation and Places search in Google Maps
I have been trying to put together two of the functionalities the GoogleMaps API offers for developers(Places Search and Geolocation)

Since I'm not very familiar with javascript, I'm not positive what could be the mistake I'm making. So far, the Places Search is totally functional (with a predetermined location) but not so the Geolocation (which should overwrite the predetermined location with the user's location).

Here you can take a look at my code.

```<code><!DOCTYPE html>
<html>
<head>
    <title>Place searches</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

    <style>
        #map {
            height: 580px;
            width: 680px;
            border: 10px solid darkred;
            padding: 5px;
            margin: 25px;
        }

        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }

    </style>
    <script>
        // This example requires the Places library. Include the libraries=places
        // parameter when you first load the API. For example:
        // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

        var map;
        var infowindow;

        function initMap() {
            var pyrmont = {lat:43.364490, lng:-8.407406};

            map = new google.maps.Map(document.getElementById('map'), {
                center: pyrmont,
                zoom: 15
            });

            infowindow = new google.maps.InfoWindow({map:map});
            var service = new google.maps.places.PlacesService(map);
            service.nearbySearch({
                location: pyrmont,
                radius: 2000,
                type: ['gym']
            }, callback);

            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    var pos = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude
                    };

                    infoWindow.setPosition(pos);
                    infoWindow.setContent('Location found.');
                    map.setCenter(pos);
                }, function() {
                    handleLocationError(true, infoWindow, map.getCenter());
                });
            } else {
                // Browser doesn't support Geolocation
                handleLocationError(false, infoWindow, map.getCenter());
            }
        }

        function handleLocationError(browserHasGeolocation, infoWindow, pos) {
            infoWindow.setPosition(pos);
            infoWindow.setContent(browserHasGeolocation ?
                'Error: The Geolocation service failed.' :
                'Error: Your browser doesn\'t support geolocation.');

        }

        function callback(results, status) {
            if (status === google.maps.places.PlacesServiceStatus.OK) {
                for (var i = 0; i < results.length; i++) {
                    createMarker(results[i]);
                }
            }
        }

        function createMarker(place) {
            var placeLoc = place.geometry.location;
            var marker = new google.maps.Marker({
                map: map,
                position: place.geometry.location
            });

            google.maps.event.addListener(marker, 'click', function() {
                infowindow.setContent(place.name);
                infowindow.open(map, this);
            });
        }
    </script>
</head>
<body>
<header>
    <h1>Encuentra tu gimnasio más próximo</h1>
</header>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=***MY_KEY***&libraries=places,geometry&callback=initMap" async defer></script>
</body>
</html>
</code>```

Any help would be very much appreciated.

答:
There seems te be an error with the casing of the infoWindow variable.

It's declared like this:

```<code>var infowindow;
</code>```

But in the callback for navigator.geolocation.getCurrentPosition is used with different casing:

```<code>infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
</code>```

This error should have been shown in the browser's development tools console.

Body:
I have been trying to put together two of the functionalities the GoogleMaps API offers for developers(Places Search and Geolocation)

Since I'm not very familiar with javascript, I'm not positive what could be the mistake I'm making. So far, the Places Search is totally functional (with a predetermined location) but not so the Geolocation (which should overwrite the predetermined location with the user's location).

Here you can take a look at my code.

<!DOCTYPE html>

    <title>Place searches</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

Encuentra tu gimnasio más próximo

Any help would be very much appreciated.

Body:
There seems te be an error with the casing of the infoWindow variable.

It's declared like this:

var infowindow;

But in the callback for navigator.geolocation.getCurrentPosition is used with different casing:

infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');

This error should have been shown in the browser's development tools console.


问:
Making a string concatenation operator in R
I was wondering how one might go about writing a string concatenation operator in R, something like || in SAS, + in Java/C# or & in Visual Basic.

The easiest way would be to create a special operator using %, like

```<code>`%+%` <- function(a, b) paste(a, b, sep="")
</code>```

but this leads to lots of ugly %'s in the code.

I noticed that + is defined in the Ops group, and you can write S4 methods for that group, so perhaps something like that would be the way to go. However, I have no experience with S4 language features at all. How would I modify the above function to use S4?

答:
You can also use S3 classes for this:</p>

```<code>String <- function(x) {
  class(x) <- c("String", class(x))
  x
}

"+.String" <- function(x,...) {
  x <- paste(x, paste(..., sep="", collapse=""), sep="", collapse="")
  String(x)
}

print.String <- function(x, ...) cat(x)

x <- "The quick brown "
y <- "fox jumped over "
z <- "the lazy dog"

String(x) + y + z
</code>```

Body:
I was wondering how one might go about writing a string concatenation operator in R, something like || in SAS, + in Java/C# or & in Visual Basic.

The easiest way would be to create a special operator using %, like

`%+%` <- function(a, b) paste(a, b, sep="")

but this leads to lots of ugly %'s in the code.

I noticed that + is defined in the Ops group, and you can write S4 methods for that group, so perhaps something like that would be the way to go. However, I have no experience with S4 language features at all. How would I modify the above function to use S4?

Body:
You can also use S3 classes for this:

String <- function(x) {
  class(x) <- c("String", class(x))
  x
}

"+.String" <- function(x,...) {
  x <- paste(x, paste(..., sep="", collapse=""), sep="", collapse="")
  String(x)
}

print.String <- function(x, ...) cat(x)

x <- "The quick brown "
y <- "fox jumped over "
z <- "the lazy dog"

String(x) + y + z


问:
Mockito inOrder.verify() fails - "Wanted but not invoked ... wanted anywhere AFTER following interaction"
I've been given a bunch of tests to develop a simple game and I've reached a point where Mockito's InOrder.verify() produces the error.

Verification in order failure. Wanted but not invoked: jumpListener.jumpPerformed( ... ) at line x. Wanted anywhere AFTER the following interaction: walkListener.walkPerformed( ... ) at line y.

The code I got looks similar to what is seen below where the relevant functions performWalk(int x) and performJump(int y) both contains other function calls in if / else logic, before and after walkListeners.get(0).walkPerformed(x); and jumpListeners.get(0).jumpPerformed(y);. I've never heard about Mockito until reaching this part and most questions seems to be asked by those producing the tests, not using them. So my question is, what exactly does inOrder.verify() require of the function calls?

```<code>order.verify(walkListener).walkPerformed(5);
order.verify(jumpListener).jumpPerformed(2);
</code>```

Can there be other function calls going off between these two statements, say a boolean function checking the argument value interval?

```<code>public interface WalkListener extends EventListener {
    public void walkPerformed(int x);
}

public interface JumpListener extends EventListener {
    public void jumpPerformed(int y);
}

public class Game {
    private Vector<WalkListener> walkListeners;
    private Vector<JumpListener> jumpListeners;

    public void addWalkListener(WalkListener listener) { ... }
    public void addJumpListener(JumpListener listener) { ... }

    public void performWalk(int x) {
        ...
        walkListeners.get(0).walkPerformed(x);
        ...
    }
    public void performJump(int y) {
        ...
        jumpListeners.get(0).jumpPerformed(y);
        ...
    }

    private class Walk implements WalkListener { ... }
    private class Jump implements JumpListener { ... }
}

public class GameTest {
    @Test
    public void finalTest() {
        Game game = new Game();
        WalkListener walkListener = mock(WalkListener.class)
        JumpListener jumpListener = mock(JumpListener.class)

        game.addWalkListener(walkListener);
        game.addJumpListener(jumpListener);

        game.performWalk(5);
        game.performJump(2);

        InOrder order = inOrder(walkListener, jumpListener);
        order.verify(walkListener).walkPerformed(5);
        order.verify(jumpListener).jumpPerformed(2);
    }
}
</code>```

答:
So this is the relevant bit:

```<code>InOrder order = inOrder(walkListener, jumpListener);
order.verify(walkListener).walkPerformed(5);
order.verify(jumpListener).jumpPerformed(2);
</code>```

It verifies that

jumpListener is called after walkListener (the case you're failing, since you apparently don't call jumpListener at all),

walkListener.walkPerformed() is called with argument 5 and

jumpListener.jumpPerformed() is called with argument 2

Can there be other function calls going off between these two statements, say a boolean function checking the argument value interval?

Sure.

See example:

```<code>class Foo {
    public void foo() {}
    public void bar() {}
    public void baz() {}
}

@Test
public void testFoo() {

    Foo mock = mock(Foo.class);
    mock.foo(); //1st
    mock.bar(); //2nd
    mock.baz(); //3rd

    InOrder inOrder = inOrder(mock);

    inOrder.verify(mock).foo(); //1st
    inOrder.verify(mock).baz(); //3rd (last method)

    //passes because there are no more interactions after last method:
    inOrder.verifyNoMoreInteractions();

}
</code>```

Test passes, as after baz() call there were no more method calls. It doesn't matter that bar() call was in between as that was not part of verification.

Same is the case with two classes:

```<code>class Foo {
    public void foo() {}
    public void bar() {}
}

class Bar {
    public void foo() {}
}

@Test
public void testFoo() {

    Foo mock = mock(Foo.class);
    Bar mock2 = mock(Bar.class);
    mock.foo(); //1st
    mock.bar(); //2nd
    mock2.foo(); //3rd

    InOrder inOrder = inOrder(mock, mock2);

    inOrder.verify(mock).foo(); //1st
    inOrder.verify(mock2).foo(); //3rd (last method)

    //passes because there are no more interactions after last method:
    inOrder.verifyNoMoreInteractions();
}
</code>```

Test again passes, as the second method call was not part of verification.

If you'd have wanted the test to fail on non-specified methods calls, you'd need to add for example Mockito.verifyNoMoreInteractions(mock); at the end of the test.

Body:
I've been given a bunch of tests to develop a simple game and I've reached a point where Mockito's InOrder.verify() produces the error.

Verification in order failure. Wanted but not invoked: jumpListener.jumpPerformed( ... ) at line x. Wanted anywhere AFTER the following interaction: walkListener.walkPerformed( ... ) at line y.

The code I got looks similar to what is seen below where the relevant functions performWalk(int x) and performJump(int y) both contains other function calls in if / else logic, before and after walkListeners.get(0).walkPerformed(x); and jumpListeners.get(0).jumpPerformed(y);. I've never heard about Mockito until reaching this part and most questions seems to be asked by those producing the tests, not using them. So my question is, what exactly does inOrder.verify() require of the function calls?

order.verify(walkListener).walkPerformed(5);
order.verify(jumpListener).jumpPerformed(2);

Can there be other function calls going off between these two statements, say a boolean function checking the argument value interval?

public interface WalkListener extends EventListener {
    public void walkPerformed(int x);
}

public interface JumpListener extends EventListener {
    public void jumpPerformed(int y);
}

public class Game {
    private Vector<WalkListener> walkListeners;
    private Vector<JumpListener> jumpListeners;

    public void addWalkListener(WalkListener listener) { ... }
    public void addJumpListener(JumpListener listener) { ... }

    public void performWalk(int x) {
        ...
        walkListeners.get(0).walkPerformed(x);
        ...
    }
    public void performJump(int y) {
        ...
        jumpListeners.get(0).jumpPerformed(y);
        ...
    }

    private class Walk implements WalkListener { ... }
    private class Jump implements JumpListener { ... }
}

public class GameTest {
    @Test
    public void finalTest() {
        Game game = new Game();
        WalkListener walkListener = mock(WalkListener.class)
        JumpListener jumpListener = mock(JumpListener.class)

        game.addWalkListener(walkListener);
        game.addJumpListener(jumpListener);

        game.performWalk(5);
        game.performJump(2);

        InOrder order = inOrder(walkListener, jumpListener);
        order.verify(walkListener).walkPerformed(5);
        order.verify(jumpListener).jumpPerformed(2);
    }
}

Body:
So this is the relevant bit:

InOrder order = inOrder(walkListener, jumpListener);
order.verify(walkListener).walkPerformed(5);
order.verify(jumpListener).jumpPerformed(2);

It verifies that

jumpListener is called after walkListener (the case you're failing, since you apparently don't call jumpListener at all),

walkListener.walkPerformed() is called with argument 5 and

jumpListener.jumpPerformed() is called with argument 2

Can there be other function calls going off between these two statements, say a boolean function checking the argument value interval?

Sure.

See example:

class Foo {
    public void foo() {}
    public void bar() {}
    public void baz() {}
}

@Test
public void testFoo() {

    Foo mock = mock(Foo.class);
    mock.foo(); //1st
    mock.bar(); //2nd
    mock.baz(); //3rd

    InOrder inOrder = inOrder(mock);

    inOrder.verify(mock).foo(); //1st
    inOrder.verify(mock).baz(); //3rd (last method)

    //passes because there are no more interactions after last method:
    inOrder.verifyNoMoreInteractions();

}

Test passes, as after baz() call there were no more method calls. It doesn't matter that bar() call was in between as that was not part of verification.

Same is the case with two classes:

class Foo {
    public void foo() {}
    public void bar() {}
}

class Bar {
    public void foo() {}
}

@Test
public void testFoo() {

    Foo mock = mock(Foo.class);
    Bar mock2 = mock(Bar.class);
    mock.foo(); //1st
    mock.bar(); //2nd
    mock2.foo(); //3rd

    InOrder inOrder = inOrder(mock, mock2);

    inOrder.verify(mock).foo(); //1st
    inOrder.verify(mock2).foo(); //3rd (last method)

    //passes because there are no more interactions after last method:
    inOrder.verifyNoMoreInteractions();
}

Test again passes, as the second method call was not part of verification.

If you'd have wanted the test to fail on non-specified methods calls, you'd need to add for example Mockito.verifyNoMoreInteractions(mock); at the end of the test.


问:
Flask Running Issue: socket.error: [Errno 98] Address already in use
I got this error message sublime issue(My OS: Ubuntu 16.04) "socket.error: [Errno 98] Address already in use" If I run flask in sublime text or PyCharm. But if I run flask on my Ubuntu terminal,it is running. I understood that port used another service. Then i was trying to solve this issue from google/stackoverflow.

# ps ax | grep 5000     // or # ps ax | grep name_of_service

```<code># kill 3750            // or # killall name_of_service
</code>```

But nothing changed. Only i found this problem when i was trying to run on sublime or pycharm IDE.

答:
Simple way is to use fuser.

```<code>fuser <yourport>/tcp #this will fetch the process/service
</code>```

Replace <yourport> with the port you want to use

```<code>#to kill the process using <yourport> add `-k` argument
fuser <yourport>/tcp -k
</code>```

In your case

```<code>fuser 5000/tcp -k
</code>```

Now you can run flask with that port.

Body:
I got this error message sublime issue(My OS: Ubuntu 16.04) "socket.error: [Errno 98] Address already in use" If I run flask in sublime text or PyCharm. But if I run flask on my Ubuntu terminal,it is running. I understood that port used another service. Then i was trying to solve this issue from google/stackoverflow.

# ps ax | grep 5000     // or # ps ax | grep name_of_service

# kill 3750            // or # killall name_of_service

But nothing changed. Only i found this problem when i was trying to run on sublime or pycharm IDE.

Body:
Simple way is to use fuser.

fuser <yourport>/tcp #this will fetch the process/service

Replace <yourport> with the port you want to use

#to kill the process using <yourport> add `-k` argument
fuser <yourport>/tcp -k

In your case

fuser 5000/tcp -k

Now you can run flask with that port.


问:
Facebook Ads API Error - Not enabled for usage
So I have been trying to create an app that uses the Facebook Ads API to get ad costs and stats. I have created an app and added my ad account ids to the app settings but still get the error:

```<code>"error":{"message":"(#274) The ad account is not enabled for usage in Ads API. Please add it in developer.facebook.com -> application -> settings -> advanced -> advertising accounts -> Ads API. Account XXXXXXXXXXXXX not enabled for application XXXXXXXXXXXXX.","type":"OAuthException","code":274}}
</code>```

Any idear why it would still be giving me this error? Or how I can get through this step.

答:
I was getting this #274 error and it started working after adding the Test Sandbox Ad Account's ID (under Marketing API > Tools) to the Ads API Account Configuration (under Settings > Advanced > Advertising Accounts).  Prior to adding the Test Sandbox Ad Account's ID, I had only added my production Ad Account's ID, which didn't work for some reason.

Also when I was making test Graph API calls using Graph API Explorer, there's the Application select box in the top right.  For some reason it was defaulting to "Graph API Explorer" instead of the name of my application.  Whenever I selected the name of my application and generated a new user access token, I was able to make requests similar to the following:

```<code>//Get the Ad name associated with an AD_ID
https://graph.facebook.com/<API_VERSION>/<AD_ID>?fields=adset_id,campaign_id,name,account_id

//Get the Adset name associated with an ADSET_ID
https://graph.facebook.com/<API_VERSION>/<ADSET_ID>?fields=account_id,name

//Get the Campaign name associated with a CAMPAIGN_ID
https://graph.facebook.com/<API_VERSION>/<CAMPAIGN_ID>?fields=account_id,name
</code>```

Body:
So I have been trying to create an app that uses the Facebook Ads API to get ad costs and stats. I have created an app and added my ad account ids to the app settings but still get the error:

"error":{"message":"(#274) The ad account is not enabled for usage in Ads API. Please add it in developer.facebook.com -> application -> settings -> advanced -> advertising accounts -> Ads API. Account XXXXXXXXXXXXX not enabled for application XXXXXXXXXXXXX.","type":"OAuthException","code":274}}

Any idear why it would still be giving me this error? Or how I can get through this step.

Body:
I was getting this #274 error and it started working after adding the Test Sandbox Ad Account's ID (under Marketing API > Tools) to the Ads API Account Configuration (under Settings > Advanced > Advertising Accounts).  Prior to adding the Test Sandbox Ad Account's ID, I had only added my production Ad Account's ID, which didn't work for some reason.

Also when I was making test Graph API calls using Graph API Explorer, there's the Application select box in the top right.  For some reason it was defaulting to "Graph API Explorer" instead of the name of my application.  Whenever I selected the name of my application and generated a new user access token, I was able to make requests similar to the following:

//Get the Ad name associated with an AD_ID
https://graph.facebook.com/<API_VERSION>/<AD_ID>?fields=adset_id,campaign_id,name,account_id

//Get the Adset name associated with an ADSET_ID
https://graph.facebook.com/<API_VERSION>/<ADSET_ID>?fields=account_id,name

//Get the Campaign name associated with a CAMPAIGN_ID
https://graph.facebook.com/<API_VERSION>/<CAMPAIGN_ID>?fields=account_id,name


问:
Query / Filter Azure Search Edm.Collection by any of multiple strings
I'm trying to filter an azure search edm.collection to return results if any of multiple strings are in the collection.  I can only get it working when querying for one item, which isn't good enough for my use case.  I can't find syntax for querying multiple parameters.

```<code>filter += "FirmTypes / any (x: x eq 'Big 4')";
</code>```

the above works and returns all of the documents where firm type is Big 4.

I've tried multiple ways (some below) to filter for more than one parameter with no success

```<code>//filter += " OR any (x: x eq 'Industry')";
//filter += "FirmTypes / any (x: x eq 'Industry')";
//filter += "FirmTypes / any (x: x eq 'Big 4', 'Industry', 'PLC')"
//filter += "FirmTypes / any (x: x eq 'Big 4' or 'Industry' or 'PLC')"
//filter += "FirmTypes / any (x: x eq 'Big 4') or (x: x eq 'Industry')"
//filter += "FirmTypes / any (x: x eq 'Big 4')|(x: x eq 'Industry')"
</code>```

Can anybody kindly point me in the right direction?  Thank you in advance.

答:
Got it as soon as I posted.  If anybody else has same issue </p>

```<code>"FirmTypes / any (x: x eq 'Big 4') or FirmTypes / any (x: x eq 'Industry')"
</code>```

Body:
I'm trying to filter an azure search edm.collection to return results if any of multiple strings are in the collection.  I can only get it working when querying for one item, which isn't good enough for my use case.  I can't find syntax for querying multiple parameters.

filter += "FirmTypes / any (x: x eq 'Big 4')";

the above works and returns all of the documents where firm type is Big 4.

I've tried multiple ways (some below) to filter for more than one parameter with no success

//filter += " OR any (x: x eq 'Industry')";
//filter += "FirmTypes / any (x: x eq 'Industry')";
//filter += "FirmTypes / any (x: x eq 'Big 4', 'Industry', 'PLC')"
//filter += "FirmTypes / any (x: x eq 'Big 4' or 'Industry' or 'PLC')"
//filter += "FirmTypes / any (x: x eq 'Big 4') or (x: x eq 'Industry')"
//filter += "FirmTypes / any (x: x eq 'Big 4')|(x: x eq 'Industry')"

Can anybody kindly point me in the right direction?  Thank you in advance.

Body:
Got it as soon as I posted.  If anybody else has same issue

"FirmTypes / any (x: x eq 'Big 4') or FirmTypes / any (x: x eq 'Industry')"