问:
Flask renders svg file with no interactivity
My flask app has a route that creates a .svg file (using pygal) and renders in in a template.  Within the app, there are no interactive features however, if I open the the same .svg file from my file browser, I get the full interactive features I'm aiming for like labels on hover etc. Any ideas on how to get the interactive hovers working from my route?

{% extends "base.html" %}
{% block content %}

Matrix of Concern for {{ company.companyname }}

{% endblock %}
```

<p>here is the plot variable passed to the template</p>

<pre class="lang-html prettyprint-override"><code><?xml version='1.0' encoding='utf-8'?>
<svg xmlns:xlink="http://www.w3.org/1999/xlink" class="pygal-chart" id="chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3" viewBox="0 0 800 600" xmlns="http://www.w3.org/2000/svg"><!--Generated with pygal 2.3.1 (etree) ©Kozea 2012-2016 on 2017-12-07--><!--http://pygal.org--><!--http://github.com/Kozea/pygal--><defs><style type="text/css">#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3{-webkit-user-select:none;-webkit-font-smoothing:antialiased;font-family:Consolas,"Liberation Mono",Menlo,Courier,monospace}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .title{font-family:Consolas,"Liberation Mono",Menlo,Courier,monospace;font-size:16px}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .legends .legend text{font-family:Consolas,"Liberation Mono",Menlo,Courier,monospace;font-size:14px}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis text{font-family:Consolas,"Liberation Mono",Menlo,Courier,monospace;font-size:10px}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis text.major{font-family:Consolas,"Liberation Mono",Menlo,Courier,monospace;font-size:10px}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .text-overlay text.value{font-family:Consolas,"Liberation Mono",Menlo,Courier,monospace;font-size:16px}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .text-overlay text.label{font-family:Consolas,"Liberation Mono",Menlo,Courier,monospace;font-size:10px}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .tooltip{font-family:Consolas,"Liberation Mono",Menlo,Courier,monospace;font-size:14px}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 text.no_data{font-family:Consolas,"Liberation Mono",Menlo,Courier,monospace;font-size:64px}
#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3{background-color:rgba(249,249,249,1)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 path,#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 line,#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 rect,#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 circle{-webkit-transition:150ms;-moz-transition:150ms;transition:150ms}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .graph > .background{fill:rgba(249,249,249,1)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .plot > .background{fill:rgba(255,255,255,1)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .graph{fill:rgba(0,0,0,.87)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 text.no_data{fill:rgba(0,0,0,1)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .title{fill:rgba(0,0,0,1)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .legends .legend text{fill:rgba(0,0,0,.87)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .legends .legend:hover text{fill:rgba(0,0,0,1)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis .line{stroke:rgba(0,0,0,1)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis .guide.line{stroke:rgba(0,0,0,.54)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis .major.line{stroke:rgba(0,0,0,.87)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis text.major{fill:rgba(0,0,0,1)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis.y .guides:hover .guide.line,#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .line-graph .axis.x .guides:hover .guide.line,#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .stackedline-graph .axis.x .guides:hover .guide.line,#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .xy-graph .axis.x .guides:hover .guide.line{stroke:rgba(0,0,0,1)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis .guides:hover text{fill:rgba(0,0,0,1)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .reactive{fill-opacity:.7;stroke-opacity:.8}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .ci{stroke:rgba(0,0,0,.87)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .reactive.active,#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .active .reactive{fill-opacity:.8;stroke-opacity:.9;stroke-width:4}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .ci .reactive.active{stroke-width:1.5}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .series text{fill:rgba(0,0,0,1)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .tooltip rect{fill:rgba(255,255,255,1);stroke:rgba(0,0,0,1);-webkit-transition:opacity 150ms;-moz-transition:opacity 150ms;transition:opacity 150ms}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .tooltip .label{fill:rgba(0,0,0,.87)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .tooltip .label{fill:rgba(0,0,0,.87)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .tooltip .legend{font-size:.8em;fill:rgba(0,0,0,.54)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .tooltip .x_label{font-size:.6em;fill:rgba(0,0,0,1)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .tooltip .xlink{font-size:.5em;text-decoration:underline}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .tooltip .value{font-size:1.5em}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .bound{font-size:.5em}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .max-value{font-size:.75em;fill:rgba(0,0,0,.54)}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .map-element{fill:rgba(255,255,255,1);stroke:rgba(0,0,0,.54) !important}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .map-element .reactive{fill-opacity:inherit;stroke-opacity:inherit}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .color-0,#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .color-0 a:visited{stroke:#F44336;fill:#F44336}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .text-overlay .color-0 text{fill:black}
#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 text.no_data{text-anchor:middle}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .guide.line{fill:none}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .centered{text-anchor:middle}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .title{text-anchor:middle}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .legends .legend text{fill-opacity:1}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis.x text{text-anchor:middle}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis.x:not(.web) text[transform]{text-anchor:start}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis.x:not(.web) text[transform].backwards{text-anchor:end}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis.y text{text-anchor:end}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis.y text[transform].backwards{text-anchor:start}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis.y2 text{text-anchor:start}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis.y2 text[transform].backwards{text-anchor:end}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis .guide.line{stroke-dasharray:4,4}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis .major.guide.line{stroke-dasharray:6,6}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .horizontal .axis.y .guide.line,#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .horizontal .axis.y2 .guide.line,#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .vertical .axis.x .guide.line{opacity:0}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .horizontal .axis.always_show .guide.line,#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .vertical .axis.always_show .guide.line{opacity:1 !important}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis.y .guides:hover .guide.line,#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis.y2 .guides:hover .guide.line,#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis.x .guides:hover .guide.line{opacity:1}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .axis .guides:hover text{opacity:1}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .nofill{fill:none}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .subtle-fill{fill-opacity:.2}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .dot{stroke-width:1px;fill-opacity:1}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .dot.active{stroke-width:5px}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .dot.negative{fill:transparent}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 text,#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 tspan{stroke:none !important}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .series text.active{opacity:1}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .tooltip rect{fill-opacity:.95;stroke-width:.5}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .tooltip text{fill-opacity:1}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .showable{visibility:hidden}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .showable.shown{visibility:visible}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .gauge-background{fill:rgba(229,229,229,1);stroke:none}#chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3 .bg-lines{stroke:rgba(249,249,249,1);stroke-width:2px}</style>
    <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>

  </body>
</html>
</code>```

答:
When you load SVG as an image, in this case via the  tag it is not interactive. This is a general rule and is not flask specific.

SVG in an image has the same capabilities as raster images so that they can be used in the same situations without needing to specially consider their security and privacy implications.

Body:
My flask app has a route that creates a .svg file (using pygal) and renders in in a template.  Within the app, there are no interactive features however, if I open the the same .svg file from my file browser, I get the full interactive features I'm aiming for like labels on hover etc. Any ideas on how to get the interactive hovers working from my route?

{% extends "base.html" %}
{% block content %}

Matrix of Concern for {{ company.companyname }}

{% endblock %}

here is the plot variable passed to the template

<?xml version='1.0' encoding='utf-8'?>
<svg xmlns:xlink="http://www.w3.org/1999/xlink" class="pygal-chart" id="chart-9aa1b551-e893-4065-bf16-b5022bb4e8e3" viewBox="0 0 800 600" xmlns="http://www.w3.org/2000/svg"><defs>

Body:
When you load SVG as an image, in this case via the <img> tag it is not interactive. This is a general rule and is not flask specific.

SVG in an image has the same capabilities as raster images so that they can be used in the same situations without needing to specially consider their security and privacy implications.


来源: stackexchange

问:
Angular 5 downgradeModule not work in hybrid mode
I am trying to change my hybrid app from upgrademodule to downgrademodule, since the $digest fire too much issue.

But I found app is work well, just ng2 components does not work while all things in ng1 works fine.

I had create a plunker: https://plnkr.co/edit/ZaIp5i20fiqH1vfBnZ99?p=info

I add the test component in main.ts:

```<code>angular.module('interestApp').directive('test', downgradeComponent({component: Test}));
</code>```

And add to $stateProvider in script.js:

```<code>$stateProvider
    .state('home', {
      template: '<test></test>',
      url: '/'
    })
</code>```

But when I click the link -> home. nothing happened only  label stay in html.

This works fine in upgrademodule.

Please help me out! Any suggestions or answers are welcomed.

Thanks

答:
Finally, I found out how to use downgrademodule.
If anyone have encountered same questions, please refer to this issue:
https://github.com/angular/angular/issues/20856</p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to change my hybrid app from upgrademodule to downgrademodule, since the $digest fire too much issue.

But I found app is work well, just ng2 components does not work while all things in ng1 works fine.

I had create a plunker: https://plnkr.co/edit/ZaIp5i20fiqH1vfBnZ99?p=info

I add the test component in main.ts:

angular.module('interestApp').directive('test', downgradeComponent({component: Test}));

And add to $stateProvider in script.js:

$stateProvider
    .state('home', {
      template: '<test></test>',
      url: '/'
    })

But when I click the link -> home. nothing happened only  label stay in html.

This works fine in upgrademodule.

Please help me out! Any suggestions or answers are welcomed.

Thanks


问:
ORACLE 12.2 - Invalid string conversion from CLOB fiel using JDBC THIN driver
we have ORACLE database in charset WIN1250 (EE8MSWIN1250). Until ORACLE version 12.1 was everything Ok. But now we have installed ORACLE 12.2 and same data which are read from database contains invalid characters. For example, i show screenshot from DBeaver (It is something like SQLDeveloper - but it universal and for connection to ORACLE have used same THIN driver as we) Firs two pictures are from ORACLE 12.1 (settings and data from table with CLOB field) and second two pictures are from ORACLE 12.2 (settings and same data)

Does anybody know what difference is between 12.1 and 12.2 version? I have read many documents on ORACLE website but no result.

ORACLE 12.1 SETTINGS

Data from ORACLE 12.1 - correct characters

ORACLE 12.2 SETTINGS

Data from ORACLE 12.2 - contains invalid characters

答:
It is issue in ORACLE 12cR2.  It is necessary to apply patch number 27002286.
For my case it was "Patch 27002286: WINDOWS DB BUNDLE PATCH 12.2.0.1.171130"

It will solve the problem.


问:
change button based on previously "liked" status by usr django
I am new to Django and am trying to create a favorite application.
I would like to have the liked button change based on whether or not the user has already favorited the physician.

I pass physicians and liked list to my template but not sure what to do next to extract liked from the array, and not sure if this the most elegant way to approach this.

Any help would be much appreciated!

models.py

```<code>class Physician(models.Model):
    speciality = models.CharField(null=False, blank=False, max_length=30)
    first_name = models.CharField(null=False, blank=False, max_length=50)
    last_name = models.CharField(null=False, blank=False, max_length=50)
    title = models.CharField(null=False, blank=False, max_length=2)
    address1 = models.CharField(null=False, blank=True, max_length=50)
    address2 = models.CharField(null=True, blank=True, max_length=20)
    city = models.CharField(null=False, blank=False, max_length=50)
    state = models.CharField(null=False, blank=False, max_length=2)
    zip = models.CharField(null=False, blank=False, max_length=12)
    likes = models.IntegerField(default=1)

def __str__(self):
    template = '{0.last_name} {0.first_name} {0.speciality}'
    return template.format(self)

class Voter(models.Model):
    user = models.ForeignKey(User)
    physician = models.ForeignKey(Physician)
</code>```

My template is

```<code>    {% if physicians %}
        {% for physician in physicians  %}
            <tr>
            <td>
            <a href="/getmd/{{physician.id}}/">
                {{ physician.last_name }}, {{ physician.first_name }} </a>
            </td>
            <td>{{ physician.state }}</td>
            <td>{{ physician.speciality }}</td>
            <td>{{ physician.id}}</td>
            <td><strong id="like_count{{physician.id}}">{{ physician.likes }}</strong> </td>
            <td>
                {% if user.is_authenticated %}

                    {% if likedalready.physician].liked   %}

                        <button id="alreadyvoted" data-catid="{{physician.id}}" class="likes btn btn-secondary" type="button" title="Already faved">
                        <span class="glyphicon glyphicon-check"></span>
                        Faved
                        </button>
                    {%else%}
                        <button id="{{physician.id}}like" data-catid="{{physician.id}}" class="likes btn btn-primary" type="button" title="Fave Me">
                            <span class="glyphicon glyphicon-thumbs-up"></span>
                            Fav
                        </button>

                    {% endif %}

                {% endif %}

            </td>

            </tr>
        {% endfor %}

    {% else %}
    <p>Sign in to fave</p>
    {% endif %}
</tbody>
</code>```

my views.py
def physicians(request):

```<code>user = User;
liked = False;
args = {}
args.update(csrf(request))
physicians = Physician.objects.all().order_by('last_name')

page = request.GET.get('page', 1)
paginator = Paginator(physicians, 10)
try:
    physicians = paginator.page(page)
except PageNotAnInteger:
    physicians = paginator.page(1)
except EmptyPage:
    physicians = paginator.page(paginator.num_pages)

#Create list of already liked physicians
return_list = []

for physician in physicians:
    liked = Voter.objects.filter(physician_id=physician.id, user_id=request.user.id).exists()
    return_list.append((physician, {'liked': liked}))

args['physicians'] = physicians
return render(request, 'physicians.html', args, {'liked': return_list})
</code>```

答:
I would have a different model, Like:

```<code>class Like(models.Model):
    user = models.ForeignKey(User)
    physician = models.ForeignKey(Physician)
</code>```

This table will have a relation between a user and a physician.
You can know if a user has liked a physician.

```<code>Like.objects.filter(user=user, physician=physician).exists()
</code>```

Delete the relation if the user un-favorites the physician and so on.

To get all the ids of physicians liked by the user, you could do:

```<code>physicians_liked = Like.objects.filter(user=user).values_list('physician', flat=True)
</code>```

And later in your template is as easier as checking:

```<code>{% if physician.id in physicians_liked %}
    ...
{% endif %}
</code>```

Body:
I am new to Django and am trying to create a favorite application.
I would like to have the liked button change based on whether or not the user has already favorited the physician.

I pass physicians and liked list to my template but not sure what to do next to extract liked from the array, and not sure if this the most elegant way to approach this.

Any help would be much appreciated!

models.py

class Physician(models.Model):
    speciality = models.CharField(null=False, blank=False, max_length=30)
    first_name = models.CharField(null=False, blank=False, max_length=50)
    last_name = models.CharField(null=False, blank=False, max_length=50)
    title = models.CharField(null=False, blank=False, max_length=2)
    address1 = models.CharField(null=False, blank=True, max_length=50)
    address2 = models.CharField(null=True, blank=True, max_length=20)
    city = models.CharField(null=False, blank=False, max_length=50)
    state = models.CharField(null=False, blank=False, max_length=2)
    zip = models.CharField(null=False, blank=False, max_length=12)
    likes = models.IntegerField(default=1)

def __str__(self):
    template = '{0.last_name} {0.first_name} {0.speciality}'
    return template.format(self)

class Voter(models.Model):
    user = models.ForeignKey(User)
    physician = models.ForeignKey(Physician)

My template is

    {% if physicians %}
        {% for physician in physicians  %}

                {{ physician.last_name }}, {{ physician.first_name }}

            {{ physician.state }}
            {{ physician.speciality }}
            {{ physician.id}}
            {{ physician.likes }}

                {% if user.is_authenticated %}

                    {% if likedalready.physician].liked   %}

                        <button id="alreadyvoted" data-catid="{{physician.id}}" class="likes btn btn-secondary" type="button" title="Already faved">

                        Faved
                        </button>
                    {%else%}
                        <button id="{{physician.id}}like" data-catid="{{physician.id}}" class="likes btn btn-primary" type="button" title="Fave Me">

                            Fav
                        </button>

                    {% endif %}

                {% endif %}

        {% endfor %}

    {% else %}

Sign in to fave

    {% endif %}

my views.py
def physicians(request):

user = User;
liked = False;
args = {}
args.update(csrf(request))
physicians = Physician.objects.all().order_by('last_name')

page = request.GET.get('page', 1)
paginator = Paginator(physicians, 10)
try:
    physicians = paginator.page(page)
except PageNotAnInteger:
    physicians = paginator.page(1)
except EmptyPage:
    physicians = paginator.page(paginator.num_pages)

#Create list of already liked physicians
return_list = []

for physician in physicians:
    liked = Voter.objects.filter(physician_id=physician.id, user_id=request.user.id).exists()
    return_list.append((physician, {'liked': liked}))

args['physicians'] = physicians
return render(request, 'physicians.html', args, {'liked': return_list})

Body:
I would have a different model, Like:

class Like(models.Model):
    user = models.ForeignKey(User)
    physician = models.ForeignKey(Physician)

This table will have a relation between a user and a physician.
You can know if a user has liked a physician.

Like.objects.filter(user=user, physician=physician).exists()

Delete the relation if the user un-favorites the physician and so on.

To get all the ids of physicians liked by the user, you could do:

physicians_liked = Like.objects.filter(user=user).values_list('physician', flat=True)

And later in your template is as easier as checking:

{% if physician.id in physicians_liked %}
    ...
{% endif %}


问:
How to change Value dynamically in @GET annotation?
I am using Retrofit for download APK file from the server.

Below is code snippet.

```<code>Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Util.APK_DOWNLOAD_URL)
                .build();

        RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);

        Call<ResponseBody> request = retrofitInterface.downloadFile();
        try {

            downloadFile(request.execute().body());

        } catch (IOException e) {

            e.printStackTrace();
            Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();

        }
</code>```

And

```<code>public interface RetrofitInterface {

    @GET("development/filename.apk")
    @Streaming
    Call<ResponseBody> downloadFile();
}
</code>```

But there is problem.

Download APK is always different.
So

How can I set Some public static String in

```<code>@GET(Utils.APK_FILE_NAME)
</code>```

And in my Utils class

```<code>public static String APK_FILE_NAME = ""
</code>```

Currently I am getting

Attribute Value Must be Constant

答:
You can make it dynamic by passing it as parameter instead of declaring it at annotation as in

```<code>public interface RetrofitInterface {
    @Streaming
    Call<ResponseBody> downloadFile(@Url String filename);
}
</code>```

Now you can access it at run time using

```<code> Call<ResponseBody> request = retrofitInterface.downloadFile(Utils.APK_FILE_NAME);
</code>```

Body:
I am using Retrofit for download APK file from the server.

Below is code snippet.

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Util.APK_DOWNLOAD_URL)
                .build();

        RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);

        Call<ResponseBody> request = retrofitInterface.downloadFile();
        try {

            downloadFile(request.execute().body());

        } catch (IOException e) {

            e.printStackTrace();
            Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();

        }

And

public interface RetrofitInterface {

    @GET("development/filename.apk")
    @Streaming
    Call<ResponseBody> downloadFile();
}

But there is problem.

Download APK is always different.
So

How can I set Some public static String in

@GET(Utils.APK_FILE_NAME)

And in my Utils class

public static String APK_FILE_NAME = ""

Currently I am getting

Attribute Value Must be Constant

Body:
You can make it dynamic by passing it as parameter instead of declaring it at annotation as in

public interface RetrofitInterface {
    @Streaming
    Call<ResponseBody> downloadFile(@Url String filename);
}

Now you can access it at run time using

 Call<ResponseBody> request = retrofitInterface.downloadFile(Utils.APK_FILE_NAME);


问:
IIS7 ASPX 404 Error Pages / Server.Transfer and problems with relative paths
I am trying to implement a universal .NET 3.5 ASPX 404 error page that handles both "not found" requests in IIS 7 (classic mode) as well as 404 HttpExceptions thrown in code. I am avoiding customErrors as I want a true 404 return code rather than a redirect.

To do this I have added the following in the system.webserver section of web.config:

```<code><httpErrors>
  <remove statusCode="404" subStatusCode="-1" />
  <error statusCode="404" subStatusCode="-1" path="/virtualdir/errorpages/error404.aspx" responseMode="ExecuteURL" prefixLanguageFilePath="" />
</httpErrors>
</code>```

I have also added a Server.Transfer call in Global.asax Application_Error to capture exceptions thrown in code.

The problem is that the relative paths (such as app_themes as well as any links) are calculated relative to the error page rather than the URL of the original request.

So a request for /virtualdir/fail/fail/fail/fail/fail.html tries to find app_themes at /virtualdir/fail/fail/fail/app_themes.

I think there might be a solution involving Request.RawUrl but I haven't found it yet.

I'm sure I can't be the first person to have this problem but my Google Fu has let me down this time.

EDIT

I've done some investigation and under different circumstances the faulting URL is either maintained in the Request.URL property (desired) or appended to the error page URL as part of the query string in the format (/virtualdir/errorpages/error404.aspx?404;http://host/virtualdir/fail/fail/fail/fail/fail.html).

On my IIS 6 local box, ASPX errors act in the former manner, on the IIS 7 test box, ASPX pages use the latter method.

答:
I can't test it out right now, but have you tried using the tilde to make the URLs app-relative?  eg:</p>

```<code><error statusCode="404" subStatusCode="-1" path="~/errorpages/error404.aspx" responseMode="ExecuteURL" prefixLanguageFilePath="" />
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to implement a universal .NET 3.5 ASPX 404 error page that handles both "not found" requests in IIS 7 (classic mode) as well as 404 HttpExceptions thrown in code. I am avoiding customErrors as I want a true 404 return code rather than a redirect.

To do this I have added the following in the system.webserver section of web.config:

<httpErrors>
  <remove statusCode="404" subStatusCode="-1" />
  <error statusCode="404" subStatusCode="-1" path="/virtualdir/errorpages/error404.aspx" responseMode="ExecuteURL" prefixLanguageFilePath="" />
</httpErrors>

I have also added a Server.Transfer call in Global.asax Application_Error to capture exceptions thrown in code.

The problem is that the relative paths (such as app_themes as well as any links) are calculated relative to the error page rather than the URL of the original request.

So a request for /virtualdir/fail/fail/fail/fail/fail.html tries to find app_themes at /virtualdir/fail/fail/fail/app_themes.

I think there might be a solution involving Request.RawUrl but I haven't found it yet.

I'm sure I can't be the first person to have this problem but my Google Fu has let me down this time.

EDIT

I've done some investigation and under different circumstances the faulting URL is either maintained in the Request.URL property (desired) or appended to the error page URL as part of the query string in the format (/virtualdir/errorpages/error404.aspx?404;http://host/virtualdir/fail/fail/fail/fail/fail.html).

On my IIS 6 local box, ASPX errors act in the former manner, on the IIS 7 test box, ASPX pages use the latter method.

Body:
I can't test it out right now, but have you tried using the tilde to make the URLs app-relative?  eg:

<error statusCode="404" subStatusCode="-1" path="~/errorpages/error404.aspx" responseMode="ExecuteURL" prefixLanguageFilePath="" />


问:
Multiple images are uploading in server folder but only one record is inserted in mysql
The below code is successfully uploading mutiple images to web/images/album but the only one record is updated in mysql.
So while displaying the images only one image is being displayed.
Since I am new to symfony I don't know how to do.
Can any one guide me how to get all the name of the images and insert their names in mysql??

Entity

```<code>class album
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="albumName", type="string", length=255)
 */
private $albumName;

/**
 * @var string
 *
 * @ORM\Column(name="imageName", type="string", length=255)
 */
private $imageName;

/**
 * Get id
 *
 * @return int
 */
public function getId()
{
    return $this->id;
}

/**
 * Set albumName
 *
 * @param string $albumName
 *
 * @return album
 */
public function setAlbumName($albumName)
{
    $this->albumName = $albumName;

    return $this;
}

/**
 * Get albumName
 *
 * @return string
 */
public function getAlbumName()
{
    return $this->albumName;
}

/**
 * Set imageName
 *
 * @param string $imageName
 *
 * @return album
 */
public function setImageName($imageName)
{
    $this->imageName = $imageName;

    return $this;
}

/**
 * Get imageName
 *
 * @return string
 */
public function getImageName()
{
    return $this->imageName;
}
 }
</code>```

Form

```<code>     $builder->add('albumName', TextType::class)
               ->add('imageName', FileType::class, array(
                'multiple' => true,
                'data_class' => null
            ))
               ->add('save', SubmitType::class, array('label' => 'Submit',        'attr' => array('class' => 'btn btn-primary')));
</code>```

Controller

```<code>  public function indexAction(Request $request) {

    $albumMember = new album();

    $galleryView = $this->createForm(imageUpload::class, $albumMember);
    $galleryView->handleRequest($request);
    if ($galleryView->isSubmitted() && $galleryView->isValid()) {

        /**
         * @var UploadedFile $file
         */
        $file = $albumMember->getImageName();
        foreach ($file as $count) {
            $fileName = md5(uniqid()) . '.' . $count->guessExtension();

            $count->move(
                    $this->getParameter('image_directory'), $fileName
            );
            $albumMember->setImageName($fileName);

            $albumName = $galleryView['albumName']->getData();
            $albumMember->setAlbumName($albumName);
        }
        $em = $this->getDoctrine()->getManager();
        $em->persist($albumMember);
        $em->flush();

        $this->addFlash('notice', 'Images Added');
        return $this->redirectToRoute('createGallery');
    }

    return $this->render('admin/galleryView.html.twig', [
                'galleryView' => $galleryView->createView()
    ]);
}
</code>```

答:
That is because you only have one column called image name for each album, when in fact you need to have multiple images. You have to make a manyToOne relationship
https://symfony.com/doc/current/doctrine/associations.html

You make an image class and the album class, with many images mapping to one album, and then you create multiple image objects for each image and set them to said album...

Body:
The below code is successfully uploading mutiple images to web/images/album but the only one record is updated in mysql.
So while displaying the images only one image is being displayed.
Since I am new to symfony I don't know how to do.
Can any one guide me how to get all the name of the images and insert their names in mysql??

Entity

class album
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="albumName", type="string", length=255)
 */
private $albumName;

/**
 * @var string
 *
 * @ORM\Column(name="imageName", type="string", length=255)
 */
private $imageName;

/**
 * Get id
 *
 * @return int
 */
public function getId()
{
    return $this->id;
}

/**
 * Set albumName
 *
 * @param string $albumName
 *
 * @return album
 */
public function setAlbumName($albumName)
{
    $this->albumName = $albumName;

    return $this;
}

/**
 * Get albumName
 *
 * @return string
 */
public function getAlbumName()
{
    return $this->albumName;
}

/**
 * Set imageName
 *
 * @param string $imageName
 *
 * @return album
 */
public function setImageName($imageName)
{
    $this->imageName = $imageName;

    return $this;
}

/**
 * Get imageName
 *
 * @return string
 */
public function getImageName()
{
    return $this->imageName;
}
 }

Form

     $builder->add('albumName', TextType::class)
               ->add('imageName', FileType::class, array(
                'multiple' => true,
                'data_class' => null
            ))
               ->add('save', SubmitType::class, array('label' => 'Submit',        'attr' => array('class' => 'btn btn-primary')));

Controller

  public function indexAction(Request $request) {

    $albumMember = new album();

    $galleryView = $this->createForm(imageUpload::class, $albumMember);
    $galleryView->handleRequest($request);
    if ($galleryView->isSubmitted() && $galleryView->isValid()) {

        /**
         * @var UploadedFile $file
         */
        $file = $albumMember->getImageName();
        foreach ($file as $count) {
            $fileName = md5(uniqid()) . '.' . $count->guessExtension();

            $count->move(
                    $this->getParameter('image_directory'), $fileName
            );
            $albumMember->setImageName($fileName);

            $albumName = $galleryView['albumName']->getData();
            $albumMember->setAlbumName($albumName);
        }
        $em = $this->getDoctrine()->getManager();
        $em->persist($albumMember);
        $em->flush();

        $this->addFlash('notice', 'Images Added');
        return $this->redirectToRoute('createGallery');
    }

    return $this->render('admin/galleryView.html.twig', [
                'galleryView' => $galleryView->createView()
    ]);
}


问:
Invocation of MavenCli fails within a Maven plugin
I've created small util to wrap MavenCli, which generates a new Maven project, using the quickstart archetype.

When executing the Util as a unit test, it is working quite well (just generating an empty Maven project).

Now I want to integrate this small wrapper into a Maven plugin. But when I execute the mojo (within a third Maven project), the invocation of MavenCli fails with exception:

[ERROR] Error executing Maven.
[ERROR] java.util.NoSuchElementException
  role: org.apache.maven.eventspy.internal.EventSpyDispatcher
  roleHint:
[ERROR] Caused by: null
```

<p>The util looks like:</p>

```public void createProject() {
    final MavenCli cli = new MavenCli();
    System.setProperty("maven.multiModuleProjectDirectory", "/usr/share/maven");
    cli.doMain(new String[] { "archetype:generate", "-DgroupId=com.my.company",
            "-DartifactId=hello-world", "-DarchetypeArtifactId=maven-archetype-quickstart",
            "-DinteractiveMode=false" }, "/tmp", System.out, System.out);
}
```

<p>relevant dependency of the util:</p>

```<dependency>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven-embedder</artifactId>
    <version>3.3.9</version>
</dependency>
<dependency>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven-core</artifactId>
    <version>3.3.9</version>
</dependency>
```

<p>The mojo code looks like:</p>

```@Mojo(name = "custommojo", requiresProject = false)
public class CustomMojo extends AbstractMojo {

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        Util.createProject();
    }

}
```

The POM of the mojo just includes dependencies to relevant Maven artifacts (plugin-api, plugin-annotation, etc.) and the util.

The third project I mentioned, is an empty "maven-quickstart" project which have dependency to the mojo-project and a configuration for the mojo to execute in compile phase.

I have no idea why it works in context of unit test, but not in context of a mojo.

Can anybody help?

答:
This works for me inside a custom maven plugin (using Maven 3.5.0):

```<code>ClassRealm classRealm = (ClassRealm) Thread.currentThread().getContextClassLoader();
MavenCli cli = new MavenCli(classRealm.getWorld());
cli.doMain( ... );
</code>```

The plexus Launcher sets the context class loader to its ClassRealm, which has access to the "global" ClassWorld.

Not sure how stable that solution is, but so far looking good.

Used imports:

```<code>import org.codehaus.plexus.classworlds.ClassWorld;
import org.codehaus.plexus.classworlds.realm.ClassRealm;
import org.apache.maven.cli.MavenCli;
</code>```

Body:
I've created small util to wrap MavenCli, which generates a new Maven project, using the quickstart archetype.

When executing the Util as a unit test, it is working quite well (just generating an empty Maven project).

Now I want to integrate this small wrapper into a Maven plugin. But when I execute the mojo (within a third Maven project), the invocation of MavenCli fails with exception:

[ERROR] Error executing Maven.
[ERROR] java.util.NoSuchElementException
  role: org.apache.maven.eventspy.internal.EventSpyDispatcher
  roleHint:
[ERROR] Caused by: null

The util looks like:

public void createProject() {
    final MavenCli cli = new MavenCli();
    System.setProperty("maven.multiModuleProjectDirectory", "/usr/share/maven");
    cli.doMain(new String[] { "archetype:generate", "-DgroupId=com.my.company",
            "-DartifactId=hello-world", "-DarchetypeArtifactId=maven-archetype-quickstart",
            "-DinteractiveMode=false" }, "/tmp", System.out, System.out);
}

relevant dependency of the util:

<dependency>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven-embedder</artifactId>
    <version>3.3.9</version>
</dependency>
<dependency>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven-core</artifactId>
    <version>3.3.9</version>
</dependency>

The mojo code looks like:

@Mojo(name = "custommojo", requiresProject = false)
public class CustomMojo extends AbstractMojo {

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        Util.createProject();
    }

}

The POM of the mojo just includes dependencies to relevant Maven artifacts (plugin-api, plugin-annotation, etc.) and the util.

The third project I mentioned, is an empty "maven-quickstart" project which have dependency to the mojo-project and a configuration for the mojo to execute in compile phase.

I have no idea why it works in context of unit test, but not in context of a mojo.

Can anybody help?

Body:
This works for me inside a custom maven plugin (using Maven 3.5.0):

ClassRealm classRealm = (ClassRealm) Thread.currentThread().getContextClassLoader();
MavenCli cli = new MavenCli(classRealm.getWorld());
cli.doMain( ... );

The plexus Launcher sets the context class loader to its ClassRealm, which has access to the "global" ClassWorld.

Not sure how stable that solution is, but so far looking good.

Used imports:

import org.codehaus.plexus.classworlds.ClassWorld;
import org.codehaus.plexus.classworlds.realm.ClassRealm;
import org.apache.maven.cli.MavenCli;


问:
Check Empty System.IO.FileStream is empty
What i am trying to do is return a message box whenever a user click the button without uploading an image into the FileStream.

```<code> FileStream stream = new FileStream(imgLocation, FileMode.Open, FileAccess.Read);
        BinaryReader brs = new BinaryReader(stream);
        images = brs.ReadBytes((int)stream.Length);

        SqlCommand cmd = new SqlCommand(sql, con);
        cmd.Parameters.Add(new SqlParameter("@images", images));

        MessageBox.Show("Upload complete");
        cmd.ExecuteNonQuery();
        con.Close();
</code>```

The program shows the "empty path name is not legal" error. How do I check for empty path name and return a message box?

答:
You could do multiple checks here:

Check if string is empty:

```<code>if (string.IsNullOrEmpty(imgLocation)) MessageBox.Show("Invalid path");
</code>```

After check you can load the location in FileInfo class:

```<code>FileInfo file = new FileInfo(path);
</code>```

then check multiple things:

```<code>   if(file.Exists) //Check file's existence
   if(file.Length == 0) //Check if file is not empty
</code>```

before operating on the file.

You can also check: (if you want to skip file.Length)

```<code>    FileStream stream = new FileStream(imgLocation, FileMode.Open, FileAccess.Read);
    if(stream.Length==0) //check if stream is empty
</code>```

Body:
What i am trying to do is return a message box whenever a user click the button without uploading an image into the FileStream.

 FileStream stream = new FileStream(imgLocation, FileMode.Open, FileAccess.Read);
        BinaryReader brs = new BinaryReader(stream);
        images = brs.ReadBytes((int)stream.Length);

        SqlCommand cmd = new SqlCommand(sql, con);
        cmd.Parameters.Add(new SqlParameter("@images", images));

        MessageBox.Show("Upload complete");
        cmd.ExecuteNonQuery();
        con.Close();

The program shows the "empty path name is not legal" error. How do I check for empty path name and return a message box?

Body:
You could do multiple checks here:

Check if string is empty:

if (string.IsNullOrEmpty(imgLocation)) MessageBox.Show("Invalid path");

After check you can load the location in FileInfo class:

FileInfo file = new FileInfo(path);

then check multiple things:

   if(file.Exists) //Check file's existence
   if(file.Length == 0) //Check if file is not empty

before operating on the file.

You can also check: (if you want to skip file.Length)

    FileStream stream = new FileStream(imgLocation, FileMode.Open, FileAccess.Read);
    if(stream.Length==0) //check if stream is empty


问:
Copy the values from variable cell values excel macro
Please find the snapshot attched here with,

Snapshot show the A1 cell values varies from 1 to 19,

C1 contains the value which is vary fron number to number, i need row and columns of complete numbers and values.

like E and F columns indicate ( i have entered manually)

答:
Enter this formula into cel C1:

```<code>=VLOOKUP($A$1,$E$1:$F$19,2,FALSE)
</code>```

It will look for the number you entered in A1 in column E, and return the corresponding value from column F.

Body:
Enter this formula into cel C1:

=VLOOKUP($A$1,$E$1:$F$19,2,FALSE)

It will look for the number you entered in A1 in column E, and return the corresponding value from column F.


问:
Executing a function in backgroud/seperate thread in angular 2 application
I am developing an application and I have below requirement. from my angular application I am making REST call to server which will trigger some job on the server and return status as "Job Started". After that I want to keep checking status of job every 10 seconds, for which server provides API that return status of job.

Now my requirement is I need to call this job status API every 10 seconds, but in background, that means user should able to perform other tasks on application.

How would I achieve this?

Any help with some example would be really helpful.

答:
You can use RxJS observable with timer so that you control the timer with ease. If you don't destroy the timer on page unload, API will be called after page destroy also. In the component file API will be called for every 10 seconds till the variable alive is true and we are setting that to false on destroy to stop the timer.

Working demo

Component file

```<code>import { Component } from '@angular/core';
import { AppTestService } from './app-test.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/takeWhile';
import 'rxjs/add/observable/timer'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers:[ AppTestService ]
})
export class AppComponent  {
  name = 'Angular 5';
  alive = true;

  constructor(private appTest : AppTestService) {
    Observable.timer(0,10000)
    .takeWhile(() => this.alive) // only fires when component is alive
    .subscribe(() => {
      this.appTest.getData().subscribe(data=> {
        console.log(data);
      })
    });
  }

  ngOnDestroy(){
    this.alive = false; // switches your IntervalObservable off
  }
}
</code>```

Service

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class AppTestService {

  constructor(private http:HttpClient) { }

  getData(){
    return this.http.get('https://jsonplaceholder.typicode.com/users/1');
  }

}
</code>```

Body:
You can use RxJS observable with timer so that you control the timer with ease. If you don't destroy the timer on page unload, API will be called after page destroy also. In the component file API will be called for every 10 seconds till the variable alive is true and we are setting that to false on destroy to stop the timer.

Working demo

Component file

import { Component } from '@angular/core';
import { AppTestService } from './app-test.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/takeWhile';
import 'rxjs/add/observable/timer'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers:[ AppTestService ]
})
export class AppComponent  {
  name = 'Angular 5';
  alive = true;

  constructor(private appTest : AppTestService) {
    Observable.timer(0,10000)
    .takeWhile(() => this.alive) // only fires when component is alive
    .subscribe(() => {
      this.appTest.getData().subscribe(data=> {
        console.log(data);
      })
    });
  }

  ngOnDestroy(){
    this.alive = false; // switches your IntervalObservable off
  }
}

Service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class AppTestService {

  constructor(private http:HttpClient) { }

  getData(){
    return this.http.get('https://jsonplaceholder.typicode.com/users/1');
  }

}


问:
Can you get this same Java SHA-1 in PHP please?
I find myself in a need to change website platforms from Java to PHP but I'd like to keep all my user's passwords...

I had this code do the password hashing prior to writting the hashed value as the password to the website:

```<code>MessageDigest md = null;
md = MessageDigest.getInstance("SHA");
md.update(plaintext.getBytes("UTF-8"));
byte raw[] = md.digest();
hash = new Base64().encodeToString(raw).replaceAll("\n", "").replaceAll("\r", "");
</code>```

I think the Java code did SHA-1 hashing of the password but just prior to that it was byte encoded to UTF-8 and afterwards it was Base64 encoded.

I'd like to have a PHP code do the same, i.e. return the same value of a hash for the same password as in Java, only it seems that the PHP code doing SHA-1 hashing I have won't return the same SHA(-1, not Base64 encoded, I think?) value when compared to a Java Base64 decoded value of the hash...could it have something to do with the fact that my passwords in PHP are not UTF-8 byte encoded first (and how can I do that in PHP) please?

p.s.

Another strange thing...my passwords in Java are all 28characters long (usually something like this rnwn4zTNgH30l4pP8V05lRVGmF4=)...but the Base64().decode(hash) value of those password hashes is 10 characters long (an example [B@14e1f2b).

I thought Base64 did an additional 1 character to each 3 charters (28 or 27, excluding the padding = charter, is much more that a third larger than those 10 charcters) so am I doing the decoding call wrong somehow maybe???

And on top of all that the SHA-1 password hashed values in PHP are 40 characters long (in a UTF-8 mysql database) like so dd94709528bb1c83d08f3088d4043f4742891f4f?

答:
[B@14e1f2b is definitely not a hash. It's a result of implicit conversion from byte[] to String.

It looks like you do something like this:

```<code>String decodedHash = Base64().decode(hash); // Produces [B@14e1f2b
</code>```

However, the correct representation of the hash is a byte array:

```<code>byte[] decodedHash = Base64().decode(hash);
</code>```

Body:
I find myself in a need to change website platforms from Java to PHP but I'd like to keep all my user's passwords...

I had this code do the password hashing prior to writting the hashed value as the password to the website:

MessageDigest md = null;
md = MessageDigest.getInstance("SHA");
md.update(plaintext.getBytes("UTF-8"));
byte raw[] = md.digest();
hash = new Base64().encodeToString(raw).replaceAll("\n", "").replaceAll("\r", "");

I think the Java code did SHA-1 hashing of the password but just prior to that it was byte encoded to UTF-8 and afterwards it was Base64 encoded.

I'd like to have a PHP code do the same, i.e. return the same value of a hash for the same password as in Java, only it seems that the PHP code doing SHA-1 hashing I have won't return the same SHA(-1, not Base64 encoded, I think?) value when compared to a Java Base64 decoded value of the hash...could it have something to do with the fact that my passwords in PHP are not UTF-8 byte encoded first (and how can I do that in PHP) please?

p.s.

Another strange thing...my passwords in Java are all 28characters long (usually something like this rnwn4zTNgH30l4pP8V05lRVGmF4=)...but the Base64().decode(hash) value of those password hashes is 10 characters long (an example [B@14e1f2b).

I thought Base64 did an additional 1 character to each 3 charters (28 or 27, excluding the padding = charter, is much more that a third larger than those 10 charcters) so am I doing the decoding call wrong somehow maybe???

And on top of all that the SHA-1 password hashed values in PHP are 40 characters long (in a UTF-8 mysql database) like so dd94709528bb1c83d08f3088d4043f4742891f4f?

Body:
[B@14e1f2b is definitely not a hash. It's a result of implicit conversion from byte[] to String.

It looks like you do something like this:

String decodedHash = Base64().decode(hash); // Produces [B@14e1f2b

However, the correct representation of the hash is a byte array:

byte[] decodedHash = Base64().decode(hash);


问:
How can I use C++ boost geometry to create ring (donut) from two polgons?

I am trying to calculate the differences between 2 polygons (in fact, rectilinear shapes for simplicity). For example, shape1 has point list {0 0, 100, 0, 100 100, 0 100} and shape2 has point list {25 25, 75 25, 75 75, 25 75}.
So by concept, I expect "shape1 - shape2" will provide me with 4 rectangular boxes, which can make a ring or donut shape.  I don't know how to achieve that, but I found "boost" library online and tried it like this:

```<code>#include <iostream>
#include <list>

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>

#include <boost/foreach.hpp>

int main()
{
    typedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;

    polygon green, blue;

    boost::geometry::read_wkt( "POLYGON((0 0 100 0 100 100 0 100))", green);

    boost::geometry::read_wkt( "POLYGON((25 25 75 22 75 75 25 75))", blue);

    std::list<polygon> output;
    boost::geometry::difference(green, blue, output);

    int i = 0;
    std::cout << "green - blue:" << std::endl;
    BOOST_FOREACH(polygon const& p, output)
    {
        std::cout << i++ << ": " << boost::geometry::area(p) << std::endl;
    }

    output.clear();
    boost::geometry::difference(blue, green, output);

    i = 0;
    std::cout << "blue - green:" << std::endl;
    BOOST_FOREACH(polygon const& p, output)
    {
        std::cout << i++ << ": " << boost::geometry::area(p) << std::endl;
    }

    return 0;
}
</code>```

However, nothing was printed out ... My plan was to figure out a way to convert the output results to rectangular boxes {0 0 100 0 100 25 0 25} {0 75 100 75 100 100 0 100} {0 25 25 25 25 75 0 75}  and {75 25 100 25 100 75 75 75},but I feel frustrated that the above code not print out anything at all.

Could anyone give me some guidance?
I have attached a picture showing what I want to do. In fact, I have already had all the point coordinates to represent this donut, so maybe I can skip "difference() function" ?  If this is the case, the difficult part will be to convert the donut into rectangular segments. (Let us assume all polygons here are rectilinear shapes.)
Thanks.

答:
The other answer will end your frustration/confusion, this answer will make you more productive :)

And, yes, you can skip the difference function:

```<code>bg::read_wkt("POLYGON((0 0 0 100 100 100 100 0 0 0) (25 25 75 22 75 75 25 75 25 25))", donut);
</code>```

This specifies the inner ring (in reverse orientation!).

Result:

Generated by this program:

Live On Coliru

```<code>#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>

#include <iostream>
#include <fstream>

namespace bg = boost::geometry;

int main() {
    typedef bg::model::d2::point_xy<double> point;
    typedef bg::model::polygon<point> polygon;

    polygon donut;
    bg::read_wkt("POLYGON((0 0 0 100 100 100 100 0 0 0) (25 25 75 22 75 75 25 75 25 25))", donut);

    std::ofstream svg("output.svg");
    boost::geometry::svg_mapper<point> mapper(svg, 400, 400);
    mapper.add(donut);

    mapper.map(donut, "fill-opacity:0.5;fill:rgb(0,0,153);stroke:rgb(0,0,200);stroke-width:2");
}
</code>```

Body:
I am trying to calculate the differences between 2 polygons (in fact, rectilinear shapes for simplicity). For example, shape1 has point list {0 0, 100, 0, 100 100, 0 100} and shape2 has point list {25 25, 75 25, 75 75, 25 75}.
So by concept, I expect "shape1 - shape2" will provide me with 4 rectangular boxes, which can make a ring or donut shape.  I don't know how to achieve that, but I found "boost" library online and tried it like this:

#include <iostream>
#include <list>

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>

#include <boost/foreach.hpp>

int main()
{
    typedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;

    polygon green, blue;

    boost::geometry::read_wkt( "POLYGON((0 0 100 0 100 100 0 100))", green);

    boost::geometry::read_wkt( "POLYGON((25 25 75 22 75 75 25 75))", blue);

    std::list<polygon> output;
    boost::geometry::difference(green, blue, output);

    int i = 0;
    std::cout << "green - blue:" << std::endl;
    BOOST_FOREACH(polygon const& p, output)
    {
        std::cout << i++ << ": " << boost::geometry::area(p) << std::endl;
    }

    output.clear();
    boost::geometry::difference(blue, green, output);

    i = 0;
    std::cout << "blue - green:" << std::endl;
    BOOST_FOREACH(polygon const& p, output)
    {
        std::cout << i++ << ": " << boost::geometry::area(p) << std::endl;
    }

    return 0;
}

However, nothing was printed out ... My plan was to figure out a way to convert the output results to rectangular boxes {0 0 100 0 100 25 0 25} {0 75 100 75 100 100 0 100} {0 25 25 25 25 75 0 75}  and {75 25 100 25 100 75 75 75},but I feel frustrated that the above code not print out anything at all.

Could anyone give me some guidance?
I have attached a picture showing what I want to do. In fact, I have already had all the point coordinates to represent this donut, so maybe I can skip "difference() function" ?  If this is the case, the difficult part will be to convert the donut into rectangular segments. (Let us assume all polygons here are rectilinear shapes.)
Thanks.

Body:
The other answer will end your frustration/confusion, this answer will make you more productive :)

And, yes, you can skip the difference function:

bg::read_wkt("POLYGON((0 0 0 100 100 100 100 0 0 0) (25 25 75 22 75 75 25 75 25 25))", donut);

This specifies the inner ring (in reverse orientation!).

Result:

Generated by this program:

Live On Coliru

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>

#include <iostream>
#include <fstream>

namespace bg = boost::geometry;

int main() {
    typedef bg::model::d2::point_xy<double> point;
    typedef bg::model::polygon<point> polygon;

    polygon donut;
    bg::read_wkt("POLYGON((0 0 0 100 100 100 100 0 0 0) (25 25 75 22 75 75 25 75 25 25))", donut);

    std::ofstream svg("output.svg");
    boost::geometry::svg_mapper<point> mapper(svg, 400, 400);
    mapper.add(donut);

    mapper.map(donut, "fill-opacity:0.5;fill:rgb(0,0,153);stroke:rgb(0,0,200);stroke-width:2");
}


问:
post value from one page to multiple page in php
referral-page.php

I have submitted email data and store in DB and then goto Primary page

```<code><form action="store-db.php">
   <input type="text" name="email" />
   <input type="submit" value="Submit" />
</form>
</code>```

I have stored email data in DB using ajax ( this was completed ). but I want to post email value to primary-page.php

primary-page.php  ( email field should be prefilled if I come from referral otherwise it should be empty value )

```<code><form action="thank-you.php">
    <input type="text" name="name" value="" />
    <input type="text" name="email" value="<?php echo !empty($_POST['email']) ? $_POST['email'] : ''; ?>" />
    <input type="submit" value="Submit" />
</form>
</code>```

答:
After the ajax call to the DB has succeeded, why not just redirect to the thank you page, sending the email address in the query string ($_GET)?

Or maybe better: just submit to the php page and do the db storage there, before outputting "thank you" or "error"?

Body:
referral-page.php

I have submitted email data and store in DB and then goto Primary page

<form action="store-db.php">
   <input type="text" name="email" />
   <input type="submit" value="Submit" />
</form>

I have stored email data in DB using ajax ( this was completed ). but I want to post email value to primary-page.php

primary-page.php  ( email field should be prefilled if I come from referral otherwise it should be empty value )

<form action="thank-you.php">
    <input type="text" name="name" value="" />
    <input type="text" name="email" value="<?php echo !empty($_POST['email']) ? $_POST['email'] : ''; ?>" />
    <input type="submit" value="Submit" />
</form>


问:
Learning Python from Ruby; Differences and Similarities
I know Ruby very well. I believe that I may need to learn Python presently. For those who know both, what concepts are similar between the two, and what are different?

I'm looking for a list similar to a primer I wrote for Learning Lua for JavaScripters: simple things like whitespace significance and looping constructs; the name of nil in Python, and what values are considered "truthy"; is it idiomatic to use the equivalent of map and each, or are mumble somethingaboutlistcomprehensions mumble the norm?

If I get a good variety of answers I'm happy to aggregate them into a community wiki. Or else  you all can fight and crib from each other to try to create the one true comprehensive list.

Edit: To be clear, my goal is "proper" and idiomatic Python. If there is a Python equivalent of inject, but nobody uses it because there is a better/different way to achieve the common functionality of iterating a list and accumulating a result along the way, I want to know how you do things. Perhaps I'll update this question with a list of common goals, how you achieve them in Ruby, and ask what the equivalent is in Python.

答:
My suggestion: Don't try to learn the differences.  Learn how to approach the problem in Python.  Just like there's a Ruby approach to each problem (that works very well givin the limitations and strengths of the language), there's a Python approach to the problem.  they are both different.  To get the best out of each language, you really should learn the language itself, and not just the "translation" from one to the other.

Now, with that said, the difference will help you adapt faster and make 1 off modifications to a Python program.  And that's fine for a start to get writing.  But try to learn from other projects the why behind the architecture and design decisions rather than the how behind the semantics of the language...


问:
why can't "_all" field be enabled in ElasticSearch 6.0?
I have the index "index" and type "fulltext" created, but when I was trying to enable "_all" field with (as suggested by https://www.elastic.co/guide/en/elasticsearch/reference/6.0/mapping-all-field.html):

```<code>curl -XPUT 'localhost:9200/index?pretty' -H 'Content-Type: application/json' -d'
{
  "mapping": {
    "fulltext": {
      "_all": {
        "enabled": true
      }
    }
  }
}
'
</code>```

The message I got was as follows:

```<code>{
  "error" : {
    "root_cause" : [
      {
        "type" : "illegal_argument_exception",
        "reason" : "unknown setting [index.mapping.fulltext._all.enabled] please check that any required plugins are installed, or check the breaking changes documentation for removed settings"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "unknown setting [index.mapping.fulltext._all.enabled] please check that any required plugins are installed, or check the breaking changes documentation for removed settings"
  },
  "status" : 400
}
</code>```

How can I correct it? Thanks.

答:
You can’t change that anymore in 6.0.
Basically the field does not exist anymore but the feature is still there but implemented differently. So you don’t need to care about it anymore.

That’s what the first lines of documentation you linked to are saying:

_all may no longer be enabled for indices created in 6.0+, use a custom field and the mapping copy_to parameter

Body:
I have the index "index" and type "fulltext" created, but when I was trying to enable "_all" field with (as suggested by https://www.elastic.co/guide/en/elasticsearch/reference/6.0/mapping-all-field.html):

curl -XPUT 'localhost:9200/index?pretty' -H 'Content-Type: application/json' -d'
{
  "mapping": {
    "fulltext": {
      "_all": {
        "enabled": true
      }
    }
  }
}
'

The message I got was as follows:

{
  "error" : {
    "root_cause" : [
      {
        "type" : "illegal_argument_exception",
        "reason" : "unknown setting [index.mapping.fulltext._all.enabled] please check that any required plugins are installed, or check the breaking changes documentation for removed settings"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "unknown setting [index.mapping.fulltext._all.enabled] please check that any required plugins are installed, or check the breaking changes documentation for removed settings"
  },
  "status" : 400
}

How can I correct it? Thanks.


问:
How to open a text file in SSH virtual machine in Google cloud platform?
How can I open a text file in google cloud platform? The script says I have to agree to a text file called EULA, open the text file on a text editor and change the last form eula=false to eula=true. How can I accomplish this?

```<code>a_castro4@mc-server:/home/minecraft$ sudo java -Xms1G -Xmx7G -d64 -jar
minecraft_server.1.11.2.jar nogui
[01:05:30] [Server thread/INFO]: Starting minecraft server version 1.11.2
[01:05:30] [Server thread/INFO]: Loading properties
[01:05:30] [Server thread/INFO]: You need to agree to the EULA in order to
run the server. Go to eula.txt for more
info.
[01:05:30] [Server thread/INFO]: Stopping server
a_castro4@mc-server:/home/minecraft$
</code>```

One file is the server.properties which you could edit to change the default behavior of the minecraft server.
Use your favorite text editor to edit the eula.txt file. Remember to use sudo so you can save the edit. Change the last line that says eula=false to eula=true.

答:
You can easily create and edit files using the nano or vim tools. If you are new to this environment, I would suggest you to go with nano, which should be easier to understand for beginners.

A set of simple steps to edit the file you want is:

Go to the directory where your file is located.

Write the command sudo nano eula.txt in the terminal; sudo will ensure that you have permissions for editing the file.

Move to the end of the file with your arrow keys and write the change in your file.

Press Ctrl + X to exit the application, then Y to save changes.

Your file should be edited right now.

Body:
How can I open a text file in google cloud platform? The script says I have to agree to a text file called EULA, open the text file on a text editor and change the last form eula=false to eula=true. How can I accomplish this?

a_castro4@mc-server:/home/minecraft$ sudo java -Xms1G -Xmx7G -d64 -jar
minecraft_server.1.11.2.jar nogui
[01:05:30] [Server thread/INFO]: Starting minecraft server version 1.11.2
[01:05:30] [Server thread/INFO]: Loading properties
[01:05:30] [Server thread/INFO]: You need to agree to the EULA in order to
run the server. Go to eula.txt for more
info.
[01:05:30] [Server thread/INFO]: Stopping server
a_castro4@mc-server:/home/minecraft$

One file is the server.properties which you could edit to change the default behavior of the minecraft server.
Use your favorite text editor to edit the eula.txt file. Remember to use sudo so you can save the edit. Change the last line that says eula=false to eula=true.


问:
Find an entity which use a class Id
To find an object from  entity with primary key we use em.find(Person.class, <Id>).

I'm using JPA EclipseLink and I have a Person entity which has a composite primary key(@classId),

the Person entity:

```<code>@Entity
    @IdClass(PersonId.class)
    public class Person {

@Id
private int id;

@Id
private String name;

public String getName() {
    return name;
}

// getters & setters
}
</code>```

and the PersonID:

```<code>public class PersonId implements Serializable {

private static final long idVersionUID = 343L;

private int id;
private String name;

// must have a default construcot
public PersonId() {

}

public PersonId(int id, String name) {
    this.id = id;
    this.name = name;
}

//getters & setters
//hachCode & equals
}
</code>```

How to use em.find to get a Person object?

答:
I found the solution :</p>
```<code>    PersonId personeId = new PersonId(33, "Jhon");

    Person persistedPerson = em.find(Person.class, personeId);

    System.out.println(persistedPerson.getID() + " - " + persistedPerson.getName());
</code>```

ContentLicense: CC BY-SA 4.0

Title: Find an entity which use a class Id

Body:
To find an object from  entity with primary key we use em.find(Person.class, <Id>).

I'm using JPA EclipseLink and I have a Person entity which has a composite primary key(@classId),

the Person entity:

@Entity
    @IdClass(PersonId.class)
    public class Person {

@Id
private int id;

@Id
private String name;

public String getName() {
    return name;
}

// getters & setters
}

and the PersonID:

public class PersonId implements Serializable {

private static final long idVersionUID = 343L;

private int id;
private String name;

// must have a default construcot
public PersonId() {

}

public PersonId(int id, String name) {
    this.id = id;
    this.name = name;
}

//getters & setters
//hachCode & equals
}

How to use em.find to get a Person object?

Body:
I found the solution :

    PersonId personeId = new PersonId(33, "Jhon");

    Person persistedPerson = em.find(Person.class, personeId);

    System.out.println(persistedPerson.getID() + " - " + persistedPerson.getName());


问:
Pointer to std::vector, pointer declaration
Are there any differences between these two pointer declarations to pass a std::vector to a function that has a special signature that I don't really understand?

```<code>libraryFunction (int numSamples, double* const* arrayOfChannels) {
  //things
}

std::vector<double> theVectorA = {11, 22, 33, 44};
double * p_VecA[1];
p_VecA[0] = theVectorA.data();
libraryFunction(theVectorA.size(), p_VecA);

std::vector<double> theVectorB = {55, 66, 77};
double * p_VecB = theVectorB.data();
libraryFunction(theVectorB.size(), p_VecB);
</code>```

What are the differences between p_VecA and p_VecB?

Can you explain the function signature? I don't understand the last part.

答:
p_vecA is an array of pointers with size 1

```<code>double * p_VecA[1];
</code>```

p_VecB is pointer

```<code>double * p_VecB = theVectorB.data();
</code>```

Can be written as

```<code>double * p_VecB;
p_VecB = theVectorB.data();
</code>```

Body:
Are there any differences between these two pointer declarations to pass a std::vector to a function that has a special signature that I don't really understand?

libraryFunction (int numSamples, double* const* arrayOfChannels) {
  //things
}

std::vector<double> theVectorA = {11, 22, 33, 44};
double * p_VecA[1];
p_VecA[0] = theVectorA.data();
libraryFunction(theVectorA.size(), p_VecA);

std::vector<double> theVectorB = {55, 66, 77};
double * p_VecB = theVectorB.data();
libraryFunction(theVectorB.size(), p_VecB);

What are the differences between p_VecA and p_VecB?

Can you explain the function signature? I don't understand the last part.

Body:
p_vecA is an array of pointers with size 1

double * p_VecA[1];

p_VecB is pointer

double * p_VecB = theVectorB.data();

Can be written as

double * p_VecB;
p_VecB = theVectorB.data();


问:
The current display adapter does not meet the emulator requirements to run XNA Framework applications
hi *
I create a Windows Phone Game (4.0) application in Visual Studio 2010 and Win7. My application build successfully but when run it, throw an error that says:

"The current display adapter does not meet the emulator requirements to run XNA Framework applications."

What should I do, to remove this error?

答:
Thanks for your thread. Followed the links ...
Ended up downloading the latest DirectX Version Dated: 11/30/2010.
It cleared up the error message.
Given the time that past this may not be of any help, as you've probably already worked around it.

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=2da43d38-db71-4c1b-bc6a-9b6652cd92a3&displayLang=en

Version:9.29.1973
Date Published:11/30/2010


问:
passing value to img src with spaces and quotation marks
img src = '$imagepath'

This command is in a loop and some of the paths have single quotation marks in name and thats what creates the problem as it truncates the path after the first quotation mark

I tried using {imagepath} but that neglects the words after the first space.

Similarly,

some start html tags "img src =".$imagepath."height='300' width ='300' onclick='window.open(this.src)"

This too neglects the words after first space.

I also tried urlencode and decode and that doesn't work as well

答:
The problem is not part of PHP but pure HTML.

HTML tag attributes have to be encapsulated within quotation marks ' or " and there must be a space character between each attribute.

If you need to use the same encapsulating character, ie ' or " as part of attribute value then it must be encoded, in PHP using urlencode() http://php.net/manual/en/function.urlencode.php

The src attribute must be present, and must contain a valid non-empty URL potentially surrounded by spaces referencing a non-interactive, optionally animated, image resource that is neither paged nor scripted. The img element and
 valid non-empty URL potentially surrounded by spaces


问:
Inserting data into table with a large number of columns
I have a table with about 200 or so columns. I want to know the best way to insert this data into MySQL using Jooq.

Right now, I am using POJOs across my program to handle/transform my data. My problem is that, as far as I understand it, if I want to create a POJO I have to call .set{column name}. There is no generic .set method I can call on my POJO such as: .set(column, value).

Before anyone says it, I would be happy doing it the long way for 200 columns but I have about ten more tables of similar size that I would also need to do this for so this would be difficult to maintain.

So my question is two-fold:

Is my understanding of the POJO api correct? I have looked through the config and I couldn't see anything that might help me.

What is the easiest way to do this outside of POJOs? My best idea at the moment is using Records

```<code>Record test = conn.newRecord(table);
Field<Object> field1 = field(name(table,col));
test.set(field1, 10);
</code>```

But I don't know if this is the correct way to do it (and if this is going to cause me grief down the line).

答:
If by "POJO" you mean jOOQ's generated POJOs, then yes indeed, there is no set(column, value) method as that would not be something you'd expect from a classic POJO (or JavaBean). jOOQ's records (as you've noticed) however, do have these methods. Records also support setting many values at once, e.g. from a Map, or from an array. See the Record.from(Object) method for details.

In other words, your usage of records is idiomatic for jOOQ. I don't see how this will cause "grief down the line".

Body:
I have a table with about 200 or so columns. I want to know the best way to insert this data into MySQL using Jooq.

Right now, I am using POJOs across my program to handle/transform my data. My problem is that, as far as I understand it, if I want to create a POJO I have to call .set{column name}. There is no generic .set method I can call on my POJO such as: .set(column, value).

Before anyone says it, I would be happy doing it the long way for 200 columns but I have about ten more tables of similar size that I would also need to do this for so this would be difficult to maintain.

So my question is two-fold:

Is my understanding of the POJO api correct? I have looked through the config and I couldn't see anything that might help me.

What is the easiest way to do this outside of POJOs? My best idea at the moment is using Records

Record test = conn.newRecord(table);
Field<Object> field1 = field(name(table,col));
test.set(field1, 10);

But I don't know if this is the correct way to do it (and if this is going to cause me grief down the line).


问:
react-native-fb sdk com.android.support dependency error
```<code> > A problem occurred configuring project ':react-native-fbsdk'.
  > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
     > Could not find com.android.support:appcompat-v7:27.0.1.
       Searched in the following locations:
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           file:/<location_to_app>/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
       Required by:
           newPtMobile:react-native-fbsdk:unspecified
</code>```

This issue started happening this morning when running react-native run-android without making any changes to the code or adding new packages, it was working fine untill now!

"react-native":"0.50.3", "react-native-fbsdk":"0.6.3"

I can see that I am missing android support libraries in my sdk/extras/android/m2repository/com/android/support subfolders, all the subfolders have the 26.0.0-alpha1 folder as the last one.
I already tried removing support repository and installing again through android studio and downloading the latest android_m2repository manually but the folders are still missing.

What I am having trouble understanding is why google's maven repository (https://dl.google.com/dl/android/maven2/index.html) states that under for example m2repository/com/android/support/appcompat-v7 I should have a folder named 27.0.2 (along with some previous versions which are also missing) but even in the latest android_m2repository which they offer it is also missing!

https://dl.google.com/android/repository/android_m2repository_r48.zip

答:
I see that another thread was open on this very same issue:  getting error when run react-native run-android

The solution recommended there is close to Sutani one, that is editing node_modules/react-native-fbsdk/android/build.gradle
and adding

compile('com.facebook.android:facebook-android-sdk:4.28.0')

It seems not to be a regression introduced by react-native-fbsdk but by Google Android libraries but I am not 100% clear about it.

Body:
 > A problem occurred configuring project ':react-native-fbsdk'.
  > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
     > Could not find com.android.support:appcompat-v7:27.0.1.
       Searched in the following locations:
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           file:/<location_to_app>/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
       Required by:
           newPtMobile:react-native-fbsdk:unspecified

This issue started happening this morning when running react-native run-android without making any changes to the code or adding new packages, it was working fine untill now!

"react-native":"0.50.3", "react-native-fbsdk":"0.6.3"

I can see that I am missing android support libraries in my sdk/extras/android/m2repository/com/android/support subfolders, all the subfolders have the 26.0.0-alpha1 folder as the last one.
I already tried removing support repository and installing again through android studio and downloading the latest android_m2repository manually but the folders are still missing.

What I am having trouble understanding is why google's maven repository (https://dl.google.com/dl/android/maven2/index.html) states that under for example m2repository/com/android/support/appcompat-v7 I should have a folder named 27.0.2 (along with some previous versions which are also missing) but even in the latest android_m2repository which they offer it is also missing!

https://dl.google.com/android/repository/android_m2repository_r48.zip


问:
Getting an exception like "Items collection must be empty before using ItemsSource." while trying to set the itemsource of a child DataGrid in WPF
I have a Datagrid and another DataGrid nested inside the parent DataGrid. I need to set the ItemSource of the child DataGrid as a property of the parent DataContext. I already tried to use RelativeSource for the child itemsource to get the parent datacontext.

xaml code

```<code><DataGrid Grid.Row ="1" x:Name="Grid1" ItemsSource="{Binding Path=md,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False">
    <DataGrid.Columns>
      <DataGridTextColumn Header="Categogy" Width="100"  Binding="{Binding Path =CateName,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
      <DataGridTemplateColumn Header="Characterictics" Width="300">
           <DataGridTemplateColumn.CellTemplate>
             <DataTemplate>
               <DataGrid ItemsSource="{Binding DataContext.list, RelativeSource={RelativeSource AncestorType=DataGrid}}">
                 <DataGridTextColumn Binding="{Binding DataContext.list.Name, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
               </DataGrid>
             </DataTemplate>
           </DataGridTemplateColumn.CellTemplate>
      </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
</code>```

ViewModel

```<code>Model m = new Model();
m.CateName = "CategoryName";
m.list.Add(new Characteristics() { Name="XX", Value="00"});
m.list.Add(new Characteristics() { Name = "XX", Value = "00" });
m.list.Add(new Characteristics() { Name = "XX", Value = "00" });
md.Add(m);

Model m1 = new Model();
m1.CateName = "CategoryName1";
m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
md.Add(m1);

list = new ObservableCollection<Characteristics>();
list.Add(new Characteristics() { Name = "XX", Value = "00" });
list.Add(new Characteristics() { Name = "XX", Value = "00" });
</code>```

The Characteristics class has properties Name and Model.

Now, I am getting exception like "Items collection must be empty before using ItemsSource."

I am not sure where I am doing wrong?
Can someone please help me to correctly bind the child dataGrid Itemsource?

答:
I think you can try this

```<code> <DataGrid Grid.Row ="1" x:Name="Grid1" ItemsSource="{Binding Path=md,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Categogy" Width="100"  Binding="{Binding Path =CateName,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                <DataGridTemplateColumn Header="Characterictics" Width="600">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <DataGrid   AutoGenerateColumns="False" Height="100" ItemsSource="{Binding list}">
                                <DataGrid.Columns>
                                    <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                                </DataGrid.Columns>
                            </DataGrid>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
</code>```

Edit:If you prefer to use list from the datacontext of window
please change the nested datarid as

```<code> <DataGrid   AutoGenerateColumns="False" Height="100" ItemsSource="{Binding list,RelativeSource={RelativeSource AncestorType=Window}}">
                                <DataGrid.Columns>
                                    <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                                </DataGrid.Columns>
                            </DataGrid>
</code>```

ViewModel:

```<code>  public partial class MainWindow : Window
    {
        private ObservableCollection<Model> _md = new ObservableCollection<Model>();
        public ObservableCollection<Model> md
        {
            get { return _md; }
            set { _md = value; }
        }

        private ObservableCollection<Characteristics> _list;
        public ObservableCollection<Characteristics> list
        {
            get { return _list; }
            set { _list = value; }
        }
        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = this;

            Model m = new Model();
            m.CateName = "CategoryName";
            m.list.Add(new Characteristics() { Name = "test Name", Value = "00" });
            m.list.Add(new Characteristics() { Name = "TEst name1", Value = "00" });
            m.list.Add(new Characteristics() { Name = "XX", Value = "00" });
            md.Add(m);

            Model m1 = new Model();
            m1.CateName = "CategoryName1";
            m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
            m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
            m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
            md.Add(m1);

            list = new ObservableCollection<Characteristics>();
            list.Add(new Characteristics() { Name = "vali", Value = "00" });
            list.Add(new Characteristics() { Name = "XX", Value = "00" });

        }
    }

    public class Model
    {
        private string cateName;
        public string CateName
        {
            get { return cateName; }
            set { cateName = value; }
        }

        private List<Characteristics> _list = new List<Characteristics>();

        public List<Characteristics> list
        {
            get { return _list; }
            set { _list = value; }
        }
    }

    public class Characteristics
    {
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        private string value;

        public string Value
        {
            get { return this.value; }
            set { this.value = value; }
        }
    }
</code>```

Body:
I have a Datagrid and another DataGrid nested inside the parent DataGrid. I need to set the ItemSource of the child DataGrid as a property of the parent DataContext. I already tried to use RelativeSource for the child itemsource to get the parent datacontext.

xaml code

<DataGrid Grid.Row ="1" x:Name="Grid1" ItemsSource="{Binding Path=md,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False">
    <DataGrid.Columns>
      <DataGridTextColumn Header="Categogy" Width="100"  Binding="{Binding Path =CateName,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
      <DataGridTemplateColumn Header="Characterictics" Width="300">
           <DataGridTemplateColumn.CellTemplate>
             <DataTemplate>
               <DataGrid ItemsSource="{Binding DataContext.list, RelativeSource={RelativeSource AncestorType=DataGrid}}">
                 <DataGridTextColumn Binding="{Binding DataContext.list.Name, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
               </DataGrid>
             </DataTemplate>
           </DataGridTemplateColumn.CellTemplate>
      </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

ViewModel

Model m = new Model();
m.CateName = "CategoryName";
m.list.Add(new Characteristics() { Name="XX", Value="00"});
m.list.Add(new Characteristics() { Name = "XX", Value = "00" });
m.list.Add(new Characteristics() { Name = "XX", Value = "00" });
md.Add(m);

Model m1 = new Model();
m1.CateName = "CategoryName1";
m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
md.Add(m1);

list = new ObservableCollection<Characteristics>();
list.Add(new Characteristics() { Name = "XX", Value = "00" });
list.Add(new Characteristics() { Name = "XX", Value = "00" });

The Characteristics class has properties Name and Model.

Now, I am getting exception like "Items collection must be empty before using ItemsSource."

I am not sure where I am doing wrong?
Can someone please help me to correctly bind the child dataGrid Itemsource?

Body:
I think you can try this

 <DataGrid Grid.Row ="1" x:Name="Grid1" ItemsSource="{Binding Path=md,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Categogy" Width="100"  Binding="{Binding Path =CateName,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                <DataGridTemplateColumn Header="Characterictics" Width="600">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <DataGrid   AutoGenerateColumns="False" Height="100" ItemsSource="{Binding list}">
                                <DataGrid.Columns>
                                    <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                                </DataGrid.Columns>
                            </DataGrid>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>

Edit:If you prefer to use list from the datacontext of window
please change the nested datarid as

 <DataGrid   AutoGenerateColumns="False" Height="100" ItemsSource="{Binding list,RelativeSource={RelativeSource AncestorType=Window}}">
                                <DataGrid.Columns>
                                    <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                                </DataGrid.Columns>
                            </DataGrid>

ViewModel:

  public partial class MainWindow : Window
    {
        private ObservableCollection<Model> _md = new ObservableCollection<Model>();
        public ObservableCollection<Model> md
        {
            get { return _md; }
            set { _md = value; }
        }

        private ObservableCollection<Characteristics> _list;
        public ObservableCollection<Characteristics> list
        {
            get { return _list; }
            set { _list = value; }
        }
        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = this;

            Model m = new Model();
            m.CateName = "CategoryName";
            m.list.Add(new Characteristics() { Name = "test Name", Value = "00" });
            m.list.Add(new Characteristics() { Name = "TEst name1", Value = "00" });
            m.list.Add(new Characteristics() { Name = "XX", Value = "00" });
            md.Add(m);

            Model m1 = new Model();
            m1.CateName = "CategoryName1";
            m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
            m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
            m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
            md.Add(m1);

            list = new ObservableCollection<Characteristics>();
            list.Add(new Characteristics() { Name = "vali", Value = "00" });
            list.Add(new Characteristics() { Name = "XX", Value = "00" });

        }
    }

    public class Model
    {
        private string cateName;
        public string CateName
        {
            get { return cateName; }
            set { cateName = value; }
        }

        private List<Characteristics> _list = new List<Characteristics>();

        public List<Characteristics> list
        {
            get { return _list; }
            set { _list = value; }
        }
    }

    public class Characteristics
    {
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        private string value;

        public string Value
        {
            get { return this.value; }
            set { this.value = value; }
        }
    }


问:
How to maintain cucumber test results for each Jenkins job
I am executing cucumber tests using Jenkins pipeline job(Jenkinsfile). But for every job it is overwriting the existing test results in the target/surefire-reports folder.

I would like to display all the cucumber test results for each and every job.

答:
To display the cucumber test result use cucumber report plugin

https://wiki.jenkins.io/display/JENKINS/Cucumber+Test+Result+Plugin
https://wiki.jenkins.io/display/JENKINS/Cucumber+Reports+Plugin

And detailed configuration of cucumber plugin in jenkins

https://wiki.jenkins.io/display/JENKINS/Cucumber+Test+Result+Plugin


问:
how to cap kotlin coroutines maximum concurrency
I've got a Sequence (from File.walkTopDown) and I need to run a long-running operation on each of them.  I'd like to use Kotlin best practices / coroutines, but I either get no parallelism, or way too much parallelism and hit a "too many open files" IO error.

```<code>File("/Users/me/Pictures/").walkTopDown()
    .onFail { file, ex -> println("ERROR: $file caused $ex") }
    .filter { ... only big images... }
    .map { file ->
        async { // I *think* I want async and not "launch"...
            ImageProcessor.fromFile(file)
        }
    }
</code>```

This doesn't seem to run it in parallel, and my multi-core CPU never goes above 1 CPU's worth.  Is there a way with coroutines to run "NumberOfCores parallel operations" worth of Deferred jobs?

I looked at Multithreading using Kotlin Coroutines which first creates ALL the jobs then joins them, but that means completing the Sequence/file tree walk completly bfore the heavy processing join step, and that seems... iffy!  Splitting it into a collect and a process step means the collection could run way ahead of the processing.

```<code>val jobs = ... the Sequence above...
    .toSet()
println("Found ${jobs.size}")
jobs.forEach { it.await() }
</code>```

答:
The problem with your first snippet is that it doesn't run at all - remember, Sequence is lazy, and you have to use a terminal operation such as toSet() or forEach(). Additionally, you need to limit the number of threads that can be used for that task via constructing a newFixedThreadPoolContext context and using it in async:

```<code>val pictureContext = newFixedThreadPoolContext(nThreads = 10, name = "reading pictures in parallel")

File("/Users/me/Pictures/").walkTopDown()
    .onFail { file, ex -> println("ERROR: $file caused $ex") }
    .filter { ... only big images... }
    .map { file ->
        async(pictureContext) {
            ImageProcessor.fromFile(file)
        }
    }
    .toList()
    .forEach { it.await() }
</code>```

Edit:
You have to use a terminal operator (toList) befor awaiting the results

Body:
I've got a Sequence (from File.walkTopDown) and I need to run a long-running operation on each of them.  I'd like to use Kotlin best practices / coroutines, but I either get no parallelism, or way too much parallelism and hit a "too many open files" IO error.

File("/Users/me/Pictures/").walkTopDown()
    .onFail { file, ex -> println("ERROR: $file caused $ex") }
    .filter { ... only big images... }
    .map { file ->
        async { // I *think* I want async and not "launch"...
            ImageProcessor.fromFile(file)
        }
    }

This doesn't seem to run it in parallel, and my multi-core CPU never goes above 1 CPU's worth.  Is there a way with coroutines to run "NumberOfCores parallel operations" worth of Deferred jobs?

I looked at Multithreading using Kotlin Coroutines which first creates ALL the jobs then joins them, but that means completing the Sequence/file tree walk completly bfore the heavy processing join step, and that seems... iffy!  Splitting it into a collect and a process step means the collection could run way ahead of the processing.

val jobs = ... the Sequence above...
    .toSet()
println("Found ${jobs.size}")
jobs.forEach { it.await() }

Body:
The problem with your first snippet is that it doesn't run at all - remember, Sequence is lazy, and you have to use a terminal operation such as toSet() or forEach(). Additionally, you need to limit the number of threads that can be used for that task via constructing a newFixedThreadPoolContext context and using it in async:

val pictureContext = newFixedThreadPoolContext(nThreads = 10, name = "reading pictures in parallel")

File("/Users/me/Pictures/").walkTopDown()
    .onFail { file, ex -> println("ERROR: $file caused $ex") }
    .filter { ... only big images... }
    .map { file ->
        async(pictureContext) {
            ImageProcessor.fromFile(file)
        }
    }
    .toList()
    .forEach { it.await() }

Edit:
You have to use a terminal operator (toList) befor awaiting the results


问:
Programatically determine Mono memory usage in a Xamarin app
To help monitor/track down memory leaks, we need to know what memory our app is consuming.

This is for a Xamarin.Forms app; currently we're only running on Android, but will be on iOS in the future.

I know we can get the OS memory used on the device, in the Droid project, by using code like below:

```<code>public static MemoryInfo GetMemoryInfo()
{
        MemoryInfo retVal = new MemoryInfo();
        retVal.MaxMemory = Java.Lang.Runtime.GetRuntime().MaxMemory();
        retVal.FreeMemory = Java.Lang.Runtime.GetRuntime().FreeMemory();
        retVal.TotalMemory = Java.Lang.Runtime.GetRuntime().TotalMemory();

        return retVal;
}
</code>```

Is there any mechanism for getting a figure for the memory being consumed in the Mono runtime?

答: As Jon Douglas and Lex Li have pointed out, the answer is to use GC.GetTotalMemory(bool).</p>

Body:
To help monitor/track down memory leaks, we need to know what memory our app is consuming.

This is for a Xamarin.Forms app; currently we're only running on Android, but will be on iOS in the future.

I know we can get the OS memory used on the device, in the Droid project, by using code like below:

public static MemoryInfo GetMemoryInfo()
{
        MemoryInfo retVal = new MemoryInfo();
        retVal.MaxMemory = Java.Lang.Runtime.GetRuntime().MaxMemory();
        retVal.FreeMemory = Java.Lang.Runtime.GetRuntime().FreeMemory();
        retVal.TotalMemory = Java.Lang.Runtime.GetRuntime().TotalMemory();

        return retVal;
}

Is there any mechanism for getting a figure for the memory being consumed in the Mono runtime?