问:
How to display all components on a single page in angular 2 without bootstrapping them in appModule?
I want to display all of my angular 2 components on a single page so that i can see them all after I start 'npm'... How to do this with the help of router-outlet or parent-child relationship or anything like that??
I want to avoid bootstrapping all those components in AppModule.ts</p>

答:
You have two choices:

1) You can nest them. Give each component a selector and then nest the components in the App component like this:

```<code><comp1></comp1>
<comp2></comp2>
<comp3></comp3>
</code>```

2) You can set up multiple router outlets, either child outlets or secondary (also called auxiliary or named) outlets. This one requires a bit more setup ... so if you are wanting quick I'd go with option 1.

Body:
You have two choices:

1) You can nest them. Give each component a selector and then nest the components in the App component like this:

<comp1></comp1>
<comp2></comp2>
<comp3></comp3>

2) You can set up multiple router outlets, either child outlets or secondary (also called auxiliary or named) outlets. This one requires a bit more setup ... so if you are wanting quick I'd go with option 1.


来源: stackexchange

问:
Brackets Tag Colors
I just updated my version of Brackets to be most current. The colors that denote different tags has changed. The colors selected are too light, and I would like to change them, but I can't find where to do that. I tried to go to the View menu and select customized tag colors, but it is asking for a file. I did a search but everything that comes up with the name brackets is generally not brackets the text editor.</p>

答: You can make original css file and change tags color from View -> customize tag colors.</p>

ContentLicense: CC BY-SA 3.0

Title: Brackets Tag Colors


问:
PHP Search query result ORDER BY not working
I have this code to search database. It now works perfectly but i want to change the order of which it displays. Below is my code.

```<code>if (isset($_GET["mainSearch"]))
{
  $condition = '';
  $query = explode(" ", $_GET["mainSearch"]);

  foreach ($query as $text)
  {
      $condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR ";
  }
  $condition = substr($condition, 0, -4);

  $order = "ORDER BY quiz_id DESC";
  $sql_query = "SELECT * FROM questions WHERE " . $condition;
  $sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition . $order;
  $result = $db->query($sql_query);
  $resultCount = $db->querySingle($sql_query_count);

  if ($resultCount > 0)
  {
  if ($result)
  {
      while ($row = $result->fetchArray(SQLITE3_ASSOC))
      {
           echo '<div class="quesbox_3">
            <div class="questitle">
                <h2>'.$row["question"].'</h2>
            </div>
            <div class="quesanswer">'.$row["answer"].'</div>
        </div>';
      }
  }
  }
  else
  {
      echo "No results found";
  }
}
</code>```

I want the ORDER of which result show to be from bottom to top. Please how can i add this properly as current code isn't working.

答:
Your putting the order by on the count() query, which doesn't do much really.

```<code>$sql_query = "SELECT * FROM questions WHERE " . $condition;
  $sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition . $order;
</code>```

Try

```<code>$sql_query = "SELECT * FROM questions WHERE " . $condition. ' '. $order;
  $sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition ;
</code>```

Body:
I have this code to search database. It now works perfectly but i want to change the order of which it displays. Below is my code.

if (isset($_GET["mainSearch"]))
{
  $condition = '';
  $query = explode(" ", $_GET["mainSearch"]);

  foreach ($query as $text)
  {
      $condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR ";
  }
  $condition = substr($condition, 0, -4);

  $order = "ORDER BY quiz_id DESC";
  $sql_query = "SELECT * FROM questions WHERE " . $condition;
  $sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition . $order;
  $result = $db->query($sql_query);
  $resultCount = $db->querySingle($sql_query_count);

  if ($resultCount > 0)
  {
  if ($result)
  {
      while ($row = $result->fetchArray(SQLITE3_ASSOC))
      {
           echo '

'.$row["question"].'

'.$row["answer"].'

';
      }
  }
  }
  else
  {
      echo "No results found";
  }
}

I want the ORDER of which result show to be from bottom to top. Please how can i add this properly as current code isn't working.

Body:
Your putting the order by on the count() query, which doesn't do much really.

$sql_query = "SELECT * FROM questions WHERE " . $condition;
  $sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition . $order;

Try

$sql_query = "SELECT * FROM questions WHERE " . $condition. ' '. $order;
  $sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition ;


问:
center align grid without gaps and floating
I have a grid set up where the blocks are centre aligned, thus I've done this using display: inline block and set text-align: center to the container. BUT now the client wants variable heights on the blocks which now leaves big gaps in the grid as they're inline-block. Alternatively I could use float: left but this won't work as the blocks need to be centred. I have a codepen setup here: https://codepen.io/anon/pen/WOaeve

I usually use the isotope plugin for grids but there's no layout mode that'll allow for centre aligned blocks so I need a solution that'll allow for all the gaps in the grid to be filled AND for the blocks to be centred. Here's my CSS markup also:

```<code>.feed-grid {
  position: relative;
  display: block;
  width: 100%;
  height: auto;
  text-align: center;
  font-size: 0;
}

.feed-grid .grid-block {
  display: inline-block;
  vertical-align: top;
  margin-left: 6px;
  margin-right: 6px;
  margin-bottom: 12px;
  width: auto;
  height: 255px;
}

.feed-grid .grid-block.large {
  height: 522px;
}

.feed-grid .grid-block img {
  position: relative;
  display: block;
  width: auto;
  height: 255px;
}

.feed-grid .grid-block.large img {
  height: 522px;
}
</code>```

Any solutions to this would be greatly appreciated!

答:
It may solve your problem. I have used float: left; in .child elements.

.container {background: green; overflow: hidden; text-align: center; padding: 15px;}
.center-element {float: none; background: yellow; overflow: hidden; width: auto; box-sizing: border-box; display: inline-block; padding: 5px; vertical-align: middle;}
.child {float: left; padding: 12px 24px; background-color: red;}
.child:not(:first-child) {margin-left: 5px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
 <div class="center-element">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
 </div>
</div></code>```

Body:
I have a grid set up where the blocks are centre aligned, thus I've done this using display: inline block and set text-align: center to the container. BUT now the client wants variable heights on the blocks which now leaves big gaps in the grid as they're inline-block. Alternatively I could use float: left but this won't work as the blocks need to be centred. I have a codepen setup here: https://codepen.io/anon/pen/WOaeve

I usually use the isotope plugin for grids but there's no layout mode that'll allow for centre aligned blocks so I need a solution that'll allow for all the gaps in the grid to be filled AND for the blocks to be centred. Here's my CSS markup also:

.feed-grid {
  position: relative;
  display: block;
  width: 100%;
  height: auto;
  text-align: center;
  font-size: 0;
}

.feed-grid .grid-block {
  display: inline-block;
  vertical-align: top;
  margin-left: 6px;
  margin-right: 6px;
  margin-bottom: 12px;
  width: auto;
  height: 255px;
}

.feed-grid .grid-block.large {
  height: 522px;
}

.feed-grid .grid-block img {
  position: relative;
  display: block;
  width: auto;
  height: 255px;
}

.feed-grid .grid-block.large img {
  height: 522px;
}

Any solutions to this would be greatly appreciated!

Body:
It may solve your problem. I have used float: left; in .child elements.

.container {background: green; overflow: hidden; text-align: center; padding: 15px;}
.center-element {float: none; background: yellow; overflow: hidden; width: auto; box-sizing: border-box; display: inline-block; padding: 5px; vertical-align: middle;}
.child {float: left; padding: 12px 24px; background-color: red;}
.child:not(:first-child) {margin-left: 5px;}

<div class="container">
 <div class="center-element">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
 </div>
</div>


问:
JIRA creating issue using java
What I'm trying to do is creating a new issue on JIRA over Java. Actually I'm on internship and didn't work with APIs before. Here is the code I found while studying JIRA's documents. Not sure if paramaters are wrong.

```<code>public class ExampleCreateIssuesAsynchronous {

    private static URI jiraServerUri = URI.create("https://stajtest.atlassian.net/");

    public static void main(String[] args) throws IOException {
        final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
        final JiraRestClient restClient = factory.createWithBasicHttpAuthentication(jiraServerUri, "internship2016****", "***************");

        try {
            final List<Promise<BasicIssue>> promises = Lists.newArrayList();
            final IssueRestClient issueClient = restClient.getIssueClient();

            System.out.println("Sending issue creation requests...");
            for (int i = 0; i < 100; i++) {
                final String summary = "NewIssue#" + i;
                final IssueInput newIssue = new IssueInputBuilder("TST", 1L, summary).build();
                System.out.println("\tCreating: " + summary);
                promises.add(issueClient.createIssue(newIssue));
            }
            System.out.println("Collecting responses...");
            final Iterable<BasicIssue> createdIssues = transform(promises, new Function<Promise<BasicIssue>, BasicIssue>() {
                @Override
                public BasicIssue apply(Promise<BasicIssue> promise) {
                    return promise.claim();
                }
            });
            System.out.println("Created issues:\n" + Joiner.on("\n").join(createdIssues));
        } finally {
            restClient.close();
        }
    }
}
</code>```

I've studied for 2 days and all I got is that error. Any help would be appreciated.

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: com/atlassian/sal/api/executor/ThreadLocalContextManager
    at com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory.create(AsynchronousJiraRestClientFactory.java:35)
    at com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory.createWithBasicHttpAuthentication(AsynchronousJiraRestClientFactory.java:42)
    at ExampleCreateIssuesAsynchronous.main(ExampleCreateIssuesAsynchronous.java:25)
Caused by: java.lang.ClassNotFoundException: com.atlassian.sal.api.executor.ThreadLocalContextManager
    at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 3 more
</code>```

Edit:

```<code> import java.net.URI;
    import java.util.Optional;

    import com.atlassian.jira.rest.client.api.JiraRestClient;
    import com.atlassian.jira.rest.client.api.domain.Issue;
    import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
    import com.atlassian.util.concurrent.Promise;

    public class JRC
    {
        public Issue getIssue(String issueKey) throws Exception
        {
            final URI jiraServerUri = new URI("stajtest.atlassian.net");
            final JiraRestClient restClient = new AsynchronousJiraRestClientFactory().createWithBasicHttpAuthentication(jiraServerUri, "stajtest***", "********");
            @SuppressWarnings("rawtypes")
            Promise issuePromise = restClient.getIssueClient().getIssue(issueKey);
            return Optional.ofNullable((Issue) issuePromise.claim()).orElseThrow(() -> new Exception("No such issue"));
        }
    }

    import static org.hamcrest.CoreMatchers.is;
    import static org.junit.Assert.assertThat;

    import org.junit.Test;

    import com.atlassian.jira.rest.client.api.domain.Issue;

public class JRCTest
    {
        private static final String jiraKey = "DEN-24";
        @Test
        public void testGetIssue() throws Exception {
            Issue issue = new JRC().getIssue(jiraKey);
            assertThat(issue.getKey(), is(jiraKey));
        }
    }
</code>```

Edit 2

[INFO] Scanning for projects... [INFO]

  [INFO] Building jrjc 1.0-SNAPSHOT [INFO]
  [INFO]  [INFO] --- maven-resources-plugin:2.6:resources
  (default-resources) @ jrjc --- [WARNING] Using platform encoding
  (Cp1254 actually) to copy filtered resources, i.e. build is platformdependent! > [INFO] Copying 0 resource [INFO]  [INFO] ---
  maven-compiler-plugin:3.1:compile (default-compile) @ jrjc
  [INFO] Changes detected - recompiling the module!
  [WARNING] File encoding has not been set, using platform encoding Cp1254, i.e. build is platform dependent! [INFO] Compiling 1 source file to
  C:\Users\Madara\workspace\jrjc-master\target\classes
  [ERROR] COMPILATION ERROR
  [ERROR] /C:/Users/Madara/workspace/jrjc-master/src/main/java/JRC.java:[17,81]
  lambda expressions are not supported in -source 1.5   (use -source 8
  or higher to enable lambda expressions) [INFO] 1 error [INFO]
                 ------------------------------------------------------------- [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO]
  [INFO] Total time: 0.970 s [INFO] Finished at:
                 2016-07-04T19:37:26+03:00 [INFO] Final Memory: 11M/245M [INFO]
  [ERROR] Failed to execute goal
  org.apache.maven.plugins:maven-compiler-plugin:3.1:compile
  (default-compile) on project jrjc: Compilation failure [ERROR]
   /C:/Users/Madara/workspace/jrjc-master/src/main/java/JRC.java:[17,81]
   lambda expressions are not supported in -source 1.5 [ERROR] (use
   -source 8 or higher to enable lambda expressions)
  [ERROR] -> [Help 1] [ERROR]  [ERROR] To see the full stack trace of
  the errors, re-run
  Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to
  enable full debug logging. [ERROR]  [ERROR] For more information
  about the errors and possible solutions, please read the following
  articles: [ERROR] [Help 1]
              http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

答:
I was able to create and get the bug in Jira using the following Java code:

```<code>public Issue getIssue(String issueKey) throws Exception
{
    final URI jiraServerUri = new URI("https://yourJiraURI");

    final JiraRestClient restClient = new AsynchronousJiraRestClientFactory().createWithBasicHttpAuthentication(jiraServerUri, "yourUsername", "yourPassword");
    System.out.println("\n connecting... ");

    Promise issuePromise = restClient.getIssueClient().getIssue(issueKey);
    System.out.println("issuPromise... ");

    return (Issue) issuePromise.claim();
}

public Issue createIssue(String project, Long key, String summary, String description) throws Exception
{
    final URI jiraServerUri = new URI("https://yourJiraURI");

    System.out.println("\n connecting to create a bug... ");

    JiraRestClientFactory restClientFactory = new AsynchronousJiraRestClientFactory();
    JiraRestClient restClient = restClientFactory.createWithBasicHttpAuthentication(jiraServerUri, "yourUsername", "yourPassword");
    IssueRestClient issueClient = restClient.getIssueClient();

    IssueInputBuilder issueBuilder = new IssueInputBuilder(project, key, summary);
    issueBuilder.setDescription(description);

    IssueType it = new IssueType(jiraServerUri, key, summary, false, "Testing the Issue creation", null);

    issueBuilder.setIssueType(it);
    IssueInput issueInput = issueBuilder.build();

    Promise<BasicIssue> promise = restClient.getIssueClient().createIssue(issueInput);
    BasicIssue basicIssue = promise.claim();
    Promise<Issue> promiseJavaIssue = restClient.getIssueClient().getIssue(basicIssue.getKey());

    Issue issue = promiseJavaIssue.claim();
    System.out.println(String.format("New issue created is: %s\r\n", issue.getSummary()));

    return issue;
}
</code>```

POM.xml dependencies:
jersey: 1.9
junit: 4.8.2
jira-rest-java-client-*: 3.0.0
guava: 14.0-rc1
commons-logging: 4.0.6

Title: JIRA creating issue using java

Body:
What I'm trying to do is creating a new issue on JIRA over Java. Actually I'm on internship and didn't work with APIs before. Here is the code I found while studying JIRA's documents. Not sure if paramaters are wrong.

public class ExampleCreateIssuesAsynchronous {

    private static URI jiraServerUri = URI.create("https://stajtest.atlassian.net/");

    public static void main(String[] args) throws IOException {
        final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
        final JiraRestClient restClient = factory.createWithBasicHttpAuthentication(jiraServerUri, "internship2016****", "***************");

        try {
            final List<Promise<BasicIssue>> promises = Lists.newArrayList();
            final IssueRestClient issueClient = restClient.getIssueClient();

            System.out.println("Sending issue creation requests...");
            for (int i = 0; i < 100; i++) {
                final String summary = "NewIssue#" + i;
                final IssueInput newIssue = new IssueInputBuilder("TST", 1L, summary).build();
                System.out.println("\tCreating: " + summary);
                promises.add(issueClient.createIssue(newIssue));
            }
            System.out.println("Collecting responses...");
            final Iterable<BasicIssue> createdIssues = transform(promises, new Function<Promise<BasicIssue>, BasicIssue>() {
                @Override
                public BasicIssue apply(Promise<BasicIssue> promise) {
                    return promise.claim();
                }
            });
            System.out.println("Created issues:\n" + Joiner.on("\n").join(createdIssues));
        } finally {
            restClient.close();
        }
    }
}

I've studied for 2 days and all I got is that error. Any help would be appreciated.

Exception in thread "main" java.lang.NoClassDefFoundError: com/atlassian/sal/api/executor/ThreadLocalContextManager
    at com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory.create(AsynchronousJiraRestClientFactory.java:35)
    at com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory.createWithBasicHttpAuthentication(AsynchronousJiraRestClientFactory.java:42)
    at ExampleCreateIssuesAsynchronous.main(ExampleCreateIssuesAsynchronous.java:25)
Caused by: java.lang.ClassNotFoundException: com.atlassian.sal.api.executor.ThreadLocalContextManager
    at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 3 more

Edit:

 import java.net.URI;
    import java.util.Optional;

    import com.atlassian.jira.rest.client.api.JiraRestClient;
    import com.atlassian.jira.rest.client.api.domain.Issue;
    import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
    import com.atlassian.util.concurrent.Promise;

    public class JRC
    {
        public Issue getIssue(String issueKey) throws Exception
        {
            final URI jiraServerUri = new URI("stajtest.atlassian.net");
            final JiraRestClient restClient = new AsynchronousJiraRestClientFactory().createWithBasicHttpAuthentication(jiraServerUri, "stajtest***", "********");
            @SuppressWarnings("rawtypes")
            Promise issuePromise = restClient.getIssueClient().getIssue(issueKey);
            return Optional.ofNullable((Issue) issuePromise.claim()).orElseThrow(() -> new Exception("No such issue"));
        }
    }

    import static org.hamcrest.CoreMatchers.is;
    import static org.junit.Assert.assertThat;

    import org.junit.Test;

    import com.atlassian.jira.rest.client.api.domain.Issue;

public class JRCTest
    {
        private static final String jiraKey = "DEN-24";
        @Test
        public void testGetIssue() throws Exception {
            Issue issue = new JRC().getIssue(jiraKey);
            assertThat(issue.getKey(), is(jiraKey));
        }
    }

Edit 2

[INFO] Scanning for projects... [INFO]

  [INFO] Building jrjc 1.0-SNAPSHOT [INFO]
  [INFO]  [INFO] --- maven-resources-plugin:2.6:resources
  (default-resources) @ jrjc --- [WARNING] Using platform encoding
  (Cp1254 actually) to copy filtered resources, i.e. build is platformdependent! > [INFO] Copying 0 resource [INFO]  [INFO] ---
  maven-compiler-plugin:3.1:compile (default-compile) @ jrjc
  [INFO] Changes detected - recompiling the module!
  [WARNING] File encoding has not been set, using platform encoding Cp1254, i.e. build is platform dependent! [INFO] Compiling 1 source file to
  C:\Users\Madara\workspace\jrjc-master\target\classes
  [ERROR] COMPILATION ERROR
  [ERROR] /C:/Users/Madara/workspace/jrjc-master/src/main/java/JRC.java:[17,81]
  lambda expressions are not supported in -source 1.5   (use -source 8
  or higher to enable lambda expressions) [INFO] 1 error [INFO]
                 ------------------------------------------------------------- [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO]
  [INFO] Total time: 0.970 s [INFO] Finished at:
                 2016-07-04T19:37:26+03:00 [INFO] Final Memory: 11M/245M [INFO]
  [ERROR] Failed to execute goal
  org.apache.maven.plugins:maven-compiler-plugin:3.1:compile
  (default-compile) on project jrjc: Compilation failure [ERROR]
   /C:/Users/Madara/workspace/jrjc-master/src/main/java/JRC.java:[17,81]
   lambda expressions are not supported in -source 1.5 [ERROR] (use
   -source 8 or higher to enable lambda expressions)
  [ERROR] -> [Help 1] [ERROR]  [ERROR] To see the full stack trace of
  the errors, re-run
  Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to
  enable full debug logging. [ERROR]  [ERROR] For more information
  about the errors and possible solutions, please read the following
  articles: [ERROR] [Help 1]
              http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Body:
I was able to create and get the bug in Jira using the following Java code:

public Issue getIssue(String issueKey) throws Exception
{
    final URI jiraServerUri = new URI("https://yourJiraURI");

    final JiraRestClient restClient = new AsynchronousJiraRestClientFactory().createWithBasicHttpAuthentication(jiraServerUri, "yourUsername", "yourPassword");
    System.out.println("\n connecting... ");

    Promise issuePromise = restClient.getIssueClient().getIssue(issueKey);
    System.out.println("issuPromise... ");

    return (Issue) issuePromise.claim();
}

public Issue createIssue(String project, Long key, String summary, String description) throws Exception
{
    final URI jiraServerUri = new URI("https://yourJiraURI");

    System.out.println("\n connecting to create a bug... ");

    JiraRestClientFactory restClientFactory = new AsynchronousJiraRestClientFactory();
    JiraRestClient restClient = restClientFactory.createWithBasicHttpAuthentication(jiraServerUri, "yourUsername", "yourPassword");
    IssueRestClient issueClient = restClient.getIssueClient();

    IssueInputBuilder issueBuilder = new IssueInputBuilder(project, key, summary);
    issueBuilder.setDescription(description);

    IssueType it = new IssueType(jiraServerUri, key, summary, false, "Testing the Issue creation", null);

    issueBuilder.setIssueType(it);
    IssueInput issueInput = issueBuilder.build();

    Promise<BasicIssue> promise = restClient.getIssueClient().createIssue(issueInput);
    BasicIssue basicIssue = promise.claim();
    Promise<Issue> promiseJavaIssue = restClient.getIssueClient().getIssue(basicIssue.getKey());

    Issue issue = promiseJavaIssue.claim();
    System.out.println(String.format("New issue created is: %s\r\n", issue.getSummary()));

    return issue;
}

POM.xml dependencies:
jersey: 1.9
junit: 4.8.2
jira-rest-java-client-*: 3.0.0
guava: 14.0-rc1
commons-logging: 4.0.6


问:
How to change values in excel acording to different sheet
I have an excelsheet which contains two sheets named respectively 'Sertifika' and 'Egitim Katılım'. in Sertifika i need a button which upgrades value of cells B6, M2 and M3 to next cells from Egitim Katılım.

Example:

```<code>B6 ='Eğitim katılım'!C149
</code>```

and i want to change value of B6 to,

```<code>='Eğitim katılım'!C150
</code>```

how can it be possible?

答:
Assuming you already know how to use a button, include the below code inside the command button,

```<code>Sub mac()
Dim str As String, a As String
str = Range("B6").Formula
a = Right(str, (Len(str) - InStr(str, "C")))
a = a + 1
Range("B6").Formula = "='E?itim kat?l?m'!C" & a
End Sub
</code>```

The code extracts the formula in cell B6, unstrings the row number from the formula, adds +1 to it and updated the formula. I would like you to manipulate this for the other 2 cells.

Body:
I have an excelsheet which contains two sheets named respectively 'Sertifika' and 'Egitim Katılım'. in Sertifika i need a button which upgrades value of cells B6, M2 and M3 to next cells from Egitim Katılım.

Example:

B6 ='Eğitim katılım'!C149

and i want to change value of B6 to,

='Eğitim katılım'!C150

how can it be possible?

Body:
Assuming you already know how to use a button, include the below code inside the command button,

Sub mac()
Dim str As String, a As String
str = Range("B6").Formula
a = Right(str, (Len(str) - InStr(str, "C")))
a = a + 1
Range("B6").Formula = "='E?itim kat?l?m'!C" & a
End Sub

The code extracts the formula in cell B6, unstrings the row number from the formula, adds +1 to it and updated the formula. I would like you to manipulate this for the other 2 cells.


问:
How to copy fields from one structure to another
I have several input structures which I need to convert to some other structure so I can pass it to my method.

```<code>struct Source1
{
    public float x1;
    public float x2;
    public float x3;
}

struct Source2
{
    public float x1;
    public float x3;
    public float x2;
    public float x4;
}

struct Target
{
    public float x1;
    public float x2;
    public float x3;
}
</code>```

I am sure that source structure has required field (type and name is what matters) but that field's offset is unknown. Also source structure might contain some extra fields that I don't need.

How do I copy required fields from source structure to target structure. I need to do it as fast as possible.

In C there is a very simple recipe for that kind of problems.

```<code>#define COPY(x, y) \
{\
x.x1 = y.x1;\
x.x2 = y.x2;\
x.x3 = y.x3;\
}
</code>```

I was thinking about getting a collection of fields and then get field's value using its name as a key but it looks like slow solution to me.

答:
Look at this explicit cast

This is the source struct.

```<code> public struct Source
    {
        public int X1;
        public int X2;
    }
</code>```

This is the target.

```<code> public struct  Target
    {
        public int Y1;
        public int Y2;
        public int Y3;

        public static explicit operator Target(Source source)
        {
            return new Target
            {
                Y1 = source.X1,
                Y2 = source.X2,
                Y3 = 0
            };
        }

}
</code>```

Converting phase :

```<code> static void Main(string[] args)
        {
            var source = new Source {X1 = 1, X2 = 2};
            var target = (Target) source;
            Console.WriteLine("Y1:{0} ,Y2{1} ,Y3:{2} ",target.Y1,target.Y2,target.Y3);
            Console.Read();
        }
</code>```

Body:
I have several input structures which I need to convert to some other structure so I can pass it to my method.

struct Source1
{
    public float x1;
    public float x2;
    public float x3;
}

struct Source2
{
    public float x1;
    public float x3;
    public float x2;
    public float x4;
}

struct Target
{
    public float x1;
    public float x2;
    public float x3;
}

I am sure that source structure has required field (type and name is what matters) but that field's offset is unknown. Also source structure might contain some extra fields that I don't need.

How do I copy required fields from source structure to target structure. I need to do it as fast as possible.

In C there is a very simple recipe for that kind of problems.

#define COPY(x, y) \
{\
x.x1 = y.x1;\
x.x2 = y.x2;\
x.x3 = y.x3;\
}

I was thinking about getting a collection of fields and then get field's value using its name as a key but it looks like slow solution to me.

Body:
Look at this explicit cast

This is the source struct.

 public struct Source
    {
        public int X1;
        public int X2;
    }

This is the target.

 public struct  Target
    {
        public int Y1;
        public int Y2;
        public int Y3;

        public static explicit operator Target(Source source)
        {
            return new Target
            {
                Y1 = source.X1,
                Y2 = source.X2,
                Y3 = 0
            };
        }

}

Converting phase :

 static void Main(string[] args)
        {
            var source = new Source {X1 = 1, X2 = 2};
            var target = (Target) source;
            Console.WriteLine("Y1:{0} ,Y2{1} ,Y3:{2} ",target.Y1,target.Y2,target.Y3);
            Console.Read();
        }


问:
How can I align text inside a GnomeCanvas text item
I would like to have a GnomeCanvas text item and according to its content (and the content language) decide whether to align the text to the right or to the left.
I found one way to do it by changing the anchor property, but using this method would require me to manage the anchor position myself (change it to the right of the text bounding box when aligning to the right), and it seems there must be a simpler way.

EDIT: I see there is also the justification property, which allows me to align the text to the right. However, I still need to set the anchor point according to the language, instead of setting a bounding box that would apply to any language.

答: Its about a month without another answer. I guess my first understanding was correct and there isn't another way with the canvas. My solution would then be to change the anchor to east and change the anchor point accordingly.</p>

ContentLicense: CC BY-SA 2.5


问:
How does random shuffling in quick sort help in increasing the efficiency of the code?
I was going through lecture videos by Robert Sedgwick on algorithms, and he explains that random shuffling ensures we don't get to encounter the worst case quadratic time scenario in quick sort. But I am unable to understand how.</p>

答:
In case of randomized QuickSort, since the pivot element is randomly chosen, we can expect the split of the input array to be reasonably well balanced on average - as opposed to the case of 1 and (n-1) split in a non randomized version of the algorithm. This helps in preventing the worst-case behavior of QuickSort which occurs in unbalanced partitioning.

Hence, the average case running time of the randomized version of QuickSort is O(nlogn) and not O(n^2);


问:
How to center a div fixed over another?
I am trying to center a div (overlay) over another. I've managed to center it inside the div. But then it will be cut off and not stick to the center when the content of the parent is scrolled. Unfortunately, the overlay cannot just be set to fixed: https://stackoverflow.com/a/20621323/1981832.

Here is my code so far:

https://codepen.io/anon/pen/PjyYwV

.parent {
  position: relative;
  height: 50px;
  width: 200px;
  border: 1px solid blue;
  white-space:nowrap;
  overflow: scroll;
}

.overlay {
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 100px;
  width: 100px;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="overlay"></div>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div></code>```

答:
You can use flexbox for this. Also you'll have to add wrapper that will occupy content's width and height and move text to some tag (i.e. span):

.parent {
  height: 50px;
  max-width: 200px;
  border: 1px solid blue;
  white-space: nowrap;
  overflow: scroll;
}

.flex {
  position: relative;
  display: inline-flex; /* Width fit content */
  min-width: 100%; /* Not less than parent's width */
  min-height: 100%; /* Not less than parent's height */
  justify-content: center; /* Center items horizontally */
  align-items: center;  /* Center items vertically */
}

.overlay {
  position: absolute;
  height: 100px;
  width: 100px;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="flex">
      <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span>
      <div class="overlay"></div>
  </div>
</div></code>```

Title: How to center a div fixed over another?

Body:
I am trying to center a div (overlay) over another. I've managed to center it inside the div. But then it will be cut off and not stick to the center when the content of the parent is scrolled. Unfortunately, the overlay cannot just be set to fixed: https://stackoverflow.com/a/20621323/1981832.

Here is my code so far:

https://codepen.io/anon/pen/PjyYwV

.parent {
  position: relative;
  height: 50px;
  width: 200px;
  border: 1px solid blue;
  white-space:nowrap;
  overflow: scroll;
}

.overlay {
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 100px;
  width: 100px;
  background-color: red;
}

  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Body:
You can use flexbox for this. Also you'll have to add wrapper that will occupy content's width and height and move text to some tag (i.e. span):

.parent {
  height: 50px;
  max-width: 200px;
  border: 1px solid blue;
  white-space: nowrap;
  overflow: scroll;
}

.flex {
  position: relative;
  display: inline-flex; /* Width fit content */
  min-width: 100%; /* Not less than parent's width */
  min-height: 100%; /* Not less than parent's height */
  justify-content: center; /* Center items horizontally */
  align-items: center;  /* Center items vertically */
}

.overlay {
  position: absolute;
  height: 100px;
  width: 100px;
  background-color: red;
}

<div class="parent">
  <div class="flex">
      <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span>
      <div class="overlay"></div>
  </div>
</div>


答:
Your $order is in your count query alone. Add to your $sql_query

```<code>$sql_query = "SELECT * FROM questions WHERE " . $condition . ' '. $order;
</code>```

Title: PHP Search query result ORDER BY not working

Body:
Your $order is in your count query alone. Add to your $sql_query

$sql_query = "SELECT * FROM questions WHERE " . $condition . ' '. $order;


问:
Openlayers 4 use canvas pattern for feature style
I'm using latest OL 4 version.
I have several features on the map (one company -> one feature).
Each company has a category and each category has one color.

Style of feature

```<code>var style = new ol.style.Style({
    image: new ol.style.RegularShape({
        fill: new ol.style.Fill({color: color}),
        stroke: new ol.style.Stroke({ color: 'black', width: 2 }),
        points: 4,
        radius: 10,
        angle: Math.PI / 4
    })
});
</code>```

Color is a simple string like: "green" or "blue".
This is working fine.

But there are companies with more than one category (max 2). My idea was to use a canvas pattern:

```<code>var canvas = document.createElement('canvas');
canvas.width = 10;
canvas.height = 10;
var context = canvas.getContext('2d');
context.fillStyle = "black";
context.fillRect(0, 0, 5, 5);
context.fillStyle= "white";
context.fillRect(5,0,5,5);
color = context.createPattern(canvas, "no-repeat");
</code>```

And then use this color for the style of the feature:

```<code>var style = new ol.style.Style({
    fill: new ol.style.Fill({colorlike: color})
});
</code>```

this didn't work so I tried to use it with image fill:

```<code>var style = new ol.style.Style({
    image: new ol.style.RegularShape({
        fill: new ol.style.Fill({colorlike: color})
    })
});
</code>```

This didn't work either. color and colorlike won't work

How do I use a canvas pattern for a OL feature. I just want a rectangle with a different color each half.
But I can't get it by the OL api or the examples, because they all use style on layer or image style, but not the exact way I need it...

Any ideas?

thanks in advance

答:
You can work on getting your fill pattern correct, but here is a working example using a canvas generated pattern using a variety of shapes and two vector layers.

<!DOCTYPE html>

    <title>Regular Shapes</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.2.0/css/ol.css" type="text/css">

```

Body:
I'm using latest OL 4 version.
I have several features on the map (one company -> one feature).
Each company has a category and each category has one color.

Style of feature

var style = new ol.style.Style({
    image: new ol.style.RegularShape({
        fill: new ol.style.Fill({color: color}),
        stroke: new ol.style.Stroke({ color: 'black', width: 2 }),
        points: 4,
        radius: 10,
        angle: Math.PI / 4
    })
});

Color is a simple string like: "green" or "blue".
This is working fine.

But there are companies with more than one category (max 2). My idea was to use a canvas pattern:

var canvas = document.createElement('canvas');
canvas.width = 10;
canvas.height = 10;
var context = canvas.getContext('2d');
context.fillStyle = "black";
context.fillRect(0, 0, 5, 5);
context.fillStyle= "white";
context.fillRect(5,0,5,5);
color = context.createPattern(canvas, "no-repeat");

And then use this color for the style of the feature:

var style = new ol.style.Style({
    fill: new ol.style.Fill({colorlike: color})
});

this didn't work so I tried to use it with image fill:

var style = new ol.style.Style({
    image: new ol.style.RegularShape({
        fill: new ol.style.Fill({colorlike: color})
    })
});

This didn't work either. color and colorlike won't work

How do I use a canvas pattern for a OL feature. I just want a rectangle with a different color each half.
But I can't get it by the OL api or the examples, because they all use style on layer or image style, but not the exact way I need it...

Any ideas?

thanks in advance

Body:
You can work on getting your fill pattern correct, but here is a working example using a canvas generated pattern using a variety of shapes and two vector layers.

<!DOCTYPE html>
<html>
  <head>
    <title>Regular Shapes</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.2.0/css/ol.css" type="text/css">
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
    <script src="https://openlayers.org/en/v4.2.0/build/ol.js"></script>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script>
    /*var canvas = document.createElement('canvas');
canvas.width = 10;
canvas.height = 10;
var context = canvas.getContext('2d');
context.fillStyle = "black";
context.fillRect(0, 0, 5, 5);
context.fillStyle= "white";
context.fillRect(5,0,5,5);
color = context.createPattern(canvas, "no-repeat");*/

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');

var pixelRatio = ol.has.DEVICE_PIXEL_RATIO;
var pattern = (function() {
        canvas.width = 10;
        canvas.height = 10
        // white background
        context.fillStyle = 'white';
        context.fillRect(0, 0, 5, 5);
          context.fill();
        // outer circle
        context.fillStyle = 'black';
        context.fillRect(5, 5, 5, 5);
        context.fill();

        return context.createPattern(canvas, 'repeat');
      }());
    /*var vectorLayer = new ol.layer.Vector({
        source: new ol.source.Vector({
          url: 'https://openlayers.org/en/v4.2.0/examples/data/geojson/countries.geojson',
          format: new ol.format.GeoJSON()
        }),
        style: getStackedStyle
      });*/
      var getStackedStyle = function(feature, resolution) {
        var id = feature.getId();
        fill.setColor(id > 'J' ? gradient(feature, resolution) : pattern);
        return style;
      };
      var stroke = new ol.style.Stroke({color: 'black', width: 2});
      var fill = new ol.style.Fill(pattern);
      var fill2 = new ol.style.Fill();
     /* fill2..setColor(patter);*/
      var style2 = new ol.style.Style({
            stroke: new ol.style.Stroke({
           color: '#333',
           width: 2
        })
      });
      fill.setColor(pattern);
      var styles = {
        'custom': style2,
        'square': new ol.style.Style({
          image: new ol.style.RegularShape({
            fill: fill,
            stroke: stroke,
            points: 4,
            radius: 10,
            angle: Math.PI / 4
          })
        }),
        'triangle': new ol.style.Style({
          image: new ol.style.RegularShape({
            fill: fill,
            stroke: stroke,
            points: 3,
            radius: 10,
            rotation: Math.PI / 4,
            angle: 0
          })
        }),
        'star': new ol.style.Style({
          image: new ol.style.RegularShape({
            fill: fill,
            stroke: stroke,
            points: 5,
            radius: 10,
            radius2: 4,
            angle: 0
          })
        }),
        'cross': new ol.style.Style({
          image: new ol.style.RegularShape({
            fill: fill,
            stroke: stroke,
            points: 4,
            radius: 10,
            radius2: 0,
            angle: 0
          })
        }),
        'x': new ol.style.Style({
          image: new ol.style.RegularShape({
            fill: fill,
            stroke: stroke,
            points: 4,
            radius: 10,
            radius2: 0,
            angle: Math.PI / 4
          })
        })
      };

      var styleKeys = ['x', 'cross', 'star', 'triangle', 'square'];
      var count = 250;
      var features = new Array(count);
      var e = 4500000;
      for (var i = 0; i < count; ++i) {
        var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e];
        features[i] = new ol.Feature(new ol.geom.Point(coordinates));
        features[i].setStyle(styles[styleKeys[Math.floor(Math.random() * 5)]]);
      }

      var source = new ol.source.Vector({
        features: features
      });

     /* */var vectorLayer = new ol.layer.Vector({
        source: source,
        style: getStackedStyle
      });

      // Create a vector layer that makes use of the style function above…
      var vectorLayer2 = new ol.layer.Vector({
        source: new ol.source.Vector({
          url: 'https://openlayers.org/en/v4.2.0/examples/data/geojson/countries.geojson',
          format: new ol.format.GeoJSON()
        }),

      });/**/
      var map = new ol.Map({
        layers: [
          vectorLayer, vectorLayer2
        ],
        target: 'map',
        view: new ol.View({
          center: [0, 0],
          zoom: 2
        })
      });
    </script>
  </body>
</html>


问:
jQuery: Get value of url in load() function
I'm using a library which has already defined an onclick event handler on a hyperlink eg:

```<code><a onclick="$('#myDiv').load('/?__=634285190817664832&sort=Id&sortdir=ASC&page=1 #myDiv');" href="#">1</a>
</code>```

How can I get the value of the 'url' parameter?

答:
Try using the attribute nodes to get the un-parsed version, then use a regex to extract the URL.</p>

```<code>link.attributes.getNamedItem('onclick').value.match(/someRegex/)
</code>```

Body:
I'm using a library which has already defined an onclick event handler on a hyperlink eg:

1

How can I get the value of the 'url' parameter?

Body:
Try using the attribute nodes to get the un-parsed version, then use a regex to extract the URL.

link.attributes.getNamedItem('onclick').value.match(/someRegex/)


问:
Managing Java based Desktop Applicationc(Database Management)
I am developing a Java based  desktop application for a school.
As I am beginner, I am facing some issues.

Where to store the data of students or teachers (In files or database )

If in files, how I will ensure the security ?

If in Database, Can I embed db in application  or I need to install db on server.

If db is installed on server, how I will manage the application if I will give that to other school users. (Means distributing the application to different users)

Do I need to create separate database for different users on servers or Can I make separate schema on same db.

答:
You could do this:

1.Where to store the data of students or teachers (In files or database )
If you would like to go with open source databases, go with MYSQL instead of storing in files. Basic user authentication is enough to give you security to get started with your application. So no need of 2nd.

You can install and run on a remote system or your local machine depending on your application requirements and budgets.

On top your database, to communicate with it, develop a Spring web application (Spring data jpa) with REST web services so that any user can communicate with your application.
In your data base, you can manage users as well with basic authentication like username, password.

No you need not create separate schemas or dbs for each user. Instead you can create a single table that has information regarding Users for your application. For example, create a table "User_Management" which has columns like emailId, phone, name etc.

To get started, you can refer below:
http://javabeat.net/spring-data-jpa/


问:
AWS EC2 SSH with Private key to incorrect instance
I've setup a new EC2 Instance in AWS with a Private Key (downloaded and added to my ~/.ssh folder).

However, once the EC2 Instance has started, I try to ssh to that instance "a.a.a.a" public IP using the Private Key, however it logs me in to a different IP/instance.

Is there an ssh or private key cache of some sort I don't know about, or howcome I get ssh'd into a different EC2 Instance (in a different subnet)?

答:
You can still get all meta-data or user-data of the instance by doing simple http request using curl/wget inside your instance:

```<code>$ curl http://169.254.169.254/latest/meta-data/
</code>```

It should return all keys that you might be interested in getting its value like the following:

```<code>ami-id
ami-launch-index
ami-manifest-path
block-device-mapping/
hostname
instance-action
instance-id
instance-type
kernel-id
local-hostname
local-ipv4
mac
metrics/
network/
placement/
profile
public-hostname
public-ipv4
public-keys/
reservation-id
security-groups
</code>```

Now get only the key/data you want by specifying its name, the following will help distinguish your instance(s):

```<code>$ curl http://169.254.169.254/latest/meta-data/public-ipv4
$ curl http://169.254.169.254/latest/meta-data/local-ipv4
$ curl http://169.254.169.254/latest/meta-data/ami-id
$ curl http://169.254.169.254/latest/meta-data/public-hostname
$ curl http://169.254.169.254/latest/meta-data/local-hostname
$ curl http://169.254.169.254/latest/meta-data/mac
</code>```

To know more about EC2 Metadata, you can check http://www.dowdandassociates.com/blog/content/howto-get-amazon-ec2-instance-metadata/

Body:
You can still get all meta-data or user-data of the instance by doing simple http request using curl/wget inside your instance:

$ curl http://169.254.169.254/latest/meta-data/

It should return all keys that you might be interested in getting its value like the following:

ami-id
ami-launch-index
ami-manifest-path
block-device-mapping/
hostname
instance-action
instance-id
instance-type
kernel-id
local-hostname
local-ipv4
mac
metrics/
network/
placement/
profile
public-hostname
public-ipv4
public-keys/
reservation-id
security-groups

Now get only the key/data you want by specifying its name, the following will help distinguish your instance(s):

$ curl http://169.254.169.254/latest/meta-data/public-ipv4
$ curl http://169.254.169.254/latest/meta-data/local-ipv4
$ curl http://169.254.169.254/latest/meta-data/ami-id
$ curl http://169.254.169.254/latest/meta-data/public-hostname
$ curl http://169.254.169.254/latest/meta-data/local-hostname
$ curl http://169.254.169.254/latest/meta-data/mac

To know more about EC2 Metadata, you can check http://www.dowdandassociates.com/blog/content/howto-get-amazon-ec2-instance-metadata/


问:
outerHTML alternative for SVG's tspan
I'm rendering multiple lines of the text for an SVG image (v2.0). Each text line is represented as one tspan element. I loop over all tspans and append them as new children to a text element (this.node).

```<code>while (tSpans.length > 0) {
    var tSpan = tSpans.shift()
    this.node.appendChild(tSpan)
}
</code>```

The html output is one single string.

```<code><svg ...>
    <text ...>
        <tspan ...>Long text</tspan>
        <tspan ...>in the tspan</tspan>
    </text>
</svg>
</code>```

Firefox is strict regarding the spaces. So, whenever the next line starts with an "i" (very small char), the browser renders this char at the end of the first line. It looks like "Long texti" at the UI.

My idea to fix this was to add an empty space in between the tspans. So that Firefox renders a hidden pseudo whitespace character (Example whitespace-only text nodes at Firefox's Dev tools)

I tried to use the outerHTML property to set a blank space. It's working at dev tools (Edit HTML).

```<code><tspan ... />SPACE<tspan ... />

while (tSpans.length > 0) {
     var tSpan = tSpans.shift()

     console.log('before', tSpan.outerHTML)
     tSpan.outerHTML += ' '
     console.log('after', tSpan.outerHTML)

     this.node.appendChild(tSpan)
}
</code>```

Sadly, it turns out that outerHTML seems to be read-only. Does somebody know why? Is there an alternative way?

答:
Why not just append a space using the DOM given that's what you're doing to append tspans?</p>

```<code>while (tSpans.length > 0) {
    var tSpan = tSpans.shift()
    this.node.appendChild(tSpan)
    this.node.appendChild(document.createTextNode(" "));
}
</code>```

Title: outerHTML alternative for SVG's tspan

Body:
I'm rendering multiple lines of the text for an SVG image (v2.0). Each text line is represented as one tspan element. I loop over all tspans and append them as new children to a text element (this.node).

while (tSpans.length > 0) {
    var tSpan = tSpans.shift()
    this.node.appendChild(tSpan)
}

The html output is one single string.

<svg ...>
    <text ...>
        <tspan ...>Long text</tspan>
        <tspan ...>in the tspan</tspan>
    </text>
</svg>

Firefox is strict regarding the spaces. So, whenever the next line starts with an "i" (very small char), the browser renders this char at the end of the first line. It looks like "Long texti" at the UI.

My idea to fix this was to add an empty space in between the tspans. So that Firefox renders a hidden pseudo whitespace character (Example whitespace-only text nodes at Firefox's Dev tools)

I tried to use the outerHTML property to set a blank space. It's working at dev tools (Edit HTML).

<tspan ... />SPACE<tspan ... />

while (tSpans.length > 0) {
     var tSpan = tSpans.shift()

     console.log('before', tSpan.outerHTML)
     tSpan.outerHTML += ' '
     console.log('after', tSpan.outerHTML)

     this.node.appendChild(tSpan)
}

Sadly, it turns out that outerHTML seems to be read-only. Does somebody know why? Is there an alternative way?

Body:
Why not just append a space using the DOM given that's what you're doing to append tspans?

while (tSpans.length > 0) {
    var tSpan = tSpans.shift()
    this.node.appendChild(tSpan)
    this.node.appendChild(document.createTextNode(" "));
}


问:
How to save the selected indexpaths of an UICollectionViewCell which is inside a UITableViewCell to an array?
I have UICollectionViewCells inside the UITableView. I am trying to highlight the selected UICollectionViewCell for of each row the UITableView. When the UITableView reloads the selected cells should be highlighted. Here is sample code:

```<code>var selectedIndexes = [IndexPath]()
var familyAModelArray : [[Child1]] = []
var childAModelArray : [Child1] = []

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return familyAModelArray[collectionView.tag].count

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ChildCollectionViewCell

        cell.nameLabel.text = childAModelArray[indexPath.row].person! // or childArray

        cell.profilePicture.sd_setImage(with: URL(string: "\(baseUrl)\(childAModelArray[indexPath.row].image!)"), placeholderImage: #imageLiteral(resourceName: "avatar.png"), options: [.continueInBackground,.progressiveDownload])

     return cell
        }

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        selectedIndexes.append(indexPath)

        let i = selectedIndexes[collectionView.tag][indexPath.row]

}
</code>```

Here i got Index out of range:let i = selectedIndexes[collectionView.tag][indexPath.row]

How to achieve this?Any Idea?Thanks in advance.

答:
A good way to check if your cells are being selected is to change the background color of the cell

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItemAt(indexPath)
    cell.backgroundColor = .red

    // append the selected red cells to an array like such
    selectedIndices.append(indexPath)

}
</code>```

Once the tableView reloads you can check your array for selected indexes and change the background color.

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ChildCollectionViewCell

    if selectedIndices.contains(indexPath) {
        cell.backgroundColor = .red
        // check if the index matches a selectedIndex and change it to the selected color.
    }
    cell.nameLabel.text = childAModelArray[indexPath.row].person! // or childArray

    cell.profilePicture.sd_setImage(with: URL(string: "\(baseUrl)\(childAModelArray[indexPath.row].image!)"), placeholderImage: #imageLiteral(resourceName: "avatar.png"), options: [.continueInBackground,.progressiveDownload])

 return cell
}
</code>```

Now once it reloads, the cellForItemAt function is called again and the indices at the selected index paths will be red again.

Body:
I have UICollectionViewCells inside the UITableView. I am trying to highlight the selected UICollectionViewCell for of each row the UITableView. When the UITableView reloads the selected cells should be highlighted. Here is sample code:

var selectedIndexes = [IndexPath]()
var familyAModelArray : [[Child1]] = []
var childAModelArray : [Child1] = []

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return familyAModelArray[collectionView.tag].count

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ChildCollectionViewCell

        cell.nameLabel.text = childAModelArray[indexPath.row].person! // or childArray

        cell.profilePicture.sd_setImage(with: URL(string: "\(baseUrl)\(childAModelArray[indexPath.row].image!)"), placeholderImage: #imageLiteral(resourceName: "avatar.png"), options: [.continueInBackground,.progressiveDownload])

     return cell
        }

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        selectedIndexes.append(indexPath)

        let i = selectedIndexes[collectionView.tag][indexPath.row]

}

Here i got Index out of range:let i = selectedIndexes[collectionView.tag][indexPath.row]

How to achieve this?Any Idea?Thanks in advance.

Body:
A good way to check if your cells are being selected is to change the background color of the cell

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItemAt(indexPath)
    cell.backgroundColor = .red

    // append the selected red cells to an array like such
    selectedIndices.append(indexPath)

}

Once the tableView reloads you can check your array for selected indexes and change the background color.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ChildCollectionViewCell

    if selectedIndices.contains(indexPath) {
        cell.backgroundColor = .red
        // check if the index matches a selectedIndex and change it to the selected color.
    }
    cell.nameLabel.text = childAModelArray[indexPath.row].person! // or childArray

    cell.profilePicture.sd_setImage(with: URL(string: "\(baseUrl)\(childAModelArray[indexPath.row].image!)"), placeholderImage: #imageLiteral(resourceName: "avatar.png"), options: [.continueInBackground,.progressiveDownload])

 return cell
}

Now once it reloads, the cellForItemAt function is called again and the indices at the selected index paths will be red again.


问:
Timer is not getting called on scheduled time
I want to track a location every 10 minutes and send it to server through TraceDelivery async task. For this I tried to use a service and timer to get the location every 10 minutes.

But when from another activity I call the service it works only once, i.e. once TraceDelivery api gets called but not again. For testing I have given just a second delay still its not getting called again.

Also if I check if mLatLang is null and then call the TraceDelivery it it did not get called at least once. But if location is null it gets crashed with a null pointer on mLatLang.

Service code :

```<code>public class LocationTrackerService extends IntentService implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{

    private Handler handler;
    private Timer timer;
    private TimerTask timerTask;
    private GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    private LatLng mLatLang;
    LocationManager mLocationManager = null;
    boolean gps_enabled = false;
    boolean network_enabled = false;

    LocationListener[] mLocationListeners = new LocationListener[]{
            new LocationListener(LocationManager.NETWORK_PROVIDER),
            new LocationListener(LocationManager.GPS_PROVIDER)

    };

    /**
     * A constructor is required, and must call the super IntentService(String)
     * constructor with a name for the worker thread.
     */
    public LocationTrackerService() {
        super("HelloIntentService");
    }

    /**
     * The IntentService calls this method from the default worker thread with
     * the intent that started the service. When this method returns, IntentService
     * stops the service, as appropriate.
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        // Normally we would do some work here, like download a file.
        // For our sample, we just sleep for 5 seconds.
        try {
            Thread.sleep(1000);

            buildGoogleApiClient();
            mGoogleApiClient.connect();

            handler = new Handler();

                initializeLocationManager();
                requestLocation();

                startTimer(intent.getStringExtra("dl_id"), intent.getStringExtra("pt_id"), intent.getStringExtra("ur_id"),intent.getStringExtra("address"),
                        intent.getStringExtra("api_key"));

        } catch (InterruptedException e) {
            // Restore interrupt status.
            Thread.currentThread().interrupt();
        }
    }
    public void startTimer(String dlId,String ptId,String urId,String add,String key) {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask(dlId, ptId, urId,key);

        //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
        timer.schedule(timerTask, 1000, 1000);//
    }

    public void initializeTimerTask(final String dlId, final String ptId, final String urId, final String key) {

        timerTask = new TimerTask() {
            public void run() {

                //use a handler to run a toast that shows the current timestamp
                handler.post(new Runnable() {
                    public void run() {

                            TraceDeliveryAsyncTask traceDeliveryAsyncTask = new TraceDeliveryAsyncTask(LocationTrackerService.this);
                            traceDeliveryAsyncTask.execute(dlId, ptId, urId, String.valueOf(mLatLang.latitude),
                                    String.valueOf(mLatLang.longitude),"", key);

                            Log.e("timer","success");

                    }
                });
            }
        };
    }

    public void stoptimertask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    protected synchronized void buildGoogleApiClient() {

        mGoogleApiClient = new GoogleApiClient.Builder(LocationTrackerService.this)
                .addConnectionCallbacks(LocationTrackerService.this)
                .addOnConnectionFailedListener(LocationTrackerService.this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    public void onConnected(Bundle bundle) {
        // Toast.makeText(getActivity(),"onConnected",Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onConnectionSuspended(int i) {
        //  Toast.makeText(getActivity(),"onConnectionSuspended",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        //    Toast.makeText(getActivity(),"onConnectionFailed",Toast.LENGTH_SHORT).show();
    }

    private void initializeLocationManager() {
        // Log.e(Application.TAG, "initializeLocationManager");
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        }

        try {
            gps_enabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }

        try {
            network_enabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }

        if (!gps_enabled && !network_enabled) {
            // notify user
            if(!CommonUtils.isGPSEnabled(getApplicationContext()))
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }

    }

    public class LocationListener implements android.location.LocationListener {

        public LocationListener() {
        }

        public LocationListener(String provider) {
            Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location location) {
            Log.e(TAG, "onLocationChanged: " + location);

            //get current location

            if(mLastLocation != null && !mLastLocation.equals("")) {
                mLastLocation.set(location);
                mLatLang = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
            }
            else {

            }

        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.e(TAG, "onProviderDisabled: " + provider);

        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.e(TAG, "onProviderEnabled: " + provider);

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }

    //request for location, first by network, then by gps

    public void requestLocation() {

        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 0, 0,
                    mLocationListeners[0]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "network provider does not exist, " + ex.getMessage());
        }

        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 0, 0,
                    mLocationListeners[1]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "gps provider does not exist " + ex.getMessage());
        }
    }

}
</code>```

How can I achieve this?
Please help with this.Thank you..

答:
IntentService will stop immediately one its finished the task in OnHandleIntent,

So instead of using IntentService try to use Service for long running operations.

Body:
I want to track a location every 10 minutes and send it to server through TraceDelivery async task. For this I tried to use a service and timer to get the location every 10 minutes.

But when from another activity I call the service it works only once, i.e. once TraceDelivery api gets called but not again. For testing I have given just a second delay still its not getting called again.

Also if I check if mLatLang is null and then call the TraceDelivery it it did not get called at least once. But if location is null it gets crashed with a null pointer on mLatLang.

Service code :

public class LocationTrackerService extends IntentService implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{

    private Handler handler;
    private Timer timer;
    private TimerTask timerTask;
    private GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    private LatLng mLatLang;
    LocationManager mLocationManager = null;
    boolean gps_enabled = false;
    boolean network_enabled = false;

    LocationListener[] mLocationListeners = new LocationListener[]{
            new LocationListener(LocationManager.NETWORK_PROVIDER),
            new LocationListener(LocationManager.GPS_PROVIDER)

    };

    /**
     * A constructor is required, and must call the super IntentService(String)
     * constructor with a name for the worker thread.
     */
    public LocationTrackerService() {
        super("HelloIntentService");
    }

    /**
     * The IntentService calls this method from the default worker thread with
     * the intent that started the service. When this method returns, IntentService
     * stops the service, as appropriate.
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        // Normally we would do some work here, like download a file.
        // For our sample, we just sleep for 5 seconds.
        try {
            Thread.sleep(1000);

            buildGoogleApiClient();
            mGoogleApiClient.connect();

            handler = new Handler();

                initializeLocationManager();
                requestLocation();

                startTimer(intent.getStringExtra("dl_id"), intent.getStringExtra("pt_id"), intent.getStringExtra("ur_id"),intent.getStringExtra("address"),
                        intent.getStringExtra("api_key"));

        } catch (InterruptedException e) {
            // Restore interrupt status.
            Thread.currentThread().interrupt();
        }
    }
    public void startTimer(String dlId,String ptId,String urId,String add,String key) {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask(dlId, ptId, urId,key);

        //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
        timer.schedule(timerTask, 1000, 1000);//
    }

    public void initializeTimerTask(final String dlId, final String ptId, final String urId, final String key) {

        timerTask = new TimerTask() {
            public void run() {

                //use a handler to run a toast that shows the current timestamp
                handler.post(new Runnable() {
                    public void run() {

                            TraceDeliveryAsyncTask traceDeliveryAsyncTask = new TraceDeliveryAsyncTask(LocationTrackerService.this);
                            traceDeliveryAsyncTask.execute(dlId, ptId, urId, String.valueOf(mLatLang.latitude),
                                    String.valueOf(mLatLang.longitude),"", key);

                            Log.e("timer","success");

                    }
                });
            }
        };
    }

    public void stoptimertask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    protected synchronized void buildGoogleApiClient() {

        mGoogleApiClient = new GoogleApiClient.Builder(LocationTrackerService.this)
                .addConnectionCallbacks(LocationTrackerService.this)
                .addOnConnectionFailedListener(LocationTrackerService.this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    public void onConnected(Bundle bundle) {
        // Toast.makeText(getActivity(),"onConnected",Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onConnectionSuspended(int i) {
        //  Toast.makeText(getActivity(),"onConnectionSuspended",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        //    Toast.makeText(getActivity(),"onConnectionFailed",Toast.LENGTH_SHORT).show();
    }

    private void initializeLocationManager() {
        // Log.e(Application.TAG, "initializeLocationManager");
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        }

        try {
            gps_enabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }

        try {
            network_enabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }

        if (!gps_enabled && !network_enabled) {
            // notify user
            if(!CommonUtils.isGPSEnabled(getApplicationContext()))
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }

    }

    public class LocationListener implements android.location.LocationListener {

        public LocationListener() {
        }

        public LocationListener(String provider) {
            Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location location) {
            Log.e(TAG, "onLocationChanged: " + location);

            //get current location

            if(mLastLocation != null && !mLastLocation.equals("")) {
                mLastLocation.set(location);
                mLatLang = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
            }
            else {

            }

        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.e(TAG, "onProviderDisabled: " + provider);

        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.e(TAG, "onProviderEnabled: " + provider);

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }

    //request for location, first by network, then by gps

    public void requestLocation() {

        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 0, 0,
                    mLocationListeners[0]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "network provider does not exist, " + ex.getMessage());
        }

        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 0, 0,
                    mLocationListeners[1]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "gps provider does not exist " + ex.getMessage());
        }
    }

}

How can I achieve this?
Please help with this.Thank you..


问:
Visual Studio Filenames
I think this is a simple question but I can't figure out how to do it. I have a C++ project that I am compiling and running on Windows but I am running into an issue with the NiTE2 library I am using. When NiTE2 calls a specific function required for setup it searches for an "s.dat" file located at "./NiTE2/s.dat". The problem is when I run it in the Visual Studio environment it tries to search the path ".\NiTE2/s.dat". That's not a typo it mixes the slashes. The program understandably can't find the necessary file. However when I run my program under Git Bash it executes just fine.

Using Git Bash works but it's making debugging extremely difficult, does anyone know how or if it is possible to get the Visual Studio run-time environment to use forward slashes instead of Windows default backslashes for the path? The path that defines where to find "s.dat" is buried in proprietary code that I can't edit so that solution is out.

Side Note: I'm running Windows 10 if that helps in anyway. I'm trying to get bash debugging with VSCode working but that's also an uphill battle at the moment.

答:
I think visual studio is choosing an unexpected working directory, and if you edit the working directory, it should work just fine.

To solve this problem, I use the system internals procmon tool.  When I run my application, the full path of the files which are attempted, are shown.

Visual Studio starts an application in a strange working directory (the location of the source), and this can be a major cause for lost files, when running in the debugger.

You can change the debuggers starting directory by going to the .exe location in the solution explorer, right clicking to edit the properties, and choosing the "Debugging" configuration property.

Here you can set the command Arguments - sent as text into the program, and the Working Directory.

Windows has 2 path parsers.   The native NT path parser does not accept /, but there is a DOS parser which may be activated.  The DOS parser differs by :-

Not caring about '\' or '/'

Allowing relative searching c:\program files\myApp\..\yourapp\prog.exe

Not caring about consecutive '\' or '//'

There are some strange rules about spaces at the end of the file. (DOS parser can't open such).

The DOS parser can be disabled when opening a file with '\?' prepended to the path and using the unicode variant of the function.

```<code>wfopen( L"\\\\?\\c:\\program files\\yourapp\\prog.exe", L"rb" );
</code>```

So in normal operation, '\' and '/' are equivalent, except if the DOS parser is disabled.

Title: Visual Studio Filenames

Body:
I think visual studio is choosing an unexpected working directory, and if you edit the working directory, it should work just fine.

To solve this problem, I use the system internals procmon tool.  When I run my application, the full path of the files which are attempted, are shown.

Visual Studio starts an application in a strange working directory (the location of the source), and this can be a major cause for lost files, when running in the debugger.

You can change the debuggers starting directory by going to the .exe location in the solution explorer, right clicking to edit the properties, and choosing the "Debugging" configuration property.

Here you can set the command Arguments - sent as text into the program, and the Working Directory.

Windows has 2 path parsers.   The native NT path parser does not accept /, but there is a DOS parser which may be activated.  The DOS parser differs by :-

Not caring about '\' or '/'

Allowing relative searching c:\program files\myApp\..\yourapp\prog.exe

Not caring about consecutive '\' or '//'

There are some strange rules about spaces at the end of the file. (DOS parser can't open such).

The DOS parser can be disabled when opening a file with '\?' prepended to the path and using the unicode variant of the function.

wfopen( L"\\\\?\\c:\\program files\\yourapp\\prog.exe", L"rb" );

So in normal operation, '\' and '/' are equivalent, except if the DOS parser is disabled.


问:
Restoring failed Informix mirror chunk
What should be done if an Informix mirror chunk failed and needs to be replaced with new chunk?</p>

答:
One command that you could use is onspaces.  Run by a DBSA with no arguments, the help output includes the information:

```<code>onspaces -m <spacename> { -p <path> -o <offset> -m <path> <offset> [-y] |
                          -f <filename> }
onspaces -r <spacename> [-y]
onspaces -s <spacename> -p <path> -o <offset> {-O | -D} [-y]
</code>```

-m — Add mirroring to an existing DBspace, PLOGspace, BLOBspace or
      SBLOBspace

-r — Turn mirroring off for a DBspace, PLOGspace, BLOBspace or SBLOBspace

-s — Change the status of a chunk

Managing mirroring for a complete dbspace

Clearly, you could turn mirroring off for the down chunk (with -r) and then turn it back on with -m.  You should investigate the Administrator's Reference — especially the section on ON-Spaces — and maybe the Administrator's Guide too.

The ON-Spaces section on mirroring contains the note:

The mirrored chunks should be on a different disk. You must mirror all the chunks at the same time.

and the syntax diagram allows multiple occurrences of the -p <path> -o <offset> -m <path> <offset> part of the synopsis.  The -p and -o portions identify the existing chunk, and the -m portion identifies the new mirror chunk.

The -f option allows you to put the per-chunk information into a text file.

This technique has the not necessarily desirable side-effect of dropping all mirroring on the affected dbspace temporarily, and then reinstating it.

Managing single mirror chunks

Further research reveals a way to recover a single chunk at a time.  The Administrator's Guide has a section on:

Fault tolerance

with sub-sections:

Mirroring

Using mirroring

These cover the theory and practice of mirroring.  In particular, you seem to need:

Take down a mirror chunk using onspaces

```<code>onspaces -s db_acct -p /dev/mirror_chk1 -o 0 -D
</code>```

Recover a mirror chunk using onspaces

```<code>onspaces -s db_acct -p /dev/mirror_chk1 -o 0 -O
</code>```

This allows you to specify the chunk that is down — if the system has not already marked it down.  And you can then bring it back online (into recovery mode) when you've replaced the physical media.  As noted in a comment, this is much easier when you use symlinks to name the device (file) that holds the data (and if you don't use non-zero offsets; for the most part, they're a relic from the days when big disk drives were 100 MiB or less).

Title: Restoring failed Informix mirror chunk

Body:
One command that you could use is onspaces.  Run by a DBSA with no arguments, the help output includes the information:

onspaces -m <spacename> { -p <path> -o <offset> -m <path> <offset> [-y] |
                          -f <filename> }
onspaces -r <spacename> [-y]
onspaces -s <spacename> -p <path> -o <offset> {-O | -D} [-y]

-m — Add mirroring to an existing DBspace, PLOGspace, BLOBspace or
      SBLOBspace

-r — Turn mirroring off for a DBspace, PLOGspace, BLOBspace or SBLOBspace

-s — Change the status of a chunk

Managing mirroring for a complete dbspace

Clearly, you could turn mirroring off for the down chunk (with -r) and then turn it back on with -m.  You should investigate the Administrator's Reference — especially the section on ON-Spaces — and maybe the Administrator's Guide too.

The ON-Spaces section on mirroring contains the note:

The mirrored chunks should be on a different disk. You must mirror all the chunks at the same time.

and the syntax diagram allows multiple occurrences of the -p <path> -o <offset> -m <path> <offset> part of the synopsis.  The -p and -o portions identify the existing chunk, and the -m portion identifies the new mirror chunk.

The -f option allows you to put the per-chunk information into a text file.

This technique has the not necessarily desirable side-effect of dropping all mirroring on the affected dbspace temporarily, and then reinstating it.

Managing single mirror chunks

Further research reveals a way to recover a single chunk at a time.  The Administrator's Guide has a section on:

Fault tolerance

with sub-sections:

Mirroring

Using mirroring

These cover the theory and practice of mirroring.  In particular, you seem to need:

Take down a mirror chunk using onspaces

onspaces -s db_acct -p /dev/mirror_chk1 -o 0 -D

Recover a mirror chunk using onspaces

onspaces -s db_acct -p /dev/mirror_chk1 -o 0 -O

This allows you to specify the chunk that is down — if the system has not already marked it down.  And you can then bring it back online (into recovery mode) when you've replaced the physical media.  As noted in a comment, this is much easier when you use symlinks to name the device (file) that holds the data (and if you don't use non-zero offsets; for the most part, they're a relic from the days when big disk drives were 100 MiB or less).


问:
YouTube Playlist Download
I have a Youtube playlist, I want to download it but I want youtube-dl to name the files like 1-{video name}, 2-{video name}, ... n-{video name} in order to be able to watch them in the same sequence as original Youtube playlist. In other words I need my downloaded videos to be prefixed with numbers. How to do it?</p>

答:
Use an output template:

```<code>youtube-dl -o "%(playlist_index)s.%(title)s-%(id)s.%(ext)s" PLAYLIST_URL
</code>```

Replace PLAYLIST_URL with the URL of your playlist.

Title: YouTube Playlist Download

Body:
Use an output template:

youtube-dl -o "%(playlist_index)s.%(title)s-%(id)s.%(ext)s" PLAYLIST_URL

Replace PLAYLIST_URL with the URL of your playlist.

OwnerDisplayName: anon


问:
How to fetch particular data from Firebase in Android
I have integrated Google sign-in in my app and i am pushing some data in to fire base including user U-id.I had researched a lot and didn't get anything the problem i am facing that i want to fetch Particular data for eg If User A sign-in and push 5 data and Then User B sign-in and push 3 data.I want a query like if User A sing-in Again it will get his 5 data only and not the data which is pushed by User B.Thanks in Advance :)

By using this it fetch all the data from firebase:

```<code> databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot data : dataSnapshot.getChildren()) {
                FirebaseModel firebasemodel =
      data.getValue(FirebaseModel.class);
                firebasemodels.add(firebasemodel);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

I have tried all that .child .orderby and .equalTo but did'nt work

My Structure is Like:

My FireBase Structure

答:
First U have to differentiate.U have to implement Firebase Authentication the u can get Firebase UID of every USER.

```<code>String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
</code>```

Then store seperatly in new node.
i.e Take Firebase Database Instance and

```<code>databaserefernace.child("Data").Child("userID);
</code>```

Body:
I have integrated Google sign-in in my app and i am pushing some data in to fire base including user U-id.I had researched a lot and didn't get anything the problem i am facing that i want to fetch Particular data for eg If User A sign-in and push 5 data and Then User B sign-in and push 3 data.I want a query like if User A sing-in Again it will get his 5 data only and not the data which is pushed by User B.Thanks in Advance :)

By using this it fetch all the data from firebase:

 databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot data : dataSnapshot.getChildren()) {
                FirebaseModel firebasemodel =
      data.getValue(FirebaseModel.class);
                firebasemodels.add(firebasemodel);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

I have tried all that .child .orderby and .equalTo but did'nt work

My Structure is Like:

My FireBase Structure

Body:
First U have to differentiate.U have to implement Firebase Authentication the u can get Firebase UID of every USER.

String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();

Then store seperatly in new node.
i.e Take Firebase Database Instance and

databaserefernace.child("Data").Child("userID);


答:
First of all you need Mysql server installed for the following:

1->Store it in Database(mysql database)

2->database security (refer mysql secuity)

3->all you need is mysql connector for java put in the application folder of app you are creating

4->You can provide database inside of folder of application no

5->You can add user in same database.

Title: Managing Java based Desktop Applicationc(Database Management)

Body:
I am developing a Java based  desktop application for a school.
As I am beginner, I am facing some issues.

Where to store the data of students or teachers (In files or database )

If in files, how I will ensure the security ?

If in Database, Can I embed db in application  or I need to install db on server.

If db is installed on server, how I will manage the application if I will give that to other school users. (Means distributing the application to different users)

Do I need to create separate database for different users on servers or Can I make separate schema on same db.


问:
Scheme & Smalltalk
Not really a question as such in here regarding Smalltalk and Scheme. I only started playing in Smalltalk 3 weeks ago and have been bouncing between Squeak and Pharo. Both are amazing its hard to think to me smalltalk isn't the most popular language going. Everything is in the one image I don't need an interactive command prompt an editor a web page for Rdoc etc I just do it click it mess around, heck if I do UiDesigner Open. I get a GUI app close to QT4. There are database utilities for my small databases like magma.

Anyway, I also started to play with Scheme in Racket and though there are a lot of () involved it still had a lot of simplicity; it seems to be quite logical from the get go. The only thing I am finding is that there are a lot of scheme/Lisp dialects. Racket seems to be quite an easy environment as well, however, notably, there seems to be Chicken and MIT Scheme.

Is there a particular reason I should be using Chicken over Racket or MIT? Or Vice Versa. Good System support, Database or GUI support...etc.

PS I am clearly not picking the most popular languages but I am having fun :-)

答: Both Racket and Chicken have good library support. (GUI, database, networking etc). If you are just having fun, I suggest you go with Racket. It has full support for the Scheme standards (R5RS, R6RS) and good documentation. There are a few good programming books that use Racket as the implementation language. On the other hand, if you are looking for portability of your compiled code across a wide assortment of hardware, Chicken might be better than Racket.</p>

Title: Scheme & Smalltalk


问:
Port 465 cannot send email
I set up account in google compute engine, and I use go daddy smtp
smtpout.asia.secureserver.net , this works fine in my localhost but in GCE it will threw error Connection could not be established with host smtpout.asia.secureserver.net [Connection timed out #110] ...is port 465 with option 'ssl' is block ? ...how to enable this 465 'ssl' in GCE ?

EDIT
465 works fine if I use gmail account...but why using other smtp is not working ?

Thank you in advance.

答:
You need to try for Port 587 that is using TLS protocol for sending emails from Google. Google recommends using port 587 instead of 465. Also, use telnet client to check for the protocols available on your machine.

Open command prompt and type:

```<code>telnet smtp.gmail.com 587
ehlo nico
</code>```

Check for the text listed under it.
You should be getting STARTTLS and CHUNKING keyword. If not, your network is blocking these features.

For further reference see

Title: Port 465 cannot send email

Body:
You need to try for Port 587 that is using TLS protocol for sending emails from Google. Google recommends using port 587 instead of 465. Also, use telnet client to check for the protocols available on your machine.

Open command prompt and type:

telnet smtp.gmail.com 587
ehlo nico

Check for the text listed under it.
You should be getting STARTTLS and CHUNKING keyword. If not, your network is blocking these features.

For further reference see


问:
How write a query in SQL Server 2000?
I have 2 databases with the same tables and views, one in SQL Server 2008 and another in SQL Server 2000.

I wrote this query and it works in SQL Server 2008, but it didn't work in SQL Server 2000.

How can I change my code to work in SQL Server 2000 ?

```<code>SELECT
    SUM(NA_DA) OVER (PARTITION BY vd.SI_VoucherH) AS a,
    SUM(NA_CA) OVER (PARTITION BY vd.SI_VoucherH) AS b
FROM
    acc.ACC_VOUCHERH vh
INNER JOIN
    acc.Acc_VoucherD vd ON vh.SI_VoucherH = vd.SI_VoucherH
</code>```

答:
It's hard to say w/o knowing which table NA_DA & NA_CA are coming from or knowing which table has SI_VoucherH as it PK and which has it a FK.

Hopefully the following will get you close...

```<code>SELECT
    vda.NA_DA,
    vda.NA_CA
FROM
    acc.ACC_VOUCHERH vh
    JOIN (
            select
                vd.SI_VoucherH,
                NA_DA = Sum(vd.NA_DA),
                NA_CA = SUM(NA_CA)
            FROM
                acc.Acc_VoucherD vd
            GROUP BY
                vd.SI_VoucherH
            ) vda
        on vh.SI_VoucherH=vda.SI_VoucherH;
</code>```

Title: How write a query in SQL Server 2000?

Body:
I have 2 databases with the same tables and views, one in SQL Server 2008 and another in SQL Server 2000.

I wrote this query and it works in SQL Server 2008, but it didn't work in SQL Server 2000.

How can I change my code to work in SQL Server 2000 ?

SELECT
    SUM(NA_DA) OVER (PARTITION BY vd.SI_VoucherH) AS a,
    SUM(NA_CA) OVER (PARTITION BY vd.SI_VoucherH) AS b
FROM
    acc.ACC_VOUCHERH vh
INNER JOIN
    acc.Acc_VoucherD vd ON vh.SI_VoucherH = vd.SI_VoucherH

Body:
It's hard to say w/o knowing which table NA_DA & NA_CA are coming from or knowing which table has SI_VoucherH as it PK and which has it a FK.

Hopefully the following will get you close...

SELECT
    vda.NA_DA,
    vda.NA_CA
FROM
    acc.ACC_VOUCHERH vh
    JOIN (
            select
                vd.SI_VoucherH,
                NA_DA = Sum(vd.NA_DA),
                NA_CA = SUM(NA_CA)
            FROM
                acc.Acc_VoucherD vd
            GROUP BY
                vd.SI_VoucherH
            ) vda
        on vh.SI_VoucherH=vda.SI_VoucherH;


问:
Does the put method increases the "modCount" in case of replacing the old value for a given key?
In the below code (actual implementation of put method inside HashMap), I see the modCount is incremented only in case of new entry getting added but not sure whether it is getting incremented in normal case of replacement of old value and inserting new value for a given key. But I have an understanding that mod count increases in case of the hashmap structure changes, i.e in case of add, remove or update the value inside a map. Can someone explain this, as I do not see here in the code the modCount getting incremented inside the if part rather outside the for loop (so is it only for adding anew value, this modCount changes)?</p>

```<code>public V put(K key, V value) {
 if (key == null)
     return putForNullKey(value);
  int hash = hash(key.hashCode());
  int i = indexFor(hash, table.length);
  for (Entry<K,V> e = table[i]; e != null; e = e.next) {
       Object k;
       if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
           V oldValue = e.value;
           e.value = value;
           e.recordAccess(this);
           return oldValue;
       }
  }
  modCount++;
  addEntry(hash, key, value, i);
  return null;
}
</code>```

答:
Java 8 HashMap docs literally say (emphasis mine):

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.)

So, as modCount keeps the count of structural modifications to the map, the answer to your question is: no, modCount is not increased in case of replacing the old value for a given key.

Body:
In the below code (actual implementation of put method inside HashMap), I see the modCount is incremented only in case of new entry getting added but not sure whether it is getting incremented in normal case of replacement of old value and inserting new value for a given key. But I have an understanding that mod count increases in case of the hashmap structure changes, i.e in case of add, remove or update the value inside a map. Can someone explain this, as I do not see here in the code the modCount getting incremented inside the if part rather outside the for loop (so is it only for adding anew value, this modCount changes)?

public V put(K key, V value) {
 if (key == null)
     return putForNullKey(value);
  int hash = hash(key.hashCode());
  int i = indexFor(hash, table.length);
  for (Entry<K,V> e = table[i]; e != null; e = e.next) {
       Object k;
       if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
           V oldValue = e.value;
           e.value = value;
           e.recordAccess(this);
           return oldValue;
       }
  }
  modCount++;
  addEntry(hash, key, value, i);
  return null;
}