问:
Get clicked chess piece from an SVG chessboard
I am developing a chess GUI in Python 3.6.3 using PyQt5 5.9.1 (GUI framework) and python-chess 0.21.1 (chess library) on Windows 10. I want to get the value of a piece that was clicked on an SVG chessboard (provided by python-chess) so that I can then move that piece to another square.

After the first left mouse click and getting the piece, I want to get the second left mouse click from the user and get the square that the user clicked on. Then my chess GUI must move the piece from originating square to the target square.

So, here's my complete working code so far. Any hints or actual code additions are very welcome.

```<code>import chess
import chess.svg
from PyQt5.QtSvg import QSvgWidget
from PyQt5.QtCore import pyqtSlot, Qt
from PyQt5.QtWidgets import QApplication, QWidget

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Chess Titan")
        self.setGeometry(300, 300, 800, 800)

        self.widgetSvg = QSvgWidget(parent=self)
        self.widgetSvg.setGeometry(10, 10, 600, 600)

        self.chessboard = chess.Board()

    @pyqtSlot(QWidget)
    def mousePressEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            ## How to get the clicked SVG chess piece?

            # Envoke the paint event.
            self.update()

    @pyqtSlot(QWidget)
    def paintEvent(self, event):
        self.chessboardSvg = chess.svg.board(self.chessboard).encode("UTF-8")
        self.widgetSvg.load(self.chessboardSvg)

if __name__ == "__main__":
    chessTitan = QApplication([])
    window = MainWindow()
    window.show()
    chessTitan.exec()
</code>```

答:
If size of chessboard is known, you can find the coordinates of  the mouseclick from event.pos() resp.event.x(), event.y() depending on marginwidth and squaresize, see chess.svg.py line 129 ff.

edit Nov 25: event.pos() is in this example in MainWindow coordinates, to find the coordinates on chessboard all must be calculated from top left corner represented by self.svgX and self.svgY:

```<code>import chess
import chess.svg
from PyQt5.QtCore import pyqtSlot, Qt
from PyQt5.QtSvg import QSvgWidget
from PyQt5.QtWidgets import QApplication, QWidget

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Chess Titan")
        self.setGeometry(300, 300, 800, 800)

        self.widgetSvg = QSvgWidget(parent=self)
        self.svgX = 50                          # top left x-pos of chessboard
        self.svgY = 50                          # top left y-pos of chessboard
        self.cbSize = 600                       # size of chessboard
        self.widgetSvg.setGeometry(self.svgX,self.svgY, self.cbSize, self.cbSize)
        self.coordinates = True
        # see chess.svg.py line 129
        self.margin = 0.05*self.cbSize if self.coordinates == True else 0
        self.squareSize  = (self.cbSize - 2 * self.margin) / 8.0
        self.chessboard = chess.Board()
        self.pieceToMove = [None, None]

    @pyqtSlot(QWidget)
    def mousePressEvent(self, event):
        if self.svgX < event.x() <= self.svgX + self.cbSize and self.svgY < event.y() <= self.svgY + self.cbSize:   # mouse on chessboard
            if event.buttons() == Qt.LeftButton:
                # if the click is on chessBoard only
                if self.svgX + self.margin < event.x() < self.svgX + self.cbSize - self.margin and self.svgY + self.margin < event.y() < self.svgY + self.cbSize - self.margin:
                    file = int((event.x() - (self.svgX + self.margin))/self.squareSize)
                    rank = 7 - int((event.y() - (self.svgY + self.margin))/self.squareSize)
                    square = chess.square(file, rank)                       # chess.sqare.mirror() if white is on top
                    piece = self.chessboard.piece_at(square)
                    coordinates = '{}{}'.format(chr(file + 97), str(rank +1))
                    if self.pieceToMove[0] is not None:
                        move = chess.Move.from_uci('{}{}'.format(self.pieceToMove[1], coordinates))
                        self.chessboard.push(move)
                        print(self.chessboard.fen())
                        piece = None
                        coordinates= None
                    self.pieceToMove = [piece, coordinates]
                else:
                    print('coordinates clicked')
                # Envoke the paint event.
                self.update()
        else:
            QWidget.mousePressEvent(self, event)

    @pyqtSlot(QWidget)
    def paintEvent(self, event):
        self.chessboardSvg = chess.svg.board(self.chessboard, size = self.cbSize, coordinates = self.coordinates).encode("UTF-8")
        self.widgetSvg.load(self.chessboardSvg)

if __name__ == "__main__":
    chessTitan = QApplication([])
    window = MainWindow()
    window.show()
    chessTitan.exec()
</code>```

move white and black pieces alternating, they change the color if the same color is moved twice.

Body:
I am developing a chess GUI in Python 3.6.3 using PyQt5 5.9.1 (GUI framework) and python-chess 0.21.1 (chess library) on Windows 10. I want to get the value of a piece that was clicked on an SVG chessboard (provided by python-chess) so that I can then move that piece to another square.

After the first left mouse click and getting the piece, I want to get the second left mouse click from the user and get the square that the user clicked on. Then my chess GUI must move the piece from originating square to the target square.

So, here's my complete working code so far. Any hints or actual code additions are very welcome.

import chess
import chess.svg
from PyQt5.QtSvg import QSvgWidget
from PyQt5.QtCore import pyqtSlot, Qt
from PyQt5.QtWidgets import QApplication, QWidget

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Chess Titan")
        self.setGeometry(300, 300, 800, 800)

        self.widgetSvg = QSvgWidget(parent=self)
        self.widgetSvg.setGeometry(10, 10, 600, 600)

        self.chessboard = chess.Board()

    @pyqtSlot(QWidget)
    def mousePressEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            ## How to get the clicked SVG chess piece?

            # Envoke the paint event.
            self.update()

    @pyqtSlot(QWidget)
    def paintEvent(self, event):
        self.chessboardSvg = chess.svg.board(self.chessboard).encode("UTF-8")
        self.widgetSvg.load(self.chessboardSvg)

if __name__ == "__main__":
    chessTitan = QApplication([])
    window = MainWindow()
    window.show()
    chessTitan.exec()

Body:
If size of chessboard is known, you can find the coordinates of  the mouseclick from event.pos() resp.event.x(), event.y() depending on marginwidth and squaresize, see chess.svg.py line 129 ff.

edit Nov 25: event.pos() is in this example in MainWindow coordinates, to find the coordinates on chessboard all must be calculated from top left corner represented by self.svgX and self.svgY:

import chess
import chess.svg
from PyQt5.QtCore import pyqtSlot, Qt
from PyQt5.QtSvg import QSvgWidget
from PyQt5.QtWidgets import QApplication, QWidget

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Chess Titan")
        self.setGeometry(300, 300, 800, 800)

        self.widgetSvg = QSvgWidget(parent=self)
        self.svgX = 50                          # top left x-pos of chessboard
        self.svgY = 50                          # top left y-pos of chessboard
        self.cbSize = 600                       # size of chessboard
        self.widgetSvg.setGeometry(self.svgX,self.svgY, self.cbSize, self.cbSize)
        self.coordinates = True
        # see chess.svg.py line 129
        self.margin = 0.05*self.cbSize if self.coordinates == True else 0
        self.squareSize  = (self.cbSize - 2 * self.margin) / 8.0
        self.chessboard = chess.Board()
        self.pieceToMove = [None, None]

    @pyqtSlot(QWidget)
    def mousePressEvent(self, event):
        if self.svgX < event.x() <= self.svgX + self.cbSize and self.svgY < event.y() <= self.svgY + self.cbSize:   # mouse on chessboard
            if event.buttons() == Qt.LeftButton:
                # if the click is on chessBoard only
                if self.svgX + self.margin < event.x() < self.svgX + self.cbSize - self.margin and self.svgY + self.margin < event.y() < self.svgY + self.cbSize - self.margin:
                    file = int((event.x() - (self.svgX + self.margin))/self.squareSize)
                    rank = 7 - int((event.y() - (self.svgY + self.margin))/self.squareSize)
                    square = chess.square(file, rank)                       # chess.sqare.mirror() if white is on top
                    piece = self.chessboard.piece_at(square)
                    coordinates = '{}{}'.format(chr(file + 97), str(rank +1))
                    if self.pieceToMove[0] is not None:
                        move = chess.Move.from_uci('{}{}'.format(self.pieceToMove[1], coordinates))
                        self.chessboard.push(move)
                        print(self.chessboard.fen())
                        piece = None
                        coordinates= None
                    self.pieceToMove = [piece, coordinates]
                else:
                    print('coordinates clicked')
                # Envoke the paint event.
                self.update()
        else:
            QWidget.mousePressEvent(self, event)

    @pyqtSlot(QWidget)
    def paintEvent(self, event):
        self.chessboardSvg = chess.svg.board(self.chessboard, size = self.cbSize, coordinates = self.coordinates).encode("UTF-8")
        self.widgetSvg.load(self.chessboardSvg)

if __name__ == "__main__":
    chessTitan = QApplication([])
    window = MainWindow()
    window.show()
    chessTitan.exec()

move white and black pieces alternating, they change the color if the same color is moved twice.


来源: stackexchange

问:
RESTful web service API documentation with Sphinx
What's the best way to markup methods/URLs for a RESTful webservice using ReST/Sphinx? Is there a default domain that's suitable for marking up URLs with their possible parameters, HTTP methods, headers and body content?

Something along the lines of:

```<code>.. rest:method:: GET /api/foo

   :param bar: A valid bar
   :extension: json or xml

   Retrieve foos for the given parameters. E.g.::

      GET /api/foo.json?bar=baz
</code>```

Does something like this already exist or is one of the default extensions usable, or will I have to write one myself?

答:
Since there doesn't appear to be any existing solution, I have implemented a very simple HTTP domain that I can use to mark up API methods:

```<code>import re

from docutils import nodes

from sphinx import addnodes
from sphinx.locale import l_, _
from sphinx.domains import Domain, ObjType
from sphinx.directives import ObjectDescription

http_method_sig_re = re.compile(r'^(GET|POST|PUT|DELETE)?\s?(\S+)(.*)$')

class HTTPMethod(ObjectDescription):

    def handle_signature(self, sig, signode):
        m = http_method_sig_re.match(sig)
        if m is None:
            raise ValueError

        verb, url, query = m.groups()
        if verb is None:
            verb = 'GET'

        signode += addnodes.desc_addname(verb, verb)
        signode += addnodes.desc_name(url, url)

        if query:
            params = query.strip().split()
            for param in params:
                signode += addnodes.desc_optional(param, param)

        return url

class HTTPDomain(Domain):
    """HTTP language domain."""
    name = 'http'
    label = 'HTTP'
    object_types = {
        'method':    ObjType(l_('method'),    'method')
    }
    directives = {
        'method':       HTTPMethod
    }

def setup(app):
    app.add_domain(HTTPDomain)
</code>```

It allows me to mark up methods like this and they'll be styled somewhat visually nicely:

```<code>.. http:method:: GET /api/foo/bar/:id/:slug

   :param id: An id
   :param slug: A slug

   Retrieve list of foobars matching given id.
</code>```

This was my first foray into both Sphinx and Python, so this should be considered very rudimentary code. If anybody is interested in fleshing this out, please fork this project on Github!

ContentLicense: CC BY-SA 2.5

Body:
What's the best way to markup methods/URLs for a RESTful webservice using ReST/Sphinx? Is there a default domain that's suitable for marking up URLs with their possible parameters, HTTP methods, headers and body content?

Something along the lines of:

.. rest:method:: GET /api/foo

   :param bar: A valid bar
   :extension: json or xml

   Retrieve foos for the given parameters. E.g.::

      GET /api/foo.json?bar=baz

Does something like this already exist or is one of the default extensions usable, or will I have to write one myself?

Body:
Since there doesn't appear to be any existing solution, I have implemented a very simple HTTP domain that I can use to mark up API methods:

import re

from docutils import nodes

from sphinx import addnodes
from sphinx.locale import l_, _
from sphinx.domains import Domain, ObjType
from sphinx.directives import ObjectDescription

http_method_sig_re = re.compile(r'^(GET|POST|PUT|DELETE)?\s?(\S+)(.*)$')

class HTTPMethod(ObjectDescription):

    def handle_signature(self, sig, signode):
        m = http_method_sig_re.match(sig)
        if m is None:
            raise ValueError

        verb, url, query = m.groups()
        if verb is None:
            verb = 'GET'

        signode += addnodes.desc_addname(verb, verb)
        signode += addnodes.desc_name(url, url)

        if query:
            params = query.strip().split()
            for param in params:
                signode += addnodes.desc_optional(param, param)

        return url

class HTTPDomain(Domain):
    """HTTP language domain."""
    name = 'http'
    label = 'HTTP'
    object_types = {
        'method':    ObjType(l_('method'),    'method')
    }
    directives = {
        'method':       HTTPMethod
    }

def setup(app):
    app.add_domain(HTTPDomain)

It allows me to mark up methods like this and they'll be styled somewhat visually nicely:

.. http:method:: GET /api/foo/bar/:id/:slug

   :param id: An id
   :param slug: A slug

   Retrieve list of foobars matching given id.

This was my first foray into both Sphinx and Python, so this should be considered very rudimentary code. If anybody is interested in fleshing this out, please fork this project on Github!


问:
Flask app "Restarting with stat"
I've built a few Flask apps, but on my latest project I noticed something a little strange in development mode.  The second line of the usual message in the terminal which always reads:

```<code> * Running on http://127.0.0.1:5000/
 * Restarting with reloader
</code>```

has been replaced by:

```<code> * Restarting with stat
</code>```

I don't think I've done anything different, in fact, I started by cloning a starter-kit project that I have used many times, which itself, does not display this behavior.  I also notice that this project consumes about 15% CPU steadily, whereas my other project are barely a blip.

Any ideas why this is happening?

答:
Use run(use_reloader=False) to disable the reloader.

It gave me some problems where it wasn't able to find my server file when it restarted. This did the trick. It executed just once and everything worked. Quite odd.

ContentLicense: CC BY-SA 3.0

Title: Flask app "Restarting with stat"

Body:
I've built a few Flask apps, but on my latest project I noticed something a little strange in development mode.  The second line of the usual message in the terminal which always reads:

 * Running on http://127.0.0.1:5000/
 * Restarting with reloader

has been replaced by:

 * Restarting with stat

I don't think I've done anything different, in fact, I started by cloning a starter-kit project that I have used many times, which itself, does not display this behavior.  I also notice that this project consumes about 15% CPU steadily, whereas my other project are barely a blip.

Any ideas why this is happening?


问:
How can a divider line be added in an Android RecyclerView?
I am developing an android application where I am using RecyclerView. I need to add a divider in RecyclerView.
I tried to add -

```<code>recyclerView.addItemDecoration(new
     DividerItemDecoration(getActivity(),
       DividerItemDecoration.VERTICAL_LIST));
</code>```

below is my xml code -

```<code>   <android.support.v7.widget.RecyclerView
    android:id="@+id/drawerList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="15dp"
    />
</code>```

答:
Try this simple single line code</p>

```<code>recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),LinearLayoutManager.VERTICAL));
</code>```

Body:
I am developing an android application where I am using RecyclerView. I need to add a divider in RecyclerView.
I tried to add -

recyclerView.addItemDecoration(new
     DividerItemDecoration(getActivity(),
       DividerItemDecoration.VERTICAL_LIST));

below is my xml code -

   <android.support.v7.widget.RecyclerView
    android:id="@+id/drawerList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="15dp"
    />

Body:
Try this simple single line code

recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),LinearLayoutManager.VERTICAL));

ContentLicense: CC BY-SA 4.0


问:
Create a mailto link with Razor
I have a view with a model that has an email address.  How do I create an anchor? to allow the user to simply click on it an open Outlook?  I could create an anchor manually but then how do I include the email address?</p>

```<code><a href="mailto:" + Model.CreatorEmail >Email</a>
</code>```

答:
I found an answer to my problem:</p>

```<code>@{ var email = "mailto:" + Model.CreatorEmail;}
            <a href="@email">Email</a>
</code>```

Title: Create a mailto link with Razor

Body:
I have a view with a model that has an email address.  How do I create an anchor? to allow the user to simply click on it an open Outlook?  I could create an anchor manually but then how do I include the email address?

Email

Body:
I found an answer to my problem:

@{ var email = "mailto:" + Model.CreatorEmail;}
            <a href="@email">Email</a>


问:
VS2010 debugging just stopped, Unknown error: 0x80072ee6
For some reason, my ability to attach a debugger to ANYTHING has just stopped. It has persisted after a computer reboot, and it's really making things difficult.

This is the error I get:

```<code>---------------------------
Microsoft Visual Studio
---------------------------
Unable to attach to the process. Operation not supported. Unknown error: 0x80072ee6.
---------------------------
OK
---------------------------
</code>```

I mean, what the hell? It stopped working whilst VS2010 was running: worked for one debug, I stopped it, and then the next one didn't work.

Any help? Thanks in advance.

EDIT:

I have tried:
a) rebooting the computer
b) regsvr32 MSXML3.dll
c) repairing MS VS2010
d) attaching the debugger manually, and by using the debug button

答:
I got it working again, but I'm not going to mark this as a answer.

Here's what I did:

Started debugging a WP7 project - success!

Stopped debugging the WP7 project.

Started debugging the ASP.Net project (runs on a remote machine) that was in the same solution as my silverlight project I was attempting to debug - success!

Started debugging the silverlight project I was having problems with - success!

Stopped debugging both

Started debugging just the silverlight project - success!

Apparently it works now, but as I said, but I'm not marking this as the answer.

Body:
For some reason, my ability to attach a debugger to ANYTHING has just stopped. It has persisted after a computer reboot, and it's really making things difficult.

This is the error I get:

---------------------------
Microsoft Visual Studio
---------------------------
Unable to attach to the process. Operation not supported. Unknown error: 0x80072ee6.
---------------------------
OK
---------------------------

I mean, what the hell? It stopped working whilst VS2010 was running: worked for one debug, I stopped it, and then the next one didn't work.

Any help? Thanks in advance.

EDIT:

I have tried:
a) rebooting the computer
b) regsvr32 MSXML3.dll
c) repairing MS VS2010
d) attaching the debugger manually, and by using the debug button


问:
google map to display multiple markers in each external links location click without page refresh
I wanted to display the Google map to pin multiple stores in each location.

For example, locations are

Chennai

Trichy

Bangalore

Hyderabad

If I click the link Chennai, the map will display multiple stores only in Chennai. If I click the link Trichy, the map will display multiple stores only in Trichy without page reloading.

How to code this in google map?

Current code is

Html:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="js/map.js"></script>
  </head>
  <body>
    <div id="map-canvas"style="width: 500px; height: 400px;"/>
  </body>
</html>
</code>```

js code

```<code>// *
// * Add multiple markers
// * 2013 - en.marnoto.com
// *

// necessary variables
var map;
var infoWindow;

// markersData variable stores the information necessary to each marker
var markersData = [
   {
      lat: 40.6386333,
      lng: -8.745,
      name: "Jayasurya Tex",
      address1:"Anna strret",
      address2: "Chennai",
      postalCode: "625789" // don't insert comma in the last item of each marker
   },
   {
      lat: 40.59955,
      lng: -8.7498167,
      name: "Ram Tex",
      address1:"65 Kovalan strret",
      address2: "chennai",
      postalCode: "625001" // don't insert comma in the last item of each marker
   },
   {
      lat: -33.890542,
      lng: 51.274856,
      name: "Keerthi Tex",
      address1:"465 avinashi road",
      address2: "Erode",
      postalCode: "638009" // don't insert comma in the last item of each marker
   },
   {
      lat: -33.890542,
      lng: 51.274856,
      name: "supreme Tex",
      address1:"468 Pks road",
      address2: "Erode",
      postalCode: "638009" // don't insert comma in the last item of each marker
   },
   {
      lat: 40.6247167,
      lng: -8.7129167,
      name: "Niva Tex",
      address1:"75 small bazar street",
      address2: "Trichy",
      postalCode: "698547" // don't insert comma in the last item of each marker
   } // don't insert comma in the last item
];

function initialize() {
   var mapOptions = {
      center: new google.maps.LatLng(40.601203,-8.668173),
      zoom: 9,
      mapTypeId: 'roadmap',
   };

   map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

   // a new Info Window is created
   infoWindow = new google.maps.InfoWindow();

   // Event that closes the Info Window with a click on the map
   google.maps.event.addListener(map, 'click', function() {
      infoWindow.close();
   });

   // Finally displayMarkers() function is called to begin the markers creation
   displayMarkers();
}
google.maps.event.addDomListener(window, 'load', initialize);

// This function will iterate over markersData array
// creating markers with createMarker function
function displayMarkers(){

   // this variable sets the map bounds according to markers position
   var bounds = new google.maps.LatLngBounds();

   // for loop traverses markersData array calling createMarker function for each marker
   for (var i = 0; i < markersData.length; i++){

      var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
      var name = markersData[i].name;
      var address1 = markersData[i].address1;
      var address2 = markersData[i].address2;
      var postalCode = markersData[i].postalCode;

      createMarker(latlng, name, address1, address2, postalCode);

      // marker position is added to bounds variable
      bounds.extend(latlng);
   }

   // Finally the bounds variable is used to set the map bounds
   // with fitBounds() function
   map.fitBounds(bounds);
}

// This function creates each marker and it sets their Info Window content
function createMarker(latlng, name, address1, address2, postalCode){
   var marker = new google.maps.Marker({
      map: map,
      position: latlng,
      title: name
   });

   // This event expects a click on a marker
   // When this event is fired the Info Window content is created
   // and the Info Window is opened.
   google.maps.event.addListener(marker, 'click', function() {

      // Creating the content to be inserted in the infowindow
      var iwContent = '<div id="iw_container">' +
            '<div class="iw_title">' + name + '</div>' +
         '<div class="iw_content">' + address1 + '<br />' +
         address2 + '<br />' +
         postalCode + '</div></div>';

      // including content to the Info Window.
      infoWindow.setContent(iwContent);

      // opening the Info Window in the current map and at the current marker location.
      infoWindow.open(map, marker);
   });
}
</code>```

css

```<code>#map-canvas {
    height: 50%;
}
#iw_container .iw_title {
    font-size: 16px;
    font-weight: bold;
}
.iw_content {
    padding: 15px 15px 15px 0;
}
</code>```

答:
You can make several changes in the existing code:

add an array markers to keep all your markers

add a property, for example tag to each marker and set there the value of the location this marker belongs to

write a function that filters markers according to the tag

finally, add link elements that call this function to filter markers on click event.

Proof of concept

// necessary variables
var map;
var infoWindow;
var markers = [];

// markersData variable stores the information necessary to each marker
var markersData = [
   {
      lat: 40.6386333,
      lng: -8.745,
      name: "Jayasurya Tex",
      address1:"Anna strret",
      address2: "Chennai",
      postalCode: "625789" // don't insert comma in the last item of each marker
   },
   {
      lat: 40.59955,
      lng: -8.7498167,
      name: "Ram Tex",
      address1:"65 Kovalan strret",
      address2: "Chennai",
      postalCode: "625001" // don't insert comma in the last item of each marker
   },
   {
      lat: 40.6247167,
      lng: -8.7129167,
      name: "Niva Tex",
      address1:"75 small bazar street",
      address2: "Trichy",
      postalCode: "698547" // don't insert comma in the last item of each marker
   } // don't insert comma in the last item
];

function initialize() {
   var mapOptions = {
      center: new google.maps.LatLng(40.601203,-8.668173),
      zoom: 9,
      mapTypeId: 'roadmap',
   };

   map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

   // a new Info Window is created
   infoWindow = new google.maps.InfoWindow();

   // Event that closes the Info Window with a click on the map
   google.maps.event.addListener(map, 'click', function() {
      infoWindow.close();
   });

   // Finally displayMarkers() function is called to begin the markers creation
   displayMarkers();
}

// This function will iterate over markersData array
// creating markers with createMarker function
function displayMarkers(){

   // this variable sets the map bounds according to markers position
   var bounds = new google.maps.LatLngBounds();

   // for loop traverses markersData array calling createMarker function for each marker
   for (var i = 0; i < markersData.length; i++){

      var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
      var name = markersData[i].name;
      var address1 = markersData[i].address1;
      var address2 = markersData[i].address2;
      var postalCode = markersData[i].postalCode;

      createMarker(latlng, name, address1, address2, postalCode);

      // marker position is added to bounds variable
      bounds.extend(latlng);
   }

   // Finally the bounds variable is used to set the map bounds
   // with fitBounds() function
   map.fitBounds(bounds);
}

// This function creates each marker and it sets their Info Window content
function createMarker(latlng, name, address1, address2, postalCode){
   var marker = new google.maps.Marker({
      map: map,
      position: latlng,
      title: name
   });

   marker.tag = address2;
   markers.push(marker);

   // This event expects a click on a marker
   // When this event is fired the Info Window content is created
   // and the Info Window is opened.
   google.maps.event.addListener(marker, 'click', function() {

      // Creating the content to be inserted in the infowindow
      var iwContent = '
' +
            '
' + name + '
' +
         '
' + address1 + '
' +
         address2 + '
' +
         postalCode + '

';

      // including content to the Info Window.
      infoWindow.setContent(iwContent);

      // opening the Info Window in the current map and at the current marker location.
      infoWindow.open(map, marker);
   });
}

function filterMarkersByTag(tagName) {
    var bounds = new google.maps.LatLngBounds();

    markers.forEach(function(marker) {
        marker.setMap(null);
    });

    var filtered = markers.filter(function(marker) {
        return marker.tag === tagName;
    });

    if (filtered && filtered.length) {
        filtered.forEach(function(marker) {
            bounds.extend(marker.getPosition());
            marker.setMap(map);
        });

        map.fitBounds(bounds);
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#map-canvas {
    height: 50%;
}
#iw_container .iw_title {
    font-size: 16px;
    font-weight: bold;
}
.iw_content {
    padding: 15px 15px 15px 0;
}</code>```

Chennai
Trichy

```

I hope this helps!

Body:
I wanted to display the Google map to pin multiple stores in each location.

For example, locations are

Chennai

Trichy

Bangalore

Hyderabad

If I click the link Chennai, the map will display multiple stores only in Chennai. If I click the link Trichy, the map will display multiple stores only in Trichy without page reloading.

How to code this in google map?

Current code is

Html:

<!DOCTYPE html>

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

js code

// *
// * Add multiple markers
// * 2013 - en.marnoto.com
// *

// necessary variables
var map;
var infoWindow;

// markersData variable stores the information necessary to each marker
var markersData = [
   {
      lat: 40.6386333,
      lng: -8.745,
      name: "Jayasurya Tex",
      address1:"Anna strret",
      address2: "Chennai",
      postalCode: "625789" // don't insert comma in the last item of each marker
   },
   {
      lat: 40.59955,
      lng: -8.7498167,
      name: "Ram Tex",
      address1:"65 Kovalan strret",
      address2: "chennai",
      postalCode: "625001" // don't insert comma in the last item of each marker
   },
   {
      lat: -33.890542,
      lng: 51.274856,
      name: "Keerthi Tex",
      address1:"465 avinashi road",
      address2: "Erode",
      postalCode: "638009" // don't insert comma in the last item of each marker
   },
   {
      lat: -33.890542,
      lng: 51.274856,
      name: "supreme Tex",
      address1:"468 Pks road",
      address2: "Erode",
      postalCode: "638009" // don't insert comma in the last item of each marker
   },
   {
      lat: 40.6247167,
      lng: -8.7129167,
      name: "Niva Tex",
      address1:"75 small bazar street",
      address2: "Trichy",
      postalCode: "698547" // don't insert comma in the last item of each marker
   } // don't insert comma in the last item
];

function initialize() {
   var mapOptions = {
      center: new google.maps.LatLng(40.601203,-8.668173),
      zoom: 9,
      mapTypeId: 'roadmap',
   };

   map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

   // a new Info Window is created
   infoWindow = new google.maps.InfoWindow();

   // Event that closes the Info Window with a click on the map
   google.maps.event.addListener(map, 'click', function() {
      infoWindow.close();
   });

   // Finally displayMarkers() function is called to begin the markers creation
   displayMarkers();
}
google.maps.event.addDomListener(window, 'load', initialize);

// This function will iterate over markersData array
// creating markers with createMarker function
function displayMarkers(){

   // this variable sets the map bounds according to markers position
   var bounds = new google.maps.LatLngBounds();

   // for loop traverses markersData array calling createMarker function for each marker
   for (var i = 0; i < markersData.length; i++){

      var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
      var name = markersData[i].name;
      var address1 = markersData[i].address1;
      var address2 = markersData[i].address2;
      var postalCode = markersData[i].postalCode;

      createMarker(latlng, name, address1, address2, postalCode);

      // marker position is added to bounds variable
      bounds.extend(latlng);
   }

   // Finally the bounds variable is used to set the map bounds
   // with fitBounds() function
   map.fitBounds(bounds);
}

// This function creates each marker and it sets their Info Window content
function createMarker(latlng, name, address1, address2, postalCode){
   var marker = new google.maps.Marker({
      map: map,
      position: latlng,
      title: name
   });

   // This event expects a click on a marker
   // When this event is fired the Info Window content is created
   // and the Info Window is opened.
   google.maps.event.addListener(marker, 'click', function() {

      // Creating the content to be inserted in the infowindow
      var iwContent = '
' +
            '
' + name + '
' +
         '
' + address1 + '
' +
         address2 + '
' +
         postalCode + '

';

      // including content to the Info Window.
      infoWindow.setContent(iwContent);

      // opening the Info Window in the current map and at the current marker location.
      infoWindow.open(map, marker);
   });
}

css

#map-canvas {
    height: 50%;
}
#iw_container .iw_title {
    font-size: 16px;
    font-weight: bold;
}
.iw_content {
    padding: 15px 15px 15px 0;
}

Body:
You can make several changes in the existing code:

add an array markers to keep all your markers

add a property, for example tag to each marker and set there the value of the location this marker belongs to

write a function that filters markers according to the tag

finally, add link elements that call this function to filter markers on click event.

Proof of concept

// necessary variables
var map;
var infoWindow;
var markers = [];

// markersData variable stores the information necessary to each marker
var markersData = [
   {
      lat: 40.6386333,
      lng: -8.745,
      name: "Jayasurya Tex",
      address1:"Anna strret",
      address2: "Chennai",
      postalCode: "625789" // don't insert comma in the last item of each marker
   },
   {
      lat: 40.59955,
      lng: -8.7498167,
      name: "Ram Tex",
      address1:"65 Kovalan strret",
      address2: "Chennai",
      postalCode: "625001" // don't insert comma in the last item of each marker
   },
   {
      lat: 40.6247167,
      lng: -8.7129167,
      name: "Niva Tex",
      address1:"75 small bazar street",
      address2: "Trichy",
      postalCode: "698547" // don't insert comma in the last item of each marker
   } // don't insert comma in the last item
];

function initialize() {
   var mapOptions = {
      center: new google.maps.LatLng(40.601203,-8.668173),
      zoom: 9,
      mapTypeId: 'roadmap',
   };

   map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

   // a new Info Window is created
   infoWindow = new google.maps.InfoWindow();

   // Event that closes the Info Window with a click on the map
   google.maps.event.addListener(map, 'click', function() {
      infoWindow.close();
   });

   // Finally displayMarkers() function is called to begin the markers creation
   displayMarkers();
}

// This function will iterate over markersData array
// creating markers with createMarker function
function displayMarkers(){

   // this variable sets the map bounds according to markers position
   var bounds = new google.maps.LatLngBounds();

   // for loop traverses markersData array calling createMarker function for each marker
   for (var i = 0; i < markersData.length; i++){

      var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
      var name = markersData[i].name;
      var address1 = markersData[i].address1;
      var address2 = markersData[i].address2;
      var postalCode = markersData[i].postalCode;

      createMarker(latlng, name, address1, address2, postalCode);

      // marker position is added to bounds variable
      bounds.extend(latlng);
   }

   // Finally the bounds variable is used to set the map bounds
   // with fitBounds() function
   map.fitBounds(bounds);
}

// This function creates each marker and it sets their Info Window content
function createMarker(latlng, name, address1, address2, postalCode){
   var marker = new google.maps.Marker({
      map: map,
      position: latlng,
      title: name
   });

   marker.tag = address2;
   markers.push(marker);

   // This event expects a click on a marker
   // When this event is fired the Info Window content is created
   // and the Info Window is opened.
   google.maps.event.addListener(marker, 'click', function() {

      // Creating the content to be inserted in the infowindow
      var iwContent = '<div id="iw_container">' +
            '<div class="iw_title">' + name + '</div>' +
         '<div class="iw_content">' + address1 + '<br />' +
         address2 + '<br />' +
         postalCode + '</div></div>';

      // including content to the Info Window.
      infoWindow.setContent(iwContent);

      // opening the Info Window in the current map and at the current marker location.
      infoWindow.open(map, marker);
   });
}

function filterMarkersByTag(tagName) {
    var bounds = new google.maps.LatLngBounds();

    markers.forEach(function(marker) {
        marker.setMap(null);
    });

    var filtered = markers.filter(function(marker) {
        return marker.tag === tagName;
    });

    if (filtered && filtered.length) {
        filtered.forEach(function(marker) {
            bounds.extend(marker.getPosition());
            marker.setMap(map);
        });

        map.fitBounds(bounds);
    }
}

#map-canvas {
    height: 50%;
}
#iw_container .iw_title {
    font-size: 16px;
    font-weight: bold;
}
.iw_content {
    padding: 15px 15px 15px 0;
}

<a href="#" title="Chennai" onclick="filterMarkersByTag('Chennai');return false;">Chennai</a>
<a href="#" title="Trichy" onclick="filterMarkersByTag('Trichy');return false;">Trichy</a>
<div id="map-canvas" style="width: 500px; height: 400px;">
</div>
<script async defer type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initialize"></script>

I hope this helps!


问:
c# deleting the 0s of an int, but not if it is 20
In my string start can be all sorts of numbers (1 until 99), but when the numbers get generated, 1 always get shown like 01. Is there an way to remove that 0, without if the number is 20 that the number get changed to 2?

答:
Another solution:

```<code>if (start.ElementAt(0) == '0')
    start = start.Remove(0, 1);
</code>```

or shorter:

```<code>start = start.ElementAt(0) == '0' ? start.Substring(1) : start;
</code>```

Body:
Another solution:

if (start.ElementAt(0) == '0')
    start = start.Remove(0, 1);

or shorter:

start = start.ElementAt(0) == '0' ? start.Substring(1) : start;


问:
Android Studio 3.0 Warning: Using incompatible plugins for the annotation processing
After update Android Studio to 3.0 version I have warning:

```<code>Error:android-apt plugin is incompatible with the Android Gradle plugin.  Please use 'annotationProcessor' configuration instead.
</code>```

I tried to rewrite my gradle source ,but I still have a warning.
Here is a source

```<code>buildscript {
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'
    classpath 'io.realm:realm-gradle-plugin:0.89.+'
}
}
allprojects {
repositories {
    google()
    jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.syncapp"
    minSdkVersion 21
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

 buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.11'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:support-v4:27.0.1'
implementation 'com.android.support:appcompat-v7:27.0.1'
implementation 'com.android.support:design:27.0.1'
compile 'org.greenrobot:eventbus:3.1.1'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

compile 'com.squareup.okhttp:okhttp:2.7.5'
compile 'com.squareup.okhttp:mockwebserver:2.7.5'

compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

compile 'com.google.dagger:dagger:2.4'
annotationProcessor 'com.google.dagger:dagger-compiler:2.4'

}
apply plugin: 'realm-android'
</code>```

As you can see,in my project I'm using butterknife,dagger,okhttp,retrofit2 and     eventbus support libraries

Any solution? I can't run my app
Thanks

答: Remove apt plugin from your build.gradle file. And wherever in dependency you are using apt replace it with annotationProcessor. Moreover update your realm dependency version to 4.1.1  as well.

Body:
After update Android Studio to 3.0 version I have warning:

Error:android-apt plugin is incompatible with the Android Gradle plugin.  Please use 'annotationProcessor' configuration instead.

I tried to rewrite my gradle source ,but I still have a warning.
Here is a source

buildscript {
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'
    classpath 'io.realm:realm-gradle-plugin:0.89.+'
}
}
allprojects {
repositories {
    google()
    jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.syncapp"
    minSdkVersion 21
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

 buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.11'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:support-v4:27.0.1'
implementation 'com.android.support:appcompat-v7:27.0.1'
implementation 'com.android.support:design:27.0.1'
compile 'org.greenrobot:eventbus:3.1.1'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

compile 'com.squareup.okhttp:okhttp:2.7.5'
compile 'com.squareup.okhttp:mockwebserver:2.7.5'

compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

compile 'com.google.dagger:dagger:2.4'
annotationProcessor 'com.google.dagger:dagger-compiler:2.4'

}
apply plugin: 'realm-android'

As you can see,in my project I'm using butterknife,dagger,okhttp,retrofit2 and     eventbus support libraries

Any solution? I can't run my app
Thanks


问:
Apply groups on already created menu
I have developed a new module and in that module I have created a group in .xml file.

Now I want to apply that group in menus which are already created in other menu.

So can I apply groups to those menus?

I don't want to override the menu, I just want to apply groups in already created menus.

Thanks in advance.

答:
Instead of updating record, you can replace menuitem itself,

All you have to do is find menuitem that you want to override then add your code to it.
For example,
Already defined menu,

```<code><menuitem id="menu_example" action="menu_action" name="Example Menu" parent="menu_example_parent" sequence="10"/>
</code>```

Now suppose you want to add group to this menu,

```<code><menuitem id="existing_module.menu_example" action="existing_module.menu_action" name="Example Menu" parent="existing_module.menu_example_parent" sequence="10" groups="group_example"/>
</code>```

If it doesn't work then first delete that menu and after that write that menu again including your code.
For deleting menu,

```<code><delete model="ir.ui.menu" id="module_name.menu_id" />
</code>```

Hope this is helpful.

Title: Apply groups on already created menu

Body:
Instead of updating record, you can replace menuitem itself,

All you have to do is find menuitem that you want to override then add your code to it.
For example,
Already defined menu,

<menuitem id="menu_example" action="menu_action" name="Example Menu" parent="menu_example_parent" sequence="10"/>

Now suppose you want to add group to this menu,

<menuitem id="existing_module.menu_example" action="existing_module.menu_action" name="Example Menu" parent="existing_module.menu_example_parent" sequence="10" groups="group_example"/>

If it doesn't work then first delete that menu and after that write that menu again including your code.
For deleting menu,

<delete model="ir.ui.menu" id="module_name.menu_id" />

Hope this is helpful.


问:
Test the size of a text on a button with getTextSize()
I need to check if the text size on a button have the size 37sp.
I found a method to get the size with: .getTextSize(), but the size with I receive is: 126.0,  and not 48sp.
The code off button:

```<code><Button
    android:id="@+id/buttoneql"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="="
    android:textColor="@android:color/black"
    android:textSize="48sp" />
</code>```

The test:

```<code>buttoneql = (Button) currentActivity.findViewById(R.id.buttoneql);
assertEquals( 48.0f, buttoneql.getTextSize() );
</code>```

How I should do to recive the ral value of the text size?

答:
getTextSize() return px float

This is code for the convert PX to SP format.

```<code>view.setTextSize(TypedValue.COMPLEX_UNIT_PX, 24);
</code>```

Body:
I need to check if the text size on a button have the size 37sp.
I found a method to get the size with: .getTextSize(), but the size with I receive is: 126.0,  and not 48sp.
The code off button:

<Button
    android:id="@+id/buttoneql"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="="
    android:textColor="@android:color/black"
    android:textSize="48sp" />

The test:

buttoneql = (Button) currentActivity.findViewById(R.id.buttoneql);
assertEquals( 48.0f, buttoneql.getTextSize() );

How I should do to recive the ral value of the text size?

Body:
getTextSize() return px float

This is code for the convert PX to SP format.

view.setTextSize(TypedValue.COMPLEX_UNIT_PX, 24);


问:
Facebook Javascript Login Example
I would like to make a ASP MVC 3 website with Facebook auth system.
I want to add users to my database when they connect to the website so that I can save their posts on the web site. The problem is that I couldn't manage to do a proper login/logout system. I have tried the C# sdk and the Javascript SDK. I have also read some sample code that I found out at web but it's no use...
Can anyone provide me a mvc 3 / javascript login/logout system?

 Thanks a lot!

答: Have you tried sample "CSMvc3FacebookApp" from Facebook C# SDK ( http://facebooksdk.codeplex.com/ )?</p>

Title: Facebook Javascript Login Example


问:
React Maximum call stack size exceeded when using react-hot-loader
When using react-hot-loader,a strange issue occurs to me.

Only this case will throw Uncaught RangeError: Maximum call stack size exceeded at PatientEdit.__test__REACT_HOT_LOADER__

```<code>class PatientEdit extends React.Component {
    test = () => {
        return 123
    }
    constructor(props) {
        super(props)
    }
    static propTypes = {
    }
    render() {
        return (
            <div>{this.test()}</div>)
    }
}
</code>```

But the followings three are all right

```<code>// A
class PatientEdit extends React.Component {
    test(){
        return 123
    }
    constructor(props) {
        super(props)
    }
    static propTypes = {}
    render() {
        return (
            <div>{this.test()}</div>)
    }
}
// B
class PatientEdit extends React.Component {
    test(){
        return 123
    }
    constructor(props) {
        super(props)
    }
    static propTypes = {}

    render() {
        return (
            <div>{this.test()}</div>)
    }
}
// C
class PatientEdit extends React.Component {
    test = () => {
        return 123
    }
    static propTypes = {}
    render() {
        return (
            <div>{this.test()}</div>)
    }
}
</code>```

Loader configuration  was followed as the doc says : .babelrc as below, add babel-polyfill and react-hot-loader/patch before file entry

```<code>    // .babelrc
    {
        "presets": [["env", {"modules": false}], "react", "stage-1"],
        "plugins": [
            "react-hot-loader/babel",
            "transform-decorators-legacy",
            "transform-flow-strip-types",
            "transform-object-assign",
            "transform-runtime",
            "typecheck",
            "react-css-modules"
        ]
    }
</code>```

In the beginning i was too shocked by the strange behavior and ignored the error stack. Now its my time to look into react-hot-loader's mechanism and welcome detailed explainations

答:
More of a guess than true reasoning. (Would love to hear throughout answer though)

Arrow function auto-binds itself to it's runtime context. (In this case PatientEdit class instance, resp. component).

I'm guessing the problem is, the class instance hasn't been created yet, as constructor has not been executed. But the instance is needed to be bound to. This probably causes class code to run again (in expectation to find it's constructor). And this is what causes the loop which, in the end, results with call stack overflow.

Body:
When using react-hot-loader,a strange issue occurs to me.

Only this case will throw Uncaught RangeError: Maximum call stack size exceeded at PatientEdit.__test__REACT_HOT_LOADER__

class PatientEdit extends React.Component {
    test = () => {
        return 123
    }
    constructor(props) {
        super(props)
    }
    static propTypes = {
    }
    render() {
        return (

{this.test()}
)
    }
}

But the followings three are all right

// A
class PatientEdit extends React.Component {
    test(){
        return 123
    }
    constructor(props) {
        super(props)
    }
    static propTypes = {}
    render() {
        return (

{this.test()}
)
    }
}
// B
class PatientEdit extends React.Component {
    test(){
        return 123
    }
    constructor(props) {
        super(props)
    }
    static propTypes = {}

    render() {
        return (

{this.test()}
)
    }
}
// C
class PatientEdit extends React.Component {
    test = () => {
        return 123
    }
    static propTypes = {}
    render() {
        return (

{this.test()}
)
    }
}

Loader configuration  was followed as the doc says : .babelrc as below, add babel-polyfill and react-hot-loader/patch before file entry

    // .babelrc
    {
        "presets": [["env", {"modules": false}], "react", "stage-1"],
        "plugins": [
            "react-hot-loader/babel",
            "transform-decorators-legacy",
            "transform-flow-strip-types",
            "transform-object-assign",
            "transform-runtime",
            "typecheck",
            "react-css-modules"
        ]
    }

In the beginning i was too shocked by the strange behavior and ignored the error stack. Now its my time to look into react-hot-loader's mechanism and welcome detailed explainations


问:
How to create temp table with dynamic SQL query result
I have this stored procedure:

```<code>Declare @MarketID AS NVARCHAR(MAX) = '1.136529848';
Declare @UserID AS NVARCHAR(MAX) = '6a309d84-d1c6-434d-b9df-4f96a74da912';

DECLARE @colsSelect AS NVARCHAR(MAX);
DECLARE @colsTemp AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

SELECT
    @colsSelect = STUFF((SELECT distinct ',' +
                    '''''' + ' as ' + QUOTENAME(name)
                         FROM RunnersInfoes  AS t
                         WHERE marketID = @MarketID
                         FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') , 1, 1, '');

PRINT @colsSelect

SET @query= ';WITH cte AS
             (
                  SELECT
                      id, ParentId, 0 AS Level, Share, AccountTypeName, FirstName
                  FROM
                      dbo.View_UserProfile
                  WHERE
                      View_UserProfile.id = ' + '''' + @UserID + '''' +'
                  UNION ALL
                  SELECT
                      t.id, t.ParentId, Level + 1 AS Level, t.Share, t.AccountTypeName, t.FirstName
                  FROM
                      View_UserProfile t
                  INNER JOIN
                      cte ON t.ParentId = cte.id
             )
             SELECT
                 ID, AccountTypeName AS Type, FirstName AS Name, ' + @colsSelect + '
             FROM cte AS t'

EXECUTE (@query)
</code>```

and it's generating this result:

I want to create temp table or variable type table for following result , remember the column of this result are dynamically rendered. Sometimes result returns more columns and sometimes with less but first 3 columns remain the same for every result. So kindly help for creating dynamic table inside the stored procedure.

答:
You can do:

```<code>SELECT ID
,      AccountTypeName AS Type
,      FirstName AS Name
,      ' + @colsSelect + '
INTO   ##TEMPTABLE
FROM   cte AS t
</code>```

Since you execute this dynamically, you cannot use #TEMPTABLE because a local temp table will only exist in the scope of the query that defines it. Using ## creates a global temp table which will be accessible outside the scope of the dynamic query.

Body:
I have this stored procedure:

Declare @MarketID AS NVARCHAR(MAX) = '1.136529848';
Declare @UserID AS NVARCHAR(MAX) = '6a309d84-d1c6-434d-b9df-4f96a74da912';

DECLARE @colsSelect AS NVARCHAR(MAX);
DECLARE @colsTemp AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

SELECT
    @colsSelect = STUFF((SELECT distinct ',' +
                    '''''' + ' as ' + QUOTENAME(name)
                         FROM RunnersInfoes  AS t
                         WHERE marketID = @MarketID
                         FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') , 1, 1, '');

PRINT @colsSelect

SET @query= ';WITH cte AS
             (
                  SELECT
                      id, ParentId, 0 AS Level, Share, AccountTypeName, FirstName
                  FROM
                      dbo.View_UserProfile
                  WHERE
                      View_UserProfile.id = ' + '''' + @UserID + '''' +'
                  UNION ALL
                  SELECT
                      t.id, t.ParentId, Level + 1 AS Level, t.Share, t.AccountTypeName, t.FirstName
                  FROM
                      View_UserProfile t
                  INNER JOIN
                      cte ON t.ParentId = cte.id
             )
             SELECT
                 ID, AccountTypeName AS Type, FirstName AS Name, ' + @colsSelect + '
             FROM cte AS t'

EXECUTE (@query)

and it's generating this result:

I want to create temp table or variable type table for following result , remember the column of this result are dynamically rendered. Sometimes result returns more columns and sometimes with less but first 3 columns remain the same for every result. So kindly help for creating dynamic table inside the stored procedure.

Body:
You can do:

SELECT ID
,      AccountTypeName AS Type
,      FirstName AS Name
,      ' + @colsSelect + '
INTO   ##TEMPTABLE
FROM   cte AS t

Since you execute this dynamically, you cannot use #TEMPTABLE because a local temp table will only exist in the scope of the query that defines it. Using ## creates a global temp table which will be accessible outside the scope of the dynamic query.


答:
Please use the SELECT - INTO clause for your use case as given below

```<code>SELECT * INTO #temptable FROM cte
</code>```

Title: How to create temp table with dynamic SQL query result

Body:
Please use the SELECT - INTO clause for your use case as given below

SELECT * INTO #temptable FROM cte


问:
How to print message in terminal with concat two strings in flutter?
I knows print() will useful but how to merge or concat two string variables.
like print(" "+str1+" "+str2)</p>

答:
It is more of a dart question.
You can achieve that using:</p>
```<code>print('Something $string1 something more ${someObject.string2} even more $string3');
</code>```

Body:
It is more of a dart question.
You can achieve that using:

print('Something $string1 something more ${someObject.string2} even more $string3');


问:
Difficult MySQL self-join please explain
This is supposed to be able to return a random post id. It is also said to be the fastest method using MySQL. </p>

```<code>SELECT t.id
FROM table t
JOIN (SELECT(FLOOR(max(id) * rand())) AS maxid FROM table)
AS tt
ON t.id >= tt.maxid
LIMIT 1
</code>```

<p>Can't seem to wrap my head around this, please help. </p>

答:
First, formatting helps

```<code>1. SELECT t.id
2.   FROM table t
3.          JOIN (SELECT(FLOOR(max(id) * rand())) AS maxid FROM table) AS tt
4.          ON t.id >= tt.maxid
5. LIMIT 1
</code>```

Let's look at subquery inside JOIN first:

rand() returns random value in range [0, 1] (e.g. 0.999, 0.251, 1)

max(id) means that your query will return maximal value of column id from specified table

Floor rounds input number down to the nearest integer (e.g. Floor(5.1) == 5, Floor(5.9) = 5)

hence, the subquery will return you random integer (due to FLOOR) number in the

range [0, 1]

"LIMIT 1" means that your query will return only one row from resulting set.

Hope this enough. Feel free to ask more details

Body:
This is supposed to be able to return a random post id. It is also said to be the fastest method using MySQL.

SELECT t.id
FROM table t
JOIN (SELECT(FLOOR(max(id) * rand())) AS maxid FROM table)
AS tt
ON t.id >= tt.maxid
LIMIT 1

Can't seem to wrap my head around this, please help.

Body:
First, formatting helps

1. SELECT t.id
2.   FROM table t
3.          JOIN (SELECT(FLOOR(max(id) * rand())) AS maxid FROM table) AS tt
4.          ON t.id >= tt.maxid
5. LIMIT 1

Let's look at subquery inside JOIN first:

rand() returns random value in range [0, 1] (e.g. 0.999, 0.251, 1)

max(id) means that your query will return maximal value of column id from specified table

Floor rounds input number down to the nearest integer (e.g. Floor(5.1) == 5, Floor(5.9) = 5)

hence, the subquery will return you random integer (due to FLOOR) number in the

range [0, 1]

"LIMIT 1" means that your query will return only one row from resulting set.

Hope this enough. Feel free to ask more details


问:
Arrow bouncing to the bottom right corner in CSS
I need an arrow to slightly move (bounce) to the bottom right corner on hover, using CSS. I've used the code below and I like what it does however this only moves the arrow left/right. How do I amend it so that it moves slightly to the bottom as well? I've tried using 'translateY' but couldn't workout the exact pixel amount for the animation to be smooth.

I've tried using 'bounce' but actually 'swing' seems to look better.
What I'm looking for is the kind on animation of this page:

http://ianlunn.github.io/Hover/   (called 'Wobble to Bottom Right')

```<code>.arrow:hover{

-webkit-animation: swing 1s ease;
animation: swing 1s ease;
-webkit-animation-iteration-count: 1;
animation-iteration-count: 1;

}

@-webkit-keyframes swing
{
    15%
    {
        -webkit-transform: translateX(5px);
        transform: translateX(5px);
    }
    30%
    {
        -webkit-transform: translateX(-5px);
       transform: translateX(-5px);
    }
    50%
    {
        -webkit-transform: translateX(3px);
        transform: translateX(3px);
    }
    65%
    {
        -webkit-transform: translateX(-3px);
        transform: translateX(-3px);
    }
    80%
    {
        -webkit-transform: translateX(2px);
        transform: translateX(2px);
    }
    100%
    {
        -webkit-transform: translateX(0);
        transform: translateX(0);
    }
}
@keyframes swing
{
    15%
    {
        -webkit-transform: translateX(5px);
        transform: translateX(5px);
    }
    30%
    {
        -webkit-transform: translateX(-5px);
        transform: translateX(-5px);
    }
    50%
    {
        -webkit-transform: translateX(3px);
        transform: translateX(3px);
    }
    65%
    {
        -webkit-transform: translateX(-3px);
        transform: translateX(-3px);
    }
    80%
    {
        -webkit-transform: translateX(2px);
        transform: translateX(2px);
    }
    100%
    {
        -webkit-transform: translateX(0);
        transform: translateX(0);
    }
}
</code>```

答:
You have to use translate(x,y) instead of translateX(x) for 2d transformation as @fen1x mentioned in the comment above

Try this:

```<code>@keyframes hvr-wobble-to-bottom-right {

16.65% {
    -webkit-transform: translate(8px, 8px);
    transform: translate(8px, 8px);
}

33.3% {
    -webkit-transform: translate(-6px, -6px);
    transform: translate(-6px, -6px);
}

49.95% {
    -webkit-transform: translate(4px, 4px);
    transform: translate(4px, 4px);
}

66.6% {
    -webkit-transform: translate(-2px, -2px);
    transform: translate(-2px, -2px);
}

83.25% {
    -webkit-transform: translate(1px, 1px);
    transform: translate(1px, 1px);
}

100% {
    -webkit-transform: translate(0, 0);
    transform: translate(0, 0);
}
}
</code>```

Body:
I need an arrow to slightly move (bounce) to the bottom right corner on hover, using CSS. I've used the code below and I like what it does however this only moves the arrow left/right. How do I amend it so that it moves slightly to the bottom as well? I've tried using 'translateY' but couldn't workout the exact pixel amount for the animation to be smooth.

I've tried using 'bounce' but actually 'swing' seems to look better.
What I'm looking for is the kind on animation of this page:

http://ianlunn.github.io/Hover/   (called 'Wobble to Bottom Right')

.arrow:hover{

-webkit-animation: swing 1s ease;
animation: swing 1s ease;
-webkit-animation-iteration-count: 1;
animation-iteration-count: 1;

}

@-webkit-keyframes swing
{
    15%
    {
        -webkit-transform: translateX(5px);
        transform: translateX(5px);
    }
    30%
    {
        -webkit-transform: translateX(-5px);
       transform: translateX(-5px);
    }
    50%
    {
        -webkit-transform: translateX(3px);
        transform: translateX(3px);
    }
    65%
    {
        -webkit-transform: translateX(-3px);
        transform: translateX(-3px);
    }
    80%
    {
        -webkit-transform: translateX(2px);
        transform: translateX(2px);
    }
    100%
    {
        -webkit-transform: translateX(0);
        transform: translateX(0);
    }
}
@keyframes swing
{
    15%
    {
        -webkit-transform: translateX(5px);
        transform: translateX(5px);
    }
    30%
    {
        -webkit-transform: translateX(-5px);
        transform: translateX(-5px);
    }
    50%
    {
        -webkit-transform: translateX(3px);
        transform: translateX(3px);
    }
    65%
    {
        -webkit-transform: translateX(-3px);
        transform: translateX(-3px);
    }
    80%
    {
        -webkit-transform: translateX(2px);
        transform: translateX(2px);
    }
    100%
    {
        -webkit-transform: translateX(0);
        transform: translateX(0);
    }
}

Body:
You have to use translate(x,y) instead of translateX(x) for 2d transformation as @fen1x mentioned in the comment above

Try this:

@keyframes hvr-wobble-to-bottom-right {

16.65% {
    -webkit-transform: translate(8px, 8px);
    transform: translate(8px, 8px);
}

33.3% {
    -webkit-transform: translate(-6px, -6px);
    transform: translate(-6px, -6px);
}

49.95% {
    -webkit-transform: translate(4px, 4px);
    transform: translate(4px, 4px);
}

66.6% {
    -webkit-transform: translate(-2px, -2px);
    transform: translate(-2px, -2px);
}

83.25% {
    -webkit-transform: translate(1px, 1px);
    transform: translate(1px, 1px);
}

100% {
    -webkit-transform: translate(0, 0);
    transform: translate(0, 0);
}
}


问:
Python & Pandas: a proper way to fetch data from a dataframe and create a new one
This issue arises quite often and my current method isn't the optimal one.

eg.

I've a dataframe (df1) that contains some data:

```<code>date          tweet                    sent_by

2017/01/01    'OMG @user2 @POTUS'      user1
2017/01/01    'THIS IS A TWEET!'       user17
......        .....                    ......
</code>```

I've a list of users:

```<code>user_list = ['user1','user2', ...]
</code>```

Now I'd like to go through df1 and check whether any user (exluding the sender) is mentioned in the tweet and create a new dataframe (df2) that contains the relevant information.

My current method:

```<code>date_list = []
tweet_list = []
sent_by_list = []
user_mentioned_list = []

for i in range(len(df1)):
    for user in user_list:
        if user in df1['tweet'][i] and user != df1['sent_by'][i]:
            date_list.append(df1['date'][i])
            tweet_list.append(df1['tweet'][i])
            sent_by_list.append(df1['sent_by'][i])
            user_mentioned_list.append(user)

df2 = pd.DataFrame()
df2['date'] = date_list
df2['tweet'] = tweet_list
df2['sent_by'] = sent_by_list
df2['user_mentioned'] = user_mentioned_list
</code>```

What is the best way to fetch the data and form a new dataframe?

答:
I think you need extract by list with | regex (or) and then compare with isin, last filter by boolean indexing:

```<code>print (df1)
         date                tweet sent_by
0  2017/01/01  'OMG @user2 @POTUS'   user1
1  2017/01/01  'OMG @user2 @POTUS'   user2
2  2017/01/01  'OMG @user2 @POTUS'   user4
3  2017/01/01  'OMG @user4 @POTUS'   user1
4  2017/01/01   'THIS IS A TWEET!'  user17

user_list = ['user1','user2']
pat = '(' + '|'.join(user_list) + ')'
df1['user_mentioned'] = df1['tweet'].str.extract(pat, expand=False)
df2 = df1[df1['user_mentioned'].isin(user_list) & (df1['user_mentioned']!= df1['sent_by'])]
print (df2)
         date                tweet sent_by user_mentioned
0  2017/01/01  'OMG @user2 @POTUS'   user1          user2
2  2017/01/01  'OMG @user2 @POTUS'   user4          user2
</code>```

Detail:

```<code>print (df1)
         date                tweet sent_by user_mentioned
0  2017/01/01  'OMG @user2 @POTUS'   user1          user2
1  2017/01/01  'OMG @user2 @POTUS'   user2          user2
2  2017/01/01  'OMG @user2 @POTUS'   user4          user2
3  2017/01/01  'OMG @user4 @POTUS'   user1            NaN
4  2017/01/01   'THIS IS A TWEET!'  user17            NaN
</code>```

Body:
This issue arises quite often and my current method isn't the optimal one.

eg.

I've a dataframe (df1) that contains some data:

date          tweet                    sent_by

2017/01/01    'OMG @user2 @POTUS'      user1
2017/01/01    'THIS IS A TWEET!'       user17
......        .....                    ......

I've a list of users:

user_list = ['user1','user2', ...]

Now I'd like to go through df1 and check whether any user (exluding the sender) is mentioned in the tweet and create a new dataframe (df2) that contains the relevant information.

My current method:

date_list = []
tweet_list = []
sent_by_list = []
user_mentioned_list = []

for i in range(len(df1)):
    for user in user_list:
        if user in df1['tweet'][i] and user != df1['sent_by'][i]:
            date_list.append(df1['date'][i])
            tweet_list.append(df1['tweet'][i])
            sent_by_list.append(df1['sent_by'][i])
            user_mentioned_list.append(user)

df2 = pd.DataFrame()
df2['date'] = date_list
df2['tweet'] = tweet_list
df2['sent_by'] = sent_by_list
df2['user_mentioned'] = user_mentioned_list

What is the best way to fetch the data and form a new dataframe?

Body:
I think you need extract by list with | regex (or) and then compare with isin, last filter by boolean indexing:

print (df1)
         date                tweet sent_by
0  2017/01/01  'OMG @user2 @POTUS'   user1
1  2017/01/01  'OMG @user2 @POTUS'   user2
2  2017/01/01  'OMG @user2 @POTUS'   user4
3  2017/01/01  'OMG @user4 @POTUS'   user1
4  2017/01/01   'THIS IS A TWEET!'  user17

user_list = ['user1','user2']
pat = '(' + '|'.join(user_list) + ')'
df1['user_mentioned'] = df1['tweet'].str.extract(pat, expand=False)
df2 = df1[df1['user_mentioned'].isin(user_list) & (df1['user_mentioned']!= df1['sent_by'])]
print (df2)
         date                tweet sent_by user_mentioned
0  2017/01/01  'OMG @user2 @POTUS'   user1          user2
2  2017/01/01  'OMG @user2 @POTUS'   user4          user2

Detail:

print (df1)
         date                tweet sent_by user_mentioned
0  2017/01/01  'OMG @user2 @POTUS'   user1          user2
1  2017/01/01  'OMG @user2 @POTUS'   user2          user2
2  2017/01/01  'OMG @user2 @POTUS'   user4          user2
3  2017/01/01  'OMG @user4 @POTUS'   user1            NaN
4  2017/01/01   'THIS IS A TWEET!'  user17            NaN


问:
Query multiple data with array of primary ids in DynamoDB
I'm working on a application that is using DynamoDB as the database.
I have a table of users like:

```<code>{
   id: 1, (Primary Key)
   name: "Indranil"
}
</code>```

Now my requirement is, I have the array if ids like : [1,5,8] and I want to load all the users using single query.

Now I'm using the id as keyConditionExpreassion in the query and I can fetch each user data one after another, but then it'll result in multiple queries.

```<code>    let readparams  = {
      TableName : "user",
      KeyConditionExpression: "# = :",
      ExpressionAttributeNames:{
        "#": "id"
      },
      ExpressionAttributeValues: {
        ":id":1
      }
    };
</code>```

Then I saw there is an 'IN' operation in the expressions but that can't be used in the KeyConditionExpression, it can be used in FilterExpreassion but in filterExpression I can't use primary key. And moreover I can't pass only filter expression in the query I have to pass a key expression as well but in my case I don't have any other condition to check.

```<code>    let readparams  = {
      TableName : "user",
      FilterExpression: "id IN (:id1, :id2)",
      ExpressionAttributeValues: {
        ":id1":1,
        ":id2":1
      }
    };
</code>```

So eventually I've left with only option, to load all the data in the frontend and then filter those using ids in the frontend, but obviously that's not a good solution at all.

Can someone please point out what is the best solution here.

答:
Batch get item API can be used to get multiple items by key attributes. If you have sort key defined for your table, you need to provide both partition and sort key attribute value.

Batch get item

Some sample code:-

```<code>var table = "phone";

var params = {
    "RequestItems" : {
        "phone" : {
            "Keys" : [ {
                "phone_num" : "+14085551212",
                "Country" : "USA"
            },
            {
                "phone_num" : "+14085551313",
                "Country" : "USA"
            }
             ]
        }
    }

};

docClient.batchGet(params, function(err, data) {
    if (err) {
        console.error("Unable to read item. Error JSON:", JSON.stringify(err,
                null, 2));
    } else {
        console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
    }
});
</code>```

Body:
I'm working on a application that is using DynamoDB as the database.
I have a table of users like:

{
   id: 1, (Primary Key)
   name: "Indranil"
}

Now my requirement is, I have the array if ids like : [1,5,8] and I want to load all the users using single query.

Now I'm using the id as keyConditionExpreassion in the query and I can fetch each user data one after another, but then it'll result in multiple queries.

    let readparams  = {
      TableName : "user",
      KeyConditionExpression: "# = :",
      ExpressionAttributeNames:{
        "#": "id"
      },
      ExpressionAttributeValues: {
        ":id":1
      }
    };

Then I saw there is an 'IN' operation in the expressions but that can't be used in the KeyConditionExpression, it can be used in FilterExpreassion but in filterExpression I can't use primary key. And moreover I can't pass only filter expression in the query I have to pass a key expression as well but in my case I don't have any other condition to check.

    let readparams  = {
      TableName : "user",
      FilterExpression: "id IN (:id1, :id2)",
      ExpressionAttributeValues: {
        ":id1":1,
        ":id2":1
      }
    };

So eventually I've left with only option, to load all the data in the frontend and then filter those using ids in the frontend, but obviously that's not a good solution at all.

Can someone please point out what is the best solution here.

Body:
Batch get item API can be used to get multiple items by key attributes. If you have sort key defined for your table, you need to provide both partition and sort key attribute value.

Batch get item

Some sample code:-

var table = "phone";

var params = {
    "RequestItems" : {
        "phone" : {
            "Keys" : [ {
                "phone_num" : "+14085551212",
                "Country" : "USA"
            },
            {
                "phone_num" : "+14085551313",
                "Country" : "USA"
            }
             ]
        }
    }

};

docClient.batchGet(params, function(err, data) {
    if (err) {
        console.error("Unable to read item. Error JSON:", JSON.stringify(err,
                null, 2));
    } else {
        console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
    }
});


问:
TypeError: express is not a function
Hi I'm trying to use jade and express together. But it is giving me TypeError.
I made npm init, npm install express -save and then node app.js. But it is giving me same error "TypeError: express is not a function"

```<code>// Module dependencies
var express = require('express')
  , nib = require('nib')
  , mysql = require('mysql')

 var app = express();

var app = module.exports = app.createServer();

app.set('views', __dirname + '/views')
app.set('view engine', 'jade')
app.use(express.logger('dev'))
</code>```

And package.json :

```<code>{
  "name": "reddit-node-mysql",
  "description": "A demo of how to use Express and MySQL together",
  "author": "Clarence Leung <github@clarle>",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "express": "^2.5.11",
    "mysql": "~2.0",
    "nib": "^1.1.2",
    "jade": "^1.0.4"
  },
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "license": "ISC",
  "devDependencies": {}
}
</code>```

Solution
My modules' version outdated so they can't installed well. I updated version of them, now working.

答:
You are using outdated express ,

Remove

"express": "^2.5.11", from package json
and run

npm install --save express

Title: TypeError: express is not a function

Body:
Hi I'm trying to use jade and express together. But it is giving me TypeError.
I made npm init, npm install express -save and then node app.js. But it is giving me same error "TypeError: express is not a function"

// Module dependencies
var express = require('express')
  , nib = require('nib')
  , mysql = require('mysql')

 var app = express();

var app = module.exports = app.createServer();

app.set('views', __dirname + '/views')
app.set('view engine', 'jade')
app.use(express.logger('dev'))

And package.json :

{
  "name": "reddit-node-mysql",
  "description": "A demo of how to use Express and MySQL together",
  "author": "Clarence Leung <github@clarle>",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "express": "^2.5.11",
    "mysql": "~2.0",
    "nib": "^1.1.2",
    "jade": "^1.0.4"
  },
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "license": "ISC",
  "devDependencies": {}
}

Solution
My modules' version outdated so they can't installed well. I updated version of them, now working.


问:
What is the process of getting browser support to my custom application layer protocol?
I have a custom protocol(TCP based) working with 2 java based client and a server as a prototype. If I am to get browsers support to this what is the process and what are my chances?</p>

答:
"Browser support"?

If you need a web server there are two basic approaches: you either write one yourself or you adapt one that's already available. For the latter, you can either integrate your application into the server by using a present API or write a frontend interfacing with your application (which is probably the most common approach).


问:
Application works in Debug - Fails when compiled
I have a situation I just don't understand.

I have a c# class library application that works perfectly when I step through it in debug mode within VS2017.

When I compile it in "Debug" mode and call it from a console app it fails when calling a https API endpoint and does not report any error.

This is how I am calling the "CreateOrder":

```<code>// send the order to DNAGenotek
DNAGenotek.Model.Order.CreateResponse.CreateOrderResponse orderResponse = await DNAGenotek.Orders.CreateOrder(DNAGenotekAPIKey, DNAGenotekOrder);
</code>```

This is how I am calling the "CallAPIString" function:

```<code>public static async Task<Model.Order.CreateResponse.CreateOrderResponse> CreateOrder(string APIKey, Model.Order.Create.Order order)
    {
        // convert the object to a string
        string orderAsString = JsonConvert.SerializeObject(order);

        // create the order
        string result = await Helpers.CallAPIString(APIKey, "https://sofia-stage.dnagenotek.com/api/v2/orders", "POST", orderAsString);

        DNAGenotek.Model.Order.CreateResponse.CreateOrderResponse orderResponse = JsonConvert.DeserializeObject<Model.Order.CreateResponse.CreateOrderResponse>(result);

        return orderResponse;
    }
</code>```

I have attached to the running console .exe and stepped through and it fails on this line when doing a POST

```<code>WebResponse httpResponseGETDELETE = await httpWebRequest.GetResponseAsync();
</code>```

In the following code:

```<code>public static async Task<string> CallAPIString(string APIKey, string url, string method, string bodyContent = null)
    {
        try
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.Method = method;
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Headers.Add("Authorization", "Basic " + APIKey);

            switch (method)
            {
                case "GET":
                case "DELETE":
                    WebResponse httpResponseGETDELETE = await httpWebRequest.GetResponseAsync();

                    using (StreamReader streamReader = new StreamReader(httpResponseGETDELETE.GetResponseStream()))
                    {
                        string result = await streamReader.ReadToEndAsync();
                        return result;
                    }
                case "POST":
                case "PUT":
                case "PATCH":
                    using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                    {
                        await streamWriter.WriteLineAsync(bodyContent);
                        await streamWriter.FlushAsync();
                        streamWriter.Close();

                        WebResponse httpResponsePOSTPUT = await httpWebRequest.GetResponseAsync();

                        using (StreamReader streamReader = new StreamReader(httpResponsePOSTPUT.GetResponseStream()))
                        {
                            string result = await streamReader.ReadToEndAsync();
                            return result;
                        }
                    }
                default:
                    return "Method Not Found!";
            }
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }
</code>```

It doesn't even bubble up to the catch line. It just closes the app.

When I watch the network traffic in Fiddler I can see it attempting to open the https connection but it then stalls.

This is what I see in Fiddler:

I am complete stumped how to get to the root cause without an error message?

UPDATE

I have now rewritten my code using the HttpClient and it now fails at the line:

```<code>HttpResponseMessage response = await client.PostAsync(url, content);
</code>```

in this code:

```<code>using (HttpClient client = new HttpClient())
{
   client.DefaultRequestHeaders.Add("Authorization", "Basic " + APIKey);
   StringContent content = new StringContent(bodyContent, System.Text.Encoding.UTF8, "application/json");

   HttpResponseMessage response = await client.PostAsync(url, content);
   return await response.Content.ReadAsStringAsync();
}
</code>```

答:
OK - this was my fault.

In the console application I was using :

```<code>SyncEngine.Functions.Sync("APIKey1", "APIKey2");
</code>```

When I should have been using:

```<code>SyncEngine.Functions.Sync("APIKey1", "APIKey2").GetAwaiter().GetResult();
</code>```

Sorry guys

Body:
I have a situation I just don't understand.

I have a c# class library application that works perfectly when I step through it in debug mode within VS2017.

When I compile it in "Debug" mode and call it from a console app it fails when calling a https API endpoint and does not report any error.

This is how I am calling the "CreateOrder":

// send the order to DNAGenotek
DNAGenotek.Model.Order.CreateResponse.CreateOrderResponse orderResponse = await DNAGenotek.Orders.CreateOrder(DNAGenotekAPIKey, DNAGenotekOrder);

This is how I am calling the "CallAPIString" function:

public static async Task<Model.Order.CreateResponse.CreateOrderResponse> CreateOrder(string APIKey, Model.Order.Create.Order order)
    {
        // convert the object to a string
        string orderAsString = JsonConvert.SerializeObject(order);

        // create the order
        string result = await Helpers.CallAPIString(APIKey, "https://sofia-stage.dnagenotek.com/api/v2/orders", "POST", orderAsString);

        DNAGenotek.Model.Order.CreateResponse.CreateOrderResponse orderResponse = JsonConvert.DeserializeObject<Model.Order.CreateResponse.CreateOrderResponse>(result);

        return orderResponse;
    }

I have attached to the running console .exe and stepped through and it fails on this line when doing a POST

WebResponse httpResponseGETDELETE = await httpWebRequest.GetResponseAsync();

In the following code:

public static async Task<string> CallAPIString(string APIKey, string url, string method, string bodyContent = null)
    {
        try
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.Method = method;
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Headers.Add("Authorization", "Basic " + APIKey);

            switch (method)
            {
                case "GET":
                case "DELETE":
                    WebResponse httpResponseGETDELETE = await httpWebRequest.GetResponseAsync();

                    using (StreamReader streamReader = new StreamReader(httpResponseGETDELETE.GetResponseStream()))
                    {
                        string result = await streamReader.ReadToEndAsync();
                        return result;
                    }
                case "POST":
                case "PUT":
                case "PATCH":
                    using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                    {
                        await streamWriter.WriteLineAsync(bodyContent);
                        await streamWriter.FlushAsync();
                        streamWriter.Close();

                        WebResponse httpResponsePOSTPUT = await httpWebRequest.GetResponseAsync();

                        using (StreamReader streamReader = new StreamReader(httpResponsePOSTPUT.GetResponseStream()))
                        {
                            string result = await streamReader.ReadToEndAsync();
                            return result;
                        }
                    }
                default:
                    return "Method Not Found!";
            }
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }

It doesn't even bubble up to the catch line. It just closes the app.

When I watch the network traffic in Fiddler I can see it attempting to open the https connection but it then stalls.

This is what I see in Fiddler:

I am complete stumped how to get to the root cause without an error message?

UPDATE

I have now rewritten my code using the HttpClient and it now fails at the line:

HttpResponseMessage response = await client.PostAsync(url, content);

in this code:

using (HttpClient client = new HttpClient())
{
   client.DefaultRequestHeaders.Add("Authorization", "Basic " + APIKey);
   StringContent content = new StringContent(bodyContent, System.Text.Encoding.UTF8, "application/json");

   HttpResponseMessage response = await client.PostAsync(url, content);
   return await response.Content.ReadAsStringAsync();
}

Body:
OK - this was my fault.

In the console application I was using :

SyncEngine.Functions.Sync("APIKey1", "APIKey2");

When I should have been using:

SyncEngine.Functions.Sync("APIKey1", "APIKey2").GetAwaiter().GetResult();

Sorry guys


问:
CSS3 PIE background color transparency
I am using CSS3 PIE for adding CSS3 Rules to IE.

http://css3pie.com/
It's great but I have a little problem now m using a semi transparent image for the background and PIE.htc automatically adds a gray background.
"background-color:Transparent;" is not working for me.

My question is this: how can I use CSS3 PIE with transparent background?

答: Okay, well the problem is that you are probably setting just the background property but not the generated -pie-background property. So, try this -pie-background: transparent;. Sorry, I may not be of much help because I am not familiar to CSS3 PIE.

Title: CSS3 PIE background color transparency


问:
Android using both WebViewClient and WebChromeClient
I need to manipulate the links in the html so i'm using a WebViewClient to do it. The problem is I've got some iframes that load local html pages and they aren't displyed.
But, if i use the WebChromeClient they works!

So, i want to use the both of them but it doesn't work. It seems that only the webViewClient works, I don't know why.

I set Internet permission and write to external storage (because my html is located in the storage) in the manifest and enabled the hardware acceleration as well.

this is my code:

```<code>public class BChromeClient : WebChromeClient
    {
        public BChromeClient ()
        {}

        public bool OnShowCustomView(WebView view, string url)
        {
            return true;
        }

        public void OnHideCustomView()
        {
        }

    }

    public class BWebClient : WebViewClient
    {
        int _position;
        string _path;
        Activity _parent;
        ViewPager _pager;
        string _chapName;
        public BWebClient (int position, string Path, Activity Parent, ViewPager Pager, string ChapName){
            _position = position;
            _parent = Parent;
            _path = Path;
            _pager = Pager;
            _chapName = ChapName;
        }

        public override void OnPageFinished (WebView view, string url)
        {
            base.OnPageFinished (view, url);
            view.ScrollTo (0, _position);
        }

        public override bool ShouldOverrideUrlLoading (WebView view, string url)
        {

            if (url.StartsWith ("navigate")) {
                string destination = url.Substring (url.IndexOf ("navigate://") + "navigate://".Length);
                int DestinationChapter = Int32.Parse (destination.Substring (0, destination.IndexOf("_")));
                int l = destination.IndexOf("_") + 1;
                int b = destination.Length - l;
                int DestinationPage = Int32.Parse (destination.Substring (l,b));

                if (DestinationPage == 0) {
                    _pager.SetCurrentItem(DestinationChapter ,true);
                    WebView _web = (WebView)_pager.FindViewWithTag(300 + DestinationChapter);
                    _web.LoadUrl ("file://" + _path + "/" + _chapName);
                }

            } else if (url.StartsWith ("pdf")) {
                string file_path = _path + url.Substring (5);
                if (System.IO.File.Exists(file_path)) {
                    Android.Net.Uri pdfFile = Android.Net.Uri.FromFile (new Java.IO.File (file_path));
                    Intent pdfIntent = new Intent (Intent.ActionView);
                    pdfIntent.SetDataAndType (pdfFile, "application/pdf");
                    pdfIntent.SetFlags (ActivityFlags.NoHistory);
                    _parent.StartActivity (pdfIntent);
                }
            }

            return true;
        }
    }
</code>```

While in the fragment OnCreateView method (Yeah, i'm using a webview inside a PageViewer, but i don't think it is important to know).

```<code>web_view = view.FindViewById<WebView> (Resource.Id.webview);
        web_view.SetWebChromeClient (new BChromeClient ());
        web_view.SetWebViewClient(new BWebClient(_position,_path,_parent, _pager, _chap.Name ));
        web_view.SetBackgroundColor(Color.Transparent);
        web_view.Settings.JavaScriptEnabled = true;
        web_view.Settings.AllowFileAccess = true;
        //web_view.Settings.SetPluginState (WebSettings.PluginState.On);
</code>```

答:
In MainActivity.cs </p>

```<code>web_view..webviewClient = new ExtendedWebViewClient();
 web_view.SetWebChromeClient(new ExtendedChromeClient(MainActivity));
            web_view.SetWebViewClient(this.webviewClient);
</code>```

Body:
I need to manipulate the links in the html so i'm using a WebViewClient to do it. The problem is I've got some iframes that load local html pages and they aren't displyed.
But, if i use the WebChromeClient they works!

So, i want to use the both of them but it doesn't work. It seems that only the webViewClient works, I don't know why.

I set Internet permission and write to external storage (because my html is located in the storage) in the manifest and enabled the hardware acceleration as well.

this is my code:

public class BChromeClient : WebChromeClient
    {
        public BChromeClient ()
        {}

        public bool OnShowCustomView(WebView view, string url)
        {
            return true;
        }

        public void OnHideCustomView()
        {
        }

    }

    public class BWebClient : WebViewClient
    {
        int _position;
        string _path;
        Activity _parent;
        ViewPager _pager;
        string _chapName;
        public BWebClient (int position, string Path, Activity Parent, ViewPager Pager, string ChapName){
            _position = position;
            _parent = Parent;
            _path = Path;
            _pager = Pager;
            _chapName = ChapName;
        }

        public override void OnPageFinished (WebView view, string url)
        {
            base.OnPageFinished (view, url);
            view.ScrollTo (0, _position);
        }

        public override bool ShouldOverrideUrlLoading (WebView view, string url)
        {

            if (url.StartsWith ("navigate")) {
                string destination = url.Substring (url.IndexOf ("navigate://") + "navigate://".Length);
                int DestinationChapter = Int32.Parse (destination.Substring (0, destination.IndexOf("_")));
                int l = destination.IndexOf("_") + 1;
                int b = destination.Length - l;
                int DestinationPage = Int32.Parse (destination.Substring (l,b));

                if (DestinationPage == 0) {
                    _pager.SetCurrentItem(DestinationChapter ,true);
                    WebView _web = (WebView)_pager.FindViewWithTag(300 + DestinationChapter);
                    _web.LoadUrl ("file://" + _path + "/" + _chapName);
                }

            } else if (url.StartsWith ("pdf")) {
                string file_path = _path + url.Substring (5);
                if (System.IO.File.Exists(file_path)) {
                    Android.Net.Uri pdfFile = Android.Net.Uri.FromFile (new Java.IO.File (file_path));
                    Intent pdfIntent = new Intent (Intent.ActionView);
                    pdfIntent.SetDataAndType (pdfFile, "application/pdf");
                    pdfIntent.SetFlags (ActivityFlags.NoHistory);
                    _parent.StartActivity (pdfIntent);
                }
            }

            return true;
        }
    }

While in the fragment OnCreateView method (Yeah, i'm using a webview inside a PageViewer, but i don't think it is important to know).

web_view = view.FindViewById<WebView> (Resource.Id.webview);
        web_view.SetWebChromeClient (new BChromeClient ());
        web_view.SetWebViewClient(new BWebClient(_position,_path,_parent, _pager, _chap.Name ));
        web_view.SetBackgroundColor(Color.Transparent);
        web_view.Settings.JavaScriptEnabled = true;
        web_view.Settings.AllowFileAccess = true;
        //web_view.Settings.SetPluginState (WebSettings.PluginState.On);

Body:
In MainActivity.cs

web_view..webviewClient = new ExtendedWebViewClient();
 web_view.SetWebChromeClient(new ExtendedChromeClient(MainActivity));
            web_view.SetWebViewClient(this.webviewClient);


问:
Unexpected namespace prefix "app" found for tag TextView when I try to set fontFamily attribute
I set app:fontFamily="@font/montserrat_bold" on TextView and i get error: Unexpected namespace prefix "app" found for tag TextView. I use Android Studio 3.0. Is there any solution?

答: Changing TextView to android.support.v7.widget.AppCompatTextView works if I use "app" name space prefix. If I use "android" name space prefix it provides compatibility with API version 16 and higher, but I needed compatibility from API version 14 so "app" prefix solved my problem.


问:
Get the Week Number in iOS SDK
I want to get the Week number of the year from the date.I tried the code as follow but gives me a wrong week number.

My code for week number:

```<code>NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSDate *date = [dateFormatter dateFromString:@"2012-09-15"];

    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSLog(@"week: %i", [[calendar components: NSWeekOfYearCalendarUnit fromDate:date] weekOfYear]); //Display 38 instead of 37
}
</code>```

Note: If i try with with [NSDate date] display the correct.

Help me to solve this..
Thank you,

答:
Updated code in ObjectiveC used Xcode version - 9.1 - :</p>

```<code>    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponent = [calendar components:(NSCalendarUnitWeekOfYear | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:[NSDate date]];
    NSLog(@"%ld",(long)[dateComponent weekOfYear]);
</code>```

Title: Get the Week Number in iOS SDK

Body:
I want to get the Week number of the year from the date.I tried the code as follow but gives me a wrong week number.

My code for week number:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSDate *date = [dateFormatter dateFromString:@"2012-09-15"];

    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSLog(@"week: %i", [[calendar components: NSWeekOfYearCalendarUnit fromDate:date] weekOfYear]); //Display 38 instead of 37
}

Note: If i try with with [NSDate date] display the correct.

Help me to solve this..
Thank you,

Body:
Updated code in ObjectiveC used Xcode version - 9.1 - :

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponent = [calendar components:(NSCalendarUnitWeekOfYear | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:[NSDate date]];
    NSLog(@"%ld",(long)[dateComponent weekOfYear]);