问:
Dynamically creating and expanding std::tuple into parameter pack
I'm writing a plugin for software written in C++, here's a snippet where the plugin is defined:

extern "C"
irods::ms_table_entry* plugin_factory() {

    // The number of msParam_t* arguments that it will accept
    int numArguments = 2;

    irods::ms_table_entry* msvc = new irods::ms_table_entry(numArguments);

    msvc->add_operation(
        "my_microservice",
        std::function<int(msParam_t*, msParam_t*, ruleExecInfo_t*)>(MyMicroservice)
    );

    return msvc;
}
```

I'd like to be able to use numArguments to dynamically generate the std::function<int(msParam_t*, msParam_t*, ruleExecInfo_t*)> parameter pack. Where numArguments represents the number of msParam_t* arguments.

I'm not a C++ expert (especially with templating), so after some research I've found that this might be possible by implementing the following:

std::tuple

std::tuple_cat

std::index_sequence

std::make_integer_sequence

But I don't really know how to get started on implementing this. The examples I found were hard to understand, and I couldn't manage to translate them into my own needs. Can anyone provide tips, short examples, or references on how this might work? Any info is greatly appreciated!

答:
```<code>template<typename T>
struct toFunc;

template<typename...T>
struct toFunc<std::tuple<T...>>
{
    using type = std::function<void(T...)>;
};

int main(int argc, char **argv) {

    using t = std::tuple<int, int, int>;
    using func = toFunc<t>::type;
    auto f = func([](int a, int b, int c){std::cout << a << b << c << std::endl;});
    f(1, 2, 3);
  return 0;
}
</code>```

toFunc typetrait will convert your tuple to a function type. not sure if you want that. If you want to call with the argument you maybe need to look for
http://en.cppreference.com/w/cpp/utility/apply

or you can use this implementation:

```<code>namespace detail
{
            template <unsigned int N>
            struct for_each_t_idx
            {
                template <template<std::size_t> class Functor, typename... ArgsT>
                static void exec(const std::tuple<ArgsT...>& t, Functor<N> func)
                {
                    for_each_t_idx<N - 1>::exec(t, func);
                    func<N - 1>(t);
                }
            };

            template <>
            struct for_each_t_idx<0>
            {
                template <template<std::size_t> class Functor, typename... ArgsT>
                static void exec(const std::tuple<ArgsT...>& t, Functor<0> func)
                {
                }
            };
}

    template <template<std::size_t> class Functor, typename... ArgsT>
    void for_each_idx(const std::tuple<ArgsT...>& t, Functor<sizeof...(ArgsT)> func)
    {
        detail::for_each_t_idx<sizeof...(ArgsT)>::exec(t, func);
    }
</code>```

This will call a given function for each element in a the tuple.

Body:
I'm writing a plugin for software written in C++, here's a snippet where the plugin is defined:

extern "C"
irods::ms_table_entry* plugin_factory() {

    // The number of msParam_t* arguments that it will accept
    int numArguments = 2;

    irods::ms_table_entry* msvc = new irods::ms_table_entry(numArguments);

    msvc->add_operation(
        "my_microservice",
        std::function<int(msParam_t*, msParam_t*, ruleExecInfo_t*)>(MyMicroservice)
    );

    return msvc;
}

I'd like to be able to use numArguments to dynamically generate the std::function<int(msParam_t*, msParam_t*, ruleExecInfo_t*)> parameter pack. Where numArguments represents the number of msParam_t* arguments.

I'm not a C++ expert (especially with templating), so after some research I've found that this might be possible by implementing the following:

std::tuple

std::tuple_cat

std::index_sequence

std::make_integer_sequence

But I don't really know how to get started on implementing this. The examples I found were hard to understand, and I couldn't manage to translate them into my own needs. Can anyone provide tips, short examples, or references on how this might work? Any info is greatly appreciated!

Body:
template<typename T>
struct toFunc;

template<typename...T>
struct toFunc<std::tuple<T...>>
{
    using type = std::function<void(T...)>;
};

int main(int argc, char **argv) {

    using t = std::tuple<int, int, int>;
    using func = toFunc<t>::type;
    auto f = func([](int a, int b, int c){std::cout << a << b << c << std::endl;});
    f(1, 2, 3);
  return 0;
}

toFunc typetrait will convert your tuple to a function type. not sure if you want that. If you want to call with the argument you maybe need to look for
http://en.cppreference.com/w/cpp/utility/apply

or you can use this implementation:

namespace detail
{
            template <unsigned int N>
            struct for_each_t_idx
            {
                template <template<std::size_t> class Functor, typename... ArgsT>
                static void exec(const std::tuple<ArgsT...>& t, Functor<N> func)
                {
                    for_each_t_idx<N - 1>::exec(t, func);
                    func<N - 1>(t);
                }
            };

            template <>
            struct for_each_t_idx<0>
            {
                template <template<std::size_t> class Functor, typename... ArgsT>
                static void exec(const std::tuple<ArgsT...>& t, Functor<0> func)
                {
                }
            };
}

    template <template<std::size_t> class Functor, typename... ArgsT>
    void for_each_idx(const std::tuple<ArgsT...>& t, Functor<sizeof...(ArgsT)> func)
    {
        detail::for_each_t_idx<sizeof...(ArgsT)>::exec(t, func);
    }

This will call a given function for each element in a the tuple.


来源: stackexchange

问:
How to do the createJS equivalent of gotoAndPlay() and stop()
Here's the scenario:
I am creating an infographic interactive animation which allows the user to virtually set up a tripod, interact with a virtual camera, etc. I need the timeline to stop when an arrow points where the user should click. Then the timeline should resume playing upon clicking the tripod (A movieClip) (the tripod also animates and then the view switches to first-person with the camera). Currently, the animation just plays forever, without stopping whatsoever to allow user interaction. Here is my createJS code so far:

```<code>    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>CreateJS export from birdsofprey-anim9c</title>

    <script src="http://code.createjs.com/easeljs-0.6.0.min.js"></script>
    <script src="http://code.createjs.com/tweenjs-0.4.0.min.js"></script>
    <script src="http://code.createjs.com/movieclip-0.6.0.min.js"></script>
    <script src="http://code.createjs.com/preloadjs-0.3.0.min.js"></script>
    <script src="birdsofprey-anim9c.js"></script>

    <script>
    var canvas, stage, exportRoot;

    function init() {
        canvas = document.getElementById("canvas");
        images = images||{};

        var manifest = [
            {src:"images/Bitmap1.png", id:"Bitmap1"},
            {src:"images/Bitmap2.png", id:"Bitmap2"},
            {src:"images/Scene_1.jpg", id:"Scene_1"}
        ];

        var loader = new createjs.LoadQueue(false);
        loader.addEventListener("fileload", handleFileLoad);
        loader.addEventListener("complete", handleComplete);
        loader.loadManifest(manifest);
    }

    function handleFileLoad(evt) {
        if (evt.item.type == "image") { images[evt.item.id] = evt.result; }
    }

    function handleComplete() {
        exportRoot = new lib.birdsofpreyanim11a();

        stage = new createjs.Stage(canvas);
        stage.addChild(exportRoot);
        tripodleg = new lib.LEFT_LEG_MC;
        stage.addChild(tripodleg);
        stage.update();

        createjs.Ticker.setFPS(24);
        createjs.Ticker.addEventListener("tick",f);
        function f(e){
        //var t=this;
        //t.stop();
        //exportRoot.stop();
        var delay = 4000;
        var startTime=createjs.Ticker.getTime();
        createjs.Ticker.getMeasuredFPS();
        if(createjs.Ticker.getMeasuredFPS == 6){
           exportRoot.stop();
           tripodleg.onclick = function(){
               exportRoot.gotoAndPlay(90);
           }
           //exportRoot.gotoAndPlay(90);
            createjs.Ticker.removeEventListener("tick",f);
            }
        }
        createjs.Ticker.addEventListener("tick", stage);
    }

    </script>
    </head>

    <body onload="init();" style="background-color:#D4D4D4">
        <canvas id="canvas" width="550" height="540" style="background-
    color:#ffffff"></canvas>
    </body>
    </html>
</code>```

Thanks in advance, StackOverflow and for the expertise of the super coders they're affiliated with! -qs
[EDIT] Updated my code again this time adding an instance of my tripod MovieClip to the stage via addChild(); and stopping the timeline via exportRoot.stop(); exportRoot isn't stopping, any clues? Thanks in advance.

答:
I am guessing you are talking about the line:

```<code>function handlClick(){
    mc.play(2);
}
</code>```

If so, just use gotoAndPlay(2) instead of play. EaselJS was initially based on the ActionScript language, so it mirrors a lot of that functionality. Check out the MovieClip docs.

```<code>function handlClick(){
    mc.gotoAndPlay(2);
}
</code>```

One thing to note: What is createjs.Ticker.tick in your handlTick method? There is no tick property, only a "tick" event. The if statement this is in will never be true. What are you trying to do with that code exactly? Are you looking for the click handler to be added when the main clip reaches frame 30? Or after 30 "ticks"? Either way, this will do nothing.

Hope that helps.

[EDIT based on updates]

It looks like you changed it to use gotoAndPlay, but there are a few problems:

You are calling a global gotoAndPlay function (which doesn't exist) instead of targeting a MovieClip instance. If your main timeline has the frame you want to go to, use exportRoot.gotoAndPlay(90);.

Next, you are calling this.stop(). Your event listener is anonymous (which is fine), but that means that this is Window. Again, there is no global stop method -- so you should call it on the timeline you wish to stop. In this case, it's probably exportRoot.stop().

Cheers,

ContentLicense: CC BY-SA 3.0

Body:
Here's the scenario:
I am creating an infographic interactive animation which allows the user to virtually set up a tripod, interact with a virtual camera, etc. I need the timeline to stop when an arrow points where the user should click. Then the timeline should resume playing upon clicking the tripod (A movieClip) (the tripod also animates and then the view switches to first-person with the camera). Currently, the animation just plays forever, without stopping whatsoever to allow user interaction. Here is my createJS code so far:

    <!DOCTYPE html>

    <meta charset="UTF-8">
    <title>CreateJS export from birdsofprey-anim9c</title>

        <canvas id="canvas" width="550" height="540" style="background-
    color:#ffffff"></canvas>

Thanks in advance, StackOverflow and for the expertise of the super coders they're affiliated with! -qs
[EDIT] Updated my code again this time adding an instance of my tripod MovieClip to the stage via addChild(); and stopping the timeline via exportRoot.stop(); exportRoot isn't stopping, any clues? Thanks in advance.

Body:
I am guessing you are talking about the line:

function handlClick(){
    mc.play(2);
}

If so, just use gotoAndPlay(2) instead of play. EaselJS was initially based on the ActionScript language, so it mirrors a lot of that functionality. Check out the MovieClip docs.

function handlClick(){
    mc.gotoAndPlay(2);
}

One thing to note: What is createjs.Ticker.tick in your handlTick method? There is no tick property, only a "tick" event. The if statement this is in will never be true. What are you trying to do with that code exactly? Are you looking for the click handler to be added when the main clip reaches frame 30? Or after 30 "ticks"? Either way, this will do nothing.

Hope that helps.

[EDIT based on updates]

It looks like you changed it to use gotoAndPlay, but there are a few problems:

You are calling a global gotoAndPlay function (which doesn't exist) instead of targeting a MovieClip instance. If your main timeline has the frame you want to go to, use exportRoot.gotoAndPlay(90);.

Next, you are calling this.stop(). Your event listener is anonymous (which is fine), but that means that this is Window. Again, there is no global stop method -- so you should call it on the timeline you wish to stop. In this case, it's probably exportRoot.stop().

Cheers,


问:
Visual Studio asking for a semicolon after for loop
```<code>#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
   char ch;
   int count;

   while ((ch = getchar()) != '\n')
      for (count = 0, count <= (ch - '0'), count++)
         printf("%c", ch);

   return 0;
}
</code>```

I haven't really gotten to the logistics of the coding. Just trying something. But as I was writing what seems like a simple for loop for the first time in C, I keep coming across an error on visual studio telling em to put a semicolon after the ) in the for loop statement. Well the problem is, even after I put one there, it keeps telling me I need a semicolon after the ).

I know that sometimes, the error might be somewhere else and it just tells you something totally irrelevant. I haven't even gotten to much coding yet and I can't find any really obvious mistakes.

I tried using brackets to block in the while and the for loops. If I remember correctly, I don't think you need a semicolon after the for statement...

Does anyone know what the problem might be? I thought maybe the project itself got a little faulty, so I opened a new project and wrote the new code in there. Sometimes, that works. I would just copy and paste the same exact code on a new project and it builds with no errors.

答: I believe it's asking you to put the semicolon after count <= (ch - '0'). Note that a for loop syntax is for (;;), where the each part can contain many expressions separated by commas.

ContentLicense: CC BY-SA 4.0

Body:
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
   char ch;
   int count;

   while ((ch = getchar()) != '\n')
      for (count = 0, count <= (ch - '0'), count++)
         printf("%c", ch);

   return 0;
}

I haven't really gotten to the logistics of the coding. Just trying something. But as I was writing what seems like a simple for loop for the first time in C, I keep coming across an error on visual studio telling em to put a semicolon after the ) in the for loop statement. Well the problem is, even after I put one there, it keeps telling me I need a semicolon after the ).

I know that sometimes, the error might be somewhere else and it just tells you something totally irrelevant. I haven't even gotten to much coding yet and I can't find any really obvious mistakes.

I tried using brackets to block in the while and the for loops. If I remember correctly, I don't think you need a semicolon after the for statement...

Does anyone know what the problem might be? I thought maybe the project itself got a little faulty, so I opened a new project and wrote the new code in there. Sometimes, that works. I would just copy and paste the same exact code on a new project and it builds with no errors.


问:
Python selenium : How to close the tab that gets open automatically along with the tab that selenium opens
I installed chrome extension on chromedriver before I open the required url.
As the extension get installed, it opens a tab mentioning "Thank you for installing".

extension url:https://chrome.google.com/webstore/detail/buyhatke/jaehkpjddfdgiiefcnhahapilbejohhj?hl=en

I would like to close the tab opened by extension as it unnecessarily loads data.

code snippet:

```<code>from selenium import webdriver
import time
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from bs4 import BeautifulSoup as soup

chrome_options = Options()
chrome_options.add_argument('load-
extension=C:\\Users\\SACHIN\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Extensions\\jaehkpjddfdgiiefcnhahapilbejohhj\\3.4.141_0')

driver = webdriver.Chrome(chrome_options=chrome_options)
driver.implicitly_wait(30)

driver.get("https://paytm.com/shop/p/samsung-j3-pro-16-gb-black-MOBSAMSUNG-J3-PSTPL5914255C1B4E1C?src=grid&tracker=curated%7C%7Cmobile%20phones%7CCategory%20Grid%7C%2Fg%2Fmobile-accessories%2Fmobiles%2Fsmart-phones%7C66781%7C1%7C")
</code>```

答:
You can switch to tab as

```<code>window_before = driver.window_handles[0] // May be 1 in your case
driver.switch_to_window(window_before)
</code>```

and close the driver.

Or send Alt + Tab keys and close the tab

Body:
I installed chrome extension on chromedriver before I open the required url.
As the extension get installed, it opens a tab mentioning "Thank you for installing".

extension url:https://chrome.google.com/webstore/detail/buyhatke/jaehkpjddfdgiiefcnhahapilbejohhj?hl=en

I would like to close the tab opened by extension as it unnecessarily loads data.

code snippet:

from selenium import webdriver
import time
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from bs4 import BeautifulSoup as soup

chrome_options = Options()
chrome_options.add_argument('load-
extension=C:\\Users\\SACHIN\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Extensions\\jaehkpjddfdgiiefcnhahapilbejohhj\\3.4.141_0')

driver = webdriver.Chrome(chrome_options=chrome_options)
driver.implicitly_wait(30)

driver.get("https://paytm.com/shop/p/samsung-j3-pro-16-gb-black-MOBSAMSUNG-J3-PSTPL5914255C1B4E1C?src=grid&tracker=curated%7C%7Cmobile%20phones%7CCategory%20Grid%7C%2Fg%2Fmobile-accessories%2Fmobiles%2Fsmart-phones%7C66781%7C1%7C")

Body:
You can switch to tab as

window_before = driver.window_handles[0] // May be 1 in your case
driver.switch_to_window(window_before)

and close the driver.

Or send Alt + Tab keys and close the tab


问:
Python Basemap Coordinates
I am using python 3.6 to open a shapefile of the Amazon River on to basemap. However I am confused with how coordinates work in python. I looked up coordinates of the the Amazon River and found it to be lon,lat=-55.126648,-2.163106. But to open my map I need the lat/lon values of corners, which I am not sure how to get.

Here is my code so far:

```<code>from mpl_toolkits.basemap import Basemap

import matplotlib.pyplot as plt

map= Basemap(projection='tmerc',
            lon_0=180,
            lat_0=0,
            resolution='l')
map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='#ddaa66',lake_color='aqua')
map.drawcoastlines()

map.readshapefile('filename','Amazon')
plt.show()
</code>```

Here is the error message I get when I try to run it:
ValueError: must either specify lat/lon values of corners
(llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters

答: When creating your map (map = Basemap(...)) , you need to specify those values.  They are lower left corner longitude, lower left corner latitude, upper right corner longitude, and upper right corner latitude.  These define the extents of the map.  You could just plot the whole earth, then look at the region you want and pick the points off of it for your new corners.

Title: Python Basemap Coordinates

Body:
I am using python 3.6 to open a shapefile of the Amazon River on to basemap. However I am confused with how coordinates work in python. I looked up coordinates of the the Amazon River and found it to be lon,lat=-55.126648,-2.163106. But to open my map I need the lat/lon values of corners, which I am not sure how to get.

Here is my code so far:

from mpl_toolkits.basemap import Basemap

import matplotlib.pyplot as plt

map= Basemap(projection='tmerc',
            lon_0=180,
            lat_0=0,
            resolution='l')
map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='#ddaa66',lake_color='aqua')
map.drawcoastlines()

map.readshapefile('filename','Amazon')
plt.show()

Here is the error message I get when I try to run it:
ValueError: must either specify lat/lon values of corners
(llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters


问:
Manipulating React State from an Existing DOM Node
I'm currently using a, "Handsontable," wrapper for React (react-handsontable).

The main issue I've been having is being able to hook into a <select> field that was created by the wrapper to change my application state.

I need to hook into an input that's on the DOM (not the virtual DOM) and onchange change my component state.

How can I go about accomplishing this.

答: Have you considered rendering the select as a React component itself with an onChange handler? Either way, what you could do is add a custom renderer where you add the onchange handler to that select element, and assign it to a bound method of your React component class. That way you'll be able to modify state with it without needing to do anything nasty like manipulating state from a DOM node.


问:
Dependency injection not working with League\Route and League\Container
I'm building a web application right now and I'm facing a problem with my controller.

I want to send to my controller my League\Plate\Engine (registred in my Container) but I keep having the same error : Argument 3 passed to App\Controller\Main::index() must be an instance of League\Plates\Engine, array given

Here is my files :

dependencies.php

```<code>use League\Container\Container;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Yajra\Pdo\Oci8;
use League\Container\ReflectionContainer;

$container = new Container();

// Active auto-wiring
$container->delegate(
    new ReflectionContainer
);

// Others dependencies
// ...

// Views
$container->add('view', function () {
    $templates = new League\Plates\Engine();

    $templates->addFolder('web', __DIR__ . '/templates/views/');
    $templates->addFolder('emails', __DIR__ . '/templates/emails/');

    // Extension
    //$templates->loadExtension(new League\Plates\Extension\Asset('/path/to/public'));
    //$templates->loadExtension(new League\Plates\Extension\URI($_SERVER['PATH_INFO']));

    return $templates;
});

return $container;
</code>```

routes.php

```<code>use League\Route\RouteCollection;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

$route = new RouteCollection($container);

// Page index
$route->get('/', 'App\Controller\Main::index');

// Others routes...

return $route;
</code>```

Main.php

```<code>namespace App\Controller;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use League\Plates\Engine;

class Main
{
    public function index(ServerRequestInterface $request, ResponseInterface $response, Engine $templates) {
        //return $response->getBody()->write($this->templates->render('web::home'));
        return $response;
    }
}
</code>```

Thank you in advance

EDIT

I've made a progress.
I extended the Main class to extends the abstract class BaseController which looks like this :

```<code>namespace App\Controller;

use League\Plates\Engine;

 class BaseController
{
    protected $templates;

    public function __construct(Engine $templates) {
        $this->templates = $templates;
    }
}
</code>```

The first error goes away, but another one show up. In the Main class, I would like to use the view object that I instanciate in the container, but the object passed to the constructor is an empty one :

Main.php

```<code>class Main extends BaseController
{
    public function index(ServerRequestInterface $request, ResponseInterface $response) {
        echo '```'.print_r($this->templates,1).'```'; // Return an empty Plate Engine object
        return $response->getBody()->write($this->templates->render('web::home'));
        //return $response;
    }
}
</code>```

And this doesn't explain why the first error shows up

EDIT 2

After some digging, I finally make it works, but I sense that something is wrong.
I replaced in the container the term view by the namespace of the Engine class :

```<code>$container->add('League\Plates\Engine', function () {
    // The same as before
});
</code>```

In Main.php I've updated the index function like this :

```<code>public function index(ServerRequestInterface $request, ResponseInterface $response) {
        $body = $response->getBody();
        $body->write($this->templates->render('web::home'));
        return $response->withBody($body);
    }
</code>```

And the page doesn't throw a 500 error and the html file is displayed correctly.

But, what if I want to change the template engine by Twig for example ? This would mean I'll need to change all the call to $container->get('League\Plate\Engine'); by $container->get('What\Ever'); ? That's not very practical!
I probably missed something!
And the problem will rise again when I'll want to use my PDO object... or every other object.

答:
Ok so I solved my problem by registering my Controllers classes in the container itself.

For example, for displaying the index page, the Main class call the index function. In my container, I call

```<code>$container->add('App\Controller\Main')
    ->withArgument($container->get('view'));
</code>```

To summary :

bootstap.php (called by index.php)

```<code>require __DIR__ . '/../../vendor/autoload.php';

$dotenv = new \Dotenv\Dotenv(__DIR__ . '/../');
$dotenv->load();

$config = new Config(__DIR__ . '/../config/');

$container = require __DIR__ . '/../dependencies.php';

$route = require __DIR__ . '/../routes.php';

$response = $route->dispatch($container->get('request'), $container->get('response'));
$container->get('emitter')->emit($response);
</code>```

dependencies.php

```<code>$container = new Container();

// activate auto-wiring
$container->delegate(
    new ReflectionContainer
);

// Others dependencies...

// Views
$container->add('view', function () {
    $templates = new League\Plates\Engine();

    $templates->addFolder('web', __DIR__ . '/templates/views/');
    $templates->addFolder('emails', __DIR__ . '/templates/emails/');

    // Extension
    //$templates->loadExtension(new League\Plates\Extension\Asset('/path/to/public'));
    //$templates->loadExtension(new League\Plates\Extension\URI($_SERVER['PATH_INFO']));

    return $templates;
});

// THIS IS THE TRICK
$container->add('App\Controller\Main')
    ->withArgument($container->get('view'));
// others controllers...

return $container;
</code>```

routes.php

```<code>$route = new RouteCollection($container);

// Page index
$route->get('/', 'App\Controller\Main::index');

// Others routes...

return $route;
</code>```

I have no idea why or how this work !

Body:
I'm building a web application right now and I'm facing a problem with my controller.

I want to send to my controller my League\Plate\Engine (registred in my Container) but I keep having the same error : Argument 3 passed to App\Controller\Main::index() must be an instance of League\Plates\Engine, array given

Here is my files :

dependencies.php

use League\Container\Container;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Yajra\Pdo\Oci8;
use League\Container\ReflectionContainer;

$container = new Container();

// Active auto-wiring
$container->delegate(
    new ReflectionContainer
);

// Others dependencies
// ...

// Views
$container->add('view', function () {
    $templates = new League\Plates\Engine();

    $templates->addFolder('web', __DIR__ . '/templates/views/');
    $templates->addFolder('emails', __DIR__ . '/templates/emails/');

    // Extension
    //$templates->loadExtension(new League\Plates\Extension\Asset('/path/to/public'));
    //$templates->loadExtension(new League\Plates\Extension\URI($_SERVER['PATH_INFO']));

    return $templates;
});

return $container;

routes.php

use League\Route\RouteCollection;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

$route = new RouteCollection($container);

// Page index
$route->get('/', 'App\Controller\Main::index');

// Others routes...

return $route;

Main.php

namespace App\Controller;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use League\Plates\Engine;

class Main
{
    public function index(ServerRequestInterface $request, ResponseInterface $response, Engine $templates) {
        //return $response->getBody()->write($this->templates->render('web::home'));
        return $response;
    }
}

Thank you in advance

EDIT

I've made a progress.
I extended the Main class to extends the abstract class BaseController which looks like this :

namespace App\Controller;

use League\Plates\Engine;

 class BaseController
{
    protected $templates;

    public function __construct(Engine $templates) {
        $this->templates = $templates;
    }
}

The first error goes away, but another one show up. In the Main class, I would like to use the view object that I instanciate in the container, but the object passed to the constructor is an empty one :

Main.php

class Main extends BaseController
{
    public function index(ServerRequestInterface $request, ResponseInterface $response) {
        echo '
'.print_r($this->templates,1).'
'; // Return an empty Plate Engine object
        return $response->getBody()->write($this->templates->render('web::home'));
        //return $response;
    }
}

And this doesn't explain why the first error shows up

EDIT 2

After some digging, I finally make it works, but I sense that something is wrong.
I replaced in the container the term view by the namespace of the Engine class :

$container->add('League\Plates\Engine', function () {
    // The same as before
});

In Main.php I've updated the index function like this :

public function index(ServerRequestInterface $request, ResponseInterface $response) {
        $body = $response->getBody();
        $body->write($this->templates->render('web::home'));
        return $response->withBody($body);
    }

And the page doesn't throw a 500 error and the html file is displayed correctly.

But, what if I want to change the template engine by Twig for example ? This would mean I'll need to change all the call to $container->get('League\Plate\Engine'); by $container->get('What\Ever'); ? That's not very practical!
I probably missed something!
And the problem will rise again when I'll want to use my PDO object... or every other object.

Body:
Ok so I solved my problem by registering my Controllers classes in the container itself.

For example, for displaying the index page, the Main class call the index function. In my container, I call

$container->add('App\Controller\Main')
    ->withArgument($container->get('view'));

To summary :

bootstap.php (called by index.php)

require __DIR__ . '/../../vendor/autoload.php';

$dotenv = new \Dotenv\Dotenv(__DIR__ . '/../');
$dotenv->load();

$config = new Config(__DIR__ . '/../config/');

$container = require __DIR__ . '/../dependencies.php';

$route = require __DIR__ . '/../routes.php';

$response = $route->dispatch($container->get('request'), $container->get('response'));
$container->get('emitter')->emit($response);

dependencies.php

$container = new Container();

// activate auto-wiring
$container->delegate(
    new ReflectionContainer
);

// Others dependencies...

// Views
$container->add('view', function () {
    $templates = new League\Plates\Engine();

    $templates->addFolder('web', __DIR__ . '/templates/views/');
    $templates->addFolder('emails', __DIR__ . '/templates/emails/');

    // Extension
    //$templates->loadExtension(new League\Plates\Extension\Asset('/path/to/public'));
    //$templates->loadExtension(new League\Plates\Extension\URI($_SERVER['PATH_INFO']));

    return $templates;
});

// THIS IS THE TRICK
$container->add('App\Controller\Main')
    ->withArgument($container->get('view'));
// others controllers...

return $container;

routes.php

$route = new RouteCollection($container);

// Page index
$route->get('/', 'App\Controller\Main::index');

// Others routes...

return $route;

I have no idea why or how this work !


问:
How do I tell if the user has entered something other than Male, male, Female or female for my input?
I am making a project and was wondering how I could use code to tell if the user has entered something other than "Male", "Female", "male", or "female".

I am using Python 3.0

This is my code:

```<code> import time
def w(t):
  if t == t:
    time.sleep(t)
print("In the following story, you are a mouse. Please fill out the following information (the story will use this name and gender).")
w(3)
print('\n')
name = input("Your Name:")
w(0.5)
print('\n')
gender = input("Your Gender (Male / Female):")
w(0.5)
print('\n')
input("Press Enter to Begin The Story")
w(1)
print('\n')
print("The Lion and The Mouse")
print("A Short Tale by Aesop")
w(1)
print('\n')
print("Once upon a time in a secluded jungle, there was a mouse.")
w(2)
print('\n')
if gender == ("male" or "Male"):
    heorshe = "he"
    hisher = "his"
    himher = "him"
    himselfherself = "himself"
    HeShe = "He"
if gender == "female" or "Female":
    heorshe = "she"
    hisher = "her"
    himher = "her"
    himselfherself = "herself"
    HeShe = "He"
</code>```

I would also like to be able to tell if the user has entered in nothing into the input! Please help!

答: You could just use else:, or if not 'male' or not 'Male:' and then print for example 'Please enter Male or Female.'

Body:
I am making a project and was wondering how I could use code to tell if the user has entered something other than "Male", "Female", "male", or "female".

I am using Python 3.0

This is my code:

 import time
def w(t):
  if t == t:
    time.sleep(t)
print("In the following story, you are a mouse. Please fill out the following information (the story will use this name and gender).")
w(3)
print('\n')
name = input("Your Name:")
w(0.5)
print('\n')
gender = input("Your Gender (Male / Female):")
w(0.5)
print('\n')
input("Press Enter to Begin The Story")
w(1)
print('\n')
print("The Lion and The Mouse")
print("A Short Tale by Aesop")
w(1)
print('\n')
print("Once upon a time in a secluded jungle, there was a mouse.")
w(2)
print('\n')
if gender == ("male" or "Male"):
    heorshe = "he"
    hisher = "his"
    himher = "him"
    himselfherself = "himself"
    HeShe = "He"
if gender == "female" or "Female":
    heorshe = "she"
    hisher = "her"
    himher = "her"
    himselfherself = "herself"
    HeShe = "He"

I would also like to be able to tell if the user has entered in nothing into the input! Please help!


问:
How to structure REGEX in C#
I currently have a regex that checks if a US State is spelled correctly

var r = new Regex(string.Format(@"\b(?:{0})\b", pattern), RegexOptions.IgnoreCase)

pattern is a pipe delimited string containing all US states.

It was working as intended today until one of the states was spelled like "Florida.." I would have liked it picked up the fact there was a fullstop character.

I found this regex that will only match letters.
    ^[a-zA-Z]+

How do I combine this with my current Regex or is it not possible?

I tried some variations of this but it didn't work

```<code>var r = new Regex(string.Format(@"\b^[a-zA-Z]+(?:{0})\b", pattern), RegexOptions.IgnoreCase);
</code>```

EDIT: Florida.. was in my input string. My pattern string hasn't changed at all. Apologies for not being clearer.

答:
Basically don't use a regex here.

```<code>List<string> values = new List<string>() {"florida", etc.};
string input;
//is input in values, ignore case and look for any value that includes the input value
bool correct = values.Any(a =>
                  input.IndexOf(a, StringComparison.CurrentCultureIgnoreCase) >= 0);
</code>```

This will be considerably more efficient than a regex based option. This should match florida, Florida and Florida..., etc.

Title: How to structure REGEX in C#

Body:
I currently have a regex that checks if a US State is spelled correctly

var r = new Regex(string.Format(@"\b(?:{0})\b", pattern), RegexOptions.IgnoreCase)

pattern is a pipe delimited string containing all US states.

It was working as intended today until one of the states was spelled like "Florida.." I would have liked it picked up the fact there was a fullstop character.

I found this regex that will only match letters.
    ^[a-zA-Z]+

How do I combine this with my current Regex or is it not possible?

I tried some variations of this but it didn't work

var r = new Regex(string.Format(@"\b^[a-zA-Z]+(?:{0})\b", pattern), RegexOptions.IgnoreCase);

EDIT: Florida.. was in my input string. My pattern string hasn't changed at all. Apologies for not being clearer.

Body:
Basically don't use a regex here.

List<string> values = new List<string>() {"florida", etc.};
string input;
//is input in values, ignore case and look for any value that includes the input value
bool correct = values.Any(a =>
                  input.IndexOf(a, StringComparison.CurrentCultureIgnoreCase) >= 0);

This will be considerably more efficient than a regex based option. This should match florida, Florida and Florida..., etc.


问:
Using ViewModelToModel for classes in Orc.Wizard ViewModels and WizardPage
I have created a Wizard using Orc.Wizard.  My WizardPage has several backing items:

```<code>public LoadOptions LoadOpts {get; set;}
public string FolderPath {get; set;}
</code>```

In my ViewModel I am using the [ViewModelToModel] to expose the classes and the properties of those classes in my WizardPage model using this method.

```<code>[ViewModelToModel]
public string FolderPath {get; set;}

[ViewModelToModel]
[Expose("PropertyA")]
[Expose("PropertyB")]
public LoadOptions LoadOpts {get; set; }
</code>```

Any suggestions would be greatly appreciated. NOTE: All of the example applications I can find just use simple fields like "string", none of them have class in the backing WizardPage.

答:
In order to expose, you will need to decorate your property with the Model attribute:</p>

```<code>[ViewModelToModel(nameof(LoadOpts))]
public string FolderPath {get; set;}

[Model]
[Expose("PropertyA")]
[Expose("PropertyB")]
public LoadOptions LoadOpts {get; set; }
</code>```

Body:
I have created a Wizard using Orc.Wizard.  My WizardPage has several backing items:

public LoadOptions LoadOpts {get; set;}
public string FolderPath {get; set;}

In my ViewModel I am using the [ViewModelToModel] to expose the classes and the properties of those classes in my WizardPage model using this method.

[ViewModelToModel]
public string FolderPath {get; set;}

[ViewModelToModel]
[Expose("PropertyA")]
[Expose("PropertyB")]
public LoadOptions LoadOpts {get; set; }

Any suggestions would be greatly appreciated. NOTE: All of the example applications I can find just use simple fields like "string", none of them have class in the backing WizardPage.

Body:
In order to expose, you will need to decorate your property with the Model attribute:

[ViewModelToModel(nameof(LoadOpts))]
public string FolderPath {get; set;}

[Model]
[Expose("PropertyA")]
[Expose("PropertyB")]
public LoadOptions LoadOpts {get; set; }


问:
Is mouse over Form?
This code is not working for me on Delphi XE:

http://delphi.about.com/cs/adptips2000/a/bltip0800_5.htm

```<code>procedure TForm1.FormDeactivate(Sender: TObject) ;
begin
   ReleaseCapture;
end;

procedure TForm1.FormMouseMove
(Sender: TObject; Shift: TShiftState; X,Y: Integer) ;
begin
  If GetCapture = 0 then
    SetCapture(Form1.Handle) ;
    if PtInRect(Rect(Form1.Left,
                    Form1.Top,
                    Form1.Left + Form1.Width,
                    Form1.Top + Form1.Height),
                    ClientToScreen(Point(x, y))) then
     Form1.Caption := 'Mouse is over form' else
     Form1.Caption := 'Mouse is outside of form';
end;
</code>```

No errors - it just has no effect.

Please help.

EDIT 1

It turned out the problem is not with the code, even mouse FormMouseEnter and FormMouseLeave are not working because I'm passing the form to a Unit I created with a function like this:

procedure Slide(Form: TForm; Show: Boolean);

I'm calling the Show method from inside this procedure. How can I overcome this problem?

Thanks.

EDIT 2

I don't want to use the function I posted now. I want to use what the people suggested below (FormMouseEnter and FormMouseLeave) but it's not working in my case as well.

答:
This is just a matter of entering the necessary code in the OnMouseEnter and OnMouseLeave events of the corresponding form.  In my case, all I did was :

Create a new project in Delphi

Select the form you are working with

Go to the Object Inspector

Switch to the Events tab in the object inspector if necessary

Scroll down to the OnMouseEnter event, double click in the white space next to it which will generate an EventHandler. Make sure you end up with the following code in the event handler :

```<code>procedure TForm1.FormMouseEnter(Sender: TObject);
begin
  Self.Caption := 'Mouse in form';
end;
</code>```

Go to the Object Inspector again

Find the OnMouseLeave event and double click in the white area to the right of it to generate a new event handler, and add the following code to it

```<code>procedure TForm1.FormMouseLeave(Sender: TObject);
begin
  Self.Caption := 'Mouse outside form';
end;
</code>```

Run the app ... move your mouse over the form and the caption will change to 'Mouse inside form', move it outside the form and the caption will say 'Mouse outside form'

Works as a charm (Tested in Delphi 2010)

ContentLicense: CC BY-SA 2.5

Title: Is mouse over Form?

Body:
This code is not working for me on Delphi XE:

http://delphi.about.com/cs/adptips2000/a/bltip0800_5.htm

procedure TForm1.FormDeactivate(Sender: TObject) ;
begin
   ReleaseCapture;
end;

procedure TForm1.FormMouseMove
(Sender: TObject; Shift: TShiftState; X,Y: Integer) ;
begin
  If GetCapture = 0 then
    SetCapture(Form1.Handle) ;
    if PtInRect(Rect(Form1.Left,
                    Form1.Top,
                    Form1.Left + Form1.Width,
                    Form1.Top + Form1.Height),
                    ClientToScreen(Point(x, y))) then
     Form1.Caption := 'Mouse is over form' else
     Form1.Caption := 'Mouse is outside of form';
end;

No errors - it just has no effect.

Please help.

EDIT 1

It turned out the problem is not with the code, even mouse FormMouseEnter and FormMouseLeave are not working because I'm passing the form to a Unit I created with a function like this:

procedure Slide(Form: TForm; Show: Boolean);

I'm calling the Show method from inside this procedure. How can I overcome this problem?

Thanks.

EDIT 2

I don't want to use the function I posted now. I want to use what the people suggested below (FormMouseEnter and FormMouseLeave) but it's not working in my case as well.

Body:
This is just a matter of entering the necessary code in the OnMouseEnter and OnMouseLeave events of the corresponding form.  In my case, all I did was :

Create a new project in Delphi

Select the form you are working with

Go to the Object Inspector

Switch to the Events tab in the object inspector if necessary

Scroll down to the OnMouseEnter event, double click in the white space next to it which will generate an EventHandler. Make sure you end up with the following code in the event handler :

procedure TForm1.FormMouseEnter(Sender: TObject);
begin
  Self.Caption := 'Mouse in form';
end;

Go to the Object Inspector again

Find the OnMouseLeave event and double click in the white area to the right of it to generate a new event handler, and add the following code to it

procedure TForm1.FormMouseLeave(Sender: TObject);
begin
  Self.Caption := 'Mouse outside form';
end;

Run the app ... move your mouse over the form and the caption will change to 'Mouse inside form', move it outside the form and the caption will say 'Mouse outside form'

Works as a charm (Tested in Delphi 2010)


问:
An exception of type 'System.ArgumentException' occurred in Google.Apis.dll but was not handled in user code
I am trying to connect Google Drive Service client but I am getting this exception and I am not getting any solution. Here is my code.

```<code>public static DriveService GetDriveClient()
    {
        var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets { ClientId = clientID, ClientSecret = clientSecret }
                , scopes
                , Environment.UserName
                , CancellationToken.None
                , new FileDataStore(credPath, true)
            ).Result;

        // Create Drive API service.
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = appName,
        });

        return service;
    }
</code>```

I am getting following error in yellow screen:

Invalid Application name
Parameter name: ApplicationName

答:
.NET doesn't like any special characters in the Application Name.
I copied code from the Google API Quickstart and continually received errors. </p>

```<code>//static string ApplicationName = "Drive API .NET Quickstart"; //DOESN'T WORK!
static string ApplicationName = "oneWord";   //WORKS!
</code>```

<p>Possibly needs URL encoding or some other handling but the above fixed my problem. </p>

Body:
I am trying to connect Google Drive Service client but I am getting this exception and I am not getting any solution. Here is my code.

public static DriveService GetDriveClient()
    {
        var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets { ClientId = clientID, ClientSecret = clientSecret }
                , scopes
                , Environment.UserName
                , CancellationToken.None
                , new FileDataStore(credPath, true)
            ).Result;

        // Create Drive API service.
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = appName,
        });

        return service;
    }

I am getting following error in yellow screen:

Invalid Application name
Parameter name: ApplicationName

Body:
.NET doesn't like any special characters in the Application Name.
I copied code from the Google API Quickstart and continually received errors.

//static string ApplicationName = "Drive API .NET Quickstart"; //DOESN'T WORK!
static string ApplicationName = "oneWord";   //WORKS!

Possibly needs URL encoding or some other handling but the above fixed my problem.


问:
I can't set up Kubernetes in Centos 7: Unable to update cni config
I am trying to follow docs to setup a one node Kubernetes cluster with Centos 7.

kubeadm init will return no error but kubectl get nodes will return:

```<code>NAME      STATUS     AGE       VERSION
[MY_IP]   NotReady   22s       v1.6.4
</code>```

system log repeats:

```<code>Jun  6 16:21:48 localhost kubelet: W0606 16:21:48.064388   11520 cni.go:157] Unable to update cni config: No networks found in /etc/cni/net.d
Jun  6 16:21:48 localhost kubelet: E0606 16:21:48.064537   11520 kubelet.go:2067] Container runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
</code>```

I can only find info about this in Kubernetes github logs but they talk about a  bug and I haven't found a workaround. Thanks

答: Looks like you need a pod network. Have you completed step 3 in the guide here? If you install one of the network overlays (listed at https://kubernetes.io/docs/concepts/cluster-administration/addons/), you should be good to go.</p>

Body:
I am trying to follow docs to setup a one node Kubernetes cluster with Centos 7.

kubeadm init will return no error but kubectl get nodes will return:

NAME      STATUS     AGE       VERSION
[MY_IP]   NotReady   22s       v1.6.4

system log repeats:

Jun  6 16:21:48 localhost kubelet: W0606 16:21:48.064388   11520 cni.go:157] Unable to update cni config: No networks found in /etc/cni/net.d
Jun  6 16:21:48 localhost kubelet: E0606 16:21:48.064537   11520 kubelet.go:2067] Container runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized

I can only find info about this in Kubernetes github logs but they talk about a  bug and I haven't found a workaround. Thanks


问:
How to add a bot to contact list after removing it
I believe I've found a bug in Skype for Windows 10. I was trying to test detecting add/remove bot from contacts. Once I removed the bot from contacts, the link to add the bot back stopped working. It only shows you the bot with a question mark next to it. I tried to follow these instructions for adding:

https://support.skype.com/en/faq/FA421/how-do-i-manage-my-contacts-in-skype-for-windows-desktop#5

But when right clicking the name to add to contacts again, the expected option is missing. It also turns out that any message sent from my bot to myself while in this state will go missing. This had me believing my bot was not working for at least a day which was very annoying.

Please advise! This is a blocking issue. Thanks.

答:
As confirmed in comments, trying add/remove bot from web version of Skype works:

https://web.skype.com

So probably that really was a bug of Skype for windows.


问:
Precision field in printf when formatting integer
When I execute these two lines:

```<code>printf("%.5d\n", 3);  // use of precision filed
printf("%05d\n", 3);  // use of 0 flag to prepend with 0
</code>```

I get the following output:

```<code>00003
00003
</code>```

The same result

So I wonder what is the meaning of the precision field for integer types

答:
For %d, the precision is the minimum number of digits to print.

From the man page:

The precision

An optional precision, in the form of a period ('.')  followed by
  an optional decimal digit string.  Instead of a  decimal  digit
  string  one  may    write "*" or "*m$" (for some decimal integer m) to
  specify that the precision is given in the next argument, or in the
  m-th argument, respectively,    which must be of type int.  If the
  precision is given as just '.', or the precision is negative, the
  precision is taken to be zero.  This gives the    minimum  number  of
  digits to appear for d, i, o, u, x, and X conversions, the number of
  digits to appear after the radix character for a, A, e, E,    f, and F
  conversions, the maximum number of significant digits for g and G
  conversions, or the maximum number of characters to be  printed  from
  a    string for s and S conversions.

For positive values, this works out to be the same as giving the same value for the field width and a 0  flag.  If the value is negative, the negative sign will take up one character in the width of %05d.

```<code>printf("%.5d\n", -3);  // use of precision filed
printf("%05d\n", -3);  // use of 0 flag to prepend with 0
</code>```

Output:

```<code>-00003
-0003
</code>```

Body:
When I execute these two lines:

printf("%.5d\n", 3);  // use of precision filed
printf("%05d\n", 3);  // use of 0 flag to prepend with 0

I get the following output:

00003
00003

The same result

So I wonder what is the meaning of the precision field for integer types

Body:
For %d, the precision is the minimum number of digits to print.

From the man page:

The precision

An optional precision, in the form of a period ('.')  followed by
  an optional decimal digit string.  Instead of a  decimal  digit
  string  one  may    write "*" or "*m$" (for some decimal integer m) to
  specify that the precision is given in the next argument, or in the
  m-th argument, respectively,    which must be of type int.  If the
  precision is given as just '.', or the precision is negative, the
  precision is taken to be zero.  This gives the    minimum  number  of
  digits to appear for d, i, o, u, x, and X conversions, the number of
  digits to appear after the radix character for a, A, e, E,    f, and F
  conversions, the maximum number of significant digits for g and G
  conversions, or the maximum number of characters to be  printed  from
  a    string for s and S conversions.

For positive values, this works out to be the same as giving the same value for the field width and a 0  flag.  If the value is negative, the negative sign will take up one character in the width of %05d.

printf("%.5d\n", -3);  // use of precision filed
printf("%05d\n", -3);  // use of 0 flag to prepend with 0

Output:

-00003
-0003


问:
How to measure ios nsurlsession dowload task Speed?
How to measure a downloadTask Speed:

The Method which I thought is:

calc the last 3s avg speed, and reset received Bytes after 3s, and start a NSTimer which every 0.8s call once.

But this will cause a problem: After 3s the NSTimer call at once, the received Bytes has been reset to 0, but I want a Smooth speed.

答:
First, use NSURLSessionDelegate. If you are using completionHandler: delegate methods won't be called. Then in:

```<code>-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
</code>```

you can add your own counter of [data length]. Collect and reset it in a synchronized way using NSTimer and you have it. Remember that NSTimer is not firing exactly as specified so if you need better precision store exact times of measurements

Body:
First, use NSURLSessionDelegate. If you are using completionHandler: delegate methods won't be called. Then in:

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data

you can add your own counter of [data length]. Collect and reset it in a synchronized way using NSTimer and you have it. Remember that NSTimer is not firing exactly as specified so if you need better precision store exact times of measurements


问:
How to sort a table in XlsxWriter using filter's 'Sort A to Z'?
Recently, I've discovered XlsxWriter for Python (and I do enjoy it!) and I started working on some spreadsheet. I need to programmatically create a spreadsheet identical to one created manually by some other person. I managed to create everything I needed except for sorting table in autofilter. Basically, I would like to create something like this:
and I couldn't figure out how. I checked with the documentation (1, 2) and didn't find any information about sorting. What I do now is:

worksheet.autofilter(1, 0, known_lenght, known_width)

which results in autofilter arrow appearing in lower right corner of header cells but worksheet.autofilter() seems to lack sorting capability. Am I missing something or is there no option to create autofilter and set sorting in it in XlsxWriter? Thanks!

答:
Am I missing something or is there no option to create autofilter and set sorting in it in XlsxWriter?

Sorting of data in Excel is done at runtime and isn't a function of the file format. As such it isn't supported by XlsxWriter.

Instead you should sort the data in Python and then write it to the autofilter region.

However, that won't set the autofilter arrow to "sorted". That isn't currently supported in XlsxWriter.


问:
Cannot connect to localhost with cURL on Command Prompt
I've just installed cURL on my hard-drive in order to use for testing with my localhost (on the command prompt). However I cannot connect to any port. You can see the directory and my input below:

C:\Users\me\curl\src>curl -v http://localhost:9000

which gives me:

Rebuilt URL to: http://localhost:9000/

timeout on name lookup is not supported

Trying ::1...

TCP_NODELAY set

Trying 127.0.0.1...

TCP_NODELAY set

connect to ::1 port 9000 failed: Connection refused

connect to 127.0.0.1 port 9000 failed: Connection refused

Failed to connect to localhost port 9000: Connection refused

Closing connection 0 curl: (7) Failed to connect to localhost port 9000: Connection refused

Perhaps I should have added that  I am using IntelliJ and have since enabled cURL on the harddrive (allowing me to access it from any directory); prompting me to try the following:

C:\Users\me\scala\play\my-project>curl -v http://localhost:9000/

which returns:

timeout on name lookup is not supported

Trying ::1...

TCP_NODELAY set

connect to ::1 port 9000 failed: Connection refused

Trying 127.0.0.1...

TCP_NODELAY set

connect to 127.0.0.1 port 9000 failed: Connection refused

Failed to connect to localhost port 9000: Connection refused

Closing connection 0 curl: (7) Failed to connect to localhost port 9000: Connection refused

So it seems that port 9000 is not open. And I am now thinking that this needs to be configured within intelliJ - here - but this looks as though it is only supported on the Ultimate Edition. This might be the cause of the issue that I am having. It may be helpful to others but it would be good to be sure of this if anyone does have any more information.

答:
This means that your application is not started yet (so it isn't actually listening on port 9000)

You should add a run configuration in IntelliJ (Run > Edit Configurations > + > Play 2 App) and run it before doing your curl call.

Another way to start your application is just to open a terminal in your project folder, and run sbt run.


问:
ggplot strange ordering of stacked bar
I am attempting to create a diverging stacked bar like here, and am experiencing a similar issue to this SO question. My approach is slightly different though as I am managing it all via a single dataset, rather than two and my colours are independent of my data.

Reprex as follows:

```<code>library(tidyverse)
library(RColorBrewer)
x <- tribble(
  ~response, ~count,
  0,         -27,
  1,          -9,
  2,         -41,
  3,         -43,
  4,         -58,
  5,        -120,
  5,         120,
  6,         233,
  7,         379,
  8,         388,
  9,         145,
  10,         61
) %>%
  mutate(response = factor(response))

ggplot(x, aes(x = 1, y = count, fill = response)) +
  geom_col() +
  scale_fill_brewer(palette = "RdBu") +
  coord_flip()
</code>```

This gives me an image like this:

The issue is to do with the ordering of the stacked data on the right hand side of the zero where they stacking appears to be in descending order. Any thoughts on how to fix this would be greatly appreciated (expected ordering would be 0-10, not 0-5,10-5)

答:
A tough one! I played with ordering and it seems that geom_bar and geom_col don't like it when you combine positive and negative values in the common same order. So I divided your data inside the dataframe for positive and negative values, generated colors for every response value and used two geoms for positive and negative values separately:

```<code>library(tidyverse)
library(RColorBrewer)
x <- tribble(
  ~response, ~count,
  0,         -27,
  1,          -9,
  2,         -41,
  3,         -43,
  4,         -58,
  5,        -120,
  5,         120,
  6,         233,
  7,         379,
  8,         388,
  9,         145,
  10,         61
) %>%
  # Get absolute values and add dummy to distuingish positive and negative values
  mutate(subzero = count < 0,
         count = abs(count))

# Generate variable with colors from ColorBrewer for every response level (ugly but works)
colors <- brewer.pal(length(unique(x$response)),"RdBu")
x$colors <- NA
for (i in 1:nrow(x)){
  x$colors[i] <- colors[x$response[i]+1]
}

ggplot() +
  geom_bar(data = x[x$subzero==T,], aes(x = "", y = -count, fill = reorder(colors, response)), position="stack", stat="identity") +
  geom_bar(data = x[x$subzero==F,], aes(x = "", y = count, fill = reorder(colors, -response)), position="stack", stat="identity") +
  geom_hline(yintercept = 0, color =c("black")) +
  scale_fill_identity("Response", labels = unique(x$response), breaks=unique(x$colors), guide="legend") +
  coord_flip() +
  labs(y="",x="") +
  theme(legend.position = "bottom", legend.direction = "horizontal") +
  scale_y_continuous(breaks=seq(-1400,1400,200), limits=c(-1400,1400))
</code>```

UPD: made Y-scale balanced so it look more clear

Title: ggplot strange ordering of stacked bar

Body:
I am attempting to create a diverging stacked bar like here, and am experiencing a similar issue to this SO question. My approach is slightly different though as I am managing it all via a single dataset, rather than two and my colours are independent of my data.

Reprex as follows:

library(tidyverse)
library(RColorBrewer)
x <- tribble(
  ~response, ~count,
  0,         -27,
  1,          -9,
  2,         -41,
  3,         -43,
  4,         -58,
  5,        -120,
  5,         120,
  6,         233,
  7,         379,
  8,         388,
  9,         145,
  10,         61
) %>%
  mutate(response = factor(response))

ggplot(x, aes(x = 1, y = count, fill = response)) +
  geom_col() +
  scale_fill_brewer(palette = "RdBu") +
  coord_flip()

This gives me an image like this:

The issue is to do with the ordering of the stacked data on the right hand side of the zero where they stacking appears to be in descending order. Any thoughts on how to fix this would be greatly appreciated (expected ordering would be 0-10, not 0-5,10-5)

Body:
A tough one! I played with ordering and it seems that geom_bar and geom_col don't like it when you combine positive and negative values in the common same order. So I divided your data inside the dataframe for positive and negative values, generated colors for every response value and used two geoms for positive and negative values separately:

library(tidyverse)
library(RColorBrewer)
x <- tribble(
  ~response, ~count,
  0,         -27,
  1,          -9,
  2,         -41,
  3,         -43,
  4,         -58,
  5,        -120,
  5,         120,
  6,         233,
  7,         379,
  8,         388,
  9,         145,
  10,         61
) %>%
  # Get absolute values and add dummy to distuingish positive and negative values
  mutate(subzero = count < 0,
         count = abs(count))

# Generate variable with colors from ColorBrewer for every response level (ugly but works)
colors <- brewer.pal(length(unique(x$response)),"RdBu")
x$colors <- NA
for (i in 1:nrow(x)){
  x$colors[i] <- colors[x$response[i]+1]
}

ggplot() +
  geom_bar(data = x[x$subzero==T,], aes(x = "", y = -count, fill = reorder(colors, response)), position="stack", stat="identity") +
  geom_bar(data = x[x$subzero==F,], aes(x = "", y = count, fill = reorder(colors, -response)), position="stack", stat="identity") +
  geom_hline(yintercept = 0, color =c("black")) +
  scale_fill_identity("Response", labels = unique(x$response), breaks=unique(x$colors), guide="legend") +
  coord_flip() +
  labs(y="",x="") +
  theme(legend.position = "bottom", legend.direction = "horizontal") +
  scale_y_continuous(breaks=seq(-1400,1400,200), limits=c(-1400,1400))

UPD: made Y-scale balanced so it look more clear


问:
How to parse out date from non standard date string
I have a date that is returned in this string format from moment.js for a calendar app.

Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)

How can i parse this string back into '2017-06-16', using moment to backtrack specifies this is an invalid input. Using it as an instance of new Date() returns to me an incorrect date.

```<code>var check = moment('Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)', 'YYYY/MM/DD');

var month = check.format('M');
var day   = check.format('D');
var year  = check.format('YYYY');

console.log(month, day, year);
//-->invalid date
</code>```

http://jsfiddle.net/t89apndd/

答:
Totally agree with Jordan Running's comment

That console output does not show a string. It show an object property named date whose value is a Moment object

Since you already have a moment object (your date var), you can simply use format() to show moment value in the format you prefer.

In your case you can do:

```<code>date.format('YYYY-MM-DD');
</code>```

Here a live sample:

var date = moment([2017, 5, 16]);
console.log(date); // Print moment object (like the one provided in the question)
console.log(date.format('YYYY-MM-DD')); // Print string output of format (in the desired format)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script></code>```

Body:
I have a date that is returned in this string format from moment.js for a calendar app.

Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)

How can i parse this string back into '2017-06-16', using moment to backtrack specifies this is an invalid input. Using it as an instance of new Date() returns to me an incorrect date.

var check = moment('Fri Jun 16 2017 00:00:00 GMT-0500 (Central Daylight Time)', 'YYYY/MM/DD');

var month = check.format('M');
var day   = check.format('D');
var year  = check.format('YYYY');

console.log(month, day, year);
//-->invalid date

http://jsfiddle.net/t89apndd/

Body:
Totally agree with Jordan Running's comment

That console output does not show a string. It show an object property named date whose value is a Moment object

Since you already have a moment object (your date var), you can simply use format() to show moment value in the format you prefer.

In your case you can do:

date.format('YYYY-MM-DD');

Here a live sample:

var date = moment([2017, 5, 16]);
console.log(date); // Print moment object (like the one provided in the question)
console.log(date.format('YYYY-MM-DD')); // Print string output of format (in the desired format)

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>


问:
Firefox display=block problem
I have a the following HTML

```<code> <a id="rptQuestions_ctl01_hlQuestion" onclick="rptQuestions_ctl01_pnlAnswer.style.display = rptQuestions_ctl01_pnlAnswer.style.display == 'none'? 'block' : 'none';" href="javascript:">Header Link</a>

            <div id="rptQuestions_ctl01_pnlAnswer" style="display:none;">

            My Text to display

</div>
</code>```

This works as i would expect in IE8, where it displays the div when you click the header link, and then hides it when clicking the header link again. However, in Firefox, nothing happens when i click the header link.
I'm assuming this is to do with IE being forgiving of an error i have made, and Firefox sticking to the rules, but i can't see what i am doing wrong.
Any ideas?

--- EDIT

I've tried this with the following code and it works fine:

```<code>        <a id="rptQuestions_ctl01_hlQuestion" onclick="jasvascript:document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display='block';" href="#">My header Link</a>

            <div id="rptQuestions_ctl01_pnlAnswer" style="display:none;">
My Text

</div>
</code>```

so it seems the problem is the ternary operator not working correctly.
Anyone see the problem?

答:
No, it does work in Firefox (just tested on 3.6.13).

Can't you use jQuery, or some other library? Sorry, this is just too ugly... :-)

Title: Firefox display=block problem

Body:
I have a the following HTML

 Header Link

            My Text to display

This works as i would expect in IE8, where it displays the div when you click the header link, and then hides it when clicking the header link again. However, in Firefox, nothing happens when i click the header link.
I'm assuming this is to do with IE being forgiving of an error i have made, and Firefox sticking to the rules, but i can't see what i am doing wrong.
Any ideas?

--- EDIT

I've tried this with the following code and it works fine:

        My header Link

My Text

so it seems the problem is the ternary operator not working correctly.
Anyone see the problem?


问:
Get Title and Description when Title item is clicked on Listview android
I use JSON to get data items Title and Description from a web server. I know how to parse it, use a custom Adapter and populate a listview with the Title only.. I want it to open a new activity and display the Title and Description of the clicked Item. Do I have to create a new custom adapter to populate this listview?  What should I pass from this side of the activity and how do I receive it on the other side?  Thanks in advance.

```<code> displayTitleAdapter = new DisplayTitleAdapter(this, R.layout.rowlayout);
    listView = (ListView)findViewById(R.id.listviewfinal);
    listView.setAdapter(displayTitleAdapter);
    listView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
</code>```

This is my  Adapter class' getView method

```<code>public View getView(int position,  View convertView,  ViewGroup parent) {
    View row;
    row = convertView;
    ReqHolder reqHolder;
    if(row == null){
        LayoutInflater layoutInflate = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = layoutInflate.inflate(R.layout.rowlayout, parent, false);
        reqHolder = new ReqHolder();

        reqHolder.Title = (TextView)row.findViewById(R.id.title_title);
        reqHolder.Requirement = (TextView)row.findViewById(R.id.req_req);

        row.setTag(reqHolder);
    }
    else{
        reqHolder = (ReqHolder)row.getTag();
    }
    //Requirements is the model class with getter and setter methods for Fields Title and Requirement.
    Requirements requirements = (Requirements) this.getItem(position);
    reqHolder.Title.setText(requirements.getTitle());
    reqHolder.Requirement.setText(requirements.getRequirement());
    return row;
}

static class ReqHolder{
    TextView Title;
     TextView Requirement;
}
</code>```

}

答:
that's works good :</p>

```<code>listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Object o = listView.getItemAtPosition(position);
                UserConnected str=(UserConnected) o;//As you are using Default String Adapter
                Toast.makeText(getBaseContext(),str.getPrenom(), Toast.LENGTH_SHORT).show();
            }
        });
</code>```

Body:
I use JSON to get data items Title and Description from a web server. I know how to parse it, use a custom Adapter and populate a listview with the Title only.. I want it to open a new activity and display the Title and Description of the clicked Item. Do I have to create a new custom adapter to populate this listview?  What should I pass from this side of the activity and how do I receive it on the other side?  Thanks in advance.

 displayTitleAdapter = new DisplayTitleAdapter(this, R.layout.rowlayout);
    listView = (ListView)findViewById(R.id.listviewfinal);
    listView.setAdapter(displayTitleAdapter);
    listView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

This is my  Adapter class' getView method

public View getView(int position,  View convertView,  ViewGroup parent) {
    View row;
    row = convertView;
    ReqHolder reqHolder;
    if(row == null){
        LayoutInflater layoutInflate = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = layoutInflate.inflate(R.layout.rowlayout, parent, false);
        reqHolder = new ReqHolder();

        reqHolder.Title = (TextView)row.findViewById(R.id.title_title);
        reqHolder.Requirement = (TextView)row.findViewById(R.id.req_req);

        row.setTag(reqHolder);
    }
    else{
        reqHolder = (ReqHolder)row.getTag();
    }
    //Requirements is the model class with getter and setter methods for Fields Title and Requirement.
    Requirements requirements = (Requirements) this.getItem(position);
    reqHolder.Title.setText(requirements.getTitle());
    reqHolder.Requirement.setText(requirements.getRequirement());
    return row;
}

static class ReqHolder{
    TextView Title;
     TextView Requirement;
}

}

Body:
that's works good :

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Object o = listView.getItemAtPosition(position);
                UserConnected str=(UserConnected) o;//As you are using Default String Adapter
                Toast.makeText(getBaseContext(),str.getPrenom(), Toast.LENGTH_SHORT).show();
            }
        });


问:
Swift return result of function calls
I'm completing some exercism exercises. One is a Binary tree (although the context is not relevant to the question as I have experienced this previously in Swift)

I would like to put the following function on one line as:

```<code>func allData () -> [Int] {
    return ( left?.allData() ?? [] ) + [data] + ( right?.allData() ?? [] )
}
</code>```

But the error is 'Int' is not convertible to '[Int]'

Ok, but splitting into separate lines is fine:

```<code>func allData () -> [Int] {
    let leftdata = left?.allData() ?? []
    let rightdata = right?.allData() ?? []
    return ( leftdata ) + [data] + ( rightdata )
}
</code>```

In fact it will compile with either the left data, right data and [data], but not both.

Within exercism I can see that people did not solve this in one line.

So why is

```<code>return ( left?.allData() ?? [] ) + [data] + ( right?.allData() ?? [] )
</code>```

invalid?

答:
It won't answer your "why" question, but this might offer you an alternative if you want to keep it as a one-liner:

```<code>func allData() -> [Int] {
    return [left?.allData() ?? [], [data], right?.allData() ?? []].flatMap { $0 }
}
</code>```

or

```<code>func allData() -> [Int] {
    // The first flatMap removes nil elements and the second flattens the array
    return [left?.allData(), [data], right?.allData()].flatMap { $0 }.flatMap { $0 }
}
</code>```

Title: Swift return result of function calls

Body:
I'm completing some exercism exercises. One is a Binary tree (although the context is not relevant to the question as I have experienced this previously in Swift)

I would like to put the following function on one line as:

func allData () -> [Int] {
    return ( left?.allData() ?? [] ) + [data] + ( right?.allData() ?? [] )
}

But the error is 'Int' is not convertible to '[Int]'

Ok, but splitting into separate lines is fine:

func allData () -> [Int] {
    let leftdata = left?.allData() ?? []
    let rightdata = right?.allData() ?? []
    return ( leftdata ) + [data] + ( rightdata )
}

In fact it will compile with either the left data, right data and [data], but not both.

Within exercism I can see that people did not solve this in one line.

So why is

return ( left?.allData() ?? [] ) + [data] + ( right?.allData() ?? [] )

invalid?

Body:
It won't answer your "why" question, but this might offer you an alternative if you want to keep it as a one-liner:

func allData() -> [Int] {
    return [left?.allData() ?? [], [data], right?.allData() ?? []].flatMap { $0 }
}

or

func allData() -> [Int] {
    // The first flatMap removes nil elements and the second flattens the array
    return [left?.allData(), [data], right?.allData()].flatMap { $0 }.flatMap { $0 }
}


问:
Better way to structure/new keyword
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

```<code>boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();
</code>```

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

```<code>boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();
</code>```

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

答:
You seem concerned that evaluating condition 2 requires some setup, and you don't know where to put it.  Refactor that into a separate boolean method and then use that the way almost everybody here has described.  For example:

```<code>if (checkCondition1() && checkCondition2(someInput) && checkCondition3()) {
    doSomething();
}
</code>```

and..

```<code>private boolean checkCondition2(Object someInput) {
    //setup condition 2
    return condition2;
}
</code>```

Title: Better way to structure/new keyword

Body:
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

Body:
You seem concerned that evaluating condition 2 requires some setup, and you don't know where to put it.  Refactor that into a separate boolean method and then use that the way almost everybody here has described.  For example:

if (checkCondition1() && checkCondition2(someInput) && checkCondition3()) {
    doSomething();
}

and..

private boolean checkCondition2(Object someInput) {
    //setup condition 2
    return condition2;
}


问:
UITableview Add Padding to custom section header imageview
I am trying to add padding to this custom header view (an image).

The table is static content cells and I am only adding an image to the first section.

I tried to follow this link but was unsuccessful.

I am trying to add some top and bottom padding in the header view.

I tried this to no luck:

```<code>override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 0 {
        var header = tableView.tableHeaderView
        let image = UIImage(named: "Placeholder") // is 121x121
        let imageView = UIImageView(frame: CGRect(x: 0, y: 20, width: tableView.frame.width, height: tableView.sectionHeaderHeight))
        imageView.image = image
        imageView.contentMode = .scaleAspectFit
        header = imageView
        return header
    }
    return nil
}
</code>```

I am also defining the header height in the delegate:

```<code>override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if section == 0 {
        return 125.0
    }
    return 44.0
}
</code>```

The result is the same with no padding.

Any help would be appreciated

I have also tried to add the imageView to the header subview which results in the whole image disappearing.

答:
Instead of returning a UIImageView as a header, add it as a subview to a UIView, and create the padding there.

Your problem is that, even if you set the frame for the header, the UITableView will resizes it to fit its width, and the height that you set as 125. Therefore, you have to contain it in a UIView that will fill the table's header, and contain the UIImageView that you wish to give it padding.

Edit:
Try this

```<code>override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 0 {
        let header = UIView()
        header.backgroundColor = UIColor.clear
        let image = UIImage(named: "Placeholder") // is 121x121
        let imageView = UIImageView(frame: CGRect(x: 0, y: 20, width: tableView.frame.width, height: tableView.sectionHeaderHeight))
        imageView.image = image
        imageView.contentMode = .scaleAspectFit
        header.addSubview(imageView)
        return header
    }
    return nil
}
</code>```

Body:
I am trying to add padding to this custom header view (an image).

The table is static content cells and I am only adding an image to the first section.

I tried to follow this link but was unsuccessful.

I am trying to add some top and bottom padding in the header view.

I tried this to no luck:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 0 {
        var header = tableView.tableHeaderView
        let image = UIImage(named: "Placeholder") // is 121x121
        let imageView = UIImageView(frame: CGRect(x: 0, y: 20, width: tableView.frame.width, height: tableView.sectionHeaderHeight))
        imageView.image = image
        imageView.contentMode = .scaleAspectFit
        header = imageView
        return header
    }
    return nil
}

I am also defining the header height in the delegate:

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if section == 0 {
        return 125.0
    }
    return 44.0
}

The result is the same with no padding.

Any help would be appreciated

I have also tried to add the imageView to the header subview which results in the whole image disappearing.

Body:
Instead of returning a UIImageView as a header, add it as a subview to a UIView, and create the padding there.

Your problem is that, even if you set the frame for the header, the UITableView will resizes it to fit its width, and the height that you set as 125. Therefore, you have to contain it in a UIView that will fill the table's header, and contain the UIImageView that you wish to give it padding.

Edit:
Try this

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 0 {
        let header = UIView()
        header.backgroundColor = UIColor.clear
        let image = UIImage(named: "Placeholder") // is 121x121
        let imageView = UIImageView(frame: CGRect(x: 0, y: 20, width: tableView.frame.width, height: tableView.sectionHeaderHeight))
        imageView.image = image
        imageView.contentMode = .scaleAspectFit
        header.addSubview(imageView)
        return header
    }
    return nil
}


问:
Checking correspondences between cities and postcodes in R
I have a database with addresses (df) and a database of all the existing postcodes in France (cp). I am trying to check if a postcode/city couple in df is correct according to the postcode database.

The main issue I'm facing is the many-to-many relationship of the data. Basically, a city can have multiple postcodes and different cities can be in the same postcode area. For example, these cities are causing a problem :

```<code>        cp$city      cp$postcode
AIX EN PROVENCE            13080
AIX EN PROVENCE            13090
AIX EN PROVENCE            13100
AIX EN PROVENCE            13290
AIX EN PROVENCE            13540
BEAURECUEIL                13100
ST MARC JAUMEGARDE         13100
LE THOLONET                13100
</code>```

As you can see, Aix en Provence has five different postcodes and 13100 covers four different cities.

I have been trying the following code to see whether a couple is correct or not :

```<code>df$city == cp$city[match(df$postcode, cp$postcode)]
</code>```

But it's returning that the couple 13100 LE THOLONET is false. I'm pretty sure this piece of code would be fine if each city had a single code, and each code matched a single city. What can I do to adjust it to the many-to-many cardinality?

答:
You can try something like this maybe:</p>

```<code>cp = data.frame(city=c(rep("AIX EN PROVENCE",5),"BEAURECUEIL","ST MARC JAUMEGARDE","LE THOLONET"),postcode=c(13080,13090,13100,13290,13540,13100,13100,13100))
df = data.frame(city=c(rep("AIX EN PROVENCE",4),"BEAURECUEIL","LE THOLONET","PARIS","MARSEILLE"),postcode=c(13080,13090,13100,13540,13100,13100,75014,13001))

df$correct<-paste0(df$city,df$postcode) %in% paste0(cp$city,cp$postcode)

>df
             city postcode correct
1 AIX EN PROVENCE    13080    TRUE
2 AIX EN PROVENCE    13090    TRUE
3 AIX EN PROVENCE    13100    TRUE
4 AIX EN PROVENCE    13540    TRUE
5     BEAURECUEIL    13100    TRUE
6     LE THOLONET    13100    TRUE
7           PARIS    75014   FALSE
8       MARSEILLE    13001   FALSE
</code>```

Body:
I have a database with addresses (df) and a database of all the existing postcodes in France (cp). I am trying to check if a postcode/city couple in df is correct according to the postcode database.

The main issue I'm facing is the many-to-many relationship of the data. Basically, a city can have multiple postcodes and different cities can be in the same postcode area. For example, these cities are causing a problem :

        cp$city      cp$postcode
AIX EN PROVENCE            13080
AIX EN PROVENCE            13090
AIX EN PROVENCE            13100
AIX EN PROVENCE            13290
AIX EN PROVENCE            13540
BEAURECUEIL                13100
ST MARC JAUMEGARDE         13100
LE THOLONET                13100

As you can see, Aix en Provence has five different postcodes and 13100 covers four different cities.

I have been trying the following code to see whether a couple is correct or not :

df$city == cp$city[match(df$postcode, cp$postcode)]

But it's returning that the couple 13100 LE THOLONET is false. I'm pretty sure this piece of code would be fine if each city had a single code, and each code matched a single city. What can I do to adjust it to the many-to-many cardinality?

Body:
You can try something like this maybe:

cp = data.frame(city=c(rep("AIX EN PROVENCE",5),"BEAURECUEIL","ST MARC JAUMEGARDE","LE THOLONET"),postcode=c(13080,13090,13100,13290,13540,13100,13100,13100))
df = data.frame(city=c(rep("AIX EN PROVENCE",4),"BEAURECUEIL","LE THOLONET","PARIS","MARSEILLE"),postcode=c(13080,13090,13100,13540,13100,13100,75014,13001))

df$correct<-paste0(df$city,df$postcode) %in% paste0(cp$city,cp$postcode)

>df
             city postcode correct
1 AIX EN PROVENCE    13080    TRUE
2 AIX EN PROVENCE    13090    TRUE
3 AIX EN PROVENCE    13100    TRUE
4 AIX EN PROVENCE    13540    TRUE
5     BEAURECUEIL    13100    TRUE
6     LE THOLONET    13100    TRUE
7           PARIS    75014   FALSE
8       MARSEILLE    13001   FALSE


问:
Rescue Phoenix.MissingParamError and return json for user
I have the following action in one of controllers in my Phoenix app:

```<code>      plug :scrub_params, "account"
      plug :scrub_params, "studio"

      def create(conn, %{"account" => account_params, "studio" => studio_params}) do
      end
</code>```

When somebody do not send proper params app is returning Phoenix.MissingParamError error. How can I rescue it and return nice message to user in json?

答:
You could create another function head to handle that case. Something like this, maybe</p>

```<code>def create(conn, %{"account" => account_params, "studio" => studio_params}) do
  # handle request
end

def create(conn, params) do
  # handle missing param
end
</code>```

Body:
I have the following action in one of controllers in my Phoenix app:

      plug :scrub_params, "account"
      plug :scrub_params, "studio"

      def create(conn, %{"account" => account_params, "studio" => studio_params}) do
      end

When somebody do not send proper params app is returning Phoenix.MissingParamError error. How can I rescue it and return nice message to user in json?

Body:
You could create another function head to handle that case. Something like this, maybe

def create(conn, %{"account" => account_params, "studio" => studio_params}) do
  # handle request
end

def create(conn, params) do
  # handle missing param
end


问:
Bluemix: cf push using DEA instead of DIEGO architecture
When deploying an application into dedicated Bluemix it uses DEA architecture by default. How can I force it to use DIEGO architecture instead?</p>

答:
I built a bash exec to do this, which will use your existing manifest.yml file and pack all of this into a single request. The contents of the bash exec follow:

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

filename="manifest.yml"
if [ -e $filename ];
then
  echo "using manifest.yml file in this directory"
else
  echo "no manifest.yml file found. exiting"
  exit -2
fi
shopt -s nocasematch
string='name:'
targetName=""
echo "Retrieving name from manifest file"
while read -r line
do
    name="$line"
    variable=${name%%:*}
    if [[ $variable == *"name"* ]]
    then
      inBound=${name#*:}
      targetName="$(echo -e "${inBound}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
    fi
done < "$filename"
if [ "$targetName" == "" ];
then
  echo "Could not find name of application in manifest.yml file. Cancelling build."
  echo "application name is identified by the 'name: ' term in the manifest.yml file"
  exit -1
else
  echo "starting cf push for $targetName"

  cf push --no-start

  echo "cf enable-diego $targetName"
  cf enable-diego $targetName

  echo "cf start $targetName"
  cf start $targetName

  exit 0
fi
</code>```

Just put this code into your editor as a new file and then make the file executable. I keep a copy of this exec in each of my repos in the root directory. After doing a copy-paste and executing this exec, you may get the following error:

```<code>/bin/bash^M: bad interpreter: No such file or directory
</code>```

If you do, just run the dos2unix command and it will 'fix up' the line endings to match your os.

Body:
I built a bash exec to do this, which will use your existing manifest.yml file and pack all of this into a single request. The contents of the bash exec follow:

#!/bin/bash

filename="manifest.yml"
if [ -e $filename ];
then
  echo "using manifest.yml file in this directory"
else
  echo "no manifest.yml file found. exiting"
  exit -2
fi
shopt -s nocasematch
string='name:'
targetName=""
echo "Retrieving name from manifest file"
while read -r line
do
    name="$line"
    variable=${name%%:*}
    if [[ $variable == *"name"* ]]
    then
      inBound=${name#*:}
      targetName="$(echo -e "${inBound}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
    fi
done < "$filename"
if [ "$targetName" == "" ];
then
  echo "Could not find name of application in manifest.yml file. Cancelling build."
  echo "application name is identified by the 'name: ' term in the manifest.yml file"
  exit -1
else
  echo "starting cf push for $targetName"

  cf push --no-start

  echo "cf enable-diego $targetName"
  cf enable-diego $targetName

  echo "cf start $targetName"
  cf start $targetName

  exit 0
fi

Just put this code into your editor as a new file and then make the file executable. I keep a copy of this exec in each of my repos in the root directory. After doing a copy-paste and executing this exec, you may get the following error:

/bin/bash^M: bad interpreter: No such file or directory

If you do, just run the dos2unix command and it will 'fix up' the line endings to match your os.


问:
Add PayPal payment method Ionic
I'm trying to implement PayPal payment method on my APP made with Ionic 2/3, I allready installed

```<code>$ ionic cordova plugin add com.paypal.cordova.mobilesdk
$ npm install --save @ionic-native/paypal
</code>```

but now how can I create the event button, I mean I need when I press a button it calls the PayPal API giving them the product and price I guess and then make the payment.

I've read the Paypal Ionic documentation but when it puts Usage I don't know where I have to put this code.

Anyone can guide me how to implement it? Or at least a guideance?

答:
I don't have a chance to test this myself, but you could have a button that invokes initiatePaypal() which would look like this:

import { Injectable } from '@angular/core';
//import { Paypal, PaypalPayments } from 'ionic-native';

import {PayPal, PayPalPayment} from 'ionic-native';
//import {PayPal} from 'ionic-native';

@Injectable()
export class Payments {

paymentdata : any;
paymentdetails: any;

constructor() {

}

initiatePaypal(){
PayPal.init({
        "PayPalEnvironmentProduction": "YOUR_PRODUCTION_CLIENT_ID",
        "PayPalEnvironmentSandbox": "AFcWxV21C7fd0v3bYYYRCpSSRl31ACxTIGBF1mQyNN7DjU1eCzpAZer8"
        })
    .then(onSuccess => {
        console.log("init success")
    })
    .catch(onError => {
        console.log("init failed", Error)
    });
}

initiatePayment(){

    this.paymentdata = new PayPalPayment("10.00","SGD", "MMS tickets", "MMS sale");

    PayPal.renderSinglePaymentUI(this.paymentdata)
    .then(onSuccess => {
         console.log('OnSuccess Render: ' + JSON.stringify(onSuccess));
         alert('OnSuccess Render: ' + JSON.stringify(onSuccess));
       })
    .catch(onError=> {
       console.log('onError Render: ' + JSON.stringify(onError));
       alert('onError Render: ' + JSON.stringify(onError));
         });
}

}
```

If all else fails, try to follow along this vanilla js example usage of the plugin. Taken from MyCordovaShop.

Title: Add PayPal payment method Ionic

Body:
I'm trying to implement PayPal payment method on my APP made with Ionic 2/3, I allready installed

$ ionic cordova plugin add com.paypal.cordova.mobilesdk
$ npm install --save @ionic-native/paypal

but now how can I create the event button, I mean I need when I press a button it calls the PayPal API giving them the product and price I guess and then make the payment.

I've read the Paypal Ionic documentation but when it puts Usage I don't know where I have to put this code.

Anyone can guide me how to implement it? Or at least a guideance?

Body:
I don't have a chance to test this myself, but you could have a button that invokes initiatePaypal() which would look like this:

import { Injectable } from '@angular/core';
//import { Paypal, PaypalPayments } from 'ionic-native';

import {PayPal, PayPalPayment} from 'ionic-native';
//import {PayPal} from 'ionic-native';

@Injectable()
export class Payments {

paymentdata : any;
paymentdetails: any;

constructor() {

}

initiatePaypal(){
PayPal.init({
        "PayPalEnvironmentProduction": "YOUR_PRODUCTION_CLIENT_ID",
        "PayPalEnvironmentSandbox": "AFcWxV21C7fd0v3bYYYRCpSSRl31ACxTIGBF1mQyNN7DjU1eCzpAZer8"
        })
    .then(onSuccess => {
        console.log("init success")
    })
    .catch(onError => {
        console.log("init failed", Error)
    });
}

initiatePayment(){

    this.paymentdata = new PayPalPayment("10.00","SGD", "MMS tickets", "MMS sale");

    PayPal.renderSinglePaymentUI(this.paymentdata)
    .then(onSuccess => {
         console.log('OnSuccess Render: ' + JSON.stringify(onSuccess));
         alert('OnSuccess Render: ' + JSON.stringify(onSuccess));
       })
    .catch(onError=> {
       console.log('onError Render: ' + JSON.stringify(onError));
       alert('onError Render: ' + JSON.stringify(onError));
         });
}

}

If all else fails, try to follow along this vanilla js example usage of the plugin. Taken from MyCordovaShop.


问:
django: Why do we use a nested meta class inside modelSerializer?
I am new to python as well as to django and learning about serializers. I observed that While defining a serializer class it needs a nested meta class inside it. I am not good with this meta class concept, so i googled about it and found that metaclass is a class whose instances are classes. Even after reading that i am confused. Is the outer serializer class an instance of the inner meta class here? What is the need of using this meta class here?</p>

答:
Python's metaclasses and Django's Meta classes are different concepts.

What you found on google is talking about Python's metaclasses, a construct that the Django framework uses a lot, but not in its user-facing code. This blog post goes into explaining how Django uses metaclasses in the framework's code.

Django's Meta classes on the other hand, it's an internal class structure used in some of the framework frontmost elements: Models, Forms, Serializers, ModelAdmins, etc. Those classes describe the configuration of a certain element that are read on runtime, or migration-time, but are not strictly saved on the database, because they're not of the database concern. For example, the framework reads the Meta configuration of a model when it needs to know what is the preferred order of a QuerySet of such model if order is not specified. Forms will read what fields it must validate when it calls is_valid. Et cetera.


问:
I am searching extensible mail plugin for Hudson
I want to send reports about every Hudson job build ito mail. Mail address must be get by certain rule, for example: committer - vpupkin, his mail - vasya.pupkin@co.com. I have script which makes this transformation. Is there way to do this?</p>

答:
http://wiki.hudson-ci.org/display/HUDSON/RegEx+Email+Plugin
made for this plugin shell script, which generates its config </p>