问:
Error org.testng.TestNGException: Cannot inject @Test annotated Method main with class Ljava.lang.String;
I have created a testng.xml file to run a suite of my selenium webdriver test. From eclipse I can run this just fine as a testNG Suite, but from the command like I get the following error.

testng.xml

```<code><?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "testng.org/testng-1.0.dtd">;
  <suite name="CATS Regression Suite">
    <test name="WEB UI">
      <parameter name="uid" value="TestAccount"/>
      <parameter name="pid" value="Test123"/>
      <classes>
         <class name="VerifyLogin"/>
      </classes>
     </test>
    <!-- Test -->
  </suite>
  <!-- Suite -->
</code>```

command ran:

```<code>java org.testng.TestNG testng.xml
</code>```

Exception trace:

```<code>[Error] org.testng.TestNGException:
Cannot inject @Test annotated Method [main] with [class [Ljava.lang.String;].
For more information on native dependency injection please refer to http://testng.org/doc/documentation-main.html#native-dependency-injection
    at org.testng.internal.Parameters.checkParameterTypes(Parameters.java:244)
    at org.testng.internal.Parameters.createParameters(Parameters.java:172)
    at org.testng.internal.Parameters.createParameters(Parameters.java:458)
    at org.testng.internal.Parameters.handleParameters(Parameters.java:568)
    at org.testng.internal.Invoker.handleParameters(Invoker.java:1293)
    at org.testng.internal.Invoker.createParameters(Invoker.java:1020)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1110)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
    at org.testng.TestRunner.privateRun(TestRunner.java:756)

at org.testng.TestRunner.run(TestRunner.java:610)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
    at org.testng.SuiteRunner.run(SuiteRunner.java:289)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
    at org.testng.TestNG.runSuites(TestNG.java:1133)
    at org.testng.TestNG.run(TestNG.java:1104)
    at org.testng.TestNG.privateMain(TestNG.java:1434)
    at org.testng.TestNG.main(TestNG.java:1403)
</code>```

Code (As shared in the comments)

```<code>public class VerifyLogin extends TestBase {
   @Parameters({"uid","pid"})
   @Test
   public void verifyLogin(String uid, String pid) throws IOException, Exception {
      String userName = uid;
      String passWord = pid;
      // new instance
      ExtentReports extent = new ExtentReports("C:\\Users\\AdvancedReport.html", true);
      //starting test
      ExtentTest test = extent.startTest("Login Test", "Regression");
      // log step
      test.log(LogStatus.PASS, "Browser Running");
      TestBase login=new TestBase();
      login.testLogin(userName, passWord);
   }
}
</code>```

答:
Just remove String uid, String pid in main method and run once again as

```<code>public void verifyLogin(String uid, String pid)
</code>```

to

```<code>public void verifyLogin()
</code>```

Body:
I have created a testng.xml file to run a suite of my selenium webdriver test. From eclipse I can run this just fine as a testNG Suite, but from the command like I get the following error.

testng.xml

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "testng.org/testng-1.0.dtd">;
  <suite name="CATS Regression Suite">
    <test name="WEB UI">
      <parameter name="uid" value="TestAccount"/>
      <parameter name="pid" value="Test123"/>
      <classes>
         <class name="VerifyLogin"/>
      </classes>
     </test>

  </suite>

command ran:

java org.testng.TestNG testng.xml

Exception trace:

[Error] org.testng.TestNGException:
Cannot inject @Test annotated Method [main] with [class [Ljava.lang.String;].
For more information on native dependency injection please refer to http://testng.org/doc/documentation-main.html#native-dependency-injection
    at org.testng.internal.Parameters.checkParameterTypes(Parameters.java:244)
    at org.testng.internal.Parameters.createParameters(Parameters.java:172)
    at org.testng.internal.Parameters.createParameters(Parameters.java:458)
    at org.testng.internal.Parameters.handleParameters(Parameters.java:568)
    at org.testng.internal.Invoker.handleParameters(Invoker.java:1293)
    at org.testng.internal.Invoker.createParameters(Invoker.java:1020)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1110)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
    at org.testng.TestRunner.privateRun(TestRunner.java:756)

at org.testng.TestRunner.run(TestRunner.java:610)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
    at org.testng.SuiteRunner.run(SuiteRunner.java:289)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
    at org.testng.TestNG.runSuites(TestNG.java:1133)
    at org.testng.TestNG.run(TestNG.java:1104)
    at org.testng.TestNG.privateMain(TestNG.java:1434)
    at org.testng.TestNG.main(TestNG.java:1403)

Code (As shared in the comments)

public class VerifyLogin extends TestBase {
   @Parameters({"uid","pid"})
   @Test
   public void verifyLogin(String uid, String pid) throws IOException, Exception {
      String userName = uid;
      String passWord = pid;
      // new instance
      ExtentReports extent = new ExtentReports("C:\\Users\\AdvancedReport.html", true);
      //starting test
      ExtentTest test = extent.startTest("Login Test", "Regression");
      // log step
      test.log(LogStatus.PASS, "Browser Running");
      TestBase login=new TestBase();
      login.testLogin(userName, passWord);
   }
}

Body:
Just remove String uid, String pid in main method and run once again as

public void verifyLogin(String uid, String pid)

to

public void verifyLogin()


来源: stackexchange

问:
VMware Fusion and MacbookPro keyboard
I'm running Windows 7 Ultimate (retail) under VMware Fusion on a Macbook Pro.  I've created a keyboard layout for the mac using Microsoft keyboard Layout Creator MSKLC.

My problem is that when I type the quote or double quote character, nothing happens.  Then I press it again and get the character twice.  Similar behaviour also occurs when I use a standard US-International keyboard layout.

First press of ' I get nothing.

Second press of ' I get ''

If I press ' once, then press any other key it generally produces the expected output, e.g.

First press of ' I get nothing

Now press f and I get 'f

If I press ' once, then press i, I get í (see here)

Interestingly, if I press ' once, then press backspace it's as if I never pressed ' (backspace functions normally).

A similar thing happens with #.

As you can imagine, it's taken me ages to type this out, with the keyboard doing what it's doing... should have flicked over to OSX!

答:
No, I know the reason:

You have mapped them to be dead keys.

A dead key, is a key to combine other key strokes to get a combined output. It exactly does what you described: when pressed once, nothing happens; when pressed twice, or pressed once plus space key, it repeats itself. If you press some letters, it gets you a combined output, like á.

Check your MSKLC mapping. Here is a good guide to follow:

http://www.angelfire.com/planet/linguisticsisfun/Creating_a_Keyboard_Using_MSKLC.pdf

ContentLicense: CC BY-SA 2.5

Title: VMware Fusion and MacbookPro keyboard

ContentLicense: CC BY-SA 3.0


问:
3D Max - Plane question
I've only a basic knowledge of 3D Max. I'm creating a plane using MaxScript, converting it to an editable Poly and then extruding certain faces. The thing is, I only have 16 faces to work from. Is there a way to have more than 16 faces?</p>

答:
You would have to define it before you do your conversion to poly.

The syntax shown in the listener for adding segments is:

```<code>$.lengthsegs = 20
$.widthsegs = 20
</code>```

So for your script just add this right below your line where you define your plane:

```<code>yPlane.lengthsegs =20 --any number of segments
yPlane.widthsegs = 20 --any number of segments
</code>```

this makes it more "bulletproof",
since when using $ it means any selected object.

By using "yplane" variable we make sure it only affects this object.

Title: 3D Max - Plane question

Body:
You would have to define it before you do your conversion to poly.

The syntax shown in the listener for adding segments is:

$.lengthsegs = 20
$.widthsegs = 20

So for your script just add this right below your line where you define your plane:

yPlane.lengthsegs =20 --any number of segments
yPlane.widthsegs = 20 --any number of segments

this makes it more "bulletproof",
since when using $ it means any selected object.

By using "yplane" variable we make sure it only affects this object.


问:
Spark-shell --conf option for Kryos/Java serializer
I need to launch the spark shell with custom classes using registerKryoClasses method as mentioned in the spark help page .

Now as mentioned in the page I cannot recreate the sc variable after launching the spark shell and hence need to provide the option --conf while launching the spark-shell command.

What should be the option value with --conf so that it is equivalent to the following update:

```<code>conf.registerKryoClasses(Array(classOf[ArrayBuffer[String]], classOf[ListBuffer[String]]))
</code>```

答:
The option to use Javaserializer instead of Kryos serializer worked for me:

```<code>spark-shell --conf 'spark.serializer=org.apache.spark.serializer.JavaSerializer'
</code>```

Edit: just figured out how to use the options. We can do the following:

```<code>--conf 'spark.kryo.classesToRegister=scala.collection.mutable.ArrayBuffer,scala.collection.mutable.ListBuffer'
</code>```

Body:
I need to launch the spark shell with custom classes using registerKryoClasses method as mentioned in the spark help page .

Now as mentioned in the page I cannot recreate the sc variable after launching the spark shell and hence need to provide the option --conf while launching the spark-shell command.

What should be the option value with --conf so that it is equivalent to the following update:

conf.registerKryoClasses(Array(classOf[ArrayBuffer[String]], classOf[ListBuffer[String]]))

Body:
The option to use Javaserializer instead of Kryos serializer worked for me:

spark-shell --conf 'spark.serializer=org.apache.spark.serializer.JavaSerializer'

Edit: just figured out how to use the options. We can do the following:

--conf 'spark.kryo.classesToRegister=scala.collection.mutable.ArrayBuffer,scala.collection.mutable.ListBuffer'


问:
How to use initializer-list loops for modifying elements?
I can easily simulate a for .. in loop using initializer lists for read access

```<code>std::list<int> foo, bar, baz;

int main()
{
  foo.push_back(3);
  foo.push_back(2);
  bar.push_back(1);
  for (auto &x : {foo, bar, baz}) {
    // x.push_back(42);
    std::cout << x.size() << std::endl;
  }
  return 0;
}
</code>```

This prints:

```<code>2
1
0
</code>```

What should I do so that I can modify the actual objects, just as in the commented line:

```<code>// x.push_back(42);
</code>```

答:
You can use std::reference_wrapper:

```<code>for (std::list<int>& x : {std::ref(foo), std::ref(bar), std::ref(baz)}) {
  x.push_back(42);
  std::cout << x.size() << std::endl;
}
</code>```

Body:
I can easily simulate a for .. in loop using initializer lists for read access

std::list<int> foo, bar, baz;

int main()
{
  foo.push_back(3);
  foo.push_back(2);
  bar.push_back(1);
  for (auto &x : {foo, bar, baz}) {
    // x.push_back(42);
    std::cout << x.size() << std::endl;
  }
  return 0;
}

This prints:

2
1
0

What should I do so that I can modify the actual objects, just as in the commented line:

// x.push_back(42);

Body:
You can use std::reference_wrapper:

for (std::list<int>& x : {std::ref(foo), std::ref(bar), std::ref(baz)}) {
  x.push_back(42);
  std::cout << x.size() << std::endl;
}


问:
to carry selected text and id value together of multiselect dropdown to other dropdown using jquery
I have a multiselect dropdown. All of its selected text and values should be displayed as each entry on other dropdown. I coded somewhat like this but its not working. All the selections of multiselect dropdown are appending on a single entry of the other dropdown. It is not displaying as separate entries.

#LstCashAccount is the multiselect dropdown and #ddlDefaultCash is the dropdown where entries selected in multiselect dropdown have to get affected

```<code>$('#LstCashAccount').change(function () {

    $("#ddlDefaultCash").empty();
    $("#ddlLoyaltyAcc").empty();
    var CashAcc = "";
    var CashAccId = $("#LstCashAccount").val();
    CashAccIdSplit = CashAccId.splice(",")
    CashAcc = $(this).find("option:selected").text();
    CashAccSplit = CashAcc.split(".")

    $("#ddlDefaultCash").append('<option class="InputDefCash" Id=' + CashAccIdSplit + '>' + CashAccSplit + '</option>');

});
</code>```

答:
So there are multiple issues here.

First, it's important to realize that the .append() function is what's actually creating your items. You only call this once, so expecting there to be multiple items is, frankly, a bit silly.

Second, you're using .splice() on a string, which isn't valid. I have a hunch you meant to do .split(), but without your HTML markup, it's a bit of a shot in the dark.

And finally, your CashAccSplit variable is (and, I assume, your CashAccIdSplit is supposed to be) an array. If you just concatenate this with a string, it will output the entire array.

If we clean this up, you might be looking for something more like the following...

```<code>$('#LstCashAccount').change(function () {

    $("#ddlDefaultCash").empty();
    $("#ddlLoyaltyAcc").empty();

    var CashAcc = $(this).find("option:selected").text();
    var CashAccId = $("#LstCashAccount").val();

    var CashAccIdSplit = CashAccId.split(",")
    var CashAccSplit = CashAcc.split(".")

    //Use .each to iterate through the array, append each member as an item
    $.each(CashAccIdSplit, function(index, item) {
        $("#ddlDefaultCash").append('<option class="InputDefCash" Id=' + CashAccIdSplit[index] + '>' + CashAccSplit[index] + '</option>');
    });

});
</code>```

Body:
I have a multiselect dropdown. All of its selected text and values should be displayed as each entry on other dropdown. I coded somewhat like this but its not working. All the selections of multiselect dropdown are appending on a single entry of the other dropdown. It is not displaying as separate entries.

#LstCashAccount is the multiselect dropdown and #ddlDefaultCash is the dropdown where entries selected in multiselect dropdown have to get affected

$('#LstCashAccount').change(function () {

    $("#ddlDefaultCash").empty();
    $("#ddlLoyaltyAcc").empty();
    var CashAcc = "";
    var CashAccId = $("#LstCashAccount").val();
    CashAccIdSplit = CashAccId.splice(",")
    CashAcc = $(this).find("option:selected").text();
    CashAccSplit = CashAcc.split(".")

    $("#ddlDefaultCash").append('<option class="InputDefCash" Id=' + CashAccIdSplit + '>' + CashAccSplit + '</option>');

});

Body:
So there are multiple issues here.

First, it's important to realize that the .append() function is what's actually creating your items. You only call this once, so expecting there to be multiple items is, frankly, a bit silly.

Second, you're using .splice() on a string, which isn't valid. I have a hunch you meant to do .split(), but without your HTML markup, it's a bit of a shot in the dark.

And finally, your CashAccSplit variable is (and, I assume, your CashAccIdSplit is supposed to be) an array. If you just concatenate this with a string, it will output the entire array.

If we clean this up, you might be looking for something more like the following...

$('#LstCashAccount').change(function () {

    $("#ddlDefaultCash").empty();
    $("#ddlLoyaltyAcc").empty();

    var CashAcc = $(this).find("option:selected").text();
    var CashAccId = $("#LstCashAccount").val();

    var CashAccIdSplit = CashAccId.split(",")
    var CashAccSplit = CashAcc.split(".")

    //Use .each to iterate through the array, append each member as an item
    $.each(CashAccIdSplit, function(index, item) {
        $("#ddlDefaultCash").append('<option class="InputDefCash" Id=' + CashAccIdSplit[index] + '>' + CashAccSplit[index] + '</option>');
    });

});


问:
React Native fetch() Network Request Failed
When I create a brand new project using react-native init (RN version 0.29.1) and put a fetch in the render method to the public facebook demo movie API, it throws a Network Request Failed. There is a very useless stack trace and I can't debug network requests in the chrome console. Here is the fetch I'm sending:

```<code>fetch('http://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
        return responseJson.movies;
      })
      .catch((error) => {
        console.error(error);
      });
</code>```

答:
For Android, you may have missed to add permission in AndroidManifest.xml
Need to add the following permission.</p>

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

Body:
When I create a brand new project using react-native init (RN version 0.29.1) and put a fetch in the render method to the public facebook demo movie API, it throws a Network Request Failed. There is a very useless stack trace and I can't debug network requests in the chrome console. Here is the fetch I'm sending:

fetch('http://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
        return responseJson.movies;
      })
      .catch((error) => {
        console.error(error);
      });

Body:
For Android, you may have missed to add permission in AndroidManifest.xml
Need to add the following permission.

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


问:
Using Selenium on https web application that runs over vpn
First of all, I need to state that I am total beginner with Selenium.
I am trying to test an application in firefox browser using Selenium. Due to security issues the application works only over vpn.

My problem occurs with the following steps; I create the webdriver and navigate to the start (login) page of application. I get an "Authorization request" popup. If I cancel the popup, then I get to a page that states "Connection is not secure" (it's https address). After I get passed that, I lose the part where Selenium program should populate username and password and it just stays on the login page.

My question, is there a way to start Selenium testing on an application so that it is already opened and prepared (ie logged in) in browser? I am not happy that username and password are hard-coded in Selenium code.

If that is not possible, how do I skip that authorization popup and problem with non-secure connection? How do I populate username and password in safest way?
Thanks!

```<code>public static void main(String[] args) {
    System.setProperty("webdriver.gecko.driver", "C:\\Selenium-java-3.0.1\\geckodriver.exe");
    // I tried also with this code bellow in comment, but it did not work, it did not even get to login page
    //WebDriverWait wait = new WebDriverWait(driver, 10);
    //Alert alert = wait.until(ExpectedConditions.alertIsPresent());
    //alert.authenticateUsing(new UserAndPassword("cfadmin", "20lipim18"));
    driver.get("https://Application_login_page.com");
    driver.findElement(By.xpath(".//*[@id='login']")).click();
    driver.findElement(By.xpath("[@id='login']")).sendKeys("Username");
</code>```

}

答:
if it's possible, is there a way to start Selenium testing on application that is already opened and prepared (logged) in browser?

Try using firefox profile. Since selenium open fresh instance of browser by default. You can use your own firefox frofile.

This is a code to implement a profile, which can be embedded in the selenium code.

```<code>ProfilesIni profile = new ProfilesIni();
// this will create an object for the Firefox profile
FirefoxProfile myprofile = profile.getProfile("default");
// this will Initialize the Firefox driver
WebDriver driver = new FirefoxDriver(myprofile)
</code>```

It will also maintain the session means you are already login to the application in firefox(default profile). Then if you execute the script, you will see that you are already logged in to the application.

Body:
First of all, I need to state that I am total beginner with Selenium.
I am trying to test an application in firefox browser using Selenium. Due to security issues the application works only over vpn.

My problem occurs with the following steps; I create the webdriver and navigate to the start (login) page of application. I get an "Authorization request" popup. If I cancel the popup, then I get to a page that states "Connection is not secure" (it's https address). After I get passed that, I lose the part where Selenium program should populate username and password and it just stays on the login page.

My question, is there a way to start Selenium testing on an application so that it is already opened and prepared (ie logged in) in browser? I am not happy that username and password are hard-coded in Selenium code.

If that is not possible, how do I skip that authorization popup and problem with non-secure connection? How do I populate username and password in safest way?
Thanks!

public static void main(String[] args) {
    System.setProperty("webdriver.gecko.driver", "C:\\Selenium-java-3.0.1\\geckodriver.exe");
    // I tried also with this code bellow in comment, but it did not work, it did not even get to login page
    //WebDriverWait wait = new WebDriverWait(driver, 10);
    //Alert alert = wait.until(ExpectedConditions.alertIsPresent());
    //alert.authenticateUsing(new UserAndPassword("cfadmin", "20lipim18"));
    driver.get("https://Application_login_page.com");
    driver.findElement(By.xpath(".//*[@id='login']")).click();
    driver.findElement(By.xpath("[@id='login']")).sendKeys("Username");

}

Body:
if it's possible, is there a way to start Selenium testing on application that is already opened and prepared (logged) in browser?

Try using firefox profile. Since selenium open fresh instance of browser by default. You can use your own firefox frofile.

This is a code to implement a profile, which can be embedded in the selenium code.

ProfilesIni profile = new ProfilesIni();
// this will create an object for the Firefox profile
FirefoxProfile myprofile = profile.getProfile("default");
// this will Initialize the Firefox driver
WebDriver driver = new FirefoxDriver(myprofile)

It will also maintain the session means you are already login to the application in firefox(default profile). Then if you execute the script, you will see that you are already logged in to the application.


问:
Make a JPanel not draw its background (Transparent)
Is it possible, in Java, to make a JPanel skip drawing its background thus being transparent except for the components on it?

答:
If you are using NetBeans, Then Do these steps:-

Right Click on JPanel.

Scroll Down and Search For (( Opaque )). It must be there.

Uncheck it.

Now your JPanel background will be removed and what will appear in
JPanel Background is your Background of JFrame.

OwnerDisplayName: jjnguy


问:
Xcode9's Augmented Reality App template sandbox error
Apple introduced its ARKit at WWDC 17 and they also added a new project template to Xcode 9 called "Augmented Reality App" which is basically supposed to be the demo app during WWDC keynote or something like that.

However, the original template itself returns a critical error during runtime, which is the following:

libMobileGestalt MobileGestaltSupport.m:153: pid 701 ({Your app's name}) does
  not have sandbox access for frZQaeyWLUvLjeuEK43hmg and IS NOT
  appropriately entitled

What I tried so far:

I tried all 3 different template projects: SpriteKit, SceneKit and Metal. The error stays.

I created entitlements file and set "App sandbox" to true. No luck.

Googled the error and saw that this error is actually older (and arguably less popular) than ARKit. Sadly, nobody has found a solution yet.

Lastly, I do not think that could be relevant but I tried to run it on my iPhone 6. Has anyone managed to run AR app template? If so, how? Or anyone has any bit of information on libMobileGestalt?

答:
According to Apple documentation, only devices powered by A9 and higher can use ARKit.

ARKit runs on the Apple A9 and A10 processors

On iOS devices with an A9 processor or later, the
  ARWorldTrackingSessionConfiguration
  subclass provides high-precision motion tracking and enables features to help you place virtual content in relation to real-world surfaces.

On other devices supported by ARKit, the
  ARSessionConfiguration
  base class provides basic motion tracking that permits slightly less immersive AR experiences.

The iPhone 6s and 6s plus have A9 chips, so those and all devices after that can run ARKit. Found it here.


问:
Create static library from existing project (VS)
I created a C++ project in Visual Studio (I chose "Empty Project"). Now, I want to export it as a library, so I can use the classes in other projects. What I want is a "Header Files" folder (well, that's easy) and a .lib file. However, I still want the project to remain executable for testing. The only difference between the library-project and the executable one would be my "main.cpp" file. Is there an easy way to do exactly that, Without screwing up the project settings completely?</p>

答: Move all your files into a new static lib, make your exe just a thin wrapper and link with the static lib</p>


问:
How do I connectStyle and connect in React Native?
I'd like to export my component with native-base's connectStyle and Redux's connect but no luck so far. How do I correctly apply both to my component?

Example:

```<code>export default connectStyle('myTheme.myComponent', styles)(myComponent) connect(mapStateToProps, mapDispatchToProps)(myComponent)
</code>```

答:
Try this:

```<code>export default connect(mapStateToProps, mapDispatchToProps)(connectStyle('myTheme.myComponent', styles)(myComponent))
</code>```

This will connect the component returned from connectStyle. connectStyle returns  a component with props mapped to style, which then you can use as the component to connect dispatch and state to props.

Body:
I'd like to export my component with native-base's connectStyle and Redux's connect but no luck so far. How do I correctly apply both to my component?

Example:

export default connectStyle('myTheme.myComponent', styles)(myComponent) connect(mapStateToProps, mapDispatchToProps)(myComponent)

Body:
Try this:

export default connect(mapStateToProps, mapDispatchToProps)(connectStyle('myTheme.myComponent', styles)(myComponent))

This will connect the component returned from connectStyle. connectStyle returns  a component with props mapped to style, which then you can use as the component to connect dispatch and state to props.


问:
Precomputing simple values for a function in Go
I just started using Go for a simple web programming project, but I can't quite figure out how to accomplish simple pre-computation local to a single function. This is something I do quite frequently in OCaml, e.g.:

```<code>(* maybe render_page is a handler function for an HTTP server or something *)
let render_page =
  (* let's say that Template.prepare takes a template string and returns its compiled representation *)
  let templ = Template.prepare "user: {{.}}, group: {{.}}" in
  (* return an anonymous function *)
  fun user group ->
    templ [user; group]
</code>```

For those unfamiliar with OCaml, what's happening above is I'm binding the name render_page to a function that takes two parameters and presumably returns a web page, but internally I'm first creating a local binding to templ (this binding is only visible within the definition of render_page, and the computation only happens once) and then using that binding within an anonymous function, which is the actual value bound to render_page. So when you call render_page, templ isn't recompiled every time: it's just fetched from the closure environment.

Is there a common pattern for accomplishing something like this in Go? I'd like to avoid global variables as much as possible. I'm aware that "global" variables may be confined to a package's name space, which is what I'm currently doing, but I'd like to restrict the visibility of these precomputed expressions to just the functions in which they're needed.

Thanks!

答:
In addition to the other answers here, note that once you define a closure, you can bind it to a global variable and treat it like other functions.
Here is eugenioy's answer slightly modified :

```<code>var scan = matcher("123")

func main() {
    fmt.Println(scan("456"))
    fmt.Println(scan("123"))
}
</code>```

Here, scan is a global closure, which is very close to what you did in OCaml.

https://play.golang.org/p/Lc0SC53b-0

Body:
I just started using Go for a simple web programming project, but I can't quite figure out how to accomplish simple pre-computation local to a single function. This is something I do quite frequently in OCaml, e.g.:

(* maybe render_page is a handler function for an HTTP server or something *)
let render_page =
  (* let's say that Template.prepare takes a template string and returns its compiled representation *)
  let templ = Template.prepare "user: {{.}}, group: {{.}}" in
  (* return an anonymous function *)
  fun user group ->
    templ [user; group]

For those unfamiliar with OCaml, what's happening above is I'm binding the name render_page to a function that takes two parameters and presumably returns a web page, but internally I'm first creating a local binding to templ (this binding is only visible within the definition of render_page, and the computation only happens once) and then using that binding within an anonymous function, which is the actual value bound to render_page. So when you call render_page, templ isn't recompiled every time: it's just fetched from the closure environment.

Is there a common pattern for accomplishing something like this in Go? I'd like to avoid global variables as much as possible. I'm aware that "global" variables may be confined to a package's name space, which is what I'm currently doing, but I'd like to restrict the visibility of these precomputed expressions to just the functions in which they're needed.

Thanks!

Body:
In addition to the other answers here, note that once you define a closure, you can bind it to a global variable and treat it like other functions.
Here is eugenioy's answer slightly modified :

var scan = matcher("123")

func main() {
    fmt.Println(scan("456"))
    fmt.Println(scan("123"))
}

Here, scan is a global closure, which is very close to what you did in OCaml.

https://play.golang.org/p/Lc0SC53b-0


问:
Dictionary lookup in django templates
```<code>{% for dispN0, tableDataSet0 in tabulatedTable.items %}
    {% for dispN in orderChanels %}
        {% for antenaName, antenaLevel in tableDataSet0.{{dispN}}.items %}
             <td>{{antenaName}}</td>
        {% endfor %}
    {% endfor %}
{% endfor %}
</code>```

Here {{dispN}} is integers numbers will come..like 36, 42, etc. If i give tableDataSet0.36.items it's working fine. But I need multiples in the place 36.

答:
You need to write an own template filter to lookup the value of a dictionary or an object:

Create a file like utils.py within a templatetags folder within your app like this:

```<code>app_dir/
├── __init__.py
├── models.py
  ...
├── templatetags/
│   ├── __init__.py  # required for python 2.7
│   └── utils.py
  ...
└── views.py
</code>```

And fill it with this content:

```<code>from django import template

register = template.Library()

@register.filter
def lookup(value, key):
    return value.get(key, [])
</code>```

Now you can use this filter in your template like this:

```<code>{% load utils %}

{% for dispN0, tableDataSet0 in tabulatedTable.items %}
    {% for dispN in orderChanels %}

        {% with tableData = tableDataSet0|lookup:dispN %}
            {% for antenaName, antenaLevel in tableData.items %}
                <td>{{antenaName}}</td>
            {% endfor %}
        {% endwith %}

    {% endfor %}
{% endfor %}
</code>```

Read more about

Custom template tags and filters

the {% with %} templatetag

Title: Dictionary lookup in django templates

Body:
{% for dispN0, tableDataSet0 in tabulatedTable.items %}
    {% for dispN in orderChanels %}
        {% for antenaName, antenaLevel in tableDataSet0.{{dispN}}.items %}
             {{antenaName}}
        {% endfor %}
    {% endfor %}
{% endfor %}

Here {{dispN}} is integers numbers will come..like 36, 42, etc. If i give tableDataSet0.36.items it's working fine. But I need multiples in the place 36.

Body:
You need to write an own template filter to lookup the value of a dictionary or an object:

Create a file like utils.py within a templatetags folder within your app like this:

app_dir/
├── __init__.py
├── models.py
  ...
├── templatetags/
│   ├── __init__.py  # required for python 2.7
│   └── utils.py
  ...
└── views.py

And fill it with this content:

from django import template

register = template.Library()

@register.filter
def lookup(value, key):
    return value.get(key, [])

Now you can use this filter in your template like this:

{% load utils %}

{% for dispN0, tableDataSet0 in tabulatedTable.items %}
    {% for dispN in orderChanels %}

        {% with tableData = tableDataSet0|lookup:dispN %}
            {% for antenaName, antenaLevel in tableData.items %}
                <td>{{antenaName}}</td>
            {% endfor %}
        {% endwith %}

    {% endfor %}
{% endfor %}

Read more about

Custom template tags and filters

the {% with %} templatetag


问:
Create multi-level lookup table with lodash
Lets pretend an api is returning the structure in apiResult, and I want to create a two-level index for looking up what comments a given author have made on a given article.

The lookup table for the authors, articles and comments it self is easy enough, but I struggle with the CommentsByArticleAndAuthor-lookup.

In the mapped structure, I'm showing how I'm making the lookup index for the three 'easy' parts, and also how I want the CommentsByArticleAndAuthor to look.

How can I go forward generating this index?

var apiResult = {
  Authors: [
    {
      Id: "author-id-1",
      Name: "Author One"
    },
    {
      Id: "author-id-2",
      Name: "Author Two"
    }
  ],
  Articles: [
    {
      Id: "article-id-1",
      Title: "This Great Article"
    }
  ],
  Comments: [
    {
       Id: "comment-id-1",
       AuthorId: "author-id-1",
       ArticleId: "article-id-1",
       Comment: "that great, hu?"
    },
    {
      Id: "comment-id-2",
      AuthorId: "author-id-2",
      ArticleId: "article-id-1",
      Comment: "yes, that great"
    }
  ]
}

var mapped = {
  Authors: _.keyBy(apiResult.Authors, 'Id'),
  Articles: _.keyBy(apiResult.Articles, 'Id'),
  Comments: _.keyBy(apiResult.Comments, 'Id'),
  CommentsByArticleAndAuthor: {
    "article-id-1": {
      "author-id-1": [ "comment-id-1" ],
      "author-id-2": [ "comment-id-2" ]
    }
  }
}

console.log(JSON.stringify(mapped, null, 2));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script></code>```

答:
You can reduce the apiResult.Comments into the desired result:

CommentsByArticleAndAuthor: apiResult.Comments.reduce((result, comment) => Object.assign(result, {
  [comment.ArticleId]: Object.assign(result[comment.ArticleId] || {}, {
    [comment.AuthorId]: result[comment.ArticleId] && result[comment.ArticleId][comment.AuthorId]
      ? result[comment.ArticleId][comment.AuthorId].push(comment.Id)
      : [comment.Id]
  })
}), {})
```

<p>Your example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var apiResult = {
  Authors: [
    {
      Id: "author-id-1",
      Name: "Author One"
    },
    {
      Id: "author-id-2",
      Name: "Author Two"
    }
  ],
  Articles: [
    {
      Id: "article-id-1",
      Title: "This Great Article"
    }
  ],
  Comments: [
    {
       Id: "comment-id-1",
       AuthorId: "author-id-1",
       ArticleId: "article-id-1",
       Comment: "that great, hu?"
    },
    {
      Id: "comment-id-2",
      AuthorId: "author-id-2",
      ArticleId: "article-id-1",
      Comment: "yes, that great"
    }
  ]
}

var mapped = {

  CommentsByArticleAndAuthor: {
    "article-id-1": {
      "author-id-1": [ "comment-id-1" ],
      "author-id-2": [ "comment-id-2" ]
    }
  },
  CommentsByArticleAndAuthor: apiResult.Comments.reduce((result, comment) => Object.assign(result, {
    [comment.ArticleId]: Object.assign(result[comment.ArticleId] || {}, {
      [comment.AuthorId]: result[comment.ArticleId] && result[comment.ArticleId][comment.AuthorId]
        ? result[comment.ArticleId][comment.AuthorId].push(comment.Id)
        : [comment.Id]
    })
  }), {})
}

console.log(mapped);</code>```

```

Body:
You can reduce the apiResult.Comments into the desired result:

CommentsByArticleAndAuthor: apiResult.Comments.reduce((result, comment) => Object.assign(result, {
  [comment.ArticleId]: Object.assign(result[comment.ArticleId] || {}, {
    [comment.AuthorId]: result[comment.ArticleId] && result[comment.ArticleId][comment.AuthorId]
      ? result[comment.ArticleId][comment.AuthorId].push(comment.Id)
      : [comment.Id]
  })
}), {})

Your example:

var apiResult = {
  Authors: [
    {
      Id: "author-id-1",
      Name: "Author One"
    },
    {
      Id: "author-id-2",
      Name: "Author Two"
    }
  ],
  Articles: [
    {
      Id: "article-id-1",
      Title: "This Great Article"
    }
  ],
  Comments: [
    {
       Id: "comment-id-1",
       AuthorId: "author-id-1",
       ArticleId: "article-id-1",
       Comment: "that great, hu?"
    },
    {
      Id: "comment-id-2",
      AuthorId: "author-id-2",
      ArticleId: "article-id-1",
      Comment: "yes, that great"
    }
  ]
}

var mapped = {

  CommentsByArticleAndAuthor: {
    "article-id-1": {
      "author-id-1": [ "comment-id-1" ],
      "author-id-2": [ "comment-id-2" ]
    }
  },
  CommentsByArticleAndAuthor: apiResult.Comments.reduce((result, comment) => Object.assign(result, {
    [comment.ArticleId]: Object.assign(result[comment.ArticleId] || {}, {
      [comment.AuthorId]: result[comment.ArticleId] && result[comment.ArticleId][comment.AuthorId]
        ? result[comment.ArticleId][comment.AuthorId].push(comment.Id)
        : [comment.Id]
    })
  }), {})
}

console.log(mapped);

<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>


问:
QAbstractTableModel strange rowCount
I have an abstractTable model with a very odd problem.

The rowCount method;

```<code>int ordersModel::rowCount(const QModelIndex &) const
{
    int i = oData->count();
    qDebug() << "rowc=" << i;

    return 711;
  //  return   oData->count();

}
</code>```

Works when I hard code the value (711 or something lower) but if I
use return i; or return oData->count(); the table displays nothing. (qDebug() reports that the data has 711 entries.

The headers appear correctly. I'm in Qt 5.4.1, Windows 7.

Stumped!

答:
Your problem may have nothing to do with the rowCount method itself, although even that method is not correct - see the other answer. Other aspects of the model's implementation likely don't fulfill the basic contract that every model must fulfill.

The following sequence of events takes place:

Your model starts with no elements.

A view is attached to the model. The view expects the model to fulfill the requirements of a QAbstractItemModel.

You add data to the model. The model fails to emit the rowsInserted signal - it doesn't call beginInsertRows and endInsertRows. It has broken its contract.

You've now triggered undefined behavior in the view and Things Don't Work™.

See the first section of this answer about model semantics, and make sure you understand it and follow the requirements.

Title: QAbstractTableModel strange rowCount

Body:
I have an abstractTable model with a very odd problem.

The rowCount method;

int ordersModel::rowCount(const QModelIndex &) const
{
    int i = oData->count();
    qDebug() << "rowc=" <count();

}

Works when I hard code the value (711 or something lower) but if I
use return i; or return oData->count(); the table displays nothing. (qDebug() reports that the data has 711 entries.

The headers appear correctly. I'm in Qt 5.4.1, Windows 7.

Stumped!


问:
Entity Framework 6 code-first migration - starting with the CreateDatabaseIfNotExists initializer
I have started an EF6 project to store measurement results from analytical instruments. Each instrument has a built-in PC with and it's own results database.

Initially, the database initializer CreateDatabaseIfNotExists was used. On database creation, it creates an entry in the __MigrationHistory table with a non-unique MigrationId entry (timestamp differs from instrument to instrument, e.g. 201706011336597_InitialCreate), the ContextKey if the fully qualified type of my derived DbContext.

After a while, it was decided to add more result data to the database... Furtunately, only three new tables are required. There are no changes in the existing tables.

For that, I wanted to use the MigrateDatabaseToLatestVersion initializer. But I have to support the following two scenarios:

Existing database with the non-unique MigrationId, that has to be migrated to the extended version with the three new tables.

No database, create the database with the the MigrateDatabaseToLatestVersion initializer.

How can I do this?

I have created an initial migration using the add-migration PM console command from the initial DbContext. That works well with scenario 2 (no database exists). From that starting point I can update my DbContext and create a new migration with the three new tables.

But how to support scenario 1? The Up() method of the initial migration contains the table creation code, that is not nessessary, because the tables already exist. Is an empty migration (add-migration -IgnoreChanges) helpful, maybe with a later timestamp than the initial migration?

Note: I have no access from the PM console to the target database(s), only on my developer machine to a test database.

Thanks and best regards

Karsten

Update:
I have modified the created initial migration with the static flag TablesAlreadyCreated.

```<code>  public partial class InitialMigraCreate : DbMigration
  {
    /// <summary>
    /// Set this field to true, if the tables are already created by the
    /// CreateDatabaseIfNotExists database initializer. Then, the Up()
    /// and Down() methods do nothing, but the
    /// migration is added to the __MigrationHistory table.
    /// </summary>
    public static bool TablesAlreadyCreated = false;

    public override void Up()
    {
      if (TablesAlreadyCreated)
        return;

      // several CreateTable calls here
    }

    /// <inheritdoc/>
    public override void Down()
    {
      if (TablesAlreadyCreated)
        return;

      // several Drop... calls here
    }
  }
</code>```

I have also implemented a new database initializer class as follows:

```<code>public class MigrateDatabaseToLatestVersionEx<TContext, TMigrationsConfiguration> : IDatabaseInitializer<TContext>
    where TContext : DbContext
    where TMigrationsConfiguration : DbMigrationsConfiguration<TContext>, new()

{
    ...

    /// <inheritdoc />
    public virtual void InitializeDatabase(TContext context)
    {
      if (context == null)
        throw new ArgumentNullException("context");

      // check whether a first migration exists from the CreateDatabaseIfNotExists database initializer
      var firstConfig            = new ConfigurationAutoCreatedDatabase();
      firstConfig.TargetDatabase = _config.TargetDatabase;
      var firstMigrator          = new DbMigrator(firstConfig);
      var firstDbMigrations      = firstMigrator.GetDatabaseMigrations();

      // create the default migrator with the current configuration
      var migrator = new DbMigrator(_config);

      if (1 == firstDbMigrations.Count(migra => migra.EndsWith("_InitialCreate", StringComparison.InvariantCultureIgnoreCase)))
      { // This database was created using the CreateDatabaseIfNotExists database initializer.
        // That's an indication whether it's an old database
        // Do the custom migration here!
        InitialMigraCreate.TablesAlreadyCreated = true;

        migrator.Update();
      }
      else
      { // do the default migration the database was created with this MigrateDatabaseToLatestVersionEx initializer
        InitialMigraCreate.TablesAlreadyCreated = false;

        migrator.Update();
      }
    }
}
</code>```

It checks, whether the initial migration entry is from the CreateDatabaseIfNotExists initializer and disables the table creation/drop calls in the Up()/Down() methods in that case. ConfigurationAutoCreatedDatabase is a manually created derived DbMigrationsConfiguration class:

```<code>internal sealed class ConfigurationAutoCreatedDatabase : DbMigrationsConfiguration<MyNamespace.MyDbContext>
{
    /// <summary>
    /// Creates a <c>ConfigurationAutoCreated</c> object (default constructor).
    /// </summary>
    public ConfigurationAutoCreatedDatabase()
    {
      this.AutomaticMigrationsEnabled        = false;
      this.AutomaticMigrationDataLossAllowed = false;
      this.ContextKey                        = "MyNamespace.MyDbContext";
    }
}
</code>```

So, it works for both scenarios. I hope that helps other guys with a similar problem. It would be interesting, if there is an out-of-the-box EF workflow for that task.

答:
This is a very common scenario that EF handles nicely. The non-migration initializers (CreateDatabaseIfNotExists, etc) should be used in very early development (when you don't care about the data except for stuff that is seeded).

Once you are switching to migrations you should generate a baseline migration that takes a snapshot of your current model as you indicate (add-migration MyStartPoint -IgnoreChanges). This adds a migration with no Up() code and stores the current state of your code first model so that when you change the model only those changes are reflected. You could accomplish the same thing by commenting out the items that exist from the Up() code.

Now when you run against an existing database, it will check __MigrationHistory to see which migrations have been applied. If the database does not exist, it will be created. See here and here for more info.

Not sure what you are talking about with the MigrationId. EF handles that automatically unless you change your namespace (there is a workaround for that as well).

Body:
I have started an EF6 project to store measurement results from analytical instruments. Each instrument has a built-in PC with and it's own results database.

Initially, the database initializer CreateDatabaseIfNotExists was used. On database creation, it creates an entry in the __MigrationHistory table with a non-unique MigrationId entry (timestamp differs from instrument to instrument, e.g. 201706011336597_InitialCreate), the ContextKey if the fully qualified type of my derived DbContext.

After a while, it was decided to add more result data to the database... Furtunately, only three new tables are required. There are no changes in the existing tables.

For that, I wanted to use the MigrateDatabaseToLatestVersion initializer. But I have to support the following two scenarios:

Existing database with the non-unique MigrationId, that has to be migrated to the extended version with the three new tables.

No database, create the database with the the MigrateDatabaseToLatestVersion initializer.

How can I do this?

I have created an initial migration using the add-migration PM console command from the initial DbContext. That works well with scenario 2 (no database exists). From that starting point I can update my DbContext and create a new migration with the three new tables.

But how to support scenario 1? The Up() method of the initial migration contains the table creation code, that is not nessessary, because the tables already exist. Is an empty migration (add-migration -IgnoreChanges) helpful, maybe with a later timestamp than the initial migration?

Note: I have no access from the PM console to the target database(s), only on my developer machine to a test database.

Thanks and best regards

Karsten

Update:
I have modified the created initial migration with the static flag TablesAlreadyCreated.

  public partial class InitialMigraCreate : DbMigration
  {
    ///
    /// Set this field to true, if the tables are already created by the
    /// CreateDatabaseIfNotExists database initializer. Then, the Up()
    /// and Down() methods do nothing, but the
    /// migration is added to the __MigrationHistory table.
    ///
    public static bool TablesAlreadyCreated = false;

    public override void Up()
    {
      if (TablesAlreadyCreated)
        return;

      // several CreateTable calls here
    }

    /// <inheritdoc/>
    public override void Down()
    {
      if (TablesAlreadyCreated)
        return;

      // several Drop... calls here
    }
  }

I have also implemented a new database initializer class as follows:

public class MigrateDatabaseToLatestVersionEx<TContext, TMigrationsConfiguration> : IDatabaseInitializer<TContext>
    where TContext : DbContext
    where TMigrationsConfiguration : DbMigrationsConfiguration<TContext>, new()

{
    ...

    /// <inheritdoc />
    public virtual void InitializeDatabase(TContext context)
    {
      if (context == null)
        throw new ArgumentNullException("context");

      // check whether a first migration exists from the CreateDatabaseIfNotExists database initializer
      var firstConfig            = new ConfigurationAutoCreatedDatabase();
      firstConfig.TargetDatabase = _config.TargetDatabase;
      var firstMigrator          = new DbMigrator(firstConfig);
      var firstDbMigrations      = firstMigrator.GetDatabaseMigrations();

      // create the default migrator with the current configuration
      var migrator = new DbMigrator(_config);

      if (1 == firstDbMigrations.Count(migra => migra.EndsWith("_InitialCreate", StringComparison.InvariantCultureIgnoreCase)))
      { // This database was created using the CreateDatabaseIfNotExists database initializer.
        // That's an indication whether it's an old database
        // Do the custom migration here!
        InitialMigraCreate.TablesAlreadyCreated = true;

        migrator.Update();
      }
      else
      { // do the default migration the database was created with this MigrateDatabaseToLatestVersionEx initializer
        InitialMigraCreate.TablesAlreadyCreated = false;

        migrator.Update();
      }
    }
}

It checks, whether the initial migration entry is from the CreateDatabaseIfNotExists initializer and disables the table creation/drop calls in the Up()/Down() methods in that case. ConfigurationAutoCreatedDatabase is a manually created derived DbMigrationsConfiguration class:

internal sealed class ConfigurationAutoCreatedDatabase : DbMigrationsConfiguration<MyNamespace.MyDbContext>
{
    ///
    /// Creates a <c>ConfigurationAutoCreated</c> object (default constructor).
    ///
    public ConfigurationAutoCreatedDatabase()
    {
      this.AutomaticMigrationsEnabled        = false;
      this.AutomaticMigrationDataLossAllowed = false;
      this.ContextKey                        = "MyNamespace.MyDbContext";
    }
}

So, it works for both scenarios. I hope that helps other guys with a similar problem. It would be interesting, if there is an out-of-the-box EF workflow for that task.


问:
Is there a bug in method SET_DATA_ROW of class CL_SALV_TREE?
I spotted some very strange behavior using hierarchical SALV (class CL_SALV_TREE).

If I use the set_data_row method directly after creating the node instance then I receive the correct hierarchy.

```<code>REPORT zzy.

CLASS lcl_main DEFINITION FINAL CREATE PRIVATE.
  PUBLIC SECTION.
    CLASS-METHODS:
      main
        RAISING cx_salv_msg cx_salv_error.
ENDCLASS.

CLASS lcl_main IMPLEMENTATION.
  METHOD main.
    DATA: lt_data TYPE STANDARD TABLE OF t000.
    cl_salv_tree=>factory(
      IMPORTING
        r_salv_tree = DATA(lo_salv_tree)
      CHANGING
        t_table = lt_data
    ).

    DATA(lo_tree_settings) = lo_salv_tree->get_tree_settings( ).
    lo_tree_settings->set_hierarchy_header( `Hierarchy` ).
    lo_tree_settings->set_hierarchy_size( 30 ).

    DATA(lo_nodes) = lo_salv_tree->get_nodes( ).
    DATA(lo_root_node) = lo_nodes->add_node(
      related_node = space
      relationship = if_salv_c_node_relation=>last_child
      data_row = VALUE t000( mandt = '100' )
      collapsed_icon = '@3S\QStatus: Collapsed@'
      expanded_icon = '@3T\QStatus: Expanded@'
      row_style = if_salv_c_tree_style=>emphasized_positive
      text = '100'
    ).
    lo_root_node->set_data_row( VALUE t000( mandt = '100' ) ).
    lo_root_node->get_hierarchy_item( )->set_icon( '@0V\QOK@' ).

    DATA(lo_node1) = lo_nodes->add_node(
      related_node = lo_root_node->get_key( )
      relationship = cl_gui_column_tree=>relat_last_child
      text = '200'
    ).
    lo_node1->set_data_row( VALUE t000( mandt = '200' ) ).
    DATA(lo_node2) = lo_nodes->add_node(
      related_node = lo_node1->get_key( )
      relationship = cl_gui_column_tree=>relat_last_child
      text = '300'
    ).
    lo_node2->set_data_row( VALUE t000( mandt = '300' ) ).

    DATA(lo_node3) = lo_nodes->add_node(
      related_node = lo_node2->get_key( )
      relationship = cl_gui_column_tree=>relat_last_child
      text = '400'
    ).
    lo_node3->set_data_row( VALUE t000( mandt = '400' ) ).

    lo_salv_tree->display( ).
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  TRY .
    lcl_main=>main( ).
  CATCH cx_salv_msg cx_salv_error.
    ASSERT 0 = 1.
  ENDTRY.
</code>```

However if I use set_data_row method at the end of my main method, then the result is totally unexpected.

```<code>REPORT zzy.

CLASS lcl_main DEFINITION FINAL CREATE PRIVATE.
  PUBLIC SECTION.
    CLASS-METHODS:
      main
        RAISING cx_salv_msg cx_salv_error.
ENDCLASS.

CLASS lcl_main IMPLEMENTATION.
  METHOD main.
    DATA: lt_data TYPE STANDARD TABLE OF t000.
    cl_salv_tree=>factory(
      IMPORTING
        r_salv_tree = DATA(lo_salv_tree)
      CHANGING
        t_table = lt_data
    ).

    DATA(lo_tree_settings) = lo_salv_tree->get_tree_settings( ).
    lo_tree_settings->set_hierarchy_header( `Hierarchy` ).
    lo_tree_settings->set_hierarchy_size( 30 ).

    DATA(lo_nodes) = lo_salv_tree->get_nodes( ).
    DATA(lo_root_node) = lo_nodes->add_node(
      related_node = space
      relationship = if_salv_c_node_relation=>last_child
      data_row = VALUE t000( mandt = '100' )
      collapsed_icon = '@3S\QStatus: Collapsed@'
      expanded_icon = '@3T\QStatus: Expanded@'
      row_style = if_salv_c_tree_style=>emphasized_positive
      text = '100'
    ).
    lo_root_node->get_hierarchy_item( )->set_icon( '@0V\QOK@' ).

    DATA(lo_node1) = lo_nodes->add_node(
      related_node = lo_root_node->get_key( )
      relationship = cl_gui_column_tree=>relat_last_child
      text = '200'
    ).

    DATA(lo_node2) = lo_nodes->add_node(
      related_node = lo_node1->get_key( )
      relationship = cl_gui_column_tree=>relat_last_child
      text = '300'
    ).

    DATA(lo_node3) = lo_nodes->add_node(
      related_node = lo_node2->get_key( )
      relationship = cl_gui_column_tree=>relat_last_child
      text = '400'
    ).

    lo_root_node->set_data_row( VALUE t000( mandt = '100' ) ).
    lo_node1->set_data_row( VALUE t000( mandt = '200' ) ).
    lo_node2->set_data_row( VALUE t000( mandt = '300' ) ).
    lo_node3->set_data_row( VALUE t000( mandt = '400' ) ).

    lo_salv_tree->display( ).
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  TRY .
    lcl_main=>main( ).
  CATCH cx_salv_msg cx_salv_error.
    ASSERT 0 = 1.
  ENDTRY.
</code>```

Is this a bug in this component? I could not find any documentation that would explain this strange behavior.

答:
By calling set_data_row method you overwrite all raw data, including child relations.

In the first example you always set mandt first, and add node later on. If you would do it the other way around, you would also get 'one level deep' tree.

ContentLicense: CC BY-SA 4.0

Body:
I spotted some very strange behavior using hierarchical SALV (class CL_SALV_TREE).

If I use the set_data_row method directly after creating the node instance then I receive the correct hierarchy.

REPORT zzy.

CLASS lcl_main DEFINITION FINAL CREATE PRIVATE.
  PUBLIC SECTION.
    CLASS-METHODS:
      main
        RAISING cx_salv_msg cx_salv_error.
ENDCLASS.

CLASS lcl_main IMPLEMENTATION.
  METHOD main.
    DATA: lt_data TYPE STANDARD TABLE OF t000.
    cl_salv_tree=>factory(
      IMPORTING
        r_salv_tree = DATA(lo_salv_tree)
      CHANGING
        t_table = lt_data
    ).

    DATA(lo_tree_settings) = lo_salv_tree->get_tree_settings( ).
    lo_tree_settings->set_hierarchy_header( `Hierarchy` ).
    lo_tree_settings->set_hierarchy_size( 30 ).

    DATA(lo_nodes) = lo_salv_tree->get_nodes( ).
    DATA(lo_root_node) = lo_nodes->add_node(
      related_node = space
      relationship = if_salv_c_node_relation=>last_child
      data_row = VALUE t000( mandt = '100' )
      collapsed_icon = '@3S\QStatus: Collapsed@'
      expanded_icon = '@3T\QStatus: Expanded@'
      row_style = if_salv_c_tree_style=>emphasized_positive
      text = '100'
    ).
    lo_root_node->set_data_row( VALUE t000( mandt = '100' ) ).
    lo_root_node->get_hierarchy_item( )->set_icon( '@0V\QOK@' ).

    DATA(lo_node1) = lo_nodes->add_node(
      related_node = lo_root_node->get_key( )
      relationship = cl_gui_column_tree=>relat_last_child
      text = '200'
    ).
    lo_node1->set_data_row( VALUE t000( mandt = '200' ) ).
    DATA(lo_node2) = lo_nodes->add_node(
      related_node = lo_node1->get_key( )
      relationship = cl_gui_column_tree=>relat_last_child
      text = '300'
    ).
    lo_node2->set_data_row( VALUE t000( mandt = '300' ) ).

    DATA(lo_node3) = lo_nodes->add_node(
      related_node = lo_node2->get_key( )
      relationship = cl_gui_column_tree=>relat_last_child
      text = '400'
    ).
    lo_node3->set_data_row( VALUE t000( mandt = '400' ) ).

    lo_salv_tree->display( ).
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  TRY .
    lcl_main=>main( ).
  CATCH cx_salv_msg cx_salv_error.
    ASSERT 0 = 1.
  ENDTRY.

However if I use set_data_row method at the end of my main method, then the result is totally unexpected.

REPORT zzy.

CLASS lcl_main DEFINITION FINAL CREATE PRIVATE.
  PUBLIC SECTION.
    CLASS-METHODS:
      main
        RAISING cx_salv_msg cx_salv_error.
ENDCLASS.

CLASS lcl_main IMPLEMENTATION.
  METHOD main.
    DATA: lt_data TYPE STANDARD TABLE OF t000.
    cl_salv_tree=>factory(
      IMPORTING
        r_salv_tree = DATA(lo_salv_tree)
      CHANGING
        t_table = lt_data
    ).

    DATA(lo_tree_settings) = lo_salv_tree->get_tree_settings( ).
    lo_tree_settings->set_hierarchy_header( `Hierarchy` ).
    lo_tree_settings->set_hierarchy_size( 30 ).

    DATA(lo_nodes) = lo_salv_tree->get_nodes( ).
    DATA(lo_root_node) = lo_nodes->add_node(
      related_node = space
      relationship = if_salv_c_node_relation=>last_child
      data_row = VALUE t000( mandt = '100' )
      collapsed_icon = '@3S\QStatus: Collapsed@'
      expanded_icon = '@3T\QStatus: Expanded@'
      row_style = if_salv_c_tree_style=>emphasized_positive
      text = '100'
    ).
    lo_root_node->get_hierarchy_item( )->set_icon( '@0V\QOK@' ).

    DATA(lo_node1) = lo_nodes->add_node(
      related_node = lo_root_node->get_key( )
      relationship = cl_gui_column_tree=>relat_last_child
      text = '200'
    ).

    DATA(lo_node2) = lo_nodes->add_node(
      related_node = lo_node1->get_key( )
      relationship = cl_gui_column_tree=>relat_last_child
      text = '300'
    ).

    DATA(lo_node3) = lo_nodes->add_node(
      related_node = lo_node2->get_key( )
      relationship = cl_gui_column_tree=>relat_last_child
      text = '400'
    ).

    lo_root_node->set_data_row( VALUE t000( mandt = '100' ) ).
    lo_node1->set_data_row( VALUE t000( mandt = '200' ) ).
    lo_node2->set_data_row( VALUE t000( mandt = '300' ) ).
    lo_node3->set_data_row( VALUE t000( mandt = '400' ) ).

    lo_salv_tree->display( ).
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  TRY .
    lcl_main=>main( ).
  CATCH cx_salv_msg cx_salv_error.
    ASSERT 0 = 1.
  ENDTRY.

Is this a bug in this component? I could not find any documentation that would explain this strange behavior.


问:
2 resources to notify the same service
Wanted to know if it's possible to notify the same service from two different resources:

let's say I have two configuration files:

```<code>file { "${conf_dir}/1.conf" :
  content => template('1.conf.erb'),
  owner   => $owner,
  group   => $group,
  mode    => '0777',
}

~>file { "${conf_dir}/2.conf" :
  content => template('2.conf.erb'),
  owner   => $owner,
  group   => $group,
  mode    => '0777',
}

~> service { 'some_service' :
  enable     => true,
}
</code>```

I'm not sure if the code above will even execute (because of the '~>' between the file resources)

答:
You can use the notify option to notify your service.

With your example :

```<code>file { "${conf_dir}/1.conf" :
  content => template('1.conf.erb'),
  owner   => $owner,
  group   => $group,
  mode    => '0777',
  notify  => Service['some_service'],
}

file { "${conf_dir}/2.conf" :
  content => template('2.conf.erb'),
  owner   => $owner,
  group   => $group,
  mode    => '0777',
  notify  => Service['some_service'],
}

service { 'some_service' :
  enable     => true,
}
</code>```

Title: 2 resources to notify the same service

Body:
Wanted to know if it's possible to notify the same service from two different resources:

let's say I have two configuration files:

file { "${conf_dir}/1.conf" :
  content => template('1.conf.erb'),
  owner   => $owner,
  group   => $group,
  mode    => '0777',
}

~>file { "${conf_dir}/2.conf" :
  content => template('2.conf.erb'),
  owner   => $owner,
  group   => $group,
  mode    => '0777',
}

~> service { 'some_service' :
  enable     => true,
}

I'm not sure if the code above will even execute (because of the '~>' between the file resources)

Body:
You can use the notify option to notify your service.

With your example :

file { "${conf_dir}/1.conf" :
  content => template('1.conf.erb'),
  owner   => $owner,
  group   => $group,
  mode    => '0777',
  notify  => Service['some_service'],
}

file { "${conf_dir}/2.conf" :
  content => template('2.conf.erb'),
  owner   => $owner,
  group   => $group,
  mode    => '0777',
  notify  => Service['some_service'],
}

service { 'some_service' :
  enable     => true,
}


问:
Locking a MySQL database so only one person at once can run a query?
I am having a few issues when people are trying to access a MySQL database and they are trying to update tables with the same information.

I have a webpage written using PHP. In this webpage is a query to check if certain data has been entered into the database. If the data hasn't, then i proceed to insert it. The trouble is that if two people try at the same time, the check might say the data has not been entered yet but when the insert takes place it has been by the other person.

What is the best way to handle this scenario? Can i lock the database to only process my queries first then anothers?

答:
You're looking for LOCK.

http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html

This can be run as a simple mysql_query (or MySQLi::query/prepare).

I'd say it's better to lock specific tables (although you can probably try LOCK TABLES *) that need to be locked rather than the whole database - as nothing will be able to be read. I think you're looking for something like:

```<code>LOCK TABLES items;
START TRANSACTION;
INSERT INTO items (name, label) VALUES ('foo', 'bar');
UNLOCK TABLES;
</code>```

Or in PHP:

```<code>mysql_query('LOCK TABLES items');
mysql_query("INSERT INTO items (name, label) VALUES ('foo', 'bar')");
mysql_query('UNLOCK TABLES');
</code>```

OwnerDisplayName: Gary Willoughby

LastEditorDisplayName: Jason S

Body:
You're looking for LOCK.

http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html

This can be run as a simple mysql_query (or MySQLi::query/prepare).

I'd say it's better to lock specific tables (although you can probably try LOCK TABLES *) that need to be locked rather than the whole database - as nothing will be able to be read. I think you're looking for something like:

LOCK TABLES items;
START TRANSACTION;
INSERT INTO items (name, label) VALUES ('foo', 'bar');
UNLOCK TABLES;

Or in PHP:

mysql_query('LOCK TABLES items');
mysql_query("INSERT INTO items (name, label) VALUES ('foo', 'bar')");
mysql_query('UNLOCK TABLES');

OwnerDisplayName: Ross

LastEditorDisplayName: Ross


问:
Create program installer in Visual Studio 2005?
I'm a web-guy stuck in "application world" in VS 2005.  I created my windows forms program and want to give my end users the ability to install it (and some of it's resources) into a standard Program Files/App Directory location along with a start menu/desktop launcher.

The help files don't give any instructions (that I can find).  This seems like such a trivial task to create an installer - but it's eluding me.

Any hints would be greatly appreciated!

答: The exe file is actually just a boostrap loader, which launches the MSI file.  The MSI file is the actual installation file.</p>

OwnerDisplayName: JayTee

LastEditorDisplayName: Matt Hamilton


问:
Access Google's Traffic Data through a Web Service
Is there a way I can access traffic data that Google provides through a web service?

There seems to be a GTrafficOverlay that puts traffic on top of a route on an embedded google map, but no direct web service that I can consume to, say, give the source and the destination and find the traffic between them?

Is there any other source I can get this data from?

答:
You might want to take a look at HERE MAP SERVICE. They have direct traffic data you can use, which is exactly what you need: https://developer.here.com/api-explorer/rest/traffic/traffic-flow-bounding-box

For example, by querying an area of interest, you might get something like this:

```<code>{
  "RWS": [
    {
      "RW": [
        {
          "FIS": [
            {
              "FI": [
                {
                  "TMC": {
                    "PC": 32483,
                    "DE": "SOHO",
                    "QD": "+",
                    "LE": 0.71682
                  },
                  "CF": [
                    {
                      "TY": "TR",
                      "SP": 9.1,
                      "SU": 9.1,
                      "FF": 17,
                      "JF": 3.2911,
                      "CN": 0.9
                    }
                  ]
                }
              ]
            }
          ],
....
</code>```

This example shows a current average speed SU of 9.1, where the free flow speed FF would be 17. The Jam factor JF is 3.3, which is still considered free flow but getting sluggish.
The units used (miles/km) can be defined in the API call.
To avoid dealing with TMC locations, you can ask for geocoordinates of the road segments by adding responseattributes=sh in the request.

The abbreviations used can be found here Interpreting HERE Maps real-time traffic tags:

"RWS" - A list of Roadway (RW) items

"RW" = This is the composite    item for flow across an entire roadway. A roadway item will be    present for each roadway with
  traffic flow information available

"FIS" = A list of Flow Item (FI) elements

"FI" = A single flow item

"TMC" = An ordered collection of TMC locations

"PC" = Point TMC Location Code

"DE" = Text description of the road

"QD" = Queuing direction. '+' or '-'. Note this is the opposite of the travel    direction in the fully qualified ID, For example for
  location    107+03021 the QD would be '-'

"LE" = Length of the stretch of road.    The units are defined in the file header

"CF" = Current Flow. This    element contains details about speed and Jam Factor information for    the given flow item.

"CN" = Confidence, an indication of how the    speed was determined. -1.0 road closed. 1.0=100% 0.7-100% Historical    Usually
  a value between .7 and 1.0 "FF" = The free flow speed on this

  stretch of road.

"JF" = The number between 0.0 and 10.0 indicating    the expected quality of travel. When there is a road closure, the Jam    Factor
  will be 10. As the number approaches 10.0 the quality of    travel is
  getting worse. -1.0 indicates that a Jam Factor could not    be
  calculated

"SP" = Speed (based on UNITS) capped by speed limit

"SU" = Speed (based on UNITS) not capped by speed limit

"TY" = Type    information for the given Location Referencing container. This may be    freely defined string

Also the source comes from
https://developer.here.com/rest-apis/documentation/traffic/topics/additional-parameters.html

Body:
You might want to take a look at HERE MAP SERVICE. They have direct traffic data you can use, which is exactly what you need: https://developer.here.com/api-explorer/rest/traffic/traffic-flow-bounding-box

For example, by querying an area of interest, you might get something like this:

{
  "RWS": [
    {
      "RW": [
        {
          "FIS": [
            {
              "FI": [
                {
                  "TMC": {
                    "PC": 32483,
                    "DE": "SOHO",
                    "QD": "+",
                    "LE": 0.71682
                  },
                  "CF": [
                    {
                      "TY": "TR",
                      "SP": 9.1,
                      "SU": 9.1,
                      "FF": 17,
                      "JF": 3.2911,
                      "CN": 0.9
                    }
                  ]
                }
              ]
            }
          ],
....

This example shows a current average speed SU of 9.1, where the free flow speed FF would be 17. The Jam factor JF is 3.3, which is still considered free flow but getting sluggish.
The units used (miles/km) can be defined in the API call.
To avoid dealing with TMC locations, you can ask for geocoordinates of the road segments by adding responseattributes=sh in the request.

The abbreviations used can be found here Interpreting HERE Maps real-time traffic tags:

"RWS" - A list of Roadway (RW) items

"RW" = This is the composite    item for flow across an entire roadway. A roadway item will be    present for each roadway with
  traffic flow information available

"FIS" = A list of Flow Item (FI) elements

"FI" = A single flow item

"TMC" = An ordered collection of TMC locations

"PC" = Point TMC Location Code

"DE" = Text description of the road

"QD" = Queuing direction. '+' or '-'. Note this is the opposite of the travel    direction in the fully qualified ID, For example for
  location    107+03021 the QD would be '-'

"LE" = Length of the stretch of road.    The units are defined in the file header

"CF" = Current Flow. This    element contains details about speed and Jam Factor information for    the given flow item.

"CN" = Confidence, an indication of how the    speed was determined. -1.0 road closed. 1.0=100% 0.7-100% Historical    Usually
  a value between .7 and 1.0 "FF" = The free flow speed on this

  stretch of road.

"JF" = The number between 0.0 and 10.0 indicating    the expected quality of travel. When there is a road closure, the Jam    Factor
  will be 10. As the number approaches 10.0 the quality of    travel is
  getting worse. -1.0 indicates that a Jam Factor could not    be
  calculated

"SP" = Speed (based on UNITS) capped by speed limit

"SU" = Speed (based on UNITS) not capped by speed limit

"TY" = Type    information for the given Location Referencing container. This may be    freely defined string

Also the source comes from
https://developer.here.com/rest-apis/documentation/traffic/topics/additional-parameters.html


问:
What's the advantage of multimap over map of vectors?
I don't understand why multimap exists if we can create map of vectors or map of sets.
For me only differences are:

using equal_range in multimap for getting elements of a key and in map of vectors we simply use [] operator and have vector of elements.

using multimap.insert(make_pair(key,value)) in multimap for adding elements and map_of_vectors[key].push_back(value) in map of vectors.

So why use multimap? For me it's better to have a vector than two iterators to get all values of a key.

This question applies also to unordered_map of vectors and unordered_multimap.

答:
There are many important differences between multimap<x, y> and map<x, vector<y>>

Once you had inserted a value into multimap, you know that the iterator would remain
valid until you remove it and this is very strong property, you can't have it with map of vectors.

```<code>multimap<x,y>::iterator p=mymap.insert(make_pair(a,b));
</code>```

The iterator remains valid until it is erased from map, while in second case,
it would be invalidated each time you add new entry to the vector.

Also note that map<x, vector<y>> may have an empty value set with existing key, while multimap does not.

These are different things that behave differently.

And to be honest I miss multimap in some languages that do not provide it in their library.

Body:
There are many important differences between multimap<x, y> and map<x, vector<y>>

Once you had inserted a value into multimap, you know that the iterator would remain
valid until you remove it and this is very strong property, you can't have it with map of vectors.

multimap<x,y>::iterator p=mymap.insert(make_pair(a,b));

The iterator remains valid until it is erased from map, while in second case,
it would be invalidated each time you add new entry to the vector.

Also note that map<x, vector<y>> may have an empty value set with existing key, while multimap does not.

These are different things that behave differently.

And to be honest I miss multimap in some languages that do not provide it in their library.


问:
Enabling broker after Restoring Sql Server DataBase
I have DataBase with enabled Service Broker. Then I want to restore my database in program from backup of other database, but after restoring(I restore on existing database name), my method, whitch enables Service Broker, puts this error:

```<code>    Msg 9772, Level 16, State 1, Line 1
The Service Broker in database "ServeDB2" cannot be enabled because there is already an enabled Service Broker with the same ID.
Msg 5069, Level 16, State 1, Line 1
ALTER DATABASE statement failed.
</code>```

This is my method:

```<code>public void TurnOnBroker()
{
    if (!this.database.BrokerEnabled)
    {
        this.server.KillAllProcesses(this.database.Name);
        this.database.BrokerEnabled = true;
        this.database.Alter();
        RefreshConnection();
    }
}
</code>```

What should i fix here?Any suggestions?

答:
Run this query to find out which other databases are using the same service broker as the database you are using (e.g. for a database called DATABASE_NAME)...

```<code>SELECT name, is_broker_enabled, service_broker_guid FROM sys.databases
WHERE service_broker_guid IN (SELECT service_broker_guid FROM sys.databases where name = 'DATABASE_NAME');
</code>```

... returns ...

```<code>name, is_broker_enabled, service_broker_guid
DATABASE_NAME_OTHER, 1, KBHDBVJH-SDVHIOHD-SODIVDIOH-UHDSV
DATABASE_NAME_ANOTHER, 0, KBHDBVJH-SDVHIOHD-SODIVDIOH-UHDSV
DATABASE_NAME, 0, KBHDBVJH-SDVHIOHD-SODIVDIOH-UHDSV
</code>```

Then run the following queries to obtain a new broker for your database...

```<code>ALTER DATABASE DATABASE_NAME SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE DATABASE_NAME SET NEW_BROKER;
ALTER DATABASE DATABASE_NAME SET MULTI_USER;
</code>```

Run the first query again and your database should be the only one in the list...

```<code>SELECT name, is_broker_enabled, service_broker_guid FROM sys.databases
WHERE service_broker_guid IN (SELECT service_broker_guid FROM sys.databases where name = 'DATABASE_NAME');
</code>```

... now returns ...

```<code>name, is_broker_enabled, service_broker_guid
DATABASE_NAME, 1, ASJCBUHBC-7UIOSUI-IUGGUI87-IUGHUIG
</code>```

Body:
I have DataBase with enabled Service Broker. Then I want to restore my database in program from backup of other database, but after restoring(I restore on existing database name), my method, whitch enables Service Broker, puts this error:

    Msg 9772, Level 16, State 1, Line 1
The Service Broker in database "ServeDB2" cannot be enabled because there is already an enabled Service Broker with the same ID.
Msg 5069, Level 16, State 1, Line 1
ALTER DATABASE statement failed.

This is my method:

public void TurnOnBroker()
{
    if (!this.database.BrokerEnabled)
    {
        this.server.KillAllProcesses(this.database.Name);
        this.database.BrokerEnabled = true;
        this.database.Alter();
        RefreshConnection();
    }
}

What should i fix here?Any suggestions?

Body:
Run this query to find out which other databases are using the same service broker as the database you are using (e.g. for a database called DATABASE_NAME)...

SELECT name, is_broker_enabled, service_broker_guid FROM sys.databases
WHERE service_broker_guid IN (SELECT service_broker_guid FROM sys.databases where name = 'DATABASE_NAME');

... returns ...

name, is_broker_enabled, service_broker_guid
DATABASE_NAME_OTHER, 1, KBHDBVJH-SDVHIOHD-SODIVDIOH-UHDSV
DATABASE_NAME_ANOTHER, 0, KBHDBVJH-SDVHIOHD-SODIVDIOH-UHDSV
DATABASE_NAME, 0, KBHDBVJH-SDVHIOHD-SODIVDIOH-UHDSV

Then run the following queries to obtain a new broker for your database...

ALTER DATABASE DATABASE_NAME SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE DATABASE_NAME SET NEW_BROKER;
ALTER DATABASE DATABASE_NAME SET MULTI_USER;

Run the first query again and your database should be the only one in the list...

SELECT name, is_broker_enabled, service_broker_guid FROM sys.databases
WHERE service_broker_guid IN (SELECT service_broker_guid FROM sys.databases where name = 'DATABASE_NAME');

... now returns ...

name, is_broker_enabled, service_broker_guid
DATABASE_NAME, 1, ASJCBUHBC-7UIOSUI-IUGGUI87-IUGHUIG


问:
Using something other than single or double quotes to set variable?
I have some hard coded text that contains many single quotes and double quotes.

```<code>text = "get in the "van" I said get in the 'van'"
</code>```

I can escape each double quote with \ or I can switch to single quotes on the outside and escape each single quote.

What I'd like to do is just be able to pick something else, like !
Is there something simple I can do?  In Perl I was always able to:

```<code>text = qq!this will use "whatever" I'm happy with!
</code>```

I'm using Python 3.6 if that helps.

答:
You can also concatenate multiple strings</p>

```<code>text = 'get in the "van" I said get in the ' "'van'"
</code>```

Body:
I have some hard coded text that contains many single quotes and double quotes.

text = "get in the "van" I said get in the 'van'"

I can escape each double quote with \ or I can switch to single quotes on the outside and escape each single quote.

What I'd like to do is just be able to pick something else, like !
Is there something simple I can do?  In Perl I was always able to:

text = qq!this will use "whatever" I'm happy with!

I'm using Python 3.6 if that helps.

Body:
You can also concatenate multiple strings

text = 'get in the "van" I said get in the ' "'van'"


问:
Using firebase with 000WebHost
Can I use firebase with a free web server host like 000webhost? If yes, how can I do it?

I need to implement some server code in php which is being hosted on 000webhost. I need my php code to talk to a firebase database. Is this possible?

答:
Yes it's possible with the Firebase Admin SDK for PHP.

000webhost runs PHP7 so you should be good to go.

Title: Using firebase with 000WebHost


问:
GraphQL - Is it possible to set a variable with a result for a mutation
I want to do 2 creations in my GraphQL query. (I know my query structure is not correct, but it's to illustrate my question)

```<code>mutation {
    affiliateCreate(company: "test mutation") {
    $id: id,
    affiliateUserCreate(affiliate_id: $id, name: "test name") {
      id,
      name
    },
    company
  }
}
</code>```

I want my first id result to be in variable who i pass to the second creation call? I'm very new to GraphQL and i was wondering if it's possible.

Is there any other way possible to do such thing? Or i must do 2 mutation call? The first with affiliateCreate and in it's fallback the second one?

Thank you

答:
What you want to do is not supported by GraphQL. In the Graphcool APIs we approach this kind of situation with what we call nested mutations. I've also heard it being referred to as complex mutations.

A nested create mutation is characterized by a nested input object argument. If you add an input object author to the affiliateCreate mutation, you could use it like that:

```<code>mutation createAffiliateAndUser {
  affiliateCreate(
    company: "test company"
    author: {
      name: "test user"
    }
  ) {
    id
  }
}
</code>```

This would create an affiliate, a user and then link the two together. Similarily, if you add an input object affiliates to the userCreate mutation, it could look like this:

```<code>mutation createUserAndAffiliates {
  userCreate(
    name: "test user"
    affiliates: [{
      company: "first company"
    }, {
      company: "second company"
    }]
  ) {
    id
  }
}
</code>```

Body:
I want to do 2 creations in my GraphQL query. (I know my query structure is not correct, but it's to illustrate my question)

mutation {
    affiliateCreate(company: "test mutation") {
    $id: id,
    affiliateUserCreate(affiliate_id: $id, name: "test name") {
      id,
      name
    },
    company
  }
}

I want my first id result to be in variable who i pass to the second creation call? I'm very new to GraphQL and i was wondering if it's possible.

Is there any other way possible to do such thing? Or i must do 2 mutation call? The first with affiliateCreate and in it's fallback the second one?

Thank you

Body:
What you want to do is not supported by GraphQL. In the Graphcool APIs we approach this kind of situation with what we call nested mutations. I've also heard it being referred to as complex mutations.

A nested create mutation is characterized by a nested input object argument. If you add an input object author to the affiliateCreate mutation, you could use it like that:

mutation createAffiliateAndUser {
  affiliateCreate(
    company: "test company"
    author: {
      name: "test user"
    }
  ) {
    id
  }
}

This would create an affiliate, a user and then link the two together. Similarily, if you add an input object affiliates to the userCreate mutation, it could look like this:

mutation createUserAndAffiliates {
  userCreate(
    name: "test user"
    affiliates: [{
      company: "first company"
    }, {
      company: "second company"
    }]
  ) {
    id
  }
}


问:
Explanation for event_text[-SCREEN_SIZE[1]/font_height:]?
This code is from the book "Beginning Game Development with Python and Pygame", the following script displays the events that are generated by the mouse and the keyboard on the screen:

```<code>import pygame
from pygame.locals import *
from sys import exit

pygame.init()
SCREEN_SIZE = (800, 600)
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)

font = pygame.font.SysFont("arial", 16)
font_height = font.get_linesize()
event_text = []

while True:

    event = pygame.event.wait()
    event_text.append(str(event))
    event_text = event_text[-SCREEN_SIZE[1]/font_height:]
</code>```

I have a problem with this line:

```<code>event_text = event_text[-SCREEN_SIZE[1]/font_height:]
</code>```

Could someone explain it?
Thanks in advance :)

答: It appears to be finding out how many lines of text can appear on your screen by getting the screen height, dividing it by the height of one line of text, and slicing the event_text list to get only the last how ever many lines of text.

Body:
This code is from the book "Beginning Game Development with Python and Pygame", the following script displays the events that are generated by the mouse and the keyboard on the screen:

import pygame
from pygame.locals import *
from sys import exit

pygame.init()
SCREEN_SIZE = (800, 600)
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)

font = pygame.font.SysFont("arial", 16)
font_height = font.get_linesize()
event_text = []

while True:

    event = pygame.event.wait()
    event_text.append(str(event))
    event_text = event_text[-SCREEN_SIZE[1]/font_height:]

I have a problem with this line:

event_text = event_text[-SCREEN_SIZE[1]/font_height:]

Could someone explain it?
Thanks in advance :)


问:
How to exclude a range from another range in Python?
Suppose I've a range (section) and an additional list of ranges to exclude, represented by tuples (start, end):

```<code>section=(1, 100) #Range from 1 to 100

toexclude=[(10,15),(40,50),(80,83)]  #3 sub-ranges
</code>```

I'm looking for an efficient algorithm which returns, from these two inputs, a new list of ranges like:

```<code>[(1,9),(16,39),(51,79),(84,100)]
</code>```

Which is the main range exluding the second list of ranges.

Thanks!

EDIT:

Actually the advice from deceze to use intervaltree seems to be interesting. With a few lines:

```<code>from intervaltree import Interval, IntervalTree
t=IntervalTree()
t[1:100]="main"
t.chop(10,15)
t.chop(40,50)
t.chop(80,83)
t
IntervalTree([Interval(1, 10, 'main'), Interval(15, 40, 'main'), Interval(50, 80, 'main'), Interval(83, 100, 'main')])
</code>```

The intervals are considered closed apparently, but this is a minor issue.

答:
```<code>section=(1, 100) #Range from 1 to 100

toexclude=[(10,15),(40,50),(80,83)]  #3 sub-ranges

rangelists = [x for excRange in toexclude for x in range(excRange[0], excRange[1] + 1)]
first, last = section[0], section[0]
out_ranges = []
for x in range(section[0],section[1] + 1):
    if x not in rangelists:
        if first == 'unset':
            first = x
        last = x
    elif x in rangelists:
        if last == x - 1:
            out_ranges.append((first, last))
            first = 'unset'
        else:
            continue
if first != 'unset':
    out_ranges.append((first, last))

print out_ranges
</code>```

Body:
Suppose I've a range (section) and an additional list of ranges to exclude, represented by tuples (start, end):

section=(1, 100) #Range from 1 to 100

toexclude=[(10,15),(40,50),(80,83)]  #3 sub-ranges

I'm looking for an efficient algorithm which returns, from these two inputs, a new list of ranges like:

[(1,9),(16,39),(51,79),(84,100)]

Which is the main range exluding the second list of ranges.

Thanks!

EDIT:

Actually the advice from deceze to use intervaltree seems to be interesting. With a few lines:

from intervaltree import Interval, IntervalTree
t=IntervalTree()
t[1:100]="main"
t.chop(10,15)
t.chop(40,50)
t.chop(80,83)
t
IntervalTree([Interval(1, 10, 'main'), Interval(15, 40, 'main'), Interval(50, 80, 'main'), Interval(83, 100, 'main')])

The intervals are considered closed apparently, but this is a minor issue.


问:
code has error: unable to get the vlookup property of the worksheetfunction class
I had an issue with this code before and when I tried fixing it another issue occurred. On this line of code,

```<code>If Not (IsError(Application.WorksheetFunction.VLookup(item, lookup_range, 2, False))) Then
</code>```

I get the error unable to get the vlookup property of the worksheetfunction class"

The whole code is below. Thanks for any help!

```<code>Sub code()
Columns("E:G").Insert shift:=xlToRight, copyorigin:=xlFormatFromLeftOrAbove
Range("E6").value = "Drink Price"
Range("F6").value = "Drink Revenue"
Range("G6").value = "Gross Sales less Drink Revenue"
Dim i As Variant
Dim item As Variant
Dim lookup_range As Range
Dim rev_wksht As Worksheet
Dim rev_wbk As Workbook
Dim vlkup_wbk As Workbook
Set rev_wksht = ActiveWorkbook.Sheets(1)
Set vlkup_wbk = Workbooks.Open("C:\Users\user\Documents\vlookup table drink prices.xlsx")
Set lookup_range = vlkup_wbk.Worksheets("Sheet1").Range("A:B")
i = 7
Do While rev_wksht.Cells(i, 1).value <> ""
   Set item = rev_wbk.Sheets(1).Cells(i, 1).value
    If Not (IsError(Application.WorksheetFunction.VLookup(item, lookup_range, 2, False))) Then
        rev_wksht.Cells(i, 5).value = Application.WorksheetFunction.VLookup(item, lookup_range, 2, False)
        rev_wksht.Cells(i, 6).Formula = rev_wksht.Cells(i, 11).value * rev_wksht.Cells(i, 5).value
        rev_wksht.Cells(i, 7).Formula = rev_wksht.Cells(i, 4).value - rev_wksht.Cells(i, 6).value
    ElseIf (IsError(Application.WorksheetFunction.VLookup(item, lookup_range, 2, False))) Then
        rev_wksht.Cells(i, 5).value = Empty
    End If
i = i + 1
Loop
rev_wksht.Range("F:G").NumberFormat = "#,##0.00"
rev_wksht.Cells.EntireColumn.AutoFit
End Sub
</code>```

答: Your issue is that you have not set rev_wbk.</p>

Body:
I had an issue with this code before and when I tried fixing it another issue occurred. On this line of code,

If Not (IsError(Application.WorksheetFunction.VLookup(item, lookup_range, 2, False))) Then

I get the error unable to get the vlookup property of the worksheetfunction class"

The whole code is below. Thanks for any help!

Sub code()
Columns("E:G").Insert shift:=xlToRight, copyorigin:=xlFormatFromLeftOrAbove
Range("E6").value = "Drink Price"
Range("F6").value = "Drink Revenue"
Range("G6").value = "Gross Sales less Drink Revenue"
Dim i As Variant
Dim item As Variant
Dim lookup_range As Range
Dim rev_wksht As Worksheet
Dim rev_wbk As Workbook
Dim vlkup_wbk As Workbook
Set rev_wksht = ActiveWorkbook.Sheets(1)
Set vlkup_wbk = Workbooks.Open("C:\Users\user\Documents\vlookup table drink prices.xlsx")
Set lookup_range = vlkup_wbk.Worksheets("Sheet1").Range("A:B")
i = 7
Do While rev_wksht.Cells(i, 1).value <> ""
   Set item = rev_wbk.Sheets(1).Cells(i, 1).value
    If Not (IsError(Application.WorksheetFunction.VLookup(item, lookup_range, 2, False))) Then
        rev_wksht.Cells(i, 5).value = Application.WorksheetFunction.VLookup(item, lookup_range, 2, False)
        rev_wksht.Cells(i, 6).Formula = rev_wksht.Cells(i, 11).value * rev_wksht.Cells(i, 5).value
        rev_wksht.Cells(i, 7).Formula = rev_wksht.Cells(i, 4).value - rev_wksht.Cells(i, 6).value
    ElseIf (IsError(Application.WorksheetFunction.VLookup(item, lookup_range, 2, False))) Then
        rev_wksht.Cells(i, 5).value = Empty
    End If
i = i + 1
Loop
rev_wksht.Range("F:G").NumberFormat = "#,##0.00"
rev_wksht.Cells.EntireColumn.AutoFit
End Sub


答: You have declared Dim rev_wbk As Workbook but you have not initialized it and hence you are getting the error

Title: code has error: unable to get the vlookup property of the worksheetfunction class


问:
Atlassian Confluence : Updating parent container of an attachment
I'd like to move an attachment to a different space (i.e, update the parent container of an attachment in a Confluence page) using Cloud REST API and "curl" command. I looked up REST API endpoint URL and found this:

```<code>PUT /rest/api/content/{id}/child/attachment/{attachmentId}
</code>```

Could somebody provide an example for a correctly constructed JSON input to achieve this? I tried the one below to move an attachment called "test.jpeg" with ID "att000" and current version 5 to parent with ID 1234, but it fails:

```<code>curl -v -u 'admin:password' -X PUT -H 'Content-Type:application/json' -d '{"id":"att000","type":"attachment","title":"test.jpeg","version":{"number":5,"minorEdit":false},"ancestors":[{"id":1234}]' -H ‘X-Atlassian-Token:access-token' https://test.atlassian.net/wiki/rest/api/content/170234/child/attachment | python -m json.tool
</code>```

Given below is the error message

```<code>< HTTP/1.1 415 Unsupported Media Type
.
.
.
No JSON object could be decoded
</code>```

Thank you for your time!

答:
You have to set the container property in the request object.

Specify "container":{"id":"123456","type":"attachment"}

```<code>curl -v -u 'admin:password' -X PUT -H 'Content-Type:application/json' -d '{"id":"att000","type":"attachment","title":"test.jpeg","version":{"number":5,"minorEdit":false},"container":{"id":"123456","type":"attachment"}, "ancestors":[{"id":1234}]' -H ‘X-Atlassian-Token:access-token' https://test.atlassian.net/wiki/rest/api/content/170234/child/attachment | python -m json.tool
</code>```

id => id of the page where attachment is being moved.

Body:
I'd like to move an attachment to a different space (i.e, update the parent container of an attachment in a Confluence page) using Cloud REST API and "curl" command. I looked up REST API endpoint URL and found this:

PUT /rest/api/content/{id}/child/attachment/{attachmentId}

Could somebody provide an example for a correctly constructed JSON input to achieve this? I tried the one below to move an attachment called "test.jpeg" with ID "att000" and current version 5 to parent with ID 1234, but it fails:

curl -v -u 'admin:password' -X PUT -H 'Content-Type:application/json' -d '{"id":"att000","type":"attachment","title":"test.jpeg","version":{"number":5,"minorEdit":false},"ancestors":[{"id":1234}]' -H ‘X-Atlassian-Token:access-token' https://test.atlassian.net/wiki/rest/api/content/170234/child/attachment | python -m json.tool

Given below is the error message

< HTTP/1.1 415 Unsupported Media Type
.
.
.
No JSON object could be decoded

Thank you for your time!

Body:
You have to set the container property in the request object.

Specify "container":{"id":"123456","type":"attachment"}

curl -v -u 'admin:password' -X PUT -H 'Content-Type:application/json' -d '{"id":"att000","type":"attachment","title":"test.jpeg","version":{"number":5,"minorEdit":false},"container":{"id":"123456","type":"attachment"}, "ancestors":[{"id":1234}]' -H ‘X-Atlassian-Token:access-token' https://test.atlassian.net/wiki/rest/api/content/170234/child/attachment | python -m json.tool

id => id of the page where attachment is being moved.


答:
I get the error "Run time error 91, object variable or with block variable not set" but I have set when I assign item's value. I tried with and without set...

Set keyword is used to assign to an object-type only. item is Variant and while it could be an object, a Range.Value is not an object type, it's a string, numeric, or error type and would be assigned like:

```<code>item = ...
</code>```

The actual Runtime 91 error means you're referencing an object variable which hasn't yet been assigned an instance of an object. Look over your code: you don't ever Set rev_wbk ... to any existing Workbook so while you've declared it as a Workbook object, it's presently a Nothing, and you can't do Nothing.Method or Nothing.Property without raising the 91 error :)

Body:
I get the error "Run time error 91, object variable or with block variable not set" but I have set when I assign item's value. I tried with and without set...

Set keyword is used to assign to an object-type only. item is Variant and while it could be an object, a Range.Value is not an object type, it's a string, numeric, or error type and would be assigned like:

item = ...

The actual Runtime 91 error means you're referencing an object variable which hasn't yet been assigned an instance of an object. Look over your code: you don't ever Set rev_wbk ... to any existing Workbook so while you've declared it as a Workbook object, it's presently a Nothing, and you can't do Nothing.Method or Nothing.Property without raising the 91 error :)