问:
Oracle Stored Procedure and Hibernate
I  have to call a stored procedure in pl sql from my db in-memory.
I placed the script in my sql file

```<code>create or replace PROCEDURE delete_from_db
(
abi IN ASSEGNO.ABI_ASSEGNO%type,
cab IN ASSEGNO.CAB_ASSEGNO%type,
nAss IN ASSEGNO.NUMERO_ASSEGNO%type
)
IS
BEGIN
delete FROM ASSEGNO WHERE ABI_ASSEGNO = abi AND CAB_ASSEGNO= cab AND NUMERO_ASSEGNO = nAss;
COMMIT;
END delete_from_db;
</code>```

and I tried to call it from my implementation using Hibernate like this:

@Override
public void deleteAssegno(AssegnoId idAssegno) {

```<code>Session s = getHibernateTemplate().getSessionFactory().openSession();
s.getNamedQuery("delete_from_db").setString(0, idAssegno.getAbiAssegno()).setString(1, idAssegno.getCabAssegno()).setLong(2, idAssegno.getNumeroAssegno());
s.close();
</code>```

}

but when I go with test I've got this error:

```<code>org.hibernate.MappingException: Named query not known: delete_from_db
    at org.hibernate.impl.AbstractSessionImpl.getNamedQuery(AbstractSessionImpl.java:93)
    at org.hibernate.impl.SessionImpl.getNamedQuery(SessionImpl.java:1407)
    at it.bnl.btre.orchass.busin.dao.impl.AssegnoDaoServiceImpl.deleteAssegno(AssegnoDaoServiceImpl.java:75)
    at it.bnl.btre.orchass.busin.facade.service.impl.CancellazioneDocumentaleServiceImpl.deleteFromDb(CancellazioneDocumentaleServiceImpl.java:109)
    at it.bnl.btre.orchass.busin.facade.service.impl.CancellazioneDocumentaleServiceImpl.deleteFromDoc(CancellazioneDocumentaleServiceImpl.java:70)
    at it.bnl.btre.orchass.busin.facade.CancellazioneDocumentaleFacade.handle(CancellazioneDocumentaleFacade.java:32)
    at it.bnl.btre.orchass.busin.facade.test.CancellazioneDocumentaleFacadeTest.testOk(CancellazioneDocumentaleFacadeTest.java:26)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
    at java.lang.reflect.Method.invoke(Method.java:620)
    at junit.framework.TestCase.runTest(TestCase.java:176)
    at junit.framework.TestCase.runBare(TestCase.java:141)
    at junit.framework.TestResult$1.protect(TestResult.java:122)
    at junit.framework.TestResult.runProtected(TestResult.java:142)
    at junit.framework.TestResult.run(TestResult.java:125)
    at junit.framework.TestCase.run(TestCase.java:129)
    at junit.framework.TestSuite.runTest(TestSuite.java:255)
    at junit.framework.TestSuite.run(TestSuite.java:250)
    at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code>```

I searched on internet but all the tutorial were about MySql db or other.

Thank You all!

答:
You need to call the stored procedure directly, e.g. by creating a org.springframework.jdbc.object.StoredProcedure:

```<code>StoredProcedure proc = new StoredProcedure(jdbcTemplate, "delete_from_db");
</code>```

define your parameters:

```<code>proc.declareParameter(new SqlParameter(Types.VARCHAR));
...
</code>```

and finally call the prodedure

```<code>proc.execute(<params>);
</code>```

For a full example, see e.g. Spring JDBC Template for calling Stored Procedures

Title: Oracle Stored Procedure and Hibernate

Body:
I  have to call a stored procedure in pl sql from my db in-memory.
I placed the script in my sql file

create or replace PROCEDURE delete_from_db
(
abi IN ASSEGNO.ABI_ASSEGNO%type,
cab IN ASSEGNO.CAB_ASSEGNO%type,
nAss IN ASSEGNO.NUMERO_ASSEGNO%type
)
IS
BEGIN
delete FROM ASSEGNO WHERE ABI_ASSEGNO = abi AND CAB_ASSEGNO= cab AND NUMERO_ASSEGNO = nAss;
COMMIT;
END delete_from_db;

and I tried to call it from my implementation using Hibernate like this:

@Override
public void deleteAssegno(AssegnoId idAssegno) {

Session s = getHibernateTemplate().getSessionFactory().openSession();
s.getNamedQuery("delete_from_db").setString(0, idAssegno.getAbiAssegno()).setString(1, idAssegno.getCabAssegno()).setLong(2, idAssegno.getNumeroAssegno());
s.close();

}

but when I go with test I've got this error:

org.hibernate.MappingException: Named query not known: delete_from_db
    at org.hibernate.impl.AbstractSessionImpl.getNamedQuery(AbstractSessionImpl.java:93)
    at org.hibernate.impl.SessionImpl.getNamedQuery(SessionImpl.java:1407)
    at it.bnl.btre.orchass.busin.dao.impl.AssegnoDaoServiceImpl.deleteAssegno(AssegnoDaoServiceImpl.java:75)
    at it.bnl.btre.orchass.busin.facade.service.impl.CancellazioneDocumentaleServiceImpl.deleteFromDb(CancellazioneDocumentaleServiceImpl.java:109)
    at it.bnl.btre.orchass.busin.facade.service.impl.CancellazioneDocumentaleServiceImpl.deleteFromDoc(CancellazioneDocumentaleServiceImpl.java:70)
    at it.bnl.btre.orchass.busin.facade.CancellazioneDocumentaleFacade.handle(CancellazioneDocumentaleFacade.java:32)
    at it.bnl.btre.orchass.busin.facade.test.CancellazioneDocumentaleFacadeTest.testOk(CancellazioneDocumentaleFacadeTest.java:26)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
    at java.lang.reflect.Method.invoke(Method.java:620)
    at junit.framework.TestCase.runTest(TestCase.java:176)
    at junit.framework.TestCase.runBare(TestCase.java:141)
    at junit.framework.TestResult$1.protect(TestResult.java:122)
    at junit.framework.TestResult.runProtected(TestResult.java:142)
    at junit.framework.TestResult.run(TestResult.java:125)
    at junit.framework.TestCase.run(TestCase.java:129)
    at junit.framework.TestSuite.runTest(TestSuite.java:255)
    at junit.framework.TestSuite.run(TestSuite.java:250)
    at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

I searched on internet but all the tutorial were about MySql db or other.

Thank You all!

Body:
You need to call the stored procedure directly, e.g. by creating a org.springframework.jdbc.object.StoredProcedure:

StoredProcedure proc = new StoredProcedure(jdbcTemplate, "delete_from_db");

define your parameters:

proc.declareParameter(new SqlParameter(Types.VARCHAR));
...

and finally call the prodedure

proc.execute(<params>);

For a full example, see e.g. Spring JDBC Template for calling Stored Procedures


来源: stackexchange

问:
HTML & CSS progress bar does not stop at the end
I have created this progress bar and I just can't make it stop at the end. Currently its stopping at 70% and gets cleared. Any ideas? Is there any kind of animation setting to stop it at 100%?

.wrap {
  background-color: #f2f2f2;
  height: 10px;
  width: 400px;
  margin: 0 auto;
  position: relative;
  top: 20px;
  margin-bottom: 20px;
}

.bar {
  background: #ffcc00;
  height: 10px;
  width: 0%;
}

.animating {
  -webkit-animation: progress 3s ;
}

@-webkit-keyframes progress {
  0% {
    width: 0%;
  }
  100% {
    width: 70%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <div class="bar animating"></div>
</div></code>```

答: animation-fill-mode: forwards; or -webkit-animation: progress 3s forwards;

ContentLicense: CC BY-SA 3.0


问:
Add key and value to an existing Object in Angular Dynamically
I want to add a value to an existing Object in Angular , I am getting the object from a service call and before saving it to local storage i want to save the time stamp .

I am using Object.assign for the same

The problem is that user is a typed with an Interface and if i add any property to it says that the property is not defined in interface and the interface class is not written by me its by Firebase User info . i donot want to edit that interface or add to it . I want to create a new one property dynamically.

Like Reflection in Java and also adding dynamic Value to object in Javascript.

This is what i have tried

```<code>this.afAuth.authState.subscribe((data) => {
  console.log("Here");
  if (data) {
    const value = Object.assign(data,{TimeStamp : new Date().getTime()}); // this assign is not working even having obj in variable dosent help
    console.log("Value"+JSON.stringify(value));
    localStorage.setItem("user", JSON.stringify(value));
    this.user = data;
    this.service.fetchData(this.user.uid).subscribe((res) => {
      this.comments = res;
    });
  } else {
    this.comments = null;
  }
});
</code>```

Any Help Thanks in Advance

答:
Use the assignment as Mentioned below data.TimeStamp = new Date().getTime() is the right way.

```<code>this.afAuth.authState.subscribe((data) => {
  console.log("Here");
  if (data) {
   data.TimeStamp = new Date().getTime() // this assign is not working even having obj in variable dosent help
    console.log("Value"+JSON.stringify(data));
    localStorage.setItem("user", JSON.stringify(data));
    this.user = data;
    this.service.fetchData(this.user.uid).subscribe((res) => {
      this.comments = res;
    });
  } else {
    this.comments = null;
  }
});
</code>```

Body:
I want to add a value to an existing Object in Angular , I am getting the object from a service call and before saving it to local storage i want to save the time stamp .

I am using Object.assign for the same

The problem is that user is a typed with an Interface and if i add any property to it says that the property is not defined in interface and the interface class is not written by me its by Firebase User info . i donot want to edit that interface or add to it . I want to create a new one property dynamically.

Like Reflection in Java and also adding dynamic Value to object in Javascript.

This is what i have tried

this.afAuth.authState.subscribe((data) => {
  console.log("Here");
  if (data) {
    const value = Object.assign(data,{TimeStamp : new Date().getTime()}); // this assign is not working even having obj in variable dosent help
    console.log("Value"+JSON.stringify(value));
    localStorage.setItem("user", JSON.stringify(value));
    this.user = data;
    this.service.fetchData(this.user.uid).subscribe((res) => {
      this.comments = res;
    });
  } else {
    this.comments = null;
  }
});

Any Help Thanks in Advance

Body:
Use the assignment as Mentioned below data.TimeStamp = new Date().getTime() is the right way.

this.afAuth.authState.subscribe((data) => {
  console.log("Here");
  if (data) {
   data.TimeStamp = new Date().getTime() // this assign is not working even having obj in variable dosent help
    console.log("Value"+JSON.stringify(data));
    localStorage.setItem("user", JSON.stringify(data));
    this.user = data;
    this.service.fetchData(this.user.uid).subscribe((res) => {
      this.comments = res;
    });
  } else {
    this.comments = null;
  }
});


问:
Confirmation instruction on other email with devise
I have two email fields in my model :email and :representative_email I want to send confirmation instructions email on :representative_email (if present or not nil) rather than :email how can I do it with efficiently. And I still want to login with my :email field.</p>

答:
You can create a custom mailer see how to do that, and set the email you want to send to in there.
That is the cleanest solution I could think of, and in the future if you want to change anything you can change it in one place only.</p>


问:
Close other accordions on click (without toggling class)
I'm currently using some code that closely resembles the example this w3schools link, but I can't seem to figure out what to add to the javascript in order to close other tabs when clicking on one of the tabs.

I have gone through a few SO answers regarding closing other accordions on click (such as here) - but they mostly deal with removing classes (".active") from siblings, which (may?) or may not work in this case.

I'm not very familiar with the code but I'm under the impression that it's the JS that's animating the panel sliding down, and not a CSS animation.

Currently my code looks like this : https://jsfiddle.net/joshuacsk/yw7eygxk/
and the JS in question like so:

JS

```<code>var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}
</code>```

Is there any way to close other tabs using the style of code above, or is there any other better way to do this?

答:
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
   for(var j = 0; j < acc.length; j++) {
      acc[j].nextElementSibling.style.maxHeight = null;
      acc[j].classList.remove('active');
    }
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.accordiontext{
  font-family:futura-pt;
  font-weight:300;
  font-size:11;
}
button{
    font-family:futura-pt;
    font-weight: bold;
    font-size: 20px;
    letter-spacing: 0.2em;
    box-sizing:border-box;
    box-shadow: inset 0 0 0 3px #202020;
    position:relative;
    vertical-align:middle;
    border: 0;
}
button.accordion {
    background-color: #fff;
    color: #202020;
    cursor: pointer;
    padding-top: 8px;
    padding-bottom: 8px;
    width: 100%;
    text-align: left;
    background: linear-gradient(to right, #202020 50%, #ffffff 50%);
    background-size: 205% 100%;
    background-position:right bottom;
    transition:all 1s ease;
}

button.accordion.active, button.accordion:hover {
    background-position:left bottom;
    color: #ffffff;

}

/* Style the accordion panel. Note: hidden by default */
div.panel {
    padding: 8px 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.6s ease;
}

button.accordion:after {
    content: '\e009'; /* Unicode character before click  */
    color: #202020;
    font-family: 'squarespace-ui-font';
    font-style: normal;
    font-weight: normal;
    float: right;
    margin-right: 12px;
    transition: all 0.3s ease-in

}

button.accordion.active:after {
    content: "\e006"; /* Unicode character after click */
    color: #ffffff;
}</code>```

<button class="accordion">Titleasdasdasd</button>

Lorem ipsum

<button class="accordion">Titleasdasdasd</button>

Lorem ipsum

<button class="accordion">Titleasdasdasd</button>

Lorem ipsum

<button class="accordion">Titleasdasdasd</button>

Lorem ipsum

```

Body:
I'm currently using some code that closely resembles the example this w3schools link, but I can't seem to figure out what to add to the javascript in order to close other tabs when clicking on one of the tabs.

I have gone through a few SO answers regarding closing other accordions on click (such as here) - but they mostly deal with removing classes (".active") from siblings, which (may?) or may not work in this case.

I'm not very familiar with the code but I'm under the impression that it's the JS that's animating the panel sliding down, and not a CSS animation.

Currently my code looks like this : https://jsfiddle.net/joshuacsk/yw7eygxk/
and the JS in question like so:

JS

var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}

Is there any way to close other tabs using the style of code above, or is there any other better way to do this?

Body:
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
   for(var j = 0; j < acc.length; j++) {
      acc[j].nextElementSibling.style.maxHeight = null;
      acc[j].classList.remove('active');
    }
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}

.accordiontext{
  font-family:futura-pt;
  font-weight:300;
  font-size:11;
}
button{
    font-family:futura-pt;
    font-weight: bold;
    font-size: 20px;
    letter-spacing: 0.2em;
    box-sizing:border-box;
    box-shadow: inset 0 0 0 3px #202020;
    position:relative;
    vertical-align:middle;
    border: 0;
}
button.accordion {
    background-color: #fff;
    color: #202020;
    cursor: pointer;
    padding-top: 8px;
    padding-bottom: 8px;
    width: 100%;
    text-align: left;
    background: linear-gradient(to right, #202020 50%, #ffffff 50%);
    background-size: 205% 100%;
    background-position:right bottom;
    transition:all 1s ease;
}

button.accordion.active, button.accordion:hover {
    background-position:left bottom;
    color: #ffffff;

}

/* Style the accordion panel. Note: hidden by default */
div.panel {
    padding: 8px 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.6s ease;
}

button.accordion:after {
    content: '\e009'; /* Unicode character before click  */
    color: #202020;
    font-family: 'squarespace-ui-font';
    font-style: normal;
    font-weight: normal;
    float: right;
    margin-right: 12px;
    transition: all 0.3s ease-in

}

button.accordion.active:after {
    content: "\e006"; /* Unicode character after click */
    color: #ffffff;
}

<div class="accordionholder">
<button class="accordion">Titleasdasdasd</button> <!--title-->
<div class="panel">
  <p class="accordiontext">Lorem ipsum</p> <!--content-->
</div>

<button class="accordion">Titleasdasdasd</button> <!--title-->
<div class="panel">
  <p  class="accordiontext">Lorem ipsum</p> <!--content-->
</div>

<button class="accordion">Titleasdasdasd</button> <!--title-->
<div class="panel">
  <p  class="accordiontext">Lorem ipsum</p> <!--content-->
</div>

<button class="accordion">Titleasdasdasd</button> <!--title-->
<div class="panel">
  <p  class="accordiontext">Lorem ipsum</p> <!--content-->
</div>
</div>


问:
Python's alphabetical sort file error
i'm new to python & here is my question:
Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.

This is the file:

But soft what light through yonder window breaks

It is the east and Juliet is the sun

Arise fair sun and kill the envious moon

Who is already sick and pale with grief

Desired Output:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

This is my code:

```<code>fname = raw_input("Enter file name: ")
fh = open(fname)

lst = list()

#loop through the text to get the lines
for line in fh:

    line = line.rstrip()

    #loop through the line to get the words
    for word in line:
        words = line.split()

        #if a word is not in the empty list, append it
        if not word in lst: lst.append(word)

lst.sort()
print lst
</code>```

My output:

[' ', 'A', 'B', 'I', 'J', 'W', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'v', 'w', 'y']

If you could tell me what is wrong (to get only the first letters of the words with a space in the beginning instead of the whole words), it would be great..

Note: I want the code using these instructions, not other advanced instructions (to keep my learning sequence)

Thank you

答:
Let's take the code line-by-line

```<code>for line in fh:
    line = line.rstrip()
</code>```

So now our first line contains "But soft what light through yonder window breaks", and it's a string.

```<code>for word in line:
</code>```

ah, but now, we've said "Let's iterate over line (a string) and let word be each part of it when we go through the loop. But line is a complete string! When you iterate over a string like this you get one letter at a time, which is what you're seeing in your results.

Instead, don't have that for loop and just split the line as you were before:

```<code>for line in fh:
    line = line.rstrip()
    words = line.split()
    for word in words:
        if word not in lst:
            lst.append(word)
</code>```

Title: Python's alphabetical sort file error

Body:
i'm new to python & here is my question:
Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.

This is the file:

But soft what light through yonder window breaks

It is the east and Juliet is the sun

Arise fair sun and kill the envious moon

Who is already sick and pale with grief

Desired Output:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

This is my code:

fname = raw_input("Enter file name: ")
fh = open(fname)

lst = list()

#loop through the text to get the lines
for line in fh:

    line = line.rstrip()

    #loop through the line to get the words
    for word in line:
        words = line.split()

        #if a word is not in the empty list, append it
        if not word in lst: lst.append(word)

lst.sort()
print lst

My output:

[' ', 'A', 'B', 'I', 'J', 'W', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'v', 'w', 'y']

If you could tell me what is wrong (to get only the first letters of the words with a space in the beginning instead of the whole words), it would be great..

Note: I want the code using these instructions, not other advanced instructions (to keep my learning sequence)

Thank you

Body:
Let's take the code line-by-line

for line in fh:
    line = line.rstrip()

So now our first line contains "But soft what light through yonder window breaks", and it's a string.

for word in line:

ah, but now, we've said "Let's iterate over line (a string) and let word be each part of it when we go through the loop. But line is a complete string! When you iterate over a string like this you get one letter at a time, which is what you're seeing in your results.

Instead, don't have that for loop and just split the line as you were before:

for line in fh:
    line = line.rstrip()
    words = line.split()
    for word in words:
        if word not in lst:
            lst.append(word)


问:
add app insights trace logging to .net core console application
I've got a .net core console application (not AspNetCore), and I want to add app insights logging that will push out the trace logs to app insights. I have tried using Microsoft.ApplicationInsights.AspNetCore, but when I do:

```<code> factory.AddApplicationInsights(serviceProvider);
</code>```

it throws an error saying it can't find the hosting environment

Unable to resolve service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' while attempting to activate 'Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers.AspNetCoreEnvironmentTelemetryInitializer'.

presumably because this is not an AspNetCore app, but just a pure console app.

Is there a way I can get trace logging pushed to App Insights from within my .net core console app?

答: Use Microsoft.ApplicationInsights as described in https://github.com/Microsoft/ApplicationInsights-aspnetcore/wiki/Getting-Started-for-a-.NET-Core-console-application.</p>

Body:
I've got a .net core console application (not AspNetCore), and I want to add app insights logging that will push out the trace logs to app insights. I have tried using Microsoft.ApplicationInsights.AspNetCore, but when I do:

 factory.AddApplicationInsights(serviceProvider);

it throws an error saying it can't find the hosting environment

Unable to resolve service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' while attempting to activate 'Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers.AspNetCoreEnvironmentTelemetryInitializer'.

presumably because this is not an AspNetCore app, but just a pure console app.

Is there a way I can get trace logging pushed to App Insights from within my .net core console app?


问:
Why is doLayout not working on second click?
I am using the doLayout function on a window.

```<code>    var win = new Ext.Window({
    id: 'site-action-window',
    closeAction: 'hide',
    resizable: false,
    layout: 'fit'
});

    function showWin(f) {
    win.removeAll();
    win.add(f);
    win.setSize(400, 150);
    win.setTitle(localize.addLanguage);
    win.show();
    win.doLayout();
}
</code>```

when I call this function for the first time all is working fine.
but once I make a second call I get an error saying "b.getPositionEl().dom is undefined"
from the fire bug.
can anyone explain?

thanks

答:
Found the problem,

I was destroying the object then trying to call it again from outside the scoop

Thanks for the answers

ContentLicense: CC BY-SA 2.5

Body:
I am using the doLayout function on a window.

    var win = new Ext.Window({
    id: 'site-action-window',
    closeAction: 'hide',
    resizable: false,
    layout: 'fit'
});

    function showWin(f) {
    win.removeAll();
    win.add(f);
    win.setSize(400, 150);
    win.setTitle(localize.addLanguage);
    win.show();
    win.doLayout();
}

when I call this function for the first time all is working fine.
but once I make a second call I get an error saying "b.getPositionEl().dom is undefined"
from the fire bug.
can anyone explain?

thanks


问:
What is an app container on Windows?
I am trying to debug a code which uses NetworkIsolationEnumAppContainers(). The document of the function says,

```<code>"The NetworkIsolationEnumAppContainers function enumerates all of the app containers that have been created in the system."
</code>```

What does app container in the above definition mean? I have some experience with Linux container technologies (LXC particularly). Are they the same (or similar conceptually)? Can you point me to a document which provides as in depth technical description of app containers.

答:
AppContainers are a sandbox mechanism which control what resources an UWP app can access or not. The UWP app have only access to a limited part of the file system, registry etc... The app container is also enforcing some rules about the network connectivity. For example, UWP apps cannot access the localhost. The network capabilities are driven by the manifest of the UWP app which must declare what it want to do (client, client+server). Based on the declaration of the app, the server will allow or not the network.

You should be able to find more detailed information here:

Fiddler and Win8+ Immersive applications (old name for UWP)

How to set network capabilities for UWP apps

Title: What is an app container on Windows?

Body:
I am trying to debug a code which uses NetworkIsolationEnumAppContainers(). The document of the function says,

"The NetworkIsolationEnumAppContainers function enumerates all of the app containers that have been created in the system."

What does app container in the above definition mean? I have some experience with Linux container technologies (LXC particularly). Are they the same (or similar conceptually)? Can you point me to a document which provides as in depth technical description of app containers.


问:
How to implement the Selenium HTML5 Drag and Drop workaround in Python
Using Selenium and Python, the goal is to drag and drop an element to a target, as shown with this HTML5 test website.  Selenium should be able to do that too with a simple call to an ActionChains(driver) method, as shown here in section 3.3: .  However, to my dismay it appears that the functionality is not implemented for HTML5 based websites, as explained in a selenium bug report.

Ok, time for a solution, and someone appears to have found a nice workaround.

Problem is an error that does not make sense.  Here is my implementation:

```<code>import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# drag and drop not working with ActionChains and HTML5
from selenium.webdriver import ActionChains

class PythonDragAndDrop(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_search(self):

        driver = self.driver
        driver.get("http://html5demos.com/drag")
        self.assertIn("HTML5 Demo: Drag and drop", driver.title)

    # workaround
        jquery_url = "http://code.jquery.com/jquery-1.11.2.min.js"
        driver.set_script_timeout(30)

        # load jquery helper
        with open("/Users/me/Desktop/dragNDrop/jquery_load_helper.js") as f:
            load_jquery_js = f.read()

        # load drag and drop helper
        with open("/Users/me/Desktop/dragNDrop/drag_and_drop_helper.js") as f:
            drag_and_drop_js = f.read()

        # load jquery
        driver.execute_async_script(load_jquery_js, jquery_url)

        # perform drag&drop
        driver.execute_script(drag_and_drop_js + "$('#one').simulateDragDrop({ dropTarget: '#bin'});")

    def tearDown(self):
        self.driver.close() # closes one browser tab
        # driver.quit() # closes browser and all tabs

if __name__ == "__main__":
    unittest.main()
</code>```

The result is an error:

```<code>Traceback (most recent call last):
File "testDragAndDrop.py", line 35, in test_search
driver.execute_async_script(load_jquery_js, jquery_url)
File "/Library/Python/2.7/site-packages/selenium-2.45.0-py2.7.egg/selenium/webdriver/remote/webdriver.py", line 418, in execute_async_script
{'script': script, 'args':converted_args})['value']
File "/Library/Python/2.7/site-packages/selenium-2.45.0-py2.7.egg/selenium/webdriver/remote/webdriver.py", line 175, in execute
self.error_handler.check_response(response)
File "/Library/Python/2.7/site-packages/selenium-2.45.0-py2.7.egg/selenium/webdriver/remote/errorhandler.py", line 166, in check_response
raise exception_class(message, screen, stacktrace)
WebDriverException: Message: illegal character
Stacktrace:
    at handleEvaluateEvent (http://html5demos.com/drag:69)
</code>```

What is most likely causing this error, and how might I fix it?

Note: Using Python in Xcode to test Drag and Drop functionality in Firefox.

答:
Content of jquery_load_helper.js</p>

```<code>/** dynamically load jQuery */
(function(jqueryUrl, callback) {
    if (typeof jqueryUrl != 'string') {
        jqueryUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
    }
    if (typeof jQuery == 'undefined') {
        var script = document.createElement('script');
        var head = document.getElementsByTagName('head')[0];
        var done = false;
        script.onload = script.onreadystatechange = (function() {
            if (!done && (!this.readyState || this.readyState == 'loaded'
                    || this.readyState == 'complete')) {
                done = true;
                script.onload = script.onreadystatechange = null;
                head.removeChild(script);
                callback();
            }
        });
        script.src = jqueryUrl;
        head.appendChild(script);
    }
    else {
        callback();
    }
})(arguments[0], arguments[arguments.length - 1]);
</code>```

Body:
Using Selenium and Python, the goal is to drag and drop an element to a target, as shown with this HTML5 test website.  Selenium should be able to do that too with a simple call to an ActionChains(driver) method, as shown here in section 3.3: .  However, to my dismay it appears that the functionality is not implemented for HTML5 based websites, as explained in a selenium bug report.

Ok, time for a solution, and someone appears to have found a nice workaround.

Problem is an error that does not make sense.  Here is my implementation:

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# drag and drop not working with ActionChains and HTML5
from selenium.webdriver import ActionChains

class PythonDragAndDrop(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_search(self):

        driver = self.driver
        driver.get("http://html5demos.com/drag")
        self.assertIn("HTML5 Demo: Drag and drop", driver.title)

    # workaround
        jquery_url = "http://code.jquery.com/jquery-1.11.2.min.js"
        driver.set_script_timeout(30)

        # load jquery helper
        with open("/Users/me/Desktop/dragNDrop/jquery_load_helper.js") as f:
            load_jquery_js = f.read()

        # load drag and drop helper
        with open("/Users/me/Desktop/dragNDrop/drag_and_drop_helper.js") as f:
            drag_and_drop_js = f.read()

        # load jquery
        driver.execute_async_script(load_jquery_js, jquery_url)

        # perform drag&drop
        driver.execute_script(drag_and_drop_js + "$('#one').simulateDragDrop({ dropTarget: '#bin'});")

    def tearDown(self):
        self.driver.close() # closes one browser tab
        # driver.quit() # closes browser and all tabs

if __name__ == "__main__":
    unittest.main()

The result is an error:

Traceback (most recent call last):
File "testDragAndDrop.py", line 35, in test_search
driver.execute_async_script(load_jquery_js, jquery_url)
File "/Library/Python/2.7/site-packages/selenium-2.45.0-py2.7.egg/selenium/webdriver/remote/webdriver.py", line 418, in execute_async_script
{'script': script, 'args':converted_args})['value']
File "/Library/Python/2.7/site-packages/selenium-2.45.0-py2.7.egg/selenium/webdriver/remote/webdriver.py", line 175, in execute
self.error_handler.check_response(response)
File "/Library/Python/2.7/site-packages/selenium-2.45.0-py2.7.egg/selenium/webdriver/remote/errorhandler.py", line 166, in check_response
raise exception_class(message, screen, stacktrace)
WebDriverException: Message: illegal character
Stacktrace:
    at handleEvaluateEvent (http://html5demos.com/drag:69)

What is most likely causing this error, and how might I fix it?

Note: Using Python in Xcode to test Drag and Drop functionality in Firefox.

Body:
Content of jquery_load_helper.js

/** dynamically load jQuery */
(function(jqueryUrl, callback) {
    if (typeof jqueryUrl != 'string') {
        jqueryUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
    }
    if (typeof jQuery == 'undefined') {
        var script = document.createElement('script');
        var head = document.getElementsByTagName('head')[0];
        var done = false;
        script.onload = script.onreadystatechange = (function() {
            if (!done && (!this.readyState || this.readyState == 'loaded'
                    || this.readyState == 'complete')) {
                done = true;
                script.onload = script.onreadystatechange = null;
                head.removeChild(script);
                callback();
            }
        });
        script.src = jqueryUrl;
        head.appendChild(script);
    }
    else {
        callback();
    }
})(arguments[0], arguments[arguments.length - 1]);

ContentLicense: CC BY-SA 4.0


答:
Try this:

```<code>with open('test.txt') as f:
    words = []
    for line in f:
        if line:
            words.extend(line.split())

    print(sorted(set(words)))
</code>```

Output:

```<code>['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
</code>```

Title: Python's alphabetical sort file error

Body:
Try this:

with open('test.txt') as f:
    words = []
    for line in f:
        if line:
            words.extend(line.split())

    print(sorted(set(words)))

Output:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']


问:
Comparison of variable to all other variables in data frame
I want to check how close is one variable to all of the other variables in a data frame. I want to do this by counting the times they have the same value for the same row (i.e. same observation). For instance, in the mtcars dataset, the variables gear and carb have 7 observations in which they have the same value in the same row (i.e. same car).

I have tried the following, which yields a closeness_matrix. However, the results seem to be non-sensical. Any idea what is not working?

PS: I also tried to use mapply, which I guess it would be faster, but it didn’t work so I ended up with the nested loop.

MWE:

```<code>cols_ls <- colnames(mtcars)

closeness_matrix <- matrix(nrow = ncol(mtcars),
                            ncol = ncol(mtcars))

row.names(closeness_matrix) <- cols_ls; colnames(closeness_matrix) <- cols_ls

for (i in 1:length(cols_ls)){

  for (j in i:length(cols_ls)){

    closeness_matrix[i,j] <- sum(duplicated(mtcars[,c(i,j), with = FALSE])==TRUE)

  }
}
</code>```

答:
I guess the following will do it (but i'm sure there is a smarter way):

```<code>closenessFunc<-function(v1,M){
      apply(M, 2, function(x,v2) {
        sum(x==v)
      }, v2=v1)
    }
apply(mtcars, MARGIN = 2, closenessFunc, M=mtcars)
</code>```

output:

```<code>     mpg cyl disp hp drat wt qsec vs am gear carb
mpg   32   0    0  0    0  0    0  0  0    0    0
cyl    0  32    0  0    0  0    0  0  0    8    2
disp   0   0   32  0    0  0    0  0  0    0    0
hp     0   0    0 32    0  0    0  0  0    0    0
drat   0   0    0  0   32  0    0  0  0    1    0
wt     0   0    0  0    0 32    0  0  0    0    0
qsec   0   0    0  0    0  0   32  0  0    0    0
vs     0   0    0  0    0  0    0 32 19    0    7
am     0   0    0  0    0  0    0 19 32    0    4
gear   0   8    0  0    1  0    0  0  0   32    7
carb   0   2    0  0    0  0    0  7  4    7   32
</code>```

Body:
I want to check how close is one variable to all of the other variables in a data frame. I want to do this by counting the times they have the same value for the same row (i.e. same observation). For instance, in the mtcars dataset, the variables gear and carb have 7 observations in which they have the same value in the same row (i.e. same car).

I have tried the following, which yields a closeness_matrix. However, the results seem to be non-sensical. Any idea what is not working?

PS: I also tried to use mapply, which I guess it would be faster, but it didn’t work so I ended up with the nested loop.

MWE:

cols_ls <- colnames(mtcars)

closeness_matrix <- matrix(nrow = ncol(mtcars),
                            ncol = ncol(mtcars))

row.names(closeness_matrix) <- cols_ls; colnames(closeness_matrix) <- cols_ls

for (i in 1:length(cols_ls)){

  for (j in i:length(cols_ls)){

    closeness_matrix[i,j] <- sum(duplicated(mtcars[,c(i,j), with = FALSE])==TRUE)

  }
}

Body:
I guess the following will do it (but i'm sure there is a smarter way):

closenessFunc<-function(v1,M){
      apply(M, 2, function(x,v2) {
        sum(x==v)
      }, v2=v1)
    }
apply(mtcars, MARGIN = 2, closenessFunc, M=mtcars)

output:

     mpg cyl disp hp drat wt qsec vs am gear carb
mpg   32   0    0  0    0  0    0  0  0    0    0
cyl    0  32    0  0    0  0    0  0  0    8    2
disp   0   0   32  0    0  0    0  0  0    0    0
hp     0   0    0 32    0  0    0  0  0    0    0
drat   0   0    0  0   32  0    0  0  0    1    0
wt     0   0    0  0    0 32    0  0  0    0    0
qsec   0   0    0  0    0  0   32  0  0    0    0
vs     0   0    0  0    0  0    0 32 19    0    7
am     0   0    0  0    0  0    0 19 32    0    4
gear   0   8    0  0    1  0    0  0  0   32    7
carb   0   2    0  0    0  0    0  7  4    7   32


问:
Gettitng ReferenceError: "CryptoJS" is not defined
I have written javascript to for RSASHA256 but gettitng error crypto.js is not defined.</p>

```<code> function aaa(message,secret) {
     <script src="http://crypto-
      js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha256.js"></script>;
     <script src="http://crypto-
      js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js"></script>;
     var hash = CryptoJS.HmacSHA256("Message", "secret");
     var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
     document.write(hashInBase64);
}
</code>```

答: You need to set the

Body:
I have written javascript to for RSASHA256 but gettitng error crypto.js is not defined.

 function aaa(message,secret) {
     ;
     ;
     var hash = CryptoJS.HmacSHA256("Message", "secret");
     var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
     document.write(hashInBase64);
}

Body:
You need to set the <script> tags inside your HTML.

 function aaa(message,secret) {
     var hash = CryptoJS.HmacSHA256("Message", "secret");
     var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
     document.write(hashInBase64);
 }

   <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.js">


问:
Using ReactiveFormsModule on module lazyloaded
I have this main module in Angular 4:

```<code>@NgModule({
    imports: [
        //.. other modules
        ReactiveFormsModule,
    ],
    declarations: [
        AppComponent,
        ...routingComponents,
    ],
    providers: [
        ...routingGuards,
    ],
    exports: [
        ReactiveFormsModule,
    ],
    bootstrap: [AppComponent]
})

export class AppModule { }
</code>```

I also have another module, AdminModule, that is lazy loaded from this main AppModule. On the AdminModule I have some routes where I also use the reactive form. However, when I try to create a new form I keep getting errors like these:

Error: Template parse errors: Can't bind to 'formGroup' since it isn't a known property of 'form'.

Trying to fix this problem, I saw that I had to export the ReactiveFormsModule from the main module in order to use with other modules, but I'm doing so and still getting the error. What am I doing wrong in here?

答:
We needed to import ReactiveFormsModule FormsModule in AdminModule in order to make all directives to work:

```<code>import { FormsModule, ReactiveFormsModule } from '@angular/forms';
...

@NgModule({
  imports: [
    ...,
    FormsModule,    //added here too
    ReactiveFormsModule //added here too
  ],
  declarations: [...],
  providers: [...]
})

export class AdminModule{}
</code>```

Body:
I have this main module in Angular 4:

@NgModule({
    imports: [
        //.. other modules
        ReactiveFormsModule,
    ],
    declarations: [
        AppComponent,
        ...routingComponents,
    ],
    providers: [
        ...routingGuards,
    ],
    exports: [
        ReactiveFormsModule,
    ],
    bootstrap: [AppComponent]
})

export class AppModule { }

I also have another module, AdminModule, that is lazy loaded from this main AppModule. On the AdminModule I have some routes where I also use the reactive form. However, when I try to create a new form I keep getting errors like these:

Error: Template parse errors: Can't bind to 'formGroup' since it isn't a known property of 'form'.

Trying to fix this problem, I saw that I had to export the ReactiveFormsModule from the main module in order to use with other modules, but I'm doing so and still getting the error. What am I doing wrong in here?

Body:
We needed to import ReactiveFormsModule FormsModule in AdminModule in order to make all directives to work:

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
...

@NgModule({
  imports: [
    ...,
    FormsModule,    //added here too
    ReactiveFormsModule //added here too
  ],
  declarations: [...],
  providers: [...]
})

export class AdminModule{}


问:
syntax error while specifying DOCTYPE
I am getting a syntax error while using the DOCTYPE  ...
actually  i have a base page and loading two iframes in it , and the doctype is specifyed in one of these iframes ..
I have some php codes before starting the html code ...

The firebug error is shown below

Thanks in advance

答:
Last time I saw this, it was caused by an attempt to load a JavaScript but the URL was pointing to an HTML document.

Check your script srcs.

Title: syntax error while specifying DOCTYPE


问:
What is the fastest way to select n random lines from csv file to list?
I have the following method:

```<code>ids = random.sample(list(map(int, open(file_path))), 10)
</code>```

that returns a list of 10 random ints.

How to speed up it? What is the other way to do this?

答:
it seems to me that the hangup is always going to be finding the length of the file. See How to get line count cheaply in Python? for that.

then you can do

```<code>import random

lines = random.sample(range(length_of_file), 10)

with open(file) as f:
    lines_from_file = [f.readline(line) for line in lines]
</code>```

or something like that. How does that compare speedwise?

Body:
I have the following method:

ids = random.sample(list(map(int, open(file_path))), 10)

that returns a list of 10 random ints.

How to speed up it? What is the other way to do this?

Body:
it seems to me that the hangup is always going to be finding the length of the file. See How to get line count cheaply in Python? for that.

then you can do

import random

lines = random.sample(range(length_of_file), 10)

with open(file) as f:
    lines_from_file = [f.readline(line) for line in lines]

or something like that. How does that compare speedwise?


问:
Why static initializer allow re-initialization of static variable in Java?
I am studying static initializers in Java. I came through a source code as given below:

```<code>    public class A {
       private static int count = 5;
       final static int STEP = 10;
       boolean alive;
       static {
         count = 1;
       }
       public static void main(String[] args) {
          A a = new A();
          System.out.println(A.count);
       }
    }
</code>```

My question is that why the compiler is not complaining about the variable count being reassigned the value 1 in count = 1 in the static initializer block. I know that Java allows forward referencing as long as declaration-before-read rule (i.e. any identifier should not be read before declaration) is followed which is for all initializers and if not then the reference (or identifier) must come on the left-hand side of the assignment. I also know that if multiple static initializer expressions and static field initializer blocks are written in a class then their order of execution is sequential.

According to me the flow of execution should be: The class is loaded and then all the static initializer (expressions and blocks) are executed in sequence, due to which the count will be initialized to value 5 and then the default constructor will be executed calling the super() and initializing the instance variable alive to default value. But why it is not throwing an error that static variable count has been re-initialized (as it is not the case of forward reference), instead, it gives the output 1.
Does that mean that we can re-initialize static variables through static initializer blocks?

答:
Since your class variable is appearing before use, that is ok.

Here is the language specification#Static Initializers for the same

A static initializer declared in a class is executed when the class is initialized (§12.4.2). Together with any field initializers for class variables (§8.3.2), static initializers may be used to initialize the class variables of the class.

Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope. See §8.3.3 for the precise rules governing forward reference to class variables.

Body:
I am studying static initializers in Java. I came through a source code as given below:

    public class A {
       private static int count = 5;
       final static int STEP = 10;
       boolean alive;
       static {
         count = 1;
       }
       public static void main(String[] args) {
          A a = new A();
          System.out.println(A.count);
       }
    }

My question is that why the compiler is not complaining about the variable count being reassigned the value 1 in count = 1 in the static initializer block. I know that Java allows forward referencing as long as declaration-before-read rule (i.e. any identifier should not be read before declaration) is followed which is for all initializers and if not then the reference (or identifier) must come on the left-hand side of the assignment. I also know that if multiple static initializer expressions and static field initializer blocks are written in a class then their order of execution is sequential.

According to me the flow of execution should be: The class is loaded and then all the static initializer (expressions and blocks) are executed in sequence, due to which the count will be initialized to value 5 and then the default constructor will be executed calling the super() and initializing the instance variable alive to default value. But why it is not throwing an error that static variable count has been re-initialized (as it is not the case of forward reference), instead, it gives the output 1.
Does that mean that we can re-initialize static variables through static initializer blocks?


问:
Json Date to C# MVC date
This may be a possible duplicate, but I am posting this after searching a lot and trying various method.

I am passing model as a JsonResult in ajax success and binding the value to controls. In my model I have a datetime property which gets a proper date value but in my ajax success it gets converted to something like this '/Date(1493749800000)/' .

Now when I want to use the Datetime value for further function in Datetime property of my MVC model, it gets null.

Please do suggest a way I can handle this scenario.

Things I tried:
Date.Parse(), Json.Parse(), string.Replace()

Title: Json Date to C# MVC date

Body:
var input = '/Date(464560200000)/'
var a = /\/Date\((\d*)\)\//.exec(input);
var d = new Date(+a[1]);


问:
Passing GET params to a Django View internally
I am trying to call a Django view internally from another view:

```<code>response = BlogViewSet.as_view({'get':'list'})(request)
</code>```

BlogViewSet is actually a rest framework view.
The above code works and I can access response.data but what I actually want to do is pass in some GET params to do some filtering. I tried the following but it didn't work:

```<code>response = BlogViewSet.as_view({'get':'list'})(request, my_param=something)
</code>```

I realise I could modify request to add GET params but it seems wrong to modify it as it might be used later in the view.

答:
Calling one view from another is a bad practice.

Why not request url of the view instead of calling the view itself.

```<code>r = requests.get("<url_to_access_view>", params={})
</code>```

Body:
I am trying to call a Django view internally from another view:

response = BlogViewSet.as_view({'get':'list'})(request)

BlogViewSet is actually a rest framework view.
The above code works and I can access response.data but what I actually want to do is pass in some GET params to do some filtering. I tried the following but it didn't work:

response = BlogViewSet.as_view({'get':'list'})(request, my_param=something)

I realise I could modify request to add GET params but it seems wrong to modify it as it might be used later in the view.

Body:
Calling one view from another is a bad practice.

Why not request url of the view instead of calling the view itself.

r = requests.get("<url_to_access_view>", params={})


问:
Coerce dataframe groups to list
I have a dataframe such as

```<code>id <- c(1,1,1,2,2,3,3,3,3)
element <- c(25122,356,4454,5432,342340,12443,12354,123536,234134)
df <- data.frame(id = as.factor(id), element)
</code>```

I would like to create a list of the id groups with their corresponding elements such as:

```<code>dflist <- list(c(25122,356,4454), c(5432,342340), c(12443,12354,123536,234134))
</code>```

答:
Here's a solution with tapply:

```<code>library(magrittr)
df %$% tapply(element,id,list)
</code>```

(elements are named with id, add %>% unname if it's an issue)

Title: Coerce dataframe groups to list

Body:
I have a dataframe such as

id <- c(1,1,1,2,2,3,3,3,3)
element <- c(25122,356,4454,5432,342340,12443,12354,123536,234134)
df <- data.frame(id = as.factor(id), element)

I would like to create a list of the id groups with their corresponding elements such as:

dflist <- list(c(25122,356,4454), c(5432,342340), c(12443,12354,123536,234134))

Body:
Here's a solution with tapply:

library(magrittr)
df %$% tapply(element,id,list)

(elements are named with id, add %>% unname if it's an issue)


问:
How to execute a Java method multiply in same second?
I want to limit access my server per second by ip,  How can I  execute a Java method in same second to test my code?</p>

答:
If your question is to run the same java method multiple times in parallel or at the same time, you can use multi-threading.

Multi-threading main purpose is used to perform
1. multiple tasks independently
2. multiple tasks at the same time independently.

Follow this link for further info.
https://www.javatpoint.com/multithreading-in-java


问:
Must I call (admob) loadAd in onCreate?
I'm trying to use admob in an android app.  Very simple code, taken right from the examples.

```<code>@Override
public void onCreate(Bundle savedInstanceState)
{
...stuff...

    MobileAds.initialize(this, "{my id}");
    mInterstitialAd = new InterstitialAd(this);
    mInterstitialAd.setAdUnitId("{my ad unit id}");

    AdRequest aRequest;
    aRequest = new AdRequest.Builder().build();
    mInterstitialAd.loadAd(aRequest);
}
</code>```

...and it works fine.

HOWEVER: I don't want this code here.  I want it to be somewhere else where I explicitely say "Initialize Ads."

When I do that, loadAd crashes, every single time.  The only place I can successfully call it is in OnCreate, or in a callback defined in OnCreate.  Is this a real thing, or is it some threading issue?  Is the game crashing because loadAd is blocking the UI thread or something like that?

I'm not so great at Java (I'm a c++ guy)... if that's the problem, how can I throw the whole shebang into another thread?

答:
Okay, I solved my own problem.  Putting this here for posterity in case anyone else ever needs this solution.

loadAd and showAd MUST happen in the UI thread.  If you invoke them in another thread, that's the crash.

So, it's a very simple thing to wrap those calls like so:

```<code>    runOnUiThread(new Runnable()
    {
        @Override
        public void run()
        {
            AdRequest aRequest;
            aRequest = new AdRequest.Builder().build();
            mInterstitialAd.loadAd(aRequest);
        }
    });
</code>```

...and add whatever helper infrastructure you might need if you need that call to act synchronous.

Title: Must I call (admob) loadAd in onCreate?

Body:
I'm trying to use admob in an android app.  Very simple code, taken right from the examples.

@Override
public void onCreate(Bundle savedInstanceState)
{
...stuff...

    MobileAds.initialize(this, "{my id}");
    mInterstitialAd = new InterstitialAd(this);
    mInterstitialAd.setAdUnitId("{my ad unit id}");

    AdRequest aRequest;
    aRequest = new AdRequest.Builder().build();
    mInterstitialAd.loadAd(aRequest);
}

...and it works fine.

HOWEVER: I don't want this code here.  I want it to be somewhere else where I explicitely say "Initialize Ads."

When I do that, loadAd crashes, every single time.  The only place I can successfully call it is in OnCreate, or in a callback defined in OnCreate.  Is this a real thing, or is it some threading issue?  Is the game crashing because loadAd is blocking the UI thread or something like that?

I'm not so great at Java (I'm a c++ guy)... if that's the problem, how can I throw the whole shebang into another thread?

Body:
Okay, I solved my own problem.  Putting this here for posterity in case anyone else ever needs this solution.

loadAd and showAd MUST happen in the UI thread.  If you invoke them in another thread, that's the crash.

So, it's a very simple thing to wrap those calls like so:

    runOnUiThread(new Runnable()
    {
        @Override
        public void run()
        {
            AdRequest aRequest;
            aRequest = new AdRequest.Builder().build();
            mInterstitialAd.loadAd(aRequest);
        }
    });

...and add whatever helper infrastructure you might need if you need that call to act synchronous.


问:
Get Specific class with Jquery/ JavaScript
I have got a div containing some html elements. They all have a class named

class="fileItem read write".

But there could be an Element with

class="fileItem read write selected".

Now I want to get this element with the additional 'selected' tag and edit this. Currently I have an in JQuery

```<code>$(".fileItem").click(function(){
    // Code
});
</code>```

which detect an click on one of these fileItems.

Here I want to edit style tag of the element with 'selected' tag. So is there something where I can say get all by class and select the on with "selected"?

答:
Just chain the desired class names like you would do in a CSS selector:</p>

```<code>$(".fileItem.selected").click(function() {
    // do stuff
});'
</code>```

Body:
I have got a div containing some html elements. They all have a class named

class="fileItem read write".

But there could be an Element with

class="fileItem read write selected".

Now I want to get this element with the additional 'selected' tag and edit this. Currently I have an in JQuery

$(".fileItem").click(function(){
    // Code
});

which detect an click on one of these fileItems.

Here I want to edit style tag of the element with 'selected' tag. So is there something where I can say get all by class and select the on with "selected"?

Body:
Just chain the desired class names like you would do in a CSS selector:

$(".fileItem.selected").click(function() {
    // do stuff
});'


问:
Angular - Wait until I receive data before loading template
I have a component that renders several components dynamically, with this template:

```<code><div [saJquiAccordion]="{active: group.value['collapsed']}" *ngFor="let group of filterGroupsTemplate | keysCheckDisplay;">
    <div>
        <h4>{{group.key | i18n}}</h4>
        <form id="ibo-{{group.key}}" class="form-horizontal" autocomplete="off" style="overflow: initial">
            <fieldset *ngFor="let field of group.value | keys">
                <ng-container *ngComponentOutlet="fieldSets[field.value.template];
                                    ngModuleFactory: smartadminFormsModule;"></ng-container>
            </fieldset>
        </form>
    </div>
</div>
</code>```

The thing is that the data needed to fill those components I'm getting it from an API call:

```<code>      this.getFiltersSubscription = this.getFilters().subscribe(
            (filters) => {
                this.filters = filters;
                log.info('API CALL. getting filters');

                // Sending data to fieldform components
                this.iboService.updateIBOsRankList(filters['iboRank'].data);
                this.iboService.updateIBOsNewsletterOptions(filters['iboNewsletter'].data);
                this.iboService.updateIBOsTotalOrders(filters['iboTotalOrders'].data);
            }
        );
</code>```

So, once I have my data, I'm triggering a service Observable which my components are subscribed to, and they will then process the gathered data.

PROBLEM

If the API call is made before all components load, I'll be triggering these service methods passing data but nobody will be subscribed to those Observables.

An approach would be to:

Load data first, and only when I have the data loaded, I'll render the template and, therefore, render all these components dynamically and only then I'll be triggering these service methods (Observables).

I don't want to make an API call for each component, because it can be like 60 components, I'll rather loose abstraction fo code but I prefer to do something like this:

```<code>// Listens to field's init and creates the fieldset triggering a service call that will be listened by the field component
        this.iboService.initIBOsFilters$.subscribe(
            (fieldName) => {
                if (fieldName === 'IBOsRankSelectorFieldComponent') {
                    log.data('inside initIBOsFilters$ subscription, calling updateIBOsFilters()', fieldName);
                    this.iboService.updateIBOsRankList(this.filters['iboRank'].data); // HERE I'M PASSING DATA TO THE COMPONENT RENDERED DYNAMICALY. BUT IF this.filters IS UNDEFINED, IT BREAKS
                }
            }
        );
</code>```

In order to do this, I need to ensure that this.filters is defined and thus, I come to conclusion:

How can I wait until API call ends and this.filters is defined before rendering my template html?

Sorry if my question is a bit long, if you need any more details just let me know.

Thanks!

答:
After studying the different approaches that people gave me, I found the solution on the async pipe. But, it took me a while to understand how to implement it.

Solution:

```<code>// Declaring the Promise, yes! Promise!
filtersLoaded: Promise<boolean>;

// Later in the Component, where I gather the data, I set the resolve() of the Promise
this.getFiltersSubscription = this.getFilters().subscribe(
    (filters) => {
        this.filters = filters;
        log.info('API CALL. getting filters');

        this.filtersLoaded = Promise.resolve(true); // Setting the Promise as resolved after I have the needed data
    }
);

// In this listener triggered by the dynamic components when instanced,
// I pass the data, knowing that is defined because of the template change

// Listens to field's init and creates the fieldset triggering a service call
// that will be listened by the field component
this.iboService.initIBOsFilters$.subscribe(
    (fieldName) => {
        if (fieldName === 'IBOsRankSelectorFieldComponent') {
            log.data('inside initIBOsFilters$ subscription, calling updateIBOsFilters()', fieldName);
            this.iboService.updateIBOsRankList(this.filters['iboRank'].data);
        }
    }
);
</code>```

In the template, I use the async pipe that needs an Observable or a Promise

```<code><div *ngIf="filtersLoaded | async">
    <div [saJquiAccordion]="{active: group.value['collapsed']}" *ngFor="let group of filterGroupsTemplate | keysCheckDisplay;">
        <div>
            <h4>{{group.key | i18n}}</h4>
            <form id="ibo-{{group.key}}" class="form-horizontal" autocomplete="off" style="overflow: initial">
                <fieldset *ngFor="let field of group.value | keys">
                    <ng-container *ngComponentOutlet="fieldSets[field.value.template];
                                    ngModuleFactory: smartadminFormsModule;"></ng-container>
                </fieldset>
            </form>
        </div>
    </div>
</div>
</code>```

NOTE:

async pipe need an Observable or a Promise from what I understood, that's why the only way to make it work was by creating a Promise

I didn't use the resolver approach because it's used when you arrive to the component through Angular's routing. This component is part of a larger component and it's not instanced through routing like any other normal component. (Tried that approach though, worked a bit with it, didn't do the job)

Body:
I have a component that renders several components dynamically, with this template:

{{group.key | i18n}}

        <form id="ibo-{{group.key}}" class="form-horizontal" autocomplete="off" style="overflow: initial">
            <fieldset *ngFor="let field of group.value | keys">
                <ng-container *ngComponentOutlet="fieldSets[field.value.template];
                                    ngModuleFactory: smartadminFormsModule;"></ng-container>
            </fieldset>
        </form>

The thing is that the data needed to fill those components I'm getting it from an API call:

      this.getFiltersSubscription = this.getFilters().subscribe(
            (filters) => {
                this.filters = filters;
                log.info('API CALL. getting filters');

                // Sending data to fieldform components
                this.iboService.updateIBOsRankList(filters['iboRank'].data);
                this.iboService.updateIBOsNewsletterOptions(filters['iboNewsletter'].data);
                this.iboService.updateIBOsTotalOrders(filters['iboTotalOrders'].data);
            }
        );

So, once I have my data, I'm triggering a service Observable which my components are subscribed to, and they will then process the gathered data.

PROBLEM

If the API call is made before all components load, I'll be triggering these service methods passing data but nobody will be subscribed to those Observables.

An approach would be to:

Load data first, and only when I have the data loaded, I'll render the template and, therefore, render all these components dynamically and only then I'll be triggering these service methods (Observables).

I don't want to make an API call for each component, because it can be like 60 components, I'll rather loose abstraction fo code but I prefer to do something like this:

// Listens to field's init and creates the fieldset triggering a service call that will be listened by the field component
        this.iboService.initIBOsFilters$.subscribe(
            (fieldName) => {
                if (fieldName === 'IBOsRankSelectorFieldComponent') {
                    log.data('inside initIBOsFilters$ subscription, calling updateIBOsFilters()', fieldName);
                    this.iboService.updateIBOsRankList(this.filters['iboRank'].data); // HERE I'M PASSING DATA TO THE COMPONENT RENDERED DYNAMICALY. BUT IF this.filters IS UNDEFINED, IT BREAKS
                }
            }
        );

In order to do this, I need to ensure that this.filters is defined and thus, I come to conclusion:

How can I wait until API call ends and this.filters is defined before rendering my template html?

Sorry if my question is a bit long, if you need any more details just let me know.

Thanks!

Body:
After studying the different approaches that people gave me, I found the solution on the async pipe. But, it took me a while to understand how to implement it.

Solution:

// Declaring the Promise, yes! Promise!
filtersLoaded: Promise<boolean>;

// Later in the Component, where I gather the data, I set the resolve() of the Promise
this.getFiltersSubscription = this.getFilters().subscribe(
    (filters) => {
        this.filters = filters;
        log.info('API CALL. getting filters');

        this.filtersLoaded = Promise.resolve(true); // Setting the Promise as resolved after I have the needed data
    }
);

// In this listener triggered by the dynamic components when instanced,
// I pass the data, knowing that is defined because of the template change

// Listens to field's init and creates the fieldset triggering a service call
// that will be listened by the field component
this.iboService.initIBOsFilters$.subscribe(
    (fieldName) => {
        if (fieldName === 'IBOsRankSelectorFieldComponent') {
            log.data('inside initIBOsFilters$ subscription, calling updateIBOsFilters()', fieldName);
            this.iboService.updateIBOsRankList(this.filters['iboRank'].data);
        }
    }
);

In the template, I use the async pipe that needs an Observable or a Promise

<div *ngIf="filtersLoaded | async">
    <div [saJquiAccordion]="{active: group.value['collapsed']}" *ngFor="let group of filterGroupsTemplate | keysCheckDisplay;">
        <div>
            <h4>{{group.key | i18n}}</h4>
            <form id="ibo-{{group.key}}" class="form-horizontal" autocomplete="off" style="overflow: initial">
                <fieldset *ngFor="let field of group.value | keys">
                    <ng-container *ngComponentOutlet="fieldSets[field.value.template];
                                    ngModuleFactory: smartadminFormsModule;"></ng-container>
                </fieldset>
            </form>
        </div>
    </div>
</div>

NOTE:

async pipe need an Observable or a Promise from what I understood, that's why the only way to make it work was by creating a Promise

I didn't use the resolver approach because it's used when you arrive to the component through Angular's routing. This component is part of a larger component and it's not instanced through routing like any other normal component. (Tried that approach though, worked a bit with it, didn't do the job)


答:
You can simply use this line of code to get the element with the selected class

```<code>$(".fileItem.read.write.selected").click(function() {
    // code here
});'
</code>```

Title: Get Specific class with Jquery/ JavaScript

Body:
You can simply use this line of code to get the element with the selected class

$(".fileItem.read.write.selected").click(function() {
    // code here
});'


问:
XSLT: SAXParseException: XML document structures must start and end within the same entity
I am trying to execute the below code but ended up in the below exception.

javax.xml.transform.TransformerConfigurationException: org.xml.sax.SAXParseException: XML document structures must start and end within the same entity.

Code is:

```<code><xsl:when test="/result/DECODE='CANCELLED'">
    <xsl:variable name="match_dates" >
        <xsl:for-each select="/legacyresult/*[starts-with(name(), 'END-DT')]">
            <xsl:sort data-type="number"
                      select="concat(substring(.,7, 4),substring(.,4, 2),substring(.,1, 2))" order="descending" />
            <xsl:variable name="end_dt" select="." />
            <xsl:variable name="match" select="count(/legacyresult/*[starts-with(name(), 'EFF-DT')][text()=$end_dt])" />
            <xsl:if test="$match=0" >
                <xsl:value-of select="name(.)" />
                <xsl:text >,</xsl:text>
            </xsl:if>
        </xsl:for-each>
    </xsl:variable>
    <xsl:variable name="final_date" >
        <xsl:value-of select="substring-before($match_dates, ',')" />
        <xsl:for-each select="/legacyresult/*[starts-with(name(), 'END-DT')][.=$final_date]">
            <xsl:sort select="substring(name(),13,2)" data-type="number"/>
            <xsl:variable name="prodSeq" select="substring(name(),13,2)"/>
            <xsl:variable name="id" select="position()"/>
            <xsl:variable name="id">ID<xsl:value-of select="$sq"/>
            </xsl:variable>
            <xsl:element name="product">
                <xsl:attribute name="id"><xsl:value-of select="$id"/></xsl:attribute>
                <xsl:attribute name="productId">0<xsl:value-of select="/legacyresult/*[name() = $id]/."/></xsl:attribute>
            </xsl:element>
        </xsl:for-each>
    </xsl:variable>
</xsl:when>
</code>```

Please let me know what is wrong in the above code. I have cross checked the tags. But i unable to find the issue.

答:
As far as I can see, you have the following error:

```<code>        <xsl:variable name="id">ID<xsl:value-of select="$sq"/>
        </xsl:variable>
</code>```

The first line has a / at the end, making it omni, but you're also closing a variable tag that doesn't start anywhere. Either remove the closing tag or the trailing / of the first line.

Body:
I am trying to execute the below code but ended up in the below exception.

javax.xml.transform.TransformerConfigurationException: org.xml.sax.SAXParseException: XML document structures must start and end within the same entity.

Code is:

<xsl:when test="/result/DECODE='CANCELLED'">
    <xsl:variable name="match_dates" >
        <xsl:for-each select="/legacyresult/*[starts-with(name(), 'END-DT')]">
            <xsl:sort data-type="number"
                      select="concat(substring(.,7, 4),substring(.,4, 2),substring(.,1, 2))" order="descending" />
            <xsl:variable name="end_dt" select="." />
            <xsl:variable name="match" select="count(/legacyresult/*[starts-with(name(), 'EFF-DT')][text()=$end_dt])" />
            <xsl:if test="$match=0" >
                <xsl:value-of select="name(.)" />
                <xsl:text >,</xsl:text>
            </xsl:if>
        </xsl:for-each>
    </xsl:variable>
    <xsl:variable name="final_date" >
        <xsl:value-of select="substring-before($match_dates, ',')" />
        <xsl:for-each select="/legacyresult/*[starts-with(name(), 'END-DT')][.=$final_date]">
            <xsl:sort select="substring(name(),13,2)" data-type="number"/>
            <xsl:variable name="prodSeq" select="substring(name(),13,2)"/>
            <xsl:variable name="id" select="position()"/>
            <xsl:variable name="id">ID<xsl:value-of select="$sq"/>
            </xsl:variable>
            <xsl:element name="product">
                <xsl:attribute name="id"><xsl:value-of select="$id"/></xsl:attribute>
                <xsl:attribute name="productId">0<xsl:value-of select="/legacyresult/*[name() = $id]/."/></xsl:attribute>
            </xsl:element>
        </xsl:for-each>
    </xsl:variable>
</xsl:when>

Please let me know what is wrong in the above code. I have cross checked the tags. But i unable to find the issue.

Body:
As far as I can see, you have the following error:

        <xsl:variable name="id">ID<xsl:value-of select="$sq"/>
        </xsl:variable>

The first line has a / at the end, making it omni, but you're also closing a variable tag that doesn't start anywhere. Either remove the closing tag or the trailing / of the first line.


答:
```<code>$(".fileItem").click(function(){
      $(this).find('.selected').style('blah','blah')
});
</code>```

<p>Something like this will allow you to perform other functions as well as the selected item. </p>

Body:
$(".fileItem").click(function(){
      $(this).find('.selected').style('blah','blah')
});

Something like this will allow you to perform other functions as well as the selected item.


问:
How to use global audiences to show a web part A or web part B but not both at the same time?
I have two web parts:

Web Part A
Web Part B

I have two audiences:

Audience A
Audience B

Audience B needs to contain all users that are NOT members of audience A.

On a web page, I only want to show Web Part A if they are member of Audience A and Web Part B if they are a member of Audience B.  But never both.

I can't get Audience B to show all members that are NOT a member of Audience A.

How could I do this?

答:
Audience membership can't be defined using logical rules like AND or NOT. It just takes all the members of a SPGroup or AD group and includes them. So, you'd have to be smart about group memberships...

Either make a group that contains all the members you want, to base an audience on or, to go into code, program a nightly timerjob that checks all members against audience A and if they're not in it, adds them to SPGroup B. Then when you're done, have it recompile Audience B, which is based directly on SPGroup B.


问:
use gulp to concat angularjs files but get [$injector:modulerr]
At first, I import every angularjs files into html and it worked fine.

However, I want to use gulp to concat these files into one file in order to reduce connection amount.

My folder structure is :

```<code>--- public
 |- app.js
 |- controller.js
 |- directives.js
 |- factories.js
 |- filter.js
 |---
    |--- events
       |- app.js
       |- controller.js
    ....
</code>```

inside my /public/app.js, I declared router

```<code>$stateProvider
    .state('events', {
         url: "/",
         templateUrl: "/public/partial/events",
         controller: "events",
         reloadOnSearch: false
    }).....
</code>```

I declare each pages as a folder, such as events and contain app.js and controller.js .

My events/app.js is

```<code>angular.module('events', ['ui.router', 'ngRoute', 'events.controller'])
    .config(['$routeProvider', '$locationProvider', '$stateProvider', '$urlRouterProvider',
        function($routeProvider, $locationProvider, $stateProvider, $urlRouterProvider) {

        }
    ]);
</code>```

events/controller.js is

```<code>angular.module('events.controller', ['restangular', 'LocalStorageModule', 'oitozero.ngSweetAlert', 'Alertify', 'daterangepicker', 'ngTable', 'slick'])
    .controller('events', ['$scope','$compile', ....,
        function ($scope, $compile, ....) {
</code>```

My gulpfile.js is simply concat all the angularjs files but got error!

```<code>gulp.src([
        "/public/app-v8.js",
        "/public/controller-v22.js",
        "/public/directives-v6.js",
        "/public/factories-v5.js",
        "/public/filters-v1.js",
        "/public/events/app-v0.js",
        "/public/events/controller-v23.js",
       .....
    ])
</code>```

答:
In your gulpfile, giv</p>

```<code>var gulp = require('gulp');
var concat = require('gulp-concat');
var minify = require('gulp-minify');
var cleanCss = require('gulp-clean-css');

    gulp.task('pack-js',function(){
        return gulp.src(['app.js',
            'common/controllers.js',
            'common/services.js',
            ....
            ])
        .pipe(concat('bundle.js'))
        .pipe(minify())
        .pipe(gulp.dest('myFolder/build/js/'))
});

'bundle.js' contain all your JS files. Similarly you can do for CSS files also.

At last you can run your task like this.

gulp.task('bundle-assets',['pack-js','pack-css']);
</code>```

Body:
At first, I import every angularjs files into html and it worked fine.

However, I want to use gulp to concat these files into one file in order to reduce connection amount.

My folder structure is :

--- public
 |- app.js
 |- controller.js
 |- directives.js
 |- factories.js
 |- filter.js
 |---
    |--- events
       |- app.js
       |- controller.js
    ....

inside my /public/app.js, I declared router

$stateProvider
    .state('events', {
         url: "/",
         templateUrl: "/public/partial/events",
         controller: "events",
         reloadOnSearch: false
    }).....

I declare each pages as a folder, such as events and contain app.js and controller.js .

My events/app.js is

angular.module('events', ['ui.router', 'ngRoute', 'events.controller'])
    .config(['$routeProvider', '$locationProvider', '$stateProvider', '$urlRouterProvider',
        function($routeProvider, $locationProvider, $stateProvider, $urlRouterProvider) {

        }
    ]);

events/controller.js is

angular.module('events.controller', ['restangular', 'LocalStorageModule', 'oitozero.ngSweetAlert', 'Alertify', 'daterangepicker', 'ngTable', 'slick'])
    .controller('events', ['$scope','$compile', ....,
        function ($scope, $compile, ....) {

My gulpfile.js is simply concat all the angularjs files but got error!

gulp.src([
        "/public/app-v8.js",
        "/public/controller-v22.js",
        "/public/directives-v6.js",
        "/public/factories-v5.js",
        "/public/filters-v1.js",
        "/public/events/app-v0.js",
        "/public/events/controller-v23.js",
       .....
    ])

Body:
In your gulpfile, giv

var gulp = require('gulp');
var concat = require('gulp-concat');
var minify = require('gulp-minify');
var cleanCss = require('gulp-clean-css');

    gulp.task('pack-js',function(){
        return gulp.src(['app.js',
            'common/controllers.js',
            'common/services.js',
            ....
            ])
        .pipe(concat('bundle.js'))
        .pipe(minify())
        .pipe(gulp.dest('myFolder/build/js/'))
});

'bundle.js' contain all your JS files. Similarly you can do for CSS files also.

At last you can run your task like this.

gulp.task('bundle-assets',['pack-js','pack-css']);


问:
SML functor expose a type without exposing implementation (implementing sets)
I'm writing a functor to implement sets in standard ML. Since sets don't allow duplicates and I don't want it to be constrained to equality types, it's declared like this:

```<code>signature SET = sig
    type t
    type 'a set

    val add : t -> t set -> t set
    ...
end

functor ListSet (EQ : sig type t val equal : t * t -> bool end) :> SET = struct
    type t = EQ.t
    type 'a set = 'a list

    fun add x s = ...
    ...
end
</code>```

I use :> so that list operations cannot be used on sets, hiding the internal implementation and allowing to change the representation (e.g. to a BST)

However, this also hides type t, therefore function add when used like this gives an error:

```<code>structure IntSet = ListSet (struct type t = int val equal = op= end);
val s0 = IntSet.empty
val s1 = IntSet.add 0 s0

Function: IntSet.add : IntSet.t -> IntSet.t IntSet.set -> IntSet.t IntSet.set
Argument: 0 : int
Reason:
  Can't unify int (*In Basis*) with
    IntSet.t (*Created from applying functor ListEqSet*)
    (Different type constructors)
</code>```

Is there a way to keep the implementation hidden but somehow expose the type t? Or is there a better approach to implementing sets?

P.S. The main reason I can't have equality types is to allow sets of sets, and while I can keep the lists sorted and define eqtype 'a set, it adds unnecessary complexity.

答:
You need what's sometimes called a translucent signature ascription, that is, you hide some of the types and expose the others:

```<code>functor ListSet (Eq : EQ) :> SET where type t = Eq.t = ...
</code>```

Body:
I'm writing a functor to implement sets in standard ML. Since sets don't allow duplicates and I don't want it to be constrained to equality types, it's declared like this:

signature SET = sig
    type t
    type 'a set

    val add : t -> t set -> t set
    ...
end

functor ListSet (EQ : sig type t val equal : t * t -> bool end) :> SET = struct
    type t = EQ.t
    type 'a set = 'a list

    fun add x s = ...
    ...
end

I use :> so that list operations cannot be used on sets, hiding the internal implementation and allowing to change the representation (e.g. to a BST)

However, this also hides type t, therefore function add when used like this gives an error:

structure IntSet = ListSet (struct type t = int val equal = op= end);
val s0 = IntSet.empty
val s1 = IntSet.add 0 s0

Function: IntSet.add : IntSet.t -> IntSet.t IntSet.set -> IntSet.t IntSet.set
Argument: 0 : int
Reason:
  Can't unify int (*In Basis*) with
    IntSet.t (*Created from applying functor ListEqSet*)
    (Different type constructors)

Is there a way to keep the implementation hidden but somehow expose the type t? Or is there a better approach to implementing sets?

P.S. The main reason I can't have equality types is to allow sets of sets, and while I can keep the lists sorted and define eqtype 'a set, it adds unnecessary complexity.

Body:
You need what's sometimes called a translucent signature ascription, that is, you hide some of the types and expose the others:

functor ListSet (Eq : EQ) :> SET where type t = Eq.t = ...


答:
You can use </p>

```<code>   $(".selected").click(function(){});
</code>```

Body:
You can use

   $(".selected").click(function(){});


问:
Loop over columns in DF and calculate sum based on condition for every appended column in R or Python
```<code>A B C
1 0 0
0 0 1
0 1 0
1 1 1
</code>```

Here I have 4*3 dataframe (columns A,B,C). I`d like to calculate sum in a combination of columns based on a condition that both rows are 1. In other words, in the output I want to have 1*3 dataframe with A 2 B 1 C 1. So, first I look at column A, it has 2 rows with ones, so the sum is 2, then I look at combination of A and B, there is just one row with BOTH 1, so I get 1. Finally, I get combination of A,B,C and it has one row with all ones, so I get 1 as well. Could you pls help with the best way to do it in R or Python.

答:
As a 1-line dict comprehension using cumsum

```<code>d = {col_name: sum(col == i) for i, (col_name, col) in enumerate(df.cumsum(axis=1).iteritems(), 1)}
</code>```

yields:

```<code>{'A': 2, 'B': 1, 'C': 1}
</code>```

If you want a Series:

```<code>pd.Series(d, index=df.columns)
</code>```

This only works if the value you are looking for is 1 (or True)

Body:
A B C
1 0 0
0 0 1
0 1 0
1 1 1

Here I have 4*3 dataframe (columns A,B,C). I`d like to calculate sum in a combination of columns based on a condition that both rows are 1. In other words, in the output I want to have 1*3 dataframe with A 2 B 1 C 1. So, first I look at column A, it has 2 rows with ones, so the sum is 2, then I look at combination of A and B, there is just one row with BOTH 1, so I get 1. Finally, I get combination of A,B,C and it has one row with all ones, so I get 1 as well. Could you pls help with the best way to do it in R or Python.

Body:
As a 1-line dict comprehension using cumsum

d = {col_name: sum(col == i) for i, (col_name, col) in enumerate(df.cumsum(axis=1).iteritems(), 1)}

yields:

{'A': 2, 'B': 1, 'C': 1}

If you want a Series:

pd.Series(d, index=df.columns)

This only works if the value you are looking for is 1 (or True)


问:
Load nested trait class
I have a piece of code under "test" package as below

```<code>object TestTraitsUnderObject {

  trait InnerOperation[T] {

  }

  def main(args: Array[String]): Unit = {
    Class.forName("test.OuterOperation")
    Class.forName("test.TestTraitsUnderObject.InnerOperation")

  }
}

trait OuterOperation[T] {

}
</code>```

seems I can load the class for Outer trait correctly , but for nested trait, the classpath is incorrect ? why is that ? How I can load the `nested trait class correctly ?

Thanks

答:
Use $

Class.forName("test.TestTraitsUnderObject$InnerOperation")

Title: Load nested trait class

Body:
I have a piece of code under "test" package as below

object TestTraitsUnderObject {

  trait InnerOperation[T] {

  }

  def main(args: Array[String]): Unit = {
    Class.forName("test.OuterOperation")
    Class.forName("test.TestTraitsUnderObject.InnerOperation")

  }
}

trait OuterOperation[T] {

}

seems I can load the class for Outer trait correctly , but for nested trait, the classpath is incorrect ? why is that ? How I can load the `nested trait class correctly ?

Thanks


问:
Three.js grid Axis label issue and how to plot x,y,z data on the grid
I am supposed to plot the well deviation surveys on a 3D grid. With the help of a few articles on the web, I have accomplished a 3D grid with required size. The current problem I am facing right now is that the labels for x,y and z axis are attached to the grid, rather they are misplaced on the scene.

```<code>var labelsH = labelAxis(height, data.labels.y,"y");
        labelsH.position.x = width;
        labelsH.position.y = - height +(2*height/a)-20;
        labelsH.position.z = depth;
        scene.add(labelsH);

function labelAxis(width, data, direction){

  var separator = 2*width/data.length,
            p = {
                x:0,
                y:0,
                z:0
            },
            dobj = new THREE.Object3D();

  for ( var i = 0; i < data.length; i ++ ) {
        var label = makeTextSprite(data[i]);

        label.position.set(p.x,p.y,p.z);

        dobj.add( label );
        if (direction=="y"){
            p[direction]+=separator;
        }else{
            p[direction]-=separator;
        }
    //console.log(p.x+":"+p.y+":"+p.z)
  }
  return dobj;
}
</code>```

See the https://jsfiddle.net/3tw3dt1u/ for full code example.

Further more, the data that I need to plot is already in the jsFiddle mentioned above. Having minimal javascript skills, I have no idea how this data will be plotted on the grid to form something like this:

see image for required result

Thanks a lot in advance for any help.

答:
Your question is regarding the plotting of the points, this is how it could be done:

JSFiddle working example

The key points are below.

```<code>// Not necessary, but I prefer to use the same scale as they use in their example. It's also easier since the data is according to those scales.
var graphDimensions = {
    w:3000,
    d:3000,
    h:7000
};

var vectors = realData.map(function(d) { // Create vectors from your data
    return new THREE.Vector3(d[0], d[1], d[2]);
});

var curve = new THREE.CatmullRomCurve3(vectors); // Create a curve with the vectors created above

var material = new THREE.LineBasicMaterial({color: "blue"}); // Material for the curve

var geometry = new THREE.Geometry();
var splinePoints = curve.getPoints(5000); // The 5000 in here is the resolution (number of points) on the curve. Increase for a smoother curve, decrease for a more jagged curve.

for (var i = 0; i < splinePoints.length; i++) { // Loop through the points to create vertices in the geometry
  geometry.vertices.push(splinePoints[i]);
}

var line = new THREE.Line(geometry, material); // Create a line with your geometry and material
scene.add(line); // Add it to the scene

line.rotateX(Math.PI / 2); // Orient the line correctly
boundingGrid.position.set(0, -3.5, 1.5); // Move the grid into position
boundingGrid.scale.set(0.001, 0.001, 0.001); // Reduce by whatever scale you want to decrease it in size (otherwise you have to scroll out forever)
line.scale.set(0.001, 0.001, 0.001);
</code>```

Body:
I am supposed to plot the well deviation surveys on a 3D grid. With the help of a few articles on the web, I have accomplished a 3D grid with required size. The current problem I am facing right now is that the labels for x,y and z axis are attached to the grid, rather they are misplaced on the scene.

var labelsH = labelAxis(height, data.labels.y,"y");
        labelsH.position.x = width;
        labelsH.position.y = - height +(2*height/a)-20;
        labelsH.position.z = depth;
        scene.add(labelsH);

function labelAxis(width, data, direction){

  var separator = 2*width/data.length,
            p = {
                x:0,
                y:0,
                z:0
            },
            dobj = new THREE.Object3D();

  for ( var i = 0; i < data.length; i ++ ) {
        var label = makeTextSprite(data[i]);

        label.position.set(p.x,p.y,p.z);

        dobj.add( label );
        if (direction=="y"){
            p[direction]+=separator;
        }else{
            p[direction]-=separator;
        }
    //console.log(p.x+":"+p.y+":"+p.z)
  }
  return dobj;
}

See the https://jsfiddle.net/3tw3dt1u/ for full code example.

Further more, the data that I need to plot is already in the jsFiddle mentioned above. Having minimal javascript skills, I have no idea how this data will be plotted on the grid to form something like this:

see image for required result

Thanks a lot in advance for any help.

Body:
Your question is regarding the plotting of the points, this is how it could be done:

JSFiddle working example

The key points are below.

// Not necessary, but I prefer to use the same scale as they use in their example. It's also easier since the data is according to those scales.
var graphDimensions = {
    w:3000,
    d:3000,
    h:7000
};

var vectors = realData.map(function(d) { // Create vectors from your data
    return new THREE.Vector3(d[0], d[1], d[2]);
});

var curve = new THREE.CatmullRomCurve3(vectors); // Create a curve with the vectors created above

var material = new THREE.LineBasicMaterial({color: "blue"}); // Material for the curve

var geometry = new THREE.Geometry();
var splinePoints = curve.getPoints(5000); // The 5000 in here is the resolution (number of points) on the curve. Increase for a smoother curve, decrease for a more jagged curve.

for (var i = 0; i < splinePoints.length; i++) { // Loop through the points to create vertices in the geometry
  geometry.vertices.push(splinePoints[i]);
}

var line = new THREE.Line(geometry, material); // Create a line with your geometry and material
scene.add(line); // Add it to the scene

line.rotateX(Math.PI / 2); // Orient the line correctly
boundingGrid.position.set(0, -3.5, 1.5); // Move the grid into position
boundingGrid.scale.set(0.001, 0.001, 0.001); // Reduce by whatever scale you want to decrease it in size (otherwise you have to scroll out forever)
line.scale.set(0.001, 0.001, 0.001);


问:
Universal library for C++ strings
Please recommend me universal library for C++ strings. I want to manipulate ascii text and unicode text in one build without making two versions of builds for std::string/char and for std::wstring/wchar; Also I want to convert them to each other (where it is possible);

Thank you very much!!!

答:
I'm assuming that because you're talking about using wchar_t for Unicode that we're talking about a Windows box. I wouldn't bother with making two separate builds -- nobody bothers supporting the ANSI only versions of Windows anymore. If you MUST do that, just use std::basic_string<TCHAR> (i.e. typedef std::basic_string<TCHAR> tstring) and go from there.

Converting between the two is going to be locale specific -- i.e., you have to know which particular narrow character codepage to which you wish to convert before going and doing the actual conversion. Win32 provides WideCharToMultiByte and MultiByteToWideChar to accomplish these kinds of conversions.

Title: Universal library for C++ strings


答:
$(".fileItem").click(function(e) {
  e.preventDefault();

  $('.selected').css({
    'color': 'green'
  });
});```

Body:
I have got a div containing some html elements. They all have a class named

class="fileItem read write".

But there could be an Element with

class="fileItem read write selected".

Now I want to get this element with the additional 'selected' tag and edit this. Currently I have an in JQuery

$(".fileItem").click(function(){
    // Code
});

which detect an click on one of these fileItems.

Here I want to edit style tag of the element with 'selected' tag. So is there something where I can say get all by class and select the on with "selected"?


问:
Cocoa Pods 'No such file or Directory' Error
I have an IOS project that uses cocoapods. After switching computers and updating the OS on the new computer I am getting the following error when I try running "pod update"

```<code>Robbys-iMac-454:ios-v2 robbykmyers$ pod update
Update all pods
Analyzing dependencies
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/pathname.rb:422:in `open': No such file or directory - /Users/robbykmyers/.cocoapods/repos (Errno::ENOENT)
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/pathname.rb:422:in `foreach'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/pathname.rb:422:in `children'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.35.0/lib/cocoapods/sources_manager.rb:63:in `all'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.35.0/lib/cocoapods/user_interface/error_report.rb:130:in `repo_information'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.35.0/lib/cocoapods/user_interface/error_report.rb:34:in `report'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.35.0/lib/cocoapods/command.rb:58:in `report_error'
    from /Library/Ruby/Gems/2.0.0/gems/claide-0.7.0/lib/claide/command.rb:300:in `handle_exception'
    from /Library/Ruby/Gems/2.0.0/gems/claide-0.7.0/lib/claide/command.rb:274:in `rescue in run'
    from /Library/Ruby/Gems/2.0.0/gems/claide-0.7.0/lib/claide/command.rb:264:in `run'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.35.0/lib/cocoapods/command.rb:45:in `run'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.35.0/bin/pod:43:in `<top (required)>'
    from /usr/bin/pod:23:in `load'
    from /usr/bin/pod:23:in `<main>'
</code>```

Does anyone know how to solve this?

答:
https://blog.cocoapods.org/Repairing-Our-Broken-Specs-Repository/</p>

```<code>rm -fr ~/Library/Caches/CocoaPods && \
gem update --system && \
gem update && \
gem cleanup && \
pod setup
</code>```

Body:
I have an IOS project that uses cocoapods. After switching computers and updating the OS on the new computer I am getting the following error when I try running "pod update"

Robbys-iMac-454:ios-v2 robbykmyers$ pod update
Update all pods
Analyzing dependencies
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/pathname.rb:422:in `open': No such file or directory - /Users/robbykmyers/.cocoapods/repos (Errno::ENOENT)
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/pathname.rb:422:in `foreach'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/pathname.rb:422:in `children'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.35.0/lib/cocoapods/sources_manager.rb:63:in `all'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.35.0/lib/cocoapods/user_interface/error_report.rb:130:in `repo_information'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.35.0/lib/cocoapods/user_interface/error_report.rb:34:in `report'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.35.0/lib/cocoapods/command.rb:58:in `report_error'
    from /Library/Ruby/Gems/2.0.0/gems/claide-0.7.0/lib/claide/command.rb:300:in `handle_exception'
    from /Library/Ruby/Gems/2.0.0/gems/claide-0.7.0/lib/claide/command.rb:274:in `rescue in run'
    from /Library/Ruby/Gems/2.0.0/gems/claide-0.7.0/lib/claide/command.rb:264:in `run'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.35.0/lib/cocoapods/command.rb:45:in `run'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.35.0/bin/pod:43:in `<top (required)>'
    from /usr/bin/pod:23:in `load'
    from /usr/bin/pod:23:in `'

Does anyone know how to solve this?

Body:
https://blog.cocoapods.org/Repairing-Our-Broken-Specs-Repository/

rm -fr ~/Library/Caches/CocoaPods && \
gem update --system && \
gem update && \
gem cleanup && \
pod setup