问:
CSS3 3D Animation Disapearing in Safari
I've built a simple navigation component for my website, which has left and right swinging 'doors.' These work great in all browsers except for Safari, where the 'door' seems to disappear entirely behind its background when your mouse moves from one door to another. Mousing over one door at a time works fine, as long as you wait for the animation to stop before touching the blue door.

Also, one page of my site has a fixed background video, and on that page the animations do not work at all, the entire div disappears as soon as you hover over it.

I've been working on this issue for quite a while and cannot think of a possible reason for this weird behavior. If I implement the animation without putting it in a bootstrap grid, it works, but once the background video is involved it causes the same problem seen in this codepen.

Thanks in advance for any ideas why this is happening!

HTML:

```<code><head>
  <link href="css/bootstrap.css" rel="stylesheet"/>
</head>

<body>
<div class="container-fluid">
  <div class="row">
    <div class="col-xs-6 greenbackground">
      <a href="#">
        <div class="greenlink doorleft">
          <h1>Left Swing Link</h1>
        </div>
      </a>
    </div>
    <div class="col-xs-6 bluebackground">
      <a href="#">
        <div class="bluelink doorright">
          <h1>Right Swing Link</h1>
        </div>
      </a>
    </div>
  </div>
</div>
<body>
</code>```

CSS:

```<code>.greenlink{
  width: calc(100% + 30px);
  padding-top:5em;
  padding-bottom:5em;
  text-align:center;
  background-color: lightgreen;
  margin-left:-15px;
}

.greenbackground{
  background-color: green;
}

.bluelink{
  width: calc(100% + 30px);
  padding-top:5em;
  padding-bottom:5em;
  text-align:center;
  background-color:lightblue;
  margin-left:-15px;
}

.bluebackground{
  background-color:blue;
}

.doorleft{
  transition: all 500ms ease;
  transform: perspective(900px) rotateY(0deg);
  transform-origin: 0% 0%;
  -webkit-transform-style: preserve-3d;
}

.doorleft:hover {
   transform: perspective(1000px) rotateY(30deg);
}

.doorright {
  transition: all 500ms ease;
  transform: perspective(900px) rotateY(0deg);
  transform-origin: 100% 0%;
  -webkit-transform-style: preserve-3d;
}

.doorright:hover {
  transform: perspective(1000px) rotateY(-30deg);
}
</code>```

Here's the link to a codepen: https://codepen.io/anon/pen/RgBdJp

答: I have no idea why, but giving .col-xs-6 position: static solves it (bootstrap gives it position: relative). In this case it doesn't affect anything else so should be ok. Clearly it's a Safari issue.

Title: CSS3 3D Animation Disapearing in Safari

Body:
I've built a simple navigation component for my website, which has left and right swinging 'doors.' These work great in all browsers except for Safari, where the 'door' seems to disappear entirely behind its background when your mouse moves from one door to another. Mousing over one door at a time works fine, as long as you wait for the animation to stop before touching the blue door.

Also, one page of my site has a fixed background video, and on that page the animations do not work at all, the entire div disappears as soon as you hover over it.

I've been working on this issue for quite a while and cannot think of a possible reason for this weird behavior. If I implement the animation without putting it in a bootstrap grid, it works, but once the background video is involved it causes the same problem seen in this codepen.

Thanks in advance for any ideas why this is happening!

HTML:

  <link href="css/bootstrap.css" rel="stylesheet"/>

Left Swing Link

Right Swing Link

CSS:

.greenlink{
  width: calc(100% + 30px);
  padding-top:5em;
  padding-bottom:5em;
  text-align:center;
  background-color: lightgreen;
  margin-left:-15px;
}

.greenbackground{
  background-color: green;
}

.bluelink{
  width: calc(100% + 30px);
  padding-top:5em;
  padding-bottom:5em;
  text-align:center;
  background-color:lightblue;
  margin-left:-15px;
}

.bluebackground{
  background-color:blue;
}

.doorleft{
  transition: all 500ms ease;
  transform: perspective(900px) rotateY(0deg);
  transform-origin: 0% 0%;
  -webkit-transform-style: preserve-3d;
}

.doorleft:hover {
   transform: perspective(1000px) rotateY(30deg);
}

.doorright {
  transition: all 500ms ease;
  transform: perspective(900px) rotateY(0deg);
  transform-origin: 100% 0%;
  -webkit-transform-style: preserve-3d;
}

.doorright:hover {
  transform: perspective(1000px) rotateY(-30deg);
}

Here's the link to a codepen: https://codepen.io/anon/pen/RgBdJp


来源: stackexchange

问:
How do I pass values to a vertex shader's attribute array in OpenGL?
In my vertex shader, I have

```<code>in float data[6];
</code>```

That means that if I have 100 vertices, I want to pass 600 floats.  glVertexAttribPointer only supports sizes up to 4.  If I use size 1, then will it automatically pick up the 6 elements?

答:
An attribute array in glsl is treated as a number of independent attributes with consecutive attribute locations. You'll have to setup the vertex attribute pointer for each them separately.

If you query the location of the first element with idx = glGetAttribLocation(program_index, "data"), then data[1] will have location idx + 1. You can then loop over them and call glVertexAttribPointer* with the index and the correct byte offset for each of the array elements.

ContentLicense: CC BY-SA 3.0

Body:
In my vertex shader, I have

in float data[6];

That means that if I have 100 vertices, I want to pass 600 floats.  glVertexAttribPointer only supports sizes up to 4.  If I use size 1, then will it automatically pick up the 6 elements?


问:
Referencing a dll project with separated binary folder in Visual Studio
I have a Visual Studio 2013 c++ solution that has two projects:

one that generates a dll,

and another that tests this dll.

For each project I modified the output and the intermediate directory.

Solution:

Project DLL:

/bin

/build

/src

Project Test:

/bin

/build

/src

Is there any way in which I can reference the generated dll in the test project  without being copied? Something like a static library, which in the case of Visual Studio is just add as a reference that is already linked.

The part that the Visual Studio gets lost is when I changed the binary output folders. With the default option (a folder that generates the binary for all projects) there is no problem.

答: Edit your test project properties, on Linker>General tab you will find Additional Library Directories setting - add your library directory there. Then you can add your library to Linker>Input>Additional Dependencies.</p>


问:
how do i make a loop to display the next 3 even number?
hello all i'm trying to make javascript to display an evens numbers by using a form with start number and number of evens to display. user will enter starting number and enter the number of even to display.
say start at 7 number of evens is 3 should display 8 10 12.  just need some direction. thanks

my code:

```<code><html>
<head>
<title>evens</title>
<div class="container">
           <h1>Enter Number</h1>
           <form name="number" class="form-inline">
           <div class="form-group">
            <label for="starting">Starting Number</label>
            <input type="text" id="starting" class="form-control">
           </div> <div class="form-group">
               <label for="step">numbers of evens</label>
               <input type="text" id="step" class="form-control">
           </div>
</code>```

```<code>           <button type="button" onclick="evenDisplay()" class="btn" >submit</button>

<script>

function evenDisplay() {

    var starting = document.getElementById("starting").value;
    var step = document.getElementById("step").value;
    var evens = [];

    for (i = starting;  i <=12; i++) { /* this loop would show as much as evens number as long value of i<= set to  and doesn't care if the user enter the number of evens */
        i % 2 || evens.push(i);
    }
   console.log(evens)

}
   </body>
 </html>
</code>```

答:
```<code>for (i = starting;  step==evens.length ;i++) {
    i % 2 || evens.push(i);
}
</code>```

Body:
hello all i'm trying to make javascript to display an evens numbers by using a form with start number and number of evens to display. user will enter starting number and enter the number of even to display.
say start at 7 number of evens is 3 should display 8 10 12.  just need some direction. thanks

my code:

<title>evens</title>

Enter Number

           <form name="number" class="form-inline">

            Starting Number
            <input type="text" id="starting" class="form-control">

               numbers of evens
               <input type="text" id="step" class="form-control">

           <button type="button" onclick="evenDisplay()" class="btn" >submit</button>


问:
Python Histogram of Oriented Gradients
I am trying to implement this version of Histogram of Oriented Gradients(HOG). My code is below. The only difference in my code is that I've used opencv to read the image and convert it to grayscale.

```<code>import cv2
import matplotlib.pyplot as plt
from skimage.feature import hog
from skimage import data, color, exposure

filename = 'match1/hockey15.jpg'
im = cv2.imread(filename)
gr = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

print im.shape
image = gr

fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16),
                    cells_per_block=(1, 1), visualise=True)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharex=True, sharey=True)

ax1.axis('off')
ax1.imshow(image, cmap=plt.cm.gray)
ax1.set_title('Input image')
ax1.set_adjustable('box-forced')

# Rescale histogram for better display
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))

ax2.axis('off')
ax2.imshow(hog_image_rescaled, cmap=plt.cm.gray)
ax2.set_title('Histogram of Oriented Gradients')
ax1.set_adjustable('box-forced')
plt.show()
</code>```

A sample input and output are:

Input:

Output:

Why is the output so cluttered? I have even tried the image with the astronaut in the skimage link above. For this too, I get a lot of clutter and the output is not at all like what is shown in the link. How can I fix this?

答:
I could reproduce your error with your code and got the same cluttered image. I modified your code a bit, specifically changing the axis and i got the following output.

Here's the modified code.

```<code>import cv2
import matplotlib.pyplot as plt
from skimage.feature import hog
from skimage import data, color, exposure

filename = r"pathtoimage\hockey.jpg"

im = cv2.imread(filename)

gr = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

print im.shape
image = gr

fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16),
                    cells_per_block=(1, 1), visualise=True)

fig, ax = plt.subplots(1, 2, figsize=(20, 10), sharex=True, sharey=True)

ax[0].axis('off')
ax[0].imshow(image, cmap=plt.cm.gray)
ax[0].set_title('Input image')
ax[0].set_adjustable('box-forced')

# Rescale histogram for better display
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))

ax[1].axis('off')
ax[1].imshow(hog_image, cmap=plt.cm.gray)
ax[1].set_title('Histogram of Oriented Gradients')
ax[1].set_adjustable('box-forced')

plt.show()
</code>```

Title: Python Histogram of Oriented Gradients

Body:
I am trying to implement this version of Histogram of Oriented Gradients(HOG). My code is below. The only difference in my code is that I've used opencv to read the image and convert it to grayscale.

import cv2
import matplotlib.pyplot as plt
from skimage.feature import hog
from skimage import data, color, exposure

filename = 'match1/hockey15.jpg'
im = cv2.imread(filename)
gr = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

print im.shape
image = gr

fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16),
                    cells_per_block=(1, 1), visualise=True)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharex=True, sharey=True)

ax1.axis('off')
ax1.imshow(image, cmap=plt.cm.gray)
ax1.set_title('Input image')
ax1.set_adjustable('box-forced')

# Rescale histogram for better display
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))

ax2.axis('off')
ax2.imshow(hog_image_rescaled, cmap=plt.cm.gray)
ax2.set_title('Histogram of Oriented Gradients')
ax1.set_adjustable('box-forced')
plt.show()

A sample input and output are:

Input:

Output:

Why is the output so cluttered? I have even tried the image with the astronaut in the skimage link above. For this too, I get a lot of clutter and the output is not at all like what is shown in the link. How can I fix this?

Body:
I could reproduce your error with your code and got the same cluttered image. I modified your code a bit, specifically changing the axis and i got the following output.

Here's the modified code.

import cv2
import matplotlib.pyplot as plt
from skimage.feature import hog
from skimage import data, color, exposure

filename = r"pathtoimage\hockey.jpg"

im = cv2.imread(filename)

gr = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

print im.shape
image = gr

fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16),
                    cells_per_block=(1, 1), visualise=True)

fig, ax = plt.subplots(1, 2, figsize=(20, 10), sharex=True, sharey=True)

ax[0].axis('off')
ax[0].imshow(image, cmap=plt.cm.gray)
ax[0].set_title('Input image')
ax[0].set_adjustable('box-forced')

# Rescale histogram for better display
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))

ax[1].axis('off')
ax[1].imshow(hog_image, cmap=plt.cm.gray)
ax[1].set_title('Histogram of Oriented Gradients')
ax[1].set_adjustable('box-forced')

plt.show()


问:
How to show mouse coordinates over canvas using pure javascript in tooltip form?
So its about html5 canvas. So I want to see something like x:11, y:33 in form of tooltip near to mouse when mouse is on canvas like ... mouse moves tooltip moves with it showing coordinates. How to do such thing with javascript and html 5?

答:
$(function() {
  var canvas = $('#canvas').get(0);
  var ctx = canvas.getContext('2d');
  var w = h = canvas.width = canvas.height = 300;

  ctx.fillStyle = '#0099f9';
  ctx.fillRect(0, 0, w, h);

  canvas.addEventListener('mousemove', function(e) {
    var x = e.pageX - canvas.offsetLeft;
    var y = e.pageY - canvas.offsetTop;
    var str = 'X : ' + x + ', ' + 'Y : ' + y;

    ctx.fillStyle = '#0099f9';
    ctx.fillRect(0, 0, w, h);
    ctx.fillStyle = '#ddd';
    ctx.fillRect(x + 10, y + 10, 80, 25);
    ctx.fillStyle = '#000';
    ctx.font = 'bold 20px verdana';
    ctx.fillText(str, x + 20, y + 30, 60);

  }, 0);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas"></canvas></code>```

A simple Demo

ContentLicense: CC BY-SA 2.5

Body:
$(function() {
  var canvas = $('#canvas').get(0);
  var ctx = canvas.getContext('2d');
  var w = h = canvas.width = canvas.height = 300;

  ctx.fillStyle = '#0099f9';
  ctx.fillRect(0, 0, w, h);

  canvas.addEventListener('mousemove', function(e) {
    var x = e.pageX - canvas.offsetLeft;
    var y = e.pageY - canvas.offsetTop;
    var str = 'X : ' + x + ', ' + 'Y : ' + y;

    ctx.fillStyle = '#0099f9';
    ctx.fillRect(0, 0, w, h);
    ctx.fillStyle = '#ddd';
    ctx.fillRect(x + 10, y + 10, 80, 25);
    ctx.fillStyle = '#000';
    ctx.font = 'bold 20px verdana';
    ctx.fillText(str, x + 20, y + 30, 60);

  }, 0);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas"></canvas>

A simple Demo


问:
How to check if Javascript Map has an object key
Looking at a couple of different docs, all I see is when the Map (ECMAScript6) key is a boolean, string, or integer. Is there a way we could use another customized Object (called with the new CustomObject(x,y) constructor call) to be added as a key?

I am able to add an object as a key, but unable to check if the Map has the said object.

```<code>var myMap = new Map();
myMap.set( new Tuple(1,1), "foo");
myMap.set('bar', "foo");

myMap.has(?);
myMap.has('bar');  // returns true
</code>```

Is there a way around this?

```<code>  var myMap = new Map();
  myMap.set( new Tuple(1,1), "foo");

 for(some conditions) {
 var localData = new Tuple(1,1); //Use directly if exists in myMap?
 map.has(localData) // returns false as this is a different Tuple object. But I need it to return true
}
</code>```

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has

答:
You just have to save the reference to the object:

```<code>var myMap = new Map();
var myKey = new Tuple(1,1);
myMap.set( myKey, "foo");
myMap.set('bar', "foo");

myMap.has(myKey);           // returns true;  myKey === myKey
myMap.has(new Tuple(1,1));  // returns false; new Tuple(1,1) !== myKey
myMap.has('bar');           // returns true;  'bar' === 'bar'
</code>```

Edit: Here is how to use an object to achieve what you want, which is to compare objects by their values rather than by reference:

```<code>function Tuple (x, y) {
  this.x = x;
  this.y = y;
}
Tuple.prototype.toString = function () {
  return 'Tuple [' + this.x + ',' + this.y + ']';
};

var myObject = {};
myObject[new Tuple(1, 1)] = 'foo';
myObject[new Tuple(1, 2)] = 'bar';
console.log(myObject[new Tuple(1, 1)]); // 'foo'
console.log(myObject[new Tuple(1, 2)]); // 'bar'
</code>```

These operations will run in constant time on average, which is much faster than searching through a Map for a similar object key in linear time.

Body:
Looking at a couple of different docs, all I see is when the Map (ECMAScript6) key is a boolean, string, or integer. Is there a way we could use another customized Object (called with the new CustomObject(x,y) constructor call) to be added as a key?

I am able to add an object as a key, but unable to check if the Map has the said object.

var myMap = new Map();
myMap.set( new Tuple(1,1), "foo");
myMap.set('bar', "foo");

myMap.has(?);
myMap.has('bar');  // returns true

Is there a way around this?

  var myMap = new Map();
  myMap.set( new Tuple(1,1), "foo");

 for(some conditions) {
 var localData = new Tuple(1,1); //Use directly if exists in myMap?
 map.has(localData) // returns false as this is a different Tuple object. But I need it to return true
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has

Body:
You just have to save the reference to the object:

var myMap = new Map();
var myKey = new Tuple(1,1);
myMap.set( myKey, "foo");
myMap.set('bar', "foo");

myMap.has(myKey);           // returns true;  myKey === myKey
myMap.has(new Tuple(1,1));  // returns false; new Tuple(1,1) !== myKey
myMap.has('bar');           // returns true;  'bar' === 'bar'

Edit: Here is how to use an object to achieve what you want, which is to compare objects by their values rather than by reference:

function Tuple (x, y) {
  this.x = x;
  this.y = y;
}
Tuple.prototype.toString = function () {
  return 'Tuple [' + this.x + ',' + this.y + ']';
};

var myObject = {};
myObject[new Tuple(1, 1)] = 'foo';
myObject[new Tuple(1, 2)] = 'bar';
console.log(myObject[new Tuple(1, 1)]); // 'foo'
console.log(myObject[new Tuple(1, 2)]); // 'bar'

These operations will run in constant time on average, which is much faster than searching through a Map for a similar object key in linear time.


问:
Expanding use of Javascript array.reduce helper method
Background

I am following a course on Udemy which goes over all of the ES6 features. In one of the lessons the instructor talks about using the reduce helper method to solve the popular balance parenthesis interview question.

I can solve this without the reduce method. Although with the reduce method it does get the job done in less code. I have been asked to find the depth of the parenthesis in an interview before and was wondering if this could all be done in the same method using reduce.

I do not know why this addition to the question confuses me so much but I would like to learn.

Problem

I have been trying to figure it out for a while and it might be my lack of understanding how reduce works.

Example

This uses reduce to return true of false regarding if the parenthesis or open and closed evenly.

```<code>function balanceParens(string) {
    return !string.split("").reduce((counter, char) => {
        // Handle if parens open and close out of order
        if (counter < 0) { return counter; }
        // Add 1 for each open in order
        if (char === "(") { return ++counter; }
        // subtract 1 for each close in order
        if (char === ")") { return --counter; }
        // handle use case if char is not a paren
        return counter;
    }, 0);
}
console.log(balanceParens("((()))"));
</code>```

Question

How would I return the max depth of the parenthesis using the reduce helper method.

答:
Here is a compact version that returns NaN when the parentheses are not balanced. It uses nested functions in a functional style:

function maxDepth(string) {
    return ( ([depth, max]) => depth ? NaN : max )
        ([...string].reduce(([depth, max], ch) =>
            (newDepth => [newDepth, newDepth < 0 ? NaN : Math.max(max, newDepth)])
                 (depth + (ch === "(") - (ch === ")"))
        , [0, 0]));
}
console.log(maxDepth("(((()))(((())))()(((((()))))))"));```

Body:
Background

I am following a course on Udemy which goes over all of the ES6 features. In one of the lessons the instructor talks about using the reduce helper method to solve the popular balance parenthesis interview question.

I can solve this without the reduce method. Although with the reduce method it does get the job done in less code. I have been asked to find the depth of the parenthesis in an interview before and was wondering if this could all be done in the same method using reduce.

I do not know why this addition to the question confuses me so much but I would like to learn.

Problem

I have been trying to figure it out for a while and it might be my lack of understanding how reduce works.

Example

This uses reduce to return true of false regarding if the parenthesis or open and closed evenly.

function balanceParens(string) {
    return !string.split("").reduce((counter, char) => {
        // Handle if parens open and close out of order
        if (counter < 0) { return counter; }
        // Add 1 for each open in order
        if (char === "(") { return ++counter; }
        // subtract 1 for each close in order
        if (char === ")") { return --counter; }
        // handle use case if char is not a paren
        return counter;
    }, 0);
}
console.log(balanceParens("((()))"));

Question

How would I return the max depth of the parenthesis using the reduce helper method.


问:
Convert time in seconds from the Epoch to day of the year?
I have a file filled with data, one column of which is seconds from the Epoch. For reference, an example value looks like this:

1498493536984926976

I need to convert it into a day of the year. What I have so far is this piece of code, which uses this reference to convert the date into a normal readable struct and then strftime to pull the day of the year from the struct:

```<code>time_t rawtime = stol(exploded_line[2]);
std::cout << rawtime << std::endl;
struct tm date;
date = *localtime( &rawtime );
char *buffer;
std::cout << 2 << std::endl;
strftime (buffer,sizeof(buffer),"%j",&date);
</code>```

However, this code SegFaults on the strftime line! I have no idea what is causing this. I have tried initializing buffer as

```<code>char buffer[80];
</code>```

and various other declarations but nothing seems to work. I've also tried ditching the buffer entirely and just using a std::string; that hasn't worked either.

Also, I am not partial to this method. If anyone else has a better method of getting the day of the year from an Epoch time, I will totally implement it.

Any help would be appreciated!

答:
Based on the fact they're supposed to be epoch times, your timestamps are in nanoseconds.

1498493536984926976s = 4.749E10 years.

1498493536984926976ns = 47.49 years.

Unless your time stamps really are 34 billion years into the future, you should convert them to seconds before sending them to localtime to get a struct tm.

Body:
I have a file filled with data, one column of which is seconds from the Epoch. For reference, an example value looks like this:

1498493536984926976

I need to convert it into a day of the year. What I have so far is this piece of code, which uses this reference to convert the date into a normal readable struct and then strftime to pull the day of the year from the struct:

time_t rawtime = stol(exploded_line[2]);
std::cout << rawtime << std::endl;
struct tm date;
date = *localtime( &rawtime );
char *buffer;
std::cout << 2 << std::endl;
strftime (buffer,sizeof(buffer),"%j",&date);

However, this code SegFaults on the strftime line! I have no idea what is causing this. I have tried initializing buffer as

char buffer[80];

and various other declarations but nothing seems to work. I've also tried ditching the buffer entirely and just using a std::string; that hasn't worked either.

Also, I am not partial to this method. If anyone else has a better method of getting the day of the year from an Epoch time, I will totally implement it.

Any help would be appreciated!


问:
Simple way to convert Python docstrings from reStructured Text to Google style?
Does anyone now a simple way do convert all docstrings in an existing project from reStructured Text to the Google format?

It looks like Napoleon can do something like that, but it looks very complicated, so I figured I'd ask if someone has done that before. Any idea would be much appreciated.

答:
Try using pyment to convert docstrings from reStructuredText to Google format. Then use Napolean to generate documentation via Sphinx.

Napoleon is a pre-processor that parses NumPy and Google style docstrings and converts them to reStructuredText before Sphinx attempts to parse them.


问:
Finding names with a specific letter on parser server
I am currently working on Android platform using parse server. I am making a function in which if i enter a character key it shows all the entries which are having that letter in it.
For example - i will be getting all the names starting or having character "p" in them.

I would really appreciate if u can suggest, find or give me some examples of them.

答:
You should use the documentation as your first resource. Parse is pretty well documented, and the ParseQuery class has a function specifically for this.

http://parseplatform.org/Parse-SDK-Android/api/com/parse/ParseQuery.html#whereContains(java.lang.String,%20java.lang.String)


问:
bash - find duplicate file in directory and rename
I have a directory that has thousands of files in it with various extensions.  I also have a drop location where users drop files to be migrated to this directory.  I'm looking for a script that will scan the target directory for a duplicate file name, if found, rename the file in the drop folder, then move it to the target directory.
Example:

/target/file.doc
/drop/file.doc

Script will rename file.doc to file1.doc then move it to /target/.
It needs to maintain the file extension too.

答:
This will test to see if it exists, preserve the extension (along with any structure before the extension such as in the case of FILE.tar.gz), and move it to the target directory.

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

TARGET="\target\"
DROP="\drop\"

for F in `ls $DROP`; do
    if [[ -f $TARGET$F ]]; then
        EXT=`echo $F | awk -F "." '{print $NF}'`
        PRE=`echo $F | awk -F "." '{$NF="";print $0}' | sed -e 's/ $//g;s/ /./g'`
        mv $DROP$F $DROP$PRE"1".$EXT
        F=$PRE"1".$EXT
    fi
    mv $DROP$F $TARGET
done
</code>```

Additionally you may want to do come restricting in the ls command, so that you aren't copying entire directories.

Display only regular files (no directories or symbolic links)

```<code>ls -p $DROP | grep -v /
</code>```

Body:
This will test to see if it exists, preserve the extension (along with any structure before the extension such as in the case of FILE.tar.gz), and move it to the target directory.

#!/bin/bash

TARGET="\target\"
DROP="\drop\"

for F in `ls $DROP`; do
    if [[ -f $TARGET$F ]]; then
        EXT=`echo $F | awk -F "." '{print $NF}'`
        PRE=`echo $F | awk -F "." '{$NF="";print $0}' | sed -e 's/ $//g;s/ /./g'`
        mv $DROP$F $DROP$PRE"1".$EXT
        F=$PRE"1".$EXT
    fi
    mv $DROP$F $TARGET
done

Additionally you may want to do come restricting in the ls command, so that you aren't copying entire directories.

Display only regular files (no directories or symbolic links)

ls -p $DROP | grep -v /


问:
How to parse AuthoritiyInformation from X509Certificate object
I want to retrieve the OCSP information from a given X509Certificate object. Since I don't know how to parse this information I am asking this question here.

Here is what I got so far:

```<code>X509Certificate x509cert = ... //The Certificate
ASN1Primitive obj = ASN1Primitive.fromByteArray(x509cert
                            .getExtensionValue(Extension.authorityInfoAccess
                                    .getId()));
AuthorityInformationAccess aia = AuthorityInformationAccess.getInstance(obj);
</code>```

an exception is thrown:

```<code>java.security.cert.CertificateParsingException: java.lang.IllegalArgumentException: unknown object in getInstance: org.bouncycastle.asn1.DEROctetString
</code>```

How do I parse a ASN1Primitive into a valid DEROctetString to progress?

The value of the ASN1Primitive in the example is:

```<code>3032303006082b060105050730018624687474703a2f2f6f6373702e616368656c6f732e64653a383038302f6f6373702f65676b
</code>```

and seems to me to be a valid value.

答:
In Bouncy Castle 1.57, there's no need to create the intermediary ASN1Primitive. You can get the extension just by using the org.bouncycastle.asn1.x509.Extension and org.bouncycastle.x509.extension.X509ExtensionUtil classes:

```<code>X509Certificate cert = // the certificate

// get Authority Information Access extension
byte[] extVal = cert.getExtensionValue(Extension.authorityInfoAccess.getId());
AuthorityInformationAccess aia = AuthorityInformationAccess.getInstance(X509ExtensionUtil.fromExtensionValue(extVal));
</code>```

Then you can use the aia object:

```<code>AccessDescription[] descriptions = aia.getAccessDescriptions();
for (AccessDescription ad : descriptions) {
    // ...
}
</code>```

You can do it in previous versions as well, but for version <= 1.47 I believe that Extension class doesn't exist and you should use org.bouncycastle.asn1.x509.X509Extension instead (I think that org.bouncycastle.x509.extension.X509ExtensionUtil is the same).

Body:
I want to retrieve the OCSP information from a given X509Certificate object. Since I don't know how to parse this information I am asking this question here.

Here is what I got so far:

X509Certificate x509cert = ... //The Certificate
ASN1Primitive obj = ASN1Primitive.fromByteArray(x509cert
                            .getExtensionValue(Extension.authorityInfoAccess
                                    .getId()));
AuthorityInformationAccess aia = AuthorityInformationAccess.getInstance(obj);

an exception is thrown:

java.security.cert.CertificateParsingException: java.lang.IllegalArgumentException: unknown object in getInstance: org.bouncycastle.asn1.DEROctetString

How do I parse a ASN1Primitive into a valid DEROctetString to progress?

The value of the ASN1Primitive in the example is:

3032303006082b060105050730018624687474703a2f2f6f6373702e616368656c6f732e64653a383038302f6f6373702f65676b

and seems to me to be a valid value.

Body:
In Bouncy Castle 1.57, there's no need to create the intermediary ASN1Primitive. You can get the extension just by using the org.bouncycastle.asn1.x509.Extension and org.bouncycastle.x509.extension.X509ExtensionUtil classes:

X509Certificate cert = // the certificate

// get Authority Information Access extension
byte[] extVal = cert.getExtensionValue(Extension.authorityInfoAccess.getId());
AuthorityInformationAccess aia = AuthorityInformationAccess.getInstance(X509ExtensionUtil.fromExtensionValue(extVal));

Then you can use the aia object:

AccessDescription[] descriptions = aia.getAccessDescriptions();
for (AccessDescription ad : descriptions) {
    // ...
}

You can do it in previous versions as well, but for version <= 1.47 I believe that Extension class doesn't exist and you should use org.bouncycastle.asn1.x509.X509Extension instead (I think that org.bouncycastle.x509.extension.X509ExtensionUtil is the same).


问:
Remove Object from Array using JavaScript
How can I remove an object from an array?
I wish to remove the object that includes name Kristian from someArray. For example:

```<code>someArray = [{name:"Kristian", lines:"2,5,10"},
             {name:"John", lines:"1,19,26,96"}];
</code>```

I want to achieve:

```<code>someArray = [{name:"John", lines:"1,19,26,96"}];
</code>```

答:
You could also use some:

```<code>someArray = [{name:"Kristian", lines:"2,5,10"},
             {name:"John", lines:"1,19,26,96"}];

someArray.some(item => {
    if(item.name === "Kristian") // Case sensitive, will only remove first instance
        someArray.splice(someArray.indexOf(item),1)
})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I remove an object from an array?
I wish to remove the object that includes name Kristian from someArray. For example:

someArray = [{name:"Kristian", lines:"2,5,10"},
             {name:"John", lines:"1,19,26,96"}];

I want to achieve:

someArray = [{name:"John", lines:"1,19,26,96"}];

Body:
You could also use some:

someArray = [{name:"Kristian", lines:"2,5,10"},
             {name:"John", lines:"1,19,26,96"}];

someArray.some(item => {
    if(item.name === "Kristian") // Case sensitive, will only remove first instance
        someArray.splice(someArray.indexOf(item),1)
})


问:
How To Add A Blacklist to Location
I am working on something to blacklist unwanted locations with the location service. Here is my current code:

How can I implement a blacklist feature?

      if (navigator.geolocation) {
 // Locate position
 navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
 alert('Your device location is not approved.');
}

// Success callback function
function displayPosition(pos) {
 var mylat = pos.coords.latitude;
 var mylong = pos.coords.longitude;
 var thediv = document.getElementById('locationinfo');
  alert('Your HWID is compliant of ProtoProt regulations.');
}
  function errorFunction(pos) {
 alert('Error: (PROTOPROT_POS_DENIED). We only use your HWID for checking compliance. Enable location to enter.');
 }```

答:
Maintain a list of locations given by two points w,y.

Each w,y represent the two opposite points of a w,x,y,z square which represents the blacklisted location.

Each point has longitude and latitude coordinates, so w = [long, lat] and y = [long, lat]

With those, you can rebuild all the [long, lat] of all the w,x,y,z corners of your square, thus representing the blacklisted area.

Now, it's rather easy to know the boundaries of forbidden location: any point [long, lat] which is within the square is blacklisted.

You can store those values within a Javascript Object (a dictionary) which can be stored in a distinct ".js" file. JSON representation could look like:

```<code>blacklisted_areas = {
  'area 51' : [w, y], // Replace w y with the floats of long and lat
  'pink unicorn zoo' : [w, y], // same
  // etc.
};
</code>```

Access:

```<code>long = blacklisted_area['area 51'][0]
</code>```

Title: How To Add A Blacklist to Location

Body:
Maintain a list of locations given by two points w,y.

Each w,y represent the two opposite points of a w,x,y,z square which represents the blacklisted location.

Each point has longitude and latitude coordinates, so w = [long, lat] and y = [long, lat]

With those, you can rebuild all the [long, lat] of all the w,x,y,z corners of your square, thus representing the blacklisted area.

Now, it's rather easy to know the boundaries of forbidden location: any point [long, lat] which is within the square is blacklisted.

You can store those values within a Javascript Object (a dictionary) which can be stored in a distinct ".js" file. JSON representation could look like:

blacklisted_areas = {
  'area 51' : [w, y], // Replace w y with the floats of long and lat
  'pink unicorn zoo' : [w, y], // same
  // etc.
};

Access:

long = blacklisted_area['area 51'][0]


问:
How to get intersection of two slice in golang?
Is there any efficient way to get intersection of two slices in Go?</p>

I want to avoid nested for loop like solution

```<code>slice1 := []string{"foo", "bar","hello"}
slice2 := []string{"foo", "bar"}

intersection(slice1, slice2)
=> ["foo", "bar"]
</code>```

order of string does not matter

答:
Yes there are a few different ways to go about it.. Here's an example that can be optimized.

```<code>package main

import "fmt"

func intersection(a []string, b []string) (inter []string) {
    // interacting on the smallest list first can potentailly be faster...but not by much, worse case is the same
    low, high := a, b
    if len(a) > len(b) {
        low = b
        high = a
    }

    done := false
    for i, l := range low {
        for j, h := range high {
            // get future index values
            f1 := i + 1
            f2 := j + 1
            if l == h {
                inter = append(inter, h)
                if f1 < len(low) && f2 < len(high) {
                    // if the future values aren't the same then that's the end of the intersection
                    if low[f1] != high[f2] {
                        done = true
                    }
                }
                // we don't want to interate on the entire list everytime, so remove the parts we already looped on will make it faster each pass
                high = high[:j+copy(high[j:], high[j+1:])]
                break
            }
        }
        // nothing in the future so we are done
        if done {
            break
        }
    }
    return
}

func main() {
    slice1 := []string{"foo", "bar", "hello", "bar"}
    slice2 := []string{"foo", "bar"}
    fmt.Printf("%+v\n", intersection(slice1, slice2))
}
</code>```

Now the intersection method defined above will only operate on slices of strings, like your example.. You can in theory create a definition that looks like this func intersection(a []interface, b []interface) (inter []interface), however you would be relying on reflection and type casting so that you can compare, which will add latency and make your code harder to read. It's probably easier to maintain and read to write a separate function for each type you care about.

func intersectionString(a []string, b []string) (inter []string),

func intersectionInt(a []int, b []int) (inter []int),

func intersectionFloat64(a []Float64, b []Float64) (inter []Float64), ..ect

You can then create your own package and reuse once you settle how you want to implement it.

```<code>package intersection

func String(a []string, b []string) (inter []string)

func Int(a []int, b []int) (inter []int)

func Float64(a []Float64, b []Float64) (inter []Float64)
</code>```

Body:
Is there any efficient way to get intersection of two slices in Go?

I want to avoid nested for loop like solution

slice1 := []string{"foo", "bar","hello"}
slice2 := []string{"foo", "bar"}

intersection(slice1, slice2)
=> ["foo", "bar"]

order of string does not matter

Body:
Yes there are a few different ways to go about it.. Here's an example that can be optimized.

package main

import "fmt"

func intersection(a []string, b []string) (inter []string) {
    // interacting on the smallest list first can potentailly be faster...but not by much, worse case is the same
    low, high := a, b
    if len(a) > len(b) {
        low = b
        high = a
    }

    done := false
    for i, l := range low {
        for j, h := range high {
            // get future index values
            f1 := i + 1
            f2 := j + 1
            if l == h {
                inter = append(inter, h)
                if f1 < len(low) && f2 < len(high) {
                    // if the future values aren't the same then that's the end of the intersection
                    if low[f1] != high[f2] {
                        done = true
                    }
                }
                // we don't want to interate on the entire list everytime, so remove the parts we already looped on will make it faster each pass
                high = high[:j+copy(high[j:], high[j+1:])]
                break
            }
        }
        // nothing in the future so we are done
        if done {
            break
        }
    }
    return
}

func main() {
    slice1 := []string{"foo", "bar", "hello", "bar"}
    slice2 := []string{"foo", "bar"}
    fmt.Printf("%+v\n", intersection(slice1, slice2))
}

Now the intersection method defined above will only operate on slices of strings, like your example.. You can in theory create a definition that looks like this func intersection(a []interface, b []interface) (inter []interface), however you would be relying on reflection and type casting so that you can compare, which will add latency and make your code harder to read. It's probably easier to maintain and read to write a separate function for each type you care about.

func intersectionString(a []string, b []string) (inter []string),

func intersectionInt(a []int, b []int) (inter []int),

func intersectionFloat64(a []Float64, b []Float64) (inter []Float64), ..ect

You can then create your own package and reuse once you settle how you want to implement it.

package intersection

func String(a []string, b []string) (inter []string)

func Int(a []int, b []int) (inter []int)

func Float64(a []Float64, b []Float64) (inter []Float64)


问:
Cloning a Class Definition (PCL)
The Question:
Is this possible to clone a class definition using reflection? I am not talking about shallow cloning nor deep cloning. I am talking about definition cloning. I want to have a class with a static variable not shared between all instances, but just the definition I created. And I (or the library) need to be able to create an instance from this class later on.

The Problem:
You see, I need this because of the following scenario,

There is this library that expects me to provides it with a type having a certain static method. However in my case this static method needs to compare two value one from a non static field of another type. This makes it impossible to pass the instance that has the information to the class because it is not yet initialized. Check out the following example of the situation:

```<code>class MasterClass
{
    public int SomeInfo {get; set;} = 10;
    public void PeresentClass()
    {
        SOMELIBRARY.RegisterType(typeof(StaticClass));
    }
}
class StaticClass
{
    public static bool CanCreate(int someVar)
    {
        // I need to compare someVar with the SomeInfo property of MasterClass instance that presented this type to the SOMELIBRARY.
    }
    public StaticClass()
    {
        // Something irrelevant
    }
}
</code>```

In the above example I have no control over the SOMELIBRARY and the way they decided to write the code. But it seems that they some how want to call the CanCreate method first and then create an instance of class if it meets the requirements.

However, for CanCreate to works correctly I need to have access to the instance of the class presented the StaticClass to the SOMELIBRARY in first place. And I cant make MasterClass static because there are more than one instance of this class active at every time.

Only way I could think of was to redefine a new StaticClass with a static field pointing to the MasterClass that defined it (or cloned the definition). However my knowledge of reflection failed me to do so yet. So here I am asking it this is even possible? And I really would like to be able to do it under PCL profiles.

Real World:
Just for more information, I am actually talking about XAMARIN.iOS and NSUrlProtocol class, specially CanInitWithRequest method.

Possible Solution: With more thinking, I found that another way to solve this problem is to make the StaticClass generic; Doing so allows me to have a static variable per type definition. However, for this to work I need to be able to create unique and possibly empty types at run-time. Is this possible?

XAMARIN.iOS: Unfortunately Reflection.Emit is not available on iOS so for now I don't believe that this is even possible in any way. Still waiting for your comments on the situation tho.

https://developer.xamarin.com/guides/ios/advanced_topics/limitations/#System.Reflection.Emit

答:
There are a number of ways to create a class at runtime, which seems like what you are asking.  Your question seems to have ruled out System.Reflection.Emit, so you might want to explore some of the other answers on this topic to see if they may be suitable for your platform (Xamarin.IOS).

That said, your question seems to indicate a code smell in your implementation.  You are trying to map a class instance across the API registration function, which relies on a static method to indicate a resource's suitability for handling a type of request (canInitWithRequest).  This function should only indicate if the registered NSURLProtocol class is capable of handling a particular request type, it likely should not be dependent on some class property of another object in the system.

A better approach might be to have your NSURLProtocol instance look up the shared resource at runtime when it is invoked by the underlying framework.  For instance, something like the following:

```<code>static class SystemMap {
    // Store some mapping information in a commonly accessible system resource
    // In this case a simple static class that wraps up a dictionary
    static Dictionary<Type, Master> systemMap = new Dictionary<Type, Master>();

    // Allow registered components to be accessed
    public static Master getRegisteredMaster(Type handlerType) {
        return systemMap[handlerType];
    }

    // Allow new registrations to be made in your system
    public static void registerNewMaster(Master registrant, Type handlerType) {
        systemMap[handlerType] = registrant;
    }
}

class Master {
    // This would be your custom class that you instantiate throughout your system
    public string name;
    public int someVar { get; set; } = new Random().Next(1, 100);
    public Master(string name) {
        this.name = name;
    }
}

class BaseHandlerType {
    // This would be NSURLProtocol
}

class Handler1 : BaseHandlerType {
    // This would be canInitWithRequest
    public static bool CanCreate(int someVar) {
        Master myMaster = SystemMap.getRegisteredMaster(typeof(Handler1));
        return someVar > myMaster.someVar;
    }
}

class Handler2 : BaseHandlerType {
    //... Register various handler types to various "Master" instances in your system
    // This is a concrete implementation of NSURLProtocol
}

class Handler3 : BaseHandlerType {
    //... Register various handler types to various "Master" instances in your system
    // This is a concrete implementation of NSURLProtocol
}

class SystemFactory {
    // Use a factory method to instantiate the system components and plug things together
    public void initializeSystem() {
        var masterA = new Master("a");
        var masterB = new Master("b");
        var masterC = new Master("c");
        SystemMap.registerNewMaster(masterA, typeof(Handler1));
        SystemMap.registerNewMaster(masterB, typeof(Handler2));
        SystemMap.registerNewMaster(masterC, typeof(Handler3));
        SomeLibrary.register(typeof(Handler1));
        SomeLibrary.register(typeof(Handler2));
        SomeLibrary.register(typeof(Handler3));
    }
}

static class SomeLibrary {
    public static void register(Type handlerType) {
        // This represents the API registration
    }
}
</code>```

This pattern might help you establish the relationship between components that you are trying to achieve via class creation at runtime.  This pattern would allow your various different types of handlers (i.e. NSURLProtocol classes) to access a different Master instance when they are invoked.  In this example, masterA maps to Handler1, masterB to Handler2, and so on.

Title: Cloning a Class Definition (PCL)

Body:
The Question:
Is this possible to clone a class definition using reflection? I am not talking about shallow cloning nor deep cloning. I am talking about definition cloning. I want to have a class with a static variable not shared between all instances, but just the definition I created. And I (or the library) need to be able to create an instance from this class later on.

The Problem:
You see, I need this because of the following scenario,

There is this library that expects me to provides it with a type having a certain static method. However in my case this static method needs to compare two value one from a non static field of another type. This makes it impossible to pass the instance that has the information to the class because it is not yet initialized. Check out the following example of the situation:

class MasterClass
{
    public int SomeInfo {get; set;} = 10;
    public void PeresentClass()
    {
        SOMELIBRARY.RegisterType(typeof(StaticClass));
    }
}
class StaticClass
{
    public static bool CanCreate(int someVar)
    {
        // I need to compare someVar with the SomeInfo property of MasterClass instance that presented this type to the SOMELIBRARY.
    }
    public StaticClass()
    {
        // Something irrelevant
    }
}

In the above example I have no control over the SOMELIBRARY and the way they decided to write the code. But it seems that they some how want to call the CanCreate method first and then create an instance of class if it meets the requirements.

However, for CanCreate to works correctly I need to have access to the instance of the class presented the StaticClass to the SOMELIBRARY in first place. And I cant make MasterClass static because there are more than one instance of this class active at every time.

Only way I could think of was to redefine a new StaticClass with a static field pointing to the MasterClass that defined it (or cloned the definition). However my knowledge of reflection failed me to do so yet. So here I am asking it this is even possible? And I really would like to be able to do it under PCL profiles.

Real World:
Just for more information, I am actually talking about XAMARIN.iOS and NSUrlProtocol class, specially CanInitWithRequest method.

Possible Solution: With more thinking, I found that another way to solve this problem is to make the StaticClass generic; Doing so allows me to have a static variable per type definition. However, for this to work I need to be able to create unique and possibly empty types at run-time. Is this possible?

XAMARIN.iOS: Unfortunately Reflection.Emit is not available on iOS so for now I don't believe that this is even possible in any way. Still waiting for your comments on the situation tho.

https://developer.xamarin.com/guides/ios/advanced_topics/limitations/#System.Reflection.Emit

Body:
There are a number of ways to create a class at runtime, which seems like what you are asking.  Your question seems to have ruled out System.Reflection.Emit, so you might want to explore some of the other answers on this topic to see if they may be suitable for your platform (Xamarin.IOS).

That said, your question seems to indicate a code smell in your implementation.  You are trying to map a class instance across the API registration function, which relies on a static method to indicate a resource's suitability for handling a type of request (canInitWithRequest).  This function should only indicate if the registered NSURLProtocol class is capable of handling a particular request type, it likely should not be dependent on some class property of another object in the system.

A better approach might be to have your NSURLProtocol instance look up the shared resource at runtime when it is invoked by the underlying framework.  For instance, something like the following:

static class SystemMap {
    // Store some mapping information in a commonly accessible system resource
    // In this case a simple static class that wraps up a dictionary
    static Dictionary<Type, Master> systemMap = new Dictionary<Type, Master>();

    // Allow registered components to be accessed
    public static Master getRegisteredMaster(Type handlerType) {
        return systemMap[handlerType];
    }

    // Allow new registrations to be made in your system
    public static void registerNewMaster(Master registrant, Type handlerType) {
        systemMap[handlerType] = registrant;
    }
}

class Master {
    // This would be your custom class that you instantiate throughout your system
    public string name;
    public int someVar { get; set; } = new Random().Next(1, 100);
    public Master(string name) {
        this.name = name;
    }
}

class BaseHandlerType {
    // This would be NSURLProtocol
}

class Handler1 : BaseHandlerType {
    // This would be canInitWithRequest
    public static bool CanCreate(int someVar) {
        Master myMaster = SystemMap.getRegisteredMaster(typeof(Handler1));
        return someVar > myMaster.someVar;
    }
}

class Handler2 : BaseHandlerType {
    //... Register various handler types to various "Master" instances in your system
    // This is a concrete implementation of NSURLProtocol
}

class Handler3 : BaseHandlerType {
    //... Register various handler types to various "Master" instances in your system
    // This is a concrete implementation of NSURLProtocol
}

class SystemFactory {
    // Use a factory method to instantiate the system components and plug things together
    public void initializeSystem() {
        var masterA = new Master("a");
        var masterB = new Master("b");
        var masterC = new Master("c");
        SystemMap.registerNewMaster(masterA, typeof(Handler1));
        SystemMap.registerNewMaster(masterB, typeof(Handler2));
        SystemMap.registerNewMaster(masterC, typeof(Handler3));
        SomeLibrary.register(typeof(Handler1));
        SomeLibrary.register(typeof(Handler2));
        SomeLibrary.register(typeof(Handler3));
    }
}

static class SomeLibrary {
    public static void register(Type handlerType) {
        // This represents the API registration
    }
}

This pattern might help you establish the relationship between components that you are trying to achieve via class creation at runtime.  This pattern would allow your various different types of handlers (i.e. NSURLProtocol classes) to access a different Master instance when they are invoked.  In this example, masterA maps to Handler1, masterB to Handler2, and so on.


问:
Jenkins API tree filter using regex?
I'm using the tree parameter to filter JSON data coming back from the API and that works great. My issue is I need to fetch some specific data from an array with a bunch of stuff I don't care about. I'm wondering if there is a way, using the tree command, to filter using a regex or contains string?

For example, to give me back all fileNames that start with MyProject:

```<code>   http://myapi.com?tree=fileName=MyProject*
</code>```

答:
I found that using not using the JSON and instead switching to XML you can filter with XPATH. An example on finding all job urls with name starting with "Test" is this:</p>

```<code>https://{jenkins_instance_url}/view/All/api/xml?tree=jobs[name,url]&xpath=/*/job[starts-with(name,'Test')]/url&wrapper=jobs
</code>```

Title: Jenkins API tree filter using regex?

Body:
I'm using the tree parameter to filter JSON data coming back from the API and that works great. My issue is I need to fetch some specific data from an array with a bunch of stuff I don't care about. I'm wondering if there is a way, using the tree command, to filter using a regex or contains string?

For example, to give me back all fileNames that start with MyProject:

   http://myapi.com?tree=fileName=MyProject*

Body:
I found that using not using the JSON and instead switching to XML you can filter with XPATH. An example on finding all job urls with name starting with "Test" is this:

https://{jenkins_instance_url}/view/All/api/xml?tree=jobs[name,url]&xpath=/*/job[starts-with(name,'Test')]/url&wrapper=jobs


问:
Apache Camel Event Store
I have a JBoss Fuse project, where I receive data (entities) from an external source and process it. I would like to implement event sourcing to be able to simulate the data consumption afterwards.

Is there a possibility to include some kind of event sourcing in camel routes? Is there a certain event store, which works best with camel and can be easily integrated?

Thanks in advance!

Best Regards, Sandra

答:
akka-persistence is one such implementation of event sourcing. It can be integrated with a Camel route relatively easily:
http://doc.akka.io/docs/akka/current/java/camel.html#akka-camel-components

akka-persistence supports a number of pluggable storage backends, including  cassandra, jdbc, redis, just to name a few popular options.

Title: Apache Camel Event Store


问:
Derived class vtable corrupted?

Need help in root causing a vtable corruption issue(not sure if that’s what is happening). Here is the very simplified version of the code.

```<code>class CBase
{
public:
    CBase()
    virtual ~CBase()
    virtual void base_virtual_fn1() = 0;
    virtual void base_virtual_fn2();
private:
    CData   _data;
};

class CDerived : public CBase
{
public:
    CDerived();
    virtual ~CDerived()
    virtual void base_virtual_fn1();
    virtual void base_virtual_fn2();
    virtual void derived_virtual_fn1();
    virtual void derived_virtual_fn2();
private:
    // Contains vectors , maps, integers, bools.
};
</code>```

When I create an instance of CDerived and call the derived class virtual function say derived_virtual_fn2  the other function gets called i.e. derived_virtual_fn1.

Calls to base_virtual_fnx has no issues.

This only happens with object created on the heap and not for local object.

These classes are in a shared library. I’m using gcc 3.4.2 on Linux (SLES 10). There is no pragma pack directive in any of this code and there is a mix of C and C++ code (extern c is used).
What could be the issue here?

I forgot to mention that there are there is tons of other code (executable, libraries)

答: If it only happens for objects created on the heap, the most likely explanation is heap corruption, which possibly has nothing to do with the two classes you mention. Check your allocations/deallocations! check that you're correctly using delete [] to delete arrays, etc. Maybe use valgrind or similar as well.</p>

Title: Derived class vtable corrupted?

Body:
Need help in root causing a vtable corruption issue(not sure if that’s what is happening). Here is the very simplified version of the code.

class CBase
{
public:
    CBase()
    virtual ~CBase()
    virtual void base_virtual_fn1() = 0;
    virtual void base_virtual_fn2();
private:
    CData   _data;
};

class CDerived : public CBase
{
public:
    CDerived();
    virtual ~CDerived()
    virtual void base_virtual_fn1();
    virtual void base_virtual_fn2();
    virtual void derived_virtual_fn1();
    virtual void derived_virtual_fn2();
private:
    // Contains vectors , maps, integers, bools.
};

When I create an instance of CDerived and call the derived class virtual function say derived_virtual_fn2  the other function gets called i.e. derived_virtual_fn1.

Calls to base_virtual_fnx has no issues.

This only happens with object created on the heap and not for local object.

These classes are in a shared library. I’m using gcc 3.4.2 on Linux (SLES 10). There is no pragma pack directive in any of this code and there is a mix of C and C++ code (extern c is used).
What could be the issue here?

I forgot to mention that there are there is tons of other code (executable, libraries)


问:
file_get_contents(): php_network_getaddresses: getaddrinfo failed: Name or service not known
I'm trying to download an image from a server using a PHP script on my website on xampp server.

The image is being downloaded using the function file_get_contents.

The php code for downloading on the server is:

```<code>if(isset($_GET['path']) && isset($_GET['username'])) {
    echo "path:".$_GET['path'];
    $temp = explode(".", $_GET['path']);
    $extension = end($temp);
    $fname="images/".$_GET['title'];
    $filenameIn  = $_GET['path'];
    $filenameOut = "" . $fname;
    $contentOrFalseOnFailure   = file_get_contents($filenameIn);
    $byteCountOrFalseOnFailure = file_put_contents($filenameOut,$contentOrFalseOnFailure);
}
</code>```

But I'm getting this error:

Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: Name or service not known in
  /opt/lampp/htdocs/xampp/project/upload_art.php on line 19

Warning: file_get_contents(http://app6.pixlr.com/_temp/528afa6e2f7cc6a5b1000101.jpg):
  failed to open stream: php_network_getaddresses: getaddrinfo failed:
  Name or service not known in
  /opt/lampp/htdocs/xampp/project/upload_art.php on line 19

I have checked out all posted answers here but none seems to resolve the issue. Please help!

答:
Here are advice in case you are using Docker env for your web app.
I had same problem when I used docker php image, added dns options in yml file solved my problem.

docker-compose.yml

```<code>version: '2'

services:
  webserver:
    build: ./docker/webserver
    image: my_webapp
    dns: 8.8.8.8
    dns_opt:
      - use-vc
      - no-tld-query
    ports:
      - 80:80
      - 443:443
    volumes:
      - ./:/var/www/html
</code>```

Body:
I'm trying to download an image from a server using a PHP script on my website on xampp server.

The image is being downloaded using the function file_get_contents.

The php code for downloading on the server is:

if(isset($_GET['path']) && isset($_GET['username'])) {
    echo "path:".$_GET['path'];
    $temp = explode(".", $_GET['path']);
    $extension = end($temp);
    $fname="images/".$_GET['title'];
    $filenameIn  = $_GET['path'];
    $filenameOut = "" . $fname;
    $contentOrFalseOnFailure   = file_get_contents($filenameIn);
    $byteCountOrFalseOnFailure = file_put_contents($filenameOut,$contentOrFalseOnFailure);
}

But I'm getting this error:

Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: Name or service not known in
  /opt/lampp/htdocs/xampp/project/upload_art.php on line 19

Warning: file_get_contents(http://app6.pixlr.com/_temp/528afa6e2f7cc6a5b1000101.jpg):
  failed to open stream: php_network_getaddresses: getaddrinfo failed:
  Name or service not known in
  /opt/lampp/htdocs/xampp/project/upload_art.php on line 19

I have checked out all posted answers here but none seems to resolve the issue. Please help!

Body:
Here are advice in case you are using Docker env for your web app.
I had same problem when I used docker php image, added dns options in yml file solved my problem.

docker-compose.yml

version: '2'

services:
  webserver:
    build: ./docker/webserver
    image: my_webapp
    dns: 8.8.8.8
    dns_opt:
      - use-vc
      - no-tld-query
    ports:
      - 80:80
      - 443:443
    volumes:
      - ./:/var/www/html


问:
How to group strings by sequential occurrence and check for values > X in another column
for the following data structure, I would like to use Python to find the number of SEQUENTIAL occurrences of a pattern in column C0 >= than a threshold X, and the number of corresponding values in another column prcC0 that are >= than a threshold Y

for the example below, if thresholds X = 3 and Y is 40, then the algorithm should output. rows 2:4 for string pattern B occurring >= 3 and corresponding prcC0 values >= 40

the algorithm should scan the entire data frame for such sequential patterns.

```<code>Seq nMin    nUniqe  n3WJ    prc3WJ  C0  prcC0
0   s00000  482 9   172 35.68   A   1.65
1   s00001  503 10  193 38.37   A   15.33
2   s00002  415 9   221 53.25   B   44.03
3   s00003  325 10  155 47.69   B   42.99
4   s00004  429 10  175 40.79   B   43.37
</code>```

Body:
for the following data structure, I would like to use Python to find the number of SEQUENTIAL occurrences of a pattern in column C0 >= than a threshold X, and the number of corresponding values in another column prcC0 that are >= than a threshold Y

for the example below, if thresholds X = 3 and Y is 40, then the algorithm should output. rows 2:4 for string pattern B occurring >= 3 and corresponding prcC0 values >= 40

the algorithm should scan the entire data frame for such sequential patterns.

Seq nMin    nUniqe  n3WJ    prc3WJ  C0  prcC0
0   s00000  482 9   172 35.68   A   1.65
1   s00001  503 10  193 38.37   A   15.33
2   s00002  415 9   221 53.25   B   44.03
3   s00003  325 10  155 47.69   B   42.99
4   s00004  429 10  175 40.79   B   43.37

Body:
Let's use Pandas:

import pandas as pd
df

Seq  nMin  nUniqe  n3WJ  prc3WJ C0  prcC0
0  s00000   482       9   172   35.68  A   1.65
1  s00001   503      10   193   38.37  A  15.33
2  s00002   415       9   221   53.25  B  44.03
3  s00003   325      10   155   47.69  B  42.99
4  s00004   429      10   175   40.79  B  43.37

X = 3
Y = 40
df_out = df.assign(Cond=df.prcC0 >= Y)
df_out.groupby((~df_out['Cond']).cumsum()).filter(lambda x: x.shape[0] >= X+1).query('Cond == True')

Output:

      Seq  nMin  nUniqe  n3WJ  prc3WJ C0  prcC0  Cond
2  s00002   415       9   221   53.25  B  44.03  True
3  s00003   325      10   155   47.69  B  42.99  True
4  s00004   429      10   175   40.79  B  43.37  True


问:
Query to check if an attribute was in the table from LAST YEAR
Im trying to write a CASE statement to see if school_name with the school_form_status = completed, in the current year has been also completed the previous year.

```<code>   school_name | School_status | Report date|  FORM_PREVIOUS_YEAR
________________________________________________________________________________

     Paul Keys |    Completed  | 03/31/2016  |      YES
</code>```

This is what I have but but not working , im a beginner

```<code>    select
    CASE REPORTED_DATE YEAR = REPORTED_DATE, YEAR,-1,DateAdd(Year,DATEDIFF(YEAR,0,getdate()),0))
    THEN 'Y'
     ELSE 'N'
    END AS FORM_PREV_YEAR,
    from
    TABLE1
</code>```

答:
Try this code:</p>

```<code>select
CASE WHEN school_status = 'Completed' and EXTRACT(year from report_date) = EXTRACT(year from sysdate)-1
THEN 'Y'
ELSE 'N'
END AS FORM_PREV_YEAR
from table1;
</code>```

Body:
Im trying to write a CASE statement to see if school_name with the school_form_status = completed, in the current year has been also completed the previous year.

   school_name | School_status | Report date|  FORM_PREVIOUS_YEAR
________________________________________________________________________________

     Paul Keys |    Completed  | 03/31/2016  |      YES

This is what I have but but not working , im a beginner

    select
    CASE REPORTED_DATE YEAR = REPORTED_DATE, YEAR,-1,DateAdd(Year,DATEDIFF(YEAR,0,getdate()),0))
    THEN 'Y'
     ELSE 'N'
    END AS FORM_PREV_YEAR,
    from
    TABLE1

Body:
Try this code:

select
CASE WHEN school_status = 'Completed' and EXTRACT(year from report_date) = EXTRACT(year from sysdate)-1
THEN 'Y'
ELSE 'N'
END AS FORM_PREV_YEAR
from table1;


问:
How to make jmeter behave like a browser
I'm new to JMeter and I've already read some guidelines and all. Now i wanna focus on making my JMeter behave more like a browser. I've already set up everything according to this guide, but I'd like to know if there are any more advanced settings I could apply. Haven't found anything else so far. I'm greatful for any advice!</p>

答: You can run jmeter in java code and use html in response to open in browser using desktop</p>


问:
Getting a List from another class
I've been trying to figure out how to make a List from classA accessible for ClassB
I've tried creating an instance/object of the list but it always returns empty when I get the size of the list (while in the main class its not empty).

Example:

ClassA:

```<code>List<String> players = new ArrayList<String>();
</code>```

If i used players.size() here it would return 2 for example

in ClassB I tried the following:

```<code> ClassA classA = new ClassA();
 List<String> newList = classA.players;
</code>```

newList.size() will always return 0 no matter what.

I've also tried using a getter but that doesn't seem to make a difference.

Example:

ClassA:

```<code>List<String> players = new ArrayList<String>();
public List<String> getList(){
    return this.players;
}
</code>```

ClassB:

```<code>ClassA.getList().size()
</code>```

This will also always return 0

How would I properly do this? I tried using a static and that seemed to work but i've been told:

"Static is not the right tool for the job. It's a memory management
  tool, not an access modifier."

He told me:

Instead of static and instead of creating new instances, you can pass
  instances to other classes by adding them as parameters to the
  constructor

However I don't really get what he means. If someone could explain this with an example that would be amazing. Thanks in advance!

Edit: Since a lot of you don't quite get where i want to go with this i'll post my source:
refered to as ClassA in the example

```<code>public class TeamManager {

String prefix = new Messages().prefix;
List<String> players = new ArrayList<String>();
List<String> human = new ArrayList<String>();
List<String> infected = new ArrayList<String>();

void join(Player p){
    if(!players.contains(p.getName())){
        players.add(p.getName());
        teleportToLobby(p);
        for (String temp : players) {
            Bukkit.getPlayer(temp).sendMessage("§e§l"+p.getName()+ " has joined infection. §7("+players.size()+"/16)");
        }
    }else{
        p.sendMessage(prefix + "§cFailed. You are already in the game!");
    }
}
void leave(Player p){
    if(players.contains(p.getName())){
        p.teleport(Bukkit.getWorlds().get(0).getSpawnLocation());
        players.remove(p.getName());
        for (String temp : players) {
            Bukkit.getPlayer(temp).sendMessage("§7§l"+p.getName()+ " has left infection. §7("+players.size()+"/16)");
        }
    }else{
        p.sendMessage(prefix + "§cYou are not in a game!");
    }
}
void addToHumans(String playername){
    human.add(playername);
}
void removeFromHumans(String playername){
    human.remove(playername);
}
void addToInfected(String playername){
    infected.add(playername);
}
void removeFromInfected(String playername){
    infected.remove(playername);
}

void teleportToLobby(Player p){
    Location lobby = getLocFromConfig("lobby");
    if(lobby != null){
        p.teleport(lobby);
        p.sendMessage(prefix + "§aSuccessfully added to game!");
    }else{
        p.sendMessage(prefix + "§cLobby not set! Make sure to set a lobby using /infection setlobby");
    }
}
void startGame(){
    /*if(human.size() >= 4){
    }*/
    for (String temp : players) {
        Bukkit.getPlayer(temp).sendMessage("Game will start shortly!");
    }
}
Location getLocFromConfig(String locationName){
    if(Main.plugin.getConfig().get("lobby") != null){
        double x = Main.plugin.getConfig().getInt(locationName+".x");
        double y = Main.plugin.getConfig().getInt(locationName+".y");
        double z = Main.plugin.getConfig().getInt(locationName+".z");
        World world = Main.plugin.getServer().getWorld(Main.plugin.getConfig().getString(locationName+".world"));
        Location l = new Location(world, x, y, z);
        return l;
    }else{
        Bukkit.getLogger().warning("[Infection] Lobby has not been set!");
        return null;
    }
}
int getPlayersInLobby(){
    return players.size();
}

public List<String> getPlayers(){
    List<String> players = this.players;
    return players;
}
public List<String> getHumans(){
    return human;
}
public List<String> getInfected(){
    return infected;
}
</code>```

}

Events class (referred to in the example as ClassB)

```<code>public class Events implements Listener{

TeamManager teamman = new TeamManager();
List<String> players = teamman.getPlayers();
List<String> humans = teamman.getHumans();
List<String> infected = teamman.getInfected();
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e){
    //Player p = (Player) e.getPlayer();
    //e.setJoinMessage("["+lvl+"]" + e.getPlayer().getName() +"has joined the game!");
    //p.setDisplayName("[lvl1]"+p.getName());

}
@EventHandler
public void onPlayerDamage(EntityDamageByEntityEvent  e){
    if(e.getEntity() instanceof Player){
        Player p = (Player) e.getEntity();
        Bukkit.getServer().broadcastMessage("Players: "+ players);
        if(players.contains(p.getName())){
            if((p.getHealth() - p.getLastDamage()) < 1){
                for (String temp : players) {
                    Bukkit.getPlayer(temp).sendMessage("§c"+p.getName()+" got infected by "+p.getKiller().getName()+"!");
                }
                e.setCancelled(true);
                 p.setHealth(20);
                 teamman.addToInfected(p.getName());
                 teamman.removeFromHumans(p.getName());
                 p.sendMessage("§cYou have been infected!!");
            }
        }
    }
}
</code>```

}

As said above i want to be able to access the lists from TeamManager and use them in Events. And as explained players is empty in the Events class. I hope this helps.

答:
Every time you do

```<code>ClassA classA = new ClassA();
List<String> newList = classA.players;
</code>```

will create/have new instance of ArrayList declared in ClassA.

And, since below line of code is an instance variable. So, each instance will have different copy.

```<code>List<String> players = new ArrayList<String>();
</code>```

So, solution are :

```<code> ClassA classA = new ClassA();
 classA.players.add("A");
 List<String> newList = classA.players;
</code>```

Or have setter method or initialize in constructor or declared it as static member. This all solution will depends on your requirement.

Instead of static and instead of creating new instances, you can pass
  instances to other classes by adding them as parameters to the
  constructor

This means you could pass ClassA instance to ClassB using constructor.

Title: Getting a List from another class

Body:
I've been trying to figure out how to make a List from classA accessible for ClassB
I've tried creating an instance/object of the list but it always returns empty when I get the size of the list (while in the main class its not empty).

Example:

ClassA:

List<String> players = new ArrayList<String>();

If i used players.size() here it would return 2 for example

in ClassB I tried the following:

 ClassA classA = new ClassA();
 List<String> newList = classA.players;

newList.size() will always return 0 no matter what.

I've also tried using a getter but that doesn't seem to make a difference.

Example:

ClassA:

List<String> players = new ArrayList<String>();
public List<String> getList(){
    return this.players;
}

ClassB:

ClassA.getList().size()

This will also always return 0

How would I properly do this? I tried using a static and that seemed to work but i've been told:

"Static is not the right tool for the job. It's a memory management
  tool, not an access modifier."

He told me:

Instead of static and instead of creating new instances, you can pass
  instances to other classes by adding them as parameters to the
  constructor

However I don't really get what he means. If someone could explain this with an example that would be amazing. Thanks in advance!

Edit: Since a lot of you don't quite get where i want to go with this i'll post my source:
refered to as ClassA in the example

public class TeamManager {

String prefix = new Messages().prefix;
List<String> players = new ArrayList<String>();
List<String> human = new ArrayList<String>();
List<String> infected = new ArrayList<String>();

void join(Player p){
    if(!players.contains(p.getName())){
        players.add(p.getName());
        teleportToLobby(p);
        for (String temp : players) {
            Bukkit.getPlayer(temp).sendMessage("§e§l"+p.getName()+ " has joined infection. §7("+players.size()+"/16)");
        }
    }else{
        p.sendMessage(prefix + "§cFailed. You are already in the game!");
    }
}
void leave(Player p){
    if(players.contains(p.getName())){
        p.teleport(Bukkit.getWorlds().get(0).getSpawnLocation());
        players.remove(p.getName());
        for (String temp : players) {
            Bukkit.getPlayer(temp).sendMessage("§7§l"+p.getName()+ " has left infection. §7("+players.size()+"/16)");
        }
    }else{
        p.sendMessage(prefix + "§cYou are not in a game!");
    }
}
void addToHumans(String playername){
    human.add(playername);
}
void removeFromHumans(String playername){
    human.remove(playername);
}
void addToInfected(String playername){
    infected.add(playername);
}
void removeFromInfected(String playername){
    infected.remove(playername);
}

void teleportToLobby(Player p){
    Location lobby = getLocFromConfig("lobby");
    if(lobby != null){
        p.teleport(lobby);
        p.sendMessage(prefix + "§aSuccessfully added to game!");
    }else{
        p.sendMessage(prefix + "§cLobby not set! Make sure to set a lobby using /infection setlobby");
    }
}
void startGame(){
    /*if(human.size() >= 4){
    }*/
    for (String temp : players) {
        Bukkit.getPlayer(temp).sendMessage("Game will start shortly!");
    }
}
Location getLocFromConfig(String locationName){
    if(Main.plugin.getConfig().get("lobby") != null){
        double x = Main.plugin.getConfig().getInt(locationName+".x");
        double y = Main.plugin.getConfig().getInt(locationName+".y");
        double z = Main.plugin.getConfig().getInt(locationName+".z");
        World world = Main.plugin.getServer().getWorld(Main.plugin.getConfig().getString(locationName+".world"));
        Location l = new Location(world, x, y, z);
        return l;
    }else{
        Bukkit.getLogger().warning("[Infection] Lobby has not been set!");
        return null;
    }
}
int getPlayersInLobby(){
    return players.size();
}

public List<String> getPlayers(){
    List<String> players = this.players;
    return players;
}
public List<String> getHumans(){
    return human;
}
public List<String> getInfected(){
    return infected;
}

}

Events class (referred to in the example as ClassB)

public class Events implements Listener{

TeamManager teamman = new TeamManager();
List<String> players = teamman.getPlayers();
List<String> humans = teamman.getHumans();
List<String> infected = teamman.getInfected();
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e){
    //Player p = (Player) e.getPlayer();
    //e.setJoinMessage("["+lvl+"]" + e.getPlayer().getName() +"has joined the game!");
    //p.setDisplayName("[lvl1]"+p.getName());

}
@EventHandler
public void onPlayerDamage(EntityDamageByEntityEvent  e){
    if(e.getEntity() instanceof Player){
        Player p = (Player) e.getEntity();
        Bukkit.getServer().broadcastMessage("Players: "+ players);
        if(players.contains(p.getName())){
            if((p.getHealth() - p.getLastDamage()) < 1){
                for (String temp : players) {
                    Bukkit.getPlayer(temp).sendMessage("§c"+p.getName()+" got infected by "+p.getKiller().getName()+"!");
                }
                e.setCancelled(true);
                 p.setHealth(20);
                 teamman.addToInfected(p.getName());
                 teamman.removeFromHumans(p.getName());
                 p.sendMessage("§cYou have been infected!!");
            }
        }
    }
}

}

As said above i want to be able to access the lists from TeamManager and use them in Events. And as explained players is empty in the Events class. I hope this helps.

Body:
Every time you do

ClassA classA = new ClassA();
List<String> newList = classA.players;

will create/have new instance of ArrayList declared in ClassA.

And, since below line of code is an instance variable. So, each instance will have different copy.

List<String> players = new ArrayList<String>();

So, solution are :

 ClassA classA = new ClassA();
 classA.players.add("A");
 List<String> newList = classA.players;

Or have setter method or initialize in constructor or declared it as static member. This all solution will depends on your requirement.

Instead of static and instead of creating new instances, you can pass
  instances to other classes by adding them as parameters to the
  constructor

This means you could pass ClassA instance to ClassB using constructor.


问:
Run separate queries in MySQL using a single link
I have created that toggles a material icon to on/off.
When the icon is off I need to run a delete query.
When the icon is on I need to run a insert query.

I know I need to use AJAX and am still new to it.
What I am having trouble understanding is whether I refernece the current PHP file or some other php file. Iknow I have to write my query and execute it in a PHP file, but not sure to do that. I do not want to reload the pagebecuase I lose other information by doing so.

I basically owuld like to update the icon and execute the required SQL stmnt.

Any help is appreciated.

What I have so far:

JAVASCRIPT:

```<code>    //update the favorites icon
function updateFavorites(id){
if($(this).find('#staricon'+id)){
    if($('#staricon'+id).hasClass('star-color')) {
        $('#staricon'+id).removeClass('star-color');
        //update the table
        deleteFavorites();
    }
    else {
        $('#staricon'+id).addClass('star-color');
        addFavorites();
    }
}
}

//delete the item from the table

function deleteFavorite(){

        $.ajax({
            type: "POST",
            url: "somePHPFile.php",
            cache: false,
            data:{id:'#staricon'+id},
        }).done(function( msg ) {  console.log(msg);
        });
}
</code>```

PHP:

```<code>//check to see if this is a favorite
$query = "SELECT * FROM favorites WHERE story_id = " . $story_id;
$result = mysqli_query($conn, $query);
$is_fav = mysqli_num_rows($result);

if ($is_fav > 0) {
echo '<a  class=" stats pull-right " href="javacript:void" ><span id="staricon' . $story_id .'" class="star-color"   onclick="updateFavorites(' . $story_id . ')"><i  class=" material-icons " title="Favorite" >star</i></span></a>';
 }
 else {
 echo '<a  class=" stats pull-right " href="javacript:void" ><span id="staricon' . $story_id .'"   onclick="updateFavorites(' . $story_id . ')"><i  class=" material-icons " title="Favorite" >star</i></span></a>';
 }
</code>```

I have update my code to reflect the following:

JAVASCRIPT:

```<code>function updateFavorites(id){
if($(this).find('#staricon'+id)){
    if($('#staricon'+id).hasClass('star-color')) {
        $('#staricon'+id).removeClass('star-color');
        $.ajax({
            type: "POST",
            url: "showStoryCards.php",
            data: {
                id: $(this).data(id),
                enabled: !$(this).hasClass('star-color') //delete
            },
        })
    }
    else {
        $('#staricon'+id).addClass('star-color');
        $.ajax({
            type: "POST",
            url: "showStoryCards.php",
            data: {
                id: $(this).data("id"),
                enabled: $(this).hasClass('star-color') //insert
            },
        })

    }
}
</code>```

PHP:

```<code>echo $story_title ;
$query = "SELECT count(*) FROM favorites WHERE story_id = ?";
$sql= $conn->prepare($query);
$sql->bind_param("s", $story_id);
$sql->execute();
$result = $sql->get_result();
$is_fav = mysqli_num_rows($result);
if ($is_fav == 0) {
echo '<a  class=" stats pull-right " href="javacript:void" ><span
id="staricon' . $story_id .'" class="star-color"
onclick="updateFavorites(' . $story_id . ')"><i  class=" material-icons "
title="Favorite" >star</i></span></a>';
}
else {
echo '<a  class=" stats pull-right " href="javacript:void" ><span
id="staricon' . $story_id .'"   onclick="updateFavorites(' . $story_id .
')"><i  class=" material-icons " title="Favorite" >star</i></span></a>';
}
if (isset($_POST['enabled'])){

if($_POST['enabled']) {  // INSERT query

    $sql = "INSERT INTO favorites VALUES( " . $id . ", '1') ";
    $sql->execute();
} else {// Delete query
}
}
</code>```

My icons update to the appropriate on /off colors but I still cannot get the query to fire. It does not even appear that the call back to the PHP page is functioning as I cannot retrieve the $_POST.

答:
Simplify it all.

$(document).ready(function() {

  $('#staricon').on('click', function() {
    // Prevent multiple clicks before the first one finishes.
    // There is probably a more elegant way to do this.
    if(active){
      return;
    }
    active = false;
    //console.log($(this).hasClass('star-color'));
    //console.log($(this).data("id"));
    $.ajax({
      type: "POST",
      url: "somePHPFile.php",
      data: {
        id: $(this).data("id"),
        enabled: !$(this).hasClass('star-color')
      },
    }).done(function(msg) {
      active = true;
      $(this).toggleClass('star-color');
      console.log(msg);
    });
  });

});

/*
PHP
// Use ID and enabled to add or delete from db.
if($_POST['enabled']) {
   // INSERT query
} else {
   // Delete query
}
*/```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.star-color {
  background-color: #FF00FF;
}</code>```

Test
```

Body:
I have created that toggles a material icon to on/off.
When the icon is off I need to run a delete query.
When the icon is on I need to run a insert query.

I know I need to use AJAX and am still new to it.
What I am having trouble understanding is whether I refernece the current PHP file or some other php file. Iknow I have to write my query and execute it in a PHP file, but not sure to do that. I do not want to reload the pagebecuase I lose other information by doing so.

I basically owuld like to update the icon and execute the required SQL stmnt.

Any help is appreciated.

What I have so far:

JAVASCRIPT:

    //update the favorites icon
function updateFavorites(id){
if($(this).find('#staricon'+id)){
    if($('#staricon'+id).hasClass('star-color')) {
        $('#staricon'+id).removeClass('star-color');
        //update the table
        deleteFavorites();
    }
    else {
        $('#staricon'+id).addClass('star-color');
        addFavorites();
    }
}
}

//delete the item from the table

function deleteFavorite(){

        $.ajax({
            type: "POST",
            url: "somePHPFile.php",
            cache: false,
            data:{id:'#staricon'+id},
        }).done(function( msg ) {  console.log(msg);
        });
}

PHP:

//check to see if this is a favorite
$query = "SELECT * FROM favorites WHERE story_id = " . $story_id;
$result = mysqli_query($conn, $query);
$is_fav = mysqli_num_rows($result);

if ($is_fav > 0) {
echo 'star';
 }
 else {
 echo 'star';
 }

I have update my code to reflect the following:

JAVASCRIPT:

function updateFavorites(id){
if($(this).find('#staricon'+id)){
    if($('#staricon'+id).hasClass('star-color')) {
        $('#staricon'+id).removeClass('star-color');
        $.ajax({
            type: "POST",
            url: "showStoryCards.php",
            data: {
                id: $(this).data(id),
                enabled: !$(this).hasClass('star-color') //delete
            },
        })
    }
    else {
        $('#staricon'+id).addClass('star-color');
        $.ajax({
            type: "POST",
            url: "showStoryCards.php",
            data: {
                id: $(this).data("id"),
                enabled: $(this).hasClass('star-color') //insert
            },
        })

    }
}

PHP:

echo $story_title ;
$query = "SELECT count(*) FROM favorites WHERE story_id = ?";
$sql= $conn->prepare($query);
$sql->bind_param("s", $story_id);
$sql->execute();
$result = $sql->get_result();
$is_fav = mysqli_num_rows($result);
if ($is_fav == 0) {
echo 'star';
}
else {
echo 'star';
}
if (isset($_POST['enabled'])){

if($_POST['enabled']) {  // INSERT query

    $sql = "INSERT INTO favorites VALUES( " . $id . ", '1') ";
    $sql->execute();
} else {// Delete query
}
}

My icons update to the appropriate on /off colors but I still cannot get the query to fire. It does not even appear that the call back to the PHP page is functioning as I cannot retrieve the $_POST.

Body:
Simplify it all.

$(document).ready(function() {

  $('#staricon').on('click', function() {
    // Prevent multiple clicks before the first one finishes.
    // There is probably a more elegant way to do this.
    if(active){
      return;
    }
    active = false;
    //console.log($(this).hasClass('star-color'));
    //console.log($(this).data("id"));
    $.ajax({
      type: "POST",
      url: "somePHPFile.php",
      data: {
        id: $(this).data("id"),
        enabled: !$(this).hasClass('star-color')
      },
    }).done(function(msg) {
      active = true;
      $(this).toggleClass('star-color');
      console.log(msg);
    });
  });

});

/*
PHP
// Use ID and enabled to add or delete from db.
if($_POST['enabled']) {
   // INSERT query
} else {
   // Delete query
}
*/

div.star-color {
  background-color: #FF00FF;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="staricon" data-id="1" class="star-color">Test</div>


问:
How to check if Javascript Map has an object key
Looking at a couple of different docs, all I see is when the Map (ECMAScript6) key is a boolean, string, or integer. Is there a way we could use another customized Object (called with the new CustomObject(x,y) constructor call) to be added as a key?

I am able to add an object as a key, but unable to check if the Map has the said object.

```<code>var myMap = new Map();
myMap.set( new Tuple(1,1), "foo");
myMap.set('bar', "foo");

myMap.has(?);
myMap.has('bar');  // returns true
</code>```

Is there a way around this?

```<code>  var myMap = new Map();
  myMap.set( new Tuple(1,1), "foo");

 for(some conditions) {
 var localData = new Tuple(1,1); //Use directly if exists in myMap?
 map.has(localData) // returns false as this is a different Tuple object. But I need it to return true
}
</code>```

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has

答:
When you set an object to the map, you need to pass the same memory reference when checking if the map has it.

Example:

```<code>const map = new Map();

map.set(new Tuple(1,1));
map.has(new Tuple(1,1)) // False. You are checking a new object, not the same as the one you set.

const myObject = new Tuple(1,1);
map.set(myObject);
map.has(myObject) // True. You are checking the same object.
</code>```

EDIT

If you really have to do this, you could do the following:

```<code>function checkSameObjKey(map, key) {
    const keys = map.keys();
    let anotherKey;

    while(anotherKey = keys.next().value) {
         // YOUR COMPARISON HERE
         if (key.id == anotherKey.id) return true;
    }

    return false;
}

const map = new Map();
map.set({id: 1}, 1);

checkSameObjKey(map, {id: 1}); // True
checkSameObjKey(map, {id: 2}); // False
</code>```

Body:
Looking at a couple of different docs, all I see is when the Map (ECMAScript6) key is a boolean, string, or integer. Is there a way we could use another customized Object (called with the new CustomObject(x,y) constructor call) to be added as a key?

I am able to add an object as a key, but unable to check if the Map has the said object.

var myMap = new Map();
myMap.set( new Tuple(1,1), "foo");
myMap.set('bar', "foo");

myMap.has(?);
myMap.has('bar');  // returns true

Is there a way around this?

  var myMap = new Map();
  myMap.set( new Tuple(1,1), "foo");

 for(some conditions) {
 var localData = new Tuple(1,1); //Use directly if exists in myMap?
 map.has(localData) // returns false as this is a different Tuple object. But I need it to return true
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has

Body:
When you set an object to the map, you need to pass the same memory reference when checking if the map has it.

Example:

const map = new Map();

map.set(new Tuple(1,1));
map.has(new Tuple(1,1)) // False. You are checking a new object, not the same as the one you set.

const myObject = new Tuple(1,1);
map.set(myObject);
map.has(myObject) // True. You are checking the same object.

EDIT

If you really have to do this, you could do the following:

function checkSameObjKey(map, key) {
    const keys = map.keys();
    let anotherKey;

    while(anotherKey = keys.next().value) {
         // YOUR COMPARISON HERE
         if (key.id == anotherKey.id) return true;
    }

    return false;
}

const map = new Map();
map.set({id: 1}, 1);

checkSameObjKey(map, {id: 1}); // True
checkSameObjKey(map, {id: 2}); // False


问:
VHDL: How to rapidly skip over registers that I don't care about?
I have N registers that are M bits wide.  All the registers are filled with values but I only want to sample those registers that fits a certain pattern, such as only look at the registers whose MSB is a 1.  On every rising edge of a clock I want to read one M-bit wide register that meets that pattern.

For example:
There are 256 8-bit registers (reg0 - reg255).  Reg0, Reg3, and Reg255 meets the pattern of the MSB = 1.  On the first rising clock edge, reg0 is sent to the output since it matches the pattern, 2nd rising clock edge Reg3 is sent to the output, and on the 3rd clock edge Reg255 is sent to the output.

I'm very green to HDL so I'd appreciate any assistance.  Is this an application which using a for loop within a clocked process is useful?  Oh, I'm using VHDL to figure this out.

I'm not looking for a complete answer, perhaps just some keywords I should look up.

Thanks,
J

答:
There is one way to do that.

You should use 1 flag (binary register) per register:

This flag that indicate if the pattern is detected in the associated register, it will be use to know which register to send. when the register will be send, this flag will be reset.

At the beginning, you force all register flag to '0' (No pattern detected / No need to send register)

You load data into registers.

A process check if the pattern is detected, in that case set the flag of associated register to '1'

Use amor loop or a BIG if else (not recommended) over flag. If a flag is equal to '1', send the register and reset it. if not, go to the next.
This last step could pass from a register to send to another one in one clock cycle even if they are separate by some other registers (that don't need to be send).

/!\ Be careful, the mechanism is complicate and cause timing constraint, the performance of the clock of your design will be impact and you will use more LUTs.

Best regards, and good luck.


问:
Configuring Webpack build for file:// use in CEF
I have to develop a webapp for a CEF-Browser environment. There is no HTTP server available, everything will be served over file:// protocol.

When developing a Webapp nowadays one doesn't get round working with a framework like react/vue for frontend. The standard webpack build scripts of those build a bundle which only works served over HTTP.

Is it possible to configure webpacks build bundle to work on file:// or is there another way to use react or vue via file://?

答:
I'm suggest read CEF wiki more carefully. You are especially interested in https://bitbucket.org/chromiumembedded/cef/wiki/GeneralUsage.md#markdown-header-request-handling

In short:

You can register custom scheme handler to serve resources over http+custom fake domain.

You can pack resources in zip for example if you like, or leave them at file system as is (but in that case you can expect that some funny users can edit your files, and then report back unexisting errors back to you).

Important helpers already done (but you can write own when need.)

You can... many other things.

Main thing that "file" scheme are more restricted, and for example you can't do XHR requests. But for custom handler you can. Even if dynamic loader for some reason use XHR instead DOM-based loading it will work again same as on http without touching network.

cefclient itself also has usage of custom schemes. Check URL of Tests->Other... in menu. :)

PS: Sorry that my answer doesnt have direct answer for your question. But, custom resource handling in CEF is so common, that i'm just should say about.


问:
Circle-circle intersection points
How do I calculate the intersection points of two circles.  I would expect there to be either two, one or no intersection points in all cases.

I have the x and y coordinates of the centre-point, and the radius for each circle.

An answer in python would be preferred, but any working algorithm would be acceptable.

答:
Here's an implementation in Javascript using vectors. The code is well documented, you should be able to follow it. Here's the original source

See live demo here:

// Let EPS (epsilon) be a small value
var EPS = 0.0000001;

// Let a point be a pair: (x, y)
function Point(x, y) {
  this.x = x;
  this.y = y;
}

// Define a circle centered at (x,y) with radius r
function Circle(x,y,r) {
  this.x = x;
  this.y = y;
  this.r = r;
}

// Due to double rounding precision the value passed into the Math.acos
// function may be outside its domain of [-1, +1] which would return
// the value NaN which we do not want.
function acossafe(x) {
  if (x >= +1.0) return 0;
  if (x <= -1.0) return Math.PI;
  return Math.acos(x);
}

// Rotates a point about a fixed point at some angle 'a'
function rotatePoint(fp, pt, a) {
  var x = pt.x - fp.x;
  var y = pt.y - fp.y;
  var xRot = x * Math.cos(a) + y * Math.sin(a);
  var yRot = y * Math.cos(a) - x * Math.sin(a);
  return new Point(fp.x+xRot,fp.y+yRot);
}

// Given two circles this method finds the intersection
// point(s) of the two circles (if any exists)
function circleCircleIntersectionPoints(c1, c2) {

  var r, R, d, dx, dy, cx, cy, Cx, Cy;

  if (c1.r < c2.r) {
    r  = c1.r;  R = c2.r;
    cx = c1.x; cy = c1.y;
    Cx = c2.x; Cy = c2.y;
  } else {
    r  = c2.r; R  = c1.r;
    Cx = c1.x; Cy = c1.y;
    cx = c2.x; cy = c2.y;
  }

  // Compute the vector <dx, dy>
  dx = cx - Cx;
  dy = cy - Cy;

  // Find the distance between two points.
  d = Math.sqrt( dx*dx + dy*dy );

  // There are an infinite number of solutions
  // Seems appropriate to also return null
  if (d < EPS && Math.abs(R-r) < EPS) return [];

  // No intersection (circles centered at the
  // same place with different size)
  else if (d < EPS) return [];

  var x = (dx / d) * R + Cx;
  var y = (dy / d) * R + Cy;
  var P = new Point(x, y);

  // Single intersection (kissing circles)
  if (Math.abs((R+r)-d) < EPS || Math.abs(R-(r+d)) < EPS) return [P];

  // No intersection. Either the small circle contained within
  // big circle or circles are simply disjoint.
  if ( (d+r) < R || (R+r < d) ) return [];

  var C = new Point(Cx, Cy);
  var angle = acossafe((r*r-d*d-R*R)/(-2.0*d*R));
  var pt1 = rotatePoint(C, P, +angle);
  var pt2 = rotatePoint(C, P, -angle);
  return [pt1, pt2];

}
```

Title: Circle-circle intersection points