问:
Using Android UIAutomator in Python or Ruby
I am trying to automate android apps using python (or possibly ruby), by linking into the provided UIAutomator in the android SDK.

Right now I am trying to use a Python tool here, but I am having issues connecting (getting TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

Code snipped of what i am trying to do with the Python tool:

```<code>    def print_info():
        print('Getting info...')
        d = ui.Device('SERIAL_NUMBER', adb_server_host='192.168.1.20', adb_server_port='5037')
        print(d.info)
</code>```

Is there something wrong with how I am trying to send commands? Alternatively, is there a better ruby/python tool for testing android devices?

Update I am now using the Appium library Ruby gem to test. Got applications to launch, however things like tapping the screen result in this error

```<code>assert_ok': A session is either terminated or not started
(Selenium::WebDriver::Error::NoSuchDriverError)`
</code>```

This is the code

```<code>desired_caps = {
  caps:       {
    appiumVersion:    '1.6.5',
    platformName:     'Android',
    platformVersion:  '4.4',
    browserName:      '',
    deviceName:       'DEVICE_SERIAL',
    app:              'APK',
    appActivity:      'mainactivity',
    appWaitDuration:  '60000', # wait a minute (set to 20000 by default)
    clearSystemFiles: 'true'
  },
  appium_lib: {
    sauce_username:    nil,
    sauce_access_key:  nil
  }
}

$driver = Appium::Driver.new(desired_caps)
$driver.start_driver
sleep(60) # wait a minute for app to fully load, before tring to tap anything
touch_action = Appium::TouchAction.new
touch_action.press(x: 243, y: 288).wait(5).release.perform
touch_action.press(x: 311, y: 165).wait(5).release.perform
</code>```

答:
There is an one good mobile test automation tool available - Appium.
Currently I have been using ruby,appium,cucumber,selenium webdriver for android automation. I am suggesting that you will try to use Appium tool for mobile automation. below is important link,

http://www.software-testing-tutorials-automation.com/2015/09/appium-tutorials.html
https://community.perfectomobile.com/posts/1103155-ruby-example-for-appium-android
http://appium.io/slate/en/tutorial/android.html?ruby#troubleshooting

```<code>following is the example to start
require 'appium_lib'
desired_caps = {
     caps:       {   appiumVersion:    '1.6.0',
      platformName:     'Android',
      platformVersion:  '4.4.2',
      browserName:       '',
     deviceName:       'Samsung Galaxy S4 Emulator',
     app:              'D:\Workspace\android-sample-app.apk',
    name:             'Ruby Appium Sauce example'
  }       }
driver = Appium::Driver.new(desired_caps)
puts driver
begin
  driver.start_driver
  rescue Exception => e
  puts e
end
driver.first_textfield.send_key 10
driver.last_textfield.send_key 20
driver.first_button.click
driver.driver_quit
download "android-sample-app.apk" and put in any path and also set this path
in desired_caps.
</code>```

Thanks,
Kapil Chothe

Body:
I am trying to automate android apps using python (or possibly ruby), by linking into the provided UIAutomator in the android SDK.

Right now I am trying to use a Python tool here, but I am having issues connecting (getting TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

Code snipped of what i am trying to do with the Python tool:

    def print_info():
        print('Getting info...')
        d = ui.Device('SERIAL_NUMBER', adb_server_host='192.168.1.20', adb_server_port='5037')
        print(d.info)

Is there something wrong with how I am trying to send commands? Alternatively, is there a better ruby/python tool for testing android devices?

Update I am now using the Appium library Ruby gem to test. Got applications to launch, however things like tapping the screen result in this error

assert_ok': A session is either terminated or not started
(Selenium::WebDriver::Error::NoSuchDriverError)`

This is the code

desired_caps = {
  caps:       {
    appiumVersion:    '1.6.5',
    platformName:     'Android',
    platformVersion:  '4.4',
    browserName:      '',
    deviceName:       'DEVICE_SERIAL',
    app:              'APK',
    appActivity:      'mainactivity',
    appWaitDuration:  '60000', # wait a minute (set to 20000 by default)
    clearSystemFiles: 'true'
  },
  appium_lib: {
    sauce_username:    nil,
    sauce_access_key:  nil
  }
}

$driver = Appium::Driver.new(desired_caps)
$driver.start_driver
sleep(60) # wait a minute for app to fully load, before tring to tap anything
touch_action = Appium::TouchAction.new
touch_action.press(x: 243, y: 288).wait(5).release.perform
touch_action.press(x: 311, y: 165).wait(5).release.perform

Body:
There is an one good mobile test automation tool available - Appium.
Currently I have been using ruby,appium,cucumber,selenium webdriver for android automation. I am suggesting that you will try to use Appium tool for mobile automation. below is important link,

http://www.software-testing-tutorials-automation.com/2015/09/appium-tutorials.html
https://community.perfectomobile.com/posts/1103155-ruby-example-for-appium-android
http://appium.io/slate/en/tutorial/android.html?ruby#troubleshooting

following is the example to start
require 'appium_lib'
desired_caps = {
     caps:       {   appiumVersion:    '1.6.0',
      platformName:     'Android',
      platformVersion:  '4.4.2',
      browserName:       '',
     deviceName:       'Samsung Galaxy S4 Emulator',
     app:              'D:\Workspace\android-sample-app.apk',
    name:             'Ruby Appium Sauce example'
  }       }
driver = Appium::Driver.new(desired_caps)
puts driver
begin
  driver.start_driver
  rescue Exception => e
  puts e
end
driver.first_textfield.send_key 10
driver.last_textfield.send_key 20
driver.first_button.click
driver.driver_quit
download "android-sample-app.apk" and put in any path and also set this path
in desired_caps.

Thanks,
Kapil Chothe


来源: stackexchange

问:
JSP returning null for request.getParameter() but shows values in EL
I am new to servlets and JSPs.
Recently.. I have been trying to send data from my Servlet to JSP using requestDispatcher.

This is my Servlet code responsible:

```<code>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        sampleClass sampleObject = new sampleClass(1, "myname");
        ObjectMapper mapper = new ObjectMapper();
        String jsonstring = mapper.writeValueAsString(sampleObject);
        request.setAttribute("values", jsonstring);
        request.setAttribute("valuees", "testing");
        request.getRequestDispatcher("/somejsp").forward(request, response);
    }
</code>```

My JSP part responsible for retrieving data:

```<code>${values}
${valuees}
<%
    //out.println(Message);
    Enumeration enume = request.getParameterNames();
    for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
        String name = entry.getKey();
        String value = entry.getValue()[0];
        // ...
    }
    String value = request.getParameter("values");
    out.println(value);
    String valuee = request.getParameter("valuees");
    out.println(valuee);
 %>
</code>```

But the output I get is:

{"n":1,"name":"myname"} testing null null

as you can see both the EL gives correct output, the implementation with the Enumeration returns nothing and the other two return null.

I donot understand this. I couldn't find any solution online.

答: You're confusing attributes (any object that you choose to store in the request, under a name you choose), with parameters (strings sent by the browser as part of the request, as in foo=bar&baz=2.

ContentLicense: CC BY-SA 3.0

Body:
I am new to servlets and JSPs.
Recently.. I have been trying to send data from my Servlet to JSP using requestDispatcher.

This is my Servlet code responsible:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        sampleClass sampleObject = new sampleClass(1, "myname");
        ObjectMapper mapper = new ObjectMapper();
        String jsonstring = mapper.writeValueAsString(sampleObject);
        request.setAttribute("values", jsonstring);
        request.setAttribute("valuees", "testing");
        request.getRequestDispatcher("/somejsp").forward(request, response);
    }

My JSP part responsible for retrieving data:

${values}
${valuees}
<%
    //out.println(Message);
    Enumeration enume = request.getParameterNames();
    for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
        String name = entry.getKey();
        String value = entry.getValue()[0];
        // ...
    }
    String value = request.getParameter("values");
    out.println(value);
    String valuee = request.getParameter("valuees");
    out.println(valuee);
 %>

But the output I get is:

{"n":1,"name":"myname"} testing null null

as you can see both the EL gives correct output, the implementation with the Enumeration returns nothing and the other two return null.

I donot understand this. I couldn't find any solution online.


问:
google-map tiles missing alt tag causing lower accessibility score
How can we add blank alt tags to the Google map tiles (generated by v3 api) so that they do not lower our accessibility score?

http://berkeley.edu/map/googlemap/

答:
I ended up using javascript to add the alt tags.  Please note the map id is unique to my specific map.</p>

```<code>google.maps.event.addListener(this.map, 'tilesloaded', function() {
  var images = document.querySelectorAll('#gmap_canvas1 img');
  images.forEach(function(image) {
    image.alt = "Google Maps Image";
  });
});
</code>```

Body:
I ended up using javascript to add the alt tags.  Please note the map id is unique to my specific map.

google.maps.event.addListener(this.map, 'tilesloaded', function() {
  var images = document.querySelectorAll('#gmap_canvas1 img');
  images.forEach(function(image) {
    image.alt = "Google Maps Image";
  });
});


问:
difficulty in updating csv file
I tried to update the CSV file with a description column.  I tried to add an update to the model by adding description = models.CharField(max_length=200, default='SOME STRING') like this:

```<code>wine = models.ForeignKey(Wine)
    pub_date = models.DateTimeField('date published')
    user_name = models.CharField(max_length=100)
    comment = models.CharField(max_length=200)
    rating = models.IntegerField(choices=RATING_CHOICES)
    description = models.CharField(max_length=200, default='SOME STRING')
</code>```

When I run migrate for this change I get the following error:

```<code>c:\Users\Amira Joshi\Desktop\winerama>python manage.py makemigrations
Migrations for 'reviews':
  reviews\migrations\0002_review_description.py
    - Add field description to review
</code>```

How can I solve it?  Please help!

答:
This is not an error:

```<code>c:\Users\Amira Joshi\Desktop\winerama>python manage.py makemigrations
Migrations for 'reviews':   reviews\migrations\0002_review_description.py
    - Add field description to review
</code>```

With this django says that the migration file is created, now you must apply the migration by running this command:

```<code>python manage.py migrate
</code>```

Title: difficulty in updating csv file

Body:
I tried to update the CSV file with a description column.  I tried to add an update to the model by adding description = models.CharField(max_length=200, default='SOME STRING') like this:

wine = models.ForeignKey(Wine)
    pub_date = models.DateTimeField('date published')
    user_name = models.CharField(max_length=100)
    comment = models.CharField(max_length=200)
    rating = models.IntegerField(choices=RATING_CHOICES)
    description = models.CharField(max_length=200, default='SOME STRING')

When I run migrate for this change I get the following error:

c:\Users\Amira Joshi\Desktop\winerama>python manage.py makemigrations
Migrations for 'reviews':
  reviews\migrations\0002_review_description.py
    - Add field description to review

How can I solve it?  Please help!

Body:
This is not an error:

c:\Users\Amira Joshi\Desktop\winerama>python manage.py makemigrations
Migrations for 'reviews':   reviews\migrations\0002_review_description.py
    - Add field description to review

With this django says that the migration file is created, now you must apply the migration by running this command:

python manage.py migrate


问:
Loading UIViewController inside an UIScrollView Swift3
I have 2 UIViewControllers.
One UIViewController has a view with many buttons and is +2000 points high.
Another UIViewController has a UIScrollView.

This is my code:

```<code>import UIKit

 class ViewController: UIViewController {

@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    scrollView.contentSize = CGSize(width: 375, height: 2884)

    DispatchQueue.main.async {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let thumb_vc = storyboard.instantiateViewController(withIdentifier: "thumb") as! ThumbsViewController
        //self.present(vc, animated: true, completion: nil)

    self.addChildViewController(thumb_vc)
    self.scrollView.addSubview(thumb_vc.view)
   }
 }
</code>```

and although the thumbs UIViewController get loaded to UIScrollView, the size is wrong and does not scroll.

Any help appreciated

答:
You are running into an issue with the Views being resized when loaded at run-time. Couple options...

```<code>// NOT USING constraints / auto-layout
func setupA() -> Void {

    scrollView.contentSize = CGSize(width: 375, height: 2884)

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    if let vc = storyboard.instantiateViewController(withIdentifier: "thumb") as? ThumbsViewController {

        // add the child VC
        self.addChildViewController(vc)

        // don't let "thumbs" view auto-resize
        vc.view.autoresizingMask = []

        // set "thumbs" view frame size to scroll view content size
        vc.view.frame = CGRect(origin: CGPoint.zero, size: scrollView.contentSize)

        // add "thumbs" view to the scroll view
        self.scrollView.addSubview(vc.view)

        // finish child VC process
        vc.didMove(toParentViewController: self)
    }

}

// USING constraints / auto-layout, with hard-coded sizing
func setupB() -> Void {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    if let vc = storyboard.instantiateViewController(withIdentifier: "thumb") as? ThumbsViewController {

        // add the child VC
        self.addChildViewController(vc)

        // add "thumbs" view to the scroll view
        self.scrollView.addSubview(vc.view)

        // disable auto-resizing mask
        vc.view.translatesAutoresizingMaskIntoConstraints = false

        // set constraints to both control the size of the "thumbs" view
        // as well as the contentSize of the scroll view

        // set width and height constraints for the "thumbs" view
        vc.view.widthAnchor.constraint(equalToConstant: 375).isActive = true
        vc.view.heightAnchor.constraint(equalToConstant: 2884).isActive = true

        // set leading, top, trailing, and bottom constraints to the scroll view
        vc.view.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
        vc.view.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
        vc.view.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
        vc.view.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true

        // finish child VC process
        vc.didMove(toParentViewController: self)
    }

}

// USING constraints / auto-layout, with sizing controlled by constraints set in IB for the "thumbs" view
func setupC() -> Void {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    if let vc = storyboard.instantiateViewController(withIdentifier: "althumb") as? ALThumbsViewController {

        // add the child VC
        self.addChildViewController(vc)

        // add "thumbs" view to the scroll view
        self.scrollView.addSubview(vc.view)

        // disable auto-resizing mask
        vc.view.translatesAutoresizingMaskIntoConstraints = false

        // the constraints set in Interface Builder for the elements in the "thumbs" view
        // will control its size

        // setting the "edge" constraints relative to the scroll view will control the contentSize

        // set leading, top, trailing, and bottom constraints to the scroll view
        vc.view.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
        vc.view.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
        vc.view.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
        vc.view.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true

        // finish child VC process
        vc.didMove(toParentViewController: self)
    }

}
</code>```

I'd recommend the method in setupC() It uses auto-layout constraints with no hard-coded size values. Makes it much easier to plan for different device sizes (and future use in other views / apps / jobs / etc).

Body:
I have 2 UIViewControllers.
One UIViewController has a view with many buttons and is +2000 points high.
Another UIViewController has a UIScrollView.

This is my code:

import UIKit

 class ViewController: UIViewController {

@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    scrollView.contentSize = CGSize(width: 375, height: 2884)

    DispatchQueue.main.async {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let thumb_vc = storyboard.instantiateViewController(withIdentifier: "thumb") as! ThumbsViewController
        //self.present(vc, animated: true, completion: nil)

    self.addChildViewController(thumb_vc)
    self.scrollView.addSubview(thumb_vc.view)
   }
 }

and although the thumbs UIViewController get loaded to UIScrollView, the size is wrong and does not scroll.

Any help appreciated

Body:
You are running into an issue with the Views being resized when loaded at run-time. Couple options...

// NOT USING constraints / auto-layout
func setupA() -> Void {

    scrollView.contentSize = CGSize(width: 375, height: 2884)

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    if let vc = storyboard.instantiateViewController(withIdentifier: "thumb") as? ThumbsViewController {

        // add the child VC
        self.addChildViewController(vc)

        // don't let "thumbs" view auto-resize
        vc.view.autoresizingMask = []

        // set "thumbs" view frame size to scroll view content size
        vc.view.frame = CGRect(origin: CGPoint.zero, size: scrollView.contentSize)

        // add "thumbs" view to the scroll view
        self.scrollView.addSubview(vc.view)

        // finish child VC process
        vc.didMove(toParentViewController: self)
    }

}

// USING constraints / auto-layout, with hard-coded sizing
func setupB() -> Void {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    if let vc = storyboard.instantiateViewController(withIdentifier: "thumb") as? ThumbsViewController {

        // add the child VC
        self.addChildViewController(vc)

        // add "thumbs" view to the scroll view
        self.scrollView.addSubview(vc.view)

        // disable auto-resizing mask
        vc.view.translatesAutoresizingMaskIntoConstraints = false

        // set constraints to both control the size of the "thumbs" view
        // as well as the contentSize of the scroll view

        // set width and height constraints for the "thumbs" view
        vc.view.widthAnchor.constraint(equalToConstant: 375).isActive = true
        vc.view.heightAnchor.constraint(equalToConstant: 2884).isActive = true

        // set leading, top, trailing, and bottom constraints to the scroll view
        vc.view.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
        vc.view.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
        vc.view.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
        vc.view.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true

        // finish child VC process
        vc.didMove(toParentViewController: self)
    }

}

// USING constraints / auto-layout, with sizing controlled by constraints set in IB for the "thumbs" view
func setupC() -> Void {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    if let vc = storyboard.instantiateViewController(withIdentifier: "althumb") as? ALThumbsViewController {

        // add the child VC
        self.addChildViewController(vc)

        // add "thumbs" view to the scroll view
        self.scrollView.addSubview(vc.view)

        // disable auto-resizing mask
        vc.view.translatesAutoresizingMaskIntoConstraints = false

        // the constraints set in Interface Builder for the elements in the "thumbs" view
        // will control its size

        // setting the "edge" constraints relative to the scroll view will control the contentSize

        // set leading, top, trailing, and bottom constraints to the scroll view
        vc.view.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
        vc.view.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
        vc.view.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
        vc.view.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true

        // finish child VC process
        vc.didMove(toParentViewController: self)
    }

}

I'd recommend the method in setupC() It uses auto-layout constraints with no hard-coded size values. Makes it much easier to plan for different device sizes (and future use in other views / apps / jobs / etc).


问:
Algorithm/Method Use By Google Maps For Finding the Path Between Two Cities
Recently I had a job interview they asked me "Which method is use by google maps for finding the shortest path between two cities?". I didn't had the answer to that question but I guessed they use the "Shortest Path Algorithm" for finding the path but the interviewer said "No". After that interview I Googled a lot but didn't find any method for that. Please tell me if you have any idea about how google maps find shortest path between two cities</p>

答:
As it happens I just attended a talk about it. Dijkstras Algorithm is too inefficient for google. Although the complexity, n log n , is fine the absolute time it takes is quite large.

Google uses a variant of Contraction Hierarchies. It is faster than Dijkstra because the network is preprocessed. Even though there are faster algorithms out there that involve preprocessing, CH provides a lot of flexibility.


问:
Salesforce: is it possible to develop a web application on top of Salesforce
Let me start with a bit of background: I'm helping a non-profit organization that would like to have a browser-based application that is backed by Salesforce, but has very specific requirements.

I see Salesforce has a REST API that we can call, so we can develop a standalone application to serve the web pages they want and use the REST API to call Salesforce when needed.

I'm wondering if there is a way to host a web application directly on Salesforce; this way we don't have to have a separate application server. Any recommendations or pointers to documentation/open source products is greatly appreciated.

答: Depending on the type of application, yes you can host it on salesforce using the Salesforce Sites feature, also you can develop and host your app on Heroku which is owned by salesforce and can sync data to and from salesforce using Heroku Connect, or you can build and host it on another service like AWS and connect via the REST API.  You just need to investigate and choose the option that best fits your use-case.  One thing to be aware of is that there are API limits (the number of calls you can make to salesforce in a rolling 24hr period).  Depending the the needs of the app be sure to see if those limits will be an issue.  Because if the app makes constant calls to salesforce that could be an issue.  But there are things you can do to get around that, like caching.</p>


问:
Flask Pdfkit create pdf from template and save it
I use pdfkit to create an invoice pdf. At the moment I just want to save it. Later I will save the invoice filename in the DB and store in on AWS3.

But for now I get an IO Error when trying to save the file, probably because I request it the wrong way:

```<code>pdfkit.from_file(render_template('invoice_template.html', invoice_id=1, invioce_date_start=str(date.today()),
                                     invioce_date_end=str(date.today()), invioce_company_name=form.zahlung_firma.data, invioce_user_vorename=form.vorname.data,
                                     invioce_user_surname=form.nachname.data, invioce_user_email=current_user.email), str(current_user.id) + '-invoice.pdf')
</code>```

The Error:

```<code>    Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\flask\app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Python27\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Python27\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python27\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Python27\lib\site-packages\flask\app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Python27\lib\site-packages\flask_login.py", line 758, in decorated_view
    return func(*args, **kwargs)
  File "C:\Users\User\Eclipse-Workspace\Monteurzimmer\main.py", line 114, in decorated_function
    return func(*args, **kwargs)
  File "C:\Users\User\Eclipse-Workspace\Monteurzimmer\main.py", line 1252, in logged_in
    invioce_user_surname=form.nachname.data, invioce_user_email=current_user.email), str(current_user.id) + '-invoice.pdf')
  File "C:\Python27\lib\site-packages\pdfkit\api.py", line 47, in from_file
    configuration=configuration, cover_first=cover_first)
  File "C:\Python27\lib\site-packages\pdfkit\pdfkit.py", line 41, in __init__
    self.source = Source(url_or_file, type_)
  File "C:\Python27\lib\site-packages\pdfkit\source.py", line 12, in __init__
    self.checkFiles()
  File "C:\Python27\lib\site-packages\pdfkit\source.py", line 32, in checkFiles
    raise IOError('No such file: %s' % self.source)
IOError: No such file: <!doctype html>
</code>```

The template itself can be found here, I just edited the jinja variables:

答:
pdfkit.from_file() expects a file object as its input, but render_template() returns a string. Try pdfkit.from_string() instead.

More information: pypi - pdfkit

Body:
I use pdfkit to create an invoice pdf. At the moment I just want to save it. Later I will save the invoice filename in the DB and store in on AWS3.

But for now I get an IO Error when trying to save the file, probably because I request it the wrong way:

pdfkit.from_file(render_template('invoice_template.html', invoice_id=1, invioce_date_start=str(date.today()),
                                     invioce_date_end=str(date.today()), invioce_company_name=form.zahlung_firma.data, invioce_user_vorename=form.vorname.data,
                                     invioce_user_surname=form.nachname.data, invioce_user_email=current_user.email), str(current_user.id) + '-invoice.pdf')

The Error:

    Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\flask\app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Python27\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Python27\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python27\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Python27\lib\site-packages\flask\app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Python27\lib\site-packages\flask_login.py", line 758, in decorated_view
    return func(*args, **kwargs)
  File "C:\Users\User\Eclipse-Workspace\Monteurzimmer\main.py", line 114, in decorated_function
    return func(*args, **kwargs)
  File "C:\Users\User\Eclipse-Workspace\Monteurzimmer\main.py", line 1252, in logged_in
    invioce_user_surname=form.nachname.data, invioce_user_email=current_user.email), str(current_user.id) + '-invoice.pdf')
  File "C:\Python27\lib\site-packages\pdfkit\api.py", line 47, in from_file
    configuration=configuration, cover_first=cover_first)
  File "C:\Python27\lib\site-packages\pdfkit\pdfkit.py", line 41, in __init__
    self.source = Source(url_or_file, type_)
  File "C:\Python27\lib\site-packages\pdfkit\source.py", line 12, in __init__
    self.checkFiles()
  File "C:\Python27\lib\site-packages\pdfkit\source.py", line 32, in checkFiles
    raise IOError('No such file: %s' % self.source)
IOError: No such file: <!doctype html>

The template itself can be found here, I just edited the jinja variables:


问:
Access Element inside Silverlight DataTemplate
I have not been able to find a clean solution to the following problem even though there are a few related questions already on SO.

If I have a data template that is being used multiple times, for example, a TreeViewItem.HeaderTemplate, how can I change something the template for only some of the TreeViewItems.

For example, let's say my TVI HeaderTemplate has a textblock and depending on the string, I want to make the fontweight bold.

I want to do something like this:

```<code>((TextBlock)myTreeView.Items.ElementAt(0).FindName("myTextBlock")).FontWeight = FontWeights.Bold;
</code>```

Does anyone have a solution for this? --> Thanks Evan

Edit: Is there a way to write a generic function to get a control based on it's name even if it's in a data template?

LayoutRoot.FindName("myTextBlock"); would work if myTextBlock was not in a datatemplate. How can I write a findElementInDataTemplate(string elementName, string parentName) function?

The reason Evan's answer is not what I'm looking for is because I am developing a control. I want the application developer who uses my control to be able to change any element in the control. If I use Evan's solution, that would require the application developer to have access to all the templates in the control. Possible, but not ideal. Thanks!

答:
what version of silverlight is this?
And what year of " Aug 10 at 18:55" is this post from?

in the current version of SL4 it does not seem to be there..

ContentLicense: CC BY-SA 2.5

Body:
I have not been able to find a clean solution to the following problem even though there are a few related questions already on SO.

If I have a data template that is being used multiple times, for example, a TreeViewItem.HeaderTemplate, how can I change something the template for only some of the TreeViewItems.

For example, let's say my TVI HeaderTemplate has a textblock and depending on the string, I want to make the fontweight bold.

I want to do something like this:

((TextBlock)myTreeView.Items.ElementAt(0).FindName("myTextBlock")).FontWeight = FontWeights.Bold;

Does anyone have a solution for this? --> Thanks Evan

Edit: Is there a way to write a generic function to get a control based on it's name even if it's in a data template?

LayoutRoot.FindName("myTextBlock"); would work if myTextBlock was not in a datatemplate. How can I write a findElementInDataTemplate(string elementName, string parentName) function?

The reason Evan's answer is not what I'm looking for is because I am developing a control. I want the application developer who uses my control to be able to change any element in the control. If I use Evan's solution, that would require the application developer to have access to all the templates in the control. Possible, but not ideal. Thanks!


问:
Why firebase enter the ondatachange in my query
I have very simple database

```<code>TokenAdmin:
---xccsaccxvkkgmcdds :
     ---token: "cxcxzcfsdfdsfdsfs"
     ---uid: "xccsaccxvkkgmcdds"
---hjhbnghtfgdgdgdffg :
     ---token: "vhghtytyryyr"
     ---uid: "hjhbnghtfgdgdgdffg"
</code>```

Now in my code I want to check and execute some code only if it find uid equal to "hjhbnghtfgdgdgdffg"
Here is my code :

```<code> mDatabase.child("TokenAdmin").orderByChild("uid").equalTo(mycurrUser.getUID()).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

               //say here toast "A"
            } else {
                //toast "B"
            }

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

            // ...

        }

    });
</code>```

Now I run the code with  mycurrUser.getUID() value set to "xxx" which I don't have listed in the database. I expected the code output was toast B, but instead I always get toast A, which in my understanding, it has found the value in the db. How to fix this, where did I do wrong ?

答:
I'm confused why you're using a query to load the user. You seem to store the token under they UID key already, so this would work:</p>

```<code>mDatabase.child("TokenAdmin").child(mycurrUser.getUID()).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            ... user exists
        } else {
            ... user node does not exist
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException(); // don't ignore errors
    }
});
</code>```

Body:
I have very simple database

TokenAdmin:
---xccsaccxvkkgmcdds :
     ---token: "cxcxzcfsdfdsfdsfs"
     ---uid: "xccsaccxvkkgmcdds"
---hjhbnghtfgdgdgdffg :
     ---token: "vhghtytyryyr"
     ---uid: "hjhbnghtfgdgdgdffg"

Now in my code I want to check and execute some code only if it find uid equal to "hjhbnghtfgdgdgdffg"
Here is my code :

 mDatabase.child("TokenAdmin").orderByChild("uid").equalTo(mycurrUser.getUID()).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

               //say here toast "A"
            } else {
                //toast "B"
            }

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

            // ...

        }

    });

Now I run the code with  mycurrUser.getUID() value set to "xxx" which I don't have listed in the database. I expected the code output was toast B, but instead I always get toast A, which in my understanding, it has found the value in the db. How to fix this, where did I do wrong ?

Body:
I'm confused why you're using a query to load the user. You seem to store the token under they UID key already, so this would work:

mDatabase.child("TokenAdmin").child(mycurrUser.getUID()).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            ... user exists
        } else {
            ... user node does not exist
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException(); // don't ignore errors
    }
});


问:
Division of two numbers always returns an integer value
Using the formula "(4/3)*3.14*pow(radius,3)", the number returned always yields to an integer. Any ideas on how to get a floating point number from the formula?

Code:

```<code>#include<iostream>
#include<math.h>

using namespace std;

int main(){
    float radius, v;
    cout<<"Enter value of radius";cin>>radius;
    v = (4/3)*3.14*pow(radius, 3);
    cout<<"volume of sphere: "<<v<<endl;
    system("pause");return 0;
}
</code>```

答:
The expression 4/3 performs integer division, and will result in 1 (it results in truncation of any decimals). You should be performing floating point division.

```<code>v = (4.0/3.0)*3.14*pow(radius, 3);
</code>```

Body:
Using the formula "(4/3)*3.14*pow(radius,3)", the number returned always yields to an integer. Any ideas on how to get a floating point number from the formula?

Code:

#include<iostream>
#include<math.h>

using namespace std;

int main(){
    float radius, v;
    cout<<"Enter value of radius";cin>>radius;
    v = (4/3)*3.14*pow(radius, 3);
    cout<<"volume of sphere: "<<v<<endl;
    system("pause");return 0;
}

Body:
The expression 4/3 performs integer division, and will result in 1 (it results in truncation of any decimals). You should be performing floating point division.

v = (4.0/3.0)*3.14*pow(radius, 3);


问:
Grey line and area in primary editor window in XCode
Does anybody know where this line and the grey area to the right of it comes from?

If it's just a bug, feel free to close this question!

答:
That is the Page Guide.

You can disable it here...

By unchecking this...

You can also change the distance that it shows.

It's there to show where your code would wrap on a standard 80 character width terminal.


问:
Exposing different view of Class
Is it possible to give different view of a Class . For example , i have Account class , i want expose this data using WCF. For different method call i want expose different property of Account class.Suppose for particular call i want expose only UserName and Password, for
another call i want expose Email and Address. Should i have to write different class or
i can expose needed property to client</p>

答:
You could achieve this using interfaces as "views". For example create a UsernamePassword interface with methods or properties to access username and password and have the Account class implement this interface. You can then pass this interface around and the users of it will be unaware of the other methods and properties in the account class.</p>

```<code>  interface IUsernamePassword
  {
    string Username { get; set; }
    string Password { get; set; }
  }

  class Account : IUsernamePassword
  {
    public string Username { get; set; }

    public string Password { get; set; }
  }
</code>```

Title: Exposing different view of Class

Body:
You could achieve this using interfaces as "views". For example create a UsernamePassword interface with methods or properties to access username and password and have the Account class implement this interface. You can then pass this interface around and the users of it will be unaware of the other methods and properties in the account class.

  interface IUsernamePassword
  {
    string Username { get; set; }
    string Password { get; set; }
  }

  class Account : IUsernamePassword
  {
    public string Username { get; set; }

    public string Password { get; set; }
  }


问:
Virtually indexed virtually tagged cache
As far as I know about virtually indexed virtually tagged cache, here we have a virtual address divided into page number and page offset. We use this page number to get the cache block. If there is a cache miss, we do address translation using TLB and fetch appropriate cache block from main memory.
My doubt is what is the meaning of word "indexed" here ? Is it the way cache lines are addressed? And what is the meaning of virtually tagged?

Thanks.

答:
In VIVT caches, the virtual address is used for tag comparisons and indexing. In general, CPU caches have a index and a tag, which are two parts of a memory address. Index portion of the address is used to index the entry in a cache. Tag is used to to check the entry we are looking for is the same as the entry that is being cached. Indexing and tagging can be done using either physical address or virtual addresses, or a combination of both.
VIPT - Virtually Indexed Physically Tagged

To answer your question, indexing means to fetch the cache entry that is represented by index bits.
Virtually tagged means, tag bits that are used for comparison is from virtual addresses.


问:
Sencha Architect 4.2 Preview Error: 404 - bootstrap.js not found
I am doing some exercise with Sencha Architect and for each demo app, when i click 'Preview' button, nothing displays and giving this error on log:

```<code>Failed to load resource: the server responded with a status of 404 (Not Found): bootstrap.js
</code>```

I am using trail version of Sencha Architect and using 'Commercial' licance as framework (checked on 'Project Settings') also all dependencies works fine (checked on 'Preferences').

Why is that could be or how to overcome on this error?
Thanks a lot.

答:
I have overcome on error:

Changed the Project Settings:

General> Overwrite index file on save: unchecked (leave blank)

Framework> Build Tools: Disabled

Then saved the project and opened index.html and changed script tags for ext-all.js, theme.js and link tag for theme.css to cdnjs' library.

Sencha CDN links not working! so imported cdnjs instead of it.

Body:
I am doing some exercise with Sencha Architect and for each demo app, when i click 'Preview' button, nothing displays and giving this error on log:

Failed to load resource: the server responded with a status of 404 (Not Found): bootstrap.js

I am using trail version of Sencha Architect and using 'Commercial' licance as framework (checked on 'Project Settings') also all dependencies works fine (checked on 'Preferences').

Why is that could be or how to overcome on this error?
Thanks a lot.


问:
Have another class control a picture[ ] on the main form
I try create a class "bgcar" for race cars that is responsible for handling all variables related to some race cars, one of those variables are pictures of the race car, to be placed on the main form. All variables speed position location gasoline etc work (but i removed that from below).

However loading and updating the images turns out to be problematic.
I tried a few variations on the code below but so far nothing works.

I can imagine one would think why dont simply write it all in the Main form, however i dont want to create lots of form variables, i want a class to be able to handle it self and with an classtype.update(). update the main form.
Wich is a winform application.

```<code>namespace game
{
public class Main:Form
  {
    bgcar racecars;

    public Main()
    {
      racecars = new bgcar();
      racecars.update

      //to add later
      //traficlights.update
      //people.update
    }
  }
class bgcar
{
  public PictureBox[] wagon;
  public bgcar() //constructor
  {
    wagon = new PictureBox[2];

    //below wont work.
    //while on the main form
    // picturebox1.image new bitmap(game.Properties.Resources.SportwagonA)
    //works, proving it does exist in the resource file.
    wagon[0].image = new Bitmap(game.Properties.Resources.SportwagonA);
    wagon[1].image = new Bitmap(game.Properties.Resources.SportwagonB);
  }
  public void update()
  {
    //displaying those images is also a problem
    Random rnd = new Random();
    int x = rnd.next(100);
    int y = rnd.next(100);
    Wagon[0].location = new point (x,y);

    int x = rnd.next(100);
    int y = rnd.next(100);
    Wagon[1].location = new point (x,y);
  }
 }
}
</code>```

==update
Going to eat first, i'm now thinking of creating on my Main :form
a public PictureBox[] sportcars, then have in my mainform a routine that
does something like: sportscar = bgcar.wagon;   not sure if that will work.

答:
So your racecars class is basically useless in the way you use it. Creating a new PictureBox instance each time gives you nothing. You have to add those to the form ( or other parent control ) which will draw them inside.

```<code>racecars = new bgcar();
racecars.update();
foreach(PictureBox pBox in racecars.wagon)
{
    this.Controls.Add(pBox);
}
</code>```

Body:
I try create a class "bgcar" for race cars that is responsible for handling all variables related to some race cars, one of those variables are pictures of the race car, to be placed on the main form. All variables speed position location gasoline etc work (but i removed that from below).

However loading and updating the images turns out to be problematic.
I tried a few variations on the code below but so far nothing works.

I can imagine one would think why dont simply write it all in the Main form, however i dont want to create lots of form variables, i want a class to be able to handle it self and with an classtype.update(). update the main form.
Wich is a winform application.

namespace game
{
public class Main:Form
  {
    bgcar racecars;

    public Main()
    {
      racecars = new bgcar();
      racecars.update

      //to add later
      //traficlights.update
      //people.update
    }
  }
class bgcar
{
  public PictureBox[] wagon;
  public bgcar() //constructor
  {
    wagon = new PictureBox[2];

    //below wont work.
    //while on the main form
    // picturebox1.image new bitmap(game.Properties.Resources.SportwagonA)
    //works, proving it does exist in the resource file.
    wagon[0].image = new Bitmap(game.Properties.Resources.SportwagonA);
    wagon[1].image = new Bitmap(game.Properties.Resources.SportwagonB);
  }
  public void update()
  {
    //displaying those images is also a problem
    Random rnd = new Random();
    int x = rnd.next(100);
    int y = rnd.next(100);
    Wagon[0].location = new point (x,y);

    int x = rnd.next(100);
    int y = rnd.next(100);
    Wagon[1].location = new point (x,y);
  }
 }
}

==update
Going to eat first, i'm now thinking of creating on my Main :form
a public PictureBox[] sportcars, then have in my mainform a routine that
does something like: sportscar = bgcar.wagon;   not sure if that will work.

Body:
So your racecars class is basically useless in the way you use it. Creating a new PictureBox instance each time gives you nothing. You have to add those to the form ( or other parent control ) which will draw them inside.

racecars = new bgcar();
racecars.update();
foreach(PictureBox pBox in racecars.wagon)
{
    this.Controls.Add(pBox);
}


问:
Linq: help me to make this work
I have this column:

```<code>    PersonId   CategoryId   SubCategoryId
1      61           47
2      61           48
3      61           0           424
4      61           0           425
5      84           55
6      61                       585
7      101          48
8      101                      424
8      666          47
10     666                      424
</code>```

When i search only for categoryId its fine, and subCategoryId its fine, but when i search for both, like categoryId = 47 && subCategoryId = 424.
I cant make it work... in this case i only need person 61 and person 666.

i can do with a foreach, but not a good idea for performance.

u guys can help me?

```<code>if (ids.IdCategory != null && ids.IdSubCategory != null)
{
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory || m.IdSubCategory == ids.IdSubCategory);
}
else if (ids.IdCategory != null)
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory);
else
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdSubCategory == ids.IdSubCategory);
</code>```

first case i get half what i want... but i want some way to filter, because in this way i get 101 too and i dont know how to see if people have both category and subcategory

and i cant see a way to do this without a foreach

答:
You should group all person skills by person id, and then select only those groups, which contain both given category and sub category:

```<code>unitOfWork.PersonSkillsRepository.GetAll()
          .GroupBy(p => p.PersonId)
          .Where(g => g.Any(p => p.IdCategory == ids.IdCategory)
                   && g.Any(p => p.IdSubCategory == ids.IdSubCategory))
          .Select(g => g.Key)
</code>```

For optimization, you can filter out skills which do not match any of given categories before grouping.

```<code>unitOfWork.PersonSkillsRepository.GetAll()
          .Where(p => p.IdCategory == ids.IdCategory
                   || p.IdSubCategory == ids.IdSubCategory)
          .GroupBy(p => p.PersonId)
          .Where(g => g.Any(p => p.IdCategory == ids.IdCategory)
                   && g.Any(p => p.IdSubCategory == ids.IdSubCategory))
          .Select(g => g.Key)
</code>```

Title: Linq: help me to make this work

Body:
I have this column:

    PersonId   CategoryId   SubCategoryId
1      61           47
2      61           48
3      61           0           424
4      61           0           425
5      84           55
6      61                       585
7      101          48
8      101                      424
8      666          47
10     666                      424

When i search only for categoryId its fine, and subCategoryId its fine, but when i search for both, like categoryId = 47 && subCategoryId = 424.
I cant make it work... in this case i only need person 61 and person 666.

i can do with a foreach, but not a good idea for performance.

u guys can help me?

if (ids.IdCategory != null && ids.IdSubCategory != null)
{
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory || m.IdSubCategory == ids.IdSubCategory);
}
else if (ids.IdCategory != null)
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory);
else
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdSubCategory == ids.IdSubCategory);

first case i get half what i want... but i want some way to filter, because in this way i get 101 too and i dont know how to see if people have both category and subcategory

and i cant see a way to do this without a foreach

Body:
You should group all person skills by person id, and then select only those groups, which contain both given category and sub category:

unitOfWork.PersonSkillsRepository.GetAll()
          .GroupBy(p => p.PersonId)
          .Where(g => g.Any(p => p.IdCategory == ids.IdCategory)
                   && g.Any(p => p.IdSubCategory == ids.IdSubCategory))
          .Select(g => g.Key)

For optimization, you can filter out skills which do not match any of given categories before grouping.

unitOfWork.PersonSkillsRepository.GetAll()
          .Where(p => p.IdCategory == ids.IdCategory
                   || p.IdSubCategory == ids.IdSubCategory)
          .GroupBy(p => p.PersonId)
          .Where(g => g.Any(p => p.IdCategory == ids.IdCategory)
                   && g.Any(p => p.IdSubCategory == ids.IdSubCategory))
          .Select(g => g.Key)


问:
Managing Sonata Admin with ROLES instead of ACL
My understanding in ACL is very limited and my use of SonataAdminBundle is very simple including two roles ADMIN and SUPER_ADMIN.

I do not need this complicated ACL in my project (VIEW, EDIT, LIST, DELETE). I would like to determine the access to a certain admin or action just by the role.

Is it a good practice:

In twig instead of using admin.isGranted() or admin.hasAccess() to use the default is_granted('SUPER_ADMIN')?

In controler or admin class to use security.authorization_checker isGranted()?

How do I determine which ROLE has access to which page? For example, showing only certain admin pages for SUPER_ADMIN in sidebar and not allowing to be accessed by ADMIN.

答:
Sonata role approach defines roles per admin class, included a special role *_ALL that grants complete access to related admin zone, so you could then group these *_ALL under ROLE_ADMIN or ROLE_SUPER_ADMIN roles in your role_hierarchy (security.yml file) e.g.:

```<code>role_hierarchy:
    ROLE_ADMIN:
        - ROLE_USER
        - ROLE_FOO_BUNDLE_BAR_ADMIN_ALL
        - ROLE_FOO_BUNDLE_BAZ_ADMIN_ALL
        # ...
    ROLE_SUPER_ADMIN:
        - ROLE_ADMIN
        - ROLE_ALLOWED_TO_SWITCH
        - ROLE_SU_BUNDLE_SU_ADMIN_ALL
        # ...
</code>```

Following this inheritance approach, your can to assign just ROLE_ADMIN for ones users and ROLE_SUPER_ADMIN for other. Even you could do some subgroups of roles to specific actions.

Body:
Sonata role approach defines roles per admin class, included a special role *_ALL that grants complete access to related admin zone, so you could then group these *_ALL under ROLE_ADMIN or ROLE_SUPER_ADMIN roles in your role_hierarchy (security.yml file) e.g.:

role_hierarchy:
    ROLE_ADMIN:
        - ROLE_USER
        - ROLE_FOO_BUNDLE_BAR_ADMIN_ALL
        - ROLE_FOO_BUNDLE_BAZ_ADMIN_ALL
        # ...
    ROLE_SUPER_ADMIN:
        - ROLE_ADMIN
        - ROLE_ALLOWED_TO_SWITCH
        - ROLE_SU_BUNDLE_SU_ADMIN_ALL
        # ...

Following this inheritance approach, your can to assign just ROLE_ADMIN for ones users and ROLE_SUPER_ADMIN for other. Even you could do some subgroups of roles to specific actions.


问:
Abstract types and type inference
Suppose I have a module that hides some type:

```<code>module Test : sig
  type t
  val make_t : unit -> t
end = struct
  type t = int option
  let make_t () = Some 42
end
</code>```

And I also have a function that operates on optioms:

```<code>let do_work : 'a option -> unit = function
  | Some x -> Printf.printf "Some\n"
  | None   -> Printf.printf "None\n"
</code>```

Not surprisingly, when I call do_work on t instance I get a type error:

```<code>let () =
  do_work @@ Test.make_t ()
</code>```

Error: This expression has type Test.t but an expression was expected of type 'a option

In my application I have t more complex than just int option and I don't want to expose its internals outward. However, I want to tell the compiler that t is actually something option. How can I achieve that?

答:
Or you could provide an abstraction to allow functions of the right type to be applied as in

```<code>module Test : sig
  type t
  val apply  : (int option -> 'a) -> t -> 'a
  val make_t : unit -> t
  val ( @ )  : (int option -> 'a) -> t -> 'a
end = struct
  type t = int option
  let make_t () = Some 42
  let apply f x = f x
  let ( @ ) = apply
end

let do_work : 'a option -> unit = function
  | Some x -> Printf.printf "Some\n"
  | None   -> Printf.printf "None\n"

let () =
  let open Test in
  do_work @ make_t ()
</code>```

The operator might be a little bit too much but it looks cooler.
On a side note you might want to look into monads.

ContentLicense: CC BY-SA 4.0

Title: Abstract types and type inference

Body:
Suppose I have a module that hides some type:

module Test : sig
  type t
  val make_t : unit -> t
end = struct
  type t = int option
  let make_t () = Some 42
end

And I also have a function that operates on optioms:

let do_work : 'a option -> unit = function
  | Some x -> Printf.printf "Some\n"
  | None   -> Printf.printf "None\n"

Not surprisingly, when I call do_work on t instance I get a type error:

let () =
  do_work @@ Test.make_t ()

Error: This expression has type Test.t but an expression was expected of type 'a option

In my application I have t more complex than just int option and I don't want to expose its internals outward. However, I want to tell the compiler that t is actually something option. How can I achieve that?

Body:
Or you could provide an abstraction to allow functions of the right type to be applied as in

module Test : sig
  type t
  val apply  : (int option -> 'a) -> t -> 'a
  val make_t : unit -> t
  val ( @ )  : (int option -> 'a) -> t -> 'a
end = struct
  type t = int option
  let make_t () = Some 42
  let apply f x = f x
  let ( @ ) = apply
end

let do_work : 'a option -> unit = function
  | Some x -> Printf.printf "Some\n"
  | None   -> Printf.printf "None\n"

let () =
  let open Test in
  do_work @ make_t ()

The operator might be a little bit too much but it looks cooler.
On a side note you might want to look into monads.


问:
Retraining Inception5h model from TensorFlow Android Camera Demo
TensorFlow Android Camera Demo uses Inception5h model for live image recognition which delivers exceptional performance. Since I haven't had success retraining Inception5h I've gone with InceptionV3 model but it's not quite as snappy at image recognition. So I'm back at the beginning trying to retrain (or transfer learn) Inception5h model. I've tried modifying retrain.py but it's clearly written just for the v3 model. 5h model doesn't contain "pool_3/_reshape:0", "DecodeJpeg/contents:0" or "ResizeBilinear:0" tensors to begin with. There are other differences as well.

I'm a bit of a newbie at machine learning and TensorFlow so I'd greatly appreciate clear steps as to what I have to do.

Thank you!

答:
It looks like the retrain.py script and tutorial was just updated to work with the mobilenet architecture.

So that solves the first part of your problem, it's not actually inception5h, but it runs well on mobile with much better accuracy than inception5h.

To actually get it to run in the android example you'll still need to update these settings.

I think you should be able to just copy the settings determined for the mobilenet you choose, from the retrain script and you might be okay.

If you wanted to use a different network, that didn't have the settings in retrain.py then the easiest way I can think of to determine them would be to explore the graph with TensorBoard.

So if you really wanted to use inception 5h, you could download and unzip it:

```<code>curl -O https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip
unzip -d inception5h inception5h.zip
</code>```

Then grab this simple script, from the Tensorflow for Poets: 2 codelab repo, to convert the graph .pb file to something tensorboard can use:

```<code>curl -O https://raw.githubusercontent.com/googlecodelabs/tensorflow-for-poets-2/master/scripts/graph_pb2tb.py
</code>```

And run it on your graph.pb:

```<code>mkdir tb_graph
python graph_pb2tb.py tb/inception5h inception5h/tensorflow_inception_graph.pb
</code>```

And open it in tensorboard:

```<code>tensorboard --logdir tb_graph
</code>```

Then it might be relatively simple to poke around in the graph and find the names of the nodes you need to fill up your own model_info dict.

I think this is the node you'd want to set as your bottleneck_tensor:

Body:
It looks like the retrain.py script and tutorial was just updated to work with the mobilenet architecture.

So that solves the first part of your problem, it's not actually inception5h, but it runs well on mobile with much better accuracy than inception5h.

To actually get it to run in the android example you'll still need to update these settings.

I think you should be able to just copy the settings determined for the mobilenet you choose, from the retrain script and you might be okay.

If you wanted to use a different network, that didn't have the settings in retrain.py then the easiest way I can think of to determine them would be to explore the graph with TensorBoard.

So if you really wanted to use inception 5h, you could download and unzip it:

curl -O https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip
unzip -d inception5h inception5h.zip

Then grab this simple script, from the Tensorflow for Poets: 2 codelab repo, to convert the graph .pb file to something tensorboard can use:

curl -O https://raw.githubusercontent.com/googlecodelabs/tensorflow-for-poets-2/master/scripts/graph_pb2tb.py

And run it on your graph.pb:

mkdir tb_graph
python graph_pb2tb.py tb/inception5h inception5h/tensorflow_inception_graph.pb

And open it in tensorboard:

tensorboard --logdir tb_graph

Then it might be relatively simple to poke around in the graph and find the names of the nodes you need to fill up your own model_info dict.

I think this is the node you'd want to set as your bottleneck_tensor:


问:
What is happening when you assign a pointer to another pointer?
Code:

```<code>int x = 2;
int* pointerone = &x;
int* pointertwo = pointerone;
</code>```

So the address of pointerone is assigned to pointertwo, but is the copy constructor being called and the object that holds the address is copied into the address object of the other pointer, like all the default copy constructors on other types performing a shallow copy. If it is as I expect, how does the copy constructor of a pointer look like?

答:
When you initialize a pointer with the value of another pointer you are just making another variable for the same memory address, as @Michael just said.

But be careful doing this. If you delete one of the pointer and you dereference the other one in another point of the program, it will raise an exception, and if not handled properly will crash your program.

Take this as an example:

```<code>int *ptr1 { new int(15) };
int *ptr2 { ptr1 }; // ptr2 points to same memory address as ptr1

// ... Some cool code goes here

delete ptr1; // Free the memory of ptr1

cout << *ptr2;
// Raises an exception because the address
// has been removed from the effective
// memory of the program.
</code>```

Body:
Code:

int x = 2;
int* pointerone = &x;
int* pointertwo = pointerone;

So the address of pointerone is assigned to pointertwo, but is the copy constructor being called and the object that holds the address is copied into the address object of the other pointer, like all the default copy constructors on other types performing a shallow copy. If it is as I expect, how does the copy constructor of a pointer look like?

Body:
When you initialize a pointer with the value of another pointer you are just making another variable for the same memory address, as @Michael just said.

But be careful doing this. If you delete one of the pointer and you dereference the other one in another point of the program, it will raise an exception, and if not handled properly will crash your program.

Take this as an example:

int *ptr1 { new int(15) };
int *ptr2 { ptr1 }; // ptr2 points to same memory address as ptr1

// ... Some cool code goes here

delete ptr1; // Free the memory of ptr1

cout << *ptr2;
// Raises an exception because the address
// has been removed from the effective
// memory of the program.


问:
uwp adaptive gridview renders 1st element wrong
I am using AdaptiveGridView from UWP Community toolkit.
The Very first Item displays horribly wrong and all other Items are displayed just fine.

See in the picture below the 1st item has bigger Folder Image than others.

XAML

```<code><Style TargetType="controls:AdaptiveGridView" x:Key="MainAdaptiveStyle">
    <Setter Property="SelectionMode" Value="None"/>
    <Setter Property="StretchContentForSingleRow" Value="False"/>
    <Setter Property="DesiredWidth" Value="220"/>
    <Setter Property="IsItemClickEnabled" Value="True"/>
    <Setter Property="animations:ReorderGridAnimation.Duration" Value="400"/>
</Style>

<PivotItem Header="Folders">
    <controls:AdaptiveGridView Name="FoldersLibraryGridView"
                               Style="{StaticResource MainAdaptiveStyle}"
                               ItemsSource="{x:Bind ViewModel.Folders}">
        <controls:AdaptiveGridView.ItemTemplate>
            <DataTemplate  x:DataType="data:FolderItem">
                <userTemplates:FolderTemplate />
            </DataTemplate>
        </controls:AdaptiveGridView.ItemTemplate>
    </controls:AdaptiveGridView>
</PivotItem>
</code>```

<....below is user control which is used the DataTemplate, known as FolderTemplate...>

```<code><Grid >
    <Grid.Resources>
        <Style TargetType="Image" x:Key="ThumbImageStyle" >
            <Setter Property="Stretch" Value="UniformToFill"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="Margin" Value="8"/>
        </Style>
    </Grid.Resources>
    <Grid.RowDefinitions>
        <RowDefinition Height="8*"/>
        <RowDefinition Height="3*"/>
    </Grid.RowDefinitions>
    <Border x:Name="ThumbImage" Grid.Row="0">
        <Border.Background>
            <SolidColorBrush Color="{ThemeResource SystemAccentColor}" Opacity="0.5"/>
        </Border.Background>
        <Image  Source="ms-appx:///Assets/FolderIcon.png"

                Style="{StaticResource ThumbImageStyle}"
                />
    </Border>
    <Border Background="{ThemeResource SystemAltHighColor}" Grid.Row="1" Padding="8,0,4,0">
        <TextBlock  Text="{x:Bind FolderItem.MyFolder.DisplayName}"
                    Style="{StaticResource GridViewVideoName}"/>
    </Border>
</Grid>
</code>```

UPDATE
as You can see in the picture below, market with red line, right side of each item is faded where the folder name textblock ends, and this occurs only when ItemHeight is Explicitly set on the ApativeGridView

答:
I think the fix is simple. First have a look at the description of this control on GitHub -

```<code>/// <remarks>
/// The number and the width of items are calculated based on the
/// screen resolution in order to fully leverage the available screen space. The property ItemsHeight define
/// the items fixed height and the property DesiredWidth sets the minimum width for the elements to add a
/// new column.</remarks>
</code>```

I believe ItemsHeight is a typo there. It really should be ItemHeight. You just need to specify it (e.g. <controls:AdaptiveGridView ItemHeight="280" ... /> and the problem should go away.

Update

Your second issue is related to the DropShadowPanel in the toolkit. If you resize the window a bit you will notice that the shadows then render properly.

I had a look at the default style of the control and the HorizontalContentAlignment property is set to Left initially. So it looks like the control doesn't properly resize its inner shadow component when the size is changed.

But since you have already got a local style, you can just set it to Stretch and the issue should go away.

```<code><Style TargetType="controls:DropShadowPanel"
       x:Key="MainDropShadow">
    <Setter Property="HorizontalContentAlignment"
            Value="Stretch" />
</code>```

Update 2

OK, so here is the reason why initially the shadow is not stretching -

The shadow size is calculated based on the Content of the DropShadowPanel control, but the shadow only monitors the SizeChanged event of the control to update its size.

What's happening in your case is that your Grid (direct child of the DropShadowPanel control) was initially arranged with a smaller size, then the shadow size was set, and then when the size of your Grid updates, because the size of DropShadowPanel is still with the same size, no SizeChanged will be invoked, hence the shadow size is not re-calculated. If you have the toolkit source code, you should be able to simply switch to monitor the SizeChanged of the Content instead and the problem should go away.

When you are setting HorizontalContentAlignment to Stretch, you are effectively saying "the child should have the same size of the parent". So when the shadow is initially sized, your Grid is already at the same size of its parent. But I feel like they must have been using Left for a reason and this should just be a temporary fix for your case.

Body:
I am using AdaptiveGridView from UWP Community toolkit.
The Very first Item displays horribly wrong and all other Items are displayed just fine.

See in the picture below the 1st item has bigger Folder Image than others.

XAML

<PivotItem Header="Folders">
    <controls:AdaptiveGridView Name="FoldersLibraryGridView"
                               Style="{StaticResource MainAdaptiveStyle}"
                               ItemsSource="{x:Bind ViewModel.Folders}">
        <controls:AdaptiveGridView.ItemTemplate>
            <DataTemplate  x:DataType="data:FolderItem">
                <userTemplates:FolderTemplate />
            </DataTemplate>
        </controls:AdaptiveGridView.ItemTemplate>
    </controls:AdaptiveGridView>
</PivotItem>

<....below is user control which is used the DataTemplate, known as FolderTemplate...>

<Grid >
    <Grid.Resources>

    </Grid.Resources>
    <Grid.RowDefinitions>
        <RowDefinition Height="8*"/>
        <RowDefinition Height="3*"/>
    </Grid.RowDefinitions>
    <Border x:Name="ThumbImage" Grid.Row="0">
        <Border.Background>
            <SolidColorBrush Color="{ThemeResource SystemAccentColor}" Opacity="0.5"/>
        </Border.Background>
        <Image  Source="ms-appx:///Assets/FolderIcon.png"

                Style="{StaticResource ThumbImageStyle}"
                />
    </Border>
    <Border Background="{ThemeResource SystemAltHighColor}" Grid.Row="1" Padding="8,0,4,0">
        <TextBlock  Text="{x:Bind FolderItem.MyFolder.DisplayName}"
                    Style="{StaticResource GridViewVideoName}"/>
    </Border>
</Grid>

UPDATE
as You can see in the picture below, market with red line, right side of each item is faded where the folder name textblock ends, and this occurs only when ItemHeight is Explicitly set on the ApativeGridView

Body:
I think the fix is simple. First have a look at the description of this control on GitHub -

/// <remarks>
/// The number and the width of items are calculated based on the
/// screen resolution in order to fully leverage the available screen space. The property ItemsHeight define
/// the items fixed height and the property DesiredWidth sets the minimum width for the elements to add a
/// new column.</remarks>

I believe ItemsHeight is a typo there. It really should be ItemHeight. You just need to specify it (e.g. <controls:AdaptiveGridView ItemHeight="280" ... /> and the problem should go away.

Update

Your second issue is related to the DropShadowPanel in the toolkit. If you resize the window a bit you will notice that the shadows then render properly.

I had a look at the default style of the control and the HorizontalContentAlignment property is set to Left initially. So it looks like the control doesn't properly resize its inner shadow component when the size is changed.

But since you have already got a local style, you can just set it to Stretch and the issue should go away.

<Style TargetType="controls:DropShadowPanel"
       x:Key="MainDropShadow">
    <Setter Property="HorizontalContentAlignment"
            Value="Stretch" />

Update 2

OK, so here is the reason why initially the shadow is not stretching -

The shadow size is calculated based on the Content of the DropShadowPanel control, but the shadow only monitors the SizeChanged event of the control to update its size.

What's happening in your case is that your Grid (direct child of the DropShadowPanel control) was initially arranged with a smaller size, then the shadow size was set, and then when the size of your Grid updates, because the size of DropShadowPanel is still with the same size, no SizeChanged will be invoked, hence the shadow size is not re-calculated. If you have the toolkit source code, you should be able to simply switch to monitor the SizeChanged of the Content instead and the problem should go away.

When you are setting HorizontalContentAlignment to Stretch, you are effectively saying "the child should have the same size of the parent". So when the shadow is initially sized, your Grid is already at the same size of its parent. But I feel like they must have been using Left for a reason and this should just be a temporary fix for your case.


问:
Java type conversion where types are not known until runtime
I'm trying to write a data access layer for an AJAX web project. This DAL has to convert data coming in via an AJAX servlet to objects that can be passed to a PreparedStatement for execution.

Data in the AJAX servlet, retrieved by using HttpServletRequest.getParameter(...), come in as strings.

In each data class, I have a known set of fields as well as their data types, e.g. CustomerId(integer), CustomerName(string).

I can of course write a method in the Customer class to handle the conversion, but this means I have to do it for every data object's class. I would much rather have a generic method that does conversion, e.g.

```<code>Object convert(String value, Class<?> targetType) { ... }
</code>```

Can anyone point me in the right direction?

答:
Since you want to use the parameters in your PreparedStatement, why do you have to convert them at all?

When using setString(index, parameter) SQL will be happy to do the conversion for you.

Thus the only thing you might want to do is some kind of validation that the input is really valid (or you could even leave this part to your SQL engine which will throw an exception if it doesn't understand you.

Body:
I'm trying to write a data access layer for an AJAX web project. This DAL has to convert data coming in via an AJAX servlet to objects that can be passed to a PreparedStatement for execution.

Data in the AJAX servlet, retrieved by using HttpServletRequest.getParameter(...), come in as strings.

In each data class, I have a known set of fields as well as their data types, e.g. CustomerId(integer), CustomerName(string).

I can of course write a method in the Customer class to handle the conversion, but this means I have to do it for every data object's class. I would much rather have a generic method that does conversion, e.g.

Object convert(String value, Class<?> targetType) { ... }

Can anyone point me in the right direction?


问:
Align two buttons that are in two different DIVs
So I tried to play a bit with my code and was looking on many forums to see if the answer was already given. I didn't find anything yet. I wanted to know how to align the buttons divs to each other, like this :

At this time, my code is this :

.directeur {
  width: 50%;
  float: left;
}

.directeur p {
  width: 80%;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  margin-top: 10px;
}

.directeur a>img {
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="directeur">
  <img src="http://via.placeholder.com/500x150" alt="">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur maxime impedit amet labore facere. Quod quos consectetur nulla eaque soluta tenetur omnis quo sunt, modi optio iste consequuntur atque error.</p>
  <img src="http://via.placeholder.com/300x70" alt="">
</div>
<div class="directeur">
  <img src="http://via.placeholder.com/500x150" alt="">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus rem delectus enim dolorem, error nulla earum maxime aliquid ipsam, recusandae molestiae ducimus iusto, dolore omnis. Saepe temporibus autem, provident dolor!</p>
  <img src="http://via.placeholder.com/300x70" alt="">
</div></code>```

Can someone help me ? I created other Divs, tried Vertical-Align and Inline-Block. I want the Green Button Rectangle to align like this in my code. At the moment, they are not align because of the height of the text box.

答:
Set a min-height for the
Lorem ipsum parts of this to make them the same:

        .directeur{
        width: 50%;
        float: left;
    }
    .directeur p {
        width: 80%;
        text-align: center;
        margin-left: auto;
        margin-right: auto;
        margin-bottom: 10px;
        margin-top: 10px;
        min-height: 225px;
    }
    .directeur a>img{
        margin-left: auto;
        margin-right: auto;
        margin-bottom: 10px;
        display: block;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="directeur">
            <img src="http://via.placeholder.com/500x150" alt="">
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur maxime impedit amet labore facere. Quod quos consectetur nulla eaque soluta tenetur omnis quo sunt, modi optio iste consequuntur atque error.</p>
            <img src="http://via.placeholder.com/300x70" alt="">
        </div>
        <div class="directeur">
            <img src="http://via.placeholder.com/500x150" alt="">
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus rem delectus enim dolorem, error nulla earum maxime aliquid ipsam, recusandae molestiae ducimus iusto, dolore omnis. Saepe temporibus autem, provident dolor!</p>
            <img src="http://via.placeholder.com/300x70" alt="">
        </div></code>```

Or you can use some javascript to measure the tallest one then make the other one the same height on page load, something like Equalise.

Body:
So I tried to play a bit with my code and was looking on many forums to see if the answer was already given. I didn't find anything yet. I wanted to know how to align the buttons divs to each other, like this :

At this time, my code is this :

.directeur {
  width: 50%;
  float: left;
}

.directeur p {
  width: 80%;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  margin-top: 10px;
}

.directeur a>img {
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  display: block;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur maxime impedit amet labore facere. Quod quos consectetur nulla eaque soluta tenetur omnis quo sunt, modi optio iste consequuntur atque error.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus rem delectus enim dolorem, error nulla earum maxime aliquid ipsam, recusandae molestiae ducimus iusto, dolore omnis. Saepe temporibus autem, provident dolor!

Can someone help me ? I created other Divs, tried Vertical-Align and Inline-Block. I want the Green Button Rectangle to align like this in my code. At the moment, they are not align because of the height of the text box.

Body:
Set a min-height for the
Lorem ipsum parts of this to make them the same:

        .directeur{
        width: 50%;
        float: left;
    }
    .directeur p {
        width: 80%;
        text-align: center;
        margin-left: auto;
        margin-right: auto;
        margin-bottom: 10px;
        margin-top: 10px;
        min-height: 225px;
    }
    .directeur a>img{
        margin-left: auto;
        margin-right: auto;
        margin-bottom: 10px;
        display: block;
    }

<div class="directeur">
            <img src="http://via.placeholder.com/500x150" alt="">
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur maxime impedit amet labore facere. Quod quos consectetur nulla eaque soluta tenetur omnis quo sunt, modi optio iste consequuntur atque error.</p>
            <a href=""><img src="http://via.placeholder.com/300x70" alt=""></a>
        </div>
        <div class="directeur">
            <img src="http://via.placeholder.com/500x150" alt="">
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus rem delectus enim dolorem, error nulla earum maxime aliquid ipsam, recusandae molestiae ducimus iusto, dolore omnis. Saepe temporibus autem, provident dolor!</p>
            <a href=""><img src="http://via.placeholder.com/300x70" alt=""></a>
        </div>

Or you can use some javascript to measure the tallest one then make the other one the same height on page load, something like Equalise.


问:
Remove Double-Click Zoom D3
I have a stripped down force directed graph with zoom/pan capability: https://bl.ocks.org/anonymous/36b27a0b6f8c485c25995e7c223def3c

Here is the zoom portion:

```<code>var zoomHandler = d3.zoom()
    .on("zoom", zoomActions);

zoomHandler(svg);

function zoomActions(){
    g.attr("transform", d3.event.transform)
  }
</code>```

I would like to remove the zoom capability for double-click, and only keep it for scrolling. Based on the docs and other questions, I know I must include .on("dblclick.zoom", null) somewhere. However, I cannot figure out where to place this piece of code. In addition, I'm not sure if I am properly using "svg" and "g" to group my elements, which may be contributing to the issue. I have seen the other questions related to this issue, and have not been able to fit them into my situation.

How should I remedy this? Thank you for any insight you all might have!

答:
Since you are calling the zoom function on the svg selection...

```<code>zoomHandler(svg);
</code>```

... you have to add the listener to the same selection:

```<code>svg.on("dblclick.zoom", null)
</code>```

Here is your updated bl.ocks: https://bl.ocks.org/anonymous/42745557a8602692d9dc98c33a327d29

Title: Remove Double-Click Zoom D3

Body:
I have a stripped down force directed graph with zoom/pan capability: https://bl.ocks.org/anonymous/36b27a0b6f8c485c25995e7c223def3c

Here is the zoom portion:

var zoomHandler = d3.zoom()
    .on("zoom", zoomActions);

zoomHandler(svg);

function zoomActions(){
    g.attr("transform", d3.event.transform)
  }

I would like to remove the zoom capability for double-click, and only keep it for scrolling. Based on the docs and other questions, I know I must include .on("dblclick.zoom", null) somewhere. However, I cannot figure out where to place this piece of code. In addition, I'm not sure if I am properly using "svg" and "g" to group my elements, which may be contributing to the issue. I have seen the other questions related to this issue, and have not been able to fit them into my situation.

How should I remedy this? Thank you for any insight you all might have!

Body:
Since you are calling the zoom function on the svg selection...

zoomHandler(svg);

... you have to add the listener to the same selection:

svg.on("dblclick.zoom", null)

Here is your updated bl.ocks: https://bl.ocks.org/anonymous/42745557a8602692d9dc98c33a327d29


问:
.NET - Timer Elapsed Event Overlap
Is there a way to detect that elapsed events of timer are overlapping? For example, I create a Timer with 200ms interval between elapsed events but the executed code at event is taking more than 200ms. As a result, another elapsed event is executed before the last one is finished. Also is there a way to prevent this from happening such that another event is not invoked before the last one is finished?</p>

答:
If you want to fire the next cycle after the current one has finished, stop the timer if it hits it's tick event, and restart it if you're done.

```<code>Timer fires Tick-Event
    Disable/Stop Timer
    Program logic goes here
    Restart Timer
</code>```

Title: .NET - Timer Elapsed Event Overlap

Body:
If you want to fire the next cycle after the current one has finished, stop the timer if it hits it's tick event, and restart it if you're done.

Timer fires Tick-Event
    Disable/Stop Timer
    Program logic goes here
    Restart Timer


问:
How avoid the scan in the main table
I have a table partitioned using inherit in multiple tables for days.

There is one insert trigger to insert the data to the proper table, so in theory the avl table shouldnt have any data

```<code>CREATE OR REPLACE FUNCTION avl_db.avl_insert_trigger()
  RETURNS trigger AS
$BODY$
BEGIN
    IF ( NEW.event_time >= '2017-06-01 00:00:00' AND NEW.event_time < '2017-06-02 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170601 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-02 00:00:00' AND NEW.event_time < '2017-06-03 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170602 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-03 00:00:00' AND NEW.event_time < '2017-06-04 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170603 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-04 00:00:00' AND NEW.event_time < '2017-06-05 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170604 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-05 00:00:00' AND NEW.event_time < '2017-06-06 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170605 VALUES (NEW.*);
....
    ELSE
        RAISE EXCEPTION 'Date out of range.';
    END IF;

    RETURN NULL;
</code>```

Every table has a check constraint and index so only check the table with the right date

```<code>CONSTRAINT avl_20170605_event_time_check
CHECK (event_time >= '2017-06-05 00:00:00'::timestamp without time zone
   AND event_time <  '2017-06-06 00:00:00'::timestamp without time zone)

CREATE INDEX avl_20170605__event_time_idx
  ON avl_db.avl_20170605
  USING btree
  (event_time);
</code>```

The thing is when do select using the event_time to filter still do some operation over the main avl table.

```<code>explain analyze
    SELECT *
    FROM avl_db.avl
    WHERE event_time between '2017-06-05 09:40:44'::timestamp without time zone - '6 minute'::interval
                         AND '2017-06-05 09:40:44'::timestamp without time zone - '1 minute'::interval
</code>```

You can see use the index from avl_20170605__event_time_idx and ignore the rest of the tables, but also try to do a Seq Scan on avl.

```<code>Append  (cost=0.00..720.98 rows=7724 width=16) (actual time=0.044..5.523 rows=7851 loops=1)
  ->  Seq Scan on avl  (cost=0.00..0.00 rows=1 width=16) (actual time=0.001..0.001 rows=0 loops=1)
        Filter: ((event_time >= '2017-06-05 09:34:44'::timestamp without time zone) AND (event_time <= '2017-06-05 09:39:44'::timestamp without time zone))
  ->  Index Scan using avl_20170605__event_time_idx on avl_20170605  (cost=0.42..720.98 rows=7723 width=16) (actual time=0.042..5.110 rows=7851 loops=1)
        Index Cond: ((event_time >= '2017-06-05 09:34:44'::timestamp without time zone) AND (event_time <= '2017-06-05 09:39:44'::timestamp without time zone))
Planning time: 3.050 ms
Execution time: 5.737 ms
</code>```

I'm wondering if there is a way optimizer stop trying to scan and append the table avl.

答:
That is normal and as it should be.

Every scan on a partitioned table will also scan the (usually empty) parent table, since it doesn't (and cannot) have a CHECK constraint like the child tables have.

You can see that this scan doesn't contribute any time to the overall query duration.

Title: How avoid the scan in the main table

Body:
I have a table partitioned using inherit in multiple tables for days.

There is one insert trigger to insert the data to the proper table, so in theory the avl table shouldnt have any data

CREATE OR REPLACE FUNCTION avl_db.avl_insert_trigger()
  RETURNS trigger AS
$BODY$
BEGIN
    IF ( NEW.event_time >= '2017-06-01 00:00:00' AND NEW.event_time < '2017-06-02 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170601 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-02 00:00:00' AND NEW.event_time < '2017-06-03 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170602 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-03 00:00:00' AND NEW.event_time < '2017-06-04 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170603 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-04 00:00:00' AND NEW.event_time < '2017-06-05 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170604 VALUES (NEW.*);
    ELSEIF ( NEW.event_time >= '2017-06-05 00:00:00' AND NEW.event_time < '2017-06-06 00:00:00' ) THEN
        INSERT INTO avl_db.avl_20170605 VALUES (NEW.*);
....
    ELSE
        RAISE EXCEPTION 'Date out of range.';
    END IF;

    RETURN NULL;

Every table has a check constraint and index so only check the table with the right date

CONSTRAINT avl_20170605_event_time_check
CHECK (event_time >= '2017-06-05 00:00:00'::timestamp without time zone
   AND event_time <  '2017-06-06 00:00:00'::timestamp without time zone)

CREATE INDEX avl_20170605__event_time_idx
  ON avl_db.avl_20170605
  USING btree
  (event_time);

The thing is when do select using the event_time to filter still do some operation over the main avl table.

explain analyze
    SELECT *
    FROM avl_db.avl
    WHERE event_time between '2017-06-05 09:40:44'::timestamp without time zone - '6 minute'::interval
                         AND '2017-06-05 09:40:44'::timestamp without time zone - '1 minute'::interval

You can see use the index from avl_20170605__event_time_idx and ignore the rest of the tables, but also try to do a Seq Scan on avl.

Append  (cost=0.00..720.98 rows=7724 width=16) (actual time=0.044..5.523 rows=7851 loops=1)
  ->  Seq Scan on avl  (cost=0.00..0.00 rows=1 width=16) (actual time=0.001..0.001 rows=0 loops=1)
        Filter: ((event_time >= '2017-06-05 09:34:44'::timestamp without time zone) AND (event_time <= '2017-06-05 09:39:44'::timestamp without time zone))
  ->  Index Scan using avl_20170605__event_time_idx on avl_20170605  (cost=0.42..720.98 rows=7723 width=16) (actual time=0.042..5.110 rows=7851 loops=1)
        Index Cond: ((event_time >= '2017-06-05 09:34:44'::timestamp without time zone) AND (event_time <= '2017-06-05 09:39:44'::timestamp without time zone))
Planning time: 3.050 ms
Execution time: 5.737 ms

I'm wondering if there is a way optimizer stop trying to scan and append the table avl.


答:
The following would do, but you should be aware your way of storing data is quite odd.

(I mean, aren't all your subcategories related to a category ?)

```<code>// gets all the Ids of people of category 47
var personIds = entities
               .Where(x => x.categoryId == 47)
               .Select(x => x.PersonId)
               .Distinct()
               .ToList();
// gets all rows of people of category 47 and subcategory 424
var result = entities
            .Where(x => personIds.Contains(x.PersonId) && x.subCategoryId == 424)
            .ToList();
</code>```

Linked dotnetfiddle.

Title: Linq: help me to make this work

Body:
I have this column:

    PersonId   CategoryId   SubCategoryId
1      61           47
2      61           48
3      61           0           424
4      61           0           425
5      84           55
6      61                       585
7      101          48
8      101                      424
8      666          47
10     666                      424

When i search only for categoryId its fine, and subCategoryId its fine, but when i search for both, like categoryId = 47 && subCategoryId = 424.
I cant make it work... in this case i only need person 61 and person 666.

i can do with a foreach, but not a good idea for performance.

u guys can help me?

if (ids.IdCategory != null && ids.IdSubCategory != null)
{
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory || m.IdSubCategory == ids.IdSubCategory);
}
else if (ids.IdCategory != null)
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory);
else
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdSubCategory == ids.IdSubCategory);

first case i get half what i want... but i want some way to filter, because in this way i get 101 too and i dont know how to see if people have both category and subcategory

and i cant see a way to do this without a foreach

Body:
The following would do, but you should be aware your way of storing data is quite odd.

(I mean, aren't all your subcategories related to a category ?)

// gets all the Ids of people of category 47
var personIds = entities
               .Where(x => x.categoryId == 47)
               .Select(x => x.PersonId)
               .Distinct()
               .ToList();
// gets all rows of people of category 47 and subcategory 424
var result = entities
            .Where(x => personIds.Contains(x.PersonId) && x.subCategoryId == 424)
            .ToList();

Linked dotnetfiddle.


答:
```<code>var zoomHandler = d3.zoom()
  .on("zoom", zoomActions);

 zoomHandler(svg);

  svg.call("zoom").on("dblclick.zoom", null);

function zoomActions(){
   g.attr("transform", d3.event.transform)
}
</code>```

Title: Remove Double-Click Zoom D3


问:
Need to extract a DataFrame to a JSON file under specific parameters
I have a DataFrame created from an Excel .xlsx file using pandas that looks like this:

```<code>    TypeName
    TypeA
    TypeB
    TypeC

    ElementName1
    1A
    1B
    1C

    ElementName2
    2A
    2B
    2C
</code>```

To clarify, the first group of attributes describes the "name" of each type of attribute whilst the rest clarifies the actual values of each element. I need to extract this to a json file (preferrably using pandas DataFrame.to_json, but others are ok too) using the format:

```<code>    {"TypeName": {
            "ElementName1": {
                    "TypeA": "1A",
                    "TypeB": "1B",
                    "TypeC": "1C",
                    },
            "ElementName2": {
                    "TypeA": "2A",
                    "TypeB": "2B",
                    "TypeC": "2C",
                    },
            },
    }
</code>```

After much toying with the parameters of the assets pandas offers however, I haven't been able to solve this issue as of yet.

答:
I am not sure how to make the TypeName the first key in an elegant (non-manual) way, but this may help you anyway:

```<code>from io import StringIO

import pandas

df = pandas.read_csv(StringIO("""
TypeName,ElementName1,ElementName2
TypeA,1A,2A
TypeB,1B,2B
TypeC,1C,2C"""))

df.set_index('TypeName').to_json()
</code>```

That way at least you get this structure:

```<code>{
 "ElementName1": {
         "TypeA": "1A",
         "TypeB": "1B",
         "TypeC": "1C",
         },
 "ElementName2": {
         "TypeA": "2A",
         "TypeB": "2B",
         "TypeC": "2C",
         },
 }
</code>```

Body:
I have a DataFrame created from an Excel .xlsx file using pandas that looks like this:

    TypeName
    TypeA
    TypeB
    TypeC

    ElementName1
    1A
    1B
    1C

    ElementName2
    2A
    2B
    2C

To clarify, the first group of attributes describes the "name" of each type of attribute whilst the rest clarifies the actual values of each element. I need to extract this to a json file (preferrably using pandas DataFrame.to_json, but others are ok too) using the format:

    {"TypeName": {
            "ElementName1": {
                    "TypeA": "1A",
                    "TypeB": "1B",
                    "TypeC": "1C",
                    },
            "ElementName2": {
                    "TypeA": "2A",
                    "TypeB": "2B",
                    "TypeC": "2C",
                    },
            },
    }

After much toying with the parameters of the assets pandas offers however, I haven't been able to solve this issue as of yet.

Body:
I am not sure how to make the TypeName the first key in an elegant (non-manual) way, but this may help you anyway:

from io import StringIO

import pandas

df = pandas.read_csv(StringIO("""
TypeName,ElementName1,ElementName2
TypeA,1A,2A
TypeB,1B,2B
TypeC,1C,2C"""))

df.set_index('TypeName').to_json()

That way at least you get this structure:

{
 "ElementName1": {
         "TypeA": "1A",
         "TypeB": "1B",
         "TypeC": "1C",
         },
 "ElementName2": {
         "TypeA": "2A",
         "TypeB": "2B",
         "TypeC": "2C",
         },
 }


答:
This is a job for Flexbox!

Wrap you whold code in a flexbox container, which will ensure all your .directeurs have the same height

Use flexbox for your .directeur, with flex-direction: column to arrange sub-elements vertically.

Set margin-top: auto on your last element (.directeur a) to ensure it will always be a the very bottom of its parent.

.directeurs {
  display: flex;
}
.directeur{
  width: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.directeur p {
  width: 80%;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  margin-top: 10px;
}
.directeur a {
  margin-top: auto;
}
.directeur a > img{
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="directeurs">
  <div class="directeur">
    <img src="http://via.placeholder.com/500x150" alt="">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur maxime impedit amet labore facere. Quod quos consectetur nulla eaque soluta tenetur omnis quo sunt, modi optio iste consequuntur atque error.</p>
    <img src="http://via.placeholder.com/300x70" alt="">
  </div>
  <div class="directeur">
    <img src="http://via.placeholder.com/500x150" alt="">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus rem delectus enim dolorem, error nulla earum maxime aliquid ipsam, recusandae molestiae ducimus iusto, dolore omnis. Saepe temporibus autem, provident dolor! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus rem delectus enim dolorem, error nulla earum maxime aliquid ipsam, recusandae molestiae ducimus iusto, dolore omnis. Saepe temporibus autem, provident dolor!</p>
    <img src="http://via.placeholder.com/300x70" alt="">
  </div>
</div></code>```

Title: Align two buttons that are in two different DIVs

Body:
This is a job for Flexbox!

Wrap you whold code in a flexbox container, which will ensure all your .directeurs have the same height

Use flexbox for your .directeur, with flex-direction: column to arrange sub-elements vertically.

Set margin-top: auto on your last element (.directeur a) to ensure it will always be a the very bottom of its parent.

.directeurs {
  display: flex;
}
.directeur{
  width: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.directeur p {
  width: 80%;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  margin-top: 10px;
}
.directeur a {
  margin-top: auto;
}
.directeur a > img{
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  display: block;
}

<div class="directeurs">
  <div class="directeur">
    <img src="http://via.placeholder.com/500x150" alt="">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur maxime impedit amet labore facere. Quod quos consectetur nulla eaque soluta tenetur omnis quo sunt, modi optio iste consequuntur atque error.</p>
    <a href=""><img src="http://via.placeholder.com/300x70" alt=""></a>
  </div>
  <div class="directeur">
    <img src="http://via.placeholder.com/500x150" alt="">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus rem delectus enim dolorem, error nulla earum maxime aliquid ipsam, recusandae molestiae ducimus iusto, dolore omnis. Saepe temporibus autem, provident dolor! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus rem delectus enim dolorem, error nulla earum maxime aliquid ipsam, recusandae molestiae ducimus iusto, dolore omnis. Saepe temporibus autem, provident dolor!</p>
    <a href=""><img src="http://via.placeholder.com/300x70" alt=""></a>
  </div>
</div>


问:
Performance difference between MOVE and = assignment in ABAP
Is there any kind of performance gain between 'MOVE TO' vs x = y? I have a really old program I am optimizing and would like to know if it's worth it to pull out all the MOVE TO.  Any other general tips on ABAP optimization would be great as well.</p>

答: You can create CDS with ADT Eclipse. Or views(se11) have good performance for selecting.</p>