问:
Java Scanner, Pattern and difference between useDelimiter() and skip()
What is the difference between java.util.Scanner.useDelimiter() and Scanner.skip() ? For example, I have these strings formatted as shown:

```<code>String line1 = "0---20.000:\t\t \t12%";
String line2 = "0--20.000:\t  12%";
String line3 = "0-20.000: \t  \t12%";
String error = "0-: \t\t12%";
</code>```

And I need this output:

```<code>0
20.000
12
</code>```

I should use a Scanner and a pattern valid for all the three String and I need to control that the tokens are three, otherwise throw an exception.

Could I get this output with both Scanner methods?

And which regex pattern should I use?

It has to be valid also with other numbers.

EDIT: That's my try:

```<code>package scanners;

import java.util.Scanner;

public class ScannerTry {

public static void main(String[] args) {
    String line = "0--20.000:       12%";
    Scanner scan = new Scanner(line);
    scan.useDelimiter("[-*:*\t*%]*");
    while (scan.hasNext()){
        System.out.println(scan.next());
    }
    scan.close();
    }

}
</code>```

But the output is:

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

答:
Here's what you've specified as a delimiter:

```<code>scan.useDelimiter("[-*:*\t*%]*");
</code>```

The square brackets contain a list of characters, and using them means "match a character that is in this list".  The * outside the square brackets means "match 0 or more occurrences of one of these characters."

The reason you're getting one character at a time is that when you match 0 or more occurrences, that means that an empty string (string of length 0) matches the delimiter pattern.  Since every 2 characters in the input file has an empty string between them (there are no characters between them, so an empty string matches), the scanner will consider each character to be its own token.  So the first thing you want to do is to change that last * to +, which means "match 1 or more occurrences".  Now an empty string won't match.

The second problem with your pattern is that * inside square brackets just means that an asterisk is one of the characters you match; the meaning of "0 or more" does not apply inside square brackets.  In fact, whenever you have square brackets, no matter what is inside them, this pattern always matches exactly one character.  So any *, +, or anything else that you want to specify as repeating needs to be outside square brackets.

If you just take out the *:

```<code>scan.useDelimiter("[-:\t%]+");
</code>```

Now this will match any sequence of -, :, tab, and % characters.  It won't match a space, though, and I see spaces in some of your examples.  So you may want to add a space inside the square brackets.  Or you could say this:

```<code>scan.useDelimiter("[-:\\s%]+");
</code>```

since a \s combination inside square brackets means match "any whitespace character", which includes space, tab, and a few others like newlines.  (But only do this if you really do want to match the newlines.)

One other thing: you were right to put - first inside the square brackets.  If you don't, it may have a different meaning:

```<code>"[a-z]"
</code>```

matches any character from a to z, and it doesn't match hyphen.  However:

```<code>"[a\\-z]"
</code>```

matches a, z, or hyphen.  Some programmers (including me), when we want a hyphen to be in the character set, would use this backslash on the hyphen even when it isn't necessary, to avoid any possible confusion:

```<code>scan.useDelimiter("[\\-:\t%]+");
</code>```

Body:
What is the difference between java.util.Scanner.useDelimiter() and Scanner.skip() ? For example, I have these strings formatted as shown:

String line1 = "0---20.000:\t\t \t12%";
String line2 = "0--20.000:\t  12%";
String line3 = "0-20.000: \t  \t12%";
String error = "0-: \t\t12%";

And I need this output:

0
20.000
12

I should use a Scanner and a pattern valid for all the three String and I need to control that the tokens are three, otherwise throw an exception.

Could I get this output with both Scanner methods?

And which regex pattern should I use?

It has to be valid also with other numbers.

EDIT: That's my try:

package scanners;

import java.util.Scanner;

public class ScannerTry {

public static void main(String[] args) {
    String line = "0--20.000:       12%";
    Scanner scan = new Scanner(line);
    scan.useDelimiter("[-*:*\t*%]*");
    while (scan.hasNext()){
        System.out.println(scan.next());
    }
    scan.close();
    }

}

But the output is:

0
2
0
.
0
0
0
1
2

Body:
Here's what you've specified as a delimiter:

scan.useDelimiter("[-*:*\t*%]*");

The square brackets contain a list of characters, and using them means "match a character that is in this list".  The * outside the square brackets means "match 0 or more occurrences of one of these characters."

The reason you're getting one character at a time is that when you match 0 or more occurrences, that means that an empty string (string of length 0) matches the delimiter pattern.  Since every 2 characters in the input file has an empty string between them (there are no characters between them, so an empty string matches), the scanner will consider each character to be its own token.  So the first thing you want to do is to change that last * to +, which means "match 1 or more occurrences".  Now an empty string won't match.

The second problem with your pattern is that * inside square brackets just means that an asterisk is one of the characters you match; the meaning of "0 or more" does not apply inside square brackets.  In fact, whenever you have square brackets, no matter what is inside them, this pattern always matches exactly one character.  So any *, +, or anything else that you want to specify as repeating needs to be outside square brackets.

If you just take out the *:

scan.useDelimiter("[-:\t%]+");

Now this will match any sequence of -, :, tab, and % characters.  It won't match a space, though, and I see spaces in some of your examples.  So you may want to add a space inside the square brackets.  Or you could say this:

scan.useDelimiter("[-:\\s%]+");

since a \s combination inside square brackets means match "any whitespace character", which includes space, tab, and a few others like newlines.  (But only do this if you really do want to match the newlines.)

One other thing: you were right to put - first inside the square brackets.  If you don't, it may have a different meaning:

"[a-z]"

matches any character from a to z, and it doesn't match hyphen.  However:

"[a\\-z]"

matches a, z, or hyphen.  Some programmers (including me), when we want a hyphen to be in the character set, would use this backslash on the hyphen even when it isn't necessary, to avoid any possible confusion:

scan.useDelimiter("[\\-:\t%]+");


来源: stackexchange

问:
Using JS to change three div IDs (carousel-esque), works twice, but then skips a div
I'm trying to create a carousel where all three items are visible, and they switch position when the navigation is clicked (at the moment only working on the left arrow).

I am doing this by assigning each div to a position using an id, and using JS to change the ids.

It works as intended, but when #pos3 (the banana) becomes #pos1, it for some reason gets skipped, and #pos2 and #pos3 just exchange places.

The CSS:

```<code>#pos1{
left:10%;
}

#pos2{
left:30%;
z-index:2;
top:50px;
background:rgba(255,255,255,0.9);
}

#pos3{
left:60%;
}
</code>```

The JS

```<code>document.getElementById("left").onclick = function (){
  document.getElementById("pos2").setAttribute("id", "pos1");
  document.getElementById("pos3").setAttribute("id", "pos2");
  document.getElementById("pos1").setAttribute("id", "pos3");
};
</code>```

Fiddle here

答: Without testing it myself, it looks like when you change #pos2 to #pos1, you end up with 2 elements with the id #pos1, because the original #pos1 has not yet been changed to #pos3. So, when the code gets to the point where it's changing #pos1 to #pos3, it's changing both elements, leaving you without a #pos1.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a carousel where all three items are visible, and they switch position when the navigation is clicked (at the moment only working on the left arrow).

I am doing this by assigning each div to a position using an id, and using JS to change the ids.

It works as intended, but when #pos3 (the banana) becomes #pos1, it for some reason gets skipped, and #pos2 and #pos3 just exchange places.

The CSS:

#pos1{
left:10%;
}

#pos2{
left:30%;
z-index:2;
top:50px;
background:rgba(255,255,255,0.9);
}

#pos3{
left:60%;
}

The JS

document.getElementById("left").onclick = function (){
  document.getElementById("pos2").setAttribute("id", "pos1");
  document.getElementById("pos3").setAttribute("id", "pos2");
  document.getElementById("pos1").setAttribute("id", "pos3");
};

Fiddle here


问:
Facebook SDK title, description, caption and image fields are deprecated
Upgrading the Android SDK from 4.21.1 to 4.22.0

Facebook SDK
The title, description, caption and image field of FBSDKShareLinkContent have been deprecated. Please take appropriate action to remove usage of them.

How to set Content title and description now? Can anyone suggest something to make it work.
Thanks in advance!

答:
You can't, the Android-Sharing facebook documentation says:

When you implement sharing, your app should not pre-fill any content
  to be shared. This is inconsistent with Facebook Platform Policy, see
  Facebook Platform Policy, 2.3.

From Facebook Platform Policy

Don't prefill captions, comments, messages, or the user message parameter of posts with content a person or business didn’t create,
  even if the person can edit or remove the content before sharing. You
  may use our Share Dialogs to prefill a single hashtag in a post, but
  don't prefill any content a person or business didn't create via the
  API.


问:
How to get user's non-command answer in PHP Telegram Bot?
I am writing a new Bot for Telegram for the first time using PHP Telegram Bot.

Imagine I want to show What is your name? for /start command and wait for user's answer, wait for user's answer and then show Hello USER_NAME to him.

I could implement /start commands. But how can I get user's reply that is not in form of /command? Actually I need a listener to a non-command message.

Is there anyone who can help me?

答:
Goto @BotFather, and turn off privacy mode

/setprivacy — Set which messages your bot will receive when added to a group. With privacy mode disabled, the bot will receive all messages.


答: To animate hundreds of icons, it is more efficient to do the animation in the shaders rather than in the javascript. This allows you to leverage the power of the GPU. Here is a demo : http://misterfresh.github.io/mapbox-animation/</p>

Title: MapBox GL JS marker/icon animation slow performance

Body:
I'm using mapbox-gl-js to animate many image from one coordinates to another on the map.
It become slow frame rate when I try to add up to 15 image and above.
Doing performance profile on chrome give me the hint to method Actor.receive, which cost the most computational time.

/**
 * Util.js
 */
 var linesDataSource = {
  "type": "FeatureCollection",
  "features": [{
    "type": "Feature",
    "properties": {},
    "geometry": {
      "type": "LineString",
      "coordinates": [
        [
          151.15684390068054, -33.89568424317427
        ],
        [
          151.15808844566345, -33.89606717952166
        ],
        [
          151.15779876708984, -33.89680633086413
        ],
        [
          151.15740180015564, -33.897794824453406
        ],
        [
          151.1582601070404, -33.8980085512904
        ],
        [
          151.1609423160553, -33.89863191817193
        ],
        [
          151.16222977638245, -33.89621857248702
        ],
        [
          151.16639256477356, -33.89771467675142
        ],
        [
          151.1694610118866, -33.898916884371395
        ],
        [
          151.17089867591858, -33.896298721595166
        ],
        [
          151.17217540740964, -33.899014841282515
        ],
        [
          151.1714780330658, -33.899192944468965
        ],
        [
          151.17132782936093, -33.89878330658397
        ],
        [
          151.1719822883606, -33.8985784869035
        ],
        [
          151.17339849472046, -33.89839147720036
        ],
        [
          151.17376327514648, -33.89825789858986
        ],
        [
          151.17332339286804, -33.897269410368615
        ],
        [
          151.1732053756714, -33.89697553328233
        ],
        [
          151.17341995239258, -33.89662822269281
        ],
        [
          151.17295861244202, -33.896263099778615
        ],
        [
          151.17225050926208, -33.89589797530112
        ],
        [
          151.17136001586914, -33.89561299901295
        ],
        [
          151.17184281349182, -33.894758064434605
        ],
        [
          151.17200374603271, -33.89455323508587
        ],
        [
          151.17257237434387, -33.89148073582115
        ],
        [
          151.17042660713196, -33.89132042847356
        ],
        [
          151.17168188095093, -33.88838140703873
        ],
        [
          151.1716067790985, -33.887606557247125
        ],
        [
          151.16321682929993, -33.888274531623864
        ],
        [
          151.16029858589172, -33.88777577791726
        ],
        [
          151.1591076850891, -33.88790937294604
        ],
        [
          151.15857124328613, -33.8892809364742
        ],
        [
          151.1584746837616, -33.89006467716016
        ],
        [
          151.15894675254822, -33.89009139546571
        ],
        [
          151.15893602371216, -33.889806399775104
        ]
      ]
    }
  }]
}

var PI = Math.PI;
var TWO_PI = Math.PI * 2;

function rotation(start, end) {
  var dx = end[0] - start[0];
  var dy = end[1] - start[1];
  return -Math.atan2(dy, dx) * (180 / PI);
};

function lerp(v0, v1, t) {
  return v0 * (1 - t) + v1 * t
}

function interpolateAngle(fromAngle, toAngle, t) {
  fromAngle = fromAngle * (PI / 180);
  toAngle = toAngle * (PI / 180);

  fromAngle = (fromAngle + TWO_PI) % TWO_PI;
  toAngle = (toAngle + TWO_PI) % TWO_PI;

  var diff = Math.abs(fromAngle - toAngle);
  if (diff < PI) {
    return lerp(fromAngle, toAngle, t) * (180 / PI);
  } else {
    if (fromAngle > toAngle) {
      fromAngle = fromAngle - TWO_PI;
      return lerp(fromAngle, toAngle, t) * (180 / PI);
    } else if (toAngle > fromAngle) {
      toAngle = toAngle - TWO_PI;
      return lerp(fromAngle, toAngle, t) * (180 / PI);
    }
  }
}

/**
 * Car.js
 */
function Car(name, map, path) {
  this.name = name;
  this.map = map;
  this.path = path;
  this.speed = 90; // 30 km/h
  this.accumulatedDistance = 0;
  this.previousPos = this.path.features[0].geometry.coordinates[0];
  this.previousAngle = 0;

  this.animate = function(frameInfo) {

    this.accumulatedDistance += ((frameInfo.deltaTime / 3600) * this.speed);
    var point = turf.along(this.path.features[0], this.accumulatedDistance, 'kilometers');

    this.map.getSource(this.name).setData(point);

    var newAngle = rotation(this.previousPos, point.geometry.coordinates);
    var rotate = interpolateAngle(this.previousAngle, newAngle, 0.1);

    this.map.setLayoutProperty(this.name, 'icon-rotate', rotate);

    this.previousAngle = rotate;
    this.previousPos = point.geometry.coordinates;
  };

  this.init = function() {
    this.map.addSource(this.name, {
      "type": "geojson",
      "data": {
        "type": "FeatureCollection",
        "features": [{
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": this.previousPos
          }
        }]
      }
    });

    this.map.addLayer({
      "id": this.name,
      "type": "symbol",
      "source": this.name,
      "layout": {
        "icon-image": "car",
        "icon-size": 1,
        "icon-rotate": 0,
        "icon-rotation-alignment": "map"
      }
    });
  };
}

/**
 * MapBoxTest.js
 */
var destination = {};
var cars = [];
var style = 'mapbox://styles/mapbox/streets-v9'; //'/TestEmptyProject/mapbox-gl-styles-master/styles/basic-v8.json';
//'http://localhost:8080/styles/osm-bright.json';  // 'http://localhost:8080/styles/fiord-color-gl.json'

mapboxgl.accessToken = 'pk.eyJ1IjoiZW1wZXJvcjE0MTIiLCJhIjoiY2ozYTYxdXFlMDM3dzJyczRsa2M5ZjE3aCJ9.9zQGtkSsjOw6npohN6ba3w';
var map = new mapboxgl.Map({
  container: 'map',
  style: style,
  center: [132.133333, -23.116667],
  zoom: 3
});

// Used to increment the value of the point measurement against the linesData.
var counter = 0;
var linesData = {};

function addCar() {
  var car = new Car("Car_" + counter, map, linesData);
  car.init();
  cars.push(car);
  ++counter;
}

var previousTimeStamp = 0;
// Add a source and layer displaying a point which will be animated in a circle.
function animate(timeStamp) {
  if (timeStamp <= previousTimeStamp) {
    console.log("Wrong timeStamp, now: " + timeStamp + "\t previous: " + previousTimeStamp);
    return;
  }

  var i;
  var frameInfo = {
    "timeStamp": timeStamp,
    "previousTimeStamp": previousTimeStamp,
    "deltaTime": (timeStamp - previousTimeStamp) / 1000
  };
  previousTimeStamp = timeStamp;

  for (i = 0; i < cars.length; ++i) {
    var car = cars[i];
    car.animate(frameInfo);
  }
  requestAnimationFrame(animate);
}

map.on('load', function() {

  console.log("map load");

  map.loadImage('https://maxcdn.icons8.com/office/PNG/40/Transport/railroad_car-40.png', function(error, image) {
    if (error) throw error;
    map.addImage('car', image);
  });

  //fetch('./lines.geojson', {
  //method: 'get'
//}).then(function(response) {
 // return response.json();
//}).then(function(data) {

  linesData = linesDataSource;
  var coordinates = linesData.features[0].geometry.coordinates;

  var bounds = coordinates.reduce(function(bounds, coord) {
    return bounds.extend(coord);
  }, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));

  map.fitBounds(bounds, {
    padding: 20,
    duration: 2000
  });

  map.addSource('lines', {
    "type": "geojson",
    "data": linesData
  });

  map.addLayer({
    "id": "route",
    "source": "lines",
    "type": "line",
    "paint": {
      "line-width": 2,
      "line-color": "#007cbf"
    }
  });
  // }).catch(function(err) {
  //console.log("error: " + err);
//});

document.getElementById('addCar').addEventListener('click', function() {
addCar();
});

});

requestAnimationFrame(animate);

 body {
   margin: 0;
   padding: 0;
 }

 #map {
   position: absolute;
   top: 0;
   bottom: 0;
   width: 100%;
 }

 .overlay {
   position: absolute;
   top: 10px;
   left: 10px;
 }

 .overlay button {
   font: 600 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
   background-color: #3386c0;
   color: #fff;
   display: inline-block;
   margin: 0;
   padding: 10px 20px;
   border: none;
   cursor: pointer;
   border-radius: 3px;
 }

 .overlay button:hover {
   background-color: #4ea0da;
 }

<link href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.css" rel="stylesheet"/>

    <button id='addCar'>Add Car</button>


问:
How do I save a templated array of objects to file?
I have a class called

```<code>Array<T>
</code>```

You can create an array of any type.

```<code>template <typename T>
    class Array
    {
    private:
        T *m_array;
        int m_size;
        ...
</code>```

For example,

```<code>Array <int> myArray(32)
</code>```

is an array of type int with a size of 32. This can store basic types or complex objects. For instance,

```<code>Array<Monster> monsters(32)
</code>```

can hold an array of monster objects. Whatever type is used, I would like to save and load the array from disk.

One of these objects, say Actor, has a member variable (name) of type std::string. So, it is stored as

```<code>Array<Actor> actors(32)
</code>```

I realized today that C's I/O functions know nothing about std::string, so loading std::string from file was causing a crash on shutdown. I want to upgrade my Save/Load functions to C++'s equivalent. My assumption is this will solve my problem with saving and loading objects that have a member variable of type std::string.

My original Save/Load functions:
(Because they're in a header due to how templates work, I should mention they are more formally members of Array, or Array::save() and Array::load().)

```<code>            bool save(const string filename)
        {
            FILE *fOut = NULL;
            int written = 0;

            // Validate the array
            if (!isValidArray())
                return false;

            // Open the file
            fOut = fopen(filename.c_str(), "wb");
            if (fOut == NULL)
                return false;

            // Write the array's size to file.
            fwrite(&m_size, sizeof(int), 1, fOut);

            // Write the array to file.
            written = fwrite(m_array, sizeof(T), m_size, fOut);
            fclose(fOut);

            // Validate if the array was written correctly
            if (written != m_size)
                return false;

            return true;
        }
</code>```

Load:

```<code>bool load(const string filename)
        {
            FILE *fIn = NULL;
            int read = 0;
            int size = 0;

            // Open the file
            fopen_s(&fIn, filename.c_str(), "rb");
            if (fIn == NULL)
                return false;

            // Read the array's size from file.
            fread(&size, sizeof(int), 1, fIn);

            // Rleease the old array
            release();

            // Initialize the new array
            if (!init(size))
                return false;

            // Read the array from file.
            read = fread(m_array, sizeof(T), size, fIn);
            fclose(fIn);

            // Validate if the array was written correctly.
            // If not, clean up the array object.
            if (read != size)
            {
                if (m_array != NULL)
                {
                    delete[] m_array;
                    m_array = NULL;
                    m_size = 0;
                }

                return false;
            }

            return true;
        }
</code>```

Overall, I would like to convert these to C++'s file handling.

This is my C++ attempt with save():

```<code>        bool save(const string filename)
        {
            ofstream fOut;

            // Validate the array
            if (!isValidArray())
                return false;

            // Open the file
            fOut.open(filename.c_str(), std::ios::binary | std::ios::out);
            if (!fOut.is_open())
                return false;

            // Write the array's size to file.
            fOut << m_size;

            // Write the array to file. ????
            fOut.write(m_array, m_size);

            fOut.close();

            return true;
        }
</code>```

So, my problem is how do I save the array to file when its templated type could be a basic data type, struct, or class. My first assumption was this:

```<code>// Write the array to file. ????
fOut.write(m_array, m_size);
</code>```

Any thoughts would be helpful. Thank you.

Finding out I need serialization, I overloaded operator<< for my Actor class, but would like further guidance on how to use it for this purpose. Actor has a std::string that I need to save to file.

```<code>std::ofstream & X2D::operator<<(std::ofstream & output, const Actor & p)
{
    // insert magical code here
    return output;
}
</code>```

答:
This ended up being my solution. Overloading operators << and >> helped my classes remain flexible while saving.

I'll post the code below in case it's useful to anybody. The string saving looks somewhat of a mess, and could possibly be improved, but it successfully saves/loads the length and then saves/loads an std::string.

```<code>std::ostream& operator<<(std::ostream& os, const Monster& obj)
{
int length = obj.m_name.length() + 1;
char buffer[1080];

strcpy_s(buffer, 1080, obj.m_name.c_str());

os << length;
os.write(buffer, strlen(buffer) + 1);
os << endl;

os << obj.m_x << endl;
os << obj.m_y << endl;
os << obj.m_hp << endl;

return os;
 }

 std::istream& operator>>(std::istream& is, Monster& obj)
 {
int length;
char buffer[1080];

is >> length;
is.readsome(buffer, length);

std::string sBuffer(buffer, length);
obj.m_name = sBuffer;

is >> obj.m_x;
is >> obj.m_y;
is >> obj.m_hp;

return is;
 }
</code>```

Body:
I have a class called

Array<T>

You can create an array of any type.

template <typename T>
    class Array
    {
    private:
        T *m_array;
        int m_size;
        ...

For example,

Array <int> myArray(32)

is an array of type int with a size of 32. This can store basic types or complex objects. For instance,

Array<Monster> monsters(32)

can hold an array of monster objects. Whatever type is used, I would like to save and load the array from disk.

One of these objects, say Actor, has a member variable (name) of type std::string. So, it is stored as

Array<Actor> actors(32)

I realized today that C's I/O functions know nothing about std::string, so loading std::string from file was causing a crash on shutdown. I want to upgrade my Save/Load functions to C++'s equivalent. My assumption is this will solve my problem with saving and loading objects that have a member variable of type std::string.

My original Save/Load functions:
(Because they're in a header due to how templates work, I should mention they are more formally members of Array, or Array::save() and Array::load().)

            bool save(const string filename)
        {
            FILE *fOut = NULL;
            int written = 0;

            // Validate the array
            if (!isValidArray())
                return false;

            // Open the file
            fOut = fopen(filename.c_str(), "wb");
            if (fOut == NULL)
                return false;

            // Write the array's size to file.
            fwrite(&m_size, sizeof(int), 1, fOut);

            // Write the array to file.
            written = fwrite(m_array, sizeof(T), m_size, fOut);
            fclose(fOut);

            // Validate if the array was written correctly
            if (written != m_size)
                return false;

            return true;
        }

Load:

bool load(const string filename)
        {
            FILE *fIn = NULL;
            int read = 0;
            int size = 0;

            // Open the file
            fopen_s(&fIn, filename.c_str(), "rb");
            if (fIn == NULL)
                return false;

            // Read the array's size from file.
            fread(&size, sizeof(int), 1, fIn);

            // Rleease the old array
            release();

            // Initialize the new array
            if (!init(size))
                return false;

            // Read the array from file.
            read = fread(m_array, sizeof(T), size, fIn);
            fclose(fIn);

            // Validate if the array was written correctly.
            // If not, clean up the array object.
            if (read != size)
            {
                if (m_array != NULL)
                {
                    delete[] m_array;
                    m_array = NULL;
                    m_size = 0;
                }

                return false;
            }

            return true;
        }

Overall, I would like to convert these to C++'s file handling.

This is my C++ attempt with save():

        bool save(const string filename)
        {
            ofstream fOut;

            // Validate the array
            if (!isValidArray())
                return false;

            // Open the file
            fOut.open(filename.c_str(), std::ios::binary | std::ios::out);
            if (!fOut.is_open())
                return false;

            // Write the array's size to file.
            fOut << m_size;

            // Write the array to file. ????
            fOut.write(m_array, m_size);

            fOut.close();

            return true;
        }

So, my problem is how do I save the array to file when its templated type could be a basic data type, struct, or class. My first assumption was this:

// Write the array to file. ????
fOut.write(m_array, m_size);

Any thoughts would be helpful. Thank you.

Finding out I need serialization, I overloaded operator<< for my Actor class, but would like further guidance on how to use it for this purpose. Actor has a std::string that I need to save to file.

std::ofstream & X2D::operator<<(std::ofstream & output, const Actor & p)
{
    // insert magical code here
    return output;
}

Body:
This ended up being my solution. Overloading operators << and >> helped my classes remain flexible while saving.

I'll post the code below in case it's useful to anybody. The string saving looks somewhat of a mess, and could possibly be improved, but it successfully saves/loads the length and then saves/loads an std::string.

std::ostream& operator<<(std::ostream& os, const Monster& obj)
{
int length = obj.m_name.length() + 1;
char buffer[1080];

strcpy_s(buffer, 1080, obj.m_name.c_str());

os << length;
os.write(buffer, strlen(buffer) + 1);
os << endl;

os << obj.m_x << endl;
os << obj.m_y << endl;
os << obj.m_hp << endl;

return os;
 }

 std::istream& operator>>(std::istream& is, Monster& obj)
 {
int length;
char buffer[1080];

is >> length;
is.readsome(buffer, length);

std::string sBuffer(buffer, length);
obj.m_name = sBuffer;

is >> obj.m_x;
is >> obj.m_y;
is >> obj.m_hp;

return is;
 }


问:
How to inspect dynamic content in browser debugging extensions?
I have popup window, appearing on my site when mouse is hover on some object. Once this happens I can press (in Chrome) Ctrl-Shift-C and activate element selection mode and select any element inside popup window. But once I made selection, web page goes to normal flow and popup window immediately disappears since mouse is not in correct position anymore.

Is it possible to overcome this situation somehow? For example, select element, but not terminate selection mode?

答:
Both Chrome and Firefox have the ability, in their respective DevTools, to set, and keep set, pseudo-classes like hover, active and focus. This allows you to work with the page as if the mouse was interacting with the element(s) for which you change a pseudo-class.

The following show toggling the hover pseudo-class on the Documentation link in the SO top-nav bar.

Here is what it looks like in Chrome:

Here is what it looks like in Firefox:


问:
VueJS v2 Guide. Using v-model on non-value property
I am following along the VueJS guide, and I am looking at https://v2.vuejs.org/v2/guide/components.html#Customizing-Component-v-model at the moment.

I tried to create a minimal example, but haven't been able to make it work.

What changes do I need to make so that the following two HTML statements are interchangeable as the VueJS guide suggests?:

```<code><my-checkbox :checked="chicken" @change="val => { chicken = val }" value="A Bird"></my-checkbox>
</code>```

and

```<code><my-checkbox v-model="chicken" value="Chicken"></my-checkbox>
</code>```

Here's the code I've got so far.

// Components#CustomizingComponentVModel
Vue.component('myCheckbox', {
  model: { prop: 'checked', emit: 'change' },
  props: ['value'],
  methods: {
    uVal: function(checkStatus) {
      this.$emit('change', checkStatus);
    }
  },
  template: '' +
              '<input type="checkbox" @change="uVal($event.target.checked)">' +
              '{{ value }}' +
            ''
});

// Default app
new Vue({
  el: '#app',
  data: function() {
    return { chicken: false };
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>

<!--
     I am trying to create a minimal example of customizing v-model described at
     https://v2.vuejs.org/v2/guide/components.html#Customizing-Component-v-model
-->

<div id="app">
  <my-checkbox :checked="chicken" @change="val => { chicken = val }" value="A Bird"></my-checkbox>
  <!-- VueJS guide suggest that previous line is same as the next one: -->
  <!-- <my-checkbox v-model="chicken" value="Chicken"></my-checkbox> -->
  <!-- If I comment line 9 and uncomment line 11, what changes do I need to make in my code to make this work? Also, why are those changes needed? -->
  <p>Chicken: {{ chicken }}</p>
</div></code>```

答:
Never mind. I just answered my own question. It was merely a case of typo. The model should've read:

```<code>model: { prop: 'checked', event: 'change' }
</code>```

instead of

```<code>model: { prop: 'checked', emit: 'change' }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am following along the VueJS guide, and I am looking at https://v2.vuejs.org/v2/guide/components.html#Customizing-Component-v-model at the moment.

I tried to create a minimal example, but haven't been able to make it work.

What changes do I need to make so that the following two HTML statements are interchangeable as the VueJS guide suggests?:

<my-checkbox :checked="chicken" @change="val => { chicken = val }" value="A Bird"></my-checkbox>

and

<my-checkbox v-model="chicken" value="Chicken"></my-checkbox>

Here's the code I've got so far.

// Components#CustomizingComponentVModel
Vue.component('myCheckbox', {
  model: { prop: 'checked', emit: 'change' },
  props: ['value'],
  methods: {
    uVal: function(checkStatus) {
      this.$emit('change', checkStatus);
    }
  },
  template: '' +
              '<input type="checkbox" @change="uVal($event.target.checked)">' +
              '{{ value }}' +
            ''
});

// Default app
new Vue({
  el: '#app',
  data: function() {
    return { chicken: false };
  }
});

  <my-checkbox :checked="chicken" @change="val => { chicken = val }" value="A Bird"></my-checkbox>

Chicken: {{ chicken }}

Body:
Never mind. I just answered my own question. It was merely a case of typo. The model should've read:

model: { prop: 'checked', event: 'change' }

instead of

model: { prop: 'checked', emit: 'change' }


问:
AWS Route 53 Domain not working on my wifi but okay on LTE
Route 53 Issue? server DNS address could not be found.

Everything was working fine until this morning. I bought  from amazon a few weeks back and had deployed a personal webpage, no issues. Today, I made a small change and added a favicon to the page. Then I redeployed, everything is working. http://34.211.101.154/

Now I'm having issues with route 53. I've checked and double checked my name servers (ns) to make sure that the registered ns match the hosted ns. I have a health check running and it shows that all the endpoints terminate with a success 200.

```<code>Success: HTTP Status Code 200, OK. Resolved IP: 34.211.101.154
</code>```

But still, when i go to the domain name, the request won't resolve on wifi but it is okay on LTE. Does anybody know the issue? Please help!

答: Perhaps the wifi router you're using has cached some DNS configuration. Try resetting the router or using a different wifi network to test the issue. </p>

Body:
Route 53 Issue? server DNS address could not be found.

Everything was working fine until this morning. I bought  from amazon a few weeks back and had deployed a personal webpage, no issues. Today, I made a small change and added a favicon to the page. Then I redeployed, everything is working. http://34.211.101.154/

Now I'm having issues with route 53. I've checked and double checked my name servers (ns) to make sure that the registered ns match the hosted ns. I have a health check running and it shows that all the endpoints terminate with a success 200.

Success: HTTP Status Code 200, OK. Resolved IP: 34.211.101.154

But still, when i go to the domain name, the request won't resolve on wifi but it is okay on LTE. Does anybody know the issue? Please help!


问:
Module vs. component design
What is the difference between module vs. component design?</p>

答:
I'd like to share my idea about this difference.

Both component and module are used to refer to a group of functions or a part of a function. Module is more logical, for example: module Finance, module HR, module Manufacturing... in ERP system. On the other hand, component is more physical. In software, it can be a dll, ocx, exe,...

There is no criteria to measure which one is greater than the other. One component can contain list of modules, and one module also can contain many components. Components are used to model a system in technical view, and module is used to model the system in function view ( functionalities of the system)

Title: Module vs. component design


问:
Maximizing a function in Matlab
I have a function in matlab called function UFamily = CalcUFamily(hh,hw). The value of the function is determined by hh and hw (working hours for husband and wife in a family). I want to get the hh and hw that maximizes the function UFamily.

How shall i proceed? I can't get the fmincon to work.

Thanks for any help! :)

答:
The function for fmincon to minimize should use 'h' (1x2) as its input, while your function CalcUFamily requires two input, hh and hw. You can do something like:</p>

```<code>myFun = @(h) -CalcUFamily(h(1), h(2)); % function to minimize with one input
Uoptimal = fmincon(myFun, [1000 1000], [], [], [], [], lb, ub);
</code>```

Title: Maximizing a function in Matlab

Body:
The function for fmincon to minimize should use 'h' (1x2) as its input, while your function CalcUFamily requires two input, hh and hw. You can do something like:

myFun = @(h) -CalcUFamily(h(1), h(2)); % function to minimize with one input
Uoptimal = fmincon(myFun, [1000 1000], [], [], [], [], lb, ub);


答:
You want to emit the input event instead of the change event, as explained in the documentation:

So for a component to work with v-model, it should (these can be configured in 2.2.0+):

accept a value prop

emit an input event with the new value

Alternatively, as hinted by the note in the parentheses, you can reconfigure your model to use the change event:

```<code>model: {
    prop: 'checked',
    event: 'change',
}
</code>```

Below is a working example using the default model, emitting the input event:

Vue.component('myCheckbox', {
  props: ['value'],
  methods: {
    uVal: function(checkStatus) {
      this.$emit('input', checkStatus);
    }
  },
  template: '' +
              '<input type="checkbox" @change="uVal($event.target.checked)">' +
              '{{ value }}' +
            ''
});

new Vue({
  el: '#app',
  data: {
    chicken: false,
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<div id="app">
  <my-checkbox v-model="chicken" value="Chicken"></my-checkbox>
  <p>Chicken: {{ chicken }}</p>
</div></code>```

Title: VueJS v2 Guide. Using v-model on non-value property

Body:
You want to emit the input event instead of the change event, as explained in the documentation:

So for a component to work with v-model, it should (these can be configured in 2.2.0+):

accept a value prop

emit an input event with the new value

Alternatively, as hinted by the note in the parentheses, you can reconfigure your model to use the change event:

model: {
    prop: 'checked',
    event: 'change',
}

Below is a working example using the default model, emitting the input event:

Vue.component('myCheckbox', {
  props: ['value'],
  methods: {
    uVal: function(checkStatus) {
      this.$emit('input', checkStatus);
    }
  },
  template: '<span>' +
              '<input type="checkbox" @change="uVal($event.target.checked)">' +
              '<label>{{ value }}</label>' +
            '</span>'
});

new Vue({
  el: '#app',
  data: {
    chicken: false,
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<div id="app">
  <my-checkbox v-model="chicken" value="Chicken"></my-checkbox>
  <p>Chicken: {{ chicken }}</p>
</div>


问:
django-paypal unable to handle notification signal
I'm using django standard ipn and unable to handle notification signal.
Payment goes very smoothly only notification part doesn't work.
this is my signals.py

```<code>def show_me_the_money(sender, **kwargs):
    ipn_obj = sender
    if ipn_obj.payment_status == ST_PP_COMPLETED:
        print("yey")
        order = Orders.objects.get(id=38)
        order.paid = True
        order.save()

valid_ipn_received.connect(show_me_the_money)
</code>```

apps.py

```<code>class PaymentConfig(AppConfig):
    name = 'payment'
    verbose_name = 'Payment'

    def ready(self):
        import payment.signals
</code>```

init.py

```<code>default_app_config = 'payment.apps.PaymentConfig'
</code>```

urls.py

```<code>url(r'^payment/', include('payment.urls', namespace='payment')),
</code>```

答: Go to settings/base.py or settings.py and insert into ALLOWED_HOSTS your DNS, or if you don't have any problem you could use just ALLOWED_HOSTS='*'</p>

Body:
I'm using django standard ipn and unable to handle notification signal.
Payment goes very smoothly only notification part doesn't work.
this is my signals.py

def show_me_the_money(sender, **kwargs):
    ipn_obj = sender
    if ipn_obj.payment_status == ST_PP_COMPLETED:
        print("yey")
        order = Orders.objects.get(id=38)
        order.paid = True
        order.save()

valid_ipn_received.connect(show_me_the_money)

apps.py

class PaymentConfig(AppConfig):
    name = 'payment'
    verbose_name = 'Payment'

    def ready(self):
        import payment.signals

init.py

default_app_config = 'payment.apps.PaymentConfig'

urls.py

url(r'^payment/', include('payment.urls', namespace='payment')),


问:
Cleaner / smarter way to use a for loop
I have a DataGridView with 35 columns and I was wondering how to programmatically do a FOR loop to set the header text alignment to center only from column 4 through 20.  I know how to do it column by column but I'm sure there must be a faster / smarter way to do it.  See below the code I'm using:</p>

```<code>alunos_detDataGridView.Columns[4].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter;
alunos_detDataGridView.Columns[5].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter;
</code>```

答:
Use for loop to increase variable (iin this case) progressively from 4 to 20 and use this variable as index of column:

```<code>for(int i = 4; i <= 20; i++)
{
       alunos_detDataGridView.Columns[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter;
}
</code>```

Title: Cleaner / smarter way to use a for loop

Body:
I have a DataGridView with 35 columns and I was wondering how to programmatically do a FOR loop to set the header text alignment to center only from column 4 through 20.  I know how to do it column by column but I'm sure there must be a faster / smarter way to do it.  See below the code I'm using:

alunos_detDataGridView.Columns[4].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter;
alunos_detDataGridView.Columns[5].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter;

Body:
Use for loop to increase variable (iin this case) progressively from 4 to 20 and use this variable as index of column:

for(int i = 4; i <= 20; i++)
{
       alunos_detDataGridView.Columns[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter;
}


问:
Dynamically insert rows and columns - React Native

What I would like to have happen

I would like my app to organize x number of photos in rows of three.

For example if I have nine images, I would like to be able to have them placed like this:

```<code>XXX
XXX
XXX
</code>```

Now If I have 12 images I would like them to be placed like this:

```<code>XXX
XXX
XXX
XXX
</code>```

And for two images:

```<code>XX
</code>```

And so on and so forth.

What I have tried

First try

With no styling the images pop up like this:

```<code>X
X
X
X
X
</code>```

Second try

And if I use {flexDirection: 'row'} they pop up like this:

```<code>XXXXXXXXXXX
</code>```

Even after they have left the screen.

Third Try

I tried using a for loop to loop through every third photo, but it complained that there was no closing/opening View:

```<code>if (x % 3 === 0) {
  return (
    </View>
    <View style={{flexDirection: 'row'}}>
        <Image
        />
  )
}else {
  return (
      <Image
      />
  )
}
</code>```

This way also does not work because I do not know if the number of photos will be a multiple of three, and if they aren't I have no way of closing the View

答:
You should be setting flexDirection: row, then using flexWrap as documented here. What it will do is treat the Views like your second attempt, but when there's not enough room for the next image, it will bring it down to the next row.

This will allow you to create a more responsive application as if there is more or less screen space (small phone versus large phone), you can have more or less on each row for the ideal experience.

Body:
What I would like to have happen

I would like my app to organize x number of photos in rows of three.

For example if I have nine images, I would like to be able to have them placed like this:

XXX
XXX
XXX

Now If I have 12 images I would like them to be placed like this:

XXX
XXX
XXX
XXX

And for two images:

XX

And so on and so forth.

What I have tried

First try

With no styling the images pop up like this:

X
X
X
X
X

Second try

And if I use {flexDirection: 'row'} they pop up like this:

XXXXXXXXXXX

Even after they have left the screen.

Third Try

I tried using a for loop to loop through every third photo, but it complained that there was no closing/opening View:

if (x % 3 === 0) {
  return (
    </View>
    <View style={{flexDirection: 'row'}}>
        <Image
        />
  )
}else {
  return (
      <Image
      />
  )
}

This way also does not work because I do not know if the number of photos will be a multiple of three, and if they aren't I have no way of closing the View


问:
angular 2 + firebase app gets user logged out on refresh
Im new to all that means Angular2, Firebase, SPAs, etc. These days I have a task to add some new functionality to an Angular2 (with Firebase email&pw auth) app. The app consists mainly of a blog(the main page), a shop(/shop) and admin area(/admin) form which you can manage both blog posts and shop items. One of a requirements of the task is to make the app to maintain the session if you hit refresh on the browser, so that if you are on any "page" from /admin area, you wont be brought back to login form, which currently happens. I literally spent hours on the web looking for a solution and I failed to find one. I tried to save a localstorage token but found that firebase already does that, and many other things, but still couldnt find a solution. App already have a mechanism to check for logged in user, and a route guard, used on the manage blog (/admin/bog-admin) and manage products(/admin/product-admin) sections in the admin area. I will try to post what I think is relevant for this problem, feel free to ask for more code snippets if I forgot anything. Also please explain briefly your solution since I really need to understand it too.

user.service.ts :

import { Injectable } from '@angular/core';
import {
  CanActivate,
  Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';
import * as firebase from 'firebase';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';

@Injectable()
export class UserService implements CanActivate {
  userLoggedIn: boolean = false;
  loggedInUser: string;
  authUser: any;

  constructor(private router: Router, public toastr: ToastsManager) {
    firebase.initializeApp({
      apiKey: "AIzaSyB7VgN55gflpKAlmM41r2DCdUsy69JkLsk",
      authDomain: "angulargigabyte-966ef.firebaseapp.com",
      databaseURL: "https://angulargigabyte-966ef.firebaseio.com",
      projectId: "angulargigabyte-966ef",
      storageBucket: "angulargigabyte-966ef.appspot.com",
      messagingSenderId: "154241614671"
    })
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;
    return this.verifyLogin(url);
  }

  verifyLogin(url: string): boolean {
    if (this.userLoggedIn) {
      return true;
    }

    this.router.navigate(['/admin/login']);
    return false;
  }

  register(email: string, password: string) {
    firebase.auth().createUserWithEmailAndPassword(email, password)
      .catch(function (error) {
        alert(`${error.message} Please Try Again!`);
      });
  }

  verifyUser() {
    this.authUser = firebase.auth().currentUser;

    if (this.authUser) {

      this.toastr.success('Alert', `Welcome ${this.authUser.email}`);
      this.loggedInUser = this.authUser.email;
      this.userLoggedIn = true;
      this.router.navigate(['/admin']);
    }
  }

  login(loginEmail: string, loginPassword: string) {
    firebase.auth().signInWithEmailAndPassword(loginEmail, loginPassword)
      .catch(function (error) {
        alert(`${error.message} Unable to login. Try again!`);
      });
  }

  logout() {
    this.userLoggedIn = false;
    firebase.auth().signOut().then(function () {

    }, function (error) {
      alert(`${error.message} Unable to logout. Try again!`);
    });
  }

}
```

<p><br>
<strong>login.component.ts</strong>
</p>

```import { Component } from '@angular/core';
import {UserService} from '../adminShared/user.service';
import { Router } from '@angular/router';

@Component({
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
 })

export class LoginComponent {
  email: string;
  password1: string;

  constructor(private userSVC: UserService, private router: Router){}

  login(){
    this.userSVC.login(this.email, this.password1);
    this.userSVC.verifyUser();
  }

  signup(){
    this.router.navigate(['/admin/signup']);
  }

  cancel(){
    this.router.navigate(['']);
  }

}
```

答:
Why you dont use angularfire2? (https://github.com/angular/angularfire2)

You could use the Observable authState, like:

```<code>afAuth.authState.subscribe((resp) => {
  if (resp.uid){
    //user is already logged
  }
});
</code>```

More info in https://github.com/angular/angularfire2/blob/master/docs/5-user-authentication.md

Body:
Im new to all that means Angular2, Firebase, SPAs, etc. These days I have a task to add some new functionality to an Angular2 (with Firebase email&pw auth) app. The app consists mainly of a blog(the main page), a shop(/shop) and admin area(/admin) form which you can manage both blog posts and shop items. One of a requirements of the task is to make the app to maintain the session if you hit refresh on the browser, so that if you are on any "page" from /admin area, you wont be brought back to login form, which currently happens. I literally spent hours on the web looking for a solution and I failed to find one. I tried to save a localstorage token but found that firebase already does that, and many other things, but still couldnt find a solution. App already have a mechanism to check for logged in user, and a route guard, used on the manage blog (/admin/bog-admin) and manage products(/admin/product-admin) sections in the admin area. I will try to post what I think is relevant for this problem, feel free to ask for more code snippets if I forgot anything. Also please explain briefly your solution since I really need to understand it too.

user.service.ts :

import { Injectable } from '@angular/core';
import {
  CanActivate,
  Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';
import * as firebase from 'firebase';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';

@Injectable()
export class UserService implements CanActivate {
  userLoggedIn: boolean = false;
  loggedInUser: string;
  authUser: any;

  constructor(private router: Router, public toastr: ToastsManager) {
    firebase.initializeApp({
      apiKey: "AIzaSyB7VgN55gflpKAlmM41r2DCdUsy69JkLsk",
      authDomain: "angulargigabyte-966ef.firebaseapp.com",
      databaseURL: "https://angulargigabyte-966ef.firebaseio.com",
      projectId: "angulargigabyte-966ef",
      storageBucket: "angulargigabyte-966ef.appspot.com",
      messagingSenderId: "154241614671"
    })
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;
    return this.verifyLogin(url);
  }

  verifyLogin(url: string): boolean {
    if (this.userLoggedIn) {
      return true;
    }

    this.router.navigate(['/admin/login']);
    return false;
  }

  register(email: string, password: string) {
    firebase.auth().createUserWithEmailAndPassword(email, password)
      .catch(function (error) {
        alert(`${error.message} Please Try Again!`);
      });
  }

  verifyUser() {
    this.authUser = firebase.auth().currentUser;

    if (this.authUser) {

      this.toastr.success('Alert', `Welcome ${this.authUser.email}`);
      this.loggedInUser = this.authUser.email;
      this.userLoggedIn = true;
      this.router.navigate(['/admin']);
    }
  }

  login(loginEmail: string, loginPassword: string) {
    firebase.auth().signInWithEmailAndPassword(loginEmail, loginPassword)
      .catch(function (error) {
        alert(`${error.message} Unable to login. Try again!`);
      });
  }

  logout() {
    this.userLoggedIn = false;
    firebase.auth().signOut().then(function () {

    }, function (error) {
      alert(`${error.message} Unable to logout. Try again!`);
    });
  }

}

login.component.ts

import { Component } from '@angular/core';
import {UserService} from '../adminShared/user.service';
import { Router } from '@angular/router';

@Component({
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
 })

export class LoginComponent {
  email: string;
  password1: string;

  constructor(private userSVC: UserService, private router: Router){}

  login(){
    this.userSVC.login(this.email, this.password1);
    this.userSVC.verifyUser();
  }

  signup(){
    this.router.navigate(['/admin/signup']);
  }

  cancel(){
    this.router.navigate(['']);
  }

}

Body:
Why you dont use angularfire2? (https://github.com/angular/angularfire2)

You could use the Observable authState, like:

afAuth.authState.subscribe((resp) => {
  if (resp.uid){
    //user is already logged
  }
});

More info in https://github.com/angular/angularfire2/blob/master/docs/5-user-authentication.md


问:
Easy way to store and retrieve objects in Java without using a relational DB?
Do you know of an "easy" way to store and retrieve objects in Java without using a relational DB / ORM like Hibernate?

[Note that I am not considering serialization as-is for this purpose, as it won't allow to retrieve arbitrary objects in the middle of an object graph. Neither am I considering DB4O because of its restrictive license. Thanks.]

"Easy" meaning: not having to handle low-level details such as key/value pairs to rebuild an object graph (as with BerkeleyDB or traditional caches). The same applies for rebuilding objects from a document- or column-oriented DB (CouchDB, HBase, ..., even Lucene).

Perhaps there are interesting projects out there that provide a layer of integration between the mentioned storage systems and the object model (like ORM would be for RDBMSs) that I am not aware of.

Anyone successfully using those in production, or experimenting with persistence strategies other than relational DBs? How about RDF stores?

Update: I came across a very interesting article: A list of distributed key-value stores

答:
Object Serialization (aka storing things to a file)

Hibernate (uses a relational database but it is fairly transparent to the developer)

I would suggest Hibernate because it will deal with most of the ugly details that bog developers down when using a database while still allowing for the optimizations that have been made to database software over the years.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Matt Campbell


问:
Streaming video over with C#
Greeting

Is there any example code to show how to stream video over ip C# windows app???

Title: Streaming video over with C#


问:
Update TextBox while in Background Worker
Unable to update textbox value while in background worker,
value to be updated is sum of column("TaxableValue") of a datatable created inside background worker.
No Error message is prompted

On Button Click following event is raised

Private Sub btnCalcTax_Click(sender As Object, e As EventArgs) Handles btnCalcTax.Click
        BackgroundWorker1.RunWorkerAsync()
    End Sub
```

<p>I have created a function to calculate TAX.</p>

<pre class="lang-vb prettyprint-override"><code>Public Sub TAXCALC(itemname As String, rackrate As Double, discountedrate As Double, billdate As Date)
    Dim finalfdtaxcalcdt As New DataTable
    finalfdtaxcalcdt.Columns.Clear()
    finalfdtaxcalcdt.Rows.Clear()
    Dim outlettyp As String = "POS"
    Dim taxcount As New DataTable
    Dim tax As New DataTable
    If finalfdtaxcalcdt.Columns.Count = 0 Then
        finalfdtaxcalcdt.Columns.Add("TaxID")
        finalfdtaxcalcdt.Columns.Add("TaxName")
        finalfdtaxcalcdt.Columns.Add("TaxableValue")
        finalfdtaxcalcdt.Columns.Add("TaxRate")
        finalfdtaxcalcdt.Columns.Add("SalesAmount")
        finalfdtaxcalcdt.Columns.Add("TaxAmount")
        finalfdtaxcalcdt.Columns.Add("SalesID")
        finalfdtaxcalcdt.Columns.Add("PurchaseID")
        finalfdtaxcalcdt.Columns.Add("TaxClassID")
    End If

    For i = 0 To BodyGridView.RowCount - 1
        If IsDBNull(BodyGridView.GetRowCellValue(i, "Particulars")) Then
            Exit Sub
        End If
        If BodyGridView.GetRowCellValue(i, "Particulars") <> "# End of List" Then
            Dim tempdt As New DataTable

            If isinterstate Then
                GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select Distinct(TaxClassid) from mstitemTaxClass where ApplyFrom = (SELECT MAX(ApplyFrom) FROM dbo.MstItemTaxClass WHERE ApplyFrom <= '" + billdate.ToString("yyyy-MM-dd") + "' and ItemId = '" + GetDataFromSql("Select ITEM_ID from MStItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars") + "'", con) + "')) and IsInterState = 'TRUE'", tempdt)
                'GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select TaxClass_Id from MstItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars").ToString + "') and IsInterState = 'True'", tempdt)
            Else
                GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select Distinct(TaxClassid) from mstitemTaxClass where ApplyFrom = (SELECT MAX(ApplyFrom) FROM dbo.MstItemTaxClass WHERE ApplyFrom <= '" + billdate.ToString("yyyy-MM-dd") + "' and ItemId = '" + GetDataFromSql("Select ITEM_ID from MStItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars") + "'", con) + "')) and IsInterState = 'False'", tempdt)
                'GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select TaxClass_Id from MstItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars").ToString + "') and IsInterState = 'False'", tempdt)
            End If

            Dim sum As Double = tempdt.Compute("SUM(TaxRate)", String.Empty)

            For j = 0 To tempdt.Rows.Count - 1
                If finalfdtaxcalcdt.Select("TaxID = '" + tempdt.Rows(j).Item(0).ToString + "'").Count = 0 Then
                    finalfdtaxcalcdt.Rows.Add()
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxID") = tempdt.Rows(j).Item("Tax_ID").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxName") = tempdt.Rows(j).Item("TaxName").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxRate") = tempdt.Rows(j).Item("TaxRate").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount") = Double.Parse(BodyGridView.GetRowCellValue(i, "Amount"))
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxAmount") = Math.Round((Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount")) / (1 + (Double.Parse(sum) * 0.01))) * (Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxRate")) * 0.01), 2)
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxableValue") = Math.Round(Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount")) / (1 + (sum * 0.01)), 2)
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesID") = tempdt.Rows(j).Item("SalesAc_ID").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxClassID") = tempdt.Rows(j).Item("TaxClassId").ToString
                    'finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("PurchaseID") = tempdt.Rows(j).Item("TaxRate").ToString
                Else
                    Dim index As Integer = finalfdtaxcalcdt.Rows.IndexOf(finalfdtaxcalcdt.Select("TaxId = '" + tempdt.Rows(j).Item(0).ToString + "'").FirstOrDefault())
                    finalfdtaxcalcdt.Rows(index).Item("SalesAmount") = Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) + Double.Parse(BodyGridView.GetRowCellValue(i, "Amount"))
                    finalfdtaxcalcdt.Rows(index).Item("TaxAmount") = Math.Round((Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) / (1 + (Double.Parse(sum) * 0.01))) * (Double.Parse(finalfdtaxcalcdt.Rows(index).Item("TaxRate")) * 0.01), 2)
                    finalfdtaxcalcdt.Rows(index).Item("TaxableValue") = Math.Round(Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) / (1 + (sum * 0.01)), 2)
                End If
            Next
        End If
    Next
    '        MsgBox(finalfdtaxcalcdt.Compute("Sum(TaxAmount)", String.Empty).ToString + "1")
    '        TaxGridControl.DataSource = finalfdtaxcalcdt
    ''       TaxGridView.Columns("TaxID").Visible = False
    '     TaxGridView.Columns("SalesAmount").Visible = False
    '    TaxGridView.Columns("SalesID").Visible = False
    '   TaxGridView.Columns("PurchaseID").Visible = False
    '  TaxGridView.Columns("TaxClassID").Visible = False
    Dim k As String = finalfdtaxcalcdt.Compute("Sum(TaxAmount)", String.Empty)
    TextBox1.Invoke(DirectCast(Sub() TextBox1.Text = k.ToString, MethodInvoker))
End Sub
</code>```

I am unable to update sum of column("TaxableValue") to Textbox1.text

Code For BackgroundWorker_DoWork is

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            TAXCALC()
 End Sub
```

答:
Unless I'm missing something you should be returning the value from the taxCalc method (convert to functions first obviously), setting e.result in the do work method and the obtain the result in the RunWorkerCompleted.

When in doubt read msdn

If your operation produces a result, you can assign the result to the DoWorkEventArgs.Result property. This will be available to the RunWorkerCompleted event handler in the RunWorkerCompletedEventArgs.Result property.

Body:
Unable to update textbox value while in background worker,
value to be updated is sum of column("TaxableValue") of a datatable created inside background worker.
No Error message is prompted

On Button Click following event is raised

Private Sub btnCalcTax_Click(sender As Object, e As EventArgs) Handles btnCalcTax.Click
        BackgroundWorker1.RunWorkerAsync()
    End Sub

I have created a function to calculate TAX.

Public Sub TAXCALC(itemname As String, rackrate As Double, discountedrate As Double, billdate As Date)
    Dim finalfdtaxcalcdt As New DataTable
    finalfdtaxcalcdt.Columns.Clear()
    finalfdtaxcalcdt.Rows.Clear()
    Dim outlettyp As String = "POS"
    Dim taxcount As New DataTable
    Dim tax As New DataTable
    If finalfdtaxcalcdt.Columns.Count = 0 Then
        finalfdtaxcalcdt.Columns.Add("TaxID")
        finalfdtaxcalcdt.Columns.Add("TaxName")
        finalfdtaxcalcdt.Columns.Add("TaxableValue")
        finalfdtaxcalcdt.Columns.Add("TaxRate")
        finalfdtaxcalcdt.Columns.Add("SalesAmount")
        finalfdtaxcalcdt.Columns.Add("TaxAmount")
        finalfdtaxcalcdt.Columns.Add("SalesID")
        finalfdtaxcalcdt.Columns.Add("PurchaseID")
        finalfdtaxcalcdt.Columns.Add("TaxClassID")
    End If

    For i = 0 To BodyGridView.RowCount - 1
        If IsDBNull(BodyGridView.GetRowCellValue(i, "Particulars")) Then
            Exit Sub
        End If
        If BodyGridView.GetRowCellValue(i, "Particulars") <> "# End of List" Then
            Dim tempdt As New DataTable

            If isinterstate Then
                GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select Distinct(TaxClassid) from mstitemTaxClass where ApplyFrom = (SELECT MAX(ApplyFrom) FROM dbo.MstItemTaxClass WHERE ApplyFrom <= '" + billdate.ToString("yyyy-MM-dd") + "' and ItemId = '" + GetDataFromSql("Select ITEM_ID from MStItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars") + "'", con) + "')) and IsInterState = 'TRUE'", tempdt)
                'GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select TaxClass_Id from MstItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars").ToString + "') and IsInterState = 'True'", tempdt)
            Else
                GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select Distinct(TaxClassid) from mstitemTaxClass where ApplyFrom = (SELECT MAX(ApplyFrom) FROM dbo.MstItemTaxClass WHERE ApplyFrom <= '" + billdate.ToString("yyyy-MM-dd") + "' and ItemId = '" + GetDataFromSql("Select ITEM_ID from MStItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars") + "'", con) + "')) and IsInterState = 'False'", tempdt)
                'GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select TaxClass_Id from MstItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars").ToString + "') and IsInterState = 'False'", tempdt)
            End If

            Dim sum As Double = tempdt.Compute("SUM(TaxRate)", String.Empty)

            For j = 0 To tempdt.Rows.Count - 1
                If finalfdtaxcalcdt.Select("TaxID = '" + tempdt.Rows(j).Item(0).ToString + "'").Count = 0 Then
                    finalfdtaxcalcdt.Rows.Add()
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxID") = tempdt.Rows(j).Item("Tax_ID").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxName") = tempdt.Rows(j).Item("TaxName").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxRate") = tempdt.Rows(j).Item("TaxRate").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount") = Double.Parse(BodyGridView.GetRowCellValue(i, "Amount"))
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxAmount") = Math.Round((Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount")) / (1 + (Double.Parse(sum) * 0.01))) * (Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxRate")) * 0.01), 2)
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxableValue") = Math.Round(Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount")) / (1 + (sum * 0.01)), 2)
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesID") = tempdt.Rows(j).Item("SalesAc_ID").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxClassID") = tempdt.Rows(j).Item("TaxClassId").ToString
                    'finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("PurchaseID") = tempdt.Rows(j).Item("TaxRate").ToString
                Else
                    Dim index As Integer = finalfdtaxcalcdt.Rows.IndexOf(finalfdtaxcalcdt.Select("TaxId = '" + tempdt.Rows(j).Item(0).ToString + "'").FirstOrDefault())
                    finalfdtaxcalcdt.Rows(index).Item("SalesAmount") = Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) + Double.Parse(BodyGridView.GetRowCellValue(i, "Amount"))
                    finalfdtaxcalcdt.Rows(index).Item("TaxAmount") = Math.Round((Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) / (1 + (Double.Parse(sum) * 0.01))) * (Double.Parse(finalfdtaxcalcdt.Rows(index).Item("TaxRate")) * 0.01), 2)
                    finalfdtaxcalcdt.Rows(index).Item("TaxableValue") = Math.Round(Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) / (1 + (sum * 0.01)), 2)
                End If
            Next
        End If
    Next
    '        MsgBox(finalfdtaxcalcdt.Compute("Sum(TaxAmount)", String.Empty).ToString + "1")
    '        TaxGridControl.DataSource = finalfdtaxcalcdt
    ''       TaxGridView.Columns("TaxID").Visible = False
    '     TaxGridView.Columns("SalesAmount").Visible = False
    '    TaxGridView.Columns("SalesID").Visible = False
    '   TaxGridView.Columns("PurchaseID").Visible = False
    '  TaxGridView.Columns("TaxClassID").Visible = False
    Dim k As String = finalfdtaxcalcdt.Compute("Sum(TaxAmount)", String.Empty)
    TextBox1.Invoke(DirectCast(Sub() TextBox1.Text = k.ToString, MethodInvoker))
End Sub

I am unable to update sum of column("TaxableValue") to Textbox1.text

Code For BackgroundWorker_DoWork is

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            TAXCALC()
 End Sub


问:
Multiplying numpy 2d Array with 1d Array
I have a numpy 2d array:

```<code>[[1,1,1],
[1,1,1],
[1,1,1],
[1,1,1]]
</code>```

How can I get it so that it multiplies the indices from top to bottom with the corresponding values from a 1d array when the row length of the 2d array is smaller than length of 1d array ? For example multiply above  with this:

```<code>[10, 20, 30, 40]
</code>```

to get this:

```<code> [[10, 10, 10],
 [20, 20, 20],
 [30, 30, 30]
 [40, 40, 40]]
</code>```

Probably a duplicate, but I couldnt find exact thing I am looking for. Thanks in advance.

答:
* in numpy does element-wise multiplication, for example multiply 1d array by another 1d array:

```<code>In [52]: np.array([3,4,5]) * np.array([1,2,3])
Out[52]: array([ 3,  8, 15])
</code>```

When you multiply a 2d array by 1d array, same thing happens for every row of 2d array:

```<code>In [53]: np.array([[3,4,5],[4,5,6]]) * np.array([1,2,3])
Out[53]:
array([[ 3,  8, 15],
       [ 4, 10, 18]])
</code>```

For your specific example:

```<code>In [66]: ones = np.ones(12, dtype=np.int).reshape(4,3)

In [67]: a = np.array([10, 20, 30, 40])

In [68]: (ones.T * a).T
Out[68]:
array([[10, 10, 10],
       [20, 20, 20],
       [30, 30, 30],
       [40, 40, 40]])
</code>```

Body:
I have a numpy 2d array:

[[1,1,1],
[1,1,1],
[1,1,1],
[1,1,1]]

How can I get it so that it multiplies the indices from top to bottom with the corresponding values from a 1d array when the row length of the 2d array is smaller than length of 1d array ? For example multiply above  with this:

[10, 20, 30, 40]

to get this:

 [[10, 10, 10],
 [20, 20, 20],
 [30, 30, 30]
 [40, 40, 40]]

Probably a duplicate, but I couldnt find exact thing I am looking for. Thanks in advance.

Body:
* in numpy does element-wise multiplication, for example multiply 1d array by another 1d array:

In [52]: np.array([3,4,5]) * np.array([1,2,3])
Out[52]: array([ 3,  8, 15])

When you multiply a 2d array by 1d array, same thing happens for every row of 2d array:

In [53]: np.array([[3,4,5],[4,5,6]]) * np.array([1,2,3])
Out[53]:
array([[ 3,  8, 15],
       [ 4, 10, 18]])

For your specific example:

In [66]: ones = np.ones(12, dtype=np.int).reshape(4,3)

In [67]: a = np.array([10, 20, 30, 40])

In [68]: (ones.T * a).T
Out[68]:
array([[10, 10, 10],
       [20, 20, 20],
       [30, 30, 30],
       [40, 40, 40]])


问:
Inheriting properties among case class
What's the best way to inherit some properties from a case class?

Let's say there's a case class with some properties

```<code>case class aggregations (aggregation1: Int, aggregation2: Int)
</code>```

Two other case classes (case class A & case class B) will have the above parameters plus some extra fields. I'm trying to avoid code duplication and wondering what's the best strategy.

Found a thread discussing the same Scala case class inheritance but not sure whether composition/inheritance is the most suitable option here.

答:
1) I tend to define trait when properties are shared in scala, though I would define interface and then abstract class in java.

parent class with shared members m1, m2

```<code>scala> trait Parent { def m1: Int, def m2: Int}
</code>```

child classes with their own members

```<code>scala> case class Child1(val m1: Int, val m2: Int, val m3: Int) extends Parent
defined class Child1

scala> case class Child2(val m1: Int, val m2: Int, val m4: String) extends Parent
defined class Child2
</code>```

using child classes

```<code>scala> Child1(1, 2, 3) == Child1(1, 2, 3)
res2: Boolean = true

scala> Child2(1, 2, "urayagppd") == Child2(1, 2, "prayagupd")
res4: Boolean = false
</code>```

Also described in the post you mentioned.

NOTE : case-to-case inheritance is prohibited in scala.

```<code>scala> case class A(m1: Int)
defined class A

scala> case class B(m1: Int, m2: Int) extends A(m1)
<console>:13: error: case class B has case ancestor A, but case-to-case inheritance is prohibited. To overcome this limitation, use extractors to pattern match on non-leaf nodes.
       case class B(m1: Int, m2: Int) extends A(m1)
</code>```

2) If you don't like explicit overriding parent properties in child classes, use composition.

parent class

```<code>scala> trait Parent
defined trait Parent

scala> case class ParentClass(val m1: Int, val m2: Int) extends Parent
defined class ParentClass
</code>```

Child classes

```<code>scala> case class Child1(parent: ParentClass, val newMember: Int) extends Parent
defined class Child1

scala> Child1(ParentClass(100, 200), 400)
res0: Child1 = Child1(ParentClass(100,200),400)

scala> case class Child2(parent: ParentClass, val newMember2: String) extends Parent
defined class Child2

scala> Child2(ParentClass(100, 200), "inheritence sucks")
res2: Child2 = Child2(ParentClass(100,200),inheritence sucks)
</code>```

Title: Inheriting properties among case class

Body:
What's the best way to inherit some properties from a case class?

Let's say there's a case class with some properties

case class aggregations (aggregation1: Int, aggregation2: Int)

Two other case classes (case class A & case class B) will have the above parameters plus some extra fields. I'm trying to avoid code duplication and wondering what's the best strategy.

Found a thread discussing the same Scala case class inheritance but not sure whether composition/inheritance is the most suitable option here.

Body:
1) I tend to define trait when properties are shared in scala, though I would define interface and then abstract class in java.

parent class with shared members m1, m2

scala> trait Parent { def m1: Int, def m2: Int}

child classes with their own members

scala> case class Child1(val m1: Int, val m2: Int, val m3: Int) extends Parent
defined class Child1

scala> case class Child2(val m1: Int, val m2: Int, val m4: String) extends Parent
defined class Child2

using child classes

scala> Child1(1, 2, 3) == Child1(1, 2, 3)
res2: Boolean = true

scala> Child2(1, 2, "urayagppd") == Child2(1, 2, "prayagupd")
res4: Boolean = false

Also described in the post you mentioned.

NOTE : case-to-case inheritance is prohibited in scala.

scala> case class A(m1: Int)
defined class A

scala> case class B(m1: Int, m2: Int) extends A(m1)
<console>:13: error: case class B has case ancestor A, but case-to-case inheritance is prohibited. To overcome this limitation, use extractors to pattern match on non-leaf nodes.
       case class B(m1: Int, m2: Int) extends A(m1)

2) If you don't like explicit overriding parent properties in child classes, use composition.

parent class

scala> trait Parent
defined trait Parent

scala> case class ParentClass(val m1: Int, val m2: Int) extends Parent
defined class ParentClass

Child classes

scala> case class Child1(parent: ParentClass, val newMember: Int) extends Parent
defined class Child1

scala> Child1(ParentClass(100, 200), 400)
res0: Child1 = Child1(ParentClass(100,200),400)

scala> case class Child2(parent: ParentClass, val newMember2: String) extends Parent
defined class Child2

scala> Child2(ParentClass(100, 200), "inheritence sucks")
res2: Child2 = Child2(ParentClass(100,200),inheritence sucks)


问:
IntelliJ inspection gives "Cannot resolve symbol" but still compiles code
Platform: IntelliJ Community Edition 10.0.3

SDK: jdk1.6.0_21

OS: Windows 7

So I have a strange situation with IntelliJ that has me completely stumped.  I setup a Maven project and add log4j as a dependency in the pom.xml file.  The IDEA inspections run fine and my unit tests all compile and run.

I then added hunnysoft's jmime library to my local maven repository using the mvn install:install-file as follows.

```<code>mvn install:install-file -Dfile=jmime.jar -DgroupId=jmime \
-DartifactId=jmime -Dversion=3.1.1e -Dpackaging=jar
</code>```

Maven installed the jar file just fine into my local repository.

I then went into IntelliJ's Settings => Maven => Repository Services and Updated my local repository (so that IntelliJ would reindex the repository contents).

Finally, I added the following dependency to my pom.xml file (just above the log4j dependency).

```<code><dependency>
    <groupId>jmime</groupId>
    <artifactId>jmime</artifactId>
    <version>3.1.1e</version>
</dependency>
</code>```

I now create a new class as follows:

```<code>package com.stackoverflow.question;

import org.apache.log4j.Logger;
import com.hunnysoft.jmime.ByteString;
import com.hunnysoft.jmime.Field;
import com.hunnysoft.jmime.FieldBody;

public class StackOverflowQuestion {
    public Field create(String name, String text) {
        Logger.getLogger(getClass()).debug("create entered");
        FieldBody body = new FieldBody();
        body.setText(new ByteString(text));
        Field field = new Field();
        field.setFieldName(name);
        field.setFieldBody(body);
        return field;
    }
}
</code>```

Now for the weirdness.  IntelliJ's intention mechanism picks up and recognizes the Logger import in the maven pom file just fine.  However, for all of the hunnysoft imports it reports: "Cannot resolve symbol 'ByteString/Field/FieldBody'", BUT Build => Compile 'StackOverflowQuestion.java' compiles everything correctly and the unit test I created for this class runs fine (though the intentions mark the call to create() as a problem area too).

So somewhere, somehow IntelliJ is ignoring the jmime.jar file for the intention subsystem.  I'm confused because the log4j dependency works fine and everything compiles and runs fine.  F12 ("Go To Declaration") works on the Logger import, but breaks on all the jmime imports.

Oh, one other thing, if I go to the 'Packages' view in the "Projects" window the "com.hunnysoft.jmime" package appears and I can see ALL of the classes I imported in the code snippet above under "Libraries".  Removing the above dependency from the pom.xml file causes this package to disappear and the compilation breaks.

It appears that the inspection's classpath is broken, but there does not seem to be a setting for this anywhere in the Settings => Intentions | Compiler areas (not that I expected any such settings, I believe the IDEA should already know the correct classpath based on the pom file and JDK).

As a final experiment I created a brand new standard J2SE application project (without using maven) and added the jmime.jar file directly to the project as one of its libraries.  I run into exactly the same problems as described above in this new project.

Here is the MANIFEST.MF from the jmime jar file.

```<code>Manifest-Version: 1.0
Ant-Version: Apache Ant 1.5.4
Created-By: 10.0-b23 (Sun Microsystems Inc.)

Name: com/hunnysoft/jmime/
Sealed: true
Specification-Title: Hunny JMIME
Specification-Version: 3.1.1
Specification-Vendor: Hunny Software, Inc.
Implementation-Title: com.hunnysoft.jmime
Implementation-Version: 3.1.1E
Implementation-Vendor: Hunny Software, Inc.
</code>```

I don't see anything unusual in this jar file.

My best guess is that perhaps the problem might be a missing dependency issue.  But AFAIK jmime is supposed to be self contained (JarAnalyzer doesn't come up with anything, but I'm not sure it would if a dependency jar is missing).

So, anyone have any IDEAs?

答:
I had a similar issue when I switched to a new computer.

I copied all the IDEA files (even the related %APPDATA%-folders), but then the Maven build was successfully, but IDEA did not find any classes from the dependencies, when building it.

The solution: I started with a new and clean IDEA profile by removing the folders from the %APPDATA%-folders

Body:
Platform: IntelliJ Community Edition 10.0.3

SDK: jdk1.6.0_21

OS: Windows 7

So I have a strange situation with IntelliJ that has me completely stumped.  I setup a Maven project and add log4j as a dependency in the pom.xml file.  The IDEA inspections run fine and my unit tests all compile and run.

I then added hunnysoft's jmime library to my local maven repository using the mvn install:install-file as follows.

mvn install:install-file -Dfile=jmime.jar -DgroupId=jmime \
-DartifactId=jmime -Dversion=3.1.1e -Dpackaging=jar

Maven installed the jar file just fine into my local repository.

I then went into IntelliJ's Settings => Maven => Repository Services and Updated my local repository (so that IntelliJ would reindex the repository contents).

Finally, I added the following dependency to my pom.xml file (just above the log4j dependency).

<dependency>
    <groupId>jmime</groupId>
    <artifactId>jmime</artifactId>
    <version>3.1.1e</version>
</dependency>

I now create a new class as follows:

package com.stackoverflow.question;

import org.apache.log4j.Logger;
import com.hunnysoft.jmime.ByteString;
import com.hunnysoft.jmime.Field;
import com.hunnysoft.jmime.FieldBody;

public class StackOverflowQuestion {
    public Field create(String name, String text) {
        Logger.getLogger(getClass()).debug("create entered");
        FieldBody body = new FieldBody();
        body.setText(new ByteString(text));
        Field field = new Field();
        field.setFieldName(name);
        field.setFieldBody(body);
        return field;
    }
}

Now for the weirdness.  IntelliJ's intention mechanism picks up and recognizes the Logger import in the maven pom file just fine.  However, for all of the hunnysoft imports it reports: "Cannot resolve symbol 'ByteString/Field/FieldBody'", BUT Build => Compile 'StackOverflowQuestion.java' compiles everything correctly and the unit test I created for this class runs fine (though the intentions mark the call to create() as a problem area too).

So somewhere, somehow IntelliJ is ignoring the jmime.jar file for the intention subsystem.  I'm confused because the log4j dependency works fine and everything compiles and runs fine.  F12 ("Go To Declaration") works on the Logger import, but breaks on all the jmime imports.

Oh, one other thing, if I go to the 'Packages' view in the "Projects" window the "com.hunnysoft.jmime" package appears and I can see ALL of the classes I imported in the code snippet above under "Libraries".  Removing the above dependency from the pom.xml file causes this package to disappear and the compilation breaks.

It appears that the inspection's classpath is broken, but there does not seem to be a setting for this anywhere in the Settings => Intentions | Compiler areas (not that I expected any such settings, I believe the IDEA should already know the correct classpath based on the pom file and JDK).

As a final experiment I created a brand new standard J2SE application project (without using maven) and added the jmime.jar file directly to the project as one of its libraries.  I run into exactly the same problems as described above in this new project.

Here is the MANIFEST.MF from the jmime jar file.

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.5.4
Created-By: 10.0-b23 (Sun Microsystems Inc.)

Name: com/hunnysoft/jmime/
Sealed: true
Specification-Title: Hunny JMIME
Specification-Version: 3.1.1
Specification-Vendor: Hunny Software, Inc.
Implementation-Title: com.hunnysoft.jmime
Implementation-Version: 3.1.1E
Implementation-Vendor: Hunny Software, Inc.

I don't see anything unusual in this jar file.

My best guess is that perhaps the problem might be a missing dependency issue.  But AFAIK jmime is supposed to be self contained (JarAnalyzer doesn't come up with anything, but I'm not sure it would if a dependency jar is missing).

So, anyone have any IDEAs?


问:
Regular Expression (REGEX) to match X-SPAM-SCORE
As a domain owner I have been struggling inevitably with spam, I wrote a REGEX expression to establish an acceptable level on the X-SPAM-SCORE, I know that CPANEL provides some "filters" for establishing this but in my case I found that my expression would suit my needs better, I am sharing it to save some one some time and as the means of documenting it.</p>

答:
So in the CPANEL you need to add this expression to "match" and "message headers".

^(X-Spam-Score:)\s(-[0-9])?(28|34|35|36|37|38|39|[4-9]\d+|\d{3,})(.[0-9]?[0-9]?)?$

Just copy the full expression and it will help you on filtering your SPAM mail.

I do not claim to be an expert on REGEX and I am sure there might be a million other ways to attack this need, If you have something constructive to say, please be my guest and welcome.

Cheers

EN


问:
Slope Fields with Pyplot point in the wrong direction
I am working on a project for my Calculus class and needed to generate a slope field for a given differential equation. My code is as follows:

```<code>from numpy import *
import matplotlib.pyplot as plt
import sympy as sym

def main():
    rng = raw_input('Minimum, Maximum: ').split(',')
    rng = [float(rng[i]) for i in range(2)]
    x = sym.Symbol('x')
    y = sym.Symbol('y')
    function = input('Differential Equation in terms of x and y: ')
    a = sym.lambdify((x,y), function)  # function a is the differential#
    x_points,y_points = meshgrid(arange(rng[0],rng[1],1),arange(rng[0],rng[1],1))
    f_x = x_points + 1
    f_y = a(x_points,y_points)
    print a(1,1),a(-1,-1),a(-5,-5),a(5,5)
    N = sqrt(f_x**2+f_y**2)
    f_x2,f_y2= f_x/N,f_y/N
    ax1 = plt.subplot()
    ax1.set_title(r'$\mathit{f(x)}\in \mathbb{R}^2$')
    ax1.set_xlabel(r'$\mathit{x}$')
    ax1.set_ylabel(r'$\mathit{y}$')
    ax1.grid()
    ax1.spines['left'].set_position('zero')
    ax1.spines['right'].set_color('none')
    ax1.spines['bottom'].set_position('zero')
    ax1.spines['top'].set_color('none')
    ax1.spines['left'].set_smart_bounds(True)
    ax1.spines['bottom'].set_smart_bounds(True)
    ax1.set_aspect(1. / ax1.get_data_ratio())
    ax1.xaxis.set_ticks_position('bottom')
    ax1.yaxis.set_ticks_position('left')
    ax1.quiver(x_points,y_points,f_x2,f_y2,pivot='mid', scale_units='xy')
    plt.show()

main()
</code>```

This creates what at first glance looks to be the proper slope field, but the arrows are actually incorrect.
dy/dx = x/y
While it looks almost correct, the proper slope field would look like:
dy/dx = x/y

The code generates points properly, so there must be a problem with the quiver application. Any help would be greatly appreciated.

答:
If dy/dx = x/y, then roughly speaking, Δy/Δx = x/y, and the vector at (x, y) goes from (x, y) to (x+Δx, y+Δy).

If we take Δx = 1, then Δy = x/y * Δx = x/y. So instead of

```<code>delta_x = x_points + 1
delta_y = a(x_points,y_points)
</code>```

we should use

```<code>delta_x = np.ones_like(X)   #<-- all ones
delta_y = a(X, Y)
</code>```

```<code>import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
x, y = sym.symbols('x, y')

def main(rng, function):
    a = sym.lambdify((x, y), function)  # function a is the differential#
    num_points = 11
    X, Y = np.meshgrid(np.linspace(rng[0], rng[1], num_points),
                       np.linspace(rng[0], rng[1], num_points))

    delta_x = np.ones_like(X)
    delta_y = a(X, Y)
    length = np.sqrt(delta_x**2 + delta_y**2)
    delta_x, delta_y = delta_x/length, delta_y/length
    ax = plt.subplot()
    ax.set_title(r'$\mathit{f(x)}\in \mathbb{R}^2$')
    ax.set_xlabel(r'$\mathit{x}$')
    ax.set_ylabel(r'$\mathit{y}$')
    ax.grid()
    ax.spines['left'].set_position('zero')
    ax.spines['right'].set_color('none')
    ax.spines['bottom'].set_position('zero')
    ax.spines['top'].set_color('none')
    ax.spines['left'].set_smart_bounds(True)
    ax.spines['bottom'].set_smart_bounds(True)
    ax.set_aspect(1. / ax.get_data_ratio())
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')
    ax.quiver(X, Y, delta_x, delta_y,
               pivot='mid',
               scale_units='xy', angles='xy', scale=1
               )
    plt.show()

def get_inputs():
    # separate user input from calculation, so main can be called non-interactively
    rng = input('Minimum, Maximum: ').split(',')
    rng = [float(rng[i]) for i in range(2)]
    function = eval(input('Differential Equation in terms of x and y: '))
    return rng, function

if __name__ == '__main__':
    # rng, function = get_inputs()
    # main(rng, function)
    main(rng=[-10, 10], function=x / y)
</code>```

Note that you could just as easily take Δx to be a smaller value. For example,

```<code>delta_x = np.ones_like(X) * 0.1
delta_y = a(X, Y) * delta_x
</code>```

but the result would be exactly the same after normalization:

```<code>length = np.sqrt(delta_x**2 + delta_y**2)
delta_x, delta_y = delta_x/length, delta_y/length
</code>```

Body:
I am working on a project for my Calculus class and needed to generate a slope field for a given differential equation. My code is as follows:

from numpy import *
import matplotlib.pyplot as plt
import sympy as sym

def main():
    rng = raw_input('Minimum, Maximum: ').split(',')
    rng = [float(rng[i]) for i in range(2)]
    x = sym.Symbol('x')
    y = sym.Symbol('y')
    function = input('Differential Equation in terms of x and y: ')
    a = sym.lambdify((x,y), function)  # function a is the differential#
    x_points,y_points = meshgrid(arange(rng[0],rng[1],1),arange(rng[0],rng[1],1))
    f_x = x_points + 1
    f_y = a(x_points,y_points)
    print a(1,1),a(-1,-1),a(-5,-5),a(5,5)
    N = sqrt(f_x**2+f_y**2)
    f_x2,f_y2= f_x/N,f_y/N
    ax1 = plt.subplot()
    ax1.set_title(r'$\mathit{f(x)}\in \mathbb{R}^2$')
    ax1.set_xlabel(r'$\mathit{x}$')
    ax1.set_ylabel(r'$\mathit{y}$')
    ax1.grid()
    ax1.spines['left'].set_position('zero')
    ax1.spines['right'].set_color('none')
    ax1.spines['bottom'].set_position('zero')
    ax1.spines['top'].set_color('none')
    ax1.spines['left'].set_smart_bounds(True)
    ax1.spines['bottom'].set_smart_bounds(True)
    ax1.set_aspect(1. / ax1.get_data_ratio())
    ax1.xaxis.set_ticks_position('bottom')
    ax1.yaxis.set_ticks_position('left')
    ax1.quiver(x_points,y_points,f_x2,f_y2,pivot='mid', scale_units='xy')
    plt.show()

main()

This creates what at first glance looks to be the proper slope field, but the arrows are actually incorrect.
dy/dx = x/y
While it looks almost correct, the proper slope field would look like:
dy/dx = x/y

The code generates points properly, so there must be a problem with the quiver application. Any help would be greatly appreciated.

Body:
If dy/dx = x/y, then roughly speaking, Δy/Δx = x/y, and the vector at (x, y) goes from (x, y) to (x+Δx, y+Δy).

If we take Δx = 1, then Δy = x/y * Δx = x/y. So instead of

delta_x = x_points + 1
delta_y = a(x_points,y_points)

we should use

delta_x = np.ones_like(X)   #<-- all ones
delta_y = a(X, Y)

import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
x, y = sym.symbols('x, y')

def main(rng, function):
    a = sym.lambdify((x, y), function)  # function a is the differential#
    num_points = 11
    X, Y = np.meshgrid(np.linspace(rng[0], rng[1], num_points),
                       np.linspace(rng[0], rng[1], num_points))

    delta_x = np.ones_like(X)
    delta_y = a(X, Y)
    length = np.sqrt(delta_x**2 + delta_y**2)
    delta_x, delta_y = delta_x/length, delta_y/length
    ax = plt.subplot()
    ax.set_title(r'$\mathit{f(x)}\in \mathbb{R}^2$')
    ax.set_xlabel(r'$\mathit{x}$')
    ax.set_ylabel(r'$\mathit{y}$')
    ax.grid()
    ax.spines['left'].set_position('zero')
    ax.spines['right'].set_color('none')
    ax.spines['bottom'].set_position('zero')
    ax.spines['top'].set_color('none')
    ax.spines['left'].set_smart_bounds(True)
    ax.spines['bottom'].set_smart_bounds(True)
    ax.set_aspect(1. / ax.get_data_ratio())
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')
    ax.quiver(X, Y, delta_x, delta_y,
               pivot='mid',
               scale_units='xy', angles='xy', scale=1
               )
    plt.show()

def get_inputs():
    # separate user input from calculation, so main can be called non-interactively
    rng = input('Minimum, Maximum: ').split(',')
    rng = [float(rng[i]) for i in range(2)]
    function = eval(input('Differential Equation in terms of x and y: '))
    return rng, function

if __name__ == '__main__':
    # rng, function = get_inputs()
    # main(rng, function)
    main(rng=[-10, 10], function=x / y)

Note that you could just as easily take Δx to be a smaller value. For example,

delta_x = np.ones_like(X) * 0.1
delta_y = a(X, Y) * delta_x

but the result would be exactly the same after normalization:

length = np.sqrt(delta_x**2 + delta_y**2)
delta_x, delta_y = delta_x/length, delta_y/length


问:
dyld: Library not loaded: @rpath/libswiftCore.dylib
I am getting this issue in my existing project and i tried to create new project then i run in device getting same issue

```<code>    dyld: Library not loaded: @rpath/libswiftCore.dylib
      Referenced from: /var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Pro
Reason: no suitable image found.  Did find:
    /private/var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Frameworks/libswiftCore.dylib: mmap() errno=1 validating first page of '/private/var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Frameworks/libswiftCore.dylib'
</code>```

some of the answer i tired but still getting same issue

dyld: Library not loaded: @rpath/libswiftCore.dylib

答: Now (2017 June) at Xcode 8.3.2, Swift 3 and iOs 10.3, my solution - after trying many possible solution who did't work for me - for this issue was at Keychain Access. I have deleted Apple Worldwide Developer Relations Certificate Authority and then I have downloaded and installed a new one. After that, I have changed "trust"(double-click the certificate) from "always" to "system default". Now everything is fine.</p>

Body:
I am getting this issue in my existing project and i tried to create new project then i run in device getting same issue

    dyld: Library not loaded: @rpath/libswiftCore.dylib
      Referenced from: /var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Pro
Reason: no suitable image found.  Did find:
    /private/var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Frameworks/libswiftCore.dylib: mmap() errno=1 validating first page of '/private/var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Frameworks/libswiftCore.dylib'

some of the answer i tired but still getting same issue

dyld: Library not loaded: @rpath/libswiftCore.dylib


问:
Why does the object created without using "new" operator gets the same address
Going through this question, one answer said the object created are destroyed outside their scope, To get this concept clearly I wrote the following code:

```<code>#include <iostream>

using namespace std;

struct Node{
    int val;
    Node *next;
    Node(int x) : val(x) , next(NULL){}
};

int main(){
    for(int i=0;i<10;i++){
        int someval = rand()%100;
        Node somenode = Node(someval);
        printf("Address for object %d is %p \n",i+1, &somenode);
    }
}
</code>```

I got the following output:

```<code>Address for object 1 is 0x7ffc32ff26b0
Address for object 2 is 0x7ffc32ff26b0
Address for object 3 is 0x7ffc32ff26b0
Address for object 4 is 0x7ffc32ff26b0
Address for object 5 is 0x7ffc32ff26b0
Address for object 6 is 0x7ffc32ff26b0
Address for object 7 is 0x7ffc32ff26b0
Address for object 8 is 0x7ffc32ff26b0
Address for object 9 is 0x7ffc32ff26b0
Address for object 10 is 0x7ffc32ff26b0
</code>```

I understand that each object is destroyed every time the loop iterates and a new object is created; but why do all of them have the same address. This problem occurred to me when I was creating a linked list and I did not use the new operator to create the object instead just used the same code, and the list always pointed to the same node and I ran into an infinite loop. Why is the same address allocated to each object?

答:
You keep creating the object on the top of the stack, and then removing it (the object goes out of scope at the end of each loop iteration, and is deconstructed before the next iteration). Thus, the address of the top of the stack is the same everytime you allocate space for the object.

If you remove the loop and allocate multiple Nodes in a row, you'll see different addresses for each as the stack grows.

Body:
Going through this question, one answer said the object created are destroyed outside their scope, To get this concept clearly I wrote the following code:

#include <iostream>

using namespace std;

struct Node{
    int val;
    Node *next;
    Node(int x) : val(x) , next(NULL){}
};

int main(){
    for(int i=0;i<10;i++){
        int someval = rand()%100;
        Node somenode = Node(someval);
        printf("Address for object %d is %p \n",i+1, &somenode);
    }
}

I got the following output:

Address for object 1 is 0x7ffc32ff26b0
Address for object 2 is 0x7ffc32ff26b0
Address for object 3 is 0x7ffc32ff26b0
Address for object 4 is 0x7ffc32ff26b0
Address for object 5 is 0x7ffc32ff26b0
Address for object 6 is 0x7ffc32ff26b0
Address for object 7 is 0x7ffc32ff26b0
Address for object 8 is 0x7ffc32ff26b0
Address for object 9 is 0x7ffc32ff26b0
Address for object 10 is 0x7ffc32ff26b0

I understand that each object is destroyed every time the loop iterates and a new object is created; but why do all of them have the same address. This problem occurred to me when I was creating a linked list and I did not use the new operator to create the object instead just used the same code, and the list always pointed to the same node and I ran into an infinite loop. Why is the same address allocated to each object?