问:
Haskell preprocessor - pound sign with curly braces
Browsing sources of Haskell SDL bindings, I've stumbled upon the following piece:

```<code>#include "SDL/SDl.h"

fromAudioFormat AudioS8 = #{const AUDIO_S8}
</code>```

What does #{const AUDIO_S8} part actually do? At a glance, it extracts a symbol from SDL.h, but I'd like to know exactly what it does and how to construct similar things. I'm particularly curious about const modifier.

答:
That's hsc2hs syntax. The const directive says "output the literal numeric value of this C expression into the generated .hs file". # just invokes the preprocessor. The curly braces are optional - hsc2hs just reads to the end of the line if you omit the braces, so you could just as easily write

```<code>fromAudioFormat AudioS8 = #const AUDIO_S8
</code>```

For more on the specific preprocessor directives see the docs.

Body:
Browsing sources of Haskell SDL bindings, I've stumbled upon the following piece:

#include "SDL/SDl.h"

fromAudioFormat AudioS8 = #{const AUDIO_S8}

What does #{const AUDIO_S8} part actually do? At a glance, it extracts a symbol from SDL.h, but I'd like to know exactly what it does and how to construct similar things. I'm particularly curious about const modifier.

Body:
That's hsc2hs syntax. The const directive says "output the literal numeric value of this C expression into the generated .hs file". # just invokes the preprocessor. The curly braces are optional - hsc2hs just reads to the end of the line if you omit the braces, so you could just as easily write

fromAudioFormat AudioS8 = #const AUDIO_S8

For more on the specific preprocessor directives see the docs.


来源: stackexchange

问:
htaccess rewrite trouble with "fake" folder
Before I ask my question, let me start off by saying that I have a working htaccess rule that is:

```<code>#1.
RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /good/$1 [L,R=301]
</code>```

and, like I said, this works well.

But, when I try to do this:

```<code>#2.
RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /funfolder/good/$1 [L,R=301]
</code>```

this doesn't work anymore.

So here comes my question.

If I want to rewrite the following:

```<code>#3.
http://www.mydomain/funfolder/folder2/sheet to
http://www.mydomain/funfolder/fakefolder3/sheet
</code>```

when I write:

```<code>#4.
RewriteRule ^funfolder/folder2/sheet$ /funfolder/fakefolder3/sheet?&%{QUERY_STRING}
</code>```

or

```<code>#5.
RewriteCond %{THE_REQUEST} ^GET\ /funfolder/folder2/
RewriteRule ^funfolder/folder2/(.*) /funfolder/fakefolder3/$1 [L,R=301]
</code>```

it is not working.  I do not see the content i want to see.

If I

```<code>#6.
Redirect 301 /funfolder/folder2  http://www.mydomain/funfolder/fakefolder3
</code>```

The redirect works but not the content.

I don't know if it helps but funfolder isn't a real folder.  Neither are folder2 or fakefolder3.  The CMS (joomla), however, generates the folder2 and funfolder.  but I want to add the fakefolder3.

I also though of moving the order of the above rules since there are other rewrite rules.  But, it did not produce any difference.

what I don't understand, is why the #1 works and the #2 doesn't.  I'm thinking that if I can understand the reason, it might also give me the answer to how to do #3. with a slithly altered #4 or altered a #5

Then I can always add a #6 if I need to.

this make any sence?  anyone know why I can't get #2 to work (and thus, my real problem), how to get #3 to work trough #4 or #5?

答:
Use the power of RedirectMatch! So your redirect will be:

```<code>RedirectMatch 301 /funfolder/folder2/(.*) /funfolder/fakefolder3/$1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Before I ask my question, let me start off by saying that I have a working htaccess rule that is:

#1.
RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /good/$1 [L,R=301]

and, like I said, this works well.

But, when I try to do this:

#2.
RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /funfolder/good/$1 [L,R=301]

this doesn't work anymore.

So here comes my question.

If I want to rewrite the following:

#3.
http://www.mydomain/funfolder/folder2/sheet to
http://www.mydomain/funfolder/fakefolder3/sheet

when I write:

#4.
RewriteRule ^funfolder/folder2/sheet$ /funfolder/fakefolder3/sheet?&%{QUERY_STRING}

or

#5.
RewriteCond %{THE_REQUEST} ^GET\ /funfolder/folder2/
RewriteRule ^funfolder/folder2/(.*) /funfolder/fakefolder3/$1 [L,R=301]

it is not working.  I do not see the content i want to see.

If I

#6.
Redirect 301 /funfolder/folder2  http://www.mydomain/funfolder/fakefolder3

The redirect works but not the content.

I don't know if it helps but funfolder isn't a real folder.  Neither are folder2 or fakefolder3.  The CMS (joomla), however, generates the folder2 and funfolder.  but I want to add the fakefolder3.

I also though of moving the order of the above rules since there are other rewrite rules.  But, it did not produce any difference.

what I don't understand, is why the #1 works and the #2 doesn't.  I'm thinking that if I can understand the reason, it might also give me the answer to how to do #3. with a slithly altered #4 or altered a #5

Then I can always add a #6 if I need to.

this make any sence?  anyone know why I can't get #2 to work (and thus, my real problem), how to get #3 to work trough #4 or #5?

Body:
Use the power of RedirectMatch! So your redirect will be:

RedirectMatch 301 /funfolder/folder2/(.*) /funfolder/fakefolder3/$1

ContentLicense: CC BY-SA 3.0


问:
Hibernate 'Inverse' in mapping file
Can someone explain the use of inverse in the xml mapping file, I am reading the tutorial but failing to understand its use in the mapping file??

Thanks

答:
In many-to-many relationships, you follow the direction of your join.

Let's have an example :

Student(IdStudent, StudentName)

Course(IdCourse, CourseName)

A student can follow one or many courses, so we'll have a joint table between Student and Course, named StudentCourse(IdStudent,IdCourse).

The inverse attribute needs to be positionned on the Course half, because it will indicate to Hibernate (which doesn't know much about the StudentCourse table) to correctly build its queries.

If you put the inverse attribute to true on the Student half, Hibernate will think that the Joint Table is CourseStudent(IdCourse,IdStudent) !!

It's the same behaviour for the one-to-many relationsships.

ContentLicense: CC BY-SA 2.5

Title: Hibernate 'Inverse' in mapping file


问:
Moving from a moved-from object
Consider the following code.

```<code>using T = std::string;

void rotate_left(std::vector<T>& v) {
    T temp = std::move(v[0]);
    for (size_t i=0; i+1 < v.size(); ++i) {
        v[i] = std::move(v[i+1]);
    }
    v.back() = std::move(temp);
}

int main()
{
    std::vector<T> v(3);  // a vector of three Ts
    T x = std::move(v[1]);  // move-from the second element
    rotate_left(v);
    // Can we now say that v[0] is in a moved-from state, or did we
    // get undefined behavior when we moved from v[1] a second time?
}
</code>```

The rotate_left function is just really simply shifting everything in the vector down by one position (and then putting the first element onto the end).  My question is, does this function have defined behavior when one of the elements in the vector is in a "moved-from state"?

This is related but not quite the same as "self-move". In this case, we're moving from one moved-from object into another moved-from object, and my question is whether we can rely on this leaving both objects still in some moved-from state, or whether "assignment-from" is one of those operations that "has a precondition" and therefore can't be used on arbitrary moved-from objects.

I'm well aware that

this is perfectly fine for sane library types such as unique_ptr

this will be perfectly fine for my own user-defined types if I define them sanely

this will be problematic for my own user-defined types if I define them insanely

this is perfectly fine for all the library types I've tried on libstdc++ and libc++

So what I'm really looking for is either:

concrete wording from the Standard proving that this must be perfectly fine for all STL types going forward, or

a concrete example of an STL or Boost type "in the wild" where this code is definitely problematic

I infer from this bug that _GLIBCXX_DEBUG checks for self-move, but I can confirm that it does not check for move-from-moved; is this because they consider move-from-moved to be safe and legal, or just because nobody wrote the code to check for it yet?

答:
Your program's behavior is well-defined, but unspecified.  The difference is that v has a valid state, you just don't know what that state is without inspecting it.

This corner of the standard has been controversial, and the wording has been difficult to get right.  But I believe the latest wording (C++17) is our best attempt so far, so I will quote from that (N4660).

Disclaimer, I actually linked to N4659 as N4660 is not publicly available.  The difference is inconsequential.

From 20.5.5.15 Moved-from state of library types [lib.types.movedfrom]

1 Objects of types defined in the C++ standard library may be moved from (15.8). Move operations may be explicitly specified or implicitly generated. Unless otherwise specified, such moved-from objects shall be placed in a valid but unspecified state.

This paragraph is a blanket statement for all types defined by the std::lib that moved-from objects are not "poison", you just don't know value they have.

Furthermore, each algorithm (including member functions) defined in the standard may have a list of preconditions that must be true prior to calling that algorithm.  If there are no preconditions listed, that means that you can always call that function.

Move assignment for all types defined in the std::lib never have any preconditions listed for the left or right hand side arguments.

It is hard to quote something that doesn't exist, but that is the way this specification works.

Generalizing further, the following section refers to all types (i.e. user-supplied) that are used with the std::lib:

20.5.3.1 Template argument requirements [utility.arg.requirements]

Table 23 — MoveConstructible requirements [moveconstructible]

```<code>T u = rv;
T(rv);
</code>```

rv's state is unspecified in the post-condition.

Table 25 — MoveAssignable requirements [moveassignable]

```<code>t = rv
</code>```

Only if t and rv do not refer to the same object, t is equivalent to the value of rv before the assignment.

Afterwards, rv's state is unspecified (whether or not t and rv refer to the same object).

Furthermore this sections notes (notes are non-normative and often the normative text appears elsewhere) that rv must still meet the requirements of the library component (algorithm) it is being used with, even though it has been moved from.

For example, std::sort is allowed to move from a value x, and then use that x in a comparison expression.  x must be LessThanComparable, whether or not x is moved-from.  Only x's value is unspecified.

```<code>bool b = x < x;  // b must be false, no matter what!
</code>```

Title: Moving from a moved-from object

Body:
Consider the following code.

using T = std::string;

void rotate_left(std::vector<T>& v) {
    T temp = std::move(v[0]);
    for (size_t i=0; i+1 < v.size(); ++i) {
        v[i] = std::move(v[i+1]);
    }
    v.back() = std::move(temp);
}

int main()
{
    std::vector<T> v(3);  // a vector of three Ts
    T x = std::move(v[1]);  // move-from the second element
    rotate_left(v);
    // Can we now say that v[0] is in a moved-from state, or did we
    // get undefined behavior when we moved from v[1] a second time?
}

The rotate_left function is just really simply shifting everything in the vector down by one position (and then putting the first element onto the end).  My question is, does this function have defined behavior when one of the elements in the vector is in a "moved-from state"?

This is related but not quite the same as "self-move". In this case, we're moving from one moved-from object into another moved-from object, and my question is whether we can rely on this leaving both objects still in some moved-from state, or whether "assignment-from" is one of those operations that "has a precondition" and therefore can't be used on arbitrary moved-from objects.

I'm well aware that

this is perfectly fine for sane library types such as unique_ptr

this will be perfectly fine for my own user-defined types if I define them sanely

this will be problematic for my own user-defined types if I define them insanely

this is perfectly fine for all the library types I've tried on libstdc++ and libc++

So what I'm really looking for is either:

concrete wording from the Standard proving that this must be perfectly fine for all STL types going forward, or

a concrete example of an STL or Boost type "in the wild" where this code is definitely problematic

I infer from this bug that _GLIBCXX_DEBUG checks for self-move, but I can confirm that it does not check for move-from-moved; is this because they consider move-from-moved to be safe and legal, or just because nobody wrote the code to check for it yet?

Body:
Your program's behavior is well-defined, but unspecified.  The difference is that v has a valid state, you just don't know what that state is without inspecting it.

This corner of the standard has been controversial, and the wording has been difficult to get right.  But I believe the latest wording (C++17) is our best attempt so far, so I will quote from that (N4660).

Disclaimer, I actually linked to N4659 as N4660 is not publicly available.  The difference is inconsequential.

From 20.5.5.15 Moved-from state of library types [lib.types.movedfrom]

1 Objects of types defined in the C++ standard library may be moved from (15.8). Move operations may be explicitly specified or implicitly generated. Unless otherwise specified, such moved-from objects shall be placed in a valid but unspecified state.

This paragraph is a blanket statement for all types defined by the std::lib that moved-from objects are not "poison", you just don't know value they have.

Furthermore, each algorithm (including member functions) defined in the standard may have a list of preconditions that must be true prior to calling that algorithm.  If there are no preconditions listed, that means that you can always call that function.

Move assignment for all types defined in the std::lib never have any preconditions listed for the left or right hand side arguments.

It is hard to quote something that doesn't exist, but that is the way this specification works.

Generalizing further, the following section refers to all types (i.e. user-supplied) that are used with the std::lib:

20.5.3.1 Template argument requirements [utility.arg.requirements]

Table 23 — MoveConstructible requirements [moveconstructible]

T u = rv;
T(rv);

rv's state is unspecified in the post-condition.

Table 25 — MoveAssignable requirements [moveassignable]

t = rv

Only if t and rv do not refer to the same object, t is equivalent to the value of rv before the assignment.

Afterwards, rv's state is unspecified (whether or not t and rv refer to the same object).

Furthermore this sections notes (notes are non-normative and often the normative text appears elsewhere) that rv must still meet the requirements of the library component (algorithm) it is being used with, even though it has been moved from.

For example, std::sort is allowed to move from a value x, and then use that x in a comparison expression.  x must be LessThanComparable, whether or not x is moved-from.  Only x's value is unspecified.

bool b = x < x;  // b must be false, no matter what!


问:
xvfb-run: line 171: kill: (25939) - No such process
All automated test runs successfully. but xvfb issue causes the build failure in Jenkins.

I have used below commnad in ExecuteShell option available under Jenkins to run my test cases on headless browser

```<code>/usr/bin/xvfb-run /usr/local/apache-maven-3.3.1/bin/mvn clean test -Dbrowser=firefox
</code>```

Getting the below output:

```<code>Results :

Tests run: 22, Failures: 0, Errors: 0, Skipped: 0

[INFO] BUILD SUCCESS

[INFO] Total time: 10:19 min

[INFO] Final Memory: 20M/47M

/usr/bin/xvfb-run: line 171: kill: (25939) - No such process

Build step 'Execute shell' marked build as failure
</code>```

As we can see in the output  [INFO] BUILD SUCCESS.
But /usr/bin/xvfb-run: line 171: kill: (25939) - No such process causes the builld failure.

Could anybody please provide some workaround for this?

答:
I could skip the same error using a little trick:

```<code>sleep(10);
</code>```

on my code... after ends a task and slept my PHP code I could run another task without any errors... following my PHP script...

hope it helps

Body:
All automated test runs successfully. but xvfb issue causes the build failure in Jenkins.

I have used below commnad in ExecuteShell option available under Jenkins to run my test cases on headless browser

/usr/bin/xvfb-run /usr/local/apache-maven-3.3.1/bin/mvn clean test -Dbrowser=firefox

Getting the below output:

Results :

Tests run: 22, Failures: 0, Errors: 0, Skipped: 0

[INFO] BUILD SUCCESS

[INFO] Total time: 10:19 min

[INFO] Final Memory: 20M/47M

/usr/bin/xvfb-run: line 171: kill: (25939) - No such process

Build step 'Execute shell' marked build as failure

As we can see in the output  [INFO] BUILD SUCCESS.
But /usr/bin/xvfb-run: line 171: kill: (25939) - No such process causes the builld failure.

Could anybody please provide some workaround for this?

Body:
I could skip the same error using a little trick:

sleep(10);

on my code... after ends a task and slept my PHP code I could run another task without any errors... following my PHP script...

hope it helps


问:
Iterate array based on operations on elements
Suppose I have two arrays.

```<code>a = ["A1", "A2", "B1"]
b = ["C2", "B1", "C1"]
</code>```

What I want is to iterate over the array 'a' first,

Get the element from array 'a' and do some operation on that.

1.a If that operation is successful, then move to next element of array 'a'.

1.b If that operation is unsuccessful, then start iterating the array 'b'.

Get the element from array 'b' and do some operation on that.

2.a If that operation is successful, then move to next element of array 'b'.

2.b If that operation is unsuccessful, then start iterating the array 'a' from the position where we left in 1.a and so on...

All of this would go on till all elements in both arrays are traversed. What is the approach I should use to code? I would be happy to write in case more details are needed.

答:
This is a pretty simple idea. What you want is:

```<code>until both lists A and B exhausted
   while not (A exhausted or processing A has failed)
      process next element of A
   while not (B exhausted or processing B has failed)
      process next element of B
</code>```

Now you can translate that most any normal iterative language. In C,

```<code>for (int ia = 0, ib = 0; ia < a_len || ib < b_len; ) {
  while (ia < a_len) if (process(a[ia++]) == FAIL) break;
  while (ib < b_len) if (process(b[ib++]) == FAIL) break;
}
</code>```

But different languages provide other ways to express this. An excellent example here is co-routines.

```<code>coroutine processA
  while A not empty and process(nextElement(A)) != FAIL, /* empty */ ;
  if not empty(B) yield B

coroutine processB
  while B not empty and process(nextElement(B)) != FAIL, /* empty */ ;
  if not empty(A) yield A
</code>```

Beautifully symmetrical, no?

Body:
Suppose I have two arrays.

a = ["A1", "A2", "B1"]
b = ["C2", "B1", "C1"]

What I want is to iterate over the array 'a' first,

Get the element from array 'a' and do some operation on that.

1.a If that operation is successful, then move to next element of array 'a'.

1.b If that operation is unsuccessful, then start iterating the array 'b'.

Get the element from array 'b' and do some operation on that.

2.a If that operation is successful, then move to next element of array 'b'.

2.b If that operation is unsuccessful, then start iterating the array 'a' from the position where we left in 1.a and so on...

All of this would go on till all elements in both arrays are traversed. What is the approach I should use to code? I would be happy to write in case more details are needed.

Body:
This is a pretty simple idea. What you want is:

until both lists A and B exhausted
   while not (A exhausted or processing A has failed)
      process next element of A
   while not (B exhausted or processing B has failed)
      process next element of B

Now you can translate that most any normal iterative language. In C,

for (int ia = 0, ib = 0; ia < a_len || ib < b_len; ) {
  while (ia < a_len) if (process(a[ia++]) == FAIL) break;
  while (ib < b_len) if (process(b[ib++]) == FAIL) break;
}

But different languages provide other ways to express this. An excellent example here is co-routines.

coroutine processA
  while A not empty and process(nextElement(A)) != FAIL, /* empty */ ;
  if not empty(B) yield B

coroutine processB
  while B not empty and process(nextElement(B)) != FAIL, /* empty */ ;
  if not empty(A) yield A

Beautifully symmetrical, no?


问:
M3 API Toolkit ? unable to find
M3 API Toolkit ? unable to find. I want to scan rfid from M3 mobile and want to show it in the text field of the browser based application by using M3 API Toolkit  !!! Need Help?</p>

答:
This year 2017, the SDK can't be found anywhere from josef's links.

I found the SDK from Warp Systems Downloads Section. I'm not sure if this is official and the latest version, but it runs fine on our M3 Orange device.

Having been suggested to make our custom app call on the device's RFID methods w/o the SDK (coz we didn't purchase it), I inquired a lot from communities if this is  humanely possible. Then helpful people from Core RFID (http://www.corerfid.com/contact-us/) hinted that M3's SDK is free for download, and after a few google search queries I found that download site.

I hope this info will be helpful for someone, somewhere, some other time.

Title: M3 API Toolkit ? unable to find


问:
React Component interface to methods
Q: Is there any way to provide an interface to access public methods from a given reusable component?

Scenario: Imagine that I am buiding a Tabs component. It's located inside a parent component, called App:

```<code><App>
    <Tabs />
    <button id="previous">Previous</button>
    <button id="next">Next</button>
</App>
</code>```

As you can see there is two buttons that should interact with Tabs component, moving it to previous or next tab pane.

My implementation consists in keeping next() and previous() methods inside Tabs component:

```<code>export default class Tabs extends React.Component {
    next() {}
    previous() {}
}
</code>```

Q: How can I bind next() and previous() methods to those buttons inside App component? Can I write some kind of interface exposed by Tabs component? What is the best and clean way to do that?

Edit 1: ...

Edit 2: Tabs is a "reusable" component. Many applications can render it inside.

答:
You could get a ref to Tabs instance in parent component

```<code>class Root extends Component {

  render() {
   return (
    <App>
      <Tabs ref={ref => this.tabs = ref} />
      <button id="previous" onClick={() => this.tabs.prev()}>Previous</button>
      <button id="next" onClick={() => this.tabs.next()}>Next</button>
   </App>
   )
  }
}
</code>```

Or a more reasonble approach would be to switch to some centralized state management solution say Flux. Take a look at Redux :).

Title: React Component interface to methods

Body:
Q: Is there any way to provide an interface to access public methods from a given reusable component?

Scenario: Imagine that I am buiding a Tabs component. It's located inside a parent component, called App:

<App>
    <Tabs />
    <button id="previous">Previous</button>
    <button id="next">Next</button>
</App>

As you can see there is two buttons that should interact with Tabs component, moving it to previous or next tab pane.

My implementation consists in keeping next() and previous() methods inside Tabs component:

export default class Tabs extends React.Component {
    next() {}
    previous() {}
}

Q: How can I bind next() and previous() methods to those buttons inside App component? Can I write some kind of interface exposed by Tabs component? What is the best and clean way to do that?

Edit 1: ...

Edit 2: Tabs is a "reusable" component. Many applications can render it inside.

Body:
You could get a ref to Tabs instance in parent component

class Root extends Component {

  render() {
   return (
    <App>
      <Tabs ref={ref => this.tabs = ref} />
      <button id="previous" onClick={() => this.tabs.prev()}>Previous</button>
      <button id="next" onClick={() => this.tabs.next()}>Next</button>
   </App>
   )
  }
}

Or a more reasonble approach would be to switch to some centralized state management solution say Flux. Take a look at Redux :).


问:
How to create documents in the api but with place of signature
I need create documents from my software to api integration but I would like of mark the place of signature for client.

Its possible?

答: What I've found is that it will place a signature tab for every document in an envelope, even if the other documents are using a different server template.</p>


问:
Create a backdrop/overlay behind modal with CSS
I have a modal that I have created in React using css, ReactTranstionGroupCSS and need to add a backdrop color behind the modal screen only when the modal is showing. How can I do this with just CSS? I just need to position the overlay (just need white at .5 opacity) behind the modal screen.

```<code>.modal-footer-small
  width: 450px
  height: auto
  margin: 0 auto
  top: 53%
  left: 0
  right: 0
  position: fixed
  z-index: 1
  box-shadow: -3px 0 5px rgba(100,100,100,0.2), 3px 0 5px rgba(100,100,100,0.2)
  background: white
  padding: 10px 40px
  > .ui-modal-body
    font-family: 'Flexo'
    font-size: 12px
    margin: 0 auto
    height: auto
    min-height: 160px
    max-height: 250px
    overflow: scroll

.modal-anim-enter
  opacity: 0.00
  transform: translateY(100%)
  &.modal-anim-enter-active
    opacity: 1
    transform: scale(1)
    transition: all .5s

.modal-anim-leave
  opacity: 1
  transform: translateY(100%)
  transition: all .5s
  &.modal-anim-leave-active
    opacity: 0.00
    transform: translateY(100%)
</code>```

Here is the modal component:

```<code>const UiModal = React.createClass({
    getInitialState(){
      return { isOpen: false };
    },

    openModal() {
        this.setState({ isOpen: true });
    },

    closeModal() {
        this.setState({ isOpen: false });
    },

    render() {
        const { openBtnText, header, subHeader, body, footer, footerText, actionBtnText='See More', closeBtnText='Cancel', placement='central', handleSaveAction } = this.props;

        return (
          <div>
            <div className="button" onClick={this.openModal}>{ this.props.openBtnText }</div>
            <div>
            <ReactCSSTransitionGroup transitionName="modal-anim" transitionLeaveTimeout={500} transitionEnterTimeout={500} transitionAppear={true}
            transitionAppearTimeout={500}>
            { this.state.isOpen &&
            <div className={`ui-modal-${placement}`} key={placement}>
              <div className="ui-modal-header">
                                    />
                </div>
                <div className="ui-modal-body">
                  {body}
                </div>
              <div className="ui-modal-footer">
                <div className="ui-modal-footer-button-group">
                  <div className="ui-modal-footer-button-close" onClick={this.closeModal}>{closeBtnText}</div>
                  <div className="ui-modal-footer-button button" onClick={this.handleSave}>{actionBtnText}</div>
                </div>
                <div className="ui-modal-footer-text">{footerText}</div>
              </div>
            </div>
            }
            </ReactCSSTransitionGroup>
          </div>
          </div>
        );
    }
});

export default UiModal;
</code>```

答:
Without restructuring your HTML, I would use .modal-footer-small as the overlay and position .ui-modal-body inside of it.

.ui-modal-body {
  font-family: 'Flexo';
  font-size: 12px;
  margin: 0 auto;
  height: auto;
  min-height: 160px;
  max-height: 250px;
  width: 450px;
  height: auto;
  margin: 0 auto;
  top: 53%;
  left: 0;
  right: 0;
  position: fixed;
  z-index: 1;
  box-shadow: -3px 0 5px rgba(100, 100, 100, 0.2), 3px 0 5px rgba(100, 100, 100, 0.2);
  background: white;
  padding: 10px 40px;
}

.modal-footer-small {
  background: rgba(255, 255, 255, 0.5);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

body {
  background: url("http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="modal-footer-small">
  <div class="ui-modal-body">modal</div>
</div></code>```

Body:
I have a modal that I have created in React using css, ReactTranstionGroupCSS and need to add a backdrop color behind the modal screen only when the modal is showing. How can I do this with just CSS? I just need to position the overlay (just need white at .5 opacity) behind the modal screen.

.modal-footer-small
  width: 450px
  height: auto
  margin: 0 auto
  top: 53%
  left: 0
  right: 0
  position: fixed
  z-index: 1
  box-shadow: -3px 0 5px rgba(100,100,100,0.2), 3px 0 5px rgba(100,100,100,0.2)
  background: white
  padding: 10px 40px
  > .ui-modal-body
    font-family: 'Flexo'
    font-size: 12px
    margin: 0 auto
    height: auto
    min-height: 160px
    max-height: 250px
    overflow: scroll

.modal-anim-enter
  opacity: 0.00
  transform: translateY(100%)
  &.modal-anim-enter-active
    opacity: 1
    transform: scale(1)
    transition: all .5s

.modal-anim-leave
  opacity: 1
  transform: translateY(100%)
  transition: all .5s
  &.modal-anim-leave-active
    opacity: 0.00
    transform: translateY(100%)

Here is the modal component:

const UiModal = React.createClass({
    getInitialState(){
      return { isOpen: false };
    },

    openModal() {
        this.setState({ isOpen: true });
    },

    closeModal() {
        this.setState({ isOpen: false });
    },

    render() {
        const { openBtnText, header, subHeader, body, footer, footerText, actionBtnText='See More', closeBtnText='Cancel', placement='central', handleSaveAction } = this.props;

        return (

{ this.props.openBtnText }

            <ReactCSSTransitionGroup transitionName="modal-anim" transitionLeaveTimeout={500} transitionEnterTimeout={500} transitionAppear={true}
            transitionAppearTimeout={500}>
            { this.state.isOpen &&
            <div className={`ui-modal-${placement}`} key={placement}>

                                    />

                  {body}

{closeBtnText}

{actionBtnText}

{footerText}

            }
            </ReactCSSTransitionGroup>

        );
    }
});

export default UiModal;

Body:
Without restructuring your HTML, I would use .modal-footer-small as the overlay and position .ui-modal-body inside of it.

.ui-modal-body {
  font-family: 'Flexo';
  font-size: 12px;
  margin: 0 auto;
  height: auto;
  min-height: 160px;
  max-height: 250px;
  width: 450px;
  height: auto;
  margin: 0 auto;
  top: 53%;
  left: 0;
  right: 0;
  position: fixed;
  z-index: 1;
  box-shadow: -3px 0 5px rgba(100, 100, 100, 0.2), 3px 0 5px rgba(100, 100, 100, 0.2);
  background: white;
  padding: 10px 40px;
}

.modal-footer-small {
  background: rgba(255, 255, 255, 0.5);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

body {
  background: url("http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg");
}

<div class="modal-footer-small">
  <div class="ui-modal-body">modal</div>
</div>


问:
Indexing arrays with enums in C#
I have a lot of fixed-size collections of numbers where each entry can be accessed with a constant. Naturally this seems to point to arrays and enums:

```<code>enum StatType {
    Foo = 0,
    Bar
    // ...
}

float[] stats = new float[...];
stats[StatType.Foo] = 1.23f;
</code>```

The problem with this is of course that you cannot use an enum to index an array without a cast (though the compiled IL is using plain ints). So you have to write this all over the place:

```<code>stats[(int)StatType.foo] = 1.23f;
</code>```

I have tried to find ways to use the same easy syntax without casting but haven't found a perfect solution yet. Using a dictionary seems to be out of the question since I found it to be around 320 times slower than an array. I also tried to write a generic class for an array with enums as index:

```<code>public sealed class EnumArray<T>
{
    private T[] array;
    public EnumArray(int size)
    {
        array = new T[size];
    }
    // slow!
    public T this[Enum idx]
    {
        get { return array[(int)(object)idx]; }
        set { array[(int)(object)idx] = value; }
    }
}
</code>```

or even a variant with a second generic parameter specifying the enum. This comes quite close to what I want but the problem is that you cannot just cast an unspecific enum (be it from a generic parameter or the boxed type Enum) to int. Instead you have to first box it with a cast to object and then cast it back. This works, but is quite slow. I found that the generated IL for the indexer looks something like this:

```<code>.method public hidebysig specialname instance !T get_Item(!E idx) cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldfld !0[] EnumArray`2<!T, !E>::array
    L_0006: ldarg.1
    L_0007: box !E
    L_000c: unbox.any int32
    L_0011: ldelem.any !T
    L_0016: ret
}
</code>```

As you can see there are unnecessary box and unbox instructions there. If you strip them from the binary the code works just fine and is just a tad slower than pure array access.

Is there any way to easily overcome this problem? Or maybe even better ways?
I think it would also be possible to tag such indexer methods with a custom attribute and strip those two instructions post-compile. What would be a suitable library for that? Maybe Mono.Cecil?

Of course there's always the possibility to drop enums and use constants like this:

```<code>static class StatType {
    public const int Foo = 0;
    public const int Bar = 1;
    public const int End = 2;
}
</code>```

which may be the fastest way since you can directly access the array.

答:
I don't believe there is any way to add an implicit conversion operator to an enum, unfortunately.  So you'll have to either live with ugly typecasts or just use a static class with consts.

Here's a StackOverflow question that discusses more on the implicit conversion operator:

Can we define implicit conversions of enums in c#?

Title: Indexing arrays with enums in C#

Body:
I have a lot of fixed-size collections of numbers where each entry can be accessed with a constant. Naturally this seems to point to arrays and enums:

enum StatType {
    Foo = 0,
    Bar
    // ...
}

float[] stats = new float[...];
stats[StatType.Foo] = 1.23f;

The problem with this is of course that you cannot use an enum to index an array without a cast (though the compiled IL is using plain ints). So you have to write this all over the place:

stats[(int)StatType.foo] = 1.23f;

I have tried to find ways to use the same easy syntax without casting but haven't found a perfect solution yet. Using a dictionary seems to be out of the question since I found it to be around 320 times slower than an array. I also tried to write a generic class for an array with enums as index:

public sealed class EnumArray<T>
{
    private T[] array;
    public EnumArray(int size)
    {
        array = new T[size];
    }
    // slow!
    public T this[Enum idx]
    {
        get { return array[(int)(object)idx]; }
        set { array[(int)(object)idx] = value; }
    }
}

or even a variant with a second generic parameter specifying the enum. This comes quite close to what I want but the problem is that you cannot just cast an unspecific enum (be it from a generic parameter or the boxed type Enum) to int. Instead you have to first box it with a cast to object and then cast it back. This works, but is quite slow. I found that the generated IL for the indexer looks something like this:

.method public hidebysig specialname instance !T get_Item(!E idx) cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldfld !0[] EnumArray`2<!T, !E>::array
    L_0006: ldarg.1
    L_0007: box !E
    L_000c: unbox.any int32
    L_0011: ldelem.any !T
    L_0016: ret
}

As you can see there are unnecessary box and unbox instructions there. If you strip them from the binary the code works just fine and is just a tad slower than pure array access.

Is there any way to easily overcome this problem? Or maybe even better ways?
I think it would also be possible to tag such indexer methods with a custom attribute and strip those two instructions post-compile. What would be a suitable library for that? Maybe Mono.Cecil?

Of course there's always the possibility to drop enums and use constants like this:

static class StatType {
    public const int Foo = 0;
    public const int Bar = 1;
    public const int End = 2;
}

which may be the fastest way since you can directly access the array.

OwnerDisplayName: Steven Behnke


问:
Averaging TIFF images in Matlab?
I'm trying to average 8 TIFF images in Matlab, but I've been unable to get a proper result. If I read in the images and divide by a fixed number (the number of images read), I end up with a very dark image instead of an "average image" with even brightness. The code I used is as follows:

```<code>i = 0;
R = 0;
A=imread('1.tif');
B=imread('2.tif');
R = imdivide((imadd(A,B)),2);

for i = 3:8
    TEMP = imadd(R,imread(sprintf('%d.tif' ,i)));
    R = imdivide(TEMP,8);
end

imshow(R);
imwrite(R,'AVG.tif','tif');
</code>```

Is there any way to fix this averaging scheme?
Thanks!

答:
Even easier, suppose that X = [X1; X2; X3... X8] is an array with dimensions (rows,columns,8) in which:

```<code>X1 = imread('1.tif');
X1 = double(X1);
...
X = cat(3,X1 X2 X3 X4 X5 X6 X7 X8);
R = mean(X,3);
</code>```

Where R is the average matrix.

Title: Averaging TIFF images in Matlab?

Body:
I'm trying to average 8 TIFF images in Matlab, but I've been unable to get a proper result. If I read in the images and divide by a fixed number (the number of images read), I end up with a very dark image instead of an "average image" with even brightness. The code I used is as follows:

i = 0;
R = 0;
A=imread('1.tif');
B=imread('2.tif');
R = imdivide((imadd(A,B)),2);

for i = 3:8
    TEMP = imadd(R,imread(sprintf('%d.tif' ,i)));
    R = imdivide(TEMP,8);
end

imshow(R);
imwrite(R,'AVG.tif','tif');

Is there any way to fix this averaging scheme?
Thanks!

Body:
Even easier, suppose that X = [X1; X2; X3... X8] is an array with dimensions (rows,columns,8) in which:

X1 = imread('1.tif');
X1 = double(X1);
...
X = cat(3,X1 X2 X3 X4 X5 X6 X7 X8);
R = mean(X,3);

Where R is the average matrix.


问:
Display coach marks view when user launches app for the first time Swift 3
I need to launch a coach marks/tutorial view over a tableview when the user launches the app for the first time. The coach marks will never display again, unless the user deletes and reinstalls the app.

I scoured the internet, but was unable to find a simple solution. Oh, I'm fairly new to Swift, so please be gentle. :)

EDIT:
Here is the what I used. Works great!

```<code>  override func viewDidAppear(_ animated: Bool) {
        if !UserDefaults.standard.bool(forKey: "isSecondTime") {
            let launchedBefore = UserDefaults.standard.bool(forKey: "isSecondTime")
            if launchedBefore  {
                print("Not the first launch.")
            } else {
                let VC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CoachMarksViewController")
                self.present(VC, animated: true, completion: nil)
                print("This the first launch.")
                UserDefaults.standard.set(true, forKey: "isSecondTime")
            }

        }
}
</code>```

答:
You should use "UserDefaults" to achieve this. In your "viewDidLoad" method check if a value let's say "isSecondTime == true" (This value you will access from "UserDefaults") then do nothing otherwise in else section show your tutorial and save the value "isSecondTime = true" in "UserDefaults". It will work according to your requirements. Check this code:

```<code>if(NSUserDefaults.standardUserDefaults().boolForKey("isSecondTime"))
    {
        // app already launched
    }
    else
    {
       // This is the first launch ever
       // show your tutorial.....!
        NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isSecondTime")
        NSUserDefaults.standardUserDefaults().synchronize()
    }
</code>```

For Swift 3:

```<code>let launchedBefore = UserDefaults.standard.bool(forKey: "isSecondTime")
if launchedBefore  {
print("Not first launch.")
} else {
//  // show your tutorial.....!
print("First launch, setting UserDefault.")
UserDefaults.standard.set(true, forKey: "isSecondTime")
}
</code>```

Body:
I need to launch a coach marks/tutorial view over a tableview when the user launches the app for the first time. The coach marks will never display again, unless the user deletes and reinstalls the app.

I scoured the internet, but was unable to find a simple solution. Oh, I'm fairly new to Swift, so please be gentle. :)

EDIT:
Here is the what I used. Works great!

  override func viewDidAppear(_ animated: Bool) {
        if !UserDefaults.standard.bool(forKey: "isSecondTime") {
            let launchedBefore = UserDefaults.standard.bool(forKey: "isSecondTime")
            if launchedBefore  {
                print("Not the first launch.")
            } else {
                let VC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CoachMarksViewController")
                self.present(VC, animated: true, completion: nil)
                print("This the first launch.")
                UserDefaults.standard.set(true, forKey: "isSecondTime")
            }

        }
}

Body:
You should use "UserDefaults" to achieve this. In your "viewDidLoad" method check if a value let's say "isSecondTime == true" (This value you will access from "UserDefaults") then do nothing otherwise in else section show your tutorial and save the value "isSecondTime = true" in "UserDefaults". It will work according to your requirements. Check this code:

if(NSUserDefaults.standardUserDefaults().boolForKey("isSecondTime"))
    {
        // app already launched
    }
    else
    {
       // This is the first launch ever
       // show your tutorial.....!
        NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isSecondTime")
        NSUserDefaults.standardUserDefaults().synchronize()
    }

For Swift 3:

let launchedBefore = UserDefaults.standard.bool(forKey: "isSecondTime")
if launchedBefore  {
print("Not first launch.")
} else {
//  // show your tutorial.....!
print("First launch, setting UserDefault.")
UserDefaults.standard.set(true, forKey: "isSecondTime")
}


问:
How to change the data type of an ADO recordset field?
In VBA I have a collection of ADO recordsets that I want to do calculations on and store the values in the recordset in memory while the user is using the form.

My issues: after I do a calculation on, say, and integer, I get a double/float. When I try to store that in the recordset it is cast/changed to an integer. I want the precision of the double/float after the calculation to be preserved.

My idea: change the data type of the field I am calculation and storing. I'm not seeing how to do it. How do I do that? Can I do that?

Ex:

```<code>Option Explicit
Sub test()

Dim rs As ADODB.Recordset
Dim sql As String
sql = "select * from test;"
Set rs = frsGetPgRecordset(sql)

Do While rs.EOF = False
    Debug.Print rs!x & "<- original"
    Debug.Print Application.WorksheetFunction.Log(rs!x) & "<- what I want stored"
    rs.Fields("x") = Application.WorksheetFunction.Log(rs!x)
    Debug.Print rs!x & "<- what I get"
    rs.MoveNext
Loop

End Sub
</code>```

I get:

```<code>8<- original
0.903089986991944<- what I want stored
1<- what I get
20<- original
1.30102999566398<- what I want stored
1<- what I get
</code>```

Note, this is not changing the database because in frsGetPgRecordset (not provide because it's not critical to the question) I have:

```<code>rs.CursorType = adOpenKeyset
rs.CursorLocation = adUseClient
rs.LockType = adLockBatchOptimistic
</code>```

You can get more info here on that part, because people will ask:
https://learn.microsoft.com/en-us/sql/ado/reference/ado-api/cursortype-property-ado
Update recordset without updating database

答:
I would just store calculations results in a new field instead of trying to change an existing field:</p>

```<code>rs.Fields.Append "New_Field", adDouble
</code>```

Body:
In VBA I have a collection of ADO recordsets that I want to do calculations on and store the values in the recordset in memory while the user is using the form.

My issues: after I do a calculation on, say, and integer, I get a double/float. When I try to store that in the recordset it is cast/changed to an integer. I want the precision of the double/float after the calculation to be preserved.

My idea: change the data type of the field I am calculation and storing. I'm not seeing how to do it. How do I do that? Can I do that?

Ex:

Option Explicit
Sub test()

Dim rs As ADODB.Recordset
Dim sql As String
sql = "select * from test;"
Set rs = frsGetPgRecordset(sql)

Do While rs.EOF = False
    Debug.Print rs!x & "<- original"
    Debug.Print Application.WorksheetFunction.Log(rs!x) & "<- what I want stored"
    rs.Fields("x") = Application.WorksheetFunction.Log(rs!x)
    Debug.Print rs!x & "<- what I get"
    rs.MoveNext
Loop

End Sub

I get:

8<- original
0.903089986991944<- what I want stored
1<- what I get
20<- original
1.30102999566398<- what I want stored
1<- what I get

Note, this is not changing the database because in frsGetPgRecordset (not provide because it's not critical to the question) I have:

rs.CursorType = adOpenKeyset
rs.CursorLocation = adUseClient
rs.LockType = adLockBatchOptimistic

You can get more info here on that part, because people will ask:
https://learn.microsoft.com/en-us/sql/ado/reference/ado-api/cursortype-property-ado
Update recordset without updating database

Body:
I would just store calculations results in a new field instead of trying to change an existing field:

rs.Fields.Append "New_Field", adDouble


问:
How to access the camera from within a Webview?
In my android app, I am trying to load a webpage (that must access the camera) on WebView. On my laptop, when I load the webpage, I could access the camera.

Everything else on the html page is shown.

Here are the permission I am putting in the Manifest.xml

```<code><uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.webkit.PermissionRequest" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
</code>```

I am setting the SDK as follow:

```<code><uses-sdk
    android:minSdkVersion="18"
    android:targetSdkVersion="21" />
</code>```

Here is my webview setting:

```<code>private void setMyWebviewSettings(WebSettings MyWebviewSettings) {
    MyWebviewSettings.setAllowFileAccessFromFileURLs(true);
    MyWebviewSettings.setAllowUniversalAccessFromFileURLs(true);
    MyWebviewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    MyWebviewSettings.setJavaScriptEnabled(true);
    MyWebviewSettings.setDomStorageEnabled(true);
    MyWebviewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    MyWebviewSettings.setBuiltInZoomControls(true);
    MyWebviewSettings.setAllowFileAccess(true);
    MyWebviewSettings.setSupportZoom(true);
}
</code>```

If I could access the camera from my app directly (using a normal activity), why can't I open it from within the WebView?!

答:
This is certainly possible with getUserMedia through WebRTC.

Set up your WebView to allow permission and load your HTML with loadUrl():

```<code>    WebView myWebView = (WebView) findViewById(R.id.webview);

    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.getSettings().setAllowFileAccessFromFileURLs(true);
    myWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);

    myWebView.setWebViewClient(new WebViewClient());
    myWebView.setWebChromeClient(new WebChromeClient() {
        // Grant permissions for cam
        @Override
        public void onPermissionRequest(final PermissionRequest request) {
            Log.d(TAG, "onPermissionRequest");
            MainActivity.this.runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.M)
                @Override
                public void run() {
                    Log.d(TAG, request.getOrigin().toString());
                    if(request.getOrigin().toString().equals("file:///")) {
                        Log.d(TAG, "GRANTED");
                        request.grant(request.getResources());
                    } else {
                        Log.d(TAG, "DENIED");
                        request.deny();
                    }
                }
            });
        }

    });

    myWebView.loadUrl(LOCAL_FILE);
</code>```

Then use getUserMedia through your JS file, assuming you have a <video> tag in your HTML file:

```<code>var constraints = { video: { width: 800, height: 800 } };

navigator.mediaDevices.getUserMedia(constraints)
.then(function(mediaStream) {
  var video = document.querySelector('video');
  video.srcObject = mediaStream;
  video.onloadedmetadata = function(e) {
    video.play();
  };
})
.catch(function(err) { console.log(err.name + ": " + err.message); }); // always check for errors at the end.
</code>```

Lastly, ensure you have permissions set in your manifest:

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
</code>```

Body:
In my android app, I am trying to load a webpage (that must access the camera) on WebView. On my laptop, when I load the webpage, I could access the camera.

Everything else on the html page is shown.

Here are the permission I am putting in the Manifest.xml

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.webkit.PermissionRequest" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

I am setting the SDK as follow:

<uses-sdk
    android:minSdkVersion="18"
    android:targetSdkVersion="21" />

Here is my webview setting:

private void setMyWebviewSettings(WebSettings MyWebviewSettings) {
    MyWebviewSettings.setAllowFileAccessFromFileURLs(true);
    MyWebviewSettings.setAllowUniversalAccessFromFileURLs(true);
    MyWebviewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    MyWebviewSettings.setJavaScriptEnabled(true);
    MyWebviewSettings.setDomStorageEnabled(true);
    MyWebviewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    MyWebviewSettings.setBuiltInZoomControls(true);
    MyWebviewSettings.setAllowFileAccess(true);
    MyWebviewSettings.setSupportZoom(true);
}

If I could access the camera from my app directly (using a normal activity), why can't I open it from within the WebView?!

Body:
This is certainly possible with getUserMedia through WebRTC.

Set up your WebView to allow permission and load your HTML with loadUrl():

    WebView myWebView = (WebView) findViewById(R.id.webview);

    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.getSettings().setAllowFileAccessFromFileURLs(true);
    myWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);

    myWebView.setWebViewClient(new WebViewClient());
    myWebView.setWebChromeClient(new WebChromeClient() {
        // Grant permissions for cam
        @Override
        public void onPermissionRequest(final PermissionRequest request) {
            Log.d(TAG, "onPermissionRequest");
            MainActivity.this.runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.M)
                @Override
                public void run() {
                    Log.d(TAG, request.getOrigin().toString());
                    if(request.getOrigin().toString().equals("file:///")) {
                        Log.d(TAG, "GRANTED");
                        request.grant(request.getResources());
                    } else {
                        Log.d(TAG, "DENIED");
                        request.deny();
                    }
                }
            });
        }

    });

    myWebView.loadUrl(LOCAL_FILE);

Then use getUserMedia through your JS file, assuming you have a <video> tag in your HTML file:

var constraints = { video: { width: 800, height: 800 } };

navigator.mediaDevices.getUserMedia(constraints)
.then(function(mediaStream) {
  var video = document.querySelector('video');
  video.srcObject = mediaStream;
  video.onloadedmetadata = function(e) {
    video.play();
  };
})
.catch(function(err) { console.log(err.name + ": " + err.message); }); // always check for errors at the end.

Lastly, ensure you have permissions set in your manifest:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />


问:
SQL Server 2012 CU7 for SP3 download link pls..?
Am unable to download CU7 for SQL 2012 SP3. Can anybody provide link to download CU7 for SQL Server 2012 SP3...? I don't need latest CU9..

SQL Server services running with CU7 but SSRS services still running on SP3, we are facing bit mapping issue, to fix this we need to apply CU7 on SSRS.

答: Cumulative Update 7 for SQL Server 2012 SP3</p>


问:
Kubernetes auto-scaling nodes over AWS
I am working in set up a kubernetes cluster using the following stuff:

AWS as a cloud provider

kops (Version 1.6.0-alpha, just to test) as a cli tool to create and manage cluster

kubectl (server : v1.6.2 and client : 1.6.0 ) to control my cluster

Ubuntu 16 as a local OS

I have a simple k8s cluster with the following stuff:

AWS region : us-west-2

One master over : t2.medium
/ k8s-1.5-debian-jessie-amd64-hvm-ebs-2017-01-09

One node onver : t2.medium
/ k8s-1.5-debian-jessie-amd64-hvm-ebs-2017-01-09

I also have some pods deployed over the cluster and I created jmeter stress test to generate artificial traffic.

My question is How can I create a auto-scaling node on a k8s cluster using kops over aws?

I just found the following ad-don kops addons in kops repository. I deployed as the docs says and it is available.

My parameters were:

```<code>CLOUD_PROVIDER=aws
IMAGE=gcr.io/google_containers/cluster-autoscaler:v0.4.0
MIN_NODES=1
MAX_NODES=3
AWS_REGION=us-east-2
GROUP_NAME="<the-auto-scaling-group-Name>"
SSL_CERT_PATH="/etc/ssl/certs/ca-certificates.crt" # (/etc/ssl/certs for gce)

$ kubectl get deployments --namespace=kube-system

NAME                   DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
cluster-autoscaler     1         1         1            1           3h
dns-controller         1         1         1            1           3h
kube-dns               2         2         2            2           3h
kube-dns-autoscaler    1         1         1            1           3h
kubernetes-dashboard   1         1         1            1           3h
</code>```

However, after stress my node using a pod with stress containers nothing happens (100% cpu utilization) and my auto-scaling group is not modified.

In the other hand, I export the kops output in terraform but there ia not auto scaling policies to generate auto-scaling base on cpu utilization.

Finally, I could find an entry in the k8s blog which indicates that it will be support in the future by AWS but there is not other announcement about it.

Any suggestion or experience with that task in AWS and kops?. Next I will try to generate auto-scaling policies manually just to test.

答:
After review kops (open issues related with auto scaling) I could not found an option for nodes auto scaling and as I wrote in my question I was looking for node auto scaling. Maybe in new versions of kops it will be consider. However, I decided set up a kubernetes v1.5.4 from scratch using terraform contemplating auto scaling in nodes. If some is interested in my implementation the source code is in my personal repo :: kubernetes cluster v1 with terraform (afym).

I would use this base to setup the cluster in production. I hope it can help someone.

Thank you and if someone find the auto scaling configuration option in kops it will be great.

Title: Kubernetes auto-scaling nodes over AWS

Body:
I am working in set up a kubernetes cluster using the following stuff:

AWS as a cloud provider

kops (Version 1.6.0-alpha, just to test) as a cli tool to create and manage cluster

kubectl (server : v1.6.2 and client : 1.6.0 ) to control my cluster

Ubuntu 16 as a local OS

I have a simple k8s cluster with the following stuff:

AWS region : us-west-2

One master over : t2.medium
/ k8s-1.5-debian-jessie-amd64-hvm-ebs-2017-01-09

One node onver : t2.medium
/ k8s-1.5-debian-jessie-amd64-hvm-ebs-2017-01-09

I also have some pods deployed over the cluster and I created jmeter stress test to generate artificial traffic.

My question is How can I create a auto-scaling node on a k8s cluster using kops over aws?

I just found the following ad-don kops addons in kops repository. I deployed as the docs says and it is available.

My parameters were:

CLOUD_PROVIDER=aws
IMAGE=gcr.io/google_containers/cluster-autoscaler:v0.4.0
MIN_NODES=1
MAX_NODES=3
AWS_REGION=us-east-2
GROUP_NAME="<the-auto-scaling-group-Name>"
SSL_CERT_PATH="/etc/ssl/certs/ca-certificates.crt" # (/etc/ssl/certs for gce)

$ kubectl get deployments --namespace=kube-system

NAME                   DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
cluster-autoscaler     1         1         1            1           3h
dns-controller         1         1         1            1           3h
kube-dns               2         2         2            2           3h
kube-dns-autoscaler    1         1         1            1           3h
kubernetes-dashboard   1         1         1            1           3h

However, after stress my node using a pod with stress containers nothing happens (100% cpu utilization) and my auto-scaling group is not modified.

In the other hand, I export the kops output in terraform but there ia not auto scaling policies to generate auto-scaling base on cpu utilization.

Finally, I could find an entry in the k8s blog which indicates that it will be support in the future by AWS but there is not other announcement about it.

Any suggestion or experience with that task in AWS and kops?. Next I will try to generate auto-scaling policies manually just to test.


问:
Create new file on windows
I'm using windows 7 Ultimate.
While press right button mouse there is no "New" option...enter image description here
And also while press the "New folder" button there no folder created.
It just shows the "New Folder" button is pressed but no such thing happen..
enter image description here

Help me to fix this...
Thanks in advance.

答:
Try right clicking on the white space of the window, you seem to have something selected on your first picture.

also you could try
ctrl + shift + n

this is the hot keys for creating a new folder.

Hope this helps.

Title: Create new file on windows


问:
Sequelize has and belongs to many
Is there a way to do a polymorphic self-association with a through table (e.g. Collection has and belongs to many Collections)?

Trying to adapt http://docs.sequelizejs.com/manual/tutorial/associations.html#n-m to this scenario:

```<code>// Inside collection.js associate
Collection.belongsToMany(Collection, {
    through: {
        model: models.CollectionItem,
        unique: false,
        scope: {
            collectible: 'collection'
        }
    },
    foreignKey: 'collectibleUid',
    constraints: false
});
</code>```

Where collectionItem.js would look like

```<code>const CollectionItem = sequelize.define("CollectionItem", {
    uid: {
        type: DataTypes.BIGINT,
        primaryKey: true
    },
    collectionUid: {
        type: DataTypes.BIGINT,
        allowNull: false,
        unique: 'collection_item_collectible'
    },
    order: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 0
    },
    collectibleUid: {
        type: DataTypes.BIGINT,
        allowNull: false,
        references: null, // Because the column is polymorphic, we cannot say that it REFERENCES a specific table
        unique: 'collection_item_collectible'
    },
    collectible: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: 'collection_item_collectible'
    }
}, {
    classMethods: {
    }
});
</code>```

It seems Sequelize wants me to name this differently through yet another join / through table, but that would essentially be creating a new table versus just getting a true hasAndBelongsToMany type relationship.

Error: 'as' must be defined for many-to-many self-associations

答:
Try being explicit and add:

```<code>as: "CollectionItem"
</code>```

as does not create a new join table, it just gives the relation a name

Title: Sequelize has and belongs to many

Body:
Is there a way to do a polymorphic self-association with a through table (e.g. Collection has and belongs to many Collections)?

Trying to adapt http://docs.sequelizejs.com/manual/tutorial/associations.html#n-m to this scenario:

// Inside collection.js associate
Collection.belongsToMany(Collection, {
    through: {
        model: models.CollectionItem,
        unique: false,
        scope: {
            collectible: 'collection'
        }
    },
    foreignKey: 'collectibleUid',
    constraints: false
});

Where collectionItem.js would look like

const CollectionItem = sequelize.define("CollectionItem", {
    uid: {
        type: DataTypes.BIGINT,
        primaryKey: true
    },
    collectionUid: {
        type: DataTypes.BIGINT,
        allowNull: false,
        unique: 'collection_item_collectible'
    },
    order: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 0
    },
    collectibleUid: {
        type: DataTypes.BIGINT,
        allowNull: false,
        references: null, // Because the column is polymorphic, we cannot say that it REFERENCES a specific table
        unique: 'collection_item_collectible'
    },
    collectible: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: 'collection_item_collectible'
    }
}, {
    classMethods: {
    }
});

It seems Sequelize wants me to name this differently through yet another join / through table, but that would essentially be creating a new table versus just getting a true hasAndBelongsToMany type relationship.

Error: 'as' must be defined for many-to-many self-associations

Body:
Try being explicit and add:

as: "CollectionItem"

as does not create a new join table, it just gives the relation a name


问:
Downloading large files with PHP using mod_xsendfile on linux
I had the need to serve very large files (1Gb+) from my webserver using PHP and authentication, so that only some customer had the rights to download files.

I didn't want to use direct links and using a PHP script to serve the files wasn't an option due to memory and timeout limits.

My webserver is managed with Plesk and runs on Apache / CentOS 6.

答:
Dario's comment above is really helpful. I just wanted to add what I used for the Laravel return statement in order to make sure the files are named correctly:</p>

```<code>return response(null)
    ->header('Content-Type' , 'application/octet-stream')
    ->header('Content-Disposition', 'attachment; filename="' . $filename . "')
    ->header('X-Sendfile', $fullfilepath);
</code>```

Body:
Dario's comment above is really helpful. I just wanted to add what I used for the Laravel return statement in order to make sure the files are named correctly:

return response(null)
    ->header('Content-Type' , 'application/octet-stream')
    ->header('Content-Disposition', 'attachment; filename="' . $filename . "')
    ->header('X-Sendfile', $fullfilepath);


问:
Performance Measures
I have to do combine Classification Accuracy (A), Precision (P) and Recall (R) on the minority class measures into one measure M by: M=w1*A+w2*P+W3*R where w1, w2 and w3 are weighting factors for A, R and P respectively.

I am not sure what are the weighting factors here for this linear model formula?

Thank you very much for any help!!

答: That sound like you have to come up with those weights yourself depending on your specific needs. Alternatively, I'd suggest using the well known F1 score, which Weka already provides: https://en.wikipedia.org/wiki/F1_score</p>

Title: Performance Measures


问:
Multiple repositories and Heroku
I have two git repositories (frontend and backend). Say, i need to push frontend to heroku and don't touch backend. Simple static files update, right? Should be easy. But it's not. I have to manually put my static files from frontend into backend repository and push backend to heroku. Then wait for build, env install etc. All this just to upload some files. Is there another way? Maybe some manipulations with git submodule or something like that?

答:
From what i've learned: The right way to do this is to have multiple heroku apps. It's kind of heroku's pattern. Build an app for each of your microservices. So e.g. you will have frontend app at web.yourdomain.com, auth microservice at auth.yourdomain.com, long-polling server at updates.yourdomain.com etc. Or you can redirect all requests from clients via api.yourdomain.com.

Point is, you have multiple repositories for multiple apps. That seems to be it.

Title: Multiple repositories and Heroku


问:
Find Each line of a textfile in another text file using python
I have 2 text files, 1 which contain keywords in a each line around 75 lines ex. __key25words_
Second file contains thousand of lines I want to find a keyword in secondfile if it is present anywhere in second file I want to print that line similar way it should check for all keywords in second file and print if any matches
Note: am able to print a keyword but only when second file starts a line with that key word my script not printing even if keyword exist in middle of line in second file</p>

答:
Assuming that file1 contains  keywords and file2 contains the lines to be compared ,
then this code may help you

```<code>with  open('file1.txt' , 'r+') as file1 :
    for keyword in file1.readlines() :
        keyword = keyword.replace('\n' , '')
        print ("Looking for " , keyword , " in file" )
        with  open('file2.txt' , 'r+') as file2:
            for line in file2.readlines():
                if keyword in line:
                    print(line)
</code>```

Body:
Assuming that file1 contains  keywords and file2 contains the lines to be compared ,
then this code may help you

with  open('file1.txt' , 'r+') as file1 :
    for keyword in file1.readlines() :
        keyword = keyword.replace('\n' , '')
        print ("Looking for " , keyword , " in file" )
        with  open('file2.txt' , 'r+') as file2:
            for line in file2.readlines():
                if keyword in line:
                    print(line)


问:
Why does my Python script run differently when executed by Windows 10 Task Scheduler
I have a python 3 script that relies on (among other things) selenium, bs4, smtplib, and xlsxwriter. The script scrapes a website, saves a large chunk of data to an Excel file, and then emails me smaller chunks of data that are of particular interest. I have run the script numerous times and it works fine (i.e., it writes the excel file and emails me).

Recently, I used Task Scheduler on Windows 10 to set this script to run every 24 hours. The program apparently runs (and is recorded as successful by Task Scheduler). The problem is the when Task Scheduler executes the program I only receive the email with smaller chunks of data. The Excel file is not written.

Under Task Scheduler, I put the following in the Program/Script box: C:\path\to\python\python.exe. Under Arguments, I put: C:\path\to\script.py.

Note, per a previous SO question, I tried putting cmd under Program/Script and then C:\path\to\python\python.exe C:\path\to\script.py as the arguments. The program didn't run at all with the latter cmd setup.

Not sure if relevant, but I added c:\path\to\python\python36-32\ and c:\path\to\scriptfolder\ to my system variables path. I put #!python3 at the top of my scripts. Thanks.

答: Solved. My script wrote an Excel file to the current working directory when run in PowerShell. When run through Task Scheduler, the file was written to the path specified in the Start In (Optional) box. I had the path to python.exe there per StackOverflow suggestions. So the file was written in c:\python\python36-32. I changed the Start in (optional) box to the preferred path for saving the Excel file and it worked. </p>


问:
How to create a sub array from another array in Java?
How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:

```<code>methodName(object array, int start, int end)
</code>```

I don't want to go over making loops and making my program suffer.

I keep getting error:

cannot find symbol method copyOfRange(int[],int,int)

This is my code:

```<code>import java.util.*;

public class testing
{
    public static void main(String [] arg)
    {
        int[] src = new int[] {1, 2, 3, 4, 5};
        int b1[] = Arrays.copyOfRange(src, 0, 2);
    }
}
</code>```

答: I you are using java prior to version 1.6 use System.arraycopy() instead. Or upgrade your environment.

Body:
How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:

methodName(object array, int start, int end)

I don't want to go over making loops and making my program suffer.

I keep getting error:

cannot find symbol method copyOfRange(int[],int,int)

This is my code:

import java.util.*;

public class testing
{
    public static void main(String [] arg)
    {
        int[] src = new int[] {1, 2, 3, 4, 5};
        int b1[] = Arrays.copyOfRange(src, 0, 2);
    }
}


问:
Powery query - Sort by Date - Current day minus 1
I am trying to sort within power query to sort by current day minus 1.

I've been able to sort for the current date using:

Date.From(DateTime.LocalNow()))

Any suggestions on how to return the previous day?

答: That would be: Date.AddDays(Date.From(DateTime.LocalNow())),-1)</p>


问:
Convert nested loop to recursion
I have used 3 nested loop. Now i want to convert these loops to recursive.
Also is there a general way to convert a loop into recursive?</p>

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

#define f(x, y, z) ((x + y) * (y + z))

int main()
{
    int test_case, p, q, r, i, j, k, a[100001], b[100001], c[100001], sum;
    scanf("%d", &test_case);
    while (test_case--) {
        scanf("%d%d%d", &p, &q, &r);
        sum = 0;
        for (i = 0; i < p; i++) {
            scanf("%d", &a[i]);
        }
        for (i = 0; i < q; i++) {
            scanf("%d", &b[i]);
        }
        for (i = 0; i < p; i++) {
            scanf("%d", &c[i]);
        }
        for (i = 0; i < q; i++) { // I have convert this to recursion.
            for (j = 0; j < p; j++) {
                for (k = 0; k < r; k++) {
                    if (b[i] >= a[j] && b[i] >= c[k]) {
                        sum += f(a[j], b[i], c[k]);
                    }
                }
            }
        }
        printf("%d\n", sum % 1000000007);
    }
    return 0;
}
</code>```

答:
Thanks to @Jean-Baptiste Yunès . </p>

<p>I made these changes to my code to convert it to recursive. </p>

```<code>#include<stdio.h>
#define f(x, y, z) ((x + y)*(y + z))
int sum=0;
void rec_k(int k,int r,int i,int j,int a[],int b[],int c[]) { // k-loop
    if (!(k<r)) return;
    if (b[i] >= a[j] && b[i] >= c[k]) {
        sum += f(a[j], b[i], c[k]);
    }
    rec_k(k+1,r,i,j,a,b,c);
}

void rec_j(int j,int p,int i,int r,int a[],int b[],int c[]) { // j-loop
    if (!(j<p)) return;
    rec_k(0,r,i,j,a,b,c);
    rec_j(j+1,p,i,r,a,b,c);
}

void rec_i(int i,int q,int p,int r,int a[],int b[],int c[]) { // i-loop
    if (!(i<q)) return;
    rec_j(0,p,i,r,a,b,c);
    rec_i(i+1,q,p,r,a,b,c);
}
int main() {
    int test_case, p, q, r, i, j, k, a[100001], b[100001], c[100001];
    scanf("%d", &test_case);
    while(test_case--) {
        scanf("%d%d%d", &p, &q, &r);
        sum=0;
        for(i=0;i<p;i++) {
            scanf("%d", &a[i]);
        }
        for(i=0;i<q;i++) {
            scanf("%d", &b[i]);
        }
        for(i=0;i<p;i++) {
            scanf("%d", &c[i]);
        }
        rec_i(0,q,p,r,a,b,c);
        printf("%d\n", sum%1000000007);
    }
    return 0;
}
</code>```

Title: Convert nested loop to recursion

Body:
I have used 3 nested loop. Now i want to convert these loops to recursive.
Also is there a general way to convert a loop into recursive?

#include <stdio.h>

#define f(x, y, z) ((x + y) * (y + z))

int main()
{
    int test_case, p, q, r, i, j, k, a[100001], b[100001], c[100001], sum;
    scanf("%d", &test_case);
    while (test_case--) {
        scanf("%d%d%d", &p, &q, &r);
        sum = 0;
        for (i = 0; i < p; i++) {
            scanf("%d", &a[i]);
        }
        for (i = 0; i < q; i++) {
            scanf("%d", &b[i]);
        }
        for (i = 0; i < p; i++) {
            scanf("%d", &c[i]);
        }
        for (i = 0; i < q; i++) { // I have convert this to recursion.
            for (j = 0; j < p; j++) {
                for (k = 0; k < r; k++) {
                    if (b[i] >= a[j] && b[i] >= c[k]) {
                        sum += f(a[j], b[i], c[k]);
                    }
                }
            }
        }
        printf("%d\n", sum % 1000000007);
    }
    return 0;
}

Body:
Thanks to @Jean-Baptiste Yunès .

I made these changes to my code to convert it to recursive.

#include<stdio.h>
#define f(x, y, z) ((x + y)*(y + z))
int sum=0;
void rec_k(int k,int r,int i,int j,int a[],int b[],int c[]) { // k-loop
    if (!(k<r)) return;
    if (b[i] >= a[j] && b[i] >= c[k]) {
        sum += f(a[j], b[i], c[k]);
    }
    rec_k(k+1,r,i,j,a,b,c);
}

void rec_j(int j,int p,int i,int r,int a[],int b[],int c[]) { // j-loop
    if (!(j<p)) return;
    rec_k(0,r,i,j,a,b,c);
    rec_j(j+1,p,i,r,a,b,c);
}

void rec_i(int i,int q,int p,int r,int a[],int b[],int c[]) { // i-loop
    if (!(i<q)) return;
    rec_j(0,p,i,r,a,b,c);
    rec_i(i+1,q,p,r,a,b,c);
}
int main() {
    int test_case, p, q, r, i, j, k, a[100001], b[100001], c[100001];
    scanf("%d", &test_case);
    while(test_case--) {
        scanf("%d%d%d", &p, &q, &r);
        sum=0;
        for(i=0;i<p;i++) {
            scanf("%d", &a[i]);
        }
        for(i=0;i<q;i++) {
            scanf("%d", &b[i]);
        }
        for(i=0;i<p;i++) {
            scanf("%d", &c[i]);
        }
        rec_i(0,q,p,r,a,b,c);
        printf("%d\n", sum%1000000007);
    }
    return 0;
}


问:
Cant init context with JMS
i have problems with setting up JMS. I tried using Active MQ and OpenJMS but the same error occurs. Iam clueless on how to solve it:

When i execute this:

```<code>import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Hashtable;

public class Main {
    public static void main(String[] args) throws NamingException {
        Hashtable properties = new Hashtable();

        properties.put(Context.INITIAL_CONTEXT_FACTORY,
            "org.exolab.jms.jndi.InitialContextFactory");
        properties.put(Context.PROVIDER_URL, "tcp://localhost:3035/");

        Context context = new InitialContext(properties);
    }
}
</code>```

I get this error:

```<code>Exception in thread "main" javax.naming.NoInitialContextException: Cannot instantiate class: org.exolab.jms.jndi.InitialContextFactory [Root exception is java.lang.ClassNotFoundException: org.exolab.jms.jndi.InitialContextFactory]
</code>```

After some googling i think the problem is that a jar is not in the right classpath, but all the answers already assume that i know which jar and where to store it, but this is not the case here.

Which Jar are they talking about? Where can i get it? Where do i need to store it?

Iam using IntelliJ btw. Could you point me in the right direction?

ActiveMQ is working (http://localhost:8161/ shows webpage of ActiveMQ)

Here are my steps on how i created the project:
File -> New Project -> Java -> SDK1.8 -> Next -> Next -> Project Name: Test -> Right click src folder -> New -> Java Class -> Name: Main -> Paste code from above -> Run -> Error

EDIT: for all the people having the same errors: OpenJMS comes with a libfolder. Install these libraries and it should work

答:
Here is a good explanation on how to add external jars to your project in intellij, and regarding to

Which Jar are they talking about? Where can i get it?

here is a useful web site where you can search jar files using criterias as the name of a class or a package.

I think the jar you are needing is Openjms, here is a link to download it.

Title: Cant init context with JMS

Body:
i have problems with setting up JMS. I tried using Active MQ and OpenJMS but the same error occurs. Iam clueless on how to solve it:

When i execute this:

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Hashtable;

public class Main {
    public static void main(String[] args) throws NamingException {
        Hashtable properties = new Hashtable();

        properties.put(Context.INITIAL_CONTEXT_FACTORY,
            "org.exolab.jms.jndi.InitialContextFactory");
        properties.put(Context.PROVIDER_URL, "tcp://localhost:3035/");

        Context context = new InitialContext(properties);
    }
}

I get this error:

Exception in thread "main" javax.naming.NoInitialContextException: Cannot instantiate class: org.exolab.jms.jndi.InitialContextFactory [Root exception is java.lang.ClassNotFoundException: org.exolab.jms.jndi.InitialContextFactory]

After some googling i think the problem is that a jar is not in the right classpath, but all the answers already assume that i know which jar and where to store it, but this is not the case here.

Which Jar are they talking about? Where can i get it? Where do i need to store it?

Iam using IntelliJ btw. Could you point me in the right direction?

ActiveMQ is working (http://localhost:8161/ shows webpage of ActiveMQ)

Here are my steps on how i created the project:
File -> New Project -> Java -> SDK1.8 -> Next -> Next -> Project Name: Test -> Right click src folder -> New -> Java Class -> Name: Main -> Paste code from above -> Run -> Error

EDIT: for all the people having the same errors: OpenJMS comes with a libfolder. Install these libraries and it should work


问:
HttpContent: An item with the same key has already been added
We have been seeing the following stack trace in our code base:

```<code>System.ArgumentException: An item with the same key has already been added.
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at System.Net.Http.Headers.HttpHeaders.AddHeaderToStore(String name, HeaderStoreItemInfo info)
   at System.Net.Http.Headers.HttpHeaders.SetParsedValue(String name, Object value)
   at System.Net.Http.Headers.HttpContentHeaders.get_ContentLength()
   at System.Net.Http.HttpClientHandler.PrepareAndStartContentUpload(RequestState state)
</code>```

and have narrowed it down to somewhere in our code where we call

```<code>HttpContent.ReadAsStringAsync()
</code>```

When this happens, we are sure the instance of HttpContent is being used by multiple threads, all of which are somehow trying to read the actual content.  Have not yet figured out how reading of the content affects the headers.

If it was possible to perform a deep clone of the HttpContent, assuming all if the content payload has been downloaded, we would have looked into this option.

Anyone run into this and if so, how did you solve it?

Thanks in advance.

答:
It makes no sense to me that your stacktrace is linked to a reading of a response. Seems more probable that before you make the request you have threads fighting to add a header. Perhaps some confusion with asynchronous debugging?
I have seen this when I had a line like this (client is a HttpClient)

client.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip"));

on the code where each thread could execute this, it then became a race condition because I believe the httpclient will check existence before it adds it then if between that time two threads try to add it, it will crash out like this. Depending on your setup you may either need to move something like this into the initialization or throw a lock around it.

Body:
We have been seeing the following stack trace in our code base:

System.ArgumentException: An item with the same key has already been added.
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at System.Net.Http.Headers.HttpHeaders.AddHeaderToStore(String name, HeaderStoreItemInfo info)
   at System.Net.Http.Headers.HttpHeaders.SetParsedValue(String name, Object value)
   at System.Net.Http.Headers.HttpContentHeaders.get_ContentLength()
   at System.Net.Http.HttpClientHandler.PrepareAndStartContentUpload(RequestState state)

and have narrowed it down to somewhere in our code where we call

HttpContent.ReadAsStringAsync()

When this happens, we are sure the instance of HttpContent is being used by multiple threads, all of which are somehow trying to read the actual content.  Have not yet figured out how reading of the content affects the headers.

If it was possible to perform a deep clone of the HttpContent, assuming all if the content payload has been downloaded, we would have looked into this option.

Anyone run into this and if so, how did you solve it?

Thanks in advance.


问:
How do I use client.send_file discord.py
```<code>@my_bot.command()
async def memes():
    await client.send_file(discord.Object(id='321332957690331138'),'1.jpg')
</code>```

I used that and I got error code 401 aka Unauthorized

```<code>my_bot.run(TOKEN)
</code>```

I'm using that to login
All my other commands work and do not output this error.
-I'm quite new to this website so I may have done something wrong-

答:
Your issue is that you need to pass a proper destination (channel in server) as the first parameter. To get the server object from a server ID you can use:

server = client.get_server('321332957690331138')

and to get the default channel of that server you can use:

server.default_channel

So to sum it up you now have:

```<code>await client.send_file(client.get_server('321332957690331138').default_channel, '1.jpg')
</code>```

Hope I helped!

Body:
@my_bot.command()
async def memes():
    await client.send_file(discord.Object(id='321332957690331138'),'1.jpg')

I used that and I got error code 401 aka Unauthorized

my_bot.run(TOKEN)

I'm using that to login
All my other commands work and do not output this error.
-I'm quite new to this website so I may have done something wrong-

Body:
Your issue is that you need to pass a proper destination (channel in server) as the first parameter. To get the server object from a server ID you can use:

server = client.get_server('321332957690331138')

and to get the default channel of that server you can use:

server.default_channel

So to sum it up you now have:

await client.send_file(client.get_server('321332957690331138').default_channel, '1.jpg')

Hope I helped!


问:
Remove rows with the same value across all columns
Suppose I have a data frame (df) that looks like below:

```<code>options(stringsAsFactors = F)

cars <- c("Car1", "Car2", "Car3", "Car4", "Car5", "Car6", "Car7", "Car8", "Car9")
test1 <- c(0,0,3,1,4,2,1,3,0)
test2 <- c(0,0,2,1,0,2,2,5,0)
test3 <- c(1,0,5,1,2,2,6,7,0)
test4 <- c(2,NA,2,1,2,2,1,1,0)
test5 <- c(0,0,1,1,0,2,1,3,0)
test6 <- c(1,0,1,1,1,2,3,4,0)
test7 <- c(3,0,2,1,0,2,1,1,0)

df <- data.frame(cars,test1,test2,test3,test4,test5,test6,test7)

#df
   cars test1 test2 test3 test4 test5 test6 test7
#1 Car1     0     0     1     2     0     1     3
#2 Car2     0     0     0    NA     0     0     0
#3 Car3     3     2     5     2     1     1     2
#4 Car4     1     1     1     1     1     1     1
#5 Car5     4     0     2     2     0     1     0
#6 Car6     2     2     2     2     2     2     2
#7 Car7     1     2     6     1     1     3     1
#8 Car8     3     5     7     1     3     4     1
#9 Car9     0     0     0     0     0     0     0
</code>```

I want to remove any rows that have the same value throughout the entire row (in the example above, I would like to keep rows 1, 3, 5, 7, 8 and remove the rest).

I've figured out how to remove all rows that have zeros

```<code> df$sum <- rowSums(df[,c(2:8)], na.rm = T )
 df.all0 <- df[which(df$sum == 0),]
</code>```

However, this doesn't necessarily work for all the other rows.  Unlike other questions, this question asks to look for duplicates across the entire row, not just specific columns.

Any help would be greatly appreciated!

答:
```<code>keep <- apply(df[2:8], 1, function(x) length(unique(x[!is.na(x)])) != 1)
df[keep, ]

  cars test1 test2 test3 test4 test5 test6 test7
1 Car1     0     0     1     2     0     1     3
3 Car3     3     2     5     2     1     1     2
5 Car5     4     0     2     2     0     1     0
7 Car7     1     2     6     1     1     3     1
8 Car8     3     5     7     1     3     4     1
</code>```

Body:
Suppose I have a data frame (df) that looks like below:

options(stringsAsFactors = F)

cars <- c("Car1", "Car2", "Car3", "Car4", "Car5", "Car6", "Car7", "Car8", "Car9")
test1 <- c(0,0,3,1,4,2,1,3,0)
test2 <- c(0,0,2,1,0,2,2,5,0)
test3 <- c(1,0,5,1,2,2,6,7,0)
test4 <- c(2,NA,2,1,2,2,1,1,0)
test5 <- c(0,0,1,1,0,2,1,3,0)
test6 <- c(1,0,1,1,1,2,3,4,0)
test7 <- c(3,0,2,1,0,2,1,1,0)

df <- data.frame(cars,test1,test2,test3,test4,test5,test6,test7)

#df
   cars test1 test2 test3 test4 test5 test6 test7
#1 Car1     0     0     1     2     0     1     3
#2 Car2     0     0     0    NA     0     0     0
#3 Car3     3     2     5     2     1     1     2
#4 Car4     1     1     1     1     1     1     1
#5 Car5     4     0     2     2     0     1     0
#6 Car6     2     2     2     2     2     2     2
#7 Car7     1     2     6     1     1     3     1
#8 Car8     3     5     7     1     3     4     1
#9 Car9     0     0     0     0     0     0     0

I want to remove any rows that have the same value throughout the entire row (in the example above, I would like to keep rows 1, 3, 5, 7, 8 and remove the rest).

I've figured out how to remove all rows that have zeros

 df$sum <- rowSums(df[,c(2:8)], na.rm = T )
 df.all0 <- df[which(df$sum == 0),]

However, this doesn't necessarily work for all the other rows.  Unlike other questions, this question asks to look for duplicates across the entire row, not just specific columns.

Any help would be greatly appreciated!


问:
How do I create two fields where whichever is filled first will auto-populate the other?
I manage facilities for a large complex and am responsible for issuing and tracking physical keys for our clients here. Keys are printed with specific codes (which match the lock itself), and I have also numbered individual doors on a separate system, to account for the fact that locks often change doors.

In my database I am building in Microsoft Access (sorry, very much a SQL noob), I have a table for spaces (which includes building, room and door numbers), and another separate table for keys (key code, key notch code, master keys, etc.). I also have included a field in the spaces table that references the keys table (via the ID field) to indicate which locks are associated with which doors.

Lastly, I have a log table where I record requests from clients for keys. They may request keys by door number or key code. I want to be able to enter in either the door number or the key code in a form (tied to a query which pulls from both tables) and have it automatically populate the other field accordingly. Presently, I managed a configuration where entering the door number would auto-complete the key field, but I cannot get it to work vise-versa.

This may require some kind of structural change, but I am willing to even delve into directly writing SQL code if needed. I even tried my hand at writing INNER JOIN code, but it was already doing a double-join, and I'm not sure if that is something that can be chained.

Halp!

答:
You can do this by adding some VBA in the AfterUpdate event of the textbox fields.  You can use the same query in each case.

For argument's sake, I'll call the door number textbox "txtDoorNbr", and the key code textbox "txtKeyCode".

First, write a query that pulls all door numbers and key codes.  I think you stated that you already have this query written.

Next, in the AfterUpdate event of txtDoorNbr, you would write something like this:

```<code>Dim db as Database
Dim rec as Recordset

Set db = CurrentDB
Set rec = db.OpenRecordset("Select KeyCode from MyQuery where DoorNumber = " & Me.txtDoorNbr & "")

Me.txtKeyCode = Rec(0)

rec.Close
db.Close
</code>```

In the AfterUpdate event of txtKeyCode, write something very similar:

```<code>Dim db as Database
Dim rec as Recordset

Set db = CurrentDB
Set rec = db.OpenRecordset("Select DoorNbr from MyQuery where KeyCode = " & Me.txtKeyCode & "")

Me.txtDoorNbr = Rec(0)

rec.Close
db.Close
</code>```

That should do it.  Might need to tweak it a bit to account for certain conditions (i.e. an error message if no corresponding record is found in the query, etc...) as well as the actual field names you use in your query, but that's basically the approach.

Body:
You can do this by adding some VBA in the AfterUpdate event of the textbox fields.  You can use the same query in each case.

For argument's sake, I'll call the door number textbox "txtDoorNbr", and the key code textbox "txtKeyCode".

First, write a query that pulls all door numbers and key codes.  I think you stated that you already have this query written.

Next, in the AfterUpdate event of txtDoorNbr, you would write something like this:

Dim db as Database
Dim rec as Recordset

Set db = CurrentDB
Set rec = db.OpenRecordset("Select KeyCode from MyQuery where DoorNumber = " & Me.txtDoorNbr & "")

Me.txtKeyCode = Rec(0)

rec.Close
db.Close

In the AfterUpdate event of txtKeyCode, write something very similar:

Dim db as Database
Dim rec as Recordset

Set db = CurrentDB
Set rec = db.OpenRecordset("Select DoorNbr from MyQuery where KeyCode = " & Me.txtKeyCode & "")

Me.txtDoorNbr = Rec(0)

rec.Close
db.Close

That should do it.  Might need to tweak it a bit to account for certain conditions (i.e. an error message if no corresponding record is found in the query, etc...) as well as the actual field names you use in your query, but that's basically the approach.