问:
calling variables for rule individually and adding an independent environment for a specific rule
I need to run a snakemake rule in the cluster, therefore for some rules, I need some tools and library needed to e loaded whereas, these tools are independent/ exclusive to other rules. I this case how can I specify these in my snakemake rule. For example, for rule score I need to module load r/3.5.1 and export R_lib =/user/tools/software currently, I am running these lines separately in the command line before running snakemake. But it would be great if there is a way to do it within the rule as env.

Question,

I have a rule as following,

```<code>rule score:
    input:
        count=os.path.join(config['general']['paths']['outdir'], 'count_expression', '{sample}.tsv'),
        libsize=os.path.join(config['general']['paths']['outdir'], 'count_expression', '{sample}.size_tsv')
    params:
        result_dir=os.path.join(config['general']['paths']['outdir'], 'score'),
        cancertype=config['general']['paths']['cancertype'],
        sample_id=expand('{sample}',sample=samples['sample'].unique())
    output:
        files=os.path.join(config['general']['paths']['outdir'], 'score', '{sample}_bg_scores.tsv', '{sample}_tp_scores.tsv')
    shell:
        'mkdir -p {params.result_dir};Rscript {config[general][paths][tool]} {params.result_dir} {params.cancertype} {params.sample_id} {input.count} {input.libsize}'
</code>```

My actual behavior for the above code snippet is:

```<code>shell:
        mkdir -p /cluster/user/snakemake_test/results_april30/score;Rscript /cluster/home/user/Projects/R_scripts/scoretool.R /cluster/user/snakemake_test/results_april30/score DMC GNMS4 MRT5T /cluster/projects/test/results/exp/MRT5T.tsv /cluster/projects/test/results/Exp/MRT5T.size.tsv
</code>```

Whereas, the expected behavior is:

```<code>shell:
        mkdir -p /cluster/user/snakemake_test/results_april30/score;Rscript /cluster/home/user/Projects/R_scripts/scoretool.R /cluster/user/snakemake_test/results_april30/score DMC MRT5T /cluster/projects/test/results/exp/MRT5T.tsv /cluster/projects/test/results/Exp/MRT5T.size.tsv
</code>```

and for the second sample,

```<code>shell:
        mkdir -p /cluster/user/snakemake_test/results_april30/score;Rscript /cluster/home/user/Projects/R_scripts/scoretool.R /cluster/user/snakemake_test/results_april30/score DMC GNMS4 /cluster/projects/test/results/exp/GNMS4.tsv /cluster/projects/test/results/Exp/GNMS4.ize.tsv
</code>```

I need the variable  sample_d ['GNMS4', 'MRT5T'] should be taken separately, not together in one shell command line.

答:
onstart would work I think. Note that dryruns don't trigger this handler, which is acceptable in your scenario.

```<code>onstart:
   shell("load tools")
</code>```

Simple bash for loop should solve the problem. However, if you want each sample to be run as a separate rule, you would have to use sample name as part of output filename.

```<code>shell:
   '''
   for sample in {param.sample_id}
   do
      your command $sample
   done
   '''
</code>```

Body:
I need to run a snakemake rule in the cluster, therefore for some rules, I need some tools and library needed to e loaded whereas, these tools are independent/ exclusive to other rules. I this case how can I specify these in my snakemake rule. For example, for rule score I need to module load r/3.5.1 and export R_lib =/user/tools/software currently, I am running these lines separately in the command line before running snakemake. But it would be great if there is a way to do it within the rule as env.

Question,

I have a rule as following,

rule score:
    input:
        count=os.path.join(config['general']['paths']['outdir'], 'count_expression', '{sample}.tsv'),
        libsize=os.path.join(config['general']['paths']['outdir'], 'count_expression', '{sample}.size_tsv')
    params:
        result_dir=os.path.join(config['general']['paths']['outdir'], 'score'),
        cancertype=config['general']['paths']['cancertype'],
        sample_id=expand('{sample}',sample=samples['sample'].unique())
    output:
        files=os.path.join(config['general']['paths']['outdir'], 'score', '{sample}_bg_scores.tsv', '{sample}_tp_scores.tsv')
    shell:
        'mkdir -p {params.result_dir};Rscript {config[general][paths][tool]} {params.result_dir} {params.cancertype} {params.sample_id} {input.count} {input.libsize}'

My actual behavior for the above code snippet is:

shell:
        mkdir -p /cluster/user/snakemake_test/results_april30/score;Rscript /cluster/home/user/Projects/R_scripts/scoretool.R /cluster/user/snakemake_test/results_april30/score DMC GNMS4 MRT5T /cluster/projects/test/results/exp/MRT5T.tsv /cluster/projects/test/results/Exp/MRT5T.size.tsv

Whereas, the expected behavior is:

shell:
        mkdir -p /cluster/user/snakemake_test/results_april30/score;Rscript /cluster/home/user/Projects/R_scripts/scoretool.R /cluster/user/snakemake_test/results_april30/score DMC MRT5T /cluster/projects/test/results/exp/MRT5T.tsv /cluster/projects/test/results/Exp/MRT5T.size.tsv

and for the second sample,

shell:
        mkdir -p /cluster/user/snakemake_test/results_april30/score;Rscript /cluster/home/user/Projects/R_scripts/scoretool.R /cluster/user/snakemake_test/results_april30/score DMC GNMS4 /cluster/projects/test/results/exp/GNMS4.tsv /cluster/projects/test/results/Exp/GNMS4.ize.tsv

I need the variable  sample_d ['GNMS4', 'MRT5T'] should be taken separately, not together in one shell command line.

Body:
onstart would work I think. Note that dryruns don't trigger this handler, which is acceptable in your scenario.

onstart:
   shell("load tools")

Simple bash for loop should solve the problem. However, if you want each sample to be run as a separate rule, you would have to use sample name as part of output filename.

shell:
   '''
   for sample in {param.sample_id}
   do
      your command $sample
   done
   '''


来源: stackexchange

问:
How to create Service specific services in Angular
I have two services S1 and S2 in Angular

```<code>export class S1 {
    constructor(private s2: S2) {
    // ...
    }
}
</code>```

I want to create instance of S2 that is only scoped for S1 (the same as we do for Components)

Any suggestion on how to do that?

答:
I am not pretty sure that i get what you want but let me break it down as following:

It's not possible to inject a service somewhere without provide it somewhere

You can inject a service into another service as following:

```<code>@Injectable()

export class First {
}

@Injectable()

export class Second {

    constructor(@Inject(First) first:First){

    }
}
</code>```

Note that you have to provide your services somewhere and as default you might provide them in your app root

ContentLicense: CC BY-SA 4.0

Body:
I have two services S1 and S2 in Angular

export class S1 {
    constructor(private s2: S2) {
    // ...
    }
}

I want to create instance of S2 that is only scoped for S1 (the same as we do for Components)

Any suggestion on how to do that?

Body:
I am not pretty sure that i get what you want but let me break it down as following:

It's not possible to inject a service somewhere without provide it somewhere

You can inject a service into another service as following:

@Injectable()

export class First {
}

@Injectable()

export class Second {

    constructor(@Inject(First) first:First){

    }
}

Note that you have to provide your services somewhere and as default you might provide them in your app root


问:
Setting proxy on .Rprofile on OSX fails
In order to access CRAN packages from within R on OSX I've been using

```<code>Sys.setenv(http_proxy="http://blah_blah:1234/")
</code>```

as the first command in the R GUI for a while, but would really like to set this proxy automatically.

I've tried unsuccessfully to get the same command to work in a .Rprofile file in ~/

I've also tried http_proxy="http://blah_blah:1234/", but this fails too.

The error I get when I try to view packages is a drop-down window that says:

```<code>Fetching Package List Failed
Please consult R Console output for details
</code>```

The GUI then gives:

```<code>Error in read.dcf(file = tmpf) : Line starting '<head> ...' is malformed!
</code>```

The .Rprofile file itself seems to be loading (checked using cat("my profile works\n"))

答:
Couldn't you just use .First ?

http://cran.r-project.org/doc/manuals/R-intro.html#Customizing-the-environment

ContentLicense: CC BY-SA 3.0

Title: Setting proxy on .Rprofile on OSX fails

Body:
In order to access CRAN packages from within R on OSX I've been using

Sys.setenv(http_proxy="http://blah_blah:1234/")

as the first command in the R GUI for a while, but would really like to set this proxy automatically.

I've tried unsuccessfully to get the same command to work in a .Rprofile file in ~/

I've also tried http_proxy="http://blah_blah:1234/", but this fails too.

The error I get when I try to view packages is a drop-down window that says:

Fetching Package List Failed
Please consult R Console output for details

The GUI then gives:

Error in read.dcf(file = tmpf) : Line starting ' ...' is malformed!

The .Rprofile file itself seems to be loading (checked using cat("my profile works\n"))


问:
How to open ECW file with GDAL in OpenCV 3.0
As you know, GDAL is added to OpenCV version 3. I have a satellite ecw image and want to read and show it. I already try to use OpenCV sample named : gdal-image.cpp. it has a line for reading input image: </p>

```<code>  cv::Mat image = cv::imread(argv[1], cv::IMREAD_LOAD_GDAL | cv::IMREAD_COLOR );
</code>```

<p>my problem : I set my ecw image as argv[1] but it doesnt work.
 should I convert my image before?
 any way to read ecw using GDAL?  </p>

答:
For read ecw image, i suggest you use GDAL, you can download GDAL binary prebuild and ECW extension from here https://www.gisinternals.com/release.php.

For read the first band of image you can use this code:

```<code>GDALDataset* dataset = (GDALDataset*) GDALOpenEx("image.ecw", GDAL_OF_RASTER, NULL, NULL, NULL);
GDALRasterBand* band = dataset->GetRasterBand(1);

cv::Rect roi(x, y, w, h);

cv::Mat mat;
mat.create(roi.size(),CV_32F);
band->RasterIO( GF_Read, roi.x, roi.y, roi.width, roi.height, mat.data,
                roi.width, roi.height, GDT_Float32, 0, 0);
</code>```

You just have to be sure that OpenCV data type match the GDAL datatype and that ROI dimensions are ok for the raster size.
For more info it is good: enter link description here

Body:
As you know, GDAL is added to OpenCV version 3. I have a satellite ecw image and want to read and show it. I already try to use OpenCV sample named : gdal-image.cpp. it has a line for reading input image:

  cv::Mat image = cv::imread(argv[1], cv::IMREAD_LOAD_GDAL | cv::IMREAD_COLOR );

my problem : I set my ecw image as argv[1] but it doesnt work.
 should I convert my image before?
 any way to read ecw using GDAL?

Body:
For read ecw image, i suggest you use GDAL, you can download GDAL binary prebuild and ECW extension from here https://www.gisinternals.com/release.php.

For read the first band of image you can use this code:

GDALDataset* dataset = (GDALDataset*) GDALOpenEx("image.ecw", GDAL_OF_RASTER, NULL, NULL, NULL);
GDALRasterBand* band = dataset->GetRasterBand(1);

cv::Rect roi(x, y, w, h);

cv::Mat mat;
mat.create(roi.size(),CV_32F);
band->RasterIO( GF_Read, roi.x, roi.y, roi.width, roi.height, mat.data,
                roi.width, roi.height, GDT_Float32, 0, 0);

You just have to be sure that OpenCV data type match the GDAL datatype and that ROI dimensions are ok for the raster size.
For more info it is good: enter link description here


问:
Edit Sonata User data
I'm trying to override Sonata User Admin class, on my bundle. For the moment, I just override the configureListFields method:
namespace App\Admin;

```<code>use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;

use Sonata\UserBundle\Admin\Model\UserAdmin as BaseUserAdmin;

class UserAdmin extends BaseUserAdmin
{

    /**
     * @param ListMapper $listMapper
     */
    protected function configureListFields(ListMapper $listMapper):void
    {
        $listMapper
            ->addIdentifier('username')
            ->add('email')
            ->add('groups')
            ->add('enabled', null, ['editable' => true])
            ->add('accountType')
            ->add('createdAt')
        ;

        if ($this->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
            $listMapper
                ->add('impersonating', 'string', ['template' => '@SonataUser/Admin/Field/impersonating.html.twig'])
            ;
        }
    }
}
</code>```

I refresh my page and I got the list of users without problem. But when I click into a user to edit it, I have this error: Call to a member function getClass() on null on these lines:

```<code>$now = new \DateTime();

        $genderOptions = [
            'choices' => \call_user_func([$this->getUserManager()->getClass(), 'getGenderList']),
            'required' => true,
            'translation_domain' => $this->getTranslationDomain(),
        ];

        // NEXT_MAJOR: Remove this when dropping support for SF 2.8
        if (method_exists(FormTypeInterface::class, 'setDefaultOptions')) {
            $genderOptions['choices_as_values'] = true;
        }
</code>```

Sonata_admin.yaml file:

```<code>sonata_admin:
    title: 'Staff Admin Panel'
    templates:
        dashboard: '@SonataAdmin/Core/dashboard.html.twig'
    security:
        handler: sonata.admin.security.handler.role
        role_admin: ROLE_ADMIN
        role_super_admin: ROLE_SUPER_ADMIN
        # information:
        #     GUEST: [VIEW, LIST]
        #     STAFF: [EDIT, LIST, CREATE]
        #     EDITOR: [OPERATOR, EXPORT]
        #     ADMIN: [MASTER]

        # admin_permissions: [CREATE, LIST, DELETE, UNDELETE, EXPORT, OPERATOR, MASTER]
        # object_permissions: [VIEW, EDIT, DELETE, UNDELETE, OPERATOR, MASTER, OWNER]

    dashboard:
        blocks:
            - { type: sonata.admin.block.admin_list, position: left }
        groups:
            content:
                label: Contenu
                icon: '<i class="fa fa-file-text-o"></i>'
                items:
                    - app.admin.specialty
                    - app.admin.cities
                    - app.admin.colleges
                    - app.admin.building

            sonata.admin.group.media:
                label: Médiathèque
                icon: '<i class="fa fa-camera-retro"></i>'
                items:
                    - sonata.media.admin.media

            settings:
                label: Paramètres
                icon: '<i class="fa fa-cog"></i>'
                items:
                    - sonata.classification.admin.category
                    - sonata.classification.admin.context
                    - sonata.classification.admin.tag
                    - sonata.classification.admin.collection
                    - app.admin.icon

            sonata.admin.group.administration:
                label: Utilisateur et Groupes
                label_catalogue: SonataAdminBundle
                icon: '<i class="fa fa-users"></i>'
                items:
                    - app.admin.user
                    - sonata.user.admin.group

sonata_block:
    blocks:
        sonata.admin.block.admin_list:
            contexts: [admin]

sonata_user:
    security_acl: true
    manager_type: orm
    class:
        user: App\Application\Sonata\UserBundle\Entity\User
        group: App\Application\Sonata\UserBundle\Entity\Group
</code>```

fos_user.yaml file:

```<code>fos_user:
    db_driver: orm # valid values are 'orm', 'mongodb' and 'couchdb'
    user_class: App\Entity\User #App\Application\Sonata\UserBundle\Entity\User
    firewall_name: main

    registration:
        form:
            type: App\Application\Sonata\UserBundle\Form\RegistrationType

    group:
        group_class: App\Application\Sonata\UserBundle\Entity\Group
        group_manager: sonata.user.orm.group_manager

    service:
        user_manager: sonata.user.orm.user_manager
        mailer: fos_user.mailer.noop

    from_email:
        address: "%env(MAILER_SENDER_ADDRESS)%"
        sender_name: "%env(MAILER_SENDER_NAME)%"
</code>```

答:
If you want to access to your method getGenderList() from configureFormFields() you can do that :

```<code>protected function configureFormFields(FormMapper $formMapper)
{
        $now = new \DateTime();
        $genderOptions = [
            'choices' => $this->getSubject()->getGenderList(), // here
            'required' => true,
            'translation_domain' => $this->getTranslationDomain(),
        ];

        // NEXT_MAJOR: Remove this when dropping support for SF 2.8
        if (method_exists(FormTypeInterface::class, 'setDefaultOptions')) {
            $genderOptions['choices_as_values'] = true;
        }
}
</code>```

See the Symfony docs about it.

Title: Edit Sonata User data

Body:
I'm trying to override Sonata User Admin class, on my bundle. For the moment, I just override the configureListFields method:
namespace App\Admin;

use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;

use Sonata\UserBundle\Admin\Model\UserAdmin as BaseUserAdmin;

class UserAdmin extends BaseUserAdmin
{

    /**
     * @param ListMapper $listMapper
     */
    protected function configureListFields(ListMapper $listMapper):void
    {
        $listMapper
            ->addIdentifier('username')
            ->add('email')
            ->add('groups')
            ->add('enabled', null, ['editable' => true])
            ->add('accountType')
            ->add('createdAt')
        ;

        if ($this->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
            $listMapper
                ->add('impersonating', 'string', ['template' => '@SonataUser/Admin/Field/impersonating.html.twig'])
            ;
        }
    }
}

I refresh my page and I got the list of users without problem. But when I click into a user to edit it, I have this error: Call to a member function getClass() on null on these lines:

$now = new \DateTime();

        $genderOptions = [
            'choices' => \call_user_func([$this->getUserManager()->getClass(), 'getGenderList']),
            'required' => true,
            'translation_domain' => $this->getTranslationDomain(),
        ];

        // NEXT_MAJOR: Remove this when dropping support for SF 2.8
        if (method_exists(FormTypeInterface::class, 'setDefaultOptions')) {
            $genderOptions['choices_as_values'] = true;
        }

Sonata_admin.yaml file:

sonata_admin:
    title: 'Staff Admin Panel'
    templates:
        dashboard: '@SonataAdmin/Core/dashboard.html.twig'
    security:
        handler: sonata.admin.security.handler.role
        role_admin: ROLE_ADMIN
        role_super_admin: ROLE_SUPER_ADMIN
        # information:
        #     GUEST: [VIEW, LIST]
        #     STAFF: [EDIT, LIST, CREATE]
        #     EDITOR: [OPERATOR, EXPORT]
        #     ADMIN: [MASTER]

        # admin_permissions: [CREATE, LIST, DELETE, UNDELETE, EXPORT, OPERATOR, MASTER]
        # object_permissions: [VIEW, EDIT, DELETE, UNDELETE, OPERATOR, MASTER, OWNER]

    dashboard:
        blocks:
            - { type: sonata.admin.block.admin_list, position: left }
        groups:
            content:
                label: Contenu
                icon: ''
                items:
                    - app.admin.specialty
                    - app.admin.cities
                    - app.admin.colleges
                    - app.admin.building

            sonata.admin.group.media:
                label: Médiathèque
                icon: ''
                items:
                    - sonata.media.admin.media

            settings:
                label: Paramètres
                icon: ''
                items:
                    - sonata.classification.admin.category
                    - sonata.classification.admin.context
                    - sonata.classification.admin.tag
                    - sonata.classification.admin.collection
                    - app.admin.icon

            sonata.admin.group.administration:
                label: Utilisateur et Groupes
                label_catalogue: SonataAdminBundle
                icon: ''
                items:
                    - app.admin.user
                    - sonata.user.admin.group

sonata_block:
    blocks:
        sonata.admin.block.admin_list:
            contexts: [admin]

sonata_user:
    security_acl: true
    manager_type: orm
    class:
        user: App\Application\Sonata\UserBundle\Entity\User
        group: App\Application\Sonata\UserBundle\Entity\Group

fos_user.yaml file:

fos_user:
    db_driver: orm # valid values are 'orm', 'mongodb' and 'couchdb'
    user_class: App\Entity\User #App\Application\Sonata\UserBundle\Entity\User
    firewall_name: main

    registration:
        form:
            type: App\Application\Sonata\UserBundle\Form\RegistrationType

    group:
        group_class: App\Application\Sonata\UserBundle\Entity\Group
        group_manager: sonata.user.orm.group_manager

    service:
        user_manager: sonata.user.orm.user_manager
        mailer: fos_user.mailer.noop

    from_email:
        address: "%env(MAILER_SENDER_ADDRESS)%"
        sender_name: "%env(MAILER_SENDER_NAME)%"

Body:
If you want to access to your method getGenderList() from configureFormFields() you can do that :

protected function configureFormFields(FormMapper $formMapper)
{
        $now = new \DateTime();
        $genderOptions = [
            'choices' => $this->getSubject()->getGenderList(), // here
            'required' => true,
            'translation_domain' => $this->getTranslationDomain(),
        ];

        // NEXT_MAJOR: Remove this when dropping support for SF 2.8
        if (method_exists(FormTypeInterface::class, 'setDefaultOptions')) {
            $genderOptions['choices_as_values'] = true;
        }
}

See the Symfony docs about it.


问:
How do I fetch all Git branches?
I cloned a Git repository containing many branches. However, git branch only shows one:

```<code>$ git branch
* master
</code>```

How would I pull all the branches locally so when I do git branch, it shows the following?

```<code>$ git branch
* master
* staging
* etc...
</code>```

答:
For Visual Studio Users, On Package Manager console:</p>
```<code>git branch | %{ git fetch upstream; git merge upstream/master}
</code>```

Title: How do I fetch all Git branches?

Body:
I cloned a Git repository containing many branches. However, git branch only shows one:

$ git branch
* master

How would I pull all the branches locally so when I do git branch, it shows the following?

$ git branch
* master
* staging
* etc...

Body:
For Visual Studio Users, On Package Manager console:

git branch | %{ git fetch upstream; git merge upstream/master}


问:
Can't get newest why3 version from opam
I am using Linux Slackware 14.2, opam version 1.2.2, ocaml 4.03.0 and wanted to install why3 module. As far as I can see in the Internet, the last version of why3 package is 1.2.0.

But even after I ran

```<code>opam update
</code>```

It still suggests my to install why3 1.0.0.

What should I do to update the packages list?

How can I install why3 module system wide as root? Is it safe enough?

答:
Your opam and ocaml installations are both seriously out of date. The latest version of OCaml is 4.07.1, and the latest version of opam is 2.0.4. Linux distro repositories are unfortunately often not very up to date, and as I understand it, packages published for opam v2 aren't backwards-compatible with opam v1.x.

Try installing the latest opam by following the installation guide. Then, using opam, install a more recent version of OCaml and you should be able to get the latest version of why3.

It's recommended to manage your OCaml installations and associated packages with opam instead of installing them globally, since that can potentially cause an unruly mess of broken dependencies over time.

Title: Can't get newest why3 version from opam

Body:
I am using Linux Slackware 14.2, opam version 1.2.2, ocaml 4.03.0 and wanted to install why3 module. As far as I can see in the Internet, the last version of why3 package is 1.2.0.

But even after I ran

opam update

It still suggests my to install why3 1.0.0.

What should I do to update the packages list?

How can I install why3 module system wide as root? Is it safe enough?


问:
Unable to load UTF-8 JSON data with marshmallow
I'm trying to use marshmallow to verify posted JSON data to my app. I post using Jquery like this:

```<code>var testdata = { "field1": "value1", "field2": "value2" };

$.ajax({
    type: "POST",
    url: "/api/v1/monitors",
    data: JSON.stringify(testdata),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){alert(data);},
    failure: function(errMsg){alert(errMsg);}
});
</code>```

On the server side I have a python app on Google App Engine with a schema like:

```<code>class TestSchema(Schema):
    field1 = fields.Str()
    field2 = fields.Str()
</code>```

And a handler like:

```<code>def post(self):
    schema = TestSchema()
    result = schema.load(self.request.body)
    logging.error(result)
</code>```

In the log I constantly get:

```<code>UnmarshalResult(data={}, errors={u'_schema': [u'Invalid input type.']})
</code>```

But if I replace this line:

```<code>result = schema.load(self.request.body)
</code>```

With this:

```<code>result = schema.load('{ "field1": u"value1", "field2": u"value2" }')
</code>```

It works just fine, but I don't want to post unicode I want to use UTF-8. How can I get it to take the UTF-8 posted data and load it?

答:
There was a missing s!

The load JSON in marshmallow you need to use the .loads() and not the .load() function.

Thank you for all your efforts to help!

Body:
I'm trying to use marshmallow to verify posted JSON data to my app. I post using Jquery like this:

var testdata = { "field1": "value1", "field2": "value2" };

$.ajax({
    type: "POST",
    url: "/api/v1/monitors",
    data: JSON.stringify(testdata),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){alert(data);},
    failure: function(errMsg){alert(errMsg);}
});

On the server side I have a python app on Google App Engine with a schema like:

class TestSchema(Schema):
    field1 = fields.Str()
    field2 = fields.Str()

And a handler like:

def post(self):
    schema = TestSchema()
    result = schema.load(self.request.body)
    logging.error(result)

In the log I constantly get:

UnmarshalResult(data={}, errors={u'_schema': [u'Invalid input type.']})

But if I replace this line:

result = schema.load(self.request.body)

With this:

result = schema.load('{ "field1": u"value1", "field2": u"value2" }')

It works just fine, but I don't want to post unicode I want to use UTF-8. How can I get it to take the UTF-8 posted data and load it?


答:
I want to create instance of S2 that is only scoped for S1 (the same as we do for Components)

Well, that's exactly what you do. You provide S1 and S2 in the scope of a component.

```<code>@Component({
    ...
    viewProviders: [ S1, S2 ]
})
export class MyComponent { ... }
</code>```

This means that S1 and S2 will be unique instances accessible to children of the MyComponent.

It is not possible for have a single instance of S1 that receives a different instance of S2, because you're defining the dependency in the constructor.

Title: How to create Service specific services in Angular

Body:
I want to create instance of S2 that is only scoped for S1 (the same as we do for Components)

Well, that's exactly what you do. You provide S1 and S2 in the scope of a component.

@Component({
    ...
    viewProviders: [ S1, S2 ]
})
export class MyComponent { ... }

This means that S1 and S2 will be unique instances accessible to children of the MyComponent.

It is not possible for have a single instance of S1 that receives a different instance of S2, because you're defining the dependency in the constructor.


问:
How do i make an ExtrudeGeometry face an Object with the Object3D.lookAt() function?
I need to make a 3D Polygon that faces another Object. Is there any good way to do that? I thought of using ExtrudeGeometry but i don't know how to apply the Object3D.lookat() function to it. I would appreciate any help :)

This is the Code i have for now:

```<code>  var position = new THREE.Vector3(0,0,0);

  var polyhedronPts = [];
    polyhedronPts.push(new THREE.Vector2(-100, 600));
    polyhedronPts.push(new THREE.Vector2(300, 600));
    polyhedronPts.push(new THREE.Vector2(600, -100));
    polyhedronPts.push(new THREE.Vector2(200, 100));
    polyhedronPts.push(new THREE.Vector2(400, 200));

    polyhedronShape = new THREE.Shape(polyhedronPts);
    var extrudeSettings = {
      amount: 5
    };
    var geometry = new THREE.ExtrudeGeometry(polyhedronShape, extrudeSettings);

    geometry.lookAt(position);

    var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
    mesh = new THREE.Mesh( geometry, material ) ;

    sceneEl.object3D.add(mesh);
</code>```

The geometry.lookAt(sphereposition); line should make the object face [0,0,0]
but it doesn't. Do you have any idea how to fix this?

答:
.lookAt() is a Object3D function, reference.

This means you need to use it on your mesh object, not your geometry.

To rotate an object towards a targetObject, you can use object.lookAt( targetObject.position ). This will detect the current position of the targetObject and rotate it accordingly.

I've set up an interactive JSFiddle. You can drag the cube and the cone will automatically point towards it.

Body:
I need to make a 3D Polygon that faces another Object. Is there any good way to do that? I thought of using ExtrudeGeometry but i don't know how to apply the Object3D.lookat() function to it. I would appreciate any help :)

This is the Code i have for now:

  var position = new THREE.Vector3(0,0,0);

  var polyhedronPts = [];
    polyhedronPts.push(new THREE.Vector2(-100, 600));
    polyhedronPts.push(new THREE.Vector2(300, 600));
    polyhedronPts.push(new THREE.Vector2(600, -100));
    polyhedronPts.push(new THREE.Vector2(200, 100));
    polyhedronPts.push(new THREE.Vector2(400, 200));

    polyhedronShape = new THREE.Shape(polyhedronPts);
    var extrudeSettings = {
      amount: 5
    };
    var geometry = new THREE.ExtrudeGeometry(polyhedronShape, extrudeSettings);

    geometry.lookAt(position);

    var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
    mesh = new THREE.Mesh( geometry, material ) ;

    sceneEl.object3D.add(mesh);

The geometry.lookAt(sphereposition); line should make the object face [0,0,0]
but it doesn't. Do you have any idea how to fix this?


问:
How to iterate this data model in ListView inside Future Builder?
I'm trying to show user detail with multidimensional json in ListView inside Future builder. I have these json data I got from https://jsonplaceholder.typicode.com/users?id=1. These is the json code:

```<code>[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  }
]
</code>```

I tried to generate model through https://app.quicktype.io/ And I got this data model:

// To parse this JSON data, do
//
//     final user = userFromJson(jsonString);

import 'dart:convert';

List<User> userFromJson(String str) => new List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

String userToJson(List<User> data) => json.encode(new List<dynamic>.from(data.map((x) => x.toJson())));

class User {
    int id;
    String name;
    String username;
    String email;
    Address address;
    String phone;
    String website;
    Company company;

    User({
        this.id,
        this.name,
        this.username,
        this.email,
        this.address,
        this.phone,
        this.website,
        this.company,
    });

    factory User.fromJson(Map<String, dynamic> json) => new User(
        id: json["id"],
        name: json["name"],
        username: json["username"],
        email: json["email"],
        address: Address.fromJson(json["address"]),
        phone: json["phone"],
        website: json["website"],
        company: Company.fromJson(json["company"]),
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "username": username,
        "email": email,
        "address": address.toJson(),
        "phone": phone,
        "website": website,
        "company": company.toJson(),
    };
}

class Address {
    String street;
    String suite;
    String city;
    String zipcode;
    Geo geo;

    Address({
        this.street,
        this.suite,
        this.city,
        this.zipcode,
        this.geo,
    });

    factory Address.fromJson(Map<String, dynamic> json) => new Address(
        street: json["street"],
        suite: json["suite"],
        city: json["city"],
        zipcode: json["zipcode"],
        geo: Geo.fromJson(json["geo"]),
    );

    Map<String, dynamic> toJson() => {
        "street": street,
        "suite": suite,
        "city": city,
        "zipcode": zipcode,
        "geo": geo.toJson(),
    };
}

class Geo {
    String lat;
    String lng;

    Geo({
        this.lat,
        this.lng,
    });

    factory Geo.fromJson(Map<String, dynamic> json) => new Geo(
        lat: json["lat"],
        lng: json["lng"],
    );

    Map<String, dynamic> toJson() => {
        "lat": lat,
        "lng": lng,
    };
}

class Company {
    String name;
    String catchPhrase;
    String bs;

    Company({
        this.name,
        this.catchPhrase,
        this.bs,
    });

    factory Company.fromJson(Map<String, dynamic> json) => new Company(
        name: json["name"],
        catchPhrase: json["catchPhrase"],
        bs: json["bs"],
    );

    Map<String, dynamic> toJson() => {
        "name": name,
        "catchPhrase": catchPhrase,
        "bs": bs,
    };
}
```

I need to show this data in ListView inside Future Builder. How  do I do this? Please somebody help me?

答:
this response its using http dio lib.</p>

```<code>Widget build(BuildContext context) {
  return Scaffold(
      body: SafeArea(
        child: FutureBuilder(
          future: _getData(),
          builder: (_, AsyncSnapshot<User> snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return new Theme(
                data: Theme.of(context).copyWith(accentColor: Colors.blue),
                child: new CircularProgressIndicator(),
              );
            }

            if (!snapshot.hasData) {
              return Center(
                child: Text("No data found"),
              );
            }

            User user = snapshot.data;
            return ListView(
              children: <Widget>[
                ListTile(
                  title: Text(user.name),
                  subtitle: Text(user.email),
                ),
              ],
            );
          },
        ),
      ),
    );
}

 Future<User> _getData() async {
    final Response response =
    await dio.get("https://jsonplaceholder.typicode.com/users?id=1");
    return User.fromJson(response.data[0]);
}
</code>```

Body:
I'm trying to show user detail with multidimensional json in ListView inside Future builder. I have these json data I got from https://jsonplaceholder.typicode.com/users?id=1. These is the json code:

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  }
]

I tried to generate model through https://app.quicktype.io/ And I got this data model:

// To parse this JSON data, do
//
//     final user = userFromJson(jsonString);

import 'dart:convert';

List<User> userFromJson(String str) => new List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

String userToJson(List<User> data) => json.encode(new List<dynamic>.from(data.map((x) => x.toJson())));

class User {
    int id;
    String name;
    String username;
    String email;
    Address address;
    String phone;
    String website;
    Company company;

    User({
        this.id,
        this.name,
        this.username,
        this.email,
        this.address,
        this.phone,
        this.website,
        this.company,
    });

    factory User.fromJson(Map<String, dynamic> json) => new User(
        id: json["id"],
        name: json["name"],
        username: json["username"],
        email: json["email"],
        address: Address.fromJson(json["address"]),
        phone: json["phone"],
        website: json["website"],
        company: Company.fromJson(json["company"]),
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "username": username,
        "email": email,
        "address": address.toJson(),
        "phone": phone,
        "website": website,
        "company": company.toJson(),
    };
}

class Address {
    String street;
    String suite;
    String city;
    String zipcode;
    Geo geo;

    Address({
        this.street,
        this.suite,
        this.city,
        this.zipcode,
        this.geo,
    });

    factory Address.fromJson(Map<String, dynamic> json) => new Address(
        street: json["street"],
        suite: json["suite"],
        city: json["city"],
        zipcode: json["zipcode"],
        geo: Geo.fromJson(json["geo"]),
    );

    Map<String, dynamic> toJson() => {
        "street": street,
        "suite": suite,
        "city": city,
        "zipcode": zipcode,
        "geo": geo.toJson(),
    };
}

class Geo {
    String lat;
    String lng;

    Geo({
        this.lat,
        this.lng,
    });

    factory Geo.fromJson(Map<String, dynamic> json) => new Geo(
        lat: json["lat"],
        lng: json["lng"],
    );

    Map<String, dynamic> toJson() => {
        "lat": lat,
        "lng": lng,
    };
}

class Company {
    String name;
    String catchPhrase;
    String bs;

    Company({
        this.name,
        this.catchPhrase,
        this.bs,
    });

    factory Company.fromJson(Map<String, dynamic> json) => new Company(
        name: json["name"],
        catchPhrase: json["catchPhrase"],
        bs: json["bs"],
    );

    Map<String, dynamic> toJson() => {
        "name": name,
        "catchPhrase": catchPhrase,
        "bs": bs,
    };
}

I need to show this data in ListView inside Future Builder. How  do I do this? Please somebody help me?

Body:
this response its using http dio lib.

Widget build(BuildContext context) {
  return Scaffold(
      body: SafeArea(
        child: FutureBuilder(
          future: _getData(),
          builder: (_, AsyncSnapshot<User> snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return new Theme(
                data: Theme.of(context).copyWith(accentColor: Colors.blue),
                child: new CircularProgressIndicator(),
              );
            }

            if (!snapshot.hasData) {
              return Center(
                child: Text("No data found"),
              );
            }

            User user = snapshot.data;
            return ListView(
              children: <Widget>[
                ListTile(
                  title: Text(user.name),
                  subtitle: Text(user.email),
                ),
              ],
            );
          },
        ),
      ),
    );
}

 Future<User> _getData() async {
    final Response response =
    await dio.get("https://jsonplaceholder.typicode.com/users?id=1");
    return User.fromJson(response.data[0]);
}


问:
How to get instagram number of followers using instaload?
I am using instaload librabry

source code is here

```<code> # Get instance
import instaloader
L = instaloader.Instaloader()

# Login or load session
L.login(username, password)        # (login)

# Obtain profile metadata
profile = instaloader.Profile.from_username(L.context, "pink_sfsu")

# Print list of followees
for followee in profile.get_followers():
    print(followee)
</code>```

I am trying to retrieve the number of followers of the followers of the account. I successfully get the follower of the account but can manage to know its number of follower. I am reading the source code. Because I assume that instaloader already do similar things to get all the followers of a page. Therefore I try to extend this but don't succeed.

答:
Try something like this:</p>

```<code># Print all followers with their followers count
for follower in profile.get_followers():
    print('{} has {} followers'.format(follower.username, follower.followers))
</code>```

Body:
I am using instaload librabry

source code is here

 # Get instance
import instaloader
L = instaloader.Instaloader()

# Login or load session
L.login(username, password)        # (login)

# Obtain profile metadata
profile = instaloader.Profile.from_username(L.context, "pink_sfsu")

# Print list of followees
for followee in profile.get_followers():
    print(followee)

I am trying to retrieve the number of followers of the followers of the account. I successfully get the follower of the account but can manage to know its number of follower. I am reading the source code. Because I assume that instaloader already do similar things to get all the followers of a page. Therefore I try to extend this but don't succeed.

Body:
Try something like this:

# Print all followers with their followers count
for follower in profile.get_followers():
    print('{} has {} followers'.format(follower.username, follower.followers))


问:
Is it possible to know if the node where a Kubernetes Pod is being scheduled is master or worker?
I'm currently using Kubernetes to schedule a DaemonSet on both master and worker nodes.

The DaemonSet definition is the same for both node types (same image, same volumes, etc), the only difference is that when the entrypoint is executed, I need to write a different configuration file (which is generated in Python with some dynamic values) if the node is a master or a worker.

Currently, to overcome this I'm using two different DaemonSet definitions with an env value which tells if the node is a master or not. Here's the yaml file (only relevant parts):

```<code>apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: worker-ds
  namespace: kube-system
  labels:
    k8s-app: worker
spec:
  ...
    spec:
      hostNetwork: true
      containers:
        - name: my-image
          ...
          env:
            - name: NODE_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.hostIP
            - name: IS_MASTER
              value: "false"
      ...
---
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: master-ds
  namespace: kube-system
  labels:
    k8s-app: master
spec:
  ...
    spec:
      hostNetwork: true
      nodeSelector:
        node-role.kubernetes.io/master: ""
      tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      containers:
        - name: my-image
          ...
          env:
            - name: NODE_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.hostIP
            - name: IS_MASTER
              value: "true"
      ...
</code>```

However, since the only difference is the IS_MASTER value, I want to collapse both the definitions in a single one that programmatically understands if the current node where the pod is being scheduled is a master or a worker.

Is there any way to know this information about the node programmatically (even reading a configuration file [for example something that only the master has or viceversa] in the node or something like that)?

Thanks in advance.

答:
You can tell a node is the master if it has the label node-role.kubernetes.io/master: "".
What you need to do is access that label from your containers which can be done with the Downward Api (Edit: Wrong, only Pod information can be accessed from the Downward Api). You can mount the labels inside your containers using:

```<code>volumes:
    - name: podinfo
      downwardAPI:
        items:
          - path: "labels"
            fieldRef:
              fieldPath: metadata.labels
</code>```

You can then search the content of that file from within the container.

Body:
I'm currently using Kubernetes to schedule a DaemonSet on both master and worker nodes.

The DaemonSet definition is the same for both node types (same image, same volumes, etc), the only difference is that when the entrypoint is executed, I need to write a different configuration file (which is generated in Python with some dynamic values) if the node is a master or a worker.

Currently, to overcome this I'm using two different DaemonSet definitions with an env value which tells if the node is a master or not. Here's the yaml file (only relevant parts):

apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: worker-ds
  namespace: kube-system
  labels:
    k8s-app: worker
spec:
  ...
    spec:
      hostNetwork: true
      containers:
        - name: my-image
          ...
          env:
            - name: NODE_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.hostIP
            - name: IS_MASTER
              value: "false"
      ...
---
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: master-ds
  namespace: kube-system
  labels:
    k8s-app: master
spec:
  ...
    spec:
      hostNetwork: true
      nodeSelector:
        node-role.kubernetes.io/master: ""
      tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      containers:
        - name: my-image
          ...
          env:
            - name: NODE_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.hostIP
            - name: IS_MASTER
              value: "true"
      ...

However, since the only difference is the IS_MASTER value, I want to collapse both the definitions in a single one that programmatically understands if the current node where the pod is being scheduled is a master or a worker.

Is there any way to know this information about the node programmatically (even reading a configuration file [for example something that only the master has or viceversa] in the node or something like that)?

Thanks in advance.

Body:
You can tell a node is the master if it has the label node-role.kubernetes.io/master: "".
What you need to do is access that label from your containers which can be done with the Downward Api (Edit: Wrong, only Pod information can be accessed from the Downward Api). You can mount the labels inside your containers using:

volumes:
    - name: podinfo
      downwardAPI:
        items:
          - path: "labels"
            fieldRef:
              fieldPath: metadata.labels

You can then search the content of that file from within the container.


问:
CORS implementation showing method not allowed for POST request
I am trying to call a WCF service Method using Http POST Request from another Project , it allows GET request but when I try for  POST request it is showing "Method not allowed".

When i tried it shows this error in my Console:

Access to XMLHttpRequest at 'http://localhost:7280/api/values/24' from origin 'http://localhost:6538' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Web API:
Method:

```<code>[WebInvoke(UriTemplate = "/values", Method = "POST", ResponseFormat = WebMessageFormat.Json), CorsEnabled]
        void AddValue(string value);
</code>```

Method Implementation

```<code>public void AddValue(string value)
        {
            string id = nextId.ToString();
            nextId++;
            allValues.Add(id, value);
            string location = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.ToString() + "/" + id;
            WebOperationContext.Current.OutgoingResponse.SetStatusAsCreated(new Uri(location));
        }
</code>```

Client Application:

```<code>$("#post").click(function () {
            var data = "\"" + $("#value").val() + "\"";
            $.ajax({
                url: valuesAddress,
                type: "POST",
                contentType: "application/json",
                data: data,
                success: function (result) {
                    $("#result").text(result);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $("#result").text(textStatus);
                }
            });
        });
</code>```

I followed
https://code.msdn.microsoft.com/Implementing-CORS-support-c1f9cd4b/view/SourceCode#content
I created web API and client Application as different projects.
Please help to solve this issue.

答:
I was having a problem with CORS myself, here is how I did it in asp.net (same judging by your tags):

I have installed the following NuGet package:

Install-Package Microsoft.AspNet.WebApi.Cors

Then in your WebApiConfig file:

        public static void Register(HttpConfiguration config)
        {
            EnableCorsAttribute cors = new
                 EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);

            AddRoutes(config);
        }
```

<p>You have already done this step, just move the <code>EnableCors(cors)</code> method above the <code>AddRoutes(config);</code></p>

<ul>
<li>Lastly, you put the following attribute above SaveWithPost:</li>
</ul>

<pre class="lang-cs prettyprint-override"><code>[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
</code>```

Note: If you keep getting this error:

OPTIONS http://localhost/Service1.svc/saveWithPost/WithParameter 405 (Method Not Allowed)
  Access to XMLHttpRequest at 'http://localhost/Service1.svc/saveWithPost/WithParameter' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Read here the official documentation of Microsoft. The link brings you under How Cors Work, where you can read more about preflight requests. Shortly, the browser sends an additional request, before the actual request.
Read more here.

Another side note: Check if you are not blocking the OPTIONS request. For instance, some companies use software for security, networking and storage products based on network appliances and cloud services, which FILTER all the upcoming requests to their own server, which may sometime lead to this. (not likely)

Hope this helps,

Cheers

Body:
I am trying to call a WCF service Method using Http POST Request from another Project , it allows GET request but when I try for  POST request it is showing "Method not allowed".

When i tried it shows this error in my Console:

Access to XMLHttpRequest at 'http://localhost:7280/api/values/24' from origin 'http://localhost:6538' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Web API:
Method:

[WebInvoke(UriTemplate = "/values", Method = "POST", ResponseFormat = WebMessageFormat.Json), CorsEnabled]
        void AddValue(string value);

Method Implementation

public void AddValue(string value)
        {
            string id = nextId.ToString();
            nextId++;
            allValues.Add(id, value);
            string location = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.ToString() + "/" + id;
            WebOperationContext.Current.OutgoingResponse.SetStatusAsCreated(new Uri(location));
        }

Client Application:

$("#post").click(function () {
            var data = "\"" + $("#value").val() + "\"";
            $.ajax({
                url: valuesAddress,
                type: "POST",
                contentType: "application/json",
                data: data,
                success: function (result) {
                    $("#result").text(result);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $("#result").text(textStatus);
                }
            });
        });

I followed
https://code.msdn.microsoft.com/Implementing-CORS-support-c1f9cd4b/view/SourceCode#content
I created web API and client Application as different projects.
Please help to solve this issue.

Body:
I was having a problem with CORS myself, here is how I did it in asp.net (same judging by your tags):

I have installed the following NuGet package:

Install-Package Microsoft.AspNet.WebApi.Cors

Then in your WebApiConfig file:

        public static void Register(HttpConfiguration config)
        {
            EnableCorsAttribute cors = new
                 EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);

            AddRoutes(config);
        }

You have already done this step, just move the EnableCors(cors) method above the AddRoutes(config);

Lastly, you put the following attribute above SaveWithPost:

[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]

Note: If you keep getting this error:

OPTIONS http://localhost/Service1.svc/saveWithPost/WithParameter 405 (Method Not Allowed)
  Access to XMLHttpRequest at 'http://localhost/Service1.svc/saveWithPost/WithParameter' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Read here the official documentation of Microsoft. The link brings you under How Cors Work, where you can read more about preflight requests. Shortly, the browser sends an additional request, before the actual request.
Read more here.

Another side note: Check if you are not blocking the OPTIONS request. For instance, some companies use software for security, networking and storage products based on network appliances and cloud services, which FILTER all the upcoming requests to their own server, which may sometime lead to this. (not likely)

Hope this helps,

Cheers


问:
Huge datasets operations issues on AWS
I have 5 csv of files of approximately 20gb each.

I did all my code in order to transform and merge them with pandas on samples of 1 go each.

Now, I use my code on the real datasets on AWS EC2, and still with pandas.

My questions are:

I think it's useless to use a GPU for this problem? Am I wrong?

Should I use an other library than Pandas (like Dask?)

What kind of caracteristics should I choose for EC2 ? (Several CPUs, or only one? ...)

For the moment, my code does not give errors, but my final dataset has only 100 rows. Is the data too huge, so Pandas automatically ignore a lot of rows??

Thanks a lot

Here is an example of the kind of code I have to do on these huge datasets:

```<code>as_country = pd.merge(as_country, conventions_data, left_on='country', right_on = 'country_x', how = 'left')
as_country = as_country.dropna()
as_country = as_country.drop(columns=['countryname'])
as_country.enforce_date = as_country.enforce_date.astype(int)

as_country = as_country.drop(columns=['country_x', 'country_y','country_code','year'])
as_country['date_minus_enforcedate'] = as_country['date'] - as_country['enforce_date']
as_country['date_minus_enforcedate'] =  np.where((as_country.date_minus_enforcedate <= 0), -1, 1)
## AS_country will be just for one day and group by:

as_country = as_country.groupby(['as', 'country']).mean().reset_index()

as_country = as_country.drop(columns=['date', 'enforce_date'])
as_country_columns = list(as_country.columns)
as_country_columns.remove('as')
as_country_columns.remove('country')
as_country = as_country.pivot(index='as', columns='country', values=as_country_columns)
as_country = as_country.fillna(0)
</code>```

答:
Let's take this as an expanded comment.

I think it's useless to use a GPU for this problem? Am I wrong?

If it's a one-off computation yes. Otherwise have a look at cudf from rapids.ai or blazingSQL.

Should I use an other library than Pandas (like Dask?)

If your computation run in memory you don't need Dask see docs

What kind of caracteristics should I choose for EC2 ? (Several CPUs, or only one? ...)

I suggest you to estimate the maximum RAM usage and get a 10-20% more. Number of cores is somehow related (i.e. you can't have 1 core and 200GB of RAM)

For the moment, my code does not give errors, but my final dataset has only 100 rows. Is the data too huge, so Pandas automatically ignore a lot of rows??

For this problem, which should be your principal concern, you should check step-by-step your commands. It's weird to me that you first drop as and country columns and then you  use them to pivot.

Title: Huge datasets operations issues on AWS

Body:
I have 5 csv of files of approximately 20gb each.

I did all my code in order to transform and merge them with pandas on samples of 1 go each.

Now, I use my code on the real datasets on AWS EC2, and still with pandas.

My questions are:

I think it's useless to use a GPU for this problem? Am I wrong?

Should I use an other library than Pandas (like Dask?)

What kind of caracteristics should I choose for EC2 ? (Several CPUs, or only one? ...)

For the moment, my code does not give errors, but my final dataset has only 100 rows. Is the data too huge, so Pandas automatically ignore a lot of rows??

Thanks a lot

Here is an example of the kind of code I have to do on these huge datasets:

as_country = pd.merge(as_country, conventions_data, left_on='country', right_on = 'country_x', how = 'left')
as_country = as_country.dropna()
as_country = as_country.drop(columns=['countryname'])
as_country.enforce_date = as_country.enforce_date.astype(int)

as_country = as_country.drop(columns=['country_x', 'country_y','country_code','year'])
as_country['date_minus_enforcedate'] = as_country['date'] - as_country['enforce_date']
as_country['date_minus_enforcedate'] =  np.where((as_country.date_minus_enforcedate <= 0), -1, 1)
## AS_country will be just for one day and group by:

as_country = as_country.groupby(['as', 'country']).mean().reset_index()

as_country = as_country.drop(columns=['date', 'enforce_date'])
as_country_columns = list(as_country.columns)
as_country_columns.remove('as')
as_country_columns.remove('country')
as_country = as_country.pivot(index='as', columns='country', values=as_country_columns)
as_country = as_country.fillna(0)


问:
Android app label color
I don't want to create any custom layout for app label, just want to change it's color to white (now it's black). How could I do that?</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="MyTheme" parent="@android:style/Theme.Holo.Light">
    <item name="android:actionBarStyle">@style/MyActionBar</item>

</style>

<style name="MyActionBar" parent="@android:style/Widget.Holo.ActionBar">
    <item name="android:background">@drawable/bg_blue_solid_onclick</item>
//////CHANGE label color
</style>
</resources>
</code>```

答:
in styles.xml

```<code><style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
</code>```

in toolbar

```<code>android:theme="@style/AppTheme.AppBarOverlay"
</code>```

Title: Android app label color

Body:
I don't want to create any custom layout for app label, just want to change it's color to white (now it's black). How could I do that?

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">

</resources>

Body:
in styles.xml

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

in toolbar

android:theme="@style/AppTheme.AppBarOverlay"


问:
shiny arules htmlwidget graph only populates in Viewer
I'm trying to create a shiny app for visualizing association rules. Its running fine except the graph plot keeps getting populated in the R Studio Viewer instead of within the Shiny App. Please Help!. Code below (am running R v 3.4.2)</p>

```<code>ui<-fluidPage(
titlePanel("test"),
sidebarLayout(
sidebarPanel(
radioButtons("hier", "Hierarchy:", c("DEPT", "SUB_DEPT", "CLASS")),
selectInput("period",label = em("Period"), c("P1","P2"),selected = 'P1'),
sliderInput("n_rules", "No. of rules:",min = 0, max = 100, value = 10,
step = 10)
),
mainPanel(plotlyOutput("network_graph"))
)
)
server <- function(input, output){
output$network_graph <- renderPlotly({
if (input$hier == 'DEPT' & input$period == 'P1') {
print(
(
plot(head(sort(DEPT_P1_All_Customers),input$n_rules), engine =
"htmlwidget", method = "graph", height = "800px")
))
}
})
}
shinyApp(ui, server)
</code>```

答:
For "graph" method change your input and output, as:

plotlyOutput("network_graph") to visNetworkOutput("network_graph")
and renderPlotly to renderVisNetwork.

Body:
I'm trying to create a shiny app for visualizing association rules. Its running fine except the graph plot keeps getting populated in the R Studio Viewer instead of within the Shiny App. Please Help!. Code below (am running R v 3.4.2)

ui<-fluidPage(
titlePanel("test"),
sidebarLayout(
sidebarPanel(
radioButtons("hier", "Hierarchy:", c("DEPT", "SUB_DEPT", "CLASS")),
selectInput("period",label = em("Period"), c("P1","P2"),selected = 'P1'),
sliderInput("n_rules", "No. of rules:",min = 0, max = 100, value = 10,
step = 10)
),
mainPanel(plotlyOutput("network_graph"))
)
)
server <- function(input, output){
output$network_graph <- renderPlotly({
if (input$hier == 'DEPT' & input$period == 'P1') {
print(
(
plot(head(sort(DEPT_P1_All_Customers),input$n_rules), engine =
"htmlwidget", method = "graph", height = "800px")
))
}
})
}
shinyApp(ui, server)


问:
Resolve `prop-types` in `.cache` after installing new plugin in Gatsby
I'm new to Gatsby and just following its tutorial. Whenever I install a new plugin, just say gatsby-source-filesystem or typography from the tutorial page, I cannot run gatsby develop again.

The error clearly say itself:

Module not found: Error: Can't resolve 'prop-types' in '/Users/comp-name/hello-gatsby/.cache'
  resolve 'prop-types' in '/Users/comp-name/hello-gatsby/.cache'

The only solution I can do is to remove node_modules and re-install everything again, then when I try to install another plugin. This loop happens and I find it quite annoying.

Does anyone have a solution for this?

答:
Whenever you have issues relating to gatsby's cache, you can delete the .cache folder, or try the gatsby clean command which does the same thing.

However, a cursory google search reveals someone else has encountered a similar problem here https://github.com/gatsbyjs/gatsby/issues/11375 which they resolved by updating to the latest version of npm and re-installing node packages.


问:
Perl function for escaping characters for Windows commands
I have a string in Perl which contains various special characters and I need to pass this string to a Windows command using backticks, but I don't want the special characters to mess up the command. I have found out that with Windows commands, different special characters need to be escaped in different ways. Is there a Perl function which has been specially created to escape a string in such a way as to prepare it for a Windows command?</p>

答: Yes, there's Win32::ShellQuote, which should do what you want.


问:
Compare two html files
Hi
I want to compare code of two HTML files. How do I achieve this?</p>

答:
If you can use a tool; there are a lot of compare-tools available like UltraCompare.
But if you want to build it yourself; please let us know.

Edit: There is a Java library available for this.

Title: Compare two html files


问:
How do I properly include a wx.grid inside a wx.GridBagSizer?
I'm just beginning to lean python and the use of wxpython widgets. I tried creating a 50 X 3 wx.grid.  If it's the only object in a panel, then there's no problem.  However, if I tried to include other objects by using a GridBagSizer then it seem to occupy only one cell of the sizer even of I specified span=(5,3) for 5 row, 3 columns.

I tried using a separate BoxSizer for the panel containing the grid (commented in my code) by it also didn't work.

```<code>import wx
import wx.grid

class Screen(wx.Frame):
    def __init__(self, parent, title):
        super(Screen, self).__init__(parent, title=title,
            size=(500, 500))
                self.paneltab = wx.Panel(self.panel)
        self.paneltab.SetSize(size=(150,150))

        #this is the grid I want to display properly
        self.tab = wx.grid.Grid(self.paneltab)

        self.tab.CreateGrid(50,3)
        self.tab.SetColSize(0,150)
        self.tab.SetColSize(1,100)
        self.tab.SetColSize(2,50)
        self.tab.SetColLabelValue(0, "USER")
        self.tab.SetColLabelValue(1, "Log-In Time")
        self.tab.SetColLabelValue(2, "Status")
        self.SetLayout()
        self.Centre()

    def SetLayout(self):
        sizer = wx.GridBagSizer(0,0)
        #sizertab = wx.BoxSizer(wx.VERTICAL)
        #self.paneltab.SetSizer(sizerTab)

        sizer.Add((100,-1),     pos=(0,0))
        sizer.Add((100,-1),     pos=(0,1))
        sizer.Add((100,-1),     pos=(0,2))
        text1 = wx.StaticText(self.panel, label='Hello', style =
            wx.ALIGN_CENTER)
        text2 = wx.StaticText(self.panel, label='World', style =
            wx.ALIGN_CENTER)

        sizer.Add(text1,   pos=(1,0),  span=(1,1), flag=wx.TOP|wx.EXPAND,
            border=5)
        sizer.Add(text2,   pos=(1,2),  span=(1,2), flag=wx.TOP|wx.EXPAND,
            border=5)

        #sizer.Add(sizertab,     pos=(2,1),  span=(5,2),
            flag=wx.TOP|wx.EXPAND,  border=5)
        sizer.Add(self.paneltab,     pos=(2,0),  span=(5,3),
            flag=wx.TOP|wx.EXPAND,  border=5)

        self.panel.SetSizer(sizer)
        sizer.Fit(self)
        self.panel.SetBackgroundColour("thristle1")

def main():
    app = wx.App()
    screen = Screen(None, title='Server Consule')
    screen.Show()
    app.MainLoop()
if __name__ == '__main__':
    main()
</code>```

I expected the grid to be displayed in a span=(5,3) but it seem to be displayed in a span=(1,1).

答:
Do you mean that you want something like this:

As I said in my comment, it's going to look a bit odd. You might be better off just using multiple BoxSizer's.

Your code amended to produce the above is:

```<code>import wx
import wx.grid

class Screen(wx.Frame):
    def __init__(self, parent, title):
        super(Screen, self).__init__(parent, title=title, size=(500, 500))

        self.paneltab = wx.Panel(self)
        self.paneltab.SetSize((500,250))
        #this is the grid I want to display properly
        self.tab = wx.grid.Grid(self.paneltab)
        self.tab.CreateGrid(50,3)
        self.tab.SetColSize(0,150)
        self.tab.SetColSize(1,100)
        self.tab.SetColSize(2,50)
        self.tab.SetColLabelValue(0, "USER")
        self.tab.SetColLabelValue(1, "Log-In Time")
        self.tab.SetColLabelValue(2, "Status")

        self.tab.SetMinSize((300,300))

        self.text1 = wx.StaticText(self.paneltab, label='Hello', style = wx.ALIGN_CENTER)
        self.text2 = wx.StaticText(self.paneltab, label='World', style = wx.ALIGN_CENTER)

        self.SetLayout()
        self.Centre()

    def SetLayout(self):
        sizer = wx.GridBagSizer(5,5)
        sizer.Add((100,-1),     pos=(0,0))
        sizer.Add((100,-1),     pos=(0,1))
        sizer.Add((100,-1),     pos=(0,2))
        sizer.Add(self.text1,   pos=(1,0), span=(1,1), flag=wx.TOP|wx.EXPAND, border=5)
        sizer.Add(self.text2,   pos=(1,2), span=(1,2), flag=wx.TOP|wx.EXPAND, border=5)
        sizer.Add(self.tab,     pos=(2,3), span=(3,5), flag=wx.TOP|wx.EXPAND, border=5)
        self.paneltab.SetSizer(sizer)
        self.paneltab.SetBackgroundColour("#D8BFD8")

def main():
    app = wx.App()
    screen = Screen(None, title='Server Console')
    screen.Show()
    app.MainLoop()
if __name__ == '__main__':
    main()
</code>```

Body:
I'm just beginning to lean python and the use of wxpython widgets. I tried creating a 50 X 3 wx.grid.  If it's the only object in a panel, then there's no problem.  However, if I tried to include other objects by using a GridBagSizer then it seem to occupy only one cell of the sizer even of I specified span=(5,3) for 5 row, 3 columns.

I tried using a separate BoxSizer for the panel containing the grid (commented in my code) by it also didn't work.

import wx
import wx.grid

class Screen(wx.Frame):
    def __init__(self, parent, title):
        super(Screen, self).__init__(parent, title=title,
            size=(500, 500))
                self.paneltab = wx.Panel(self.panel)
        self.paneltab.SetSize(size=(150,150))

        #this is the grid I want to display properly
        self.tab = wx.grid.Grid(self.paneltab)

        self.tab.CreateGrid(50,3)
        self.tab.SetColSize(0,150)
        self.tab.SetColSize(1,100)
        self.tab.SetColSize(2,50)
        self.tab.SetColLabelValue(0, "USER")
        self.tab.SetColLabelValue(1, "Log-In Time")
        self.tab.SetColLabelValue(2, "Status")
        self.SetLayout()
        self.Centre()

    def SetLayout(self):
        sizer = wx.GridBagSizer(0,0)
        #sizertab = wx.BoxSizer(wx.VERTICAL)
        #self.paneltab.SetSizer(sizerTab)

        sizer.Add((100,-1),     pos=(0,0))
        sizer.Add((100,-1),     pos=(0,1))
        sizer.Add((100,-1),     pos=(0,2))
        text1 = wx.StaticText(self.panel, label='Hello', style =
            wx.ALIGN_CENTER)
        text2 = wx.StaticText(self.panel, label='World', style =
            wx.ALIGN_CENTER)

        sizer.Add(text1,   pos=(1,0),  span=(1,1), flag=wx.TOP|wx.EXPAND,
            border=5)
        sizer.Add(text2,   pos=(1,2),  span=(1,2), flag=wx.TOP|wx.EXPAND,
            border=5)

        #sizer.Add(sizertab,     pos=(2,1),  span=(5,2),
            flag=wx.TOP|wx.EXPAND,  border=5)
        sizer.Add(self.paneltab,     pos=(2,0),  span=(5,3),
            flag=wx.TOP|wx.EXPAND,  border=5)

        self.panel.SetSizer(sizer)
        sizer.Fit(self)
        self.panel.SetBackgroundColour("thristle1")

def main():
    app = wx.App()
    screen = Screen(None, title='Server Consule')
    screen.Show()
    app.MainLoop()
if __name__ == '__main__':
    main()

I expected the grid to be displayed in a span=(5,3) but it seem to be displayed in a span=(1,1).

Body:
Do you mean that you want something like this:

As I said in my comment, it's going to look a bit odd. You might be better off just using multiple BoxSizer's.

Your code amended to produce the above is:

import wx
import wx.grid

class Screen(wx.Frame):
    def __init__(self, parent, title):
        super(Screen, self).__init__(parent, title=title, size=(500, 500))

        self.paneltab = wx.Panel(self)
        self.paneltab.SetSize((500,250))
        #this is the grid I want to display properly
        self.tab = wx.grid.Grid(self.paneltab)
        self.tab.CreateGrid(50,3)
        self.tab.SetColSize(0,150)
        self.tab.SetColSize(1,100)
        self.tab.SetColSize(2,50)
        self.tab.SetColLabelValue(0, "USER")
        self.tab.SetColLabelValue(1, "Log-In Time")
        self.tab.SetColLabelValue(2, "Status")

        self.tab.SetMinSize((300,300))

        self.text1 = wx.StaticText(self.paneltab, label='Hello', style = wx.ALIGN_CENTER)
        self.text2 = wx.StaticText(self.paneltab, label='World', style = wx.ALIGN_CENTER)

        self.SetLayout()
        self.Centre()

    def SetLayout(self):
        sizer = wx.GridBagSizer(5,5)
        sizer.Add((100,-1),     pos=(0,0))
        sizer.Add((100,-1),     pos=(0,1))
        sizer.Add((100,-1),     pos=(0,2))
        sizer.Add(self.text1,   pos=(1,0), span=(1,1), flag=wx.TOP|wx.EXPAND, border=5)
        sizer.Add(self.text2,   pos=(1,2), span=(1,2), flag=wx.TOP|wx.EXPAND, border=5)
        sizer.Add(self.tab,     pos=(2,3), span=(3,5), flag=wx.TOP|wx.EXPAND, border=5)
        self.paneltab.SetSizer(sizer)
        self.paneltab.SetBackgroundColour("#D8BFD8")

def main():
    app = wx.App()
    screen = Screen(None, title='Server Console')
    screen.Show()
    app.MainLoop()
if __name__ == '__main__':
    main()


问:
Mysql Filter data using Timestamp stored in table
I have stored bill date in timestamp in mysql.

In reports, i get from and to date in dd-mm-YYYY format.In query I have used like this,

```<code>WHERE  (from_unixtime(bill.bill_date,"%d-%m-%Y")) >='06-04-2019' AND (from_unixtime(bill.bill_date,"%d-%m-%Y")) <= '30-04-2019'
</code>```

But the data 06/05/2019 also fetched. I don't know why it is happening.

答:
You're specifying format for the column but not for the condition values. Try:

```<code>WHERE  (from_unixtime(bill.bill_date,"%d-%m-%Y")) >=STR_TO_DATE('06-04-2019', '%d-%m-%Y') AND (from_unixtime(bill.bill_date,"%d-%m-%Y")) <= STR_TO_DATE('30-04-2019', '%d-%m-%Y')
</code>```

or better yet:

```<code>WHERE (from_unixtime(bill.bill_date,'%Y-%m-%d')) BETWEEN '2019-04-06' AND '2019-04-30'
</code>```

Body:
I have stored bill date in timestamp in mysql.

In reports, i get from and to date in dd-mm-YYYY format.In query I have used like this,

WHERE  (from_unixtime(bill.bill_date,"%d-%m-%Y")) >='06-04-2019' AND (from_unixtime(bill.bill_date,"%d-%m-%Y")) <= '30-04-2019'

But the data 06/05/2019 also fetched. I don't know why it is happening.

Body:
You're specifying format for the column but not for the condition values. Try:

WHERE  (from_unixtime(bill.bill_date,"%d-%m-%Y")) >=STR_TO_DATE('06-04-2019', '%d-%m-%Y') AND (from_unixtime(bill.bill_date,"%d-%m-%Y")) <= STR_TO_DATE('30-04-2019', '%d-%m-%Y')

or better yet:

WHERE (from_unixtime(bill.bill_date,'%Y-%m-%d')) BETWEEN '2019-04-06' AND '2019-04-30'


问:
footer overlapping with contents
Im trying to put the "Vaccet" picture as a footer but, it keeps on going next to the "UPM" picture.

I have tried removing the footer from the body. On the other websites I've made, the contents of the footer goes under the section above it but this goes next to it.

   .column-2 {
      float: left;
      width: 33.3%;
      padding: 5px;
      padding-right: 30px;
      display: inline-block;
    }

    .column-3 {
      float: right;
      width: 30%;
      display: inline-block;
      padding-right: 30px;
      padding
    }

    .section-team{
        text-align: center;

    }

    .members{
        border-radius: 50%;
    }

    .upm{
        padding-top: 25px;
        padding-right: 5px;
    }

    footer{
        padding: 50px;
        font-size: 80%;

    }

    .footer-nav{
       display: inline-block;
       width: 100%
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <section class="section-team" id="team">
        <div class="row">
           <h2>team members</h2>
        </div>
      <div class="column-2">
        <img src="img/faceexample.jpg" class="members" alt="members" style="width:50%">
        <h3>Adam</h3>
      </div>
       <div class="column-2">
        <img src="img/faceexample.jpg" class="members" alt="members" style="width:50%">
        <h3>Adam</h3>
      </div>
       <div class="column-2">
        <img src="img/faceexample.jpg" class="members" alt="members" style="width:50%">
        <h3>Adam</h3>
      </div>
       <div class="column-2">
        <img src="img/faceexample.jpg"  class="members" alt="members" style="width:50%">
        <h3>Adam</h3>
      </div>
       <div class="column-2">
        <img src="img/faceexample.jpg" class="members" alt="members" style="width:50%">
        <h3>Adam</h3>
      </div>
       <div class="column-2">
        <img src="img/faceexample.jpg" class="members" alt="members" style="width:50%">
        <h3>Adam</h3>
      </div>
        <div class="column-3">
        <img src="img/upm.jpg" class="upm" alt="upm" style="width:30%">
        <h4>UPM</h4>
      </div>
        </section>
         <footer>
              <div class="row">
                <div class="col span-1-of-2">
                    <ul class="footer-nav">
                          <img src="img/Vaccet.jpg" alt="vaccet logo"
                            class="logo">
                    </ul>
                </div>
            </div>

 </code>```

I hope someone can show me how to fix the footer problem

答:
I think the issue is that the
 is not clearfix-ed. When using float elements, it is essential that you clearfix the container (.section-team in this case)

Try the following CSS (The Clearfix Hack):

```<code>.section-team:after,.section-team:before{
  content:''
  clear:both;
  display:table;
}
</code>```

Title: footer overlapping with contents

Body:
Im trying to put the "Vaccet" picture as a footer but, it keeps on going next to the "UPM" picture.

I have tried removing the footer from the body. On the other websites I've made, the contents of the footer goes under the section above it but this goes next to it.

   .column-2 {
      float: left;
      width: 33.3%;
      padding: 5px;
      padding-right: 30px;
      display: inline-block;
    }

    .column-3 {
      float: right;
      width: 30%;
      display: inline-block;
      padding-right: 30px;
      padding
    }

    .section-team{
        text-align: center;

    }

    .members{
        border-radius: 50%;
    }

    .upm{
        padding-top: 25px;
        padding-right: 5px;
    }

    footer{
        padding: 50px;
        font-size: 80%;

    }

    .footer-nav{
       display: inline-block;
       width: 100%
    }

team members

Adam

Adam

Adam

Adam

Adam

Adam

UPM

I hope someone can show me how to fix the footer problem

Body:
I think the issue is that the <section> is not clearfix-ed. When using float elements, it is essential that you clearfix the container (.section-team in this case)

Try the following CSS (The Clearfix Hack):

.section-team:after,.section-team:before{
  content:''
  clear:both;
  display:table;
}


问:
Protocol Extension where Self is ClassA OR ClassB
I have a protocol for which I want to provide default functionality in the case that the conforming class is either ClassA OR ClassB. Is it possible to use || in a protocol extension where clause? I've tried the following but it doesn't work:

```<code>extension Protocol where Self: ClassA || Self: ClassB {
    func method() {
        // implementation if conforming class is ClassA OR ClassB
    }
}
</code>```

答:
It's simply not possible at the moment. One solution could be creating two different extensions.

extension Protocol where Self: ClassA {
    func method() {
        commonMethod()
    }
}

extension Protocol where Self: ClassB {
    func method() {
        commonMethod()
    }
}

private func commonMethod() {
    // do here your stuff
}
```

<p>Or creating a common protocol, assuming that <code>ClassA</code> and <code>ClassB</code> conform to this one.</p>

<pre class="lang-swift prettyprint-override"><code>protocol CommonProtocol {}

class ClassA: Protocol, CommonProtocol {}

class ClassB: Protocol, CommonProtocol {}

extension Protocol where Self: CommonProtocol {
    func method() {
       // your stuff
    }
}
</code>```

Body:
I have a protocol for which I want to provide default functionality in the case that the conforming class is either ClassA OR ClassB. Is it possible to use || in a protocol extension where clause? I've tried the following but it doesn't work:

extension Protocol where Self: ClassA || Self: ClassB {
    func method() {
        // implementation if conforming class is ClassA OR ClassB
    }
}

Body:
It's simply not possible at the moment. One solution could be creating two different extensions.

extension Protocol where Self: ClassA {
    func method() {
        commonMethod()
    }
}

extension Protocol where Self: ClassB {
    func method() {
        commonMethod()
    }
}

private func commonMethod() {
    // do here your stuff
}

Or creating a common protocol, assuming that ClassA and ClassB conform to this one.

protocol CommonProtocol {}

class ClassA: Protocol, CommonProtocol {}

class ClassB: Protocol, CommonProtocol {}

extension Protocol where Self: CommonProtocol {
    func method() {
       // your stuff
    }
}


问:
Is there any way to have espresso ViewAssert for regular expressions?
I would like to know if is there any way to generate espresso ViewAssert for regular expressions, something like:</p>

```<code>onView(withId(R.id.element_id)).check(matches(withRegEx("\\+d")));
</code>```

答:
I tried to look for a matcher that already exists within espresso, but also didn't find one. A suggestion is to create your own. Here's an example using kotlin:

```<code>class RegexMatcher(private val regex: String) : BoundedMatcher<View, TextView>(TextView::class.java) {
    private val pattern = Pattern.compile(regex)

    override fun describeTo(description: Description?) {
        description?.appendText("Checking the matcher on received view: with pattern=$regex")
    }

    override fun matchesSafely(item: TextView?) =
        item?.text?.let {
            pattern.matcher(it).matches()
        } ?: false
}
</code>```

This defines a matcher that will check TextViews for their text matching a specific regex pattern.

You can have this little factory function:

```<code> private fun withPattern(regex: String): Matcher<in View>? = RegexMatcher(regex)
</code>```

And then you can use it like:

```<code>onView(withId(R.id.element_id)).check(matches(withPattern("\\+d")))
</code>```

Hope this helps a bit

Body:
I would like to know if is there any way to generate espresso ViewAssert for regular expressions, something like:

onView(withId(R.id.element_id)).check(matches(withRegEx("\\+d")));

Body:
I tried to look for a matcher that already exists within espresso, but also didn't find one. A suggestion is to create your own. Here's an example using kotlin:

class RegexMatcher(private val regex: String) : BoundedMatcher<View, TextView>(TextView::class.java) {
    private val pattern = Pattern.compile(regex)

    override fun describeTo(description: Description?) {
        description?.appendText("Checking the matcher on received view: with pattern=$regex")
    }

    override fun matchesSafely(item: TextView?) =
        item?.text?.let {
            pattern.matcher(it).matches()
        } ?: false
}

This defines a matcher that will check TextViews for their text matching a specific regex pattern.

You can have this little factory function:

 private fun withPattern(regex: String): Matcher<in View>? = RegexMatcher(regex)

And then you can use it like:

onView(withId(R.id.element_id)).check(matches(withPattern("\\+d")))

Hope this helps a bit


答:
This is a flowing issue. Footer sees the space and tries to squeeze itself within that space.

Try:

```<code>footer{
    clear: both;
}
</code>```

Otherwise: you might want to give a width: 100% to your Section.

Title: footer overlapping with contents

Body:
This is a flowing issue. Footer sees the space and tries to squeeze itself within that space.

Try:

footer{
    clear: both;
}

Otherwise: you might want to give a width: 100% to your Section.


问:
MSBuild error MSB3021: Unable to copy file. Could not find file 'obj\Release\myWebProject1.dll'
When using TeamCity to compile my MSBuild XML task script, it fails with this:

```<code>[10:43:03]: myWebProject1\ myWebProject 1 .csproj (3s)
[10:43:07]: [ myWebProject1\ myWebProject1 .csproj] _CopyWebApplicationLegacy
[10:43:07]: [_CopyWebApplicationLegacy] Copy
[10:43:07]: [Copy] C:\Program Files\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets(131, 5): error MSB3021: Unable to copy file "obj\Release\myWebProject1.dll" to "C:\MSBUILDRELEASE\myWebProject1\\bin\myWebProject1.dll". Could not find file 'obj\Release\myWebProject1.dll'.
</code>```

When I run it locally, it works.

When I compare my local output to my build server output, there are files missing on my build server. Like the global.asax file is missing from my build server output directory (but not when I compile this locally). Why is that?

Here is my current MSBuildScript:

```<code><?xml version="1.0" encoding="utf-8"?>
<Project
  xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
  ToolsVersion="4.0"
  DefaultTargets="Build">

  <PropertyGroup>
    <OutputDir>C:\MSBUILDRELEASE</OutputDir>
  </PropertyGroup>

  <ItemGroup>
    <ProjectToBuild Include="UtilityApp.sln" >
      <Properties>OutputPath=$(OutputDir);Configuration=MSBuildRelease;Platform=x86</Properties>
    </ProjectToBuild>
  </ItemGroup>

  <Target Name="Build">
    <MSBuild Projects="@(ProjectToBuild)"/>
            <CallTarget Targets="Publish WebProject1" />
            <CallTarget Targets="Publish WebProject2" />
  </Target>

<Target Name="Publish WebProject1">
 <RemoveDir Directories="$(OutputFolder)"
       ContinueOnError="true" />
 <MSBuild Projects="WebProject1\WebProject1.csproj"
      Targets="ResolveReferences;_CopyWebApplication"
      Properties="WebProjectOutputDir=$(OutputDir)\WebProject1\;
      OutDir=$(OutputDir)\WebProject1\;Configuration=Release;Platform=AnyCPU" />
</Target>

<Target Name="Publish WebProject2">
 <RemoveDir Directories="$(OutputFolder)"
       ContinueOnError="true" />
 <MSBuild Projects="WebProject2\WebProject2.csproj"
      Targets="ResolveReferences;_CopyWebApplication"
      Properties="WebProjectOutputDir=$(OutputDir)\WebProject2\;
      OutDir=$(OutputDir)\WebProject2\;Configuration=Release;Platform=AnyCPU" />
</Target>

</Project>
</code>```

I can run this script locally and it seems to work fine (no errors generated). When I run it on my build server, it fails with MSBuild error MSB3021.

Now when I compare my local build output files to my server build output files, the server output does not have as many files. For instance, the global.ASAX file is missing in the output on my buildserver. Why would it work local for me, but not on my TeamCity build server? What's the difference and how can I fix it?

I noticed the TeamCity build agent error message has a funny directory path:
"C:\MSBUILDRELEASE\myWebProject1\bin\myWebProject1.dll"

^ There are two slashes before the bin folder. I do not specify that anywhere. What gives? I have a feeling I am not building my Web Projects correctly (maybe use a different task approach?). It seems to work locally but not on my build server.

Am I building my web projects correctly? These are simply web projects for Web Service (ASMX) deployment. Help?

答: I Faced the same issue when connecting to MDF via entity framework. Tackled it by simply cleaning the solution and rebuilding it. Hope it helps..</p>

ContentLicense: CC BY-SA 2.5

Body:
When using TeamCity to compile my MSBuild XML task script, it fails with this:

[10:43:03]: myWebProject1\ myWebProject 1 .csproj (3s)
[10:43:07]: [ myWebProject1\ myWebProject1 .csproj] _CopyWebApplicationLegacy
[10:43:07]: [_CopyWebApplicationLegacy] Copy
[10:43:07]: [Copy] C:\Program Files\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets(131, 5): error MSB3021: Unable to copy file "obj\Release\myWebProject1.dll" to "C:\MSBUILDRELEASE\myWebProject1\\bin\myWebProject1.dll". Could not find file 'obj\Release\myWebProject1.dll'.

When I run it locally, it works.

When I compare my local output to my build server output, there are files missing on my build server. Like the global.asax file is missing from my build server output directory (but not when I compile this locally). Why is that?

Here is my current MSBuildScript:

<?xml version="1.0" encoding="utf-8"?>
<Project
  xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
  ToolsVersion="4.0"
  DefaultTargets="Build">

  <PropertyGroup>
    <OutputDir>C:\MSBUILDRELEASE</OutputDir>
  </PropertyGroup>

  <ItemGroup>
    <ProjectToBuild Include="UtilityApp.sln" >
      <Properties>OutputPath=$(OutputDir);Configuration=MSBuildRelease;Platform=x86</Properties>
    </ProjectToBuild>
  </ItemGroup>

  <Target Name="Build">
    <MSBuild Projects="@(ProjectToBuild)"/>
            <CallTarget Targets="Publish WebProject1" />
            <CallTarget Targets="Publish WebProject2" />
  </Target>

<Target Name="Publish WebProject1">
 <RemoveDir Directories="$(OutputFolder)"
       ContinueOnError="true" />
 <MSBuild Projects="WebProject1\WebProject1.csproj"
      Targets="ResolveReferences;_CopyWebApplication"
      Properties="WebProjectOutputDir=$(OutputDir)\WebProject1\;
      OutDir=$(OutputDir)\WebProject1\;Configuration=Release;Platform=AnyCPU" />
</Target>

<Target Name="Publish WebProject2">
 <RemoveDir Directories="$(OutputFolder)"
       ContinueOnError="true" />
 <MSBuild Projects="WebProject2\WebProject2.csproj"
      Targets="ResolveReferences;_CopyWebApplication"
      Properties="WebProjectOutputDir=$(OutputDir)\WebProject2\;
      OutDir=$(OutputDir)\WebProject2\;Configuration=Release;Platform=AnyCPU" />
</Target>

</Project>

I can run this script locally and it seems to work fine (no errors generated). When I run it on my build server, it fails with MSBuild error MSB3021.

Now when I compare my local build output files to my server build output files, the server output does not have as many files. For instance, the global.ASAX file is missing in the output on my buildserver. Why would it work local for me, but not on my TeamCity build server? What's the difference and how can I fix it?

I noticed the TeamCity build agent error message has a funny directory path:
"C:\MSBUILDRELEASE\myWebProject1\bin\myWebProject1.dll"

^ There are two slashes before the bin folder. I do not specify that anywhere. What gives? I have a feeling I am not building my Web Projects correctly (maybe use a different task approach?). It seems to work locally but not on my build server.

Am I building my web projects correctly? These are simply web projects for Web Service (ASMX) deployment. Help?


问:
Duplicate files copied in APK META-INF/library_release.kotlin_module
I recently added two Android libraries through JitPack and I have the following error:

```<code>Duplicate files copied in APK META-INF/library_release.kotlin_module
</code>```

I've cleared the cached and I've tried excluding the module using

```<code>exclude group: 'org.jetbrains'
</code>```

and

```<code>exclude group: 'org.jetbrains.kotlin'
</code>```

but neither seems to resolve the issue. Is there any way to stop the kotlin stdlib from being added through JitPack? Oddly, other libraries like DbFlow don't have this issue, though I don't see anything special about their setup (other than that it isn't through JitPack)

答:
As suggested in the post Kotlin M13 is out! by jetbrains:

Make sure these .kotlin_module files are not stripped by your packaging process.

So, we can't use exclude option to exclude this resource file from being generated.

As descripted in Kotlin M13 is out!, we should:

in Maven we use groupId and artifactId for module names, but you can say

```<code><configuration>
    <moduleName>com.example.mymodule</moduleName>
</configuration>
</code>```

in Gradle it’s project name + build task name, to customize:

```<code>compileKotlin {
    kotlinOptions.moduleName = "com.example.mymodule"
}
</code>```

This is my configuration for Android library project:

```<code>ext {
    GROUP_ID = 'custom.group.id'
    ARTIFACT_ID = 'artifactid'
}

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"

    compileOptions {
        kotlinOptions.freeCompilerArgs += ['-module-name', "$GROUP_ID.$ARTIFACT_ID"]
    }

    defaultConfig {
        ...
    }
    buildTypes {
        ...
    }
}
</code>```

Resource file named META-INF/custom.group.id.artifactId.kotlin_module will be generated instead of META-INF/library_release.kotlin_module.No more duplicate files will be found.

You can read this post and this post for more information.

Body:
I recently added two Android libraries through JitPack and I have the following error:

Duplicate files copied in APK META-INF/library_release.kotlin_module

I've cleared the cached and I've tried excluding the module using

exclude group: 'org.jetbrains'

and

exclude group: 'org.jetbrains.kotlin'

but neither seems to resolve the issue. Is there any way to stop the kotlin stdlib from being added through JitPack? Oddly, other libraries like DbFlow don't have this issue, though I don't see anything special about their setup (other than that it isn't through JitPack)

Body:
As suggested in the post Kotlin M13 is out! by jetbrains:

Make sure these .kotlin_module files are not stripped by your packaging process.

So, we can't use exclude option to exclude this resource file from being generated.

As descripted in Kotlin M13 is out!, we should:

in Maven we use groupId and artifactId for module names, but you can say

<configuration>
    <moduleName>com.example.mymodule</moduleName>
</configuration>

in Gradle it’s project name + build task name, to customize:

compileKotlin {
    kotlinOptions.moduleName = "com.example.mymodule"
}

This is my configuration for Android library project:

ext {
    GROUP_ID = 'custom.group.id'
    ARTIFACT_ID = 'artifactid'
}

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"

    compileOptions {
        kotlinOptions.freeCompilerArgs += ['-module-name', "$GROUP_ID.$ARTIFACT_ID"]
    }

    defaultConfig {
        ...
    }
    buildTypes {
        ...
    }
}

Resource file named META-INF/custom.group.id.artifactId.kotlin_module will be generated instead of META-INF/library_release.kotlin_module.No more duplicate files will be found.

You can read this post and this post for more information.