问:
Populate a Pandas SparseDataFrame from a SciPy Sparse Matrix
I noticed Pandas now has support for Sparse Matrices and Arrays.  Currently, I create DataFrame()s like this:

```<code>return DataFrame(matrix.toarray(), columns=features, index=observations)
</code>```

Is there a way to create a SparseDataFrame() with a scipy.sparse.csc_matrix() or csr_matrix()? Converting to dense format kills RAM badly. Thanks!

答:
As of pandas v 0.20.0 you can use the SparseDataFrame constructor.

An example from the pandas docs:

```<code>import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix

arr = np.random.random(size=(1000, 5))
arr[arr < .9] = 0
sp_arr = csr_matrix(arr)
sdf = pd.SparseDataFrame(sp_arr)
</code>```

Body:
I noticed Pandas now has support for Sparse Matrices and Arrays.  Currently, I create DataFrame()s like this:

return DataFrame(matrix.toarray(), columns=features, index=observations)

Is there a way to create a SparseDataFrame() with a scipy.sparse.csc_matrix() or csr_matrix()? Converting to dense format kills RAM badly. Thanks!

Body:
As of pandas v 0.20.0 you can use the SparseDataFrame constructor.

An example from the pandas docs:

import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix

arr = np.random.random(size=(1000, 5))
arr[arr < .9] = 0
sp_arr = csr_matrix(arr)
sdf = pd.SparseDataFrame(sp_arr)


来源: stackexchange

问:
Is there a way to run R code from JavaScript?
I am working on a project which requires some R code to be run for some data analysis. The project is primarily in JavaScript, and I need a way to run R code from JS. My research has not found any good way to do it yet. Is there any way to do so?

Also, I have next to no experience with R (another person is supplying the R code).

答:
This is by no means the best way, but I was able to do the following for my own Javascript+R project (silly.r is an R script that lives in the "r" directory). I basically ran the R code as a terminal command from my express server:

app.get('/sfunction', function (req, res) {
    exec('Rscript r/silly.r this is a test', function(error, stdout, stderr) {
        if (error) {
            console.log(error);
            res.send(error);
        }
        else if (stderr) {
            console.log(stderr);
            res.send(stderr);
        }
        else if (stdout) {
            console.log("RAN SUCCESSFULLY");
            res.sendfile("savedoutput/test.json");
        }
    });
});```

The code is from lines 167-182 from here: https://github.com/ngopal/VisualEncodingEngine/blob/master/jsserver/app.js

ContentLicense: CC BY-SA 3.0

Body:
This is by no means the best way, but I was able to do the following for my own Javascript+R project (silly.r is an R script that lives in the "r" directory). I basically ran the R code as a terminal command from my express server:

app.get('/sfunction', function (req, res) {
    exec('Rscript r/silly.r this is a test', function(error, stdout, stderr) {
        if (error) {
            console.log(error);
            res.send(error);
        }
        else if (stderr) {
            console.log(stderr);
            res.send(stderr);
        }
        else if (stdout) {
            console.log("RAN SUCCESSFULLY");
            res.sendfile("savedoutput/test.json");
        }
    });
});

The code is from lines 167-182 from here: https://github.com/ngopal/VisualEncodingEngine/blob/master/jsserver/app.js


问:
c remove new line char help
Im fairly new to c sorry if this is a stupid question!

i have this:

```<code>  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question)));
  memq= question;
</code>```

however the question variable always has a new line on the end of it !
how do i remove this / prevent it happening?

i have tried this:

```<code>  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question))-sizeof(char));
  memq= question;
</code>```

there was no effect!

答:
Let's say your input is ABCDEn where the n represents the new line.

You're going to be reading in ABCDEn0 where 0 represents null, which terminates the string.

So, by taking off the last char, you're taking off the null, not the newline. I would take off the last char as you are, but then set the (new) last char to null to terminate your string.

ContentLicense: CC BY-SA 2.5

Title: c remove new line char help

Body:
Im fairly new to c sorry if this is a stupid question!

i have this:

  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question)));
  memq= question;

however the question variable always has a new line on the end of it !
how do i remove this / prevent it happening?

i have tried this:

  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question))-sizeof(char));
  memq= question;

there was no effect!


问:
Why do some built-in constructors begin with a lower case letter?
Why do some constructors like int(), list(), set() and many others starts with a lower case letter instead of upper case? Shouldn't this be written Int(), List(), Set() and so on?

答:
These types were original factory functions, not types. As such they got a lower-case name:

```<code>$ python1.5
Python 1.5.2 (#1, Apr  1 2009, 22:55:54)  [GCC 4.1.2 20070925 (Red Hat
4.1.2-27)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> type(int)
<type 'builtin_function_or_method'>
</code>```

That they are now types anyway is a historical artefact

All built-in types now follow this convention, including set and frozenset, which were added after the type unification that made int et al types.

Body:
These types were original factory functions, not types. As such they got a lower-case name:

$ python1.5
Python 1.5.2 (#1, Apr  1 2009, 22:55:54)  [GCC 4.1.2 20070925 (Red Hat
4.1.2-27)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> type(int)
<type 'builtin_function_or_method'>

That they are now types anyway is a historical artefact

All built-in types now follow this convention, including set and frozenset, which were added after the type unification that made int et al types.


问:
Room Persistence library - Nested Object with List<Video>, @Embedded doesn't work.
I have a VideoList object which I want to save using room library but when i try to use @Embedded with public List list = null; it is giving me below error: Error:(23, 24) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

VideoList Class is as below.

```<code>@Entity
public class VideoList {

@PrimaryKey
public String id;

public String title;
public String viewType;
public Integer sortingOrder = null;
public String componentSlug;
public String endPoint = null;

@Embedded
public List<Video> list = null;
public boolean hidden = false; }

Any suggestions?
</code>```

答:
I think Convertor is the best solution in this kind of nested list objects.

```<code>public class Converter {

public static String strSeparator = "__,__";

@TypeConverter
public static String convertListToString(List<Video> video) {
    Video[] videoArray = new Video[video.size()];
    for (int i = 0; i <= video.size()-1; i++) {
         videoArray[i] = video.get(i);
    }
    String str = "";
    Gson gson = new Gson();
    for (int i = 0; i < videoArray.length; i++) {
        String jsonString = gson.toJson(videoArray[i]);
        str = str + jsonString;
        if (i < videoArray.length - 1) {
            str = str + strSeparator;
        }
    }
    return str;
}

@TypeConverter
public static List<Video> convertStringToList(String videoString) {
    String[] videoArray = videoString.split(strSeparator);
    List<Video> videos = new ArrayList<Video>();
    Gson gson = new Gson();
    for (int i=0;i<videoArray.length-1;i++){
        videos.add(gson.fromJson(videoArray[i] , Video.class));
    }
    return videos;
}
</code>```

}

Body:
I have a VideoList object which I want to save using room library but when i try to use @Embedded with public List list = null; it is giving me below error: Error:(23, 24) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

VideoList Class is as below.

@Entity
public class VideoList {

@PrimaryKey
public String id;

public String title;
public String viewType;
public Integer sortingOrder = null;
public String componentSlug;
public String endPoint = null;

@Embedded
public List<Video> list = null;
public boolean hidden = false; }

Any suggestions?

Body:
I think Convertor is the best solution in this kind of nested list objects.

public class Converter {

public static String strSeparator = "__,__";

@TypeConverter
public static String convertListToString(List<Video> video) {
    Video[] videoArray = new Video[video.size()];
    for (int i = 0; i <= video.size()-1; i++) {
         videoArray[i] = video.get(i);
    }
    String str = "";
    Gson gson = new Gson();
    for (int i = 0; i < videoArray.length; i++) {
        String jsonString = gson.toJson(videoArray[i]);
        str = str + jsonString;
        if (i < videoArray.length - 1) {
            str = str + strSeparator;
        }
    }
    return str;
}

@TypeConverter
public static List<Video> convertStringToList(String videoString) {
    String[] videoArray = videoString.split(strSeparator);
    List<Video> videos = new ArrayList<Video>();
    Gson gson = new Gson();
    for (int i=0;i<videoArray.length-1;i++){
        videos.add(gson.fromJson(videoArray[i] , Video.class));
    }
    return videos;
}

}


问:
Why does Pythons "any()" function work on numpy array?
Why is it possible to use any directly as a function on a numpy array?

```<code>In [30]: any(np.zeros(4))>0
Out[30]: False
</code>```

I thought numpy's any()-method was on the array itself?

Is this the python function or the actual numpy method?

答: A numpy array is iterable, which is all the built-in any expects of its argument. any returns False if all of the elements of the iterable are falsey, which all the zeros are. Then the comparison False > 0 is also False, giving you the observed value.

Body:
Why is it possible to use any directly as a function on a numpy array?

In [30]: any(np.zeros(4))>0
Out[30]: False

I thought numpy's any()-method was on the array itself?

Is this the python function or the actual numpy method?


问:
How do I pass a reference of one object to another and still modify that first object?
I am trying to understand how references work in c++ so I have make a couple files with two different objects. One is an animal and another is a zookeeper. My goal is to pass a reference of an animal to a zookeeper and have the zookeeper change the animal's name, and still be reflected in the original animal object. How is this done using references? Here are the files I'm using.

Source.cpp

```<code>#include <iostream>
#include <string>
#include "Animal.h"
#include "zookeeper.h"

using namespace std;

int main() {

    Animal animal;
    Animal& animalRef = animal;

    printf("animal's name before it is assigned to a zookeeper: %s\n", animal.getName());

    Zookeeper aZookeeper = Zookeeper(animalRef);
    aZookeeper.changeMyAnimalsName("Fred");

    printf("animal's name after it is assigned to a zookeeper: %s\n", animal.getName());

    //Keep cmd window open
    int j;
    cin >> j;
    return 0;
}
</code>```

Animal.h

```<code>#pragma once
#include <string>

using namespace std;

class Animal {

    string name = "";
    int height = 0;
public:
    string getName() { return name; }
    int getHeight() { return height; }

    void setName(string n) { name = n; }
    void setHeight(int h) { height = h; }
};
</code>```

zookeeper.cpp

```<code>#include "zookeeper.h"

using namespace std;

Zookeeper::Zookeeper(Animal& a) {
    _myAnimal = a;
}

void Zookeeper::changeMyAnimalsName(string newName) {
    _myAnimal.setName(newName);
}
</code>```

zookeeper.h

```<code>#pragma once

#include "Animal.h"

class Zookeeper {
    Animal _myAnimal;
public:
    Zookeeper(Animal& a);
    void changeMyAnimalsName(std::string newName);
};
</code>```

答:
Your reasoning is correct, but you ended up making a copy of the animal, there:

```<code>class Zookeeper {
    Animal _myAnimal;
</code>```

If you had:

```<code>Animal& _myAnimal;
</code>```

then you would maintain the reference to the original animal, making possible for the name change to be reflected in main().

After that, you should change your constructor to this:

```<code>Zookeeper(Animal& a) : _myAnimal(a) {}
</code>```

where I used an initializer list, which is essential for references, as you can read in How to initalize the reference member variable of a class?

However, this is not enough. If you had used -Wall -Wextra flag, to enable warnings you would see this:

```<code>Source.cc: In function 'int main()':
Source.cc:13:88: warning: format '%s' expects argument of type 'char*', but argument 2 has type 'std::__cxx11::string* {aka std::__cxx11::basic_string<char>*}' [-Wformat=]
     printf("animal's name before it is assigned to a zookeeper: %s\n", animal.getName());
                                                                                ^
Source.cc:18:87: warning: format '%s' expects argument of type 'char*', but argument 2 has type 'std::__cxx11::string* {aka std::__cxx11::basic_string<char>*}' [-Wformat=]
     printf("animal's name after it is assigned to a zookeeper: %s\n", animal.getName());
                                                                                ^
</code>```

In c++ we usually print with std::cout, like this:

```<code>int main() {

    Animal animal;
    Animal& animalRef = animal; // not needed, Zookeeper(animal) OK too

    std::cout << "animal's name before it is assigned to a zookeeper: " << animal.getName() << std::endl;

    Zookeeper aZookeeper = Zookeeper(animalRef);
    aZookeeper.changeMyAnimalsName("Fred");

    std::cout << "animal's name after it is assigned to a zookeeper: " << animal.getName() << std::endl;
    return 0;
}
</code>```

Or, if you really need to use printf(), then you could use c_str(), which returns a C-string of std::string, like this:

```<code>printf("animal's name before it is assigned to a zookeeper: %s\n", animal.getName().c_str());
</code>```

Body:
I am trying to understand how references work in c++ so I have make a couple files with two different objects. One is an animal and another is a zookeeper. My goal is to pass a reference of an animal to a zookeeper and have the zookeeper change the animal's name, and still be reflected in the original animal object. How is this done using references? Here are the files I'm using.

Source.cpp

#include <iostream>
#include <string>
#include "Animal.h"
#include "zookeeper.h"

using namespace std;

int main() {

    Animal animal;
    Animal& animalRef = animal;

    printf("animal's name before it is assigned to a zookeeper: %s\n", animal.getName());

    Zookeeper aZookeeper = Zookeeper(animalRef);
    aZookeeper.changeMyAnimalsName("Fred");

    printf("animal's name after it is assigned to a zookeeper: %s\n", animal.getName());

    //Keep cmd window open
    int j;
    cin >> j;
    return 0;
}

Animal.h

#pragma once
#include <string>

using namespace std;

class Animal {

    string name = "";
    int height = 0;
public:
    string getName() { return name; }
    int getHeight() { return height; }

    void setName(string n) { name = n; }
    void setHeight(int h) { height = h; }
};

zookeeper.cpp

#include "zookeeper.h"

using namespace std;

Zookeeper::Zookeeper(Animal& a) {
    _myAnimal = a;
}

void Zookeeper::changeMyAnimalsName(string newName) {
    _myAnimal.setName(newName);
}

zookeeper.h

#pragma once

#include "Animal.h"

class Zookeeper {
    Animal _myAnimal;
public:
    Zookeeper(Animal& a);
    void changeMyAnimalsName(std::string newName);
};

Body:
Your reasoning is correct, but you ended up making a copy of the animal, there:

class Zookeeper {
    Animal _myAnimal;

If you had:

Animal& _myAnimal;

then you would maintain the reference to the original animal, making possible for the name change to be reflected in main().

After that, you should change your constructor to this:

Zookeeper(Animal& a) : _myAnimal(a) {}

where I used an initializer list, which is essential for references, as you can read in How to initalize the reference member variable of a class?

However, this is not enough. If you had used -Wall -Wextra flag, to enable warnings you would see this:

Source.cc: In function 'int main()':
Source.cc:13:88: warning: format '%s' expects argument of type 'char*', but argument 2 has type 'std::__cxx11::string* {aka std::__cxx11::basic_string<char>*}' [-Wformat=]
     printf("animal's name before it is assigned to a zookeeper: %s\n", animal.getName());
                                                                                ^
Source.cc:18:87: warning: format '%s' expects argument of type 'char*', but argument 2 has type 'std::__cxx11::string* {aka std::__cxx11::basic_string<char>*}' [-Wformat=]
     printf("animal's name after it is assigned to a zookeeper: %s\n", animal.getName());
                                                                                ^

In c++ we usually print with std::cout, like this:

int main() {

    Animal animal;
    Animal& animalRef = animal; // not needed, Zookeeper(animal) OK too

    std::cout << "animal's name before it is assigned to a zookeeper: " << animal.getName() << std::endl;

    Zookeeper aZookeeper = Zookeeper(animalRef);
    aZookeeper.changeMyAnimalsName("Fred");

    std::cout << "animal's name after it is assigned to a zookeeper: " << animal.getName() << std::endl;
    return 0;
}

Or, if you really need to use printf(), then you could use c_str(), which returns a C-string of std::string, like this:

printf("animal's name before it is assigned to a zookeeper: %s\n", animal.getName().c_str());


问:
Disable mouse hover on click
I have box which flips on hover. You can check here.
http://rehabhousedeals.com/shortcode/

I have add red icon on top right corner on other side of box.
I want as user will click on this icon box should flip back.
Actually this is for mobile view. User should be able to flip back on front side by clicking this icon.
Here are container class with hover effect in my css.

```<code>.card-container:not(.manual-flip):hover .card,
.card-container.hover.manual-flip .card{
    -webkit-transform: rotateY( 180deg );
-moz-transform: rotateY( 180deg );
 -o-transform: rotateY( 180deg );
    transform: rotateY( 180deg );
}

.card-container.static:hover .card,
.card-container.static.hover .card {
    -webkit-transform: none;
-moz-transform: none;
 -o-transform: none;
    transform: none;
}
</code>```

Kindly help me get this.

答:
A CSS only solution - you can use a checkbox, and flip/unflip using the :checked pseudo-selector and the sibling selector. To control the checkbox from the card, you can use  tags with the for attribute:

.front,
.back {
  width: 100px;
  height: 200px;
}

.front {
  background: red;
}

.back {
  background: blue;
}

.flip-container {
  position: relative;
  perspective: 1000px;
}

.flip-control {
  position: absolute;
  visibility: hidden;
  z-index: -1;
}

.flip-control:checked + .flipper,
.flip-container.hover .flipper {
  transform: rotateY(180deg);
}

.flip-container,
.front,
.back {
  width: 320px;
  height: 480px;
}

.flip-control, .flipper {
  transition: 0.6s;
  transform-style: preserve-3d;
  position: relative;
}

.front,
.back {
  backface-visibility: hidden;
  position: absolute;
  top: 0;
  left: 0;
}

.front {
  z-index: 2;
}

.back {
  transform: rotateY(180deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flip-container">
  <input id="flipControl" class="flip-control" type="checkbox" />

  <div class="flipper">
    <div class="front">
      <label for="flipControl" class="push-control-label"><img src="https://image.flaticon.com/icons/png/128/148/148752.png" width="30px" style="position:absolute; top:0; right:0; margin-right:-10px; margin-top:-10px;"></label>
    </div>
    <div class="back">
      <label for="flipControl" class="push-control-label"><img src="https://image.flaticon.com/icons/png/128/148/148752.png" width="30px" style="position:absolute; top:0; right:0; margin-right:-10px; margin-top:-10px;"></label>
    </div>
  </div>
</div></code>```

Title: Disable mouse hover on click

Body:
I have box which flips on hover. You can check here.
http://rehabhousedeals.com/shortcode/

I have add red icon on top right corner on other side of box.
I want as user will click on this icon box should flip back.
Actually this is for mobile view. User should be able to flip back on front side by clicking this icon.
Here are container class with hover effect in my css.

.card-container:not(.manual-flip):hover .card,
.card-container.hover.manual-flip .card{
    -webkit-transform: rotateY( 180deg );
-moz-transform: rotateY( 180deg );
 -o-transform: rotateY( 180deg );
    transform: rotateY( 180deg );
}

.card-container.static:hover .card,
.card-container.static.hover .card {
    -webkit-transform: none;
-moz-transform: none;
 -o-transform: none;
    transform: none;
}

Kindly help me get this.

Body:
A CSS only solution - you can use a checkbox, and flip/unflip using the :checked pseudo-selector and the sibling selector. To control the checkbox from the card, you can use <label> tags with the for attribute:

.front,
.back {
  width: 100px;
  height: 200px;
}

.front {
  background: red;
}

.back {
  background: blue;
}

.flip-container {
  position: relative;
  perspective: 1000px;
}

.flip-control {
  position: absolute;
  visibility: hidden;
  z-index: -1;
}

.flip-control:checked + .flipper,
.flip-container.hover .flipper {
  transform: rotateY(180deg);
}

.flip-container,
.front,
.back {
  width: 320px;
  height: 480px;
}

.flip-control, .flipper {
  transition: 0.6s;
  transform-style: preserve-3d;
  position: relative;
}

.front,
.back {
  backface-visibility: hidden;
  position: absolute;
  top: 0;
  left: 0;
}

.front {
  z-index: 2;
}

.back {
  transform: rotateY(180deg);
}

<div class="flip-container">
  <input id="flipControl" class="flip-control" type="checkbox" />

  <div class="flipper">
    <div class="front">
      <label for="flipControl" class="push-control-label"><img src="https://image.flaticon.com/icons/png/128/148/148752.png" width="30px" style="position:absolute; top:0; right:0; margin-right:-10px; margin-top:-10px;"></label>
    </div>
    <div class="back">
      <label for="flipControl" class="push-control-label"><img src="https://image.flaticon.com/icons/png/128/148/148752.png" width="30px" style="position:absolute; top:0; right:0; margin-right:-10px; margin-top:-10px;"></label>
    </div>
  </div>
</div>


问:
Show uploaded file via  element
I am using MAMP Pro to manage building a website on a local machine i.e. not on the actual web. I am currently having issues showing files via providing a link to the correct URL's of the files. I was wondering how I can simulate how a real web server would behave when linking to files already uploaded to a server.

```<code><!DOCTYPE html>
<html>

<head>
   <meta charset="utf-8">
    <title>Total </title>
      <link type="text/css" rel="stylesheet" href="course.css">
       <script src="../jquery.js"></script>
        <script src="../jquery-ui.js"></script>

 </head>
 <body>

<?php
  if ($handle = opendir('../uploads'))
  {
      while (false !== ($entry = readdir($handle)))
     {

      if ($entry != "." && $entry != "..")
      {

          $real= realpath($entry);

            echo  "<button class='files accordian'>$entry</button>
                     <div class='panel'>";

            echo '<a href="'.$real.'"><button class="current-file" name="sent" value="View-Current-File"><img class="view-file-img" src="../images/magnify.png">View Current File</button></a>';
      }

    }
 }

 ?>
</body>
</html>
</code>```

This code produces the error "Not Found

The requested URL /Applications/MAMP/htdocs/tutorvid/uploads/Applicatgion Text.pages was not found on this server."  but when I check the file is at this location

答:
This worked: realpath() was not needed at all</p>

```<code><a href="../uploads/'.$entry'">
</code>```

Title: Show uploaded file via <a> element

Body:
I am using MAMP Pro to manage building a website on a local machine i.e. not on the actual web. I am currently having issues showing files via providing a link to the correct URL's of the files. I was wondering how I can simulate how a real web server would behave when linking to files already uploaded to a server.

<!DOCTYPE html>

   <meta charset="utf-8">
    <title>Total </title>
      <link type="text/css" rel="stylesheet" href="course.css">

<?php
  if ($handle = opendir('../uploads'))
  {
      while (false !== ($entry = readdir($handle)))
     {

      if ($entry != "." && $entry != "..")
      {

          $real= realpath($entry);

            echo  "<button class='files accordian'>$entry</button>

";

            echo '<button class="current-file" name="sent" value="View-Current-File">View Current File</button>';
      }

    }
 }

 ?>

This code produces the error "Not Found

The requested URL /Applications/MAMP/htdocs/tutorvid/uploads/Applicatgion Text.pages was not found on this server."  but when I check the file is at this location

Body:
This worked: realpath() was not needed at all

<a href="../uploads/'.$entry'">


问:
How do I recursively replace part of a string with another given string in bash?
I need to write bash script that converts a string of only integers "intString" to :id. intString always exists after /, may never contain any other types (create_step2 is not a valid intString), and may end at either a second / or end of line. intString may be any 1-8 characters. Script needs to be repeated for every line in a given file.

For example:
/sample/123456/url should be converted to /sample/:id/url
and /sample_url/9 should be converted to /sampleurl/:id however /sample_url_2/ should remain the same.

Any help would be appreciated!

答:
It seems like the long way around the problem to go recursive but then I don't know what problem you are solving.  It seems like a good sed command like

```<code>sed -E 's/\/[0-9]{1,}/\/:id/g'
</code>```

could do it in one shot, but if you insist on being recursive then it might go something like this ...

```<code>#!/bin/bash

function restring()
{
    s="$1"
    s="$(echo $s | sed -E 's/\/[0-9]{1,}/\/:id/')"

    if ( echo $s | grep -E '\/[0-9]{1,}' > /dev/null ) ; then
        restring $s
    else
        echo $s
        exit
    fi

    echo $s
}

restring "$1"
</code>```

now run it

$ ./restring.sh "/foo/123/bar/456/baz/45435/andstuff"

/foo/:id/bar/:id/baz/:id/andstuff

Body:
It seems like the long way around the problem to go recursive but then I don't know what problem you are solving.  It seems like a good sed command like

sed -E 's/\/[0-9]{1,}/\/:id/g'

could do it in one shot, but if you insist on being recursive then it might go something like this ...

#!/bin/bash

function restring()
{
    s="$1"
    s="$(echo $s | sed -E 's/\/[0-9]{1,}/\/:id/')"

    if ( echo $s | grep -E '\/[0-9]{1,}' > /dev/null ) ; then
        restring $s
    else
        echo $s
        exit
    fi

    echo $s
}

restring "$1"

now run it

$ ./restring.sh "/foo/123/bar/456/baz/45435/andstuff"

/foo/:id/bar/:id/baz/:id/andstuff


问:
Python requests.get() raises SSL error accessing web API
I'm trying to access the   at https://www.ncdc.noaa.gov/cdo-we/api/v2/.  This requires a token one receives immediately upon requesting it here. Then:

```<code>import requests

def get_noaa_data(url, data_type, header):

    r = requests.get(url, data_type, headers=header)
    print(r)

if __name__ == '__main__':

    token = 'longalphabetictoken'
    creds = dict(token=token)
    dtype = 'dataset'
    url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/'

    get_noaa_data(url, dtype, creds)
</code>```

gives requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:720)

I understand I can set verify=False, but I do want to verify. I also want to be able to distribute this code, so I don't want to work around by modifying my cacert.pem.  I've also tried this with certifi imported into script. Is there an os-agnostic way to verify the NOAA site's SSL cert that would work if people download my package?

It seems to me that there would be a secure way to access popular APIs like this without verify=False. Is this my organization's machine's problem?

```<code>ssl.get_default_verify_paths() = DefaultVerifyPaths(cafile='/data01/anaconda2/envs/imagenv/ssl/cert.pem', capath=None, openssl_cafile_env='SSL_CERT_FILE', openssl_cafile='/data01/anaconda2/envs/imagenv/ssl/cert.pem', openssl_capath_env='SSL_CERT_DIR', openssl_capath='/data01/anaconda2/envs/imagenv/ssl/certs')
</code>```

FYI: https sites like amazon, google, etc work fine.

答: You need to make sure that your organization's SSL certificate is signed by a Certification Authority(CA), otherwise ssl connection won't work.</p>

Body:
I'm trying to access the   at https://www.ncdc.noaa.gov/cdo-we/api/v2/.  This requires a token one receives immediately upon requesting it here. Then:

import requests

def get_noaa_data(url, data_type, header):

    r = requests.get(url, data_type, headers=header)
    print(r)

if __name__ == '__main__':

    token = 'longalphabetictoken'
    creds = dict(token=token)
    dtype = 'dataset'
    url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/'

    get_noaa_data(url, dtype, creds)

gives requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:720)

I understand I can set verify=False, but I do want to verify. I also want to be able to distribute this code, so I don't want to work around by modifying my cacert.pem.  I've also tried this with certifi imported into script. Is there an os-agnostic way to verify the NOAA site's SSL cert that would work if people download my package?

It seems to me that there would be a secure way to access popular APIs like this without verify=False. Is this my organization's machine's problem?

ssl.get_default_verify_paths() = DefaultVerifyPaths(cafile='/data01/anaconda2/envs/imagenv/ssl/cert.pem', capath=None, openssl_cafile_env='SSL_CERT_FILE', openssl_cafile='/data01/anaconda2/envs/imagenv/ssl/cert.pem', openssl_capath_env='SSL_CERT_DIR', openssl_capath='/data01/anaconda2/envs/imagenv/ssl/certs')

FYI: https sites like amazon, google, etc work fine.


问:
Reflexion in java

Heading

Just a little question i can't figure

```<code>    Person per = new Person();
    Class cla = per.getClass();

    for(Method m : cla.getDeclaredMethods())
         System.out.println(m);
</code>```

for example i have in my class Person method lined like this: setName,setSecondName,getName,getSecondName and when i list the Object m my output is getName and below setName so to the last method. Can someone explain me why the method is not lists as they lined up in my Class Person?Thanks

Here is my problem in full:

```<code>    Person per = new Person();
    Class cla = per.getClass();

    for(Method m : cla.getDeclaredMethods())
    {
         System.out.println(m.getName());
        if(m.getParameterCount() > 0){
             Parameter [] pa = m.getParameters();
             if(pa.length == 1){
                 if(m.getName().equals("setName") )
                     m.invoke(per , "John");
                 else if(m.getName().endsWith("setSecondName"))
                     m.invoke(per, "Cameron");
             }

        }
         else
             System.out.println(m.invoke(per));
    }
</code>```

Acutal output:

getName

null

setName

setSecondName

getSecondName

Cameron

答:
The elements in the array returned are not sorted and are not in any particular order.

JAVA API

Title: Reflexion in java

Body:
Heading

Just a little question i can't figure

    Person per = new Person();
    Class cla = per.getClass();

    for(Method m : cla.getDeclaredMethods())
         System.out.println(m);

for example i have in my class Person method lined like this: setName,setSecondName,getName,getSecondName and when i list the Object m my output is getName and below setName so to the last method. Can someone explain me why the method is not lists as they lined up in my Class Person?Thanks

Here is my problem in full:

    Person per = new Person();
    Class cla = per.getClass();

    for(Method m : cla.getDeclaredMethods())
    {
         System.out.println(m.getName());
        if(m.getParameterCount() > 0){
             Parameter [] pa = m.getParameters();
             if(pa.length == 1){
                 if(m.getName().equals("setName") )
                     m.invoke(per , "John");
                 else if(m.getName().endsWith("setSecondName"))
                     m.invoke(per, "Cameron");
             }

        }
         else
             System.out.println(m.invoke(per));
    }

Acutal output:

getName

null

setName

setSecondName

getSecondName

Cameron


问:
How to prevent deadlocks in the following C# code?
The following C# class is used in a multithreaded enviroment. I removed very much of the actual code. The problem occurs when calling MethodA and MethodB almost simultaneously. The order of the lock in the IsDepleted property doesn't solves the problem. Removing lock(WaitingQueue) from the IsDepleted property solves the deadlock, but this solution causes a problem when another thread adds/removes an item from the WaitingQueue between the WaitingQueue.Count == 0 and Processing.Count == 0 statements.</p>

```<code>using System.Collections.Generic;

class Example
{
    bool IsDepleted
    {
        get
        {
            lock (Processing)
            {
                lock (WaitingQueue)
        {
                    return WaitingQueue.Count == 0
             && Processing.Count == 0;
        }
            }
        }
    }

    private readonly List<object> Processing = new List<object>();
    private readonly Queue<object> WaitingQueue = new Queue<object>();

    public void MethodA(object item)
    {
        lock (WaitingQueue)
        {
            if (WaitingQueue.Count > 0)
            {
                if (StartItem(WaitingQueue.Peek()))
                {
                    WaitingQueue.Dequeue();
                }
            }
        }
    }

    public void MethodB(object identifier)
    {
        lock (Processing)
        {
            Processing.Remove(identifier);
            if (!IsDepleted)
            {
                return;
            }
        }
    //Do something...
    }

    bool StartItem(object item)
    {
        //Do something and return a value
    }
}
</code>```

答:
Simplify your code and use only a single object to lock on. You could also replace your locks with:

Monitor.TryEnter(Processing,1000)

this will give you a 1 second timeout. So essentially:

```<code>        if (Monitor.TryEnter(Processing, 1000))
        {
            try
            {
                //do x
            }
            finally
            {
                Monitor.Exit(Processing);
            }
        }
</code>```

Now you won't stop the deadlock but you can handle the case where you don't get a lock.

OwnerDisplayName: Vernicht

Body:
The following C# class is used in a multithreaded enviroment. I removed very much of the actual code. The problem occurs when calling MethodA and MethodB almost simultaneously. The order of the lock in the IsDepleted property doesn't solves the problem. Removing lock(WaitingQueue) from the IsDepleted property solves the deadlock, but this solution causes a problem when another thread adds/removes an item from the WaitingQueue between the WaitingQueue.Count == 0 and Processing.Count == 0 statements.

using System.Collections.Generic;

class Example
{
    bool IsDepleted
    {
        get
        {
            lock (Processing)
            {
                lock (WaitingQueue)
        {
                    return WaitingQueue.Count == 0
             && Processing.Count == 0;
        }
            }
        }
    }

    private readonly List<object> Processing = new List<object>();
    private readonly Queue<object> WaitingQueue = new Queue<object>();

    public void MethodA(object item)
    {
        lock (WaitingQueue)
        {
            if (WaitingQueue.Count > 0)
            {
                if (StartItem(WaitingQueue.Peek()))
                {
                    WaitingQueue.Dequeue();
                }
            }
        }
    }

    public void MethodB(object identifier)
    {
        lock (Processing)
        {
            Processing.Remove(identifier);
            if (!IsDepleted)
            {
                return;
            }
        }
    //Do something...
    }

    bool StartItem(object item)
    {
        //Do something and return a value
    }
}

Body:
Simplify your code and use only a single object to lock on. You could also replace your locks with:

Monitor.TryEnter(Processing,1000)

this will give you a 1 second timeout. So essentially:

        if (Monitor.TryEnter(Processing, 1000))
        {
            try
            {
                //do x
            }
            finally
            {
                Monitor.Exit(Processing);
            }
        }

Now you won't stop the deadlock but you can handle the case where you don't get a lock.

OwnerDisplayName: Josh


问:
Error detecting icon when publishing VSCode extension
I'm putting together a VSCode extension and I've already packaged up the .vsix file a few times with no issue.

However, I've just added "icon": "images/icon.png" to the package.json and started getting an error message I just can't shake:

Error: The specified icon 'extension/images/icon.png' wasn't found in the extension.

The file definitely exists (though I don't quite understand why it looks for it under extension as a hardcoded value).

I've tried setting the baseImagesUrl in the command line for packaging, but it seems to have made no difference.

Any help/insight here would be appreciated :)

答:
It turns out the default .vscodeignore file that is dropped when you generate the extension boiler plate code has the images/** file ignored. That stops the vsix package command from pulling the icon into the package and it won't find it.

Hope this helps someone else!


问:
SimpleXML Dynamic Attributes
I'm trying to figure out how to generate the code for this.

```<code>$revImages = $revXML->addChild('images');
$revImage = $revImages->addChild('image');
$revImage->addAttribute('src', '001.jpg');
</code>```

the last line is the static entry for what I need. Is there a foreach statement I can use to auto generate that last line based on the images from a directory so it outputs as such:

```<code><images>
    <image src = "001.jpg"/>
    <image src = "002.jpg"/>
    <image src = "003.jpg"/>
    <image src = "004.jpg"/>
    <image src = "005.jpg"/>
    <image src = "006.jpg"/>
    <image src = "007.jpg"/>
    <image src = "008.jpg"/>
    <image src = "009.jpg"/>
    <image src = "010.jpg"/>
</images>
</code>```

答:
The solution using glob function (to find pathnames matching a pattern):

```<code>foreach (glob("/path/to/directory/*.jpg") as $filepath) {
    $src = basename($filepath);
    $revImages
       ->addChild('image')
       ->addAttribute('src', $src)
    ;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: SimpleXML Dynamic Attributes

Body:
I'm trying to figure out how to generate the code for this.

$revImages = $revXML->addChild('images');
$revImage = $revImages->addChild('image');
$revImage->addAttribute('src', '001.jpg');

the last line is the static entry for what I need. Is there a foreach statement I can use to auto generate that last line based on the images from a directory so it outputs as such:

<images>
    <image src = "001.jpg"/>
    <image src = "002.jpg"/>
    <image src = "003.jpg"/>
    <image src = "004.jpg"/>
    <image src = "005.jpg"/>
    <image src = "006.jpg"/>
    <image src = "007.jpg"/>
    <image src = "008.jpg"/>
    <image src = "009.jpg"/>
    <image src = "010.jpg"/>
</images>

Body:
The solution using glob function (to find pathnames matching a pattern):

foreach (glob("/path/to/directory/*.jpg") as $filepath) {
    $src = basename($filepath);
    $revImages
       ->addChild('image')
       ->addAttribute('src', $src)
    ;
}


问:
Getting error Resource violated directive 'script-src ms-appx: 'unsafe-eval'' in Host Defined Policy: inline script. Resource will be blocked
I am trying to use Visual studio to make a universal windows app.  When I try to run the following code:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>testProject</title>
    <link href="css/default.css" rel="stylesheet" />
</head>
<body>
    <div>Content goes here!</div><script src="js/main.js"></script>
    <form name="myForm">

           <input type="radio" name="myRadio" value="yes"/>  Yes <br />
           <input type="radio" name="myRadio" value="No"/> No <br />
           <input type="button" name="submit"value="submit" onsubmit="return validateForm" />
    </form>
</body>
</html>
</code>```

In JavaScript main file:

```<code>function ValiditeForm(){

    document.writeln("Hello World");
}
</code>```

When I attempt to run I get the following warning:

CSP14312: Resource violated directive 'script-src ms-appx: 'unsafe-eval'' in Host Defined Policy: inline script. Resource will be blocked.

All I am simply trying to do is write HTML code using the visual studio universal app that upon a user clicking a radio button in a HTML form, that it will be passed to a function in JavaScript and will print out a value.

答:
Correct all other syntax errors.  Click off the error message you get while the program is running (the 'x' at the top of the error output window).  Terminate your program.  Close your solution.  Exit Visual Studio.

RENAME your project folder.  Open Visual Studio from the new folder.  REBUILD your solution.  Now when
you debug, you will not see the errors.

Body:
I am trying to use Visual studio to make a universal windows app.  When I try to run the following code:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>testProject</title>
    <link href="css/default.css" rel="stylesheet" />

Content goes here!

    <form name="myForm">

           <input type="radio" name="myRadio" value="yes"/>  Yes

           <input type="radio" name="myRadio" value="No"/> No

           <input type="button" name="submit"value="submit" onsubmit="return validateForm" />
    </form>

In JavaScript main file:

function ValiditeForm(){

    document.writeln("Hello World");
}

When I attempt to run I get the following warning:

CSP14312: Resource violated directive 'script-src ms-appx: 'unsafe-eval'' in Host Defined Policy: inline script. Resource will be blocked.

All I am simply trying to do is write HTML code using the visual studio universal app that upon a user clicking a radio button in a HTML form, that it will be passed to a function in JavaScript and will print out a value.


问:
Add a UILabel as a subview of UITextView with line breaks and no horizontal indicator
My custom subclass AttributedTextView of UITextView:

```<code>@IBDesignable class AttributedTextView: UITextView {

private let placeholderLabel = UILabel(frame: .zero)

override func awakeFromNib() {
    super.awakeFromNib()

    setupPlaceholderLabelIfNeeded()
}

private func setupPlaceholderLabelIfNeeded() {

    if placeholderLabel.superview == nil {

        placeholderLabel.font = UIFont.openSansLight(withSize: 21)
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        placeholderLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        placeholderLabel.textColor = UIColor.lightGray
        placeholderLabel.text = placeholder.localized
        placeholderLabel.numberOfLines = 0

        let leading = NSLayoutConstraint(item: placeholderLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)
        let trailing = NSLayoutConstraint(item: placeholderLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)
        let top = NSLayoutConstraint(item: placeholderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)
        let bottom = NSLayoutConstraint(item: placeholderLabel, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)

        addSubview(placeholderLabel)
        addConstraints([leading, trailing, top, bottom])
    }
}
}
</code>```

The result is following:

but I would like to achieve the following:

How?

答:
Please try setting your UILabel's frame as same as your UITextView's frame.

```<code>placeholderLabel.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height)
</code>```

Body:
My custom subclass AttributedTextView of UITextView:

@IBDesignable class AttributedTextView: UITextView {

private let placeholderLabel = UILabel(frame: .zero)

override func awakeFromNib() {
    super.awakeFromNib()

    setupPlaceholderLabelIfNeeded()
}

private func setupPlaceholderLabelIfNeeded() {

    if placeholderLabel.superview == nil {

        placeholderLabel.font = UIFont.openSansLight(withSize: 21)
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        placeholderLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        placeholderLabel.textColor = UIColor.lightGray
        placeholderLabel.text = placeholder.localized
        placeholderLabel.numberOfLines = 0

        let leading = NSLayoutConstraint(item: placeholderLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)
        let trailing = NSLayoutConstraint(item: placeholderLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)
        let top = NSLayoutConstraint(item: placeholderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)
        let bottom = NSLayoutConstraint(item: placeholderLabel, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)

        addSubview(placeholderLabel)
        addConstraints([leading, trailing, top, bottom])
    }
}
}

The result is following:

but I would like to achieve the following:

How?

Body:
Please try setting your UILabel's frame as same as your UITextView's frame.

placeholderLabel.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height)


问:
How to connect to IBM Cloud object storage (Cleversafe) from Golang using the AWS S3 sdk
I'm trying to connect to IBM Cloud object storage (Cleversafe) using the following code and I get following error

"bad response: MissingRegion: could not find region configuration"

```<code>package main

import (
    "fmt"
    "os"
    "bytes"
    "net/http"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/awsutil"
    "github.com/aws/aws-sdk-go/aws/credentials"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-sdk-go/aws/session"
)

func main() {

    fmt.Printf("Starting ...")

    aws_access_key_id := "some id"
    aws_secret_access_key := "some key"
    token := ""
    creds := credentials.NewStaticCredentials(aws_access_key_id, aws_secret_access_key, token)

    fmt.Printf("creds: ", creds)

    _, err := creds.Get()
    if err != nil {
        fmt.Printf("bad credentials: %s", err)
    }
    //EndpointResolver endpoints.Resolver
    cfg := aws.NewConfig().WithEndpoint("dal.ibmselect.objstor.com").WithCredentials(creds)

    fmt.Printf("cfg: %+v \n", cfg)

    //cfg := aws.NewConfig().WithEndpointResolver()
    //cfg := aws.NewConfig().WithCredentials(creds)

    svc := s3.New(session.New(), cfg)

    fmt.Printf("svc: %+v \n", svc)

    file, err := os.Open("./test.jpg")
    if err != nil {
        fmt.Printf("err opening file: %s", err)
    }
    defer file.Close()
    fileInfo, _ := file.Stat()
    size := fileInfo.Size()
    buffer := make([]byte, size) // read file content to buffer

    file.Read(buffer)
    fileBytes := bytes.NewReader(buffer)
    fileType := http.DetectContentType(buffer)
    path := file.Name()
    params := &s3.PutObjectInput{
        Bucket:        aws.String("cosv1-jlnab"),
        Key:           aws.String(path),
        Body:          fileBytes,
        ContentLength: aws.Int64(size),
        ContentType:   aws.String(fileType),
    }
    resp, err := svc.PutObject(params)
    if err != nil {
        fmt.Printf("bad response: %s \n", err)
    }
    fmt.Printf("response %s", awsutil.StringValue(resp))
}
</code>```

答:
Essentially this happens because IBM COS and AWS S3 handle the concept of a 'region' somewhat differently.  This error is being thrown because the AWS Go SDK doesn't know what value to provide for the 'region' variable used to calculate the authorization header.  In this context, IBM COS doesn't care what value, as long is it isn't null.  The easiest way is to provide an environment variable via the command line: export AWS_REGION=foo where foo can be any string, although it could also be set as a configuration variable at client creation within your application.

I'd recommend using something that makes sense, like us or us-south as IBM COS will probably enforce this at some point down the road by linking the concept of 'region' to the AWS LocationConstraint variable, which is currently used by IBM COS to define the storage class of a bucket, although this distinction will be made explicit at some point in the future.

Body:
I'm trying to connect to IBM Cloud object storage (Cleversafe) using the following code and I get following error

"bad response: MissingRegion: could not find region configuration"

package main

import (
    "fmt"
    "os"
    "bytes"
    "net/http"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/awsutil"
    "github.com/aws/aws-sdk-go/aws/credentials"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-sdk-go/aws/session"
)

func main() {

    fmt.Printf("Starting ...")

    aws_access_key_id := "some id"
    aws_secret_access_key := "some key"
    token := ""
    creds := credentials.NewStaticCredentials(aws_access_key_id, aws_secret_access_key, token)

    fmt.Printf("creds: ", creds)

    _, err := creds.Get()
    if err != nil {
        fmt.Printf("bad credentials: %s", err)
    }
    //EndpointResolver endpoints.Resolver
    cfg := aws.NewConfig().WithEndpoint("dal.ibmselect.objstor.com").WithCredentials(creds)

    fmt.Printf("cfg: %+v \n", cfg)

    //cfg := aws.NewConfig().WithEndpointResolver()
    //cfg := aws.NewConfig().WithCredentials(creds)

    svc := s3.New(session.New(), cfg)

    fmt.Printf("svc: %+v \n", svc)

    file, err := os.Open("./test.jpg")
    if err != nil {
        fmt.Printf("err opening file: %s", err)
    }
    defer file.Close()
    fileInfo, _ := file.Stat()
    size := fileInfo.Size()
    buffer := make([]byte, size) // read file content to buffer

    file.Read(buffer)
    fileBytes := bytes.NewReader(buffer)
    fileType := http.DetectContentType(buffer)
    path := file.Name()
    params := &s3.PutObjectInput{
        Bucket:        aws.String("cosv1-jlnab"),
        Key:           aws.String(path),
        Body:          fileBytes,
        ContentLength: aws.Int64(size),
        ContentType:   aws.String(fileType),
    }
    resp, err := svc.PutObject(params)
    if err != nil {
        fmt.Printf("bad response: %s \n", err)
    }
    fmt.Printf("response %s", awsutil.StringValue(resp))
}


问:
How to print only a selected HTML element?
I am trying to implement a print feature in HTML. I know I can print the whole page with window.print(), but how do I print only a specific page element? For example a particular
Some text to print
.

答:
If you are using JQuery, you can use clone to do the following:

```<code>function printElement(e) {
  var ifr = document.createElement('iframe');
  ifr.style='height: 0px; width: 0px; position: absolute'
  document.body.appendChild(ifr);

  $(e).clone().appendTo(ifr.contentDocument.body);
  ifr.contentWindow.print();

  ifr.parentElement.removeChild(ifr);
}
</code>```

and use like so:
printElement(document.getElementById('myElementToPrint'))

Body:
If you are using JQuery, you can use clone to do the following:

function printElement(e) {
  var ifr = document.createElement('iframe');
  ifr.style='height: 0px; width: 0px; position: absolute'
  document.body.appendChild(ifr);

  $(e).clone().appendTo(ifr.contentDocument.body);
  ifr.contentWindow.print();

  ifr.parentElement.removeChild(ifr);
}

and use like so:
printElement(document.getElementById('myElementToPrint'))


问:
Prolog Extended Euclidian Algorithm
I have been struggling with some prolog code for several days and I couldn't find a way out of it. I am trying to write the extended Euclidean algorithm and find values p and s in :

```<code>a*p + b*s = gcd(a,b)
</code>```

equation and here is what I have tried :`

```<code> common(X,X,X,_,_,_,_,_,_).
 common(0,Y,Y,_,_,_,_,_,_).
 common(X,0,X,_,_,_,_,_,_).

 common(X,Y,_,1,0,L1,L2,SF,TF):-
                                  append(L1,1,[H]),
                                  append(L2,0,[A]),
                                  SF is H ,
                                  TF is A,
                                  common(X,Y,_,0,1,[H],[A],SF,TF).

 common(X,Y,_,0,1,L1,L2,SF,TF):-
                                  append(L1,0,[_,S2]),
                                  append(L2,1,[_,T2]),
                                  Q is truncate(X/Y),
                                  S is 1-Q*0,T is 0-Q*1 ,
                                  common(X,Y,_,S,T,[S2,S],
                                  [T2,T],SF,TF).

 common(X,Y,N,S,T,[S1,S2],[T1,T2],SF,TF):-
                                  Q is truncate(X/Y),
                                  K is X-(Y*Q),
                                  si_finder(S1,S2,Q,SF),
                                  ti_finder(T1,T2,Q,TF),

common(Y,K,N,S,T,[S2,S],[T2,T],SF,TF).

si_finder(PP,P,Q,C):- C is  PP - Q*P.

ti_finder(P2,P1,QA,C2):- C2 is P2 - QA*P1.
</code>```

After a little search I found that s and p coefficients start from 1 and 0 and the second values for them are 0 and 1 respectively.Then it continues in a pattern which is what I have done in si_finder and ti_finder predicates.Common predicates are where I tried to control the pattern recursively. However the common predicates keeps on returning false in every call. Can anyone help me implement this algorithm in Prolog.

Thanks in advance.

答:
First let's think about the arity of the predicate. Obviously you want to have the numbers A and B as well as the Bézout coefficients P and S as arguments. Since the algorithm is calculating the GCD anyway, it is opportune to have that as an argument as well. That leaves us with arity 5. As we're talking about the extended Euclidean algorithm, let' call the predicate eeuclid/5. Next, consider an example: Let's use the algorithm to calculate P, S and GCD for A=242 and B=69:

```<code>quotient (Q) | remainder    (B1) |   P   |   S
-------------+-------------------+-------+-------
             |              242  |   1   |   0
             |              69   |   0   |   1
242/69 = 3   | 242 − 3*69 = 35   |   1   |  -3
69/35  = 1   | 69 − 1*35  = 34   |  -1   |   4
35/34  = 1   | 35 − 1*34  = 1    |   2   |  -7
34/1   = 34  | 34 − 34*1  = 0    | -69   | 242
</code>```

We can observe the following:

The algorithm stops if the remainder becomes 0

The line before the last row contains the GCD in the remainder column (in this example 1) and the Bézout coefficients in the P and S columns respectively (in this example 2 and -7)

The quotient is calculated from the previous to remainders. So in the next iteration A becomes B and B becomes B1.

P and S are calculated from their respective predecessors. For example: P3 = P1 - 3*P2 = 1 - 3*0 = 1 and S3 = S1 - 3*S2 = 0 - 3*1 = -3. And since it's sufficient to have the previous two P's and S's, we might as well pass them on as pairs, e.g. P1-P2 and S1-S2.

The algorithm starts with the pairs P: 1-0 and S: 0-1

The algorithm starts with the bigger number

Putting all this together, the calling predicate has to ensure that A is the bigger number and, in addition to it's five arguments, it has to pass along the starting pairs 1-0 and 0-1 to the predicate describing the actual relation, here a_b_p_s_/7:

```<code>:- use_module(library(clpfd)).

eeuclid(A,B,P,S,GCD) :-
   A #>= B,
   GCD #= A*P + B*S,                % <- new
   a_b_p_s_(A,B,P,S,1-0,0-1,GCD).
eeuclid(A,B,P,S,GCD) :-
   A #< B,
   GCD #= A*P + B*S,                % <- new
   a_b_p_s_(B,A,S,P,1-0,0-1,GCD).
</code>```

The first rule of a_b_p_s_/7 describes the base case, where B=0 and the algorithm stops. Then A is the GCD and P1, S1 are the Bézout coefficients. Otherwise the quotient Q, the remainder B1 and the new values for P and S are calculated and a_b_p_s_/7 is called with those new values:

```<code>a_b_p_s_(A,0,P1,S1,P1-_P2,S1-_S2,A).
a_b_p_s_(A,B,P,S,P1-P2,S1-S2,GCD) :-
   B #> 0,
   A #> B,                          % <- new
   Q #= A/B,
   B1 #= A mod B,
   P3 #= P1-(Q*P2),
   S3 #= S1-(Q*S2),
   a_b_p_s_(B,B1,P,S,P2-P3,S2-S3,GCD).
</code>```

Querying this with the above example yields the desired result:

```<code>?- eeuclid(242,69,P,S,GCD).
P = 2,
S = -7,
GCD = 1 ;
false.
</code>```

And indeed: gcd(242,69) = 1 = 2*242 − 7*69

EDIT: On a second thought I would suggest to add two constraints. Firstly Bézout's identity before calling a_b_p_s_/7 and secondly A #> B after the first goal of a_b_p_s_/7. I edited the predicates above and marked the new goals. These additions make eeuclid/5 more versatile. For example, you could ask what numbers A and B have the Bézout coefficients 2 and -7 and 1 as the gcd. There is no unique answer to this query and Prolog will give you residual goals for every potential solution. However, you can ask for a limited range for A and B, say between 0 and 50 and then use label/1 to get actual numbers:

```<code>?-  [A,B] ins 0..50, eeuclid(A,B,2,-7,1), label([A,B]).
A = 18,
B = 5 ;
A = 25,
B = 7 ;
A = 32,
B = 9 ;
A = 39,
B = 11 ;
A = 46,
B = 13 ;
false.       % <- previously loop here
</code>```

Without the newly added constraints the query would not terminate after the fifth solution. However, with the new constraints Prolog is able to determine, that there are no more solutions between 0 and 50.

Title: Prolog Extended Euclidian Algorithm

Body:
I have been struggling with some prolog code for several days and I couldn't find a way out of it. I am trying to write the extended Euclidean algorithm and find values p and s in :

a*p + b*s = gcd(a,b)

equation and here is what I have tried :`

 common(X,X,X,_,_,_,_,_,_).
 common(0,Y,Y,_,_,_,_,_,_).
 common(X,0,X,_,_,_,_,_,_).

 common(X,Y,_,1,0,L1,L2,SF,TF):-
                                  append(L1,1,[H]),
                                  append(L2,0,[A]),
                                  SF is H ,
                                  TF is A,
                                  common(X,Y,_,0,1,[H],[A],SF,TF).

 common(X,Y,_,0,1,L1,L2,SF,TF):-
                                  append(L1,0,[_,S2]),
                                  append(L2,1,[_,T2]),
                                  Q is truncate(X/Y),
                                  S is 1-Q*0,T is 0-Q*1 ,
                                  common(X,Y,_,S,T,[S2,S],
                                  [T2,T],SF,TF).

 common(X,Y,N,S,T,[S1,S2],[T1,T2],SF,TF):-
                                  Q is truncate(X/Y),
                                  K is X-(Y*Q),
                                  si_finder(S1,S2,Q,SF),
                                  ti_finder(T1,T2,Q,TF),

common(Y,K,N,S,T,[S2,S],[T2,T],SF,TF).

si_finder(PP,P,Q,C):- C is  PP - Q*P.

ti_finder(P2,P1,QA,C2):- C2 is P2 - QA*P1.

After a little search I found that s and p coefficients start from 1 and 0 and the second values for them are 0 and 1 respectively.Then it continues in a pattern which is what I have done in si_finder and ti_finder predicates.Common predicates are where I tried to control the pattern recursively. However the common predicates keeps on returning false in every call. Can anyone help me implement this algorithm in Prolog.

Thanks in advance.

Body:
First let's think about the arity of the predicate. Obviously you want to have the numbers A and B as well as the Bézout coefficients P and S as arguments. Since the algorithm is calculating the GCD anyway, it is opportune to have that as an argument as well. That leaves us with arity 5. As we're talking about the extended Euclidean algorithm, let' call the predicate eeuclid/5. Next, consider an example: Let's use the algorithm to calculate P, S and GCD for A=242 and B=69:

quotient (Q) | remainder    (B1) |   P   |   S
-------------+-------------------+-------+-------
             |              242  |   1   |   0
             |              69   |   0   |   1
242/69 = 3   | 242 − 3*69 = 35   |   1   |  -3
69/35  = 1   | 69 − 1*35  = 34   |  -1   |   4
35/34  = 1   | 35 − 1*34  = 1    |   2   |  -7
34/1   = 34  | 34 − 34*1  = 0    | -69   | 242

We can observe the following:

The algorithm stops if the remainder becomes 0

The line before the last row contains the GCD in the remainder column (in this example 1) and the Bézout coefficients in the P and S columns respectively (in this example 2 and -7)

The quotient is calculated from the previous to remainders. So in the next iteration A becomes B and B becomes B1.

P and S are calculated from their respective predecessors. For example: P3 = P1 - 3*P2 = 1 - 3*0 = 1 and S3 = S1 - 3*S2 = 0 - 3*1 = -3. And since it's sufficient to have the previous two P's and S's, we might as well pass them on as pairs, e.g. P1-P2 and S1-S2.

The algorithm starts with the pairs P: 1-0 and S: 0-1

The algorithm starts with the bigger number

Putting all this together, the calling predicate has to ensure that A is the bigger number and, in addition to it's five arguments, it has to pass along the starting pairs 1-0 and 0-1 to the predicate describing the actual relation, here a_b_p_s_/7:

:- use_module(library(clpfd)).

eeuclid(A,B,P,S,GCD) :-
   A #>= B,
   GCD #= A*P + B*S,                % <- new
   a_b_p_s_(A,B,P,S,1-0,0-1,GCD).
eeuclid(A,B,P,S,GCD) :-
   A #< B,
   GCD #= A*P + B*S,                % <- new
   a_b_p_s_(B,A,S,P,1-0,0-1,GCD).

The first rule of a_b_p_s_/7 describes the base case, where B=0 and the algorithm stops. Then A is the GCD and P1, S1 are the Bézout coefficients. Otherwise the quotient Q, the remainder B1 and the new values for P and S are calculated and a_b_p_s_/7 is called with those new values:

a_b_p_s_(A,0,P1,S1,P1-_P2,S1-_S2,A).
a_b_p_s_(A,B,P,S,P1-P2,S1-S2,GCD) :-
   B #> 0,
   A #> B,                          % <- new
   Q #= A/B,
   B1 #= A mod B,
   P3 #= P1-(Q*P2),
   S3 #= S1-(Q*S2),
   a_b_p_s_(B,B1,P,S,P2-P3,S2-S3,GCD).

Querying this with the above example yields the desired result:

?- eeuclid(242,69,P,S,GCD).
P = 2,
S = -7,
GCD = 1 ;
false.

And indeed: gcd(242,69) = 1 = 2*242 − 7*69

EDIT: On a second thought I would suggest to add two constraints. Firstly Bézout's identity before calling a_b_p_s_/7 and secondly A #> B after the first goal of a_b_p_s_/7. I edited the predicates above and marked the new goals. These additions make eeuclid/5 more versatile. For example, you could ask what numbers A and B have the Bézout coefficients 2 and -7 and 1 as the gcd. There is no unique answer to this query and Prolog will give you residual goals for every potential solution. However, you can ask for a limited range for A and B, say between 0 and 50 and then use label/1 to get actual numbers:

?-  [A,B] ins 0..50, eeuclid(A,B,2,-7,1), label([A,B]).
A = 18,
B = 5 ;
A = 25,
B = 7 ;
A = 32,
B = 9 ;
A = 39,
B = 11 ;
A = 46,
B = 13 ;
false.       % <- previously loop here

Without the newly added constraints the query would not terminate after the fifth solution. However, with the new constraints Prolog is able to determine, that there are no more solutions between 0 and 50.


问:
heap pollution for simple parameter
I have following function:

```<code>public static <T> List<T> list(T... xs) {
    final List<T> lst = new ArrayList<T>();
    for (final T x : xs) {
        lst.add(x);
    }

    return lst;
}
</code>```

Its usage is simple:

```<code>   List<Integer> ints = list(1, 2, 3, 4)
</code>```

Compiler gives me following warning for this list

"TypeSafety: potential heap pollution for via varargs parameter

I tried to find what it means but all explanastions I found were for functions of parameters that are themselves parametrized e.g.

f(List<T>... xss).

While I have function of generic non parametrized parameter.

Please explain me what is the potential problem with my function because I can not find any.

答: @VasiliyVlasov's answer nicely explains the reason for the warning. But in the context of your question, the list() method is indeed safe because it doesn't do any unsafe operations. The warning only says there's a "potential problem" because the compiler can't be sure the method you're calling is implemented safely. To avoid the warning, you can vouch for the safety of your method by marking it with @SafeVarargs. See the Javadoc and the JLS for more details.

Title: heap pollution for simple parameter

Body:
I have following function:

public static <T> List<T> list(T... xs) {
    final List<T> lst = new ArrayList<T>();
    for (final T x : xs) {
        lst.add(x);
    }

    return lst;
}

Its usage is simple:

   List<Integer> ints = list(1, 2, 3, 4)

Compiler gives me following warning for this list

"TypeSafety: potential heap pollution for via varargs parameter

I tried to find what it means but all explanastions I found were for functions of parameters that are themselves parametrized e.g.

f(List<T>... xss).

While I have function of generic non parametrized parameter.

Please explain me what is the potential problem with my function because I can not find any.


问:
SELECT TOP N with UNION and ORDER BY
Given the example below, why does using using UNION ALL with two SELECT TOP 5 statements in Query 2 below seemingly not respect the ORDER BY clause?

Query 1 returns the expected results but does not include the required union.
Query 2 demonstrates the unexpected behavior.
Query 3 is the workaround I'm currently using to get the desired results.

```<code>CREATE TABLE #T1 ([ID] int IDENTITY(1,1), [Description] varchar(100), [Inactive] bit);
CREATE TABLE #T2 ([ID] int IDENTITY(1,1), [Description] varchar(100), [Inactive] bit);

INSERT INTO #T1([Description], [Inactive]) VALUES ('One', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Two', 0);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Three', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Four', 0);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Five', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Six', 0);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Seven', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Eight', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Nine', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Ten', 0);

-- Query 1, works as expected giving all 4 records with Inactive = 0 plus one more
SELECT TOP 5 [ID], [Description], [Inactive]
FROM #T1
ORDER BY [Inactive], [Description];

-- Query 2, does not work as expected, as only 2 of the Inactive = 0 records are present
SELECT TOP 5 [ID], [Description], [Inactive]
FROM #T1
UNION ALL
SELECT TOP 5 [ID], [Description], [Inactive]
FROM #T2
ORDER BY [Inactive], [Description];

-- Query 3, Workaround to produce desired results
WITH T1 AS (
    SELECT TOP 5 [ID], [Description], [Inactive]
    FROM #T1
    ORDER BY [Inactive], [Description]
),
T2 AS (
    SELECT TOP 5 [ID], [Description], [Inactive]
    FROM #T2
    ORDER BY [Inactive], [Description]
)
SELECT [ID], [Description], [Inactive] FROM T1
UNION ALL
SELECT [ID], [Description], [Inactive] FROM T2
ORDER BY [Inactive], [Description];

DROP TABLE #T1;
DROP TABLE #T2;
</code>```

Obviously, the workaround is working for me but I'd like to understand why Query 2 does not do what I expected it to.  In case you're wondering why I am bothering with the empty table #T2, the results are actually limited by a WHERE clause in my production example - however leaving it empty here serves the purpose of providing a comparable example without bothering to populate it.

If you do populate #T2 with the following, I find the results to be just as strange - Query 2 only gives four results with Inactive = 0.

```<code>INSERT INTO #T2([Description], [Inactive]) VALUES ('Eleven', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Twelve', 0);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Thirteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Fourteen', 0);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Fifteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Sixteen', 0);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Seventeen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Eighteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Nineteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Twenty', 0);
</code>```

I have run this script with the same results on SQL Server 2014 and SQL Server 2008 R2.

答:
There is a major difference between query #2 and #3 - the ORDER BY clause on #T1. </p>

<p>The thumb rule is -in a SQL query if you don't specify the ORDER BY cause, "TOP" will just return random set of records. After you get these "random" rows, the sorting comes into play. And hence there is no "proper" sorting taking place. </p>

Title: SELECT TOP N with UNION and ORDER BY

Body:
Given the example below, why does using using UNION ALL with two SELECT TOP 5 statements in Query 2 below seemingly not respect the ORDER BY clause?

Query 1 returns the expected results but does not include the required union.
Query 2 demonstrates the unexpected behavior.
Query 3 is the workaround I'm currently using to get the desired results.

CREATE TABLE #T1 ([ID] int IDENTITY(1,1), [Description] varchar(100), [Inactive] bit);
CREATE TABLE #T2 ([ID] int IDENTITY(1,1), [Description] varchar(100), [Inactive] bit);

INSERT INTO #T1([Description], [Inactive]) VALUES ('One', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Two', 0);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Three', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Four', 0);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Five', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Six', 0);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Seven', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Eight', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Nine', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Ten', 0);

-- Query 1, works as expected giving all 4 records with Inactive = 0 plus one more
SELECT TOP 5 [ID], [Description], [Inactive]
FROM #T1
ORDER BY [Inactive], [Description];

-- Query 2, does not work as expected, as only 2 of the Inactive = 0 records are present
SELECT TOP 5 [ID], [Description], [Inactive]
FROM #T1
UNION ALL
SELECT TOP 5 [ID], [Description], [Inactive]
FROM #T2
ORDER BY [Inactive], [Description];

-- Query 3, Workaround to produce desired results
WITH T1 AS (
    SELECT TOP 5 [ID], [Description], [Inactive]
    FROM #T1
    ORDER BY [Inactive], [Description]
),
T2 AS (
    SELECT TOP 5 [ID], [Description], [Inactive]
    FROM #T2
    ORDER BY [Inactive], [Description]
)
SELECT [ID], [Description], [Inactive] FROM T1
UNION ALL
SELECT [ID], [Description], [Inactive] FROM T2
ORDER BY [Inactive], [Description];

DROP TABLE #T1;
DROP TABLE #T2;

Obviously, the workaround is working for me but I'd like to understand why Query 2 does not do what I expected it to.  In case you're wondering why I am bothering with the empty table #T2, the results are actually limited by a WHERE clause in my production example - however leaving it empty here serves the purpose of providing a comparable example without bothering to populate it.

If you do populate #T2 with the following, I find the results to be just as strange - Query 2 only gives four results with Inactive = 0.

INSERT INTO #T2([Description], [Inactive]) VALUES ('Eleven', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Twelve', 0);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Thirteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Fourteen', 0);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Fifteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Sixteen', 0);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Seventeen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Eighteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Nineteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Twenty', 0);

I have run this script with the same results on SQL Server 2014 and SQL Server 2008 R2.

Body:
There is a major difference between query #2 and #3 - the ORDER BY clause on #T1.

The thumb rule is -in a SQL query if you don't specify the ORDER BY cause, "TOP" will just return random set of records. After you get these "random" rows, the sorting comes into play. And hence there is no "proper" sorting taking place.


问:
Loading Mongo Driver 1.6.x driver on WAMP 64bit architecture
So I've installed 64bit Apache/PHP locally. Both Apache and PHP were compiled against the VC11 C++ redistributable.

https://www.apachelounge.com/download/VC11/ and

http://windows.php.net/download/ PHP5.6 (Yes... ) x64 Thread Safe (respectively)

Both work fine! (screenshots with version and architecture info inc.)

I've downloaded multiple varaities of the 1.6.x driver from both PECL and an repo' at Amazon.

https://pecl.php.net/package/mongo/1.6.14/windows

https://s3.amazonaws.com/drivers.mongodb.org/php/index.html

I've made sure they're the x64 Thread Safe variety and added to my ~/php/ext folder.

I've made sure the extension is loaded in php.ini (and that the write .ini file is called):
extension=php_mongo-1.6.8-5.6-vc11-x86_64.dll

But everytime I restart Apache I get this in my PHP error log:

[07-Jun-2017 20:21:20 UTC] PHP Warning:  PHP Startup: Unable to load dynamic library 'E:\PHP5.6\ext\php_mongo-1.6.8-5.6-vc11-x86_64.dll' - %1 is not a valid Win32 application.

(Apache comes up clean. Error.log clean)

Why is it protesting that this is not a Win32 Application. I don't want it to be. My entire architecture is 64bit and so is the Mongo Driver.

答:
In case anyone else comes across this thread. After hours of trying to get it to run I just downgraded everything to 32-bit. Worked right out the gate.

Despite PECL offering a "64bit" driver - https://pecl.php.net/package/mongo/1.6.14/windows it didn't seem to be compatible with 64bit/VC11/Thread Safe versions of Apache/PHP

I'm not sure if this is an issue with the Mongo driver compilation or something deeper?

Anyway. Downgrade to 32-bit. Mongo 1.6.x drivers will then run.


问:
Optimizing a SQL query on SQL Server
I have a SQL query on SQL Server that needs to be optimized.
It takes almost 16 minutes to run it.

```<code>SELECT DISTINCT DeptNo,
                BrandDesc,
                MfgDesc,
                CountOfActiveSKUs =
                    COALESCE((SELECT COUNT(*)
                                FROM dbo.SKU k
                               WHERE k.Status = 'A'
                                 AND k.BrandDesc = s.BrandDesc
                                 AND k.MfgDesc = s.MfgDesc
                                 AND k.DeptNo = s.DeptNo),
                             0)
           FROM dbo.SKU s
       ORDER BY BrandDesc
</code>```

I came up with the following, but it doesn't seems it grabs records that have CountOfActiveSKUs = 0.

```<code>SELECT DISTINCT DeptNo,
                BrandDesc,
                MfgDesc,
                CountOfActiveSKUs = COALESCE(Count(*), 0)
           FROM dbo.SKU
          WHERE Status = 'A'
       GROUP BY BrandDesc, MfgDesc, DeptNo
       ORDER BY BrandDesc
</code>```

Any help is appreciated,
Thank you!

答:
Don't filter the status, count the SKUs with status='A' using a conditional SUM.</p>

```<code>SELECT DISTINCT DeptNo,
                BrandDesc,
                MfgDesc,
                SUM(CASE WHEN status = 'A' THEN 1 ELSE 0 END) as CountOfActiveSKUs
           FROM dbo.SKU
       GROUP BY BrandDesc, MfgDesc, DeptNo
       ORDER BY BrandDesc
</code>```

Title: Optimizing a SQL query on SQL Server

Body:
I have a SQL query on SQL Server that needs to be optimized.
It takes almost 16 minutes to run it.

SELECT DISTINCT DeptNo,
                BrandDesc,
                MfgDesc,
                CountOfActiveSKUs =
                    COALESCE((SELECT COUNT(*)
                                FROM dbo.SKU k
                               WHERE k.Status = 'A'
                                 AND k.BrandDesc = s.BrandDesc
                                 AND k.MfgDesc = s.MfgDesc
                                 AND k.DeptNo = s.DeptNo),
                             0)
           FROM dbo.SKU s
       ORDER BY BrandDesc

I came up with the following, but it doesn't seems it grabs records that have CountOfActiveSKUs = 0.

SELECT DISTINCT DeptNo,
                BrandDesc,
                MfgDesc,
                CountOfActiveSKUs = COALESCE(Count(*), 0)
           FROM dbo.SKU
          WHERE Status = 'A'
       GROUP BY BrandDesc, MfgDesc, DeptNo
       ORDER BY BrandDesc

Any help is appreciated,
Thank you!

Body:
Don't filter the status, count the SKUs with status='A' using a conditional SUM.

SELECT DISTINCT DeptNo,
                BrandDesc,
                MfgDesc,
                SUM(CASE WHEN status = 'A' THEN 1 ELSE 0 END) as CountOfActiveSKUs
           FROM dbo.SKU
       GROUP BY BrandDesc, MfgDesc, DeptNo
       ORDER BY BrandDesc


问:
Dropdown trigger change function to fetch dates to disable in datetimepicker
I have a dropdown of staff names and  StaffId. This is wired to an appointment business logic. I am trying to trigger a select change so that setting dates stored in database will be made unavailable in the connected jquery datetimepicker.  I have assembled the code below which seems not working. Could anyone point me to the right direction. Thanks</p>

```<code><script type="text/javascript">
        $(document).ready(function () {
            getdates();
        });

        var unavailableDates;
        $(document).ready( function getdates() {

            $("#StaffId").change(function (e) {
                $this = $(e.target);
                    $.ajax({
                        type: "POST",
                        url: "/Appointment/GetOffdays",
                        data: { StaffId: $this.val()  },
                        //contentType: "application/json"
                        success: function (data) {
                            debugger;
                            unavailableDates = data;

                            $(".jqueryui-marker-datepicker").datepicker({
                                dateFormat: "dd/M/yy",
                                changeMonth: true,
                                changeYear: false,
                                yearRange: "-1:+0",
                                //beforeShowDay: $.datepicker.noWeekends,
                                minDate: new Date(@(ViewBag.year+","+ViewBag.month+","+ViewBag.day)),
                                maxDate: new Date(@(ViewBag.eyear+","+ViewBag.emonth+","+ViewBag.eday)),

                                beforeShowDay: function (date) {
                                    var dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
                                    debugger;
                                    if ($.inArray(dmy, unavailableDates) == -1) {
                                        return [true, ""];
                                    } else {
                                        return [false, "myclass", "Unavailable"];
                                    }
                                }
                                });
                            },
                             dataType: "json",
                            traditional: true,
                            })

                }

           )
            $('#StaffId').trigger('change');
        });
        </script>
</code>```

答:
Perhaps because you aren't definibg a value for the dropdown first. Try this:

```<code>$('#StaffId').val('12345');
$('#StaffId').trigger('change');
</code>```

Other remark: why the 2 document ready's ?

Body:
Perhaps because you aren't definibg a value for the dropdown first. Try this:

$('#StaffId').val('12345');
$('#StaffId').trigger('change');

Other remark: why the 2 document ready's ?


问:
MATLAB FFT -> Equalizer -> iFFT
I’m trying to implement a 32 point FFT - Equalizer - iFFT

On a step by step basis. I input a Time domain signal to a FFT block and then used iFFT to obtain the original data back.

Naturally after FFT, I get 32 points of symmetrical real and imaginary data.

I tried,

Step 1:

```<code>   fft_sig = fft(data_processing_block);                 %FFT of the signal

  ifft_sig = ifft(fft_sig);                            %iFFT of the signal
</code>```

The output matches the input. Works like a charm.

Step 2:

```<code>  fft_sig = fft(data_processing_block);                 %FFT of the signal

  after_eq_re = real(fft_sig);
  after_eq_im = imag(fft_sig);

  after_eq = after_eq_re + (i*after_eq_im);

  ifft_sig = ifft(after_eq);                            %iFFT of the signal
</code>```

This also works just fine.

Step 3:

```<code>  fft_sig = fft(data_processing_block);                 %FFT of the signal

  after_eq_re = real(fft_sig).*1.0;                     % Multiply Real data with a constant
  after_eq_im = imag(fft_sig).*1.0;                     % Multiply Imag data with a constant

  after_eq = after_eq_re + (i*after_eq_im);

  ifft_sig = ifft(after_eq);                            %iFFT of the signal
</code>```

This also works fine.

Step 4:

I replaced the constant (1.0) with an Equalizer table. Of size 32.

```<code>Eq_data_32 =[0.0;0.1347;0.2117;0.2956;0.4146;0.5300;0.5615;0.5195;0.4391;0.3621;0.2816;0.1977;0.1837;0.1172;0.0857;0.0577;0.0;0.0577;0.0857;0.1172;0.1837;0.1977;0.2816;0.3621;0.4391;0.5195;0.5615;0.5300;0.4146;0.2956;0.2117;0.1347];
</code>```

Eq_data_32(1) and Eq_data_32(17) are zeros.  Eq_data_32(2:16) is symmetrical to Eq_data_32(18:32).

```<code> re_Eq_data_32 = Eq_data_32;  % Equalizer data for real values
 im_Eq_data_32 = -(re_Eq_data_32);  % Equalizer data for imaginary values

  fft_sig = fft(data_processing_block);                 %FFT of the signal

  after_eq_re = real(fft_sig).*re_Eq_data_32';
  after_eq_im = imag(fft_sig).*im_Eq_data_32';

  after_eq = after_eq_re + (i*after_eq_im);
  ifft_sig = ifft(after_eq);                             %iFFT of the signal
</code>```

Now the output is distorted and does not sound good. I think this is due to symmetry of the Equalizer table. I can’t figure how to arrange the Equalizer table to preserve the symmetry. As far as I can tell, my real and imaginary Equalizer  table are symmetric. So why can’t I get a clear output ?

Complete code:

```<code>Fs = 16000;                       % sampling frequency
no_samples = 640;                  % no of samples
Freq1 = 1000;                      % Frequency 1 of the signal
Freq2 = 2500;                      % Frequency 2 of the signal
Freq3 = 3500;                      % Frequency 3 of the signal
Amp = 0.1;
t = 1/Fs*((1:no_samples)-1);      % time duration, t = 1/Fs
Input_sig_16k = Amp*sin(2*pi*Freq1*t)+Amp*sin(2*pi*Freq2*t)+Amp*sin(2*pi*Freq3*t);  % Multitone Input Signal

% Equlizer data
Eq_data_32 =[0.0;0.1347;0.2117;0.2956;0.4146;0.5300;0.5615;0.5195;0.4391;0.3621;0.2816;0.1977;0.1837;0.1172;0.0857;0.0577;0.0;0.0577;0.0857;0.1172;0.1837;0.1977;0.2816;0.3621;0.4391;0.5195;0.5615;0.5300;0.4146;0.2956;0.2117;0.1347];

re_Eq_data_32 = Eq_data_32;  % Equalizer data for real values
im_Eq_data_32 = -(re_Eq_data_32);

window_size = 32;

 for ii = 1:(length(Input_sig_16k)/window_size)-1

  data_range = (((ii-1)*window_size)+1:((ii-1)*window_size)+32);
  data_block = Input_sig_16k(data_range);

  fft_sig = fft(data_block);                 %FFT of the signal

  after_eq_re = real(fft_sig).*re_Eq_data_32';   % Multiply real portion of FFT with Equalizer
  after_eq_im = imag(fft_sig).*im_Eq_data_32';   % Mutliply imaginary portion with Equalizer

  after_eq = after_eq_re + (i*after_eq_im);

  ifft_sig = ifft(fft_sig);                  %iFFT of the signal

 data_full(data_range) = ifft_sig;            % Output signal

 end

plot(Input_sig_16k,'-og'), grid on;   % plot and compare both the signals
hold on;
plot(data_full,'-xr')
hold off;
</code>```

答:
Multiplication in the frequency domain is circular convolution in the time domain.  Circular convolution means that the end of your multiplication filtering process wraps around and corrupts the beginning of each FFT/IFFT buffer.

Instead, zero-pad each FFT by at least the length of the impulse response of your equalization filter.  Then use either overlap-add or overlap-save (fast convolution methods/algorithms) to re-combine your IFFT results.

Also, if you want a strictly real result (no non-zero imaginary numbers), make sure that the input to your IFFT is conjugate symmetric.

Title: MATLAB FFT -> Equalizer -> iFFT

Body:
I’m trying to implement a 32 point FFT - Equalizer - iFFT

On a step by step basis. I input a Time domain signal to a FFT block and then used iFFT to obtain the original data back.

Naturally after FFT, I get 32 points of symmetrical real and imaginary data.

I tried,

Step 1:

   fft_sig = fft(data_processing_block);                 %FFT of the signal

  ifft_sig = ifft(fft_sig);                            %iFFT of the signal

The output matches the input. Works like a charm.

Step 2:

  fft_sig = fft(data_processing_block);                 %FFT of the signal

  after_eq_re = real(fft_sig);
  after_eq_im = imag(fft_sig);

  after_eq = after_eq_re + (i*after_eq_im);

  ifft_sig = ifft(after_eq);                            %iFFT of the signal

This also works just fine.

Step 3:

  fft_sig = fft(data_processing_block);                 %FFT of the signal

  after_eq_re = real(fft_sig).*1.0;                     % Multiply Real data with a constant
  after_eq_im = imag(fft_sig).*1.0;                     % Multiply Imag data with a constant

  after_eq = after_eq_re + (i*after_eq_im);

  ifft_sig = ifft(after_eq);                            %iFFT of the signal

This also works fine.

Step 4:

I replaced the constant (1.0) with an Equalizer table. Of size 32.

Eq_data_32 =[0.0;0.1347;0.2117;0.2956;0.4146;0.5300;0.5615;0.5195;0.4391;0.3621;0.2816;0.1977;0.1837;0.1172;0.0857;0.0577;0.0;0.0577;0.0857;0.1172;0.1837;0.1977;0.2816;0.3621;0.4391;0.5195;0.5615;0.5300;0.4146;0.2956;0.2117;0.1347];

Eq_data_32(1) and Eq_data_32(17) are zeros.  Eq_data_32(2:16) is symmetrical to Eq_data_32(18:32).

 re_Eq_data_32 = Eq_data_32;  % Equalizer data for real values
 im_Eq_data_32 = -(re_Eq_data_32);  % Equalizer data for imaginary values

  fft_sig = fft(data_processing_block);                 %FFT of the signal

  after_eq_re = real(fft_sig).*re_Eq_data_32';
  after_eq_im = imag(fft_sig).*im_Eq_data_32';

  after_eq = after_eq_re + (i*after_eq_im);
  ifft_sig = ifft(after_eq);                             %iFFT of the signal

Now the output is distorted and does not sound good. I think this is due to symmetry of the Equalizer table. I can’t figure how to arrange the Equalizer table to preserve the symmetry. As far as I can tell, my real and imaginary Equalizer  table are symmetric. So why can’t I get a clear output ?

Complete code:

Fs = 16000;                       % sampling frequency
no_samples = 640;                  % no of samples
Freq1 = 1000;                      % Frequency 1 of the signal
Freq2 = 2500;                      % Frequency 2 of the signal
Freq3 = 3500;                      % Frequency 3 of the signal
Amp = 0.1;
t = 1/Fs*((1:no_samples)-1);      % time duration, t = 1/Fs
Input_sig_16k = Amp*sin(2*pi*Freq1*t)+Amp*sin(2*pi*Freq2*t)+Amp*sin(2*pi*Freq3*t);  % Multitone Input Signal

% Equlizer data
Eq_data_32 =[0.0;0.1347;0.2117;0.2956;0.4146;0.5300;0.5615;0.5195;0.4391;0.3621;0.2816;0.1977;0.1837;0.1172;0.0857;0.0577;0.0;0.0577;0.0857;0.1172;0.1837;0.1977;0.2816;0.3621;0.4391;0.5195;0.5615;0.5300;0.4146;0.2956;0.2117;0.1347];

re_Eq_data_32 = Eq_data_32;  % Equalizer data for real values
im_Eq_data_32 = -(re_Eq_data_32);

window_size = 32;

 for ii = 1:(length(Input_sig_16k)/window_size)-1

  data_range = (((ii-1)*window_size)+1:((ii-1)*window_size)+32);
  data_block = Input_sig_16k(data_range);

  fft_sig = fft(data_block);                 %FFT of the signal

  after_eq_re = real(fft_sig).*re_Eq_data_32';   % Multiply real portion of FFT with Equalizer
  after_eq_im = imag(fft_sig).*im_Eq_data_32';   % Mutliply imaginary portion with Equalizer

  after_eq = after_eq_re + (i*after_eq_im);

  ifft_sig = ifft(fft_sig);                  %iFFT of the signal

 data_full(data_range) = ifft_sig;            % Output signal

 end

plot(Input_sig_16k,'-og'), grid on;   % plot and compare both the signals
hold on;
plot(data_full,'-xr')
hold off;


问:
Aptana / Eclipse studio won't open
When I open Aptana Studio 3, I get a popup indicating an error has occurred - see the log file:
The log file says:

```<code>eclipse.buildId=unknown
java.version=1.8.0_71
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US
Command-line arguments:  -os win32 -ws win32 -arch x86

!ENTRY org.eclipse.ui.ide 4 4 2016-06-03 08:20:50.414
!MESSAGE Could not read version file

!ENTRY org.eclipse.ui.ide 4 4 2016-06-03 08:20:50.415
!MESSAGE An unexpected network error occurred
!STACK 0
java.io.IOException: An unexpected network error occurred
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(Unknown Source)
    at java.util.Properties$LineReader.readLine(Unknown Source)
    at java.util.Properties.load0(Unknown Source)
    at java.util.Properties.load(Unknown Source)
    at com.aptana.rcp.IDEApplication.readWorkspaceVersion(IDEApplication.java:419)
    at com.aptana.rcp.IDEApplication.checkValidWorkspace(IDEApplication.java:366)
    at com.aptana.rcp.IDEApplication.promptForWorkspace(IDEApplication.java:347)
    at com.aptana.rcp.IDEApplication.checkInstanceLocation(IDEApplication.java:254)
    at com.aptana.rcp.IDEApplication.start(IDEApplication.java:112)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:354)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:181)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:636)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:591)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1450)
</code>```

I appreciate your help since I cannot get Aptana to startup.

答:
Sorry, I had moved the default project folder and it couldn't find it. I was able to get it working by changing the following line in the configuration/config.ini file in the installation:

osgi.instance.area.default=@user.home/Aptana 3 Workspace

Title: Aptana / Eclipse studio won't open

Body:
When I open Aptana Studio 3, I get a popup indicating an error has occurred - see the log file:
The log file says:

eclipse.buildId=unknown
java.version=1.8.0_71
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US
Command-line arguments:  -os win32 -ws win32 -arch x86

!ENTRY org.eclipse.ui.ide 4 4 2016-06-03 08:20:50.414
!MESSAGE Could not read version file

!ENTRY org.eclipse.ui.ide 4 4 2016-06-03 08:20:50.415
!MESSAGE An unexpected network error occurred
!STACK 0
java.io.IOException: An unexpected network error occurred
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(Unknown Source)
    at java.util.Properties$LineReader.readLine(Unknown Source)
    at java.util.Properties.load0(Unknown Source)
    at java.util.Properties.load(Unknown Source)
    at com.aptana.rcp.IDEApplication.readWorkspaceVersion(IDEApplication.java:419)
    at com.aptana.rcp.IDEApplication.checkValidWorkspace(IDEApplication.java:366)
    at com.aptana.rcp.IDEApplication.promptForWorkspace(IDEApplication.java:347)
    at com.aptana.rcp.IDEApplication.checkInstanceLocation(IDEApplication.java:254)
    at com.aptana.rcp.IDEApplication.start(IDEApplication.java:112)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:354)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:181)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:636)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:591)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1450)

I appreciate your help since I cannot get Aptana to startup.


问:
Is it safe to use http inside service fabric cluster for service to service commiunication?
I created a secure service fabric and have full control. Only services developed by me will be deployed and all public facing apis are using https. The question is for communication between service to service in cluster, is it safe to use http instead of https?

Thanks,

答:
This is related to how do you set up your cluster with your network. Public facing services and internal services should be in a different NSG networks. You should control very strict communication between public and internal. If you can do that then http or any protocol between services is not a problem

Personally, i prefer http over remoting because there will be less dependency between services. Communication between services can be defined using Open API and therefore become vendor neutral.

There is a very good course on MVA for how to set up Service fabric class and best practice

https://mva.microsoft.com/en-US/training-courses/16925?l=E5B3nJSGD_805167344


答:
I think a PivotTable will do the work for you but since the 'automatic' choice of group size is restricted to days (I have no idea why) it would take a hack giving some results that would need careful interpretation, though changing the size of the grouping would be easy:

ColumnA has in B2 and copied down to suit:

```<code>=INT(B2)-42372+MOD(B2,1)*60*24
</code>```

The selected cell can be interpreted back into the start of the interval with a VLOOKUP as shown highlighted, but it would not be so simple for any ranges that start at a time for which there is no existing data point.

This takes the average of all available readings for each interval, not the first.

Title: How to convert FOREX Historical data from M1 to M2, M5 and M15 timeframes?

Body:
I have several years of FOREX historical data, but it's listed minute by minute. I would like to know how do I do to convert it to M2, M5 and M15. I tried lots of things and methods, but none worked.

Excel functions or SQL scripts are welcome.

Below is listed a little sample of data format.

Date        Time    Open    High    Low     Close
2016.01.03  17:00   1.08701 1.08713 1.08701 1.08713
2016.01.03  17:01   1.08712 1.08712 1.08712 1.08712
2016.01.03  17:02   1.08708 1.08722 1.08708 1.08722
2016.01.03  17:03   1.08717 1.08723 1.08717 1.08723
2016.01.03  17:04   1.08718 1.08718 1.08711 1.08711
2016.01.03  17:05   1.08703 1.08716 1.08701 1.08712
2016.01.03  17:06   1.08721 1.08721 1.0871  1.0871
2016.01.03  17:07   1.08712 1.08715 1.08712 1.08712
2016.01.03  17:08   1.08711 1.0872  1.08711 1.08713
2016.01.03  17:09   1.08716 1.08723 1.08708 1.08708

Body:
I think a PivotTable will do the work for you but since the 'automatic' choice of group size is restricted to days (I have no idea why) it would take a hack giving some results that would need careful interpretation, though changing the size of the grouping would be easy:

ColumnA has in B2 and copied down to suit:

=INT(B2)-42372+MOD(B2,1)*60*24

The selected cell can be interpreted back into the start of the interval with a VLOOKUP as shown highlighted, but it would not be so simple for any ranges that start at a time for which there is no existing data point.

This takes the average of all available readings for each interval, not the first.