问:
Wordpress PHP echo alt text
I've build a simple site using the WP template http://wpshower.com/themes/expositio/

The site is: Mathiaswarnich.dk

It's alright but it does not show alt texts and I can't figure the php setup out. This is the code for images:

```<code> * The template for displaying image attachments

// Retrieve attachment metadata.
$metadata = wp_get_attachment_metadata();

get_header();
?>

<section id="primary" class="content-area image-attachment">
    <div id="content" class="site-content" role="main">
</code>```

```<code>        <header class="entry-header">
            <?php the_title('<h1 class="entry-title">', '</h1>'); ?>
            <div class="entry-meta">
                <div class="full-size-link">
                    <a href="<?php echo wp_get_attachment_url(); ?>"><?php echo $metadata['width']; ?> × <?php echo $metadata['height']; ?></a>
                </div>
                <div class="parent-post-link">
                    <a href="<?php echo get_permalink($post->post_parent); ?>" rel="gallery"><?php echo get_the_title($post->post_parent); ?></a>
                </div>
            </div>
        </header><!--
        --><article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
            <div class="entry-content">
                <div class="entry-attachment">
                    <div class="attachment">
                        <?php expositio_the_attached_image(); ?>
                    </div><!-- .attachment -->
<?php if (has_excerpt()) : ?>
                    <div class="entry-caption">
                        <?php the_excerpt(); ?>
                    </div><!-- .entry-caption -->
<?php endif; ?>
                </div><!-- .entry-attachment -->
                <?php
                the_content();
                wp_link_pages(array(
                    'before' => '<div class="page-links"><span class="page-links-title">'.__('Pages:', 'expositio').'</span>',
                    'after' => '</div>',
                    'link_before' => '<span>',
                    'link_after' => '</span>',
                ));
                ?>
</code>```

答:
Yes, I have also noticed recently the same issue on my photography website which uses WP Expositio theme as well.

The workaround introduced in Stender's answer will not work because the gallery is handled by a custom function.

The solution is very easy:

Step 1: Open /inc/template-tags.php in theme directory.

Step 2: Go to line 87 and inspect code here:

```<code>function expositio_image_tag($thumbnail_id, $size = 'post-thumbnail') {
$meta = wp_get_attachment_metadata($thumbnail_id);
if ($meta === false || $meta === '') {
    return sprintf(
        '<img src="%s" width="%s" height="%s" alt="" />',
        wpShower::defaultImage(),
        wpShower::$default_image_width,
        wpShower::$default_image_height
    );
}

$src = wp_get_attachment_image_src($thumbnail_id, $size);
$size_available = isset($meta['sizes'][$size]);
return sprintf(
    '<img src="%s" width="%s" height="%s" alt="" />',
    $src[0],
    $size_available ? $meta['sizes'][$size]['width'] : $meta['width'],
    $size_available ? $meta['sizes'][$size]['height'] : $meta['height']
);
}
</code>```

Step 3: Replace above code block with this:

```<code>function expositio_image_tag($thumbnail_id, $size = 'post-thumbnail') {
$meta = wp_get_attachment_metadata($thumbnail_id);
if ($meta === false || $meta === '') {
    return sprintf(
        '<img src="%s" width="%s" height="%s" alt="" />',
        wpShower::defaultImage(),
        wpShower::$default_image_width,
        wpShower::$default_image_height
    );
}
$alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
$src = wp_get_attachment_image_src($thumbnail_id, $size);
$size_available = isset($meta['sizes'][$size]);
return sprintf(
    '<img src="%s" width="%s" height="%s" alt="%s" />',
    $src[0],
    $size_available ? $meta['sizes'][$size]['width'] : $meta['width'],
    $size_available ? $meta['sizes'][$size]['height'] : $meta['height'],
    $alt
);
}
</code>```

Step 4: Save/upload edited file. Refresh the site.

Basically, we're creating an $alt variable here which retrieves an image alt attribute and adding it to an formatted string values array. Enjoy.

Title: Wordpress PHP echo alt text

Body:
I've build a simple site using the WP template http://wpshower.com/themes/expositio/

The site is: Mathiaswarnich.dk

It's alright but it does not show alt texts and I can't figure the php setup out. This is the code for images:

 * The template for displaying image attachments

// Retrieve attachment metadata.
$metadata = wp_get_attachment_metadata();

get_header();
?>

            <?php the_title('
', '
'); ?>

                    <a href="<?php echo wp_get_attachment_url(); ?>"><?php echo $metadata['width']; ?> × <?php echo $metadata['height']; ?>

                    <a href="<?php echo get_permalink($post->post_parent); ?>" rel="gallery"><?php echo get_the_title($post->post_parent); ?>

        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

                        <?php expositio_the_attached_image(); ?>

<?php if (has_excerpt()) : ?>

                        <?php the_excerpt(); ?>

<?php endif; ?>

                <?php
                the_content();
                wp_link_pages(array(
                    'before' => '
'.__('Pages:', 'expositio').'',
                    'after' => '
',
                    'link_before' => '',
                    'link_after' => '',
                ));
                ?>

Body:
Yes, I have also noticed recently the same issue on my photography website which uses WP Expositio theme as well.

The workaround introduced in Stender's answer will not work because the gallery is handled by a custom function.

The solution is very easy:

Step 1: Open /inc/template-tags.php in theme directory.

Step 2: Go to line 87 and inspect code here:

function expositio_image_tag($thumbnail_id, $size = 'post-thumbnail') {
$meta = wp_get_attachment_metadata($thumbnail_id);
if ($meta === false || $meta === '') {
    return sprintf(
        '<img src="%s" width="%s" height="%s" alt="" />',
        wpShower::defaultImage(),
        wpShower::$default_image_width,
        wpShower::$default_image_height
    );
}

$src = wp_get_attachment_image_src($thumbnail_id, $size);
$size_available = isset($meta['sizes'][$size]);
return sprintf(
    '<img src="%s" width="%s" height="%s" alt="" />',
    $src[0],
    $size_available ? $meta['sizes'][$size]['width'] : $meta['width'],
    $size_available ? $meta['sizes'][$size]['height'] : $meta['height']
);
}

Step 3: Replace above code block with this:

function expositio_image_tag($thumbnail_id, $size = 'post-thumbnail') {
$meta = wp_get_attachment_metadata($thumbnail_id);
if ($meta === false || $meta === '') {
    return sprintf(
        '<img src="%s" width="%s" height="%s" alt="" />',
        wpShower::defaultImage(),
        wpShower::$default_image_width,
        wpShower::$default_image_height
    );
}
$alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
$src = wp_get_attachment_image_src($thumbnail_id, $size);
$size_available = isset($meta['sizes'][$size]);
return sprintf(
    '<img src="%s" width="%s" height="%s" alt="%s" />',
    $src[0],
    $size_available ? $meta['sizes'][$size]['width'] : $meta['width'],
    $size_available ? $meta['sizes'][$size]['height'] : $meta['height'],
    $alt
);
}

Step 4: Save/upload edited file. Refresh the site.

Basically, we're creating an $alt variable here which retrieves an image alt attribute and adding it to an formatted string values array. Enjoy.


来源: stackexchange

问:
Why doesn't sql compare times?
I am comparing these 2 times if it is smaller or greater than each other but it doesn't. Why ?

```<code> if(@OpeningTime < @ExpiryTime)
      Begin
            Raiserror('Opening time cannot be smaller than expiry time', 16,10);
            return
      End
</code>```

both are of type varchar(10)

time passed are like 10:00am and 11:00am

答:
What you are actually doing is comparing strings, you need to convert your VARCHAR to TIME first then compare them.

```<code>IF ( CONVERT(TIME, @OpeningTime) < CONVERT(TIME, @ExpiryTime) )
</code>```

ContentLicense: CC BY-SA 3.0

Title: Why doesn't sql compare times?

Body:
I am comparing these 2 times if it is smaller or greater than each other but it doesn't. Why ?

 if(@OpeningTime < @ExpiryTime)
      Begin
            Raiserror('Opening time cannot be smaller than expiry time', 16,10);
            return
      End

both are of type varchar(10)

time passed are like 10:00am and 11:00am

Body:
What you are actually doing is comparing strings, you need to convert your VARCHAR to TIME first then compare them.

IF ( CONVERT(TIME, @OpeningTime) < CONVERT(TIME, @ExpiryTime) )


问:
Deserialzing with javascriptserializer throws exception when found same field name
I am trying to deserialize a json file and store the values in the variables declared in set of classes. The json file is below

```<code> {
   "name"         : "sectionname",
   "section"      : 44,
   "comment"      : "Example ,
   "dimensions"   : [
      {
         "name"      : "rtfss",
         "elements"  : 34,
         "comment"   : "sdada"
      },
 ]
}
</code>```

I cant deserialize the json since there are two name and comment fields. How to solve this issue? I cant change the data in the json. Pls help.

答:
You need to create an object that is nested to contain the data in the dimensions collection.

```<code>public class Dimension
{
    public string name { get; set; }
    public int elements { get; set; }
    public string comment { get; set; }
}

public class MyObject
{
    public string name { get; set; }
    public int section { get; set; }
    public string comment { get; set; }
    public List<Dimension> dimensions { get; set; }
}
</code>```

Then you can deserialise the data in your Json to MyObject.

There are online tools like this json2csharp. You can give it your Json and then it will generate c# classes for you.

On a side note, the Json that you provided does have an error in it. "Example" is missing a closing quote mark.

Then you can use whichever serialisation tools you want to do the deserialisation.

```<code>var deserialisedObject = JsonConvert.Deserialise<MyObject>(jsonString);
</code>```

Body:
I am trying to deserialize a json file and store the values in the variables declared in set of classes. The json file is below

 {
   "name"         : "sectionname",
   "section"      : 44,
   "comment"      : "Example ,
   "dimensions"   : [
      {
         "name"      : "rtfss",
         "elements"  : 34,
         "comment"   : "sdada"
      },
 ]
}

I cant deserialize the json since there are two name and comment fields. How to solve this issue? I cant change the data in the json. Pls help.

Body:
You need to create an object that is nested to contain the data in the dimensions collection.

public class Dimension
{
    public string name { get; set; }
    public int elements { get; set; }
    public string comment { get; set; }
}

public class MyObject
{
    public string name { get; set; }
    public int section { get; set; }
    public string comment { get; set; }
    public List<Dimension> dimensions { get; set; }
}

Then you can deserialise the data in your Json to MyObject.

There are online tools like this json2csharp. You can give it your Json and then it will generate c# classes for you.

On a side note, the Json that you provided does have an error in it. "Example" is missing a closing quote mark.

Then you can use whichever serialisation tools you want to do the deserialisation.

var deserialisedObject = JsonConvert.Deserialise<MyObject>(jsonString);


问:
wrap content of Tiny MCE editor with div
I would like to wrap the content of my Tiny MCE editor with a div, the docs for doing something like this seem vague.

I would like to wrap the content with

What are my options?

Here is the code I tried to work with

```<code>   jQuery(document).ready(function( $ ){
  var name = "wprsspostprepend";
if($("#" + name).length > 0) {
 $("#wprsspostprepend").addClass("prepend_editor");
  tinyMCE.init({
        mode : "specific_textareas",
        editor_selector : "prepend_editor"
});
   var content =  tinyMCE.get("prepend_editor").getContent();
    tinyMCE.get("prepend_editor").setContent("<div id='random-wrap'>" + content + "</div>");
}

});
</code>```

I am trying to do this on wordpress so maybe that is the issue, but I keep getting the error

Cannot read property 'getContent' of null

答:
It is because you are trying to access the editor content before it fully initialized. it will take some time even after document is ready.

so the best way to use 'init' event as below .
if you want to change content in every change of the editor then use 'change' event instead of 'init'

```<code>tinyMCE.init({
        mode : "specific_textareas",
        editor_selector : "prepend_editor",
        setup: function (editor) {
                   editor.on("init", function () {
                        var content = editor.getContent();;
                        editor.setContent(content);
                   });
                }

)};
</code>```

Body:
I would like to wrap the content of my Tiny MCE editor with a div, the docs for doing something like this seem vague.

I would like to wrap the content with

What are my options?

Here is the code I tried to work with

   jQuery(document).ready(function( $ ){
  var name = "wprsspostprepend";
if($("#" + name).length > 0) {
 $("#wprsspostprepend").addClass("prepend_editor");
  tinyMCE.init({
        mode : "specific_textareas",
        editor_selector : "prepend_editor"
});
   var content =  tinyMCE.get("prepend_editor").getContent();
    tinyMCE.get("prepend_editor").setContent("
" + content + "
");
}

});

I am trying to do this on wordpress so maybe that is the issue, but I keep getting the error

Cannot read property 'getContent' of null

Body:
It is because you are trying to access the editor content before it fully initialized. it will take some time even after document is ready.

so the best way to use 'init' event as below .
if you want to change content in every change of the editor then use 'change' event instead of 'init'

tinyMCE.init({
        mode : "specific_textareas",
        editor_selector : "prepend_editor",
        setup: function (editor) {
                   editor.on("init", function () {
                        var content = editor.getContent();;
                        editor.setContent(content);
                   });
                }

)};


问:
How to get source code directory in Gradle plugin?
I want to get the directory of Java files in a Groovy plugin.

For example, I have a Java file in a directory:

```<code>"/gradleProject/src/main/java/com/file.java"
</code>```

How can I get:

```<code>"src/main/java"
</code>```

In Maven there is Build.getSourceDirectory(), what is the equivalent in Gradle?

答:
Further to Rene's answer, the groovy DSL makes it easy to get the SourceSet

```<code>SourceSet mainSourceSet = project.sourceSets.main
</code>```

In java this is a little bit more verbose

```<code>SourceSet mainSourceSet = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().getByName("main");
</code>```

Body:
I want to get the directory of Java files in a Groovy plugin.

For example, I have a Java file in a directory:

"/gradleProject/src/main/java/com/file.java"

How can I get:

"src/main/java"

In Maven there is Build.getSourceDirectory(), what is the equivalent in Gradle?

Body:
Further to Rene's answer, the groovy DSL makes it easy to get the SourceSet

SourceSet mainSourceSet = project.sourceSets.main

In java this is a little bit more verbose

SourceSet mainSourceSet = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().getByName("main");


问:
env: node: No such file or directory in phpstorm when compiling less
I'm trying to compile my main.less file to a main.css file using phpstorm. However, I'm getting this error and the .less file does not compile.

```<code>/usr/local/bin/lessc main.less
env: node: No such file or directory

Process finished with exit code 127
</code>```

I'm using a mac and not sure why this is happening. It was working fine before, but I restarted my computer and now I'm getting this error.

Does anyone know why this is happening and how to fix?

答:
This was happening to me because I had node installed via nvm, and nvm installed via homebrew, which is not officially supported. I deleted nvm completely and reinstalled it using the official install script, reinstalled node via nvm, and the error went away.

See nvm is not compatible with the npm config “prefix” option for more information.

Body:
I'm trying to compile my main.less file to a main.css file using phpstorm. However, I'm getting this error and the .less file does not compile.

/usr/local/bin/lessc main.less
env: node: No such file or directory

Process finished with exit code 127

I'm using a mac and not sure why this is happening. It was working fine before, but I restarted my computer and now I'm getting this error.

Does anyone know why this is happening and how to fix?


问:
Comparator<File> for "directories-first" order
I'm stumped... Let's say I have this directory tree:

```<code>{someRoot}/
{someRoot}/bar/
{someRoot}/bar/file1.txt
{someRoot}/foo/
{someRoot}/foo/baz/
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/file2.txt
{someRoot}/aardvark.txt
{someRoot}/food.txt
{someRoot}/zebra.txt
</code>```

You'll note the ordering. Call this order1. At each stage, the directories come first before the files. (NOTE:  bar/file1.txt comes before foo, so on a global basis, the directories do not all come before all the files.)

If I enumerate this directory tree, and then recursively enumerate the subdirectories, I'll get the following List<File>, with ordering order2.

```<code>{someRoot}/
{someRoot}/aardvark.txt
{someRoot}/bar/
{someRoot}/foo/
{someRoot}/food.txt
{someRoot}/zebra.txt
{someRoot}/bar/file1.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz/
{someRoot}/foo/file2.txt
{someRoot}/foo/baz/file3.txt
</code>```

If I create the straightforward Comparator<File>:

```<code>Comparator<File> fc = new Comparator<File>(){
    @Override public int compare(File o1, File o2) {
        return o1.compareTo(o2);
    }
};
</code>```

and I sort, I get this ordering (order3) from lexicographic ordering:

```<code>{someRoot}
{someRoot}/aardvark.txt
{someRoot}/bar
{someRoot}/bar/file1.txt
{someRoot}/foo
{someRoot}/food.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/file2.txt
{someRoot}/zebra.txt
</code>```

But I don't want this ordering (which has problems: note that food.txt comes between directory foo and its sub-items), I want order1. How can I write a Comparator to get me that?

答:
This recursivly gets the sorted file tree as you like:

```<code>public static void main(String[] args) {
    List<File> files = getFileTree(new File("."));

    for (File f : files)
        System.out.println(f);
}

private static List<File> getFileTree(File file) {

    List<File> files = new LinkedList<File>();
    files.add(file);

    if (file.isDirectory()) {
        File[] current = file.listFiles();
        Arrays.sort(current, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                if (o1.isDirectory())
                    return o2.isDirectory() ? o1.compareTo(o2) : -1;
                else if (o2.isDirectory())
                    return 1;

                return o1.compareTo(o2);
            }
        });

        for (File f : current)
            files.addAll(getFileTree(f));
    }

    return files;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm stumped... Let's say I have this directory tree:

{someRoot}/
{someRoot}/bar/
{someRoot}/bar/file1.txt
{someRoot}/foo/
{someRoot}/foo/baz/
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/file2.txt
{someRoot}/aardvark.txt
{someRoot}/food.txt
{someRoot}/zebra.txt

You'll note the ordering. Call this order1. At each stage, the directories come first before the files. (NOTE:  bar/file1.txt comes before foo, so on a global basis, the directories do not all come before all the files.)

If I enumerate this directory tree, and then recursively enumerate the subdirectories, I'll get the following List<File>, with ordering order2.

{someRoot}/
{someRoot}/aardvark.txt
{someRoot}/bar/
{someRoot}/foo/
{someRoot}/food.txt
{someRoot}/zebra.txt
{someRoot}/bar/file1.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz/
{someRoot}/foo/file2.txt
{someRoot}/foo/baz/file3.txt

If I create the straightforward Comparator<File>:

Comparator<File> fc = new Comparator<File>(){
    @Override public int compare(File o1, File o2) {
        return o1.compareTo(o2);
    }
};

and I sort, I get this ordering (order3) from lexicographic ordering:

{someRoot}
{someRoot}/aardvark.txt
{someRoot}/bar
{someRoot}/bar/file1.txt
{someRoot}/foo
{someRoot}/food.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/file2.txt
{someRoot}/zebra.txt

But I don't want this ordering (which has problems: note that food.txt comes between directory foo and its sub-items), I want order1. How can I write a Comparator to get me that?

Body:
This recursivly gets the sorted file tree as you like:

public static void main(String[] args) {
    List<File> files = getFileTree(new File("."));

    for (File f : files)
        System.out.println(f);
}

private static List<File> getFileTree(File file) {

    List<File> files = new LinkedList<File>();
    files.add(file);

    if (file.isDirectory()) {
        File[] current = file.listFiles();
        Arrays.sort(current, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                if (o1.isDirectory())
                    return o2.isDirectory() ? o1.compareTo(o2) : -1;
                else if (o2.isDirectory())
                    return 1;

                return o1.compareTo(o2);
            }
        });

        for (File f : current)
            files.addAll(getFileTree(f));
    }

    return files;
}


问:
Using checkbox value inside conditional statements in JavaScript
I'm doing a questionnaire/survey using HTML. I need to get the value of the checkbox that is being checked. The questions on the next page(L2) will be based on the questions that is only checked on the checkbox when i click "submit".

I have a problem in getting and storing the value of the checkbox and using it later for an IF else-If else statement. Read a lot of online materials but I can't see any light from this. Any help will do... here is the code of the plain checkbox.

```<code><html>
    <head>
    </head>
    <body>
        <script>
            var vg = document.getElementId("VideoGame").checked;
            var te = document.getElementId("Text").checked;
            var an = document.getElementId("Animals").checked;
            var sp = document.getElementId("Sports").checked;
            var lo = document.getElementId("Logo").checked;
        </script>
        <form action="L2.html">
            Check the box if applicable: <br>
            <input type="checkbox" name="Q1" id="VideoGame"> The image is a Video Game.
            <br>
            <input type="checkbox" name="Q1" id="Text"> The image contains text. <br>
            <input type="checkbox" name="Q1" id="Animals"> The image is about animals.
            <br>
            <input type="checkbox" name="Q1" id="Sports"> The image is about sports.
            <br>
            <input type="checkbox" name="Q1" id="Logo"> The image contains a logo. <br>
            <input type="submit" value="NEXT">
        </form>
    </body>
</html>
</code>```

答:
Try to store user-answers in cookies, that might help.
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie</p>

Body:
I'm doing a questionnaire/survey using HTML. I need to get the value of the checkbox that is being checked. The questions on the next page(L2) will be based on the questions that is only checked on the checkbox when i click "submit".

I have a problem in getting and storing the value of the checkbox and using it later for an IF else-If else statement. Read a lot of online materials but I can't see any light from this. Any help will do... here is the code of the plain checkbox.

        <form action="L2.html">
            Check the box if applicable:

            <input type="checkbox" name="Q1" id="VideoGame"> The image is a Video Game.

            <input type="checkbox" name="Q1" id="Text"> The image contains text.

            <input type="checkbox" name="Q1" id="Animals"> The image is about animals.

            <input type="checkbox" name="Q1" id="Sports"> The image is about sports.

            <input type="checkbox" name="Q1" id="Logo"> The image contains a logo.

            <input type="submit" value="NEXT">
        </form>


问:
Deploy shiny app in rocker/shiny docker
Well, I'm new at Docker and I need to implement a Shiny app in a Docker Container.

I have the image from https://hub.docker.com/r/rocker/shiny/, that includes Shiny Server, but I don't know how to deploy my app in the server.

I want to deploy the app in the server, install the required packages for my app into the Docker, save the changes and export the image/container.

As I said, I'm new at Docker and I don't know how it really works.

Any idea?

答:
I guess you should start by creating a Dockerfile in a specific folder which would look like something like this :

```<code>FROM rocker/shiny:latest

RUN  echo 'install.packages(c("package1","package2", ...), \
repos="http://cran.us.r-project.org", \
dependencies=TRUE)' > /tmp/packages.R \
  && Rscript /tmp/packages.R

EXPOSE 3838
CMD ["/usr/bin/shiny-server.sh"]
</code>```

Then go into this folder and build your image, giving it a name by using this command :

```<code>docker build -t your-tag .
</code>```

Finally, once your image is built you can create a container, and if you don't forget to map the volume and the port, you should be able to find it at localhost:3838 with the following command launched from the folder containing the srv folder :

```<code>docker run --rm -p 3838:3838 -v $PWD/srv/shinyapps/:/srv/shiny-server/ -v $PWD/srv/shinylog/:/var/log/shiny-server/ your-tag
</code>```

As said in the Docker documentation at the following address https://hub.docker.com/r/rocker/shiny/, you might want to launch it in detached mode with -d option and map it with your host's port 80 for a real deployment.

Title: Deploy shiny app in rocker/shiny docker

Body:
I guess you should start by creating a Dockerfile in a specific folder which would look like something like this :

FROM rocker/shiny:latest

RUN  echo 'install.packages(c("package1","package2", ...), \
repos="http://cran.us.r-project.org", \
dependencies=TRUE)' > /tmp/packages.R \
  && Rscript /tmp/packages.R

EXPOSE 3838
CMD ["/usr/bin/shiny-server.sh"]

Then go into this folder and build your image, giving it a name by using this command :

docker build -t your-tag .

Finally, once your image is built you can create a container, and if you don't forget to map the volume and the port, you should be able to find it at localhost:3838 with the following command launched from the folder containing the srv folder :

docker run --rm -p 3838:3838 -v $PWD/srv/shinyapps/:/srv/shiny-server/ -v $PWD/srv/shinylog/:/var/log/shiny-server/ your-tag

As said in the Docker documentation at the following address https://hub.docker.com/r/rocker/shiny/, you might want to launch it in detached mode with -d option and map it with your host's port 80 for a real deployment.


问:
Unable to get hudson to parse JUnit test output XML
EDIT: This issue has been fixed by google in gtest 1.4.0; see the original bug report for more information.

I've recently switched to gtest for my C++ testing framework, and one great feature of it which I am presently unable to use is the ability to generate JUnit-style XML test reports, which could then be read in by our hudson build server.

The XML output generated by the gtest test suite all looks legit:

```<code><?xml version="1.0" encoding="UTF-8"?>
<testsuite tests="370" failures="0" disabled="0" errors="0" time="45.61" name="AllTests">
    <testsuite name="application" tests="7" failures="0" disabled="0" errors="0" time="8.953">
        <testcase name="zero_tasks_on_bootup" status="run" time="0" classname="application" />
...etc.
    </testsuite>
</testsuite>
</code>```

I've also tried adding a JUnitReport task to my ant build script, which works fine, and generates XML like so:

```<code><?xml version="1.0" encoding="UTF-8"?>
<testsuite tests="370" failures="0" disabled="0" errors="0" time="45.61" name="AllTests">
    <testsuite name="application" tests="7" failures="0" disabled="0" errors="0" time="8.953">
        <testcase name="zero_tasks_on_bootup" status="run" time="0" classname="application" />
    ...etc.
    </testsuite>
 </testsuite>
</code>```

The problem is, whenever I tell ant to publish the JUnit test results, and then point it to either the raw test result XML, or the compiled result generated in the ant JUnitReport task, hudson always complains about finding no test results there.

I'm not a java guy, so I can't tell what's going on here, and I can't find an example of how the JUnit XML ought to look like.  Can someone help to point me in the right direction?

答:
I'm almost certain that this is not a problem parsing the XML but rather a problem finding the XML files.  If you are using a relative path in the Hudson config, make sure you are clear which directory it is relative to (I seem to remember it being non-obvious under certain circumstances).

As for examples of what the JUnit XML files are supposed to look like, good luck with that.  It's not precisely specified anywhere.  Different tools have differing dialects.  That said, Hudson does a good job of recognising all of them.  I believe it was the developers of JUnitReport who first introduced the XML format, so if you're using that, that's about as canonical as you are going to get.

OwnerDisplayName: sqook

Body:
EDIT: This issue has been fixed by google in gtest 1.4.0; see the original bug report for more information.

I've recently switched to gtest for my C++ testing framework, and one great feature of it which I am presently unable to use is the ability to generate JUnit-style XML test reports, which could then be read in by our hudson build server.

The XML output generated by the gtest test suite all looks legit:

<?xml version="1.0" encoding="UTF-8"?>
<testsuite tests="370" failures="0" disabled="0" errors="0" time="45.61" name="AllTests">
    <testsuite name="application" tests="7" failures="0" disabled="0" errors="0" time="8.953">
        <testcase name="zero_tasks_on_bootup" status="run" time="0" classname="application" />
...etc.
    </testsuite>
</testsuite>

I've also tried adding a JUnitReport task to my ant build script, which works fine, and generates XML like so:

<?xml version="1.0" encoding="UTF-8"?>
<testsuite tests="370" failures="0" disabled="0" errors="0" time="45.61" name="AllTests">
    <testsuite name="application" tests="7" failures="0" disabled="0" errors="0" time="8.953">
        <testcase name="zero_tasks_on_bootup" status="run" time="0" classname="application" />
    ...etc.
    </testsuite>
 </testsuite>

The problem is, whenever I tell ant to publish the JUnit test results, and then point it to either the raw test result XML, or the compiled result generated in the ant JUnitReport task, hudson always complains about finding no test results there.

I'm not a java guy, so I can't tell what's going on here, and I can't find an example of how the JUnit XML ought to look like.  Can someone help to point me in the right direction?

OwnerDisplayName: Dan Dyer


问:
Get details of RAID configuration on Linux
How to get the details of RAID configuration in Linux ?</p>

答:
If you're talking about a running array:

```<code>cat /proc/mdstat
</code>```

If you're talking about the mdadm config file, it's usually in /etc or /etc/mdadm depending on the distribution you're running on.  The following command should find it in any event:

```<code>find /etc -name '*mdadm*'
</code>```

ETA: Also, I would strongly recommend that you carefully study the mdadm man page so that you are very familiar with that utility.  Knowing that utility well will save your bacon at some point.

ContentLicense: CC BY-SA 4.0

Body:
If you're talking about a running array:

cat /proc/mdstat

If you're talking about the mdadm config file, it's usually in /etc or /etc/mdadm depending on the distribution you're running on.  The following command should find it in any event:

find /etc -name '*mdadm*'

ETA: Also, I would strongly recommend that you carefully study the mdadm man page so that you are very familiar with that utility.  Knowing that utility well will save your bacon at some point.


答:
```<code>if($("#your check box input field id").is(":checked")){
local jquery variable="yes";
}
else{
m11="no";
}
</code>```

try this ,this is jquery code that will help u store the values in db.if u just wanna put conditions u can see the way i used it in condition. hope its helpfull. see this if u are still confused.
saving values of toggle(yes or no) in database php. check box and toggle work same way.

Title: Using checkbox value inside conditional statements in JavaScript

Body:
if($("#your check box input field id").is(":checked")){
local jquery variable="yes";
}
else{
m11="no";
}

try this ,this is jquery code that will help u store the values in db.if u just wanna put conditions u can see the way i used it in condition. hope its helpfull. see this if u are still confused.
saving values of toggle(yes or no) in database php. check box and toggle work same way.


问:
How to efficiently find relations between html nodes with vanillaJS
I have several html nodes at various locations and depths in the DOM.
I need to efficiently sort them according to their location in the DOM regardless of each of their depths.

It should be implemented using VanillaJS, no jQuery and the likes.

For instance, given the following tree:

```<code><body>
   <div>
      <div id="a1b"></div>
   <div>
      <div>
         <div id="c1d"></div>
      </div>
      <div id="e1f"></div>
   </div>
   <div id="g1h"></div>
</body>
</code>```

Let's say we have a function that received the four html elements that have ids in a random order, the function should return those elements by the order of appearance within the DOM, namely an array similar to this: [a1b node, c1d node, e1f node, g1h node].

答:
Just use compareDocumentPosition:

```<code>elements.sort(function(a, b) {
    var p = a.compareDocumentPosition(b);
    return Boolean(p & Node.DOCUMENT_POSITION_FOLLOWING)
         - Boolean(p & Node.DOCUMENT_POSITION_PRECEDING);
});
</code>```

Body:
I have several html nodes at various locations and depths in the DOM.
I need to efficiently sort them according to their location in the DOM regardless of each of their depths.

It should be implemented using VanillaJS, no jQuery and the likes.

For instance, given the following tree:

Let's say we have a function that received the four html elements that have ids in a random order, the function should return those elements by the order of appearance within the DOM, namely an array similar to this: [a1b node, c1d node, e1f node, g1h node].

Body:
Just use compareDocumentPosition:

elements.sort(function(a, b) {
    var p = a.compareDocumentPosition(b);
    return Boolean(p & Node.DOCUMENT_POSITION_FOLLOWING)
         - Boolean(p & Node.DOCUMENT_POSITION_PRECEDING);
});


问:
Adding an element to an XML-document with a previously newly created string from an attribute node
This is my first post here. Thanks a mil for having me around and sorry if I make mistakes or create misunderstandings in this first effort. My conundrum is as follows:
I wrote a small script for updating some third party software components, which requires changing an XML file having the following structure:

```<code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>xxx</ProjectGuid>
    <OutputType>xxx</OutputType>
    <StartupObject>xxx</StartupObject>
    <RootNamespace>xxx</RootNamespace>
    <AssemblyName>xxx</AssemblyName>
    <FileAlignment>xxx</FileAlignment>
    <MyType>WindowsFormsWithCustomSubMain</MyType>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
    <TargetFrameworkProfile>
    </TargetFrameworkProfile>
    <SccProjectName>xxx</SccProjectName>
    <SccLocalPath>xxx</SccLocalPath>
    <SccAuxPath>xxx</SccAuxPath>
    <SccProvider>xxx</SccProvider>
  </PropertyGroup>
  <PropertyGroup>
...
<ItemGroup>
    <Reference Include="someString, Version=123, Culture=neutral, PublicKeyToken=ab1, processorArchitecture=xxx">
      <SpecificVersion>False</SpecificVersion>
      <Private>True</Private>
    </Reference>
</code>```

The function in question takes a substring from the attribute include and should ideally add it to a newly created XML element, (i.e. <HintPath>xyz</HintPath>). Selecting the attribute and getting the string worked once I got around the Namespace issue (thanks to StackOverflow). However, when I am about to add the HintPath-element using AppendChild, I get an error saying that the object is not correctly referenced. I tried to use LINQ to resolve the issue, but could not get around the query Syntax (since I am used to using XPath). If somebody has a LINQ solution, please do let me know.

This is my Code so far (XPath Approach)

 Private Function getAttributInclude(ByVal path2xml As String) As List(Of String)
        Dim xmlDoc As XmlDocument = New XmlDocument()
        Dim listAttributValues As New List(Of String)
        Dim nodeAttributInsertValueSplitted() As String
        Dim splittedStringMitEndungDll As String
        Dim nsmanager As XmlNamespaceManager = New XmlNamespaceManager(xmlDoc.NameTable)
        nsmanager.AddNamespace("msn", "http://schemas.microsoft.com/developer/msbuild/2003")
        nsmanager.AddNamespace(String.Empty, "urn:test") 'default namespace

        xmlDoc.Load(path2xml)

        Dim nodeListAttributInclude As XmlNodeList
        Dim root As XmlElement = xmlDoc.DocumentElement
        nodeListAttributInclude = root.SelectNodes("/Project/ItemGroup/Reference/@Include")
        Dim nodeAttributeInclude As XmlNode
        Dim hintPath As XmlElement
        For Each nodeAttributeInclude In nodeListAttributInclude
            nodeAttributInsertValueSplitted = nodeAttributeInclude.Value.Split(",")
            splittedStringMitEndungDll = String.Format("..\..\lib\{0}.dll", nodeAttributInsertValueSplitted(0))
            listAttributValues.Add(nodeAttributeInclude.InnerText)
            hintPath = xmlDoc.CreateElement("HintPath", nodeAttributeInclude.NamespaceURI)
            hintPath.InnerText = splittedStringMitEndungDll
            nodeAttributeInclude.ParentNode.AppendChild(hintPath)
        Next
        xmlDoc.Save(path2xml)

        Return listAttributValues
```

<p>I wonder particularly why .AppendChild is not working in this case</p>

<p>Thanks a mil in advance for any help provided.</p>

<p>Dear all</p>

<p>Just would like to give you an update.
I got back to the project and was provided with a good approach. However it turned out to be just one step in the right direction and I might be to blame for not having explicitly written what I intended with the original. The new snippet is as follows:
    Dim xDoc As XDocument = XDocument.Load(path2xml)</p>

```    Dim nsmanager As New XmlNamespaceManager(New NameTable)

    nsmanager.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003")
    nsmanager.AddNamespace(String.Empty, "urn:test") 'default namespace

    Dim ns As XNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"

    Dim xAttr = xDoc.XPathSelectElement("//ns:Reference", nsmanager).Attribute("Include").Value

    Dim hpElement As New XElement(New XElement(ns + "HintPath", xAttr))

    xDoc.XPathSelectElement("//ns:Reference", nsmanager).Add(hpElement)

    xDoc.Save(path2xml)
```

<p>So far the XML element is being created accordingly. However, using the Xpath-expression I thought I would get all elements having the attribute I am looking for. Moreover, I initially would have liked to get a nodelist since I am going to apply replacements on the attribute string for each node / element that contains the attribute. It turned out that only the first element is selected using your suggestion.
here are my new questions:
1.Is it possible to select all  nodes using this Syntax?
2. How would I go about carrying out the string replacement(s) in each attribute node
Please refer to my initial post, showing you my initial idea using a node list and iterating over each node for the replacements (this Approach worked, but I could not create the XML-HintPath-element in the end). I guess I got confused along the way due to my lack of programming experience, sorry about that
Would be grand if you or anyone else could shed some more light on this topic.</p>

<p>Update:
I had another go at the code and there is one thing that I do not understand at all: Having re-examined each line in the code block above, I came across the following line:</p>

```xDoc.XPathSelectElement("//ns:Reference", nsmanager).Add(hpElement)
```

<p>The description of parameters and return values said that a single value would be retrived. I admit that I missed reading that particular info beforehand. However, I saw that a plural version, i.e. XPathSelectElements was also possible. According to my understanding that seemed like a good Approach (and a slight but all too typical typo). Much to my surprise when changing the line to</p>

```xDoc.XPathSelectElements("//ns:Reference", nsmanager).Add(hpElement)
```

<p>I got an error saying that</p>

```Attribute is not a member of System.Collection.Generic.IEnumerable(Of System.Xml.Linq.XElement
```

<p>This is exactly what I do not understand. How can selecting all elements be wrong? And how is it posssible to get a List of all nodes selected by the XPAth Expression for further processing? I am quite at a loss now. Looking Forward to your replies.</p>

<p>I tried the following approaches found in this and other Forums. </p>

```Dim xAttr = xDoc.XPathSelectElement("//ns:Reference", nsmanager).Attribute("Include").Value

Dim xAttr = xDoc.Root.Descendants("Reference").Attributes("Include")

Dim xAttr = xDoc.XPathEvaluate("//Reference/@Include")
```

<p>However, none of these approaches seem to work. I cannot select the attribute-string and perform the substitutions accordingly. Maybe this helps in identifying the Problem.</p>

<p>Update:
I took another look at my previous code and was able to resolve some issues (cf. code posted below). I can now select all nodes I had envisaged. Moreover, in Debug-mode the replacements also seem to kick in. However, and this is really starting to annoy me, I cannot figure out how to add the new with some of the replaced strings. The example provided by Microsoft </p>

```uses XmlNode root = doc.DocumentElement;
```

<p>What I would like to do aacomplish us using the already existing Xpath Expression for the element . While trying that I ususally get an error that the Object 'x' cannot be converted into to Object 'y'. Could somebody please help me out resolving this issue?</p>

<p>This is the new code</p>

```Private Function getAttributInclude(ByVal pfad2xml As String) As XmlDocument

Dim xDoc As New XmlDocument
xDoc.Load(pfad2xml)

Dim ns As XNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"

Dim nsmanager As New XmlNamespaceManager(New NameTable)

nsmanager.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003")
nsmanager.AddNamespace(String.Empty, "urn:test")

Dim navigator As XPathNavigator = xDoc.CreateNavigator()

Dim xpathAttributInclude As XPathExpression = XPathExpression.Compile("//ns:Reference/ns:SpecificVersion/../@Include")

xpathAttributInclude.SetContext(nsmanager)

Dim xpathElementSpecificVersion As XPathExpression = XPathExpression.Compile("//ns:Reference/ns:SpecificVersion")
xpathElementSpecificVersion.SetContext(nsmanager)

Dim nodeListAttributInclude As XPathNodeIterator = navigator.Select(xpathAttributInclude)
Dim nodeListElementSpecificVersion As XPathNodeIterator = navigator.Select(xpathElementSpecificVersion)

Dim hintPath As XmlElement

For Each nodeAttributInclude In nodeListAttributInclude
    Dim nodeAttributInsertValueSplitted = nodeAttributInclude.Value.Split(",")
    Dim replacedNodeText As String
    Dim splittedStringMitEndungDll
    Dim replacedVersionAttribut As String

    replacedNodeText = nodeAttributInsertValueSplitted(0).ToString.Replace( _
        txtBoxEnterVersionNummerOld.Text, txtBoxEnterVersionNummerNew.Text)

    writeLog(replacedNodeText + vbCrLf)

    splittedStringMitEndungDll = String.Format("..\..\lib\{0}.dll", replacedNodeText)

    writeLog(splittedStringMitEndungDll + vbCrLf)

    If tbXmlDevExpressVersionNew.Text.Length > 0 Then
        Dim splittedElementSpecificVersion = nodeAttributInsertValueSplitted(1).Split("=")

        replacedVersionAttribut = splittedElementSpecificVersion(1).ToString.Replace( _
                splittedElementSpecificVersion(1).ToString, tbXmlDevExpressVersionNew.Text)

        writeLog(replacedVersionAttribut + vbCrLf)
    Else
            MessageBox.Show("Please enter a valid version numbers")
    End If

    hintPath = xDoc.CreateElement("HintPath", nodeAttributInclude.NamespaceURI)
    hintPath.InnerText = splittedStringMitEndungDll

    Dim node2insertAfter = xDoc.DocumentElement

    For Each nodeElementSpecificVersion In nodeListElementSpecificVersion
        xDoc.InsertAfter(hintPath, node2insertAfter.SelectSingleNode("//Reference/SpecificVersion"))
        writeLog(nodeElementSpecificVersion.ToString + vbCrLf)
    Next

Next

xDoc.Save("c:\tmp\result_xml.xml")

Return xDoc
End Function
```

<p>Update:
I came across an interesting article that provided one strep towards a solution. However, I am still having the issue that the element in question is only appended to very last item, although I am using a loop in a loop. Moreover, the replacements do not seem to take effect, either. Here is a snippet of the adjusted appendChild section for adding the XML elements</p>

```For Each nodeElementReference In nodeListElementReference
                Dim node2StartInsert = DirectCast(nodeElementReference, System.Xml.IHasXmlNode).GetNode
                node2StartInsert.AppendChild(hintPath)
            Next
```

<p>Thanks a mil in advance for your assisstance.</p>

<p>Kind regards
Sas</p>

<p>I managed to find a solution. However, the code only needed to extract the Attribute, which is now correctly in the Input XML this code is applied to. Using both XMLElement and XPathNavigator provided the means of writing the additional element to the existing XML file. </p>

```Dim hintPath As XmlElement
    Dim nodeAttributInclude As XPathNavigator

    For Each nodeAttributInclude In nodeListAttributInclude
        Dim nodeAttributInsertValueSplitted = nodeAttributInclude.Value.Split(",")

        Dim versionsInfoText As String
        Dim splittedStringMitEndungDll

        versionsInfoText = nodeAttributInsertValueSplitted(0).ToString

        splittedStringMitEndungDll = String.Format("..\..\lib\{0}.dll", versionsInfoText)

        nodeAttributInclude.MoveToParent()

        hintPath = xDoc.CreateElement("HintPath")
        hintPath.InnerText = splittedStringMitEndungDll

        nodeAttributInclude.AppendChild("<HintPath>" + hintPath.InnerText + "</HintPath>")
    Next

    xDoc.Save("c:\tmp\result_xml.xml")
```

答:
I managed to find a solution. However, the code only needed to extract the Attribute, which is now correctly in the Input XML this code is applied to. Using both XMLElement and XPathNavigator provided the means of writing the additional element to the existing XML file.
Dim hintPath As XmlElement
    Dim nodeAttributInclude As XPathNavigator</p>

```<code>For Each nodeAttributInclude In nodeListAttributInclude
    Dim nodeAttributInsertValueSplitted = nodeAttributInclude.Value.Split(",")

    Dim versionsInfoText As String
    Dim splittedStringMitEndungDll

    versionsInfoText = nodeAttributInsertValueSplitted(0).ToString

    splittedStringMitEndungDll = String.Format("..\..\lib\{0}.dll", versionsInfoText)

    nodeAttributInclude.MoveToParent()

    hintPath = xDoc.CreateElement("HintPath")
    hintPath.InnerText = splittedStringMitEndungDll

    nodeAttributInclude.AppendChild("<HintPath>" + hintPath.InnerText + "</HintPath>")
Next

xDoc.Save("c:\tmp\result_xml.xml")
</code>```

Body:
This is my first post here. Thanks a mil for having me around and sorry if I make mistakes or create misunderstandings in this first effort. My conundrum is as follows:
I wrote a small script for updating some third party software components, which requires changing an XML file having the following structure:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>xxx</ProjectGuid>
    <OutputType>xxx</OutputType>
    <StartupObject>xxx</StartupObject>
    <RootNamespace>xxx</RootNamespace>
    <AssemblyName>xxx</AssemblyName>
    <FileAlignment>xxx</FileAlignment>
    <MyType>WindowsFormsWithCustomSubMain</MyType>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
    <TargetFrameworkProfile>
    </TargetFrameworkProfile>
    <SccProjectName>xxx</SccProjectName>
    <SccLocalPath>xxx</SccLocalPath>
    <SccAuxPath>xxx</SccAuxPath>
    <SccProvider>xxx</SccProvider>
  </PropertyGroup>
  <PropertyGroup>
...
<ItemGroup>
    <Reference Include="someString, Version=123, Culture=neutral, PublicKeyToken=ab1, processorArchitecture=xxx">
      <SpecificVersion>False</SpecificVersion>
      <Private>True</Private>
    </Reference>

The function in question takes a substring from the attribute include and should ideally add it to a newly created XML element, (i.e. <HintPath>xyz</HintPath>). Selecting the attribute and getting the string worked once I got around the Namespace issue (thanks to StackOverflow). However, when I am about to add the HintPath-element using AppendChild, I get an error saying that the object is not correctly referenced. I tried to use LINQ to resolve the issue, but could not get around the query Syntax (since I am used to using XPath). If somebody has a LINQ solution, please do let me know.

This is my Code so far (XPath Approach)

 Private Function getAttributInclude(ByVal path2xml As String) As List(Of String)
        Dim xmlDoc As XmlDocument = New XmlDocument()
        Dim listAttributValues As New List(Of String)
        Dim nodeAttributInsertValueSplitted() As String
        Dim splittedStringMitEndungDll As String
        Dim nsmanager As XmlNamespaceManager = New XmlNamespaceManager(xmlDoc.NameTable)
        nsmanager.AddNamespace("msn", "http://schemas.microsoft.com/developer/msbuild/2003")
        nsmanager.AddNamespace(String.Empty, "urn:test") 'default namespace

        xmlDoc.Load(path2xml)

        Dim nodeListAttributInclude As XmlNodeList
        Dim root As XmlElement = xmlDoc.DocumentElement
        nodeListAttributInclude = root.SelectNodes("/Project/ItemGroup/Reference/@Include")
        Dim nodeAttributeInclude As XmlNode
        Dim hintPath As XmlElement
        For Each nodeAttributeInclude In nodeListAttributInclude
            nodeAttributInsertValueSplitted = nodeAttributeInclude.Value.Split(",")
            splittedStringMitEndungDll = String.Format("..\..\lib\{0}.dll", nodeAttributInsertValueSplitted(0))
            listAttributValues.Add(nodeAttributeInclude.InnerText)
            hintPath = xmlDoc.CreateElement("HintPath", nodeAttributeInclude.NamespaceURI)
            hintPath.InnerText = splittedStringMitEndungDll
            nodeAttributeInclude.ParentNode.AppendChild(hintPath)
        Next
        xmlDoc.Save(path2xml)

        Return listAttributValues

I wonder particularly why .AppendChild is not working in this case

Thanks a mil in advance for any help provided.

Dear all

Just would like to give you an update.
I got back to the project and was provided with a good approach. However it turned out to be just one step in the right direction and I might be to blame for not having explicitly written what I intended with the original. The new snippet is as follows:
    Dim xDoc As XDocument = XDocument.Load(path2xml)

    Dim nsmanager As New XmlNamespaceManager(New NameTable)

    nsmanager.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003")
    nsmanager.AddNamespace(String.Empty, "urn:test") 'default namespace

    Dim ns As XNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"

    Dim xAttr = xDoc.XPathSelectElement("//ns:Reference", nsmanager).Attribute("Include").Value

    Dim hpElement As New XElement(New XElement(ns + "HintPath", xAttr))

    xDoc.XPathSelectElement("//ns:Reference", nsmanager).Add(hpElement)

    xDoc.Save(path2xml)

So far the XML element is being created accordingly. However, using the Xpath-expression I thought I would get all elements having the attribute I am looking for. Moreover, I initially would have liked to get a nodelist since I am going to apply replacements on the attribute string for each node / element that contains the attribute. It turned out that only the first element is selected using your suggestion.
here are my new questions:
1.Is it possible to select all  nodes using this Syntax?
2. How would I go about carrying out the string replacement(s) in each attribute node
Please refer to my initial post, showing you my initial idea using a node list and iterating over each node for the replacements (this Approach worked, but I could not create the XML-HintPath-element in the end). I guess I got confused along the way due to my lack of programming experience, sorry about that
Would be grand if you or anyone else could shed some more light on this topic.

Update:
I had another go at the code and there is one thing that I do not understand at all: Having re-examined each line in the code block above, I came across the following line:

xDoc.XPathSelectElement("//ns:Reference", nsmanager).Add(hpElement)

The description of parameters and return values said that a single value would be retrived. I admit that I missed reading that particular info beforehand. However, I saw that a plural version, i.e. XPathSelectElements was also possible. According to my understanding that seemed like a good Approach (and a slight but all too typical typo). Much to my surprise when changing the line to

xDoc.XPathSelectElements("//ns:Reference", nsmanager).Add(hpElement)

I got an error saying that

Attribute is not a member of System.Collection.Generic.IEnumerable(Of System.Xml.Linq.XElement

This is exactly what I do not understand. How can selecting all elements be wrong? And how is it posssible to get a List of all nodes selected by the XPAth Expression for further processing? I am quite at a loss now. Looking Forward to your replies.

I tried the following approaches found in this and other Forums.

Dim xAttr = xDoc.XPathSelectElement("//ns:Reference", nsmanager).Attribute("Include").Value

Dim xAttr = xDoc.Root.Descendants("Reference").Attributes("Include")

Dim xAttr = xDoc.XPathEvaluate("//Reference/@Include")

However, none of these approaches seem to work. I cannot select the attribute-string and perform the substitutions accordingly. Maybe this helps in identifying the Problem.

Update:
I took another look at my previous code and was able to resolve some issues (cf. code posted below). I can now select all nodes I had envisaged. Moreover, in Debug-mode the replacements also seem to kick in. However, and this is really starting to annoy me, I cannot figure out how to add the new with some of the replaced strings. The example provided by Microsoft

uses XmlNode root = doc.DocumentElement;

What I would like to do aacomplish us using the already existing Xpath Expression for the element . While trying that I ususally get an error that the Object 'x' cannot be converted into to Object 'y'. Could somebody please help me out resolving this issue?

This is the new code

Private Function getAttributInclude(ByVal pfad2xml As String) As XmlDocument

Dim xDoc As New XmlDocument
xDoc.Load(pfad2xml)

Dim ns As XNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"

Dim nsmanager As New XmlNamespaceManager(New NameTable)

nsmanager.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003")
nsmanager.AddNamespace(String.Empty, "urn:test")

Dim navigator As XPathNavigator = xDoc.CreateNavigator()

Dim xpathAttributInclude As XPathExpression = XPathExpression.Compile("//ns:Reference/ns:SpecificVersion/../@Include")

xpathAttributInclude.SetContext(nsmanager)

Dim xpathElementSpecificVersion As XPathExpression = XPathExpression.Compile("//ns:Reference/ns:SpecificVersion")
xpathElementSpecificVersion.SetContext(nsmanager)

Dim nodeListAttributInclude As XPathNodeIterator = navigator.Select(xpathAttributInclude)
Dim nodeListElementSpecificVersion As XPathNodeIterator = navigator.Select(xpathElementSpecificVersion)

Dim hintPath As XmlElement

For Each nodeAttributInclude In nodeListAttributInclude
    Dim nodeAttributInsertValueSplitted = nodeAttributInclude.Value.Split(",")
    Dim replacedNodeText As String
    Dim splittedStringMitEndungDll
    Dim replacedVersionAttribut As String

    replacedNodeText = nodeAttributInsertValueSplitted(0).ToString.Replace( _
        txtBoxEnterVersionNummerOld.Text, txtBoxEnterVersionNummerNew.Text)

    writeLog(replacedNodeText + vbCrLf)

    splittedStringMitEndungDll = String.Format("..\..\lib\{0}.dll", replacedNodeText)

    writeLog(splittedStringMitEndungDll + vbCrLf)

    If tbXmlDevExpressVersionNew.Text.Length > 0 Then
        Dim splittedElementSpecificVersion = nodeAttributInsertValueSplitted(1).Split("=")

        replacedVersionAttribut = splittedElementSpecificVersion(1).ToString.Replace( _
                splittedElementSpecificVersion(1).ToString, tbXmlDevExpressVersionNew.Text)

        writeLog(replacedVersionAttribut + vbCrLf)
    Else
            MessageBox.Show("Please enter a valid version numbers")
    End If

    hintPath = xDoc.CreateElement("HintPath", nodeAttributInclude.NamespaceURI)
    hintPath.InnerText = splittedStringMitEndungDll

    Dim node2insertAfter = xDoc.DocumentElement

    For Each nodeElementSpecificVersion In nodeListElementSpecificVersion
        xDoc.InsertAfter(hintPath, node2insertAfter.SelectSingleNode("//Reference/SpecificVersion"))
        writeLog(nodeElementSpecificVersion.ToString + vbCrLf)
    Next

Next

xDoc.Save("c:\tmp\result_xml.xml")

Return xDoc
End Function

Update:
I came across an interesting article that provided one strep towards a solution. However, I am still having the issue that the element in question is only appended to very last item, although I am using a loop in a loop. Moreover, the replacements do not seem to take effect, either. Here is a snippet of the adjusted appendChild section for adding the XML elements

For Each nodeElementReference In nodeListElementReference
                Dim node2StartInsert = DirectCast(nodeElementReference, System.Xml.IHasXmlNode).GetNode
                node2StartInsert.AppendChild(hintPath)
            Next

Thanks a mil in advance for your assisstance.

Kind regards
Sas

I managed to find a solution. However, the code only needed to extract the Attribute, which is now correctly in the Input XML this code is applied to. Using both XMLElement and XPathNavigator provided the means of writing the additional element to the existing XML file.

Dim hintPath As XmlElement
    Dim nodeAttributInclude As XPathNavigator

    For Each nodeAttributInclude In nodeListAttributInclude
        Dim nodeAttributInsertValueSplitted = nodeAttributInclude.Value.Split(",")

        Dim versionsInfoText As String
        Dim splittedStringMitEndungDll

        versionsInfoText = nodeAttributInsertValueSplitted(0).ToString

        splittedStringMitEndungDll = String.Format("..\..\lib\{0}.dll", versionsInfoText)

        nodeAttributInclude.MoveToParent()

        hintPath = xDoc.CreateElement("HintPath")
        hintPath.InnerText = splittedStringMitEndungDll

        nodeAttributInclude.AppendChild("<HintPath>" + hintPath.InnerText + "</HintPath>")
    Next

    xDoc.Save("c:\tmp\result_xml.xml")


答:
Node.compareDocumentPosition, which is how jQuery does it, preferentially:

```<code>const nodes = [
    document.getElementById('a1b'),
    document.getElementById('c1d'),
    document.getElementById('e1f'),
];

nodes.sort((a, b) =>
    a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ?
        -1 : 1);
</code>```

const shuffle = arr => {
    for (let i = 0; i < arr.length; i++) {
        const j = i + Math.floor(Math.random() * (arr.length - i));
        const t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    return arr;
};

const nodes = shuffle(Array.from(document.body.getElementsByTagName("*")));

console.log(nodes.map(node => node.nodeName));

nodes.sort((a, b) =>
    a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ?
        -1 : 1);

console.log(nodes.map(node => node.nodeName));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <section>
    <header></header>
    <span></span>
    <footer></footer>
    <table><tbody><tr></tr></tbody></table>
  </section>
</div></code>```

Title: How to efficiently find relations between html nodes with vanillaJS

Body:
Node.compareDocumentPosition, which is how jQuery does it, preferentially:

const nodes = [
    document.getElementById('a1b'),
    document.getElementById('c1d'),
    document.getElementById('e1f'),
];

nodes.sort((a, b) =>
    a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ?
        -1 : 1);

const shuffle = arr => {
    for (let i = 0; i < arr.length; i++) {
        const j = i + Math.floor(Math.random() * (arr.length - i));
        const t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    return arr;
};

const nodes = shuffle(Array.from(document.body.getElementsByTagName("*")));

console.log(nodes.map(node => node.nodeName));

nodes.sort((a, b) =>
    a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ?
        -1 : 1);

console.log(nodes.map(node => node.nodeName));

<div>
  <section>
    <header></header>
    <span></span>
    <footer></footer>
    <table><tbody><tr></tr></tbody></table>
  </section>
</div>


问:
Basic intuition for neural networks?
There are lots of "introduction to neural networks" articles online, but most are an introduction to the math of artificial neural networks and not an introduction to the actual underlying concepts (even though they should be one and the same). How does a simple network of artificial neurons actually work?

答:
This answer is roughly based on the beginning of "Neural Networks and Deep Learning" by M. A. Nielsen which is definitely worth reading - it's online and free.

The fundamental idea behind all neural networks is this: Each neuron in a neural network makes a decision. Once you understand how they do that, everything else will make sense. Let’s walk through a simple situation which will help us arrive at that understanding.

Let’s say you are trying to decide whether or not to wear a hat today. There are a number of factors which will affect your decision, and perhaps the most important ones are:

Is it sunny?

Do I have a hat to wear?

Would a hat suit my outfit?

For simplicity, we’ll assume these are the only three factors that you’re weighing up during this decision. Forgetting about neural networks for a second, let’s just try to build a ‘decision maker’ to help us answer this question.

First, we can see each question has a certain level of importance, and so we’ll need to use this relative importance of each question, along with the corresponding answer to each question, to make our decision.

Secondly, we’ll need to have some component which interprets each (yes or no) answer along with its importance to produce the final answer. This sounds simple enough to put into an equation, right? Let’s do it. We simply decide how important each factor is and multiply that importance (or ‘weight’) by the answer to the question (which can be 0 or 1):

```<code>3a + 5b + 2c > 6
</code>```

The numbers 3, 5 and 2 are the ‘weights’ of question a, b and c, respectively. a, b and c, themselves can be either zero (the answer to the question was ‘no’), or one (the answer to the question was ‘yes’). If the above equation is true, then the decision is to wear a hat, and if it is false, the decision is to not wear a hat. The equation says that we’ll only wear a hat if the sum of our weights multiplied by our factors is greater than some threshold value. Above, I chose a threshold value of 6. If you think about it, this means that if I don’t have a hat to wear (b=0), no matter what the other answers are, I won’t be wearing a hat today. That is,

```<code>3a + 2c > 6
</code>```

is never true, since a and c are only either 0 or 1. This makes sense – our simple decision model tells us not to wear a hat if we don’t have one! So the weights of 3, 5 and 2, and the threshold value of 6 seem like a good choices for our simple “should I wear a hat” decision-maker. It also means that, as long as I have a hat to wear, the sun shining (a=1) OR the hat suiting my outfit (c=1) is enough to make me wear a hat today. That is,

```<code>5 + 3 > 6  and  5 + 2 > 6
</code>```

are both true. Good! You can see that by adjusting the weighting of each factor and the threshold, and by adding more factors, we can adjust our ‘decision maker’ to approximately model any decision-making process. What we have just demonstrated is the functionality of a simple neuron (a decision-maker!). Let’s put the above equation into ‘neuron-form’:

A neuron which processes 3 factors: a, b, c, with corresponding importance weightings of 3, 5, 2, and with a decision threshold of 6.

The neuron has 3 input connections (the factors) and 1 output connection (the decision). Each input connection has a weighting which encodes the importance of that connection. If the weighting of that connection is low (relative to the other weights), then it won’t have much effect on the decision. If it’s high, the decision will heavily depend on it.

This is great, we’ve got a fully working neuron that weights inputs and makes decisions. So here’s the next though: What if the output (our decision) was fed into the input of another neuron? That neuron would be using our decision about our hat to make a more abstract decision. And what if the inputs a, b and c are themselves the outputs of other neurons which compute lower-level decisions? We can see that neural networks can be interpreted as networks which compute decisions about decisions, leading from simple input data to more and more complex ‘meta-decisions’. This, to me, is an incredible concept. All the complexity of even the human brain can be modelled using these principles. From the level of photons interacting with our cone-cells right up to our pondering of the meaning of life, it’s just simple little decision-making neurons.

Below is a diagram of a simple neural network which essentially has 3 layers of abstraction:

A simple neural network with 2 inputs and 2 outputs.

As an example, the above inputs could be 2 infrared distance sensors, and the outputs might control control the on/off switch for 2 motors which drive the wheels of a robot.

In our simple hat example, we could pick the weights and the threshold quite easily, but how do we pick the weights and thresholds in this example so that, say, the robot can follow things that move? And how do we know how many neurons we need to solve this problem? Could we solve it with just 1 neuron, maybe 2? Or do we need 20? And how do we organise them? In layers? Modules? These questions are the questions in the field of neural networks. Techniques such as ‘backpropagation’ and (more recently) ‘neuroevolution’ are used effectively to answer some of these troubling questions, but these are outside the scope of this introduction – Wikipedia and Google Scholar and free online textbooks like “Neural Networks and Deep Learning” by M. A. Nielsen are great places to start learning about these concepts.

Hopefully you now have some intuition for how neural networks work, but if you’re interested in actually implementing a neural network there are a few optimisations and extensions to our concept of a neuron which.will make our neural nets more efficient and effective.

Firstly, notice that if we set the threshold value of the neuron to zero, we can always adjust the weightings of the inputs to account for this – only, we’ll also need to allow negative values for our weights. This is great since it removes one variable from our neuron. So we’ll allow negative weights and from now on we won’t need to worry about setting a threshold – it’ll always be zero.

Next, we’ll notice that the weights of the input connections are all relative to one-another, so we can actually normalise these to a value between -1 and 1. Cool. That simplifies things a little.

We can make a further, more substantial improvement to our decision-maker by realising that the inputs themselves (a, b and c in the above example) need not just be 0 or 1. For example, what if today is really sunny? Or maybe there’s scattered clouds, do it’s intermittently sunny? We can see that by allowing values between 0 and 1, our neuron gets more information and can therefore make a better decision – and the good news is, we don’t need to change anything in our neuron model!

So far, we’ve allowed the neuron to accept inputs between 0 and 1, and we’ve normalised the weights between -1 and 1 for convenience.

The next question is: why do we need such certainty in our final decision (i.e. the output of the neuron)? Why can’t it, like the inputs, also be a value between 0 and 1? If we did allow this, the decision of whether or not to wear a hat would become a level of certainty that wearing a hat is the right choice. But if this is a good idea, why did I introduce a threshold at all? Why not just directly pass on the sum of the weighted inputs to the output connection? Well, because, for reasons beyond the scope of this simple introduction to neural networks, it turns out that a neural network works better if the neurons are allowed to make something like an ‘educated guess’, rather than just presenting a raw probability. A threshold gives the neurons a slight bias toward certainty and allows them to be more ‘assertive’, and doing so makes neural networks more efficient. So in that sense, a threshold is good. But the problem with a threshold is that it doesn’t let us know when the neuron is uncertain about its decision – that is, if the sum of the weighted inputs is very close to the threshold, the neuron makes a definite yes/no answer where a definite yes/no answer is not ideal.

So how can we overcome this problem? Well it turns out that if we replace our “greater than zero” condition with a continuous function (called an ‘activation function’), then we can choose non-binary and non-linear reactions to the neuron’s weighted inputs. Let’s first look at our original “greater than zero” condition as a function:

‘Step’ function representing the original neuron’s ‘activation function’.

In the above activation function, the x-axis represents the sum of the weighted inputs and the y-axis represents the neuron’s output. Notice that even if the inputs sum to 0.01, the output is a very certain 1. This is not ideal, as we’ve explained earlier. So we need another activation function that only has a bias towards certainty. Here’s where we welcome the ‘sigmoid’ function:

The ‘sigmoid’ function; a more effective activation function for our artificial neural networks.

Notice how it looks like a halfway point between a step function (which we established as too certain) and a linear x=y line that we’d expect from a neuron which just outputs the raw probability that some some decision is correct. The equation for this sigmoid function is:

where x is the sum of the weighted inputs.

And that’s it! Our new-and-improved neuron does the following:

Takes multiple inputs between 0 and 1.

Weights each one by a value between -1 and 1.

Sums them all together.

Puts that sum into the sigmoid function.

Outputs the result!

It's deceptively simple, but by combining these simple decision-makers together and finding ideal connection weights, we can make arbitrarily complex decisions and calculations which stretch far beyond what our biological brains allow.

Title: Basic intuition for neural networks?

Body:
This answer is roughly based on the beginning of "Neural Networks and Deep Learning" by M. A. Nielsen which is definitely worth reading - it's online and free.

The fundamental idea behind all neural networks is this: Each neuron in a neural network makes a decision. Once you understand how they do that, everything else will make sense. Let’s walk through a simple situation which will help us arrive at that understanding.

Let’s say you are trying to decide whether or not to wear a hat today. There are a number of factors which will affect your decision, and perhaps the most important ones are:

Is it sunny?

Do I have a hat to wear?

Would a hat suit my outfit?

For simplicity, we’ll assume these are the only three factors that you’re weighing up during this decision. Forgetting about neural networks for a second, let’s just try to build a ‘decision maker’ to help us answer this question.

First, we can see each question has a certain level of importance, and so we’ll need to use this relative importance of each question, along with the corresponding answer to each question, to make our decision.

Secondly, we’ll need to have some component which interprets each (yes or no) answer along with its importance to produce the final answer. This sounds simple enough to put into an equation, right? Let’s do it. We simply decide how important each factor is and multiply that importance (or ‘weight’) by the answer to the question (which can be 0 or 1):

3a + 5b + 2c > 6

The numbers 3, 5 and 2 are the ‘weights’ of question a, b and c, respectively. a, b and c, themselves can be either zero (the answer to the question was ‘no’), or one (the answer to the question was ‘yes’). If the above equation is true, then the decision is to wear a hat, and if it is false, the decision is to not wear a hat. The equation says that we’ll only wear a hat if the sum of our weights multiplied by our factors is greater than some threshold value. Above, I chose a threshold value of 6. If you think about it, this means that if I don’t have a hat to wear (b=0), no matter what the other answers are, I won’t be wearing a hat today. That is,

3a + 2c > 6

is never true, since a and c are only either 0 or 1. This makes sense – our simple decision model tells us not to wear a hat if we don’t have one! So the weights of 3, 5 and 2, and the threshold value of 6 seem like a good choices for our simple “should I wear a hat” decision-maker. It also means that, as long as I have a hat to wear, the sun shining (a=1) OR the hat suiting my outfit (c=1) is enough to make me wear a hat today. That is,

5 + 3 > 6  and  5 + 2 > 6

are both true. Good! You can see that by adjusting the weighting of each factor and the threshold, and by adding more factors, we can adjust our ‘decision maker’ to approximately model any decision-making process. What we have just demonstrated is the functionality of a simple neuron (a decision-maker!). Let’s put the above equation into ‘neuron-form’:

A neuron which processes 3 factors: a, b, c, with corresponding importance weightings of 3, 5, 2, and with a decision threshold of 6.

The neuron has 3 input connections (the factors) and 1 output connection (the decision). Each input connection has a weighting which encodes the importance of that connection. If the weighting of that connection is low (relative to the other weights), then it won’t have much effect on the decision. If it’s high, the decision will heavily depend on it.

This is great, we’ve got a fully working neuron that weights inputs and makes decisions. So here’s the next though: What if the output (our decision) was fed into the input of another neuron? That neuron would be using our decision about our hat to make a more abstract decision. And what if the inputs a, b and c are themselves the outputs of other neurons which compute lower-level decisions? We can see that neural networks can be interpreted as networks which compute decisions about decisions, leading from simple input data to more and more complex ‘meta-decisions’. This, to me, is an incredible concept. All the complexity of even the human brain can be modelled using these principles. From the level of photons interacting with our cone-cells right up to our pondering of the meaning of life, it’s just simple little decision-making neurons.

Below is a diagram of a simple neural network which essentially has 3 layers of abstraction:

A simple neural network with 2 inputs and 2 outputs.

As an example, the above inputs could be 2 infrared distance sensors, and the outputs might control control the on/off switch for 2 motors which drive the wheels of a robot.

In our simple hat example, we could pick the weights and the threshold quite easily, but how do we pick the weights and thresholds in this example so that, say, the robot can follow things that move? And how do we know how many neurons we need to solve this problem? Could we solve it with just 1 neuron, maybe 2? Or do we need 20? And how do we organise them? In layers? Modules? These questions are the questions in the field of neural networks. Techniques such as ‘backpropagation’ and (more recently) ‘neuroevolution’ are used effectively to answer some of these troubling questions, but these are outside the scope of this introduction – Wikipedia and Google Scholar and free online textbooks like “Neural Networks and Deep Learning” by M. A. Nielsen are great places to start learning about these concepts.

Hopefully you now have some intuition for how neural networks work, but if you’re interested in actually implementing a neural network there are a few optimisations and extensions to our concept of a neuron which.will make our neural nets more efficient and effective.

Firstly, notice that if we set the threshold value of the neuron to zero, we can always adjust the weightings of the inputs to account for this – only, we’ll also need to allow negative values for our weights. This is great since it removes one variable from our neuron. So we’ll allow negative weights and from now on we won’t need to worry about setting a threshold – it’ll always be zero.

Next, we’ll notice that the weights of the input connections are all relative to one-another, so we can actually normalise these to a value between -1 and 1. Cool. That simplifies things a little.

We can make a further, more substantial improvement to our decision-maker by realising that the inputs themselves (a, b and c in the above example) need not just be 0 or 1. For example, what if today is really sunny? Or maybe there’s scattered clouds, do it’s intermittently sunny? We can see that by allowing values between 0 and 1, our neuron gets more information and can therefore make a better decision – and the good news is, we don’t need to change anything in our neuron model!

So far, we’ve allowed the neuron to accept inputs between 0 and 1, and we’ve normalised the weights between -1 and 1 for convenience.

The next question is: why do we need such certainty in our final decision (i.e. the output of the neuron)? Why can’t it, like the inputs, also be a value between 0 and 1? If we did allow this, the decision of whether or not to wear a hat would become a level of certainty that wearing a hat is the right choice. But if this is a good idea, why did I introduce a threshold at all? Why not just directly pass on the sum of the weighted inputs to the output connection? Well, because, for reasons beyond the scope of this simple introduction to neural networks, it turns out that a neural network works better if the neurons are allowed to make something like an ‘educated guess’, rather than just presenting a raw probability. A threshold gives the neurons a slight bias toward certainty and allows them to be more ‘assertive’, and doing so makes neural networks more efficient. So in that sense, a threshold is good. But the problem with a threshold is that it doesn’t let us know when the neuron is uncertain about its decision – that is, if the sum of the weighted inputs is very close to the threshold, the neuron makes a definite yes/no answer where a definite yes/no answer is not ideal.

So how can we overcome this problem? Well it turns out that if we replace our “greater than zero” condition with a continuous function (called an ‘activation function’), then we can choose non-binary and non-linear reactions to the neuron’s weighted inputs. Let’s first look at our original “greater than zero” condition as a function:

‘Step’ function representing the original neuron’s ‘activation function’.

In the above activation function, the x-axis represents the sum of the weighted inputs and the y-axis represents the neuron’s output. Notice that even if the inputs sum to 0.01, the output is a very certain 1. This is not ideal, as we’ve explained earlier. So we need another activation function that only has a bias towards certainty. Here’s where we welcome the ‘sigmoid’ function:

The ‘sigmoid’ function; a more effective activation function for our artificial neural networks.

Notice how it looks like a halfway point between a step function (which we established as too certain) and a linear x=y line that we’d expect from a neuron which just outputs the raw probability that some some decision is correct. The equation for this sigmoid function is:

where x is the sum of the weighted inputs.

And that’s it! Our new-and-improved neuron does the following:

Takes multiple inputs between 0 and 1.

Weights each one by a value between -1 and 1.

Sums them all together.

Puts that sum into the sigmoid function.

Outputs the result!

It's deceptively simple, but by combining these simple decision-makers together and finding ideal connection weights, we can make arbitrarily complex decisions and calculations which stretch far beyond what our biological brains allow.


问:
How do I determine the current operating system with Node.js
I'm writing a couple of node shell scripts for use when developing on a platform. We have both Mac and Windows developers. Is there a variable I can check for in Node to run a .sh file in one instance and .bat in another?</p>

答:
```<code>const path = require('path');

if (path.sep === "\\") {
console.log("Windows");
} else {
console.log("Not Windows");
}
</code>```


问:
get substring from string in C
I am trying to write a program in C, which will allow me to get a string I want between two other strings that will be defined. To be more specific, my example string is

```<code> "blahblah<mailto:agent007@example.org>blahblahblah"
</code>```

and I need to be able to extract the "agent007" substring to a new variable. I have tried the strtok() method, but the thing is I can't extract the tokens to a new variable or an array. I have tokenized the string and the statement that would suite me fine would be something like " if token[i] == "mailto" && token[i+2] == "example" then mailAdd = token[i+1] " (in a pseudo-code way :) )

my program so far

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

int main ()
{
  char str[] ="blahblah<mailto:agent007@example.org>blahblahblah";
  char * tch;
  tch = strtok (str,"<:@");
  while (tch != NULL)
  {
    printf ("%s\n",tch);
    tch = strtok (NULL, "<:@");
  }
  return 0;
}
</code>```

Of course, any other suggestion beyond tokens will be greatly appreciated -

答:
You could use strstr to search for 'mailto:' and then strchr to search for '@' and take the characters in between. I never use strtok but I don't see what's wrong with what you've done.

Here's an example where email should point to "agent007" in your case. Error handling is missing here. This is destructive, meaning that it modifies the input string, but so does strtok.

```<code>char *mailto = strstr( str, "mailto:" );
char *at = strchr( mailto, '@' );
char *email = mailto + strlen("mailto:");
*at = '\0';
</code>```

Title: get substring from string in C

Body:
I am trying to write a program in C, which will allow me to get a string I want between two other strings that will be defined. To be more specific, my example string is

 "blahblah<mailto:agent007@example.org>blahblahblah"

and I need to be able to extract the "agent007" substring to a new variable. I have tried the strtok() method, but the thing is I can't extract the tokens to a new variable or an array. I have tokenized the string and the statement that would suite me fine would be something like " if token[i] == "mailto" && token[i+2] == "example" then mailAdd = token[i+1] " (in a pseudo-code way :) )

my program so far

#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="blahblah<mailto:agent007@example.org>blahblahblah";
  char * tch;
  tch = strtok (str,"<:@");
  while (tch != NULL)
  {
    printf ("%s\n",tch);
    tch = strtok (NULL, "<:@");
  }
  return 0;
}

Of course, any other suggestion beyond tokens will be greatly appreciated -

Body:
You could use strstr to search for 'mailto:' and then strchr to search for '@' and take the characters in between. I never use strtok but I don't see what's wrong with what you've done.

Here's an example where email should point to "agent007" in your case. Error handling is missing here. This is destructive, meaning that it modifies the input string, but so does strtok.

char *mailto = strstr( str, "mailto:" );
char *at = strchr( mailto, '@' );
char *email = mailto + strlen("mailto:");
*at = '\0';


问:
Return individual address components (city, state, etc.) from GeoPy geocoder
I'm using GeoPy to geocode addresses to lat,lng. I would also like to extract the itemized address components (street, city, state, zip) for each address.

GeoPy returns a string with the address -- but I can't find a reliable way to separate each component. For example:

```<code>123 Main Street, Los Angeles, CA 90034, USA =>
{street: '123 Main Street', city: 'Los Angeles', state: 'CA', zip: 90034, country: 'USA'}
</code>```

The Google geocoding API does return these individual components... is there a way to get these from GeoPy? (or a different geocoding tool?)

答:
This is how I implemented such a split, as I wanted the resulting address in always the same format. You would just have to skip the concatenation and retrun each value... or put it in list. Up to you.    </p>

```<code> def getaddress(self, lat, lng, language="en"):
        try:
            geolocator = Nominatim()
            string = str(lat) + ', ' +str(lng)
            location = geolocator.reverse(string, language=language)
            data = location.raw
            data = data['address']
            address = str(data)

            street = district = postalCode= state = country = countryCode = ""

            district    =str(data['city_district'])
            postalCode  =str(data['postcode'])
            state       =str(data['state'])
            country     =str(data['country'])
            countryCode =str(data['country_code']).upper()
            address = street +' '+ district  +' '+  postalCode  +' '+  state  +' '+  country  +' '+  countryCode
        except:
            address="Error"
        return str(address.decode('utf8'))
</code>```

Body:
I'm using GeoPy to geocode addresses to lat,lng. I would also like to extract the itemized address components (street, city, state, zip) for each address.

GeoPy returns a string with the address -- but I can't find a reliable way to separate each component. For example:

123 Main Street, Los Angeles, CA 90034, USA =>
{street: '123 Main Street', city: 'Los Angeles', state: 'CA', zip: 90034, country: 'USA'}

The Google geocoding API does return these individual components... is there a way to get these from GeoPy? (or a different geocoding tool?)

Body:
This is how I implemented such a split, as I wanted the resulting address in always the same format. You would just have to skip the concatenation and retrun each value... or put it in list. Up to you.

 def getaddress(self, lat, lng, language="en"):
        try:
            geolocator = Nominatim()
            string = str(lat) + ', ' +str(lng)
            location = geolocator.reverse(string, language=language)
            data = location.raw
            data = data['address']
            address = str(data)

            street = district = postalCode= state = country = countryCode = ""

            district    =str(data['city_district'])
            postalCode  =str(data['postcode'])
            state       =str(data['state'])
            country     =str(data['country'])
            countryCode =str(data['country_code']).upper()
            address = street +' '+ district  +' '+  postalCode  +' '+  state  +' '+  country  +' '+  countryCode
        except:
            address="Error"
        return str(address.decode('utf8'))


问:
Prompt to unlock lock screen on custom notification click
I have a custom notification shown in the lock screen. I am using a broadcast pending intent to send a message to my app once the notification is clicked. Which later starts an activity in the broadcast receiver.

The problem is, once I click on the notification, it disappears from the lock-screen and the activity is launched behind the lock-screen. It does not ask the user to unlock the screen.

My requirement is to ask the user to unlock the screen as soon as the broadcast is sent by the notification's click event. How do I do that?

I could find this question which looks like my problem. But unfortunately there is no answer.

Here is some code that explains the notification creation I did.

```<code>/**
 * Method to render Notification
 */
private void showNotification() {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    /* set mandatory stuff on builder */

    Notification notification = builder.build();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        notification.bigContentView = createCustomView(context);
    }

    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(getNotificationId(), notification);
}

/**
 * Method to return notification click's PendingIntent
 */
private PendingIntent getNotificationClickIntent() {
    Intent bcIntent = new Intent(OPEN_APP);
    bcIntent.putExtra(EXTRA_DEEP_LINK_URL, getDeepLinkUrl());

    return PendingIntent.getBroadcast(
        context, getReqCode(), bcIntent, PendingIntent.FLAG_ONE_SHOT);
}

/**
 * Method to create custom view for notification
 */
private RemoteViews createCustomView(Context context) {
   RemoteViews customView = new RemoteViews(context.getPackageName(), R.layout.custom_layout);

   if (customView != null) {
        // set dat on views

        customView.setOnClickPendingIntent(R.id.my_view, getNotificationClickIntent());
   }

   return customView;
}
</code>```

答:
Use Activity intent in pending intent instead of Service or Broadcast

```<code>PendingIntent.getActivity(context, 0, intent,
                                 PendingIntent.FLAG_UPDATE_CURRENT);
</code>```

Update:

In my case i use service.

```<code>private fun activityPendingIntent(context: Context, action: String? = null): PendingIntent {
    Timber.d("activityPendingIntent")
    val intent = Intent(context, DummyBackgroundActivity::class.java)
    action?.let { intent.action = action }
    return PendingIntent.getActivity(context, ACTIVITY_NOTIFICATION_ID, intent, PendingIntent.FLAG_CANCEL_CURRENT)
}
</code>```

DummyBackgroundActivity

```<code>class DummyBackgroundActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val service = Intent(this, BackgroundService::class.java)
        service.action = intent.action
        startService(service)
    }

    override fun onResume() {
        super.onResume()
        finish()
    }
}
</code>```

Service:

```<code>override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    Timber.d("onStartCommand intent = %s", intent?.action)
    when (intent?.action) {
       //Handle it
    }

    return Service.START_NOT_STICKY
}
</code>```

I hope you replicate the same using Broadcast.

Body:
I have a custom notification shown in the lock screen. I am using a broadcast pending intent to send a message to my app once the notification is clicked. Which later starts an activity in the broadcast receiver.

The problem is, once I click on the notification, it disappears from the lock-screen and the activity is launched behind the lock-screen. It does not ask the user to unlock the screen.

My requirement is to ask the user to unlock the screen as soon as the broadcast is sent by the notification's click event. How do I do that?

I could find this question which looks like my problem. But unfortunately there is no answer.

Here is some code that explains the notification creation I did.

/**
 * Method to render Notification
 */
private void showNotification() {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    /* set mandatory stuff on builder */

    Notification notification = builder.build();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        notification.bigContentView = createCustomView(context);
    }

    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(getNotificationId(), notification);
}

/**
 * Method to return notification click's PendingIntent
 */
private PendingIntent getNotificationClickIntent() {
    Intent bcIntent = new Intent(OPEN_APP);
    bcIntent.putExtra(EXTRA_DEEP_LINK_URL, getDeepLinkUrl());

    return PendingIntent.getBroadcast(
        context, getReqCode(), bcIntent, PendingIntent.FLAG_ONE_SHOT);
}

/**
 * Method to create custom view for notification
 */
private RemoteViews createCustomView(Context context) {
   RemoteViews customView = new RemoteViews(context.getPackageName(), R.layout.custom_layout);

   if (customView != null) {
        // set dat on views

        customView.setOnClickPendingIntent(R.id.my_view, getNotificationClickIntent());
   }

   return customView;
}

Body:
Use Activity intent in pending intent instead of Service or Broadcast

PendingIntent.getActivity(context, 0, intent,
                                 PendingIntent.FLAG_UPDATE_CURRENT);

Update:

In my case i use service.

private fun activityPendingIntent(context: Context, action: String? = null): PendingIntent {
    Timber.d("activityPendingIntent")
    val intent = Intent(context, DummyBackgroundActivity::class.java)
    action?.let { intent.action = action }
    return PendingIntent.getActivity(context, ACTIVITY_NOTIFICATION_ID, intent, PendingIntent.FLAG_CANCEL_CURRENT)
}

DummyBackgroundActivity

class DummyBackgroundActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val service = Intent(this, BackgroundService::class.java)
        service.action = intent.action
        startService(service)
    }

    override fun onResume() {
        super.onResume()
        finish()
    }
}

Service:

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    Timber.d("onStartCommand intent = %s", intent?.action)
    when (intent?.action) {
       //Handle it
    }

    return Service.START_NOT_STICKY
}

I hope you replicate the same using Broadcast.