问:
Why my animation gets stuck sometimes in Firefox?
I am trying to create an animation using HTML5 canvas and Javascript. Although it works perfectly in Google Chrome, but in Firefox this gets stuck sometimes.

Live demo: http://jsfiddle.net/UbTwh/ .

I guess this is performance issue. Am drawing and clearing the canvas in a wrong way?

答:
Runs fine for me; sounds like it's performance-related on your machine. What specs are you running? If your CPU is getting bogged down or Firefox is eating RAM, everything goes out the window in relation to stability; I've seen everything from DHTML to Flash freeze and die because of performance issues on the computer itself.

If you just want to boost performance on your local machine, I would refrain from clearing the entire picture for every frame. The vast majority of your circles do not need to be redrawn; even though it's easier, calling clear() every frame significantly increases your performance cost. Plus, it's a nice exercise. :)


来源: stackexchange

问:
Teradata Query To Solve Below Scenario
I have below scenario and want to write query to get the output.
Can you please help me with this.

Input :

```<code>Column1 Column2
X       1
X       2
X       3
Y       1
Y       2
</code>```

Expected Output :

```<code>Column1 Column2
X       1,2,3
Y       1,2
</code>```

Thanks.

答:
Do like this:</p>

```<code>SELECT Column1,TRIM(TRAILING ',' FROM (XMLAGG(Column2||',' ORDER BY Column2 ) (VARCHAR(100)))) Column2  FROM database.table
GROUP BY 1
</code>```

ContentLicense: CC BY-SA 4.0

Title: Teradata Query To Solve Below Scenario

Body:
I have below scenario and want to write query to get the output.
Can you please help me with this.

Input :

Column1 Column2
X       1
X       2
X       3
Y       1
Y       2

Expected Output :

Column1 Column2
X       1,2,3
Y       1,2

Thanks.

Body:
Do like this:

SELECT Column1,TRIM(TRAILING ',' FROM (XMLAGG(Column2||',' ORDER BY Column2 ) (VARCHAR(100)))) Column2  FROM database.table
GROUP BY 1


问:
Image on Right, text on left
I'm pretty new to website development and currently still running a course..
We have this assignment and there is just one thing where I can't wrap my mind around (pun intended).

In the "problem" image, the image is in a correct position, but the text alignment is off..
The text should be as shown in the "solution" image

#article {
    width: 650px;
    min-height: 280px;
    margin: 20px;
}

#article p {
    font-size: .8em;
    line-height: 1.6em;
}

#win {
    position: relative;
    left: 160px;
    top: 40px;
    float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <div id="article">

            <img id="win" src="img/gratis.png" alt="test"/>

        <h1>de spikes & de spikids</h1>

        <p>
            Dit is de officiële Spikes-site (dus: de enige echte)! Hier vindt u alle
            informatie en nog véél méér onzin over de knotsgekke bands de Spikes en de
            Spikids. Volg ons op
            Facebook. De
            foto's die wij van jou schieten op onze optredens – vind je voortaan op
            facebook. Op onze eigenste
            <a
            href="https://www.youtube.com/channel/UCTUYz6ynn0M-vHxUXJM15NA"
            target="_blank"
            >YouTube</a
            >
            SPIKES TV kom je alvast in de stemming. Véél kijkplezier!
        </p>

        <h1>De Spikes anno 2015</h1>

        <p>
            De Spikes hebben zichzelf microscopisch onder de loep genomen. Er is gewikt,
            gewogen en het orakel heeft beslist! Het jarenlange succesvolle
            Spikes-concept heeft z’n houdbaarheidsdatum bereikt. Het tijdperk van de
            “spottende parodieën en persiflages” is voorgoed voorbij. Het muzikaal
            voornemen is om “het muzikaal OORgasme” tot méérvoudige hoogtes te brengen
            in 2015 – en tegelijkertijd toch “dé allerleukste coverband uit België” te
            blijven.
        </p>
    </div></code>```

I've been struggling with this for a while now, a solution would help me out a LOT! :)

Thanks in advance for everyone who answers this!

PROBLEM_IMAGE

SOLUTION_IMAGE

答:
Add a couple of
s into your
, then use display:flex;:

*{
  box-sizing:border-box;
}
article{
  display:flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article id='article'>
  <div>
    <h1>de spikes & de spikids</h1>
    <p>
      Dit is de officiële Spikes-site (dus: de enige echte)!
      Hier vindt u alle informatie en nog véél méér onzin
      over de knotsgekke bands de Spikes en de Spikids.
      Volg ons op
      Facebook.
      De foto's die wij van jou schieten op onze optredens
      – vind je voortaan op facebook. Op onze eigenste
      YouTube
      SPIKES TV kom je alvast in de stemming. Véél
      kijkplezier!
    </p>
    <h1>De Spikes anno 2015</h1>
    <p>
      De Spikes hebben zichzelf microscopisch onder de loep
      genomen. Er is gewikt, gewogen en het orakel heeft
      beslist! Het jarenlange succesvolle Spikes-concept
      heeft z’n houdbaarheidsdatum bereikt. Het tijdperk
      van de “spottende parodieën en persiflages” is
      voorgoed voorbij. Het muzikaal voornemen is om “het
      muzikaal OORgasme” tot méérvoudige hoogtes te brengen
      in 2015 – en tegelijkertijd toch “dé allerleukste
      coverband uit België” te blijven.
    </p>
  </div>
  <div>
    <img id='win' src='img/gratis.png' alt='test' />
  </div>
</article></code>```

Note that your image was a relative path so you just see the alt, which is test in this case.

Title: Image on Right, text on left

Body:
I'm pretty new to website development and currently still running a course..
We have this assignment and there is just one thing where I can't wrap my mind around (pun intended).

In the "problem" image, the image is in a correct position, but the text alignment is off..
The text should be as shown in the "solution" image

#article {
    width: 650px;
    min-height: 280px;
    margin: 20px;
}

#article p {
    font-size: .8em;
    line-height: 1.6em;
}

#win {
    position: relative;
    left: 160px;
    top: 40px;
    float: right;
}

de spikes & de spikids

            Dit is de officiële Spikes-site (dus: de enige echte)! Hier vindt u alle
            informatie en nog véél méér onzin over de knotsgekke bands de Spikes en de
            Spikids. Volg ons op
            Facebook. De
            foto's die wij van jou schieten op onze optredens – vind je voortaan op
            facebook. Op onze eigenste
            YouTube
            SPIKES TV kom je alvast in de stemming. Véél kijkplezier!

De Spikes anno 2015

            De Spikes hebben zichzelf microscopisch onder de loep genomen. Er is gewikt,
            gewogen en het orakel heeft beslist! Het jarenlange succesvolle
            Spikes-concept heeft z’n houdbaarheidsdatum bereikt. Het tijdperk van de
            “spottende parodieën en persiflages” is voorgoed voorbij. Het muzikaal
            voornemen is om “het muzikaal OORgasme” tot méérvoudige hoogtes te brengen
            in 2015 – en tegelijkertijd toch “dé allerleukste coverband uit België” te
            blijven.

I've been struggling with this for a while now, a solution would help me out a LOT! :)

Thanks in advance for everyone who answers this!

PROBLEM_IMAGE

SOLUTION_IMAGE

Body:
Add a couple of <div>s into your <article>, then use display:flex;:

*{
  box-sizing:border-box;
}
article{
  display:flex;
}

<article id='article'>
  <div>
    <h1>de spikes & de spikids</h1>
    <p>
      Dit is de officiële Spikes-site (dus: de enige echte)!
      Hier vindt u alle informatie en nog véél méér onzin
      over de knotsgekke bands de Spikes en de Spikids.
      Volg ons op
      <a href='https://www.facebook.com/despikes' target='_blank'>Facebook.</a>
      De foto's die wij van jou schieten op onze optredens
      – vind je voortaan op facebook. Op onze eigenste
      <a href='https://www.youtube.com/channel/UCTUYz6ynn0M-vHxUXJM15NA' target='_blank'>YouTube</a>
      SPIKES TV kom je alvast in de stemming. Véél
      kijkplezier!
    </p>
    <h1>De Spikes anno 2015</h1>
    <p>
      De Spikes hebben zichzelf microscopisch onder de loep
      genomen. Er is gewikt, gewogen en het orakel heeft
      beslist! Het jarenlange succesvolle Spikes-concept
      heeft z’n houdbaarheidsdatum bereikt. Het tijdperk
      van de “spottende parodieën en persiflages” is
      voorgoed voorbij. Het muzikaal voornemen is om “het
      muzikaal OORgasme” tot méérvoudige hoogtes te brengen
      in 2015 – en tegelijkertijd toch “dé allerleukste
      coverband uit België” te blijven.
    </p>
  </div>
  <div>
    <a href='mailto:brent.claes97@hotmail.com?subject=GRATIS HUISKAMER CONCERT&body=Ik wil graag kans maken op het winnen van het GRATIS huiskamerconcert.'><img id='win' src='img/gratis.png' alt='test' /></a>
  </div>
</article>

Note that your image was a relative path so you just see the alt, which is test in this case.


问:
Executing function pointer from a in std::vector iterator
I'm trying to write an application that adds function pointers to a vector based on some external event, then iterates through the list. For some reason, I can't seem to get the functions to actually execute despite the fact that they are added to the vector.

What am I missing?

main.cpp

```<code>#include "GameLogic.h"

GameLogic* gameLogic = nullptr;

int main(int argc, char* argv[])
{
    gameLogic = new GameLogic();
    gameLogic->run();
}
</code>```

GameLogic.cpp

```<code>#include "GameLogic.h"

GameLogic::GameLogic()
{
    FireAction.push_back(&GameLogic::AddCredit);
    FireAction.push_back(&GameLogic::AddPlayer);
}

GameLogic::~GameLogic() {}

void GameLogic::run()
{

    for (std::vector<std::function<void(const GameLogic)>>::iterator it = FireAction.begin(); it != FireAction.end(); it++)
    {
        std::cout << "Iterator Loop" << std::endl;
        (*it);
    }
}

void GameLogic::AddCredit() { std::cout << "Added Credit" << std::endl; }
void GameLogic::AddPlayer() { std::cout << "Added Player" << std::endl; }
</code>```

GameLogic.h

```<code>#pragma once
#include <functional>
#include <iostream>
#include <vector>

class GameLogic
{
public:
    GameLogic();
    ~GameLogic();
    void run();

private:
    void AddCredit();
    void AddPlayer();

    std::vector<std::function<void(const GameLogic)>> FireAction;
};
</code>```

Execution Output:

```<code>Iterator Loop
Iterator Loop
</code>```

Expected Output:

```<code>Iterator Loop
Added Credit
Iterator Loop
Added Player
</code>```

答:
If you expect (*it) to call a function pointer, you're mistaken.

You should write: (*it)(...parameters...) instead, that will get you closer. The parameter needs to be the GameLogic object that you expect those member functions to be called upon.

Note: your std::function<void(const GameLogic)> should probably be std::function<void(const GameLogic &)> or std::function<void(GameLogic &)> unless you like making copies of things.

Body:
I'm trying to write an application that adds function pointers to a vector based on some external event, then iterates through the list. For some reason, I can't seem to get the functions to actually execute despite the fact that they are added to the vector.

What am I missing?

main.cpp

#include "GameLogic.h"

GameLogic* gameLogic = nullptr;

int main(int argc, char* argv[])
{
    gameLogic = new GameLogic();
    gameLogic->run();
}

GameLogic.cpp

#include "GameLogic.h"

GameLogic::GameLogic()
{
    FireAction.push_back(&GameLogic::AddCredit);
    FireAction.push_back(&GameLogic::AddPlayer);
}

GameLogic::~GameLogic() {}

void GameLogic::run()
{

    for (std::vector<std::function<void(const GameLogic)>>::iterator it = FireAction.begin(); it != FireAction.end(); it++)
    {
        std::cout << "Iterator Loop" << std::endl;
        (*it);
    }
}

void GameLogic::AddCredit() { std::cout << "Added Credit" << std::endl; }
void GameLogic::AddPlayer() { std::cout << "Added Player" << std::endl; }

GameLogic.h

#pragma once
#include <functional>
#include <iostream>
#include <vector>

class GameLogic
{
public:
    GameLogic();
    ~GameLogic();
    void run();

private:
    void AddCredit();
    void AddPlayer();

    std::vector<std::function<void(const GameLogic)>> FireAction;
};

Execution Output:

Iterator Loop
Iterator Loop

Expected Output:

Iterator Loop
Added Credit
Iterator Loop
Added Player


问:
Custom Permissions in Django Rest Framework
I have this get View that I want to check IsOwner Permission.

Permission Class

```<code>class IsOwnerVendor(permissions.BasePermission):

def has_object_permission(self, request, view, obj):
    print(f"Vendor Email:{obj.vendor_id.email}")
    print(f"Loggon user:{obj.vendor_id.email}" )
    return obj.vendor_id.email == request.user
</code>```

this is my object Model

```<code>class Menu(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=500)
    price = models.FloatField()
    quantity = models.IntegerField(default=1)
    menu_cat = models.CharField(choices=MENU_CAT, max_length=5)
    date_created = models.DateTimeField(auto_now_add=True)
    last_edited = models.DateTimeField(auto_now=True)
    vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE)
    is_recurring = models.BooleanField(default=False)
    recurring_freq = models.IntegerField(default=1)
</code>```

Vendor Model

```<code>class Vendor(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
    business_name = models.CharField(max_length=100)
    email = models.EmailField()
    phone_number = PhoneField(help_text='Vendor phone number')
    registered_on = models.DateTimeField(auto_now_add=True)
    last_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.business_name
</code>```

and this is my view

```<code>class MenuDetailView(generics.GenericAPIView):
    permission_classes = [IsOwnerVendor | IsOwnerVendor]

    def get_serializer_class(self):
        if self.request.method == 'PUT':
            return MenuUpdateSerializer
        elif self.request.method == 'GET':
            return MenuListSerializer
        else:
            return MenuListSerializer

    def get_object(self, pk):
        try:
            obj = Menu.objects.get(pk=pk, )
            self.check_object_permissions(self.request, obj)
            return obj
        except Menu.DoesNotExist:
            raise Http404

    @method_permission_classes((IsOwnerVendor,))
    def get(self, request, pk, format=None):
        my_menu = self.get_object(pk=pk)
        menu_serializer = MenuListSerializer(my_menu)
        return Response(menu_serializer.data, status=status.HTTP_200_OK)
</code>```

When I try to access the view, I always get the error below

```<code>{
    "detail": "You do not have permission to perform this action."
}
</code>```

I have read the DRF doc and I still cannot pinpoint where my issue lies.

I also printed the Permission checkers on the console and saw that it was supposed to return true.

答:
The main point is you should let has_object_permission method return True, you can try:

return obj.vendor_id.email == request.user.email or
return obj.vendor_id.user == request.user, if this still not work, you can print log or set breakpoint to see why this method return False.Remember to restart you localserver before you next test.

Body:
I have this get View that I want to check IsOwner Permission.

Permission Class

class IsOwnerVendor(permissions.BasePermission):

def has_object_permission(self, request, view, obj):
    print(f"Vendor Email:{obj.vendor_id.email}")
    print(f"Loggon user:{obj.vendor_id.email}" )
    return obj.vendor_id.email == request.user

this is my object Model

class Menu(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=500)
    price = models.FloatField()
    quantity = models.IntegerField(default=1)
    menu_cat = models.CharField(choices=MENU_CAT, max_length=5)
    date_created = models.DateTimeField(auto_now_add=True)
    last_edited = models.DateTimeField(auto_now=True)
    vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE)
    is_recurring = models.BooleanField(default=False)
    recurring_freq = models.IntegerField(default=1)

Vendor Model

class Vendor(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
    business_name = models.CharField(max_length=100)
    email = models.EmailField()
    phone_number = PhoneField(help_text='Vendor phone number')
    registered_on = models.DateTimeField(auto_now_add=True)
    last_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.business_name

and this is my view

class MenuDetailView(generics.GenericAPIView):
    permission_classes = [IsOwnerVendor | IsOwnerVendor]

    def get_serializer_class(self):
        if self.request.method == 'PUT':
            return MenuUpdateSerializer
        elif self.request.method == 'GET':
            return MenuListSerializer
        else:
            return MenuListSerializer

    def get_object(self, pk):
        try:
            obj = Menu.objects.get(pk=pk, )
            self.check_object_permissions(self.request, obj)
            return obj
        except Menu.DoesNotExist:
            raise Http404

    @method_permission_classes((IsOwnerVendor,))
    def get(self, request, pk, format=None):
        my_menu = self.get_object(pk=pk)
        menu_serializer = MenuListSerializer(my_menu)
        return Response(menu_serializer.data, status=status.HTTP_200_OK)

When I try to access the view, I always get the error below

{
    "detail": "You do not have permission to perform this action."
}

I have read the DRF doc and I still cannot pinpoint where my issue lies.

I also printed the Permission checkers on the console and saw that it was supposed to return true.


问:
python replace 0 with blanks
I have a huge dataframe for which i need a spaceific set of rows and columns as blank always.

I am using the below for row 2, 3, 4 and column from 19:37 but its not working. Below code does not give an error but does not replace the 0 with blank.

```<code>df_return_3.iloc[2:5, 19:37].replace('^0.0$', '')
</code>```

```<code>df_return_3.iloc[2:5, 19:37].str.replace('^0.0$', '')
</code>```

This one gives an error: "AttributeError: 'DataFrame' object has no attribute 'str'"

It would also be ok if i can replace this range of dataframe without checking what value is present before replace.

答:
If you are just replacing 0 with blank, this should work unless I'm missing something:</p>

```<code>df_return_3.iloc[2:5, 19:37] = df_return_3.iloc[2:5, 19:37].astype(str).replace('0*', '', regex=True)
</code>```

Title: python replace 0 with blanks

Body:
I have a huge dataframe for which i need a spaceific set of rows and columns as blank always.

I am using the below for row 2, 3, 4 and column from 19:37 but its not working. Below code does not give an error but does not replace the 0 with blank.

df_return_3.iloc[2:5, 19:37].replace('^0.0$', '')

df_return_3.iloc[2:5, 19:37].str.replace('^0.0$', '')

This one gives an error: "AttributeError: 'DataFrame' object has no attribute 'str'"

It would also be ok if i can replace this range of dataframe without checking what value is present before replace.

Body:
If you are just replacing 0 with blank, this should work unless I'm missing something:

df_return_3.iloc[2:5, 19:37] = df_return_3.iloc[2:5, 19:37].astype(str).replace('0*', '', regex=True)


问:
How to add entity to many to many relation in Slick
I have a following table defined in Slick, it connects two entities by id, so it consists of two ids which together form primary key. I don't know how to add new value to the table.

```<code>trait CaptionNounComponent extends CaptionComponent with NounComponent {
  self: HasDatabaseConfigProvider[JdbcProfile] =>

  import profile.api._

  class CaptionNounTable(tag: Tag) extends Table[CaptionNoun](tag, "caption_noun") {

    def * : ProvenShape[CaptionNoun] = (captionId, nounId) <> ((CaptionNoun.apply _).tupled, CaptionNoun.unapply)

    def nounId: Rep[Int] = column[Int]("NOUN_ID")

    def captionId: Rep[Int] = column[Int]("CAPTION_ID")

    def pk = primaryKey("primaryKey", (captionId, nounId))

    def nounFK =
      foreignKey("noun_fk", nounId, TableQuery[NounTable])(_.id)

    def captionFK =
      foreignKey("caption_fk", captionId, TableQuery[CaptionTable])(_.id)
  }
}
</code>```

Normally I would try something like:

```<code>private val keyTable = TableQuery[CaptionNounTable]

  def addKeys(keys: CaptionNoun): Future[Int] = db.run {
    (keyTable returning keyTable.map(_.pk)) += keys
  }

</code>```

but in this case it does not work

答:
I forgot to import

```<code>  import profile.api._
</code>```

That seems to resolve the problem

Body:
I have a following table defined in Slick, it connects two entities by id, so it consists of two ids which together form primary key. I don't know how to add new value to the table.

trait CaptionNounComponent extends CaptionComponent with NounComponent {
  self: HasDatabaseConfigProvider[JdbcProfile] =>

  import profile.api._

  class CaptionNounTable(tag: Tag) extends Table[CaptionNoun](tag, "caption_noun") {

    def * : ProvenShape[CaptionNoun] = (captionId, nounId) <> ((CaptionNoun.apply _).tupled, CaptionNoun.unapply)

    def nounId: Rep[Int] = column[Int]("NOUN_ID")

    def captionId: Rep[Int] = column[Int]("CAPTION_ID")

    def pk = primaryKey("primaryKey", (captionId, nounId))

    def nounFK =
      foreignKey("noun_fk", nounId, TableQuery[NounTable])(_.id)

    def captionFK =
      foreignKey("caption_fk", captionId, TableQuery[CaptionTable])(_.id)
  }
}

Normally I would try something like:

private val keyTable = TableQuery[CaptionNounTable]

  def addKeys(keys: CaptionNoun): Future[Int] = db.run {
    (keyTable returning keyTable.map(_.pk)) += keys
  }

but in this case it does not work

Body:
I forgot to import

  import profile.api._

That seems to resolve the problem


问:
Another Rails 3 Nested Forms Issue
So I have the following:

```<code>class ComplexAssertion < ActiveRecord::Base
  has_many :assertion_groups
  has_many :assertions, :through => :assertion_group

class AssertionGroup < ActiveRecord::Base
  belongs_to :complex_assertion
  has_many :assertions, :dependent => :destroy, :autosave=>true

class Assertion < ActiveRecord::Base
  belongs_to :assertion_group
</code>```

And my form looks like the following:

```<code><%= form_for(@complex_assertion) do |f| %>
<div class="childGroup1" style="padding:5px;">
      <%= f.fields_for :assertion_groups do |assertion_group_fields| %>
      <%= assertion_group_fields.fields_for :assertions do |assertion_fields| %>
      Type: <%= assertion_fields.collection_select :assertion_type_id, AssertionType.all, :id, :name %>
      Attribute: <%= assertion_fields.collection_select :attribute_name, Attribute.find_by_sql("select distinct a.name from attributes a "), :name, :name %>
      <%= assertion_fields.label :operator_type_id %>: <%= assertion_fields.collection_select :operator_type_id, OperatorType.all, :id, :value %>
      Value: <%= assertion_fields.text_field :value, :size=>'1' %>
      <% end %>
          <div id="innerOperator">
            <!--OPERATOR BETWEEN EACH ASSERTION IN A GROUP-->
            <%= assertion_group_fields.collection_select :logical_operator_type_id, LogicalOperatorType.all, :id, :value %>
          </div>
      <% end %>
    </div>
    <div id="createComplex" align="center">
       <%= f.submit :value=>'Submit' %>
    </div>
<% end %>
</code>```

When I try to save, I get the following error:

```<code>AssertionGroup(#48180276) expected, got Array(#19330344)

Rails.root: C:/Eagle6/Assertions

Application Trace | Framework Trace | Full Trace
app/controllers/complex_assertions_controller.rb:43:in `new'
app/controllers/complex_assertions_controller.rb:43:in `create'
</code>```

I've tried to make multiple changes to get this to work correctly, but I think I'm missing some very fundamental piece of logic here.  Can anyone point me in the right direction?  I was under the impression that if I got the Models done correctly and used the Form_builders, that Rails would handle the inserts and relationships.

Thanks!

Added controller code - very vanilla.

```<code>def create
@complex_assertion = ComplexAssertion.new(params[:complex_assertion])
respond_to do |format|
  if @complex_assertion.save
    format.html { redirect_to(@complex_assertion, :notice => 'Complex assertion was successfully created.') }
    format.xml  { render :xml => @complex_assertion, :status => :created, :location => @complex_assertion }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @complex_assertion.errors, :status => :unprocessable_entity }
  end
end
end
</code>```

答:
Your ComplexAssertion class should look like this

```<code>class ComplexAssertion < ActiveRecord::Base
  has_many :assertion_groups
  has_many :assertions, :through => :assertion_group

  accepts_nested_attributes_for :assertion_groups # <= add this
</code>```

Your AssertionGroup class should look like this

```<code>class AssertionGroup < ActiveRecord::Base
  belongs_to :complex_assertion
  has_many :assertions, :dependent => :destroy, :autosave=>true

  accepts_nested_attributes_for :assertions # <= add this
</code>```

You can find more about this at http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html ("Nested attributes examples", "One-to-many").

ContentLicense: CC BY-SA 3.0

Title: Another Rails 3 Nested Forms Issue

Body:
So I have the following:

class ComplexAssertion < ActiveRecord::Base
  has_many :assertion_groups
  has_many :assertions, :through => :assertion_group

class AssertionGroup < ActiveRecord::Base
  belongs_to :complex_assertion
  has_many :assertions, :dependent => :destroy, :autosave=>true

class Assertion < ActiveRecord::Base
  belongs_to :assertion_group

And my form looks like the following:

<%= form_for(@complex_assertion) do |f| %>

      <%= f.fields_for :assertion_groups do |assertion_group_fields| %>
      <%= assertion_group_fields.fields_for :assertions do |assertion_fields| %>
      Type: <%= assertion_fields.collection_select :assertion_type_id, AssertionType.all, :id, :name %>
      Attribute: <%= assertion_fields.collection_select :attribute_name, Attribute.find_by_sql("select distinct a.name from attributes a "), :name, :name %>
      <%= assertion_fields.label :operator_type_id %>: <%= assertion_fields.collection_select :operator_type_id, OperatorType.all, :id, :value %>
      Value: <%= assertion_fields.text_field :value, :size=>'1' %>
      <% end %>

            <%= assertion_group_fields.collection_select :logical_operator_type_id, LogicalOperatorType.all, :id, :value %>

      <% end %>

       <%= f.submit :value=>'Submit' %>

<% end %>

When I try to save, I get the following error:

AssertionGroup(#48180276) expected, got Array(#19330344)

Rails.root: C:/Eagle6/Assertions

Application Trace | Framework Trace | Full Trace
app/controllers/complex_assertions_controller.rb:43:in `new'
app/controllers/complex_assertions_controller.rb:43:in `create'

I've tried to make multiple changes to get this to work correctly, but I think I'm missing some very fundamental piece of logic here.  Can anyone point me in the right direction?  I was under the impression that if I got the Models done correctly and used the Form_builders, that Rails would handle the inserts and relationships.

Thanks!

Added controller code - very vanilla.

def create
@complex_assertion = ComplexAssertion.new(params[:complex_assertion])
respond_to do |format|
  if @complex_assertion.save
    format.html { redirect_to(@complex_assertion, :notice => 'Complex assertion was successfully created.') }
    format.xml  { render :xml => @complex_assertion, :status => :created, :location => @complex_assertion }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @complex_assertion.errors, :status => :unprocessable_entity }
  end
end
end

Body:
Your ComplexAssertion class should look like this

class ComplexAssertion < ActiveRecord::Base
  has_many :assertion_groups
  has_many :assertions, :through => :assertion_group

  accepts_nested_attributes_for :assertion_groups # <= add this

Your AssertionGroup class should look like this

class AssertionGroup < ActiveRecord::Base
  belongs_to :complex_assertion
  has_many :assertions, :dependent => :destroy, :autosave=>true

  accepts_nested_attributes_for :assertions # <= add this

You can find more about this at http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html ("Nested attributes examples", "One-to-many").


问:
Executing a command when a list is equal to one line of a matrix in python
If all 3 of the values in the list below are equal to any of the 3 values in one line of the matrix, I want it to print 'hello'. </p>

```<code>#if x is equal to the 1st line of the matrix I want it to print hello. If x is equal to the 2nd part and not the 1st I still want it to print the same string.

x = [1, 2, 3]
y = [
    [1, 2, 3],
    [4, 5, 6],
    [3, 4, 5],
    [7, 8, 9]
]
if x == (y):
    print('hello')
</code>```

<p>As shown above, the x list value is equal to one of the lines in the matrix but it won't print hello. How would I get the program to do that. </p>

答:
Well, for the normal case, you can simply use -

```<code>if x in y:
    print('hello')
</code>```

If you want to check your only values in any order then you need to sort first as shown below.

```<code>x = [1, 2, 3]
y = [
[1, 3, 2],
[4, 5, 6],
[3, 4, 5],
[7, 8, 9]
]
x = sorted(x)
for i in range(len(y)):
    y[i] = sorted(y[i])
if x in y:
    print('hello')
</code>```

Body:
If all 3 of the values in the list below are equal to any of the 3 values in one line of the matrix, I want it to print 'hello'.

#if x is equal to the 1st line of the matrix I want it to print hello. If x is equal to the 2nd part and not the 1st I still want it to print the same string.

x = [1, 2, 3]
y = [
    [1, 2, 3],
    [4, 5, 6],
    [3, 4, 5],
    [7, 8, 9]
]
if x == (y):
    print('hello')

As shown above, the x list value is equal to one of the lines in the matrix but it won't print hello. How would I get the program to do that.

Body:
Well, for the normal case, you can simply use -

if x in y:
    print('hello')

If you want to check your only values in any order then you need to sort first as shown below.

x = [1, 2, 3]
y = [
[1, 3, 2],
[4, 5, 6],
[3, 4, 5],
[7, 8, 9]
]
x = sorted(x)
for i in range(len(y)):
    y[i] = sorted(y[i])
if x in y:
    print('hello')


问:
How to properly align slider's thumb on Xamarin.Forms custom slider in android?
I'm trying to create a custom slider in Xamarin.Forms, I have created a custom renderer for this purpose

```<code>protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Slider> e)
{
    base.OnElementChanged(e);
    if (e.NewElement != null)
    {
        // Set custom drawable resource
        Control.SplitTrack = false;
        Control.SetProgressDrawableTiled(
        Resources.GetDrawable(
        Resource.Drawable.custom_progressbar_style,
        (this.Context).Theme));

        Control.SetThumb(Resources.GetDrawable(
        Resource.Drawable.custom_thumb,
        (this.Context).Theme));
                        // Control.Bottom = 30;
    }
}
</code>```

Here I'm loading two xml files one for progress bar and the other one is for slider's thumb. Progress bar is loaded from custom_progressbar_style and Thumb is being loaded from custom_thumb both of them are placed under Resource/drawable.

Progress bar xml content:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:id="@android:id/background" android:height="10dp">
    <shape>
      <corners android:radius="3dp"/>
    </shape>
  </item>

  <item android:id="@android:id/secondaryProgress" android:height="10dp">
    <clip>
      <shape>
        <corners android:radius="3dp"/>
      </shape>
    </clip>
  </item>

  <item android:id="@android:id/progress" android:height="10dp">
    <clip>
      <shape>
        <corners android:radius="3dp"/>

      </shape>
    </clip>
  </item>

</layer-list>
</code>```

Thumb xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:layout_gravity="center_vertical">
<!-- Larger white circle in back -->
<item  >
    <shape android:shape="oval">
        <solid android:color="#f0f0f0"/>
        <size
                android:width="30dp"
                android:height="30dp"/>
    </shape>
</item>
<!-- Smaller blue circle in front -->
<item>
    <shape android:shape="oval">
        <!-- transparent stroke = larger_circle_size - smaller_circle_size -->
        <stroke android:color="@android:color/transparent"
                android:width="10dp"/>
        <solid android:color="#6766f6"/>
        <size
                android:width="15dp"
                android:height="15dp"/>
    </shape>
</item>
</layer-list>
</code>```

I have fixed the height of my custom slider to 10dp which is causing alignment issues with the slider's thumb. Can you suggest how I can overcome this alignment issue.

答:
According to your description, I test your code and modify your custom_progressbar_style.xml, and I have on problem.

This is my custom_progressbar_style.xml, please take a look:

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

 <item android:id="@android:id/background">
<shape>
  <corners android:radius="15dip" />
  <gradient
   android:startColor="#d9d9d9"
   android:centerColor="#e6e6e6"
   android:endColor="#d9d9d9"
   android:centerY="0.50"
   android:angle="270" />
  </shape>
 </item>

 <item android:id="@android:id/secondaryProgress">
<clip>
  <shape>
    <corners android:radius="15dip" />
    <gradient
         android:startColor="#e6b3e6"
         android:centerColor="#ffcce0"
         android:endColor="#e6b3e6"
         android:centerY="0.50"
         android:angle="270" />
  </shape>
</clip>
</item>

 <item android:id="@android:id/progress">
<clip>
  <shape>
    <corners android:radius="15dip" />
    <gradient
     android:startColor="#ff0066"
     android:centerColor="#ff00ff"
     android:centerY="0.50"
     android:endColor="#cc0052"
     android:angle="270" />
  </shape>
</clip>
 </item>

 </layer-list>
</code>```

Update:

```<code>  <StackLayout>
        <local:customslider HeightRequest="10" VerticalOptions="CenterAndExpand" />
    </StackLayout>
</code>```

Update again:

```<code>protected override void OnLayout(bool changed, int l, int t, int r, int b)
    {
        base.OnLayout(changed, l, t, r, b);

        if (Control == null)
            return;

        SeekBar seekbar = Control;

        Drawable thumb = seekbar.Thumb;
        thumb.SetBounds(thumb.Bounds.Left, -4, thumb.Bounds.Left + thumb.IntrinsicWidth,  thumb.IntrinsicHeight-4);
    }
</code>```

Body:
I'm trying to create a custom slider in Xamarin.Forms, I have created a custom renderer for this purpose

protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Slider> e)
{
    base.OnElementChanged(e);
    if (e.NewElement != null)
    {
        // Set custom drawable resource
        Control.SplitTrack = false;
        Control.SetProgressDrawableTiled(
        Resources.GetDrawable(
        Resource.Drawable.custom_progressbar_style,
        (this.Context).Theme));

        Control.SetThumb(Resources.GetDrawable(
        Resource.Drawable.custom_thumb,
        (this.Context).Theme));
                        // Control.Bottom = 30;
    }
}

Here I'm loading two xml files one for progress bar and the other one is for slider's thumb. Progress bar is loaded from custom_progressbar_style and Thumb is being loaded from custom_thumb both of them are placed under Resource/drawable.

Progress bar xml content:

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

  <item android:id="@android:id/background" android:height="10dp">
    <shape>
      <corners android:radius="3dp"/>
    </shape>
  </item>

  <item android:id="@android:id/secondaryProgress" android:height="10dp">
    <clip>
      <shape>
        <corners android:radius="3dp"/>
      </shape>
    </clip>
  </item>

  <item android:id="@android:id/progress" android:height="10dp">
    <clip>
      <shape>
        <corners android:radius="3dp"/>

      </shape>
    </clip>
  </item>

</layer-list>

Thumb xml:

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

<item  >
    <shape android:shape="oval">
        <solid android:color="#f0f0f0"/>
        <size
                android:width="30dp"
                android:height="30dp"/>
    </shape>
</item>

<item>
    <shape android:shape="oval">

        <stroke android:color="@android:color/transparent"
                android:width="10dp"/>
        <solid android:color="#6766f6"/>
        <size
                android:width="15dp"
                android:height="15dp"/>
    </shape>
</item>
</layer-list>

I have fixed the height of my custom slider to 10dp which is causing alignment issues with the slider's thumb. Can you suggest how I can overcome this alignment issue.

Body:
According to your description, I test your code and modify your custom_progressbar_style.xml, and I have on problem.

This is my custom_progressbar_style.xml, please take a look:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

 <item android:id="@android:id/background">
<shape>
  <corners android:radius="15dip" />
  <gradient
   android:startColor="#d9d9d9"
   android:centerColor="#e6e6e6"
   android:endColor="#d9d9d9"
   android:centerY="0.50"
   android:angle="270" />
  </shape>
 </item>

 <item android:id="@android:id/secondaryProgress">
<clip>
  <shape>
    <corners android:radius="15dip" />
    <gradient
         android:startColor="#e6b3e6"
         android:centerColor="#ffcce0"
         android:endColor="#e6b3e6"
         android:centerY="0.50"
         android:angle="270" />
  </shape>
</clip>
</item>

 <item android:id="@android:id/progress">
<clip>
  <shape>
    <corners android:radius="15dip" />
    <gradient
     android:startColor="#ff0066"
     android:centerColor="#ff00ff"
     android:centerY="0.50"
     android:endColor="#cc0052"
     android:angle="270" />
  </shape>
</clip>
 </item>

 </layer-list>

Update:

  <StackLayout>
        <local:customslider HeightRequest="10" VerticalOptions="CenterAndExpand" />
    </StackLayout>

Update again:

protected override void OnLayout(bool changed, int l, int t, int r, int b)
    {
        base.OnLayout(changed, l, t, r, b);

        if (Control == null)
            return;

        SeekBar seekbar = Control;

        Drawable thumb = seekbar.Thumb;
        thumb.SetBounds(thumb.Bounds.Left, -4, thumb.Bounds.Left + thumb.IntrinsicWidth,  thumb.IntrinsicHeight-4);
    }


问:
member function referring to an object's member function
I'm a c++ noob so apologies in advance if this question is not properly structured.

I have a class which instantiates an object of a different class, I'd like for the member function of the main class (excuse my naive language) to be in turn referring to the member function of the object instantiated in the main class.

I've attached a snippet for reference

foo.h

```<code>class foo {
public :

int data;
void printFunc(){
cout<< "data is"<< data;
}

};
</code>```

bar.h

```<code>class bar {

public:
void updatebarr ();
}
</code>```

bar.cpp

```<code>bar::bar()
{
foo foo1;
foo1.data = 1;
// the line below is flagged as syntax error
// I want the object of type bar's updatebarr() function to be essentially be calling
// foo::PrintFunc(). I figured this "should" work as the signatures are identical.
this->updatebarr = &foo1.printFunc();
}
</code>```

The error I get is "Reference to non-static member function must be called",

答:
The signatures might look similar but these are not free functions but member functions. Have a look at this faq!

The type of the first one is: void (foo::*)() and the second is void (bar::*)(). See the difference?

They can only be invoked on an object of their respective type. What you can do is this:

```<code>class bar {
  public:
    void updatebarr(foo& f) {
      f.printFunc();
    }
};
</code>```

Body:
I'm a c++ noob so apologies in advance if this question is not properly structured.

I have a class which instantiates an object of a different class, I'd like for the member function of the main class (excuse my naive language) to be in turn referring to the member function of the object instantiated in the main class.

I've attached a snippet for reference

foo.h

class foo {
public :

int data;
void printFunc(){
cout<< "data is"<< data;
}

};

bar.h

class bar {

public:
void updatebarr ();
}

bar.cpp

bar::bar()
{
foo foo1;
foo1.data = 1;
// the line below is flagged as syntax error
// I want the object of type bar's updatebarr() function to be essentially be calling
// foo::PrintFunc(). I figured this "should" work as the signatures are identical.
this->updatebarr = &foo1.printFunc();
}

The error I get is "Reference to non-static member function must be called",

Body:
The signatures might look similar but these are not free functions but member functions. Have a look at this faq!

The type of the first one is: void (foo::*)() and the second is void (bar::*)(). See the difference?

They can only be invoked on an object of their respective type. What you can do is this:

class bar {
  public:
    void updatebarr(foo& f) {
      f.printFunc();
    }
};


问:
Which of the following are correct regarding an equals() method in java?
This is a question on one of my practice exams that has me stumped.

Potential Answers

An equals() method written in a class named C must have a parameter that is declared to be of type C, in order to override the equals() method in the Object class.

An equals() method must have a parameter that is declared to be of type Object, in order to override the equals() method in the Object class.

An equals() method written in a class named C must cast its parameter to Object, even if its parameter is declared to be of type C, otherwise it will not be able to properly compare the fields of current object to those of the parameter object.

A well-designed equals() method should check for and handle the case where its current object may be null

An equals() method in a subclass cannot refer directly to private fields in a superclass in order to compare them, so it should invoke the superclass equals() method to do this

The answer is #2 & #5. I don't understand why #1 is wrong and #2 is correct. Don't you have to compare one type C with another type C? And why is #5 correct. I don't understand this one at all. Can't subclasses access the private fields of a superclass?

答:
I don't understand why #1 is wrong

Because:

Object::equals is defined as public boolean equals(Object), and

public boolean equals(SomeType) does not override public boolean equals(Object).  This is actually an overload not an override.  They are different operations.

Can't subclasses access the private fields of a superclass?

In general, no they can't.  Check your lecture notes.

There are some exceptions that involve the subclass being declared inside the superclass.

Technically, answer #5 is only half right.

It is correct that the subclass cannot access private fields in the superclass, assuming we stay within the bounds of pure Java.  The Java access rules forbid this.  (But see above.)

It is correct that calling super.equals(other) could be a solution.  And indeed, it usually is the correct solution.

It is incorrect to imply that calling super.equals(other) is the only solution.

Other possible solutions may include:

ignoring the superclass fields when testing for equality,

accessing the private fields of the superclass using public getters ... if they exist, or

accessing the private fields by abstraction-breaking reflection.

Of the alternatives, the first one is rarely applicable and the third is a really bad idea.  But these alternatives mean that Answer #5 (as written) is technically incorrect.


问:
PHP largest whole number from sum of unsorted array
Can someone tell me the best way to find the largest whole number summed from an unsorted array?

e.g.

```<code>{0.1, 0.2, 0.9, 0.5}

Largest whole number possible is 1 (0.1 + 0.9).

{0.9, 0.2, 0.5, 0.3, 0.9}

Largest possible is 2 (0.9 + 0.9 + 0.2)
</code>```

thanks

Update

I've accepted the method that i used but some of the below will be programmatically correct

答:
I would suggest summing up the whole array and then finding the smallest sum with the decimal part equal to that of the whole sum. Unless the numbers have very high precision after the decimal point, whatever the approach to finding the exact number is, this reversal should save a lot of computation.

Also, sorting the array and going greedy from the smallest numbers might yield nice results. However, the optimal solution is very dependent on the nature of the initial set. Could you provide any closer specifications on what kind of numbers you expect?

Body:
Can someone tell me the best way to find the largest whole number summed from an unsorted array?

e.g.

{0.1, 0.2, 0.9, 0.5}

Largest whole number possible is 1 (0.1 + 0.9).

{0.9, 0.2, 0.5, 0.3, 0.9}

Largest possible is 2 (0.9 + 0.9 + 0.2)

thanks

Update

I've accepted the method that i used but some of the below will be programmatically correct


问:
remove decimal in dart
I have a number: 466.62 as a double and can't change it to a string, how can I get rid of the decimal point and print 46662? I've managed to get 46662.0 by multiplying the value by 100, but I don't want to print the decimal point. Thanks</p>

答:
When you multiply 466.62 by 100, your end result will remain a double as well. This is why you are seeing 46662.0. So you need to convert it to Int value, so instead you should do it like this:

```<code>double vDouble = 466.62 *100
String vString = vDouble.toInt().toString();
</code>```

This will give you 4662.

For a more generic case, use the String split method;

```<code>String str = '466.62';

//split string
var arr = str.split('.');

print(arr[0]); //will print 466
print(are[1]); //will print 62
</code>```

Title: remove decimal in dart

Body:
When you multiply 466.62 by 100, your end result will remain a double as well. This is why you are seeing 46662.0. So you need to convert it to Int value, so instead you should do it like this:

double vDouble = 466.62 *100
String vString = vDouble.toInt().toString();

This will give you 4662.

For a more generic case, use the String split method;

String str = '466.62';

//split string
var arr = str.split('.');

print(arr[0]); //will print 466
print(are[1]); //will print 62


问:
What is instruction set architecture?
I'm reading Computer Organization and Design, Fifth Edition by Patterson and I'm confused about a few sentences:

Mainly, what is ISA (instruction set architecture)?

Here are some sentences I am having trouble rectifying:

Maintaining the instruction set architecture as a constant enables many implementations of that architecture—presumably varying in cost and performance—to run identical software.

and

The term clock cycles per instruction, which is the average number of clock cycles each instruction takes to execute, is often abbreviated as CPI. Since different instructions may take different amounts of time depending on what they do, CPI is an average of all the instructions executed in the program. CPI provides one way of comparing two different implementations of the same instruction set architecture, since the number of instructions executed for a program will, of course, be the same.

What is an implementation of ISA?

My book's definition:

My book's definition seems lacking... or at least I don't understand what i means:

the instruction set architecture, or simply architecture, of a computer. The instruction set architecture includes anything programmers need to know to make a binary machine language program work correctly, including instructions, I/O devices, and so on. Typically, the operating system will encapsulate the details of doing I/O, allocating memory, and other low-level system functions so that application programmers do not need to worry about such details. The combination of the basic instruction set and the operating system interface provided for application programmers is called the application binary interface (ABI).

also:

the instruction set architecture—the interface between the hardware and low-level software. This abstract interface enables many implementations of varying cost and performance to run identical software.

So is ISA some kind of program that translates software into machine level instruction like turning on and off switches? What is ABI?

答:
I would say ISA is a specification of what a processor should implement, and the implementation detail is called Micro-architecture(e.g. Out-of-Order Execution, Superscalar). So, it could be considered as an interface between software developer and the physical implementation.

So, if an ISA includes add instruction, a processor vendor has to implement such an instruction in their own way. ISA specifies many other things like the support of virtual memory, etc.

A well-known example of ISA is x86-64 and its well-known implementations (i.e. micro-architecture) could be found from Intel and AMD, while their implementations differ across generations(e.g. skylake, coffee lake) as well.

Title: What is instruction set architecture?


问:
Proguard enabled NoSuchMethodException
I'm not getting this issue, If I do not enable Proguard like this:

```<code>buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
</code>```

Logcat:

```<code>java.lang.RuntimeException: java.lang.NoSuchMethodException: com.example.NewUsers$f.<init> [class android.view.View]
    at i.c.a.b.f.b(:147)
    at androidx.recyclerview.widget.RecyclerView$g.a(:7078)
    at androidx.recyclerview.widget.RecyclerView$v.a(:6235)
    at androidx.recyclerview.widget.RecyclerView$v.b(:6118)
    at androidx.recyclerview.widget.RecyclerView$v.d(:6114)
    at androidx.recyclerview.widget.LinearLayoutManager$c.a(:2303)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1627)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1587)
    at androidx.recyclerview.widget.LinearLayoutManager.c(:665)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(:4134)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayout(:3851)
    at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(:1897)
    at androidx.recyclerview.widget.RecyclerView$a.run(:414)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:996)
    at android.view.Choreographer.doCallbacks(Choreographer.java:794)
    at android.view.Choreographer.doFrame(Choreographer.java:725)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:981)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:237)
    at android.app.ActivityThread.main(ActivityThread.java:7807)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)
 Caused by: java.lang.NoSuchMethodException: com.example.NewUsers$f.<init> [class android.view.View]
    at java.lang.Class.getConstructor0(Class.java:2332)
    at java.lang.Class.getConstructor(Class.java:1728)
    at i.c.a.b.f.b(:144)
    at androidx.recyclerview.widget.RecyclerView$g.a(:7078)
    at androidx.recyclerview.widget.RecyclerView$v.a(:6235)
    at androidx.recyclerview.widget.RecyclerView$v.b(:6118)
    at androidx.recyclerview.widget.RecyclerView$v.d(:6114)
    at androidx.recyclerview.widget.LinearLayoutManager$c.a(:2303)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1627)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1587)
    at androidx.recyclerview.widget.LinearLayoutManager.c(:665)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(:4134)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayout(:3851)
    at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(:1897)
    at androidx.recyclerview.widget.RecyclerView$a.run(:414)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:996)
    at android.view.Choreographer.doCallbacks(Choreographer.java:794)
    at android.view.Choreographer.doFrame(Choreographer.java:725)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:981)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:237)
    at android.app.ActivityThread.main(ActivityThread.java:7807)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)
</code>```

Current proguard:

```<code>-keep class com.example.models.** { *; }
</code>```

Java class:

```<code>public class NewUsers extends AppCompatActivity {

    ....

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_users);

        ....

        mNewUsersList = findViewById(R.id.newUsers);
        mNewUsersList.setHasFixedSize(true);
        mNewUsersList.setLayoutManager(new LinearLayoutManager(this));

        onStart();

    }

    @Override
    protected void onStart() {
        super.onStart();
        FirebaseRecyclerAdapter<Users, UsersViewHolder> adapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
                Users.class,
                R.layout.users_list,
                UsersViewHolder.class,
                mDatabaseReference
        ) {

            @Override
            protected void populateViewHolder(UsersViewHolder usersViewHolder, Users users, int position) {
                usersViewHolder.setName(users.getName());

            }
        };
        mNewUsersList.setAdapter(adapter);
    }

    public static class UsersViewHolder extends RecyclerView.ViewHolder {
        View mView;

        public UsersViewHolder(@NonNull View itemView) {
            super(itemView);
            mView = itemView;
        }

        public void setName(String name) {
            TextView mUserNameView = mView.findViewById(R.id.textViewUserName);
            mUserNameView.setText(name);
        }
    }
}
</code>```

Is there any possibilities, I just want to enable minify and shrink for release

Model:

```<code>public class Users {

    String name;

    public Users() {
    }

    public Users(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}
</code>```

答:
Solution 1:

Change your kept class from com.example.model to com.example.

A better solution

If you are importing this class properly in file where you are using it, and not using any kind of reflection, proguard should not remove this.

Try placing it in a common position where you may not need to use reflections or indirect method to access this class

Title: Proguard enabled NoSuchMethodException

Body:
I'm not getting this issue, If I do not enable Proguard like this:

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

Logcat:

java.lang.RuntimeException: java.lang.NoSuchMethodException: com.example.NewUsers$f.<init> [class android.view.View]
    at i.c.a.b.f.b(:147)
    at androidx.recyclerview.widget.RecyclerView$g.a(:7078)
    at androidx.recyclerview.widget.RecyclerView$v.a(:6235)
    at androidx.recyclerview.widget.RecyclerView$v.b(:6118)
    at androidx.recyclerview.widget.RecyclerView$v.d(:6114)
    at androidx.recyclerview.widget.LinearLayoutManager$c.a(:2303)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1627)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1587)
    at androidx.recyclerview.widget.LinearLayoutManager.c(:665)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(:4134)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayout(:3851)
    at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(:1897)
    at androidx.recyclerview.widget.RecyclerView$a.run(:414)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:996)
    at android.view.Choreographer.doCallbacks(Choreographer.java:794)
    at android.view.Choreographer.doFrame(Choreographer.java:725)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:981)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:237)
    at android.app.ActivityThread.main(ActivityThread.java:7807)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)
 Caused by: java.lang.NoSuchMethodException: com.example.NewUsers$f.<init> [class android.view.View]
    at java.lang.Class.getConstructor0(Class.java:2332)
    at java.lang.Class.getConstructor(Class.java:1728)
    at i.c.a.b.f.b(:144)
    at androidx.recyclerview.widget.RecyclerView$g.a(:7078)
    at androidx.recyclerview.widget.RecyclerView$v.a(:6235)
    at androidx.recyclerview.widget.RecyclerView$v.b(:6118)
    at androidx.recyclerview.widget.RecyclerView$v.d(:6114)
    at androidx.recyclerview.widget.LinearLayoutManager$c.a(:2303)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1627)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1587)
    at androidx.recyclerview.widget.LinearLayoutManager.c(:665)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(:4134)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayout(:3851)
    at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(:1897)
    at androidx.recyclerview.widget.RecyclerView$a.run(:414)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:996)
    at android.view.Choreographer.doCallbacks(Choreographer.java:794)
    at android.view.Choreographer.doFrame(Choreographer.java:725)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:981)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:237)
    at android.app.ActivityThread.main(ActivityThread.java:7807)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)

Current proguard:

-keep class com.example.models.** { *; }

Java class:

public class NewUsers extends AppCompatActivity {

    ....

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_users);

        ....

        mNewUsersList = findViewById(R.id.newUsers);
        mNewUsersList.setHasFixedSize(true);
        mNewUsersList.setLayoutManager(new LinearLayoutManager(this));

        onStart();

    }

    @Override
    protected void onStart() {
        super.onStart();
        FirebaseRecyclerAdapter<Users, UsersViewHolder> adapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
                Users.class,
                R.layout.users_list,
                UsersViewHolder.class,
                mDatabaseReference
        ) {

            @Override
            protected void populateViewHolder(UsersViewHolder usersViewHolder, Users users, int position) {
                usersViewHolder.setName(users.getName());

            }
        };
        mNewUsersList.setAdapter(adapter);
    }

    public static class UsersViewHolder extends RecyclerView.ViewHolder {
        View mView;

        public UsersViewHolder(@NonNull View itemView) {
            super(itemView);
            mView = itemView;
        }

        public void setName(String name) {
            TextView mUserNameView = mView.findViewById(R.id.textViewUserName);
            mUserNameView.setText(name);
        }
    }
}

Is there any possibilities, I just want to enable minify and shrink for release

Model:

public class Users {

    String name;

    public Users() {
    }

    public Users(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}


问:
Xamarin android application crash with condition `xref_count == xref_index' not met
Continuously navigation by some pages of my application causes its crash suddenly, with this message:

```<code>[] * Assertion at /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/mono/metadata/sgen-tarjan-bridge.c:1140, condition `xref_count == xref_index' not met, function:processing_build_callback_data, xref_count is 50 but we added 48 xrefs

[libc] Fatal signal 6 (SIGABRT), code -6 in tid 31405 (com.MyApp.Beta)
</code>```

This is how I push pages:

```<code>await ((MasterDetailPage)Application.Current.MainPage).Detail.Navigation.PushAsync(new Page());
</code>```

I read some threads about related issues and tried adding this argument to android compiler:

MONO_GC_PARAMS=bridge-implementation=old,nursery-size=128m,soft-heap-limit=512m

Also tried changing "old" by "new" but no success. Keeps crashing.

This only happens when navigating by 10... 15 pages, if you navigate by few pages it works fine.

What should I do to avoid that?

答:
I needed to create a txt file named as enviroment.txt with same arguments mentioned in question:

MONO_GC_PARAMS=bridge-implementation=old,nursery-size=128m,soft-heap-limit=512m

You can put this at Properties folder, the same of AndroidManifest.xml and set its build action to AndroidEnviroment, now it should work.

Body:
Continuously navigation by some pages of my application causes its crash suddenly, with this message:

[] * Assertion at /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/mono/metadata/sgen-tarjan-bridge.c:1140, condition `xref_count == xref_index' not met, function:processing_build_callback_data, xref_count is 50 but we added 48 xrefs

[libc] Fatal signal 6 (SIGABRT), code -6 in tid 31405 (com.MyApp.Beta)

This is how I push pages:

await ((MasterDetailPage)Application.Current.MainPage).Detail.Navigation.PushAsync(new Page());

I read some threads about related issues and tried adding this argument to android compiler:

MONO_GC_PARAMS=bridge-implementation=old,nursery-size=128m,soft-heap-limit=512m

Also tried changing "old" by "new" but no success. Keeps crashing.

This only happens when navigating by 10... 15 pages, if you navigate by few pages it works fine.

What should I do to avoid that?


问:
I am trying to create a function which will extract foursquare location data for the surroundings of each location with a search query
I have a dataset with the list of colleges in NYC. I am trying to create a function which will extract foursquare venue data for the surroundings of each location with a search query and create a new dataframe which will be a combination of both NY colleges and foursquare venues.
This is a sample of my college dataframe.

```<code>College                                       # Students    Latitude    Longitude
CUNY Borough of Manhattan Community College     26,606      40.7172     -74.0122
Suffolk County Community College                26,600      40.8486     -73.059
Nassau Community College                        22,374      40.0548     -86.943
</code>```

The funtion i am using to get data from foursquare is:

```<code>def getNearbyhotspots(names, latitudes, longitudes, radius=50):

search_query = 'pubs'
venues_list=[]
for name, lat, lng in zip(names, latitudes, longitudes):
    print(name)

    # create the API request URL
    url = 'https://api.foursquare.com/v2/venues/search?client_id={}&client_secret={}&ll={},{}&v={}&query={}&radius={}'.\
    format(CLIENT_ID,
           CLIENT_SECRET,
           lat,
           lng,
           VERSION,
           search_query,
           radius,
           )

    # make the GET request
    results = requests.get(url).json()['response']['venues']

    # return only relevant information for each nearby venue
    venues_list.append([(
        name,
        lat,
        lng,
        v[0]['name'],
        v[0]['location']['lat'],
        v[0]['location']['lng'],
        v[0]['categories'][0]['name']) for v in results])

nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list])
nearby_venues.columns = ['College',
              'College Latitude',
              'College Longitude',
              'Venue',
              'Venue Latitude',
              'Venue Longitude',
              'Venue Category']
return(nearby_venues)
</code>```

I am calling the function and getting an error that goes like:

```<code>ny_pubs = getNearbyhotspots(names=cc_df['College'],
                        latitudes=cc_df['Latitude'],
                        longitudes=cc_df['Longitude']
                        )

CUNY Borough of Manhattan Community College
Suffolk County Community College
Nassau Community College
ValueError: Length mismatch: Expected axis has 0 elements, new values have 7 elements
</code>```

Although i've created a dummy dataframe "nearby_venues" with 7 columns.

I suspect the problem is in the function with appending to the venues_list.

The output of results for a random coordinate value is as such :

```<code>results = requests.get(url).json()['response']['venues']

[{'id': '561b1281498e2a8bbf3b0fff',
'name': "McAteer's Pub",
'location': {'lat': 41.069234,
'lng': -73.799114,
'labeledLatLngs': [{'label': 'display',
 'lat': 41.069234,
 'lng': -73.799114}],
'distance': 708,
'cc': 'US',
'city': 'Greenburgh',
'state': 'NY',
'country': 'United States',
'formattedAddress': ['Greenburgh, NY', 'United States']},
'categories': [{'id': '4bf58dd8d48988d116941735',
'name': 'Bar',
'pluralName': 'Bars',
'shortName': 'Bar',
'icon': {'prefix': 'https://ss3.4sqi.net/img/categories_v2/nightlife/pub_',
 'suffix': '.png'},
'primary': True}],
'referralId': 'v-1590678183',
'hasPerk': False}]
</code>```

答:
A couple things, one Pandas can read JSON directly and make a data frame out of it. I'd check that out. The data you are working with looks well formed enough.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_json.html

Otherwise, this line

```<code>nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list])
</code>```

Should probably be re-written as something like

```<code>nearby_venues = pd.DataFrame(venues_list, columns = LIST_OF_COLUMNS)
</code>```

because pandas can just consume a list of records and make a data frame out of it if it's in a sensible shape.

Body:
I have a dataset with the list of colleges in NYC. I am trying to create a function which will extract foursquare venue data for the surroundings of each location with a search query and create a new dataframe which will be a combination of both NY colleges and foursquare venues.
This is a sample of my college dataframe.

College                                       # Students    Latitude    Longitude
CUNY Borough of Manhattan Community College     26,606      40.7172     -74.0122
Suffolk County Community College                26,600      40.8486     -73.059
Nassau Community College                        22,374      40.0548     -86.943

The funtion i am using to get data from foursquare is:

def getNearbyhotspots(names, latitudes, longitudes, radius=50):

search_query = 'pubs'
venues_list=[]
for name, lat, lng in zip(names, latitudes, longitudes):
    print(name)

    # create the API request URL
    url = 'https://api.foursquare.com/v2/venues/search?client_id={}&client_secret={}&ll={},{}&v={}&query={}&radius={}'.\
    format(CLIENT_ID,
           CLIENT_SECRET,
           lat,
           lng,
           VERSION,
           search_query,
           radius,
           )

    # make the GET request
    results = requests.get(url).json()['response']['venues']

    # return only relevant information for each nearby venue
    venues_list.append([(
        name,
        lat,
        lng,
        v[0]['name'],
        v[0]['location']['lat'],
        v[0]['location']['lng'],
        v[0]['categories'][0]['name']) for v in results])

nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list])
nearby_venues.columns = ['College',
              'College Latitude',
              'College Longitude',
              'Venue',
              'Venue Latitude',
              'Venue Longitude',
              'Venue Category']
return(nearby_venues)

I am calling the function and getting an error that goes like:

ny_pubs = getNearbyhotspots(names=cc_df['College'],
                        latitudes=cc_df['Latitude'],
                        longitudes=cc_df['Longitude']
                        )

CUNY Borough of Manhattan Community College
Suffolk County Community College
Nassau Community College
ValueError: Length mismatch: Expected axis has 0 elements, new values have 7 elements

Although i've created a dummy dataframe "nearby_venues" with 7 columns.

I suspect the problem is in the function with appending to the venues_list.

The output of results for a random coordinate value is as such :

results = requests.get(url).json()['response']['venues']

[{'id': '561b1281498e2a8bbf3b0fff',
'name': "McAteer's Pub",
'location': {'lat': 41.069234,
'lng': -73.799114,
'labeledLatLngs': [{'label': 'display',
 'lat': 41.069234,
 'lng': -73.799114}],
'distance': 708,
'cc': 'US',
'city': 'Greenburgh',
'state': 'NY',
'country': 'United States',
'formattedAddress': ['Greenburgh, NY', 'United States']},
'categories': [{'id': '4bf58dd8d48988d116941735',
'name': 'Bar',
'pluralName': 'Bars',
'shortName': 'Bar',
'icon': {'prefix': 'https://ss3.4sqi.net/img/categories_v2/nightlife/pub_',
 'suffix': '.png'},
'primary': True}],
'referralId': 'v-1590678183',
'hasPerk': False}]

Body:
A couple things, one Pandas can read JSON directly and make a data frame out of it. I'd check that out. The data you are working with looks well formed enough.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_json.html

Otherwise, this line

nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list])

Should probably be re-written as something like

nearby_venues = pd.DataFrame(venues_list, columns = LIST_OF_COLUMNS)

because pandas can just consume a list of records and make a data frame out of it if it's in a sensible shape.


问:
How do I close a Server-Send Events connection in Flask?
The below has given an answer using node.js.

How to close a "Server-Sent Events"-connection on the server?

However, how to do the same thing in python Flask?

答:
It is important to note you need to close the connection on the client as well, otherwise it will try and reopen the connection after a retry timeout.

This was confusing me until I saw this post here: https://stackoverflow.com/a/38235218/5180047

From the link:

The problem here is that the server unexpectedly closes the connection, instead of doing its work while leaving it open. When this happnes, the client re-sends a request to open a connection and to start streaming Server Sent Events. The server then closes the connection again and again, leading to an infinite loop.

After I saw this.. my preferred solution was to close the connection from the server by yielding an expected data message.

On the client (browser)

var sse = new EventSource('/sse');
sse.addEventListener('message', function(e) {
  console.log(e);
  var data = e.data;
  if (!data) {
      console.log('no data in event');
      return;
  }
  if (data === 'finished') {
      console.log('closing connection')
      sse.close()
  }
  // my work here based on message
});
```

<p><strong>My Flask Server</strong></p>

<pre class="lang-py prettyprint-override"><code>from flask import Response

@app_api.route("/sse")
def stream():
    def trackerStream():
        finished = check_if_finished()
        while not finished:
            sleep(1) # poll timeout
            if should_send_event():
                yield f"data: {mydata()}\n\n"
            else:
                yield "data: nodata\n\n"

            finished = check_if_finished()

        yield "data: finished\n\n"

    return Response(trackerStream(), mimetype="text/event-stream")
</code>```

Note: Make sure you're always sending events at some interval from the server to the client. If the user closes the browser, flask will get an error while trying to write to the socket and will close the stream for you. If you aren't writing to the client at some interval, even if you're just writing data: nodata\n\n, then the server could get stuck in a loop.

Body:
It is important to note you need to close the connection on the client as well, otherwise it will try and reopen the connection after a retry timeout.

This was confusing me until I saw this post here: https://stackoverflow.com/a/38235218/5180047

From the link:

The problem here is that the server unexpectedly closes the connection, instead of doing its work while leaving it open. When this happnes, the client re-sends a request to open a connection and to start streaming Server Sent Events. The server then closes the connection again and again, leading to an infinite loop.

After I saw this.. my preferred solution was to close the connection from the server by yielding an expected data message.

On the client (browser)

var sse = new EventSource('/sse');
sse.addEventListener('message', function(e) {
  console.log(e);
  var data = e.data;
  if (!data) {
      console.log('no data in event');
      return;
  }
  if (data === 'finished') {
      console.log('closing connection')
      sse.close()
  }
  // my work here based on message
});

My Flask Server

from flask import Response

@app_api.route("/sse")
def stream():
    def trackerStream():
        finished = check_if_finished()
        while not finished:
            sleep(1) # poll timeout
            if should_send_event():
                yield f"data: {mydata()}\n\n"
            else:
                yield "data: nodata\n\n"

            finished = check_if_finished()

        yield "data: finished\n\n"

    return Response(trackerStream(), mimetype="text/event-stream")

Note: Make sure you're always sending events at some interval from the server to the client. If the user closes the browser, flask will get an error while trying to write to the socket and will close the stream for you. If you aren't writing to the client at some interval, even if you're just writing data: nodata\n\n, then the server could get stuck in a loop.


问:
Send environment variables in Ubuntu Hosts with powershell (Azure DevOps)
I'm facing problems when I try to send an Environment variable between tasks using Powershell and Ubuntu hosts in Azure DevOps build pipelines.

To test and show this issue I have created a pipeline with the following:

-Two tasks are created, the first one is writing an environment variable:

```<code>$EnvVariable= "Value"

Write-Host "##vso[task.setvariable variable=EnvVariable;]$EnvVariable"

Write-Output "##vso[task.setvariable variable=EnvVariable;]$EnvVariable"

</code>```

-The second Task is printing this value in the output:

```<code>Write-Host "env:EnvVariable : $($env:EnvVariable)"

Write-Host "ENV:EnvVariable : $($ENV:EnvVariable)"

Write-Output "env:EnvVariable : $($env:EnvVariable)"

Write-Output "ENV:EnvVariable : $($ENV:EnvVariable)"
</code>```

-The output from this pipeline is looking good in Windows hosts, for example, using "vs2017-win2016" host I get this output:

```<code>env:EnvVariable : Value
ENV:EnvVariable : Value
env:EnvVariable : Value
ENV:EnvVariable : Value
</code>```

-But when I execute this same pipeline in ubuntu hosts I'm not getting the expected output, here you have the output from second task executed in "ubuntu-18.04" build host:

```<code>env:EnvVariable :
ENV:EnvVariable :
env:EnvVariable :
ENV:EnvVariable :
</code>```

As you can see there are no values from environment variable using the same tasks but in ubuntu hosts.

Just to double-check I've used Write-Output and Write-Host to check if the problem is caused by the requirement to use one of those and used env: and ENV: just to check if the case-sensitive variable name is the cause.

Thanks a lot for your time.

答:
I'm facing problems when I try to send an Environment variable between
  tasks using Powershell and Ubuntu hosts in Azure DevOps build
  pipelines.

According to Environment variables:

On UNIX systems (macOS and Linux), environment variables have the format $NAME. On Windows, the format is %NAME% for batch and $env:NAME in PowerShell.

So what you met is expected behavior according to the document.
And to work for both Windows and Linux, I suggest using format $(EnvVariable).

Details:

The difference when you set the variable EnvVariable:

In Linux using Powershell task you should use $env:ENVVARIABLE. Also it works for Powershell task in Windows, but it doesn't work in CMD/bash task.

In Linux using bash task you should use $ENVVARIABLE, but it can't work in PS task.

In both Linux and Windows, no matter bash task, cmd task or powershell task, you can use $(EnvVariable).

Body:
I'm facing problems when I try to send an Environment variable between tasks using Powershell and Ubuntu hosts in Azure DevOps build pipelines.

To test and show this issue I have created a pipeline with the following:

-Two tasks are created, the first one is writing an environment variable:

$EnvVariable= "Value"

Write-Host "##vso[task.setvariable variable=EnvVariable;]$EnvVariable"

Write-Output "##vso[task.setvariable variable=EnvVariable;]$EnvVariable"

-The second Task is printing this value in the output:

Write-Host "env:EnvVariable : $($env:EnvVariable)"

Write-Host "ENV:EnvVariable : $($ENV:EnvVariable)"

Write-Output "env:EnvVariable : $($env:EnvVariable)"

Write-Output "ENV:EnvVariable : $($ENV:EnvVariable)"

-The output from this pipeline is looking good in Windows hosts, for example, using "vs2017-win2016" host I get this output:

env:EnvVariable : Value
ENV:EnvVariable : Value
env:EnvVariable : Value
ENV:EnvVariable : Value

-But when I execute this same pipeline in ubuntu hosts I'm not getting the expected output, here you have the output from second task executed in "ubuntu-18.04" build host:

env:EnvVariable :
ENV:EnvVariable :
env:EnvVariable :
ENV:EnvVariable :

As you can see there are no values from environment variable using the same tasks but in ubuntu hosts.

Just to double-check I've used Write-Output and Write-Host to check if the problem is caused by the requirement to use one of those and used env: and ENV: just to check if the case-sensitive variable name is the cause.

Thanks a lot for your time.


问:
Can clang-format align variable or macro assignments in columns?
Is it possible to have clang-format align variable assignments in columns? For example:

```<code>int someInteger             = 42;
std::string someString      = "string";
const unsigned someUnsigned = 42;

#define SOME_INTEGER        42
#define SOME_STRING_LITERAL "string"
#define SOME_CONSTANT       42

enum Enum {
    ONE   = 1,
    TWO   = 2,
    THREE = 3,
    FOUR  = 4,
    FIVE  = 5,
    SIX   = 6,
    SEVEN = 7
};
</code>```

is more readable than:

```<code>int someInteger = 42;
const unsigned someUnsigned = 42;
std::string someString = "string";

#define SOME_INTEGER 42
#define SOME_STRING_LITERAL "string"
#define SOME_CONSTANT 42

enum Enum {
    ONE = 1,
    TWO = 2,
    THREE = 3,
    FOUR = 4,
    FIVE = 5,
    SIX = 6,
    SEVEN = 7
};
</code>```

I realize that it may not be practical for clang-format to always do this, but when code as already been manually formatted like said code, it would be nice for clang-format to leave the formatting in place.

答:
you can use this options:AlignConsecutiveMacros: true
ref:https://clang.llvm.org/docs/ClangFormatStyleOptions.html
support llvm version: >=10.0</p>

Body:
Is it possible to have clang-format align variable assignments in columns? For example:

int someInteger             = 42;
std::string someString      = "string";
const unsigned someUnsigned = 42;

#define SOME_INTEGER        42
#define SOME_STRING_LITERAL "string"
#define SOME_CONSTANT       42

enum Enum {
    ONE   = 1,
    TWO   = 2,
    THREE = 3,
    FOUR  = 4,
    FIVE  = 5,
    SIX   = 6,
    SEVEN = 7
};

is more readable than:

int someInteger = 42;
const unsigned someUnsigned = 42;
std::string someString = "string";

#define SOME_INTEGER 42
#define SOME_STRING_LITERAL "string"
#define SOME_CONSTANT 42

enum Enum {
    ONE = 1,
    TWO = 2,
    THREE = 3,
    FOUR = 4,
    FIVE = 5,
    SIX = 6,
    SEVEN = 7
};

I realize that it may not be practical for clang-format to always do this, but when code as already been manually formatted like said code, it would be nice for clang-format to leave the formatting in place.


问:
Binding one control to the second control's property when they are placed in different views
I'm looking for a proper way to bind to controls together.
Let's say I have two separate views. Each of those views has a control and I want to bind them together. First control has a dependency property and expects that the second control will be assigned to that property.

If I correctly understand the idea of MVVM, I don't want to have those controls in my viewmodel, just the data. So I'm trying to find a proper way to pass a control from one view to the other.

Dependency property in the View's code behind to bind the control? Would that be correct way to do that? Doesn't look a very clean way though. Considering the fact that the data context of the view would be viewmodel and not the code behind, I'll be forced to bind those controls together in the code instead of declarative way.

Maybe I'm missing something simple here. Any suggestions are appreciated.

To clarify:

The situation is as follows: 2 different views and 2 different controls. Each control resides on separate view. ControlA has a dependency property of type ControlB. So I need to do something similar to element binding but the problem is that I don't have both elements in the same view.

答:
Typically you would enable intra-view communication using the mediator pattern, and not via a dependency property. This allows you to develop the views and controls independently of one another, as a mediator will provide loose coupling between the views.

Assume you have 2 views, with View A containing Control A and View B containing Control B. You also have a view model for each view. The view model is where communication between views is going to occur by using a shared mediator. Alternately, you could add the mediator to each control as a dependency property and bind that property to the view model's mediator.

View A

Contains Control A

Has its DataContext set to ViewModel A

User interaction with Control A gets/sets view model properties using data binding

View model contains a shared reference to the mediator/messenger

View B

Contains Control B

Has its DataContext set to ViewModel B

User interaction with Control B gets/sets view model properties using data binding

View model contains a shared reference to the mediator/messenger

So when a user interacts with control A on view A, the interaction causes the mediator to publish a message that contains information about the event. The view model of view B is subscribed to be notified when this message is published, and updates its properties, which triggers a change in control B via data binding.

The mediator used by both view models is the same instance, often injected into the view models using an IoC container. Implementing a mediator is fairly trivial, and there are also several MVVM toolkits like MVVM Light that provide a 'Messenger' class that enables this sort of communication.

The key idea is that your views and controls no longer have any knowledge of each other, and instead interaction is abstracted as the publication and subscription of messages; facilitating loosely coupled communication between different objects and object types.

Mediator and MVVM resources:

Simple Mediator

MVVM Light Toolkit

Implementing the MVVM Pattern

Event Aggregation


问:
Generating random numbers in Python using random.randrange(). After the final number is generated, a "%" is created. How can I fix this?
```<code>import random

# Main menu.
print('**** Welcome to the Pick-3, Pick-4 lottery number generator! ****\n\
    \nSelect from the following menu:\n\n1. Generate 3-Digit Lottery number\
    \n2. Generate 4-Digit Lottery number\n3. Exit the Application\n')

# Holds the user's selection in memory.
userInput = int(input())

# If-else statements performs proper operation for the user.
if userInput == 1:
    print('\nYou selected 1. The following 3-digit lottery number was generated:\
        \n\n')
    for i in range(3):
        print(random.randrange(1, 10), end = '')

if userInput == 2:
    print('\nYou selected 2. The following 4-digit lottery number was generated:\
        \n\n')
    for i in range(4):
        print(random.randrange(1, 10), end = '')

if userInput == 3:
    print('\nYou selected 3.\n\nThanks for trying the Lottery Application.\
        \n\n*********************************************************')
    SystemExit
</code>```

This is the output I get when I enter 1, for example:

You selected 1. The following 3-digit lottery number was generated:

657%

How can I get rid of this percentage sign? I am using VSCode to compile. Thanks.

答: The % is not output from Python. It's your shell telling you there wasn't a trailing newline (or, rather, that the cursor was left at a nonzero column offset; your shell can't see what output the programs it ran wrote when that output wasn't captured or redirected, but it can query the terminal for cursor position). Your last print before exiting shouldn't have end=''.

Body:
import random

# Main menu.
print('**** Welcome to the Pick-3, Pick-4 lottery number generator! ****\n\
    \nSelect from the following menu:\n\n1. Generate 3-Digit Lottery number\
    \n2. Generate 4-Digit Lottery number\n3. Exit the Application\n')

# Holds the user's selection in memory.
userInput = int(input())

# If-else statements performs proper operation for the user.
if userInput == 1:
    print('\nYou selected 1. The following 3-digit lottery number was generated:\
        \n\n')
    for i in range(3):
        print(random.randrange(1, 10), end = '')

if userInput == 2:
    print('\nYou selected 2. The following 4-digit lottery number was generated:\
        \n\n')
    for i in range(4):
        print(random.randrange(1, 10), end = '')

if userInput == 3:
    print('\nYou selected 3.\n\nThanks for trying the Lottery Application.\
        \n\n*********************************************************')
    SystemExit

This is the output I get when I enter 1, for example:

You selected 1. The following 3-digit lottery number was generated:

657%

How can I get rid of this percentage sign? I am using VSCode to compile. Thanks.


问:
jquery choosing methods
I love using the hide()  and show() methods, but I've come across someone's scripting where they never use it.

Instead I see them using attr() for anything related to display.

```<code>$("#element").attr("style", "visibility:hidden");
$("#element").attr("style", "visibility:visible");
</code>```

Is this just purely preferential?

Or is it more beneficial to use one vs the other?

答:
There are differences for sure. The show() and hide() methods allow you to use animations if you'd like by setting a duration for the show or hide. Also, hide will keep track of the current display settings (inline, block, etc). http://api.jquery.com/hide/

Using .css('display', 'none') or .css('display', 'block') is probably quicker, but it does provide less functionality.

When you use show()/hide() or .css() to control display is preferential based on what you're trying to accomplish.

One more note. TheDramaLama said that hide() removes the element from the source code. I think what TheDramaLama meant is that it removes it positionally, but it still remains in the source code (aka the DOM).

Title: jquery choosing methods

Body:
I love using the hide()  and show() methods, but I've come across someone's scripting where they never use it.

Instead I see them using attr() for anything related to display.

$("#element").attr("style", "visibility:hidden");
$("#element").attr("style", "visibility:visible");

Is this just purely preferential?

Or is it more beneficial to use one vs the other?


问:
How to handle ntlm and proxy authentication with selenium and nodejs
Did anyone solve this?

The URL I am trying to access through

```<code>driver.get("http://example.com")
</code>```

challenges with NTLM authentication and could not handle with selenium. I tried the following but does not work

username:password@url

答:
Solved the issue with a tool called Autoit. Basically it allows you write a script which would find out the ntlm box based on the hint that you provide. and fill in username and password and click enter.

ntml_chrome.au3

```<code>HotKeySet("{ESC}", "Terminate")

For $i=1 to 3
    Local $hWnd = WinWait("Chrome","","10")

    If WinExists($hWnd) Then
        Send("REPLACETHISWITHYOURUSERNAME")
        Send("{TAB}")
        Send("REPLACETHISWITHYOURPASSWORD")
        Send("{Enter}")
    EndIf
Next

Func Terminate()
    Exit 0
EndFunc
</code>```

Which you right click on the file and compile it to give you exe. Run that before you run driver.get(url)

With Nodejs -

```<code>exec("exe path")
driver.get(url)
</code>```

Hope it helps someone.

Cheers

Body:
Did anyone solve this?

The URL I am trying to access through

driver.get("http://example.com")

challenges with NTLM authentication and could not handle with selenium. I tried the following but does not work

username:password@url

Body:
Solved the issue with a tool called Autoit. Basically it allows you write a script which would find out the ntlm box based on the hint that you provide. and fill in username and password and click enter.

ntml_chrome.au3

HotKeySet("{ESC}", "Terminate")

For $i=1 to 3
    Local $hWnd = WinWait("Chrome","","10")

    If WinExists($hWnd) Then
        Send("REPLACETHISWITHYOURUSERNAME")
        Send("{TAB}")
        Send("REPLACETHISWITHYOURPASSWORD")
        Send("{Enter}")
    EndIf
Next

Func Terminate()
    Exit 0
EndFunc

Which you right click on the file and compile it to give you exe. Run that before you run driver.get(url)

With Nodejs -

exec("exe path")
driver.get(url)

Hope it helps someone.

Cheers


问:
replacing componentDidMount with useEffect
I was going through React Hooks docs and it mentioned

If you’re familiar with React class lifecycle methods, you can think
  of useEffect Hook as componentDidMount, componentDidUpdate, and
  componentWillUnmount combined.

Suppose I have a class component right now where in componentDidMount I am doing something like this

```<code>  componentDidMount() {
    MapboxGL.setTelemetryEnabled(false);
  }
</code>```

As far as I can recall, Component did mount is only called once in lifecycle?

If I were to use react hooks then it would be something like this

```<code>  useEffect(() => {
   MapboxGL.setTelemetryEnabled(false);
  });
</code>```

This would call my function everytime state changes in react functional hooks component? Wouldn't it be redundant to call  MapboxGL.setTelemetryEnabled(false); to call this everytime? when you only want to do it once component have mounted?

React docs have showed how useEffect can replace multiple lifecycle methods but I am still unable to comprehend how react hooks can replace componentDidMount?

Also, Just a side note question, Can you make a full fledge app using hooks (something like foursquare or instagram?)

答:
You can create a flag and if the flag is false/true then only perform that action. something as simple as this </p>

```<code> useEffect(() => {
   if (something) {
    MapboxGL.setTelemetryEnabled(false);
    setSomething(false)
    }
  });
</code>```

<p>or if you only need hook once, you can do what Matt have suggested </p>

```<code>useEffect(() => {
   MapboxGL.setTelemetryEnabled(false);
}, []);
</code>```

Body:
I was going through React Hooks docs and it mentioned

If you’re familiar with React class lifecycle methods, you can think
  of useEffect Hook as componentDidMount, componentDidUpdate, and
  componentWillUnmount combined.

Suppose I have a class component right now where in componentDidMount I am doing something like this

  componentDidMount() {
    MapboxGL.setTelemetryEnabled(false);
  }

As far as I can recall, Component did mount is only called once in lifecycle?

If I were to use react hooks then it would be something like this

  useEffect(() => {
   MapboxGL.setTelemetryEnabled(false);
  });

This would call my function everytime state changes in react functional hooks component? Wouldn't it be redundant to call  MapboxGL.setTelemetryEnabled(false); to call this everytime? when you only want to do it once component have mounted?

React docs have showed how useEffect can replace multiple lifecycle methods but I am still unable to comprehend how react hooks can replace componentDidMount?

Also, Just a side note question, Can you make a full fledge app using hooks (something like foursquare or instagram?)

Body:
You can create a flag and if the flag is false/true then only perform that action. something as simple as this

 useEffect(() => {
   if (something) {
    MapboxGL.setTelemetryEnabled(false);
    setSomething(false)
    }
  });

or if you only need hook once, you can do what Matt have suggested

useEffect(() => {
   MapboxGL.setTelemetryEnabled(false);
}, []);


问:
TypeError: 'function' object is not subscriptable python. Im trying to combine every .mp4 file into one video
I'm trying to combine every .mp4 file in a certin folder into one a single .mp4 file

```<code>video_files = glob.glob("*.mp4")
print(video_files)

final = concatenate_videoclips[video_files]
final.write_videofile("new.mp4", codec="libx264")
</code>```

The error I get is

```<code>final = concatenate_videoclips[video_files];
TypeError: 'function' object is not subscriptable
</code>```

if anyone could explain what I am doing wrong I would appreciate it.

答:
First, the subscriptable part meant that you should use ( and ) instead of [ and ]. Second, you cannot simply put the names of the files into the function, you need to first convert them into VideoFileClip:

```<code># from moviepy.editor import VideoFileClip,concatenate_videoclips
# import glob

video_files = glob.glob("*.mp4")

clips = []

for clip in video_files: # For each mp4 file name
    clips.append(VideoFileClip(clip)) # Store them as a VideoFileClip and add to the clips list

final = concatenate_videoclips(clips) # Concatenate the VideoFileClips
final.write_videofile("new.mp4", codec="libx264")
</code>```

Body:
I'm trying to combine every .mp4 file in a certin folder into one a single .mp4 file

video_files = glob.glob("*.mp4")
print(video_files)

final = concatenate_videoclips[video_files]
final.write_videofile("new.mp4", codec="libx264")

The error I get is

final = concatenate_videoclips[video_files];
TypeError: 'function' object is not subscriptable

if anyone could explain what I am doing wrong I would appreciate it.

Body:
First, the subscriptable part meant that you should use ( and ) instead of [ and ]. Second, you cannot simply put the names of the files into the function, you need to first convert them into VideoFileClip:

# from moviepy.editor import VideoFileClip,concatenate_videoclips
# import glob

video_files = glob.glob("*.mp4")

clips = []

for clip in video_files: # For each mp4 file name
    clips.append(VideoFileClip(clip)) # Store them as a VideoFileClip and add to the clips list

final = concatenate_videoclips(clips) # Concatenate the VideoFileClips
final.write_videofile("new.mp4", codec="libx264")


问:
How to obfuscate Flutter apps?
Flutter's wiki mentions obfuscation is an opt-in in release mode.

And yet, the flutter build command has no relevant option - see:

flutter help -v build apk

Am I missing something here?

Did they make obfuscation the default?

Is obfuscation even relevant for flutter?

Any pointers on this would be very appreciated.

答:
AppBundle (recommended):

Without splitting:

```<code>flutter build appbundle --obfuscate --split-debug-info=/<directory>
</code>```

Splitting:

```<code>flutter build appbundle --target-platform android-arm,android-arm64,android-x64 --obfuscate --split-debug-info=/<directory>
</code>```

APK:

Without splitting:

```<code>flutter build apk --obfuscate --split-debug-info=/<directory>
</code>```

Splitting:

```<code>flutter build apk --target-platform android-arm,android-arm64,android-x64 --split-per-abi --obfuscate --split-debug-info=/<directory>
</code>```

PS: About Splitting:

By default, fat apk contains arm v7, arm v8 and x64 which increases apk size, which you don't want to. So, when you split it, you have separate binaries which you can upload on the store and thus reducing the size of the apk that a user would need to download.

Title: How to obfuscate Flutter apps?

Body:
AppBundle (recommended):

Without splitting:

flutter build appbundle --obfuscate --split-debug-info=/<directory>

Splitting:

flutter build appbundle --target-platform android-arm,android-arm64,android-x64 --obfuscate --split-debug-info=/<directory>

APK:

Without splitting:

flutter build apk --obfuscate --split-debug-info=/<directory>

Splitting:

flutter build apk --target-platform android-arm,android-arm64,android-x64 --split-per-abi --obfuscate --split-debug-info=/<directory>

PS: About Splitting:

By default, fat apk contains arm v7, arm v8 and x64 which increases apk size, which you don't want to. So, when you split it, you have separate binaries which you can upload on the store and thus reducing the size of the apk that a user would need to download.