问:
Error inflating class androidx.appcompat.widget.SearchView on Android 5.1.1
I have a search view in XML defined like this:

```<code><androidx.appcompat.widget.SearchView
                    android:id="@+id/sugSearchView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:layout_marginTop="2dp"
                    android:layout_marginEnd="8dp"
                    android:iconifiedByDefault="false"
                    android:layoutDirection="rtl"
                    android:textDirection="firstStrongRtl"
                    android:visibility="visible"
                    app:defaultQueryHint="Search for videos"
                    app:iconifiedByDefault="false"
                    app:layout_constraintTop_toTopOf="parent"
                    app:queryHint="Search for videos">

                </androidx.appcompat.widget.SearchView>
</code>```

I have a crash on Android 5.1.1 devices, i get:

```<code>Fatal Exception: android.view.InflateException
Binary XML file line #150: Error inflating class androidx.appcompat.widget.SearchView
android.view.LayoutInflater.createView

"Caused by java.lang.ArrayIndexOutOfBoundsException
length=6; index=7"
</code>```

I've googled it and found nothing. How can I solve this one? Does version 5.1.1 support androidx.searchview?

答:
its because of this line  android:textDirection="firstStrongRtl"
I too had the same crash and when I changed to ltr.it stopped crashing in 5.1</p>

Body:
I have a search view in XML defined like this:

<androidx.appcompat.widget.SearchView
                    android:id="@+id/sugSearchView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:layout_marginTop="2dp"
                    android:layout_marginEnd="8dp"
                    android:iconifiedByDefault="false"
                    android:layoutDirection="rtl"
                    android:textDirection="firstStrongRtl"
                    android:visibility="visible"
                    app:defaultQueryHint="Search for videos"
                    app:iconifiedByDefault="false"
                    app:layout_constraintTop_toTopOf="parent"
                    app:queryHint="Search for videos">

                </androidx.appcompat.widget.SearchView>

I have a crash on Android 5.1.1 devices, i get:

Fatal Exception: android.view.InflateException
Binary XML file line #150: Error inflating class androidx.appcompat.widget.SearchView
android.view.LayoutInflater.createView

"Caused by java.lang.ArrayIndexOutOfBoundsException
length=6; index=7"

I've googled it and found nothing. How can I solve this one? Does version 5.1.1 support androidx.searchview?


来源: stackexchange

问:
How to consume data from Apache Kafka in Spring Boot
I have got the json using kafka-avro console-consumer. Now I want to get the json in a spring-boot console. What to do next?

答:
You simply need to create a consumer: </p>

```<code>@Service
public class Consumer {

    private final Logger logger = LoggerFactory.getLogger(Consumer.class);

    @KafkaListener(topics = "myTopic", groupId = "myTopic-consumer-group")
    public void consume(String message) throws IOException {
        logger.info(String.format("Message: %s", message));
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You simply need to create a consumer:

@Service
public class Consumer {

    private final Logger logger = LoggerFactory.getLogger(Consumer.class);

    @KafkaListener(topics = "myTopic", groupId = "myTopic-consumer-group")
    public void consume(String message) throws IOException {
        logger.info(String.format("Message: %s", message));
    }
}


问:
Where do I call my function so it successfully updates my UI?
I have written the following function to ensure my user fills in a textField before being able to continue.

```<code>func validateFields() -> String {

    if textfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
        return "Please fill in textField"
    }

    return "A-OK."
}

 func updateUI() {
    let verdict = validateFields()

    if verdict == "A-OK." {
        self.buttonOne.alpha = 1
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

     updateUI()
}
</code>```

However, once the textField has been filled in, the above code fails to update the UI. I know I am missing out on something trivial here, I just cannot wrap my head around what. I'd really appreciate the help.

答:
That's easy you can create an outlet of your text fields and give its
  delegate to self in viewDidLoad() method

```<code>@IBOutlet var txtfld: UITextField!

 override func viewDidLoad() {
    super.viewDidLoad()

    txtfld.delegate = self
 }

 // UITextField Delegates
    func textFieldDidBeginEditing(_ textField: UITextField) {
        print("TextField did begin editing method called")
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        print("TextField did end editing method called")
    }
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        print("TextField should begin editing method called")
        return true;
    }
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        print("TextField should clear method called")
        return true;
    }
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        print("TextField should end editing method called")
        return true;
    }
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        print("While entering the characters this method gets called")
        return true;
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        print("TextField should return method called")
        textField.resignFirstResponder();
        return true;
    }
}
</code>```

I suggest for calling your method you should use your updateUI()
  function in textFieldShouldReturn(_ textField: UITextField) this
  method.

Body:
I have written the following function to ensure my user fills in a textField before being able to continue.

func validateFields() -> String {

    if textfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
        return "Please fill in textField"
    }

    return "A-OK."
}

 func updateUI() {
    let verdict = validateFields()

    if verdict == "A-OK." {
        self.buttonOne.alpha = 1
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

     updateUI()
}

However, once the textField has been filled in, the above code fails to update the UI. I know I am missing out on something trivial here, I just cannot wrap my head around what. I'd really appreciate the help.

Body:
That's easy you can create an outlet of your text fields and give its
  delegate to self in viewDidLoad() method

@IBOutlet var txtfld: UITextField!

 override func viewDidLoad() {
    super.viewDidLoad()

    txtfld.delegate = self
 }

 // UITextField Delegates
    func textFieldDidBeginEditing(_ textField: UITextField) {
        print("TextField did begin editing method called")
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        print("TextField did end editing method called")
    }
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        print("TextField should begin editing method called")
        return true;
    }
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        print("TextField should clear method called")
        return true;
    }
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        print("TextField should end editing method called")
        return true;
    }
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        print("While entering the characters this method gets called")
        return true;
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        print("TextField should return method called")
        textField.resignFirstResponder();
        return true;
    }
}

I suggest for calling your method you should use your updateUI()
  function in textFieldShouldReturn(_ textField: UITextField) this
  method.


问:
How to Run Azure Pipeline Builds Sequentially
I have created an Azure build pipeline using the 'classic editor' (i.e. not yaml). The build consists of two agent jobs:

Job 1 - Build code and deploy to test enviornment using a single agent.

Job 2 - Run tests against the test enviornment in parallel (using max 3 agents at a time).

My problem with this setup is if a build is triggered, and the tests are mid-run, if a second build is triggered, the code that is deployed to the test enviornment will be overwritten by the subsequent build, causing the test run in Job 2 of the first build to fail.

Is it possible to tell the build pipeline to only trigger builds sequentially?

I have figured out how to use Azure DevOps API to check if the latest build has completed, however Im not sure how I can use it in the pipeline. Is it possible to do something like:

1 - Invote REST API to check status of latest build.

2 - Success Criteria met (i.e. the build has completed)? If yes continue build, if not wait a minute and check again.

答:
You have the option to control this in the Build options. Should work based on what you described.

Edit:
After looking again to your question, i noticed that you are running your tests after you deploy your app to test environment, so it means you run your tests during release, so you need to control the flow on your release and not on your buid. In order to do it, you should control on the maximum number of parallel deployments:


问:
how to split a string value that contains characters and numbers
I have a std::string s=n8Name4Surname. How can I obtain in 2 strings the Name and the Surname? THX

答:
One way to do this is using Boost.Tokenizer. See this example:

```<code>#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
int main()
{
    using namespace std;
    using namespace boost;
    string text="n8Name4Surname.";

    char_separator<char> sep("0123456789");
    tokenizer<char_separator<char> > tokens(text, sep);

    string name, surname;
    int count = 0;
    BOOST_FOREACH(const string& s, tokens)
    {
        if(count == 1)
        {
            name = s;
        }
        if(count == 2)
        {
            surname = s;
        }
        ++count;
    }
}
</code>```

EDIT

If you put the results in a vector, its even less code:

```<code>#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
#include <algorithm>
#include <iterator>
#include <vector>

int main()
{
    using namespace std;
    using namespace boost;
    string text="n8Name4Surname.";

    char_separator<char> sep("0123456789");
    tokenizer<char_separator<char> > tokens(text, sep);

    vector<string> names;
    tokenizer<char_separator<char> >::iterator iter = tokens.begin();
    ++iter;
    if(iter != tokens.end())
    {
        copy(iter, tokens.end(), back_inserter(names));
    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
One way to do this is using Boost.Tokenizer. See this example:

#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
int main()
{
    using namespace std;
    using namespace boost;
    string text="n8Name4Surname.";

    char_separator<char> sep("0123456789");
    tokenizer<char_separator<char> > tokens(text, sep);

    string name, surname;
    int count = 0;
    BOOST_FOREACH(const string& s, tokens)
    {
        if(count == 1)
        {
            name = s;
        }
        if(count == 2)
        {
            surname = s;
        }
        ++count;
    }
}

EDIT

If you put the results in a vector, its even less code:

#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
#include <algorithm>
#include <iterator>
#include <vector>

int main()
{
    using namespace std;
    using namespace boost;
    string text="n8Name4Surname.";

    char_separator<char> sep("0123456789");
    tokenizer<char_separator<char> > tokens(text, sep);

    vector<string> names;
    tokenizer<char_separator<char> >::iterator iter = tokens.begin();
    ++iter;
    if(iter != tokens.end())
    {
        copy(iter, tokens.end(), back_inserter(names));
    }

}


问:
Condition based dependency injection
I am using strategy design pattern and want to inject different dependencies based on some conditions.

```<code>public interface strategy {
    public void task();
}

public class concreteStrategyOne implements strategy {
    public void task() {
        //task strategy one
    }
}

public class concreteStrategyTwo implements strategy {
    public void task() {
        //task strategy two
    }
}

public class taskInHand {

    private Strategy strategyImpl;

    @Inject
    public taskInHand(Strategy strategyImpl){
        this.strategy = strategyImpl;
    }

    public void use(Object obj) {

      if(obj.get("something") == 1){
            strategyImpl.task();
            // I want to call task() implemented in concreteStrategyOne
      }
      else if(obj.get("something") == 2){
            strategtImpl.task()
            // I want to call task() implemented in concreteStrategyTwo
      }
}

}
</code>```

I know I can used @Named annotation in a constructor to bind specific classes while injecting but I want to inject different dependencies according the conditions mentioned above.

So, to elaborate.. if(object.get("something")) returns 1, then I would want to run task() implemented in concreteStrategyOne.

How can this be done?

答:
You could use a Provider (I think that's what Guice calls them) that does the selection of the needed implementation and injects the needed one. But you'd need to provide the provider with all the information needed to make the decision. This might break encapsulation and a couple of other SOLID ideas.

The other option would be to inject a collection of all the implementations, iterate over the collection and have the implementations 'volounteer' if they find they're responsible or suited for the specific usecase.

More details about providers can be found in the guice wiki.

Title: Condition based dependency injection

Body:
I am using strategy design pattern and want to inject different dependencies based on some conditions.

public interface strategy {
    public void task();
}

public class concreteStrategyOne implements strategy {
    public void task() {
        //task strategy one
    }
}

public class concreteStrategyTwo implements strategy {
    public void task() {
        //task strategy two
    }
}

public class taskInHand {

    private Strategy strategyImpl;

    @Inject
    public taskInHand(Strategy strategyImpl){
        this.strategy = strategyImpl;
    }

    public void use(Object obj) {

      if(obj.get("something") == 1){
            strategyImpl.task();
            // I want to call task() implemented in concreteStrategyOne
      }
      else if(obj.get("something") == 2){
            strategtImpl.task()
            // I want to call task() implemented in concreteStrategyTwo
      }
}

}

I know I can used @Named annotation in a constructor to bind specific classes while injecting but I want to inject different dependencies according the conditions mentioned above.

So, to elaborate.. if(object.get("something")) returns 1, then I would want to run task() implemented in concreteStrategyOne.

How can this be done?


问:
How to get a normal distribution within a range in numpy?
In machine learning task. We should get a group of random w.r.t normal distribution with bound. We can get a normal distribution number with np.random.normal() but it does't offer any bound parameter. I want to know how to do that?

答:
You can subdivide your targeted range (by convention) to equal partitions and then calculate the integration of each and all area, then call uniform method on each partition according to the surface.
It's implemented in python:

quad_vec(eval('scipy.stats.norm.pdf'), 1, 4,points=[0.5,2.5,3,4],full_output=True)


问:
Remeshing of a triangular mesh for making high quality Delaunay triangulation?
I have a triangular mesh of the brain surface. I want to remesh it to a high-quality Delaunay triangulation. I'm seeking an easy and straightforward method. </p>

答:
I'm not sure if C++ is an option for you but the CGAL library provides such a functionality. See this package, see in particular this example.

If you want to use a GUI, you can use the CGAL polyhedron demo. You can compile it yourself by compiling the code in demo/Polyhedron from a release or use the pre-compiled windows demo available: demo + dlls to be extracted in the directory of the demo. Load your input mesh, select it and click on Operations -> Tetrahedral Mesh Generation -> Create a Surface Triangle Mesh


问:
Getting SQL group query from multiple tables
I'm developing a simple quiz game and I have difficulties in creating an SQL (SQL Server 2016) query. I have the following related tables:

[Authors]
 ID
Name

[Quizzes]
 ID
AuthorID (points to ID in [Authors])

[QuizGames]
 ID
QuizID (points to ID in [Quizzes])

[GamesPlayed]
 ID
QuizGameID (points to ID in [QuizGames])

[Players]
 ID
GamePlayedID (points to ID in [GamesPlayed])
DatePlayed

Given an author's ID (in the first table) I need to get the total number of Players (last table) for all his games played in the last 6 months. For example, I'd need a Stored Procedure /Query that returns me:

```<code>Feb2020  Jan2020   Dec2019   Nov2019   Oct 2019   Sep2019
1404      2512      6521      1421      2150       1120
</code>```

Basically I would need to get author's ID from first table, then look for all the quizzes he createdin the second table, then look for all the games (in the 3rd table) created with his quizzes, then look for all the games (in the 4th table) played with his games, and then look for the players (in the last table, grouped by last 6 months) that played his games.

How can I achieve this?

答:
```<code>SELECT p.DatePlayed, COUNT(p.Id)
FROM [Player] p
JOIN [GamesPlayed] gp on gp.Id = p.GamePlayedId
JOIN [QuizGames] qg on qg.Id = gp.QuizGameId
JOIN [Quizzes] q on q.Id = qg.QuizId
JOIN [Author] a on a.Id = q.AuthorId
WHERE p.DatePlayed >= DATEADD(M, DATEDIFF(M, 0,DATEADD(M, -6, GETUTCDATE())), 0)
GROUP BY p.DatePlayed
</code>```

Body:
I'm developing a simple quiz game and I have difficulties in creating an SQL (SQL Server 2016) query. I have the following related tables:

[Authors]
 ID
Name

[Quizzes]
 ID
AuthorID (points to ID in [Authors])

[QuizGames]
 ID
QuizID (points to ID in [Quizzes])

[GamesPlayed]
 ID
QuizGameID (points to ID in [QuizGames])

[Players]
 ID
GamePlayedID (points to ID in [GamesPlayed])
DatePlayed

Given an author's ID (in the first table) I need to get the total number of Players (last table) for all his games played in the last 6 months. For example, I'd need a Stored Procedure /Query that returns me:

Feb2020  Jan2020   Dec2019   Nov2019   Oct 2019   Sep2019
1404      2512      6521      1421      2150       1120

Basically I would need to get author's ID from first table, then look for all the quizzes he createdin the second table, then look for all the games (in the 3rd table) created with his quizzes, then look for all the games (in the 4th table) played with his games, and then look for the players (in the last table, grouped by last 6 months) that played his games.

How can I achieve this?


问:
Making a condition out of the addEventListener('wpcf7mailsent') CF7
I have here a code that triggers when a particular CF7 form is submitted

```<code>document.addEventListener( 'wpcf7mailsent', function( event ) {
    if(event.detail.contactFormId == '11164') {
    jQuery('.pop_timer_box').hide();
    }
}, false );
</code>```

but how can I make this a condition like

```<code>if (wpcf7mailsent) {
   do this
} elseif (wpcf7mailfail) {
   do this
}
</code>```

Thanks for the help!!!

答:
Just add a second event listener for failed.

```<code>document.addEventListener( 'wpcf7mailfailed ', function( event ) {
    alert( "Mail Failed Event" ); // Make this whatever you want.
}, false );
</code>```

Contact Form 7 Documentation

Body:
I have here a code that triggers when a particular CF7 form is submitted

document.addEventListener( 'wpcf7mailsent', function( event ) {
    if(event.detail.contactFormId == '11164') {
    jQuery('.pop_timer_box').hide();
    }
}, false );

but how can I make this a condition like

if (wpcf7mailsent) {
   do this
} elseif (wpcf7mailfail) {
   do this
}

Thanks for the help!!!

Body:
Just add a second event listener for failed.

document.addEventListener( 'wpcf7mailfailed ', function( event ) {
    alert( "Mail Failed Event" ); // Make this whatever you want.
}, false );

Contact Form 7 Documentation


问:
Return date as ddmmyyyy in SQL Server
I need the date as ddmmyyyy without any spacers.

How can I do this?

I can get yyyymmdd using CONVERT(VARCHAR, [MyDateTime], 112)

But I need the reverse of this.

SQL Server 2008

答:
Try this:

```<code>SELECT CONVERT(DATE, STUFF(STUFF('01012020', 5, 0, '-'), 3, 0, '-'), 103);
</code>```

It works with SQL Server 2016.

Title: Return date as ddmmyyyy in SQL Server

Body:
Try this:

SELECT CONVERT(DATE, STUFF(STUFF('01012020', 5, 0, '-'), 3, 0, '-'), 103);

It works with SQL Server 2016.


问:
How to optimize query set from duplicated query
```<code>1.(0.001) SELECT COUNT(*) FROM (SELECT COUNT(DISTINCT "entities_hero"."id") AS "_hero_count", COUNT(DISTINCT "entities_villain"."id") AS "_villain_count" FROM "entities_origin" LEFT OUTER JOIN "entities_hero" ON ("entities_origin"."id" = "entities_hero"."origin_id") LEFT OUTER JOIN "entities_villain" ON ("entities_origin"."id" = "entities_villain"."origin_id") GROUP BY "entities_origin"."id") subquery; args=()

2.(0.000) SELECT COUNT(*) FROM (SELECT COUNT(DISTINCT "entities_hero"."id") AS "_hero_count", COUNT(DISTINCT "entities_villain"."id") AS "_villain_count" FROM "entities_origin" LEFT OUTER JOIN "entities_hero" ON ("entities_origin"."id" = "entities_hero"."origin_id") LEFT OUTER JOIN "entities_villain" ON ("entities_origin"."id" = "entities_villain"."origin_id") GROUP BY "entities_origin"."id") subquery; args=()

  (0.001) SELECT "entities_origin"."id", "entities_origin"."name", COUNT(DISTINCT "entities_hero"."id") AS "_hero_count", COUNT(DISTINCT "entities_villain"."id") AS "_villain_count" FROM "entities_origin" LEFT OUTER JOIN "entities_hero" ON ("entities_origin"."id" = "entities_hero"."origin_id") LEFT OUTER JOIN "entities_villain" ON ("entities_origin"."id" = "entities_villain"."origin_id") GROUP BY "entities_origin"."id" ORDER BY "entities_origin"."id" DESC; args=()
</code>```

entities/models.py

```<code>from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = "Categories"

    def __str__(self):
        return self.name

class Origin(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Entity(models.Model):
    GENDER_MALE = "Male"
    GENDER_FEMALE = "Female"
    GENDER_OTHERS = "Others/Unknown"

    choice = (
        (GENDER_MALE, GENDER_MALE),
        (GENDER_FEMALE, GENDER_FEMALE),
        (GENDER_OTHERS, GENDER_OTHERS),
    )

    name = models.CharField(max_length=100)
    alternative_name = models.CharField(max_length=100, null=True, blank=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    origin = models.ForeignKey(Origin, on_delete=models.CASCADE)
    gender = models.CharField(max_length=100, choices=choice)
    description = models.TextField()

    def __str__(self):
        return self.name

    class Meta:
        abstract = True

class Hero(Entity):

    class Meta:
        verbose_name_plural = "Heroes"

    is_immortal = models.BooleanField(default=True)
    benevolence_factor = models.PositiveSmallIntegerField(help_text="How benevolent this hero is?")
    arbitrariness_factor = models.PositiveSmallIntegerField(help_text="How arbitrary this hero is?")
    father = models.ForeignKey("self", related_name="+", null=True, blank=True, on_delete=models.SET_NULL)
    mother = models.ForeignKey("self", related_name="+", null=True, blank=True, on_delete=models.SET_NULL)
    spouse = models.ForeignKey("self", related_name="+", null=True, blank=True, on_delete=models.SET_NULL)

class Villain(Entity):
    is_immortal = models.BooleanField(default=False)
    malevolence_factor = models.PositiveSmallIntegerField(help_text="How malevolent this villain is?")
    power_factor = models.PositiveSmallIntegerField(help_text="How powerful this villain is?")
    is_unique = models.BooleanField(default=True)
    count = models.PositiveSmallIntegerField(default=1)
</code>```

entities/admin.py

```<code>@admin.register(Origin)
class OriginAdmin(admin.ModelAdmin):

    list_display = ("name","hero_count", "villain_count")

    def get_queryset(self, request):
        queryset = self.model.objects.all().annotate(
            _hero_count=Count("hero", distinct=True),
            _villain_count=Count("villain", distinct=True),
        )
        return queryset

    def hero_count(self, obj):
        return obj._hero_count

    def villain_count(self, obj):
        return obj._villain_count
</code>```

答:
Django admin runs count(*) query twice in the list page.

To get object count. Django admin displays object count in the list page. This can be disabled by setting show_full_result_count = False as mentioned in docs.

Django pagination. Django paginator does a count(*) to generate pagination. For large tables, running this query everytime will make the page load slower. A quick fix is to cache the count in paginator and re-use. With this, first time page load will be slower but subsequent pages will load faster. Here is a snippet for django cached paginator.

Body:
1.(0.001) SELECT COUNT(*) FROM (SELECT COUNT(DISTINCT "entities_hero"."id") AS "_hero_count", COUNT(DISTINCT "entities_villain"."id") AS "_villain_count" FROM "entities_origin" LEFT OUTER JOIN "entities_hero" ON ("entities_origin"."id" = "entities_hero"."origin_id") LEFT OUTER JOIN "entities_villain" ON ("entities_origin"."id" = "entities_villain"."origin_id") GROUP BY "entities_origin"."id") subquery; args=()

2.(0.000) SELECT COUNT(*) FROM (SELECT COUNT(DISTINCT "entities_hero"."id") AS "_hero_count", COUNT(DISTINCT "entities_villain"."id") AS "_villain_count" FROM "entities_origin" LEFT OUTER JOIN "entities_hero" ON ("entities_origin"."id" = "entities_hero"."origin_id") LEFT OUTER JOIN "entities_villain" ON ("entities_origin"."id" = "entities_villain"."origin_id") GROUP BY "entities_origin"."id") subquery; args=()

  (0.001) SELECT "entities_origin"."id", "entities_origin"."name", COUNT(DISTINCT "entities_hero"."id") AS "_hero_count", COUNT(DISTINCT "entities_villain"."id") AS "_villain_count" FROM "entities_origin" LEFT OUTER JOIN "entities_hero" ON ("entities_origin"."id" = "entities_hero"."origin_id") LEFT OUTER JOIN "entities_villain" ON ("entities_origin"."id" = "entities_villain"."origin_id") GROUP BY "entities_origin"."id" ORDER BY "entities_origin"."id" DESC; args=()

entities/models.py

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = "Categories"

    def __str__(self):
        return self.name

class Origin(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Entity(models.Model):
    GENDER_MALE = "Male"
    GENDER_FEMALE = "Female"
    GENDER_OTHERS = "Others/Unknown"

    choice = (
        (GENDER_MALE, GENDER_MALE),
        (GENDER_FEMALE, GENDER_FEMALE),
        (GENDER_OTHERS, GENDER_OTHERS),
    )

    name = models.CharField(max_length=100)
    alternative_name = models.CharField(max_length=100, null=True, blank=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    origin = models.ForeignKey(Origin, on_delete=models.CASCADE)
    gender = models.CharField(max_length=100, choices=choice)
    description = models.TextField()

    def __str__(self):
        return self.name

    class Meta:
        abstract = True

class Hero(Entity):

    class Meta:
        verbose_name_plural = "Heroes"

    is_immortal = models.BooleanField(default=True)
    benevolence_factor = models.PositiveSmallIntegerField(help_text="How benevolent this hero is?")
    arbitrariness_factor = models.PositiveSmallIntegerField(help_text="How arbitrary this hero is?")
    father = models.ForeignKey("self", related_name="+", null=True, blank=True, on_delete=models.SET_NULL)
    mother = models.ForeignKey("self", related_name="+", null=True, blank=True, on_delete=models.SET_NULL)
    spouse = models.ForeignKey("self", related_name="+", null=True, blank=True, on_delete=models.SET_NULL)

class Villain(Entity):
    is_immortal = models.BooleanField(default=False)
    malevolence_factor = models.PositiveSmallIntegerField(help_text="How malevolent this villain is?")
    power_factor = models.PositiveSmallIntegerField(help_text="How powerful this villain is?")
    is_unique = models.BooleanField(default=True)
    count = models.PositiveSmallIntegerField(default=1)

entities/admin.py

@admin.register(Origin)
class OriginAdmin(admin.ModelAdmin):

    list_display = ("name","hero_count", "villain_count")

    def get_queryset(self, request):
        queryset = self.model.objects.all().annotate(
            _hero_count=Count("hero", distinct=True),
            _villain_count=Count("villain", distinct=True),
        )
        return queryset

    def hero_count(self, obj):
        return obj._hero_count

    def villain_count(self, obj):
        return obj._villain_count


问:
Tips of coding java programs in multicore scenario
There seems to be a lot of fuss about multicore and java. While some people say that java support is not good enough, it definitely seems to be an area to look forward to. There seems to be many techniques to improve performance of concurrent programs.

Any tips/advices about programming in a multi core scenario is appreciated.

答:
Check out the forthcoming fork-join framework. The fork-join framework enables developers to achieve fine-grained parallelism on multicore architectures.

Also you may want to check out JVM based languages like Clojure that claim to make multicore parallel programming easier.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Julien Chastang


问:
Executing Assembly Code on Windows XP?
I'm running a WINXP, and I'm quite curious as to how you run or execute assembly code. Is there some sort of application I need, or do I need to run it from a terminal...?</p>

答: You don't run or execute assembly code. Before it can be executed, it needs to be assembled into an executable (hence the name).</p>

Title: Executing Assembly Code on Windows XP?


问:
How to customize the "Hello and welcome" default response message in Microsoft Azure Bot QnA framework
I'm trying to make a chatbot using Microsoft Azure web app bot design for QnA bot (using QnA maker for the knowledgebase. I found out how to rewrite in code default response message "no good match in FAQ". Isn't it possible to rewrite similar way also the "Hello and Welcome" default message somewhere in the code?This is how I changed the "no good match in FAQ" default message in code </p>

答: Perhaps you can post some code of the bot itself where this message exactly occurs, but generally this kind of "welcome" message is handled in the OnMembersAdded event handler. See here as an example and you should have something similar in your project. I would guess without seeing more of your application that it's in your "QnABot.cs" file.</p>


问:
Correct way to build OpenCV as a third party library along with your project in CMAKE
I have a C++ project, where I use opencv, VTK. I would like to build and install these dependent libraries (opencv,vtk) automatically, which are situated in my thirdparty project folder. I know that opencv and VTK use cmake build system to build their libraries. I even saw the function ExternalProject to add them to my CMakesLists.txt but I had problem of linking the target with opencv libs.

Searching on stack overflow I could not find a proper defined method to do it to implement this for version 3.0, the proposed solutions where Version < 3.0.  I would like to know how you will structure your project to build opencv automatically as a thirdparty library, exports its targets and link it with my project target.

答:
I think that the best way is to look for what's being done on larger project on github. I would advise to look at this repo in which they use opencv version 3.2, automatically download it and compile it. I believe that this is the correct way because you just have to change the version to try the compatibility with the newer versions if you want to update your code.

What you are looking for is probably what is called a superbuild. This post might help.


问:
Canvas Signature on Signature Pad turns out fully black when downloading as JPG, PNG
I am using Signature pad js from szimek for making canvas signature pad. I have used 3 canvas at a time. After some research I got a link from Codepen for using multiple instance. Its working though, but the problem arise when the signature needs to be downloaded. After download the PNG and JPG, the images get fully black. Sharing the codes below.

var wrapper1 = document.getElementById("signature-pad-1"),
    canvas1 = wrapper1.querySelector("canvas"),
    signaturePad1;

var wrapper2 = document.getElementById("signature-pad-2"),
    canvas2 = wrapper2.querySelector("canvas"),
    signaturePad2;

function resizeCanvas(canvas) {
    var ratio =  window.devicePixelRatio || 1;
    canvas.width = canvas.offsetWidth * ratio;
    canvas.height = canvas.offsetHeight * ratio;
    canvas.getContext("2d").scale(ratio, ratio);
}

function clear1() { signaturePad1.clear(); }
function clear2() { signaturePad2.clear(); }

function save() {
    if (signaturePad1.isEmpty() || signaturePad2.isEmpty())
        alert("Error: Please sign both pads!");
    else
        alert("Success!");
}

resizeCanvas(canvas1);
signaturePad1 = new SignaturePad(canvas1);

resizeCanvas(canvas2);
signaturePad2 = new SignaturePad(canvas2);

$("#clear1").click(clear1);
$("#clear2").click(clear2);
$("#save").click(save);

var savePNGButton1 = wrapper1.querySelector("[data-action=save-png]");
var saveJPGButton1 = wrapper1.querySelector("[data-action=save-jpg]");
var saveSVGButton1 = wrapper1.querySelector("[data-action=save-svg]");

var savePNGButton2 = wrapper2.querySelector("[data-action=save-png]");
var saveJPGButton2 = wrapper2.querySelector("[data-action=save-jpg]");
var saveSVGButton2 = wrapper2.querySelector("[data-action=save-svg]");

// One could simply use Canvas#toBlob method instead, but it's just to show
// that it can be done using result of SignaturePad#toDataURL.
function dataURLToBlob(dataURL) {
  // Code taken from https://github.com/ebidel/filer.js
  var parts = dataURL.split(';base64,');
  var contentType = parts[0].split(":")[1];
  var raw = window.atob(parts[1]);
  var rawLength = raw.length;
  var uInt8Array = new Uint8Array(rawLength);

  for (var i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }

  return new Blob([uInt8Array], { type: contentType });
}

function download(dataURL, filename) {
  if (navigator.userAgent.indexOf("Safari") > -1 && navigator.userAgent.indexOf("Chrome") === -1) {
    window.open(dataURL);
  } else {
    var blob = dataURLToBlob(dataURL);
    var url = window.URL.createObjectURL(blob);

    var a = document.createElement("a");
    a.style = "display: none";
    a.href = url;
    a.download = filename;

    document.body.appendChild(a);
    a.click();

    window.URL.revokeObjectURL(url);
  }
}

savePNGButton1.addEventListener("click", function (event) {
  if (signaturePad1.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad1.toDataURL();
    download(dataURL, "signature.png");
  }
});

saveJPGButton1.addEventListener("click", function (event) {
  if (signaturePad1.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad1.toDataURL("image/jpeg");
    download(dataURL, "signature.jpg");
  }
});

saveSVGButton1.addEventListener("click", function (event) {
  if (signaturePad1.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad1.toDataURL('image/svg+xml');
    download(dataURL, "signature.svg");
  }
});

savePNGButton2.addEventListener("click", function (event) {
  if (signaturePad2.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad2.toDataURL();
    download(dataURL, "signature.png");
  }
});

saveJPGButton2.addEventListener("click", function (event) {
  if (signaturePad2.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad2.toDataURL("image/jpeg");
    download(dataURL, "signature.jpg");
  }
});

saveSVGButton2.addEventListener("click", function (event) {
  if (signaturePad2.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad2.toDataURL('image/svg+xml');
    download(dataURL, "signature.svg");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code> body {
  font-family: Helvetica, Sans-Serif;

  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
}

.m-signature-pad {
  position: relative;
  font-size: 10px;
  width: 400px;
  height: 400px;
  border: 1px solid #e8e8e8;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.27), 0 0 40px rgba(0, 0, 0, 0.08) inset;
  border-radius: 4px;
}

.m-signature-pad:before, .m-signature-pad:after {
 position: absolute;
    z-index: -1;
    content: "";
 width: 40%;
 height: 10px;
 left: 20px;
 bottom: 10px;
 background: transparent;
 -webkit-transform: skew(-3deg) rotate(-3deg);
 -moz-transform: skew(-3deg) rotate(-3deg);
 -ms-transform: skew(-3deg) rotate(-3deg);
 -o-transform: skew(-3deg) rotate(-3deg);
 transform: skew(-3deg) rotate(-3deg);
 box-shadow: 0 8px 12px rgba(0, 0, 0, 0.4);
}

.m-signature-pad:after {
 left: auto;
 right: 20px;
 -webkit-transform: skew(3deg) rotate(3deg);
 -moz-transform: skew(3deg) rotate(3deg);
 -ms-transform: skew(3deg) rotate(3deg);
 -o-transform: skew(3deg) rotate(3deg);
 transform: skew(3deg) rotate(3deg);
}

.m-signature-pad--body {
  position: absolute;
  left: 20px;
  right: 20px;
  top: 20px;
  bottom: 20px;
  border: 1px solid #f4f4f4;
}

.m-signature-pad--body canvas {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    border-radius: 4px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.02) inset;
 background-color: #fff;
  }

  .btn-grp{display:block; width:100%;}
  .signature-pad--footer{position:absolute; bottom:0; left:0; right:0;}

@media screen and (max-width: 1024px) {
  .m-signature-pad {
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 50%;
    height: auto;
    min-width: 100px;
    min-height: 100px;
    margin: 5%;
  }
  #github {
    display: none;
  }
}

@media screen and (min-device-width: 768px) and (max-device-width: 1024px) {
  .m-signature-pad {
    margin: 10%;
  }
}

@media screen and (max-height: 320px) {
  .m-signature-pad--body {
    left: 0;
    right: 0;
    top: 0;
    bottom: 32px;
  }
  .m-signature-pad--footer {
    left: 20px;
    right: 20px;
    bottom: 4px;
    height: 28px;
  }
  .m-signature-pad--footer
    .description {
      font-size: 1em;
      margin-top: 1em;
    }
}</code>```

    <canvas></canvas>

          <button type="button" class="button clear" data-action="clear">Clear</button>
          <button type="button" class="button" data-action="change-color">Change color</button>
          <button type="button" class="button" data-action="undo">Undo</button>

          <button type="button" class="button save" data-action="save-png">Save as PNG</button>
          <button type="button" class="button save" data-action="save-jpg">Save as JPG</button>
          <button type="button" class="button save" data-action="save-svg">Save as SVG</button>

<button id="clear1" onclick="clear(1);">Clear</button>

    <canvas></canvas>

          <button type="button" class="button clear" data-action="clear">Clear</button>
          <button type="button" class="button" data-action="change-color">Change color</button>
          <button type="button" class="button" data-action="undo">Undo</button>

          <button type="button" class="button save" data-action="save-png">Save as PNG</button>
          <button type="button" class="button save" data-action="save-jpg">Save as JPG</button>
          <button type="button" class="button save" data-action="save-svg">Save as SVG</button>

<button id="clear2" onclick="clear(2);">Clear</button>

<button id="save">Save</button>```

答:
The problem is that you're not setting the background colour, so the JPG is defaulting to black, which means that the whole image is black, because it can't handle transparency.

It's not a problem for PNG or SVG, which is why these work as expected.

To fix it set the background colour of the signature pad to white (taken from the signature pad example):

var signaturePad = new SignaturePad(canvas, {
  // It's Necessary to use an opaque color when saving image as JPEG;
  // this option can be omitted if only saving as PNG or SVG
  backgroundColor: 'rgb(255, 255, 255)'
});
```

<p>To apply the above to your code:</p>

<pre class="lang-js prettyprint-override"><code>signaturePad1 = new SignaturePad(canvas1, {backgroundColor: 'rgb(255, 255, 255)'});
</code>```

Body:
I am using Signature pad js from szimek for making canvas signature pad. I have used 3 canvas at a time. After some research I got a link from Codepen for using multiple instance. Its working though, but the problem arise when the signature needs to be downloaded. After download the PNG and JPG, the images get fully black. Sharing the codes below.

var wrapper1 = document.getElementById("signature-pad-1"),
    canvas1 = wrapper1.querySelector("canvas"),
    signaturePad1;

var wrapper2 = document.getElementById("signature-pad-2"),
    canvas2 = wrapper2.querySelector("canvas"),
    signaturePad2;

function resizeCanvas(canvas) {
    var ratio =  window.devicePixelRatio || 1;
    canvas.width = canvas.offsetWidth * ratio;
    canvas.height = canvas.offsetHeight * ratio;
    canvas.getContext("2d").scale(ratio, ratio);
}

function clear1() { signaturePad1.clear(); }
function clear2() { signaturePad2.clear(); }

function save() {
    if (signaturePad1.isEmpty() || signaturePad2.isEmpty())
        alert("Error: Please sign both pads!");
    else
        alert("Success!");
}

resizeCanvas(canvas1);
signaturePad1 = new SignaturePad(canvas1);

resizeCanvas(canvas2);
signaturePad2 = new SignaturePad(canvas2);

$("#clear1").click(clear1);
$("#clear2").click(clear2);
$("#save").click(save);

var savePNGButton1 = wrapper1.querySelector("[data-action=save-png]");
var saveJPGButton1 = wrapper1.querySelector("[data-action=save-jpg]");
var saveSVGButton1 = wrapper1.querySelector("[data-action=save-svg]");

var savePNGButton2 = wrapper2.querySelector("[data-action=save-png]");
var saveJPGButton2 = wrapper2.querySelector("[data-action=save-jpg]");
var saveSVGButton2 = wrapper2.querySelector("[data-action=save-svg]");

// One could simply use Canvas#toBlob method instead, but it's just to show
// that it can be done using result of SignaturePad#toDataURL.
function dataURLToBlob(dataURL) {
  // Code taken from https://github.com/ebidel/filer.js
  var parts = dataURL.split(';base64,');
  var contentType = parts[0].split(":")[1];
  var raw = window.atob(parts[1]);
  var rawLength = raw.length;
  var uInt8Array = new Uint8Array(rawLength);

  for (var i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }

  return new Blob([uInt8Array], { type: contentType });
}

function download(dataURL, filename) {
  if (navigator.userAgent.indexOf("Safari") > -1 && navigator.userAgent.indexOf("Chrome") === -1) {
    window.open(dataURL);
  } else {
    var blob = dataURLToBlob(dataURL);
    var url = window.URL.createObjectURL(blob);

    var a = document.createElement("a");
    a.style = "display: none";
    a.href = url;
    a.download = filename;

    document.body.appendChild(a);
    a.click();

    window.URL.revokeObjectURL(url);
  }
}

savePNGButton1.addEventListener("click", function (event) {
  if (signaturePad1.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad1.toDataURL();
    download(dataURL, "signature.png");
  }
});

saveJPGButton1.addEventListener("click", function (event) {
  if (signaturePad1.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad1.toDataURL("image/jpeg");
    download(dataURL, "signature.jpg");
  }
});

saveSVGButton1.addEventListener("click", function (event) {
  if (signaturePad1.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad1.toDataURL('image/svg+xml');
    download(dataURL, "signature.svg");
  }
});

savePNGButton2.addEventListener("click", function (event) {
  if (signaturePad2.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad2.toDataURL();
    download(dataURL, "signature.png");
  }
});

saveJPGButton2.addEventListener("click", function (event) {
  if (signaturePad2.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad2.toDataURL("image/jpeg");
    download(dataURL, "signature.jpg");
  }
});

saveSVGButton2.addEventListener("click", function (event) {
  if (signaturePad2.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad2.toDataURL('image/svg+xml');
    download(dataURL, "signature.svg");
  }
});

 body {
  font-family: Helvetica, Sans-Serif;

  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
}

.m-signature-pad {
  position: relative;
  font-size: 10px;
  width: 400px;
  height: 400px;
  border: 1px solid #e8e8e8;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.27), 0 0 40px rgba(0, 0, 0, 0.08) inset;
  border-radius: 4px;
}

.m-signature-pad:before, .m-signature-pad:after {
 position: absolute;
    z-index: -1;
    content: "";
 width: 40%;
 height: 10px;
 left: 20px;
 bottom: 10px;
 background: transparent;
 -webkit-transform: skew(-3deg) rotate(-3deg);
 -moz-transform: skew(-3deg) rotate(-3deg);
 -ms-transform: skew(-3deg) rotate(-3deg);
 -o-transform: skew(-3deg) rotate(-3deg);
 transform: skew(-3deg) rotate(-3deg);
 box-shadow: 0 8px 12px rgba(0, 0, 0, 0.4);
}

.m-signature-pad:after {
 left: auto;
 right: 20px;
 -webkit-transform: skew(3deg) rotate(3deg);
 -moz-transform: skew(3deg) rotate(3deg);
 -ms-transform: skew(3deg) rotate(3deg);
 -o-transform: skew(3deg) rotate(3deg);
 transform: skew(3deg) rotate(3deg);
}

.m-signature-pad--body {
  position: absolute;
  left: 20px;
  right: 20px;
  top: 20px;
  bottom: 20px;
  border: 1px solid #f4f4f4;
}

.m-signature-pad--body canvas {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    border-radius: 4px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.02) inset;
 background-color: #fff;
  }

  .btn-grp{display:block; width:100%;}
  .signature-pad--footer{position:absolute; bottom:0; left:0; right:0;}

@media screen and (max-width: 1024px) {
  .m-signature-pad {
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 50%;
    height: auto;
    min-width: 100px;
    min-height: 100px;
    margin: 5%;
  }
  #github {
    display: none;
  }
}

@media screen and (min-device-width: 768px) and (max-device-width: 1024px) {
  .m-signature-pad {
    margin: 10%;
  }
}

@media screen and (max-height: 320px) {
  .m-signature-pad--body {
    left: 0;
    right: 0;
    top: 0;
    bottom: 32px;
  }
  .m-signature-pad--footer {
    left: 20px;
    right: 20px;
    bottom: 4px;
    height: 28px;
  }
  .m-signature-pad--footer
    .description {
      font-size: 1em;
      margin-top: 1em;
    }
}

    <canvas></canvas>

          <button type="button" class="button clear" data-action="clear">Clear</button>
          <button type="button" class="button" data-action="change-color">Change color</button>
          <button type="button" class="button" data-action="undo">Undo</button>

          <button type="button" class="button save" data-action="save-png">Save as PNG</button>
          <button type="button" class="button save" data-action="save-jpg">Save as JPG</button>
          <button type="button" class="button save" data-action="save-svg">Save as SVG</button>

<button id="clear1" onclick="clear(1);">Clear</button>

    <canvas></canvas>

          <button type="button" class="button clear" data-action="clear">Clear</button>
          <button type="button" class="button" data-action="change-color">Change color</button>
          <button type="button" class="button" data-action="undo">Undo</button>

          <button type="button" class="button save" data-action="save-png">Save as PNG</button>
          <button type="button" class="button save" data-action="save-jpg">Save as JPG</button>
          <button type="button" class="button save" data-action="save-svg">Save as SVG</button>

<button id="clear2" onclick="clear(2);">Clear</button>

<button id="save">Save</button>

Body:
The problem is that you're not setting the background colour, so the JPG is defaulting to black, which means that the whole image is black, because it can't handle transparency.

It's not a problem for PNG or SVG, which is why these work as expected.

To fix it set the background colour of the signature pad to white (taken from the signature pad example):

var signaturePad = new SignaturePad(canvas, {
  // It's Necessary to use an opaque color when saving image as JPEG;
  // this option can be omitted if only saving as PNG or SVG
  backgroundColor: 'rgb(255, 255, 255)'
});

To apply the above to your code:

signaturePad1 = new SignaturePad(canvas1, {backgroundColor: 'rgb(255, 255, 255)'});


问:
Add click event to datatable cell
I'm trying to add a click event to a dynamically created a datatabe. So this is my js :

```<code>   $('#report-table').dataTable({
        "proccessing": true,
        "serverSide": true,
        "ajax": {
            url: '@Url.Action("Get","Controller")',
            type: 'GET'

        },
       "columns": [
           { "data": "Name" },
                { "data": "Date" }, //lest say I want to add a click event here ???
                { "data": "sName", render: myRender }// I tried render but this is rendered without waiting on click function
        ]

    });
</code>```

and this is my table for example :

```<code><tr role="row" class="odd">
<td class="sorting_1">A Test</td>
<td class="aaaa">2/13/2020 3:34:40 PM</td> //lets say I want to fire a click event when I click the .aaaa class
<td>
    <a  asp-route-fileid="55555555" asp-action="Download5"><img src="img/download.svg" height="30" width="30"></a>
</td>
</code>```

Let's say I want to fire a click event when I click the .aaaa class.

Can anyone please give me an idea? Can I do this?
I'm stucked right here. Any idea would be apprecciated very very much :)

答:
Instead of render use className to add a class to the cell

```<code>   "columns": [
        { "data": "Name" },
        {
            "data": "Date",
            "className": "your-class"
        },
        { "data": "sName" }
   ]
</code>```

then put an on click event handler on your class

```<code>$('#report-table').on('click', '.your-class', function() {
    //function code here
}
</code>```

Title: Add click event to datatable cell

Body:
I'm trying to add a click event to a dynamically created a datatabe. So this is my js :

   $('#report-table').dataTable({
        "proccessing": true,
        "serverSide": true,
        "ajax": {
            url: '@Url.Action("Get","Controller")',
            type: 'GET'

        },
       "columns": [
           { "data": "Name" },
                { "data": "Date" }, //lest say I want to add a click event here ???
                { "data": "sName", render: myRender }// I tried render but this is rendered without waiting on click function
        ]

    });

and this is my table for example :

A Test
2/13/2020 3:34:40 PM	 //lets say I want to fire a click event when I click the .aaaa class

Let's say I want to fire a click event when I click the .aaaa class.

Can anyone please give me an idea? Can I do this?
I'm stucked right here. Any idea would be apprecciated very very much :)

Body:
Instead of render use className to add a class to the cell

   "columns": [
        { "data": "Name" },
        {
            "data": "Date",
            "className": "your-class"
        },
        { "data": "sName" }
   ]

then put an on click event handler on your class

$('#report-table').on('click', '.your-class', function() {
    //function code here
}


问:
Ant design fixed side menu issue
I tried to added one page content to fixed left side menu and scroll content, i tried to use position:fixed style. but not working correctly,   anyone know how to do that correctly, stack blitz here

my code here

```<code>import React, { Component } from 'react';
import { render } from 'react-dom';
import 'antd/dist/antd.css';

import { Layout, Menu, Breadcrumb, Icon } from 'antd';

const { SubMenu } = Menu;
const { Header, Content, Footer, Sider } = Layout;
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  render() {
    return (
        <Layout>
    <Header className="header">
      <div className="logo" />
      <Menu
        theme="dark"
        mode="horizontal"
        defaultSelectedKeys={['2']}
        style={{ lineHeight: '64px' }}
      >
        <Menu.Item key="1">nav 1</Menu.Item>
        <Menu.Item key="2">nav 2</Menu.Item>
        <Menu.Item key="3">nav 3</Menu.Item>
      </Menu>
    </Header>
    <Content style={{ padding: '0 50px' }}>
      <Breadcrumb style={{ margin: '16px 0' }}>
        <Breadcrumb.Item>Home</Breadcrumb.Item>
        <Breadcrumb.Item>List</Breadcrumb.Item>
        <Breadcrumb.Item>App</Breadcrumb.Item>
      </Breadcrumb>
      <Layout style={{ padding: '24px 0', background: '#fff' }}>
        <Sider width={200} style={{ background: '#fff' }}>
          <Menu
            mode="inline"
            defaultSelectedKeys={['1']}
            defaultOpenKeys={['sub1']}
            style={{ height: '100%' }}
          >
            <SubMenu
              key="sub1"
              title={
                <span>
                  <Icon type="user" />
                  subnav 1
                </span>
              }
            >
              <Menu.Item key="1">option1</Menu.Item>
              <Menu.Item key="2">option2</Menu.Item>
              <Menu.Item key="3">option3</Menu.Item>
              <Menu.Item key="4">option4</Menu.Item>
            </SubMenu>
            <SubMenu
              key="sub2"
              title={
                <span>
                  <Icon type="laptop" />
                  subnav 2
                </span>
              }
            >
              <Menu.Item key="5">option5</Menu.Item>
              <Menu.Item key="6">option6</Menu.Item>
              <Menu.Item key="7">option7</Menu.Item>
              <Menu.Item key="8">option8</Menu.Item>
            </SubMenu>
            <SubMenu
              key="sub3"
              title={
                <span>
                  <Icon type="notification" />
                  subnav 3
                </span>
              }
            >
              <Menu.Item key="9">option9</Menu.Item>
              <Menu.Item key="10">option10</Menu.Item>
              <Menu.Item key="11">option11</Menu.Item>
              <Menu.Item key="12">option12</Menu.Item>
            </SubMenu>
          </Menu>
        </Sider>
        <Content style={{ padding: '0 24px', minHeight: 280,textAlign: "center" }}>    ...
                            <br/>
                            Really
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            ...
                            <br/>
                            ...
                            <br/>

                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                                ...
                            <br/>
                            Really
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            ...
                            <br/>
                            ...
                            <br/>

                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>

    ...
                            <br/>
                            Really
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            ...
                            <br/>
                            ...
                            <br/>

                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>

    ...
                            <br/>
                            Really
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            ...
                            <br/>
                            ...
                            <br/>

                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>

    ...
                            <br/>
                            Really
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            ...
                            <br/>
                            ...
                            <br/>

                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>

    ...
                            <br/>
                            Really
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            ...
                            <br/>
                            ...
                            <br/>

                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>

    ...
                            <br/>
                            Really
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            ...
                            <br/>
                            ...
                            <br/>

                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>

    ...
                            <br/>
                            Really
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            ...
                            <br/>
                            ...
                            <br/>

                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>
                            ...
                            <br/>

</Content>
      </Layout>
    </Content>
    <Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by Ant UED</Footer>
  </Layout>
    );
  }
}

render(<App />, document.getElementById('root'));
</code>```

答:
Something like this should work.

```<code><Sider
    width={200}
    style={{
        overflow: 'auto',
        height: '100vh',
        position: 'fixed',
        left: 0,
    }}
>
...
</Sider>
</code>```

Besides, maybe you want to take a look: https://react-sticky-box.codecks.io/

Title: Ant design fixed side menu issue

Body:
I tried to added one page content to fixed left side menu and scroll content, i tried to use position:fixed style. but not working correctly,   anyone know how to do that correctly, stack blitz here

my code here

import React, { Component } from 'react';
import { render } from 'react-dom';
import 'antd/dist/antd.css';

import { Layout, Menu, Breadcrumb, Icon } from 'antd';

const { SubMenu } = Menu;
const { Header, Content, Footer, Sider } = Layout;
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  render() {
    return (
        <Layout>

      <Menu
        theme="dark"
        mode="horizontal"
        defaultSelectedKeys={['2']}
        style={{ lineHeight: '64px' }}
      >
        <Menu.Item key="1">nav 1</Menu.Item>
        <Menu.Item key="2">nav 2</Menu.Item>
        <Menu.Item key="3">nav 3</Menu.Item>
      </Menu>

    <Content style={{ padding: '0 50px' }}>
      <Breadcrumb style={{ margin: '16px 0' }}>
        <Breadcrumb.Item>Home</Breadcrumb.Item>
        <Breadcrumb.Item>List</Breadcrumb.Item>
        <Breadcrumb.Item>App</Breadcrumb.Item>
      </Breadcrumb>
      <Layout style={{ padding: '24px 0', background: '#fff' }}>
        <Sider width={200} style={{ background: '#fff' }}>
          <Menu
            mode="inline"
            defaultSelectedKeys={['1']}
            defaultOpenKeys={['sub1']}
            style={{ height: '100%' }}
          >
            <SubMenu
              key="sub1"
              title={

                  <Icon type="user" />
                  subnav 1

              }
            >
              <Menu.Item key="1">option1</Menu.Item>
              <Menu.Item key="2">option2</Menu.Item>
              <Menu.Item key="3">option3</Menu.Item>
              <Menu.Item key="4">option4</Menu.Item>
            </SubMenu>
            <SubMenu
              key="sub2"
              title={

                  <Icon type="laptop" />
                  subnav 2

              }
            >
              <Menu.Item key="5">option5</Menu.Item>
              <Menu.Item key="6">option6</Menu.Item>
              <Menu.Item key="7">option7</Menu.Item>
              <Menu.Item key="8">option8</Menu.Item>
            </SubMenu>
            <SubMenu
              key="sub3"
              title={

                  <Icon type="notification" />
                  subnav 3

              }
            >
              <Menu.Item key="9">option9</Menu.Item>
              <Menu.Item key="10">option10</Menu.Item>
              <Menu.Item key="11">option11</Menu.Item>
              <Menu.Item key="12">option12</Menu.Item>
            </SubMenu>
          </Menu>
        </Sider>
        <Content style={{ padding: '0 24px', minHeight: 280,textAlign: "center" }}>    ...

                            Really

                            ...

                            ...

                            ...
                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                                ...

                            Really

                            ...

                            ...

                            ...
                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

    ...

                            Really

                            ...

                            ...

                            ...
                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

    ...

                            Really

                            ...

                            ...

                            ...
                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

    ...

                            Really

                            ...

                            ...

                            ...
                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

    ...

                            Really

                            ...

                            ...

                            ...
                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

    ...

                            Really

                            ...

                            ...

                            ...
                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

    ...

                            Really

                            ...

                            ...

                            ...
                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

                            ...

</Content>
      </Layout>
    </Content>
    Ant Design ©2018 Created by Ant UED
  </Layout>
    );
  }
}

render(<App />, document.getElementById('root'));

Body:
Something like this should work.

<Sider
    width={200}
    style={{
        overflow: 'auto',
        height: '100vh',
        position: 'fixed',
        left: 0,
    }}
>
...
</Sider>

Besides, maybe you want to take a look: https://react-sticky-box.codecks.io/


答:
Use match to return your desired vector, then cbind it to your matrix

```<code>cbind(t, z[, "symbol"][match(rownames(t), rownames(z))])

             [,1]         [,2]         [,3]         [,4]
GO.ID        "GO:0002009" "GO:0030334" "GO:0015674" NA
LEVEL        "8"          "6"          "7"          NA
Annotated    "342"        "343"        "350"        NA
Significant  "1"          "1"          "1"          NA
Expected     "0.07"       "0.07"       "0.07"       NA
resultFisher "0.679"      "0.065"      "0.065"      NA
ILMN_1652464 "0"          "0"          "1"          "PLAC8"
ILMN_1651838 "0"          "0"          "0"          "RND1"
ILMN_1711311 "1"          "1"          "0"          NA
ILMN_1653026 "0"          "0"          "0"          "GRA"
</code>```

PS.  Be warned that t is base R function that is used to transpose matrices.  By creating a variable called t, it can lead to confusion in your downstream code.

Title: Merge or combine by rownames

Body:
In the example below I have two datasets (Z and A). I want to merge or combine these sets by the ILMN numbers. If there is no match, fill in NA.

z <- matrix(c(0,0,1,1,0,0,1,1,0,0,0,0,1,0,1,1,0,1,1,1,1,0,0,0,"RND1","WDR", "PLAC8","TYBSA","GRA","TAF"), nrow=6,
    dimnames=list(c("ILMN_1651838","ILMN_1652371","ILMN_1652464","ILMN_1652952","ILMN_1653026","ILMN_1653103"),c("A","B","C","D","symbol")))

t<-matrix(c("GO:0002009", 8, 342, 1, 0.07, 0.679, 0, 0, 1, 0,
        "GO:0030334", 6, 343, 1, 0.07, 0.065, 0, 0, 1, 0,
        "GO:0015674", 7, 350, 1, 0.07, 0.065, 1, 0, 0, 0), nrow=10, dimnames= list(c("GO.ID","LEVEL","Annotated","Significant","Expected","resultFisher","ILMN_1652464","ILMN_1651838","ILMN_1711311","ILMN_1653026")))

The result will be like this:

             [,1]         [,2]         [,3]         [,4]
GO.ID        "GO:0002009" "GO:0030334" "GO:0015674"  NA
LEVEL        "8"          "6"          "7"           NA
Annotated    "342"        "343"        "350"         NA
Significant  "1"          "1"          "1"           NA
Expected     "0.07"       "0.07"       "0.07"        NA
resultFisher "0.679"      "0.065"      "0.065"       NA
ILMN_1652464 "0"          "0"          "1"           PLAC8
ILMN_1651838 "0"          "0"          "0"           RND1
ILMN_1711311 "1"          "1"          "0"           NA
ILMN_1653026 "0"          "0"          "0"           GRA

Body:
Use match to return your desired vector, then cbind it to your matrix

cbind(t, z[, "symbol"][match(rownames(t), rownames(z))])

             [,1]         [,2]         [,3]         [,4]
GO.ID        "GO:0002009" "GO:0030334" "GO:0015674" NA
LEVEL        "8"          "6"          "7"          NA
Annotated    "342"        "343"        "350"        NA
Significant  "1"          "1"          "1"          NA
Expected     "0.07"       "0.07"       "0.07"       NA
resultFisher "0.679"      "0.065"      "0.065"      NA
ILMN_1652464 "0"          "0"          "1"          "PLAC8"
ILMN_1651838 "0"          "0"          "0"          "RND1"
ILMN_1711311 "1"          "1"          "0"          NA
ILMN_1653026 "0"          "0"          "0"          "GRA"

PS.  Be warned that t is base R function that is used to transpose matrices.  By creating a variable called t, it can lead to confusion in your downstream code.


问:
Laravel paginate 'Allowed memory exhausted'
I got the problem when i was trying to paginate results of big query with several joins and groupBy inside. Part of my code here:

```<code>$lots = Lot::select('lots.id', 'lots.name', 'lots.slug', 'lots.description', 'lots.customer as lot_customer',
            'lots.created_at', 'lots.measure', 'lots.delivery_place', 'lots.amount as real_amount', 'lots.amount')
            ->leftJoin('tenders', 'tenders.id', '=', 'lots.tender_id')
            ->leftJoin('customers', 'lots.customer_id', '=', 'customers.id')
            ->groupBy('lots.id')
            ->paginate(25);
</code>```

I had 420650 - total records in database, but for pagination i wanted to show only 25 records per page. I got message:

Allowed memory size exhausted (tried to allocate 16777224 bytes)...

If you have way to resolve such problem, please share. Thank you!

答:
I found that problem was where laravel was getting total count of records for pagination results:

```<code>public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
{
 ...
 $total = $this->toBase()->getCountForPagination()
 ...
}

protected function runPaginationCountQuery($columns = ['*'])
{
 return $this->cloneWithout($without)->cloneWithoutBindings($this->unions ? ['order'] : ['select', 'order'])->setAggregate('count', $this->withoutSelectAliases($columns))->get()->all();
}
</code>```

In general last method runPaginationCountQuery in order to get count of records creates raw query to DB like:

select count(*) as aggregate from lots left join tenders on
  tenders.id = lots.tender_id left join customers on
  lots.customer_id.....

But with groupBy in query instead of one row with total count i got 420650 rows by one per row! It was enough big array which was created only to get count of rows, and in my case it was the reason of finished memory.

I understand that groupBy for big data isn't good decision and i made refactoring of my code to undo groupBy from my query. But in fact it seems to me that it wasn't normal behavoir of laravel that you probably expected.

Body:
I got the problem when i was trying to paginate results of big query with several joins and groupBy inside. Part of my code here:

$lots = Lot::select('lots.id', 'lots.name', 'lots.slug', 'lots.description', 'lots.customer as lot_customer',
            'lots.created_at', 'lots.measure', 'lots.delivery_place', 'lots.amount as real_amount', 'lots.amount')
            ->leftJoin('tenders', 'tenders.id', '=', 'lots.tender_id')
            ->leftJoin('customers', 'lots.customer_id', '=', 'customers.id')
            ->groupBy('lots.id')
            ->paginate(25);

I had 420650 - total records in database, but for pagination i wanted to show only 25 records per page. I got message:

Allowed memory size exhausted (tried to allocate 16777224 bytes)...

If you have way to resolve such problem, please share. Thank you!

Body:
I found that problem was where laravel was getting total count of records for pagination results:

public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
{
 ...
 $total = $this->toBase()->getCountForPagination()
 ...
}

protected function runPaginationCountQuery($columns = ['*'])
{
 return $this->cloneWithout($without)->cloneWithoutBindings($this->unions ? ['order'] : ['select', 'order'])->setAggregate('count', $this->withoutSelectAliases($columns))->get()->all();
}

In general last method runPaginationCountQuery in order to get count of records creates raw query to DB like:

select count(*) as aggregate from lots left join tenders on
  tenders.id = lots.tender_id left join customers on
  lots.customer_id.....

But with groupBy in query instead of one row with total count i got 420650 rows by one per row! It was enough big array which was created only to get count of rows, and in my case it was the reason of finished memory.

I understand that groupBy for big data isn't good decision and i made refactoring of my code to undo groupBy from my query. But in fact it seems to me that it wasn't normal behavoir of laravel that you probably expected.


问:
StringBuilder.append outofmemory
I'm using StringBuilder.append() to parse and process a file as following :

```<code>        StringBuilder csvString = new StringBuilder();

        bufferedReader.lines().filter(line -> !line.startsWith(HASH) && !line.isEmpty()).map(line -> line.trim())
                .forEachOrdered(line -> csvString.append(line).append(System.lineSeparator()));

        int startOfFileTagIndex = csvString.indexOf(START_OF_FILE_TAG);

        int startOfFieldsTagIndex = csvString.indexOf(START_OF_FIELDS_TAG, startOfFileTagIndex);
        int endOfFieldsTagIndex = csvString.indexOf(END_OF_FIELDS_TAG, startOfFieldsTagIndex);

        int startOfDataTagIndex = csvString.indexOf(START_OF_DATA_TAG, endOfFieldsTagIndex);
        int endOfDataTagIndex = csvString.indexOf(END_OF_DATA_TAG, startOfDataTagIndex);

        int endOfFileTagIndex = csvString.indexOf(END_OF_FILE_TAG, endOfDataTagIndex);

        int timeStartedIndex = csvString.indexOf("TIMESTARTED", endOfFieldsTagIndex);
        int dataRecordsIndex = csvString.indexOf("DATARECORDS", endOfDataTagIndex);
        int timeFinishedIndex = csvString.indexOf("TIMEFINISHED", endOfDataTagIndex);

        if (startOfFileTagIndex != 0 || startOfFieldsTagIndex == -1 || endOfFieldsTagIndex == -1
                || startOfDataTagIndex == -1 || endOfDataTagIndex == -1 || endOfFileTagIndex == -1) {

            log.error("not in correct format");

            throw new Exception("not in correct format.");
        }
</code>```

The problem is that when the file is quite large i get an outofmemoryexception.
Can you help me transform my code to avoid that exception with large files?

Edit:
As I can understand charging a huge file into a string Builder is not a good idea and won't work.
So the question is which structure in Java is the more appropriate to use to parse my huge file, delete some lines , find the index of some lines and seperate the file into parts (where to store those parts thaht can be huge) according to the found indexes then creating an output file in the end?

答:
The OOM seems to be due to the fact that you are storing all lines in the StringBuilder. When the file has too many lines, it will take up a huge amount of memory and may lead to OOM.

The strategy to avoid this depends upon what you are doing with appended strings.
As I can see in your code, you are only trying to verify the structure of the input file. In that case, you don't need to store all the lines in a StringBuilder instance. Instead,

Have multiple ints to hold each index you are interested in, (or have an array of ints)

Instead of adding the line to the StringBuilder, detect the presence of the "tag" or "index" you are looking for and save it in its designated int variable.

Finally, the check you are already doing may need to undergo a change to test not as -1 but relative to other indices. (This you are currently achieving using a start index in the indexOf() call.)

If there is a risk of a tag spanning across lines, then you may not be able to use streams, but will have to use a simple for loop in which to save some previous lines, append them and check. (Just one idea; you may have a better one.)

Title: StringBuilder.append outofmemory

Body:
I'm using StringBuilder.append() to parse and process a file as following :

        StringBuilder csvString = new StringBuilder();

        bufferedReader.lines().filter(line -> !line.startsWith(HASH) && !line.isEmpty()).map(line -> line.trim())
                .forEachOrdered(line -> csvString.append(line).append(System.lineSeparator()));

        int startOfFileTagIndex = csvString.indexOf(START_OF_FILE_TAG);

        int startOfFieldsTagIndex = csvString.indexOf(START_OF_FIELDS_TAG, startOfFileTagIndex);
        int endOfFieldsTagIndex = csvString.indexOf(END_OF_FIELDS_TAG, startOfFieldsTagIndex);

        int startOfDataTagIndex = csvString.indexOf(START_OF_DATA_TAG, endOfFieldsTagIndex);
        int endOfDataTagIndex = csvString.indexOf(END_OF_DATA_TAG, startOfDataTagIndex);

        int endOfFileTagIndex = csvString.indexOf(END_OF_FILE_TAG, endOfDataTagIndex);

        int timeStartedIndex = csvString.indexOf("TIMESTARTED", endOfFieldsTagIndex);
        int dataRecordsIndex = csvString.indexOf("DATARECORDS", endOfDataTagIndex);
        int timeFinishedIndex = csvString.indexOf("TIMEFINISHED", endOfDataTagIndex);

        if (startOfFileTagIndex != 0 || startOfFieldsTagIndex == -1 || endOfFieldsTagIndex == -1
                || startOfDataTagIndex == -1 || endOfDataTagIndex == -1 || endOfFileTagIndex == -1) {

            log.error("not in correct format");

            throw new Exception("not in correct format.");
        }

The problem is that when the file is quite large i get an outofmemoryexception.
Can you help me transform my code to avoid that exception with large files?

Edit:
As I can understand charging a huge file into a string Builder is not a good idea and won't work.
So the question is which structure in Java is the more appropriate to use to parse my huge file, delete some lines , find the index of some lines and seperate the file into parts (where to store those parts thaht can be huge) according to the found indexes then creating an output file in the end?


问:
Change frame and label colors on an item selected - syncfusion listview xamarin forms
I have been trying to change the color of the first item of my list[0] and also when I tapped on an Item - the color I need to change is the frame and the labels inside it.

I tried the following: BackgroundColor="{Binding IsActive, Converter={StaticResource colorConverter}}"

This works at the list level only, but nothing inside the data template. What else could I do?

what Im looking for , on selection change the border , background color and text

<sync:SfListView x:Name="list"
  SelectionMode="Single"
  SelectionGesture="Tap"
  ItemTapped="Day_ItemTapped">
    <sync:SfListView.ItemTemplate >
      <DataTemplate>
        <Frame x:Name="frame"
          BackgroundColor="{Binding IsActive, Converter={StaticResource colorConverter}}"
          BorderColor="#D9DADB">
            <StackLayout>

            </StackLayout>
          </Frame>
        </DataTemplate>
  </sync:SfListView.ItemTemplate>
</sync:SfListView>
```

-- @ Using template selector and frame , when you tapped the item again can comeback to its original colors ?

答:
You can achieve your requirement using Converter for BackgroundColor property of Frame and Label on ListView’s ItemTapped event. Please refer the following code snippet for more reference,

Xaml: Bind IsActive model property to BackgroundColor property of Frame and Label to change the color

```<code><syncfusion:SfListView x:Name="dayslist" Margin="10"
                               SelectionMode="Single"
                               SelectionGesture="Tap"
                               Orientation="Horizontal"
                               ItemTapped="Dayslist_ItemTapped"
                               ItemsSource="{Binding ContactsInfo}">
<syncfusion:SfListView.ItemTemplate>
                <DataTemplate>
                    <Frame x:Name="frame"
                           BackgroundColor="{Binding IsActive, Converter={StaticResource colorConverter}, ConverterParameter={x:Reference frame}}"
                           BorderColor="#D9DADB">
                        <StackLayout>
                            <Label x:Name="label" Text="{Binding ContactName}"
                                   BackgroundColor="{Binding IsActive, Converter={StaticResource colorConverter}, ConverterParameter={x:Reference label}}"/>
                        </StackLayout>
                    </Frame>
                </DataTemplate>
            </syncfusion:SfListView.ItemTemplate>
</syncfusion:SfListView>
</code>```

C#: Change the IsActive property value on ItemTapped event

```<code>    private void Dayslist_ItemTapped(object sender, Syncfusion.ListView.XForms.ItemTappedEventArgs e)
    {
        var currentItem = e.ItemData as ListViewContactsInfo;

        currentItem.IsActive = true;

       //To reset the background color for previous selected item.
        if (previousItem != null)
        {
            previousItem.IsActive = false;
        }

        previousItem = currentItem;
    }
</code>```

Converter: To return the color for Frame and Label based on selection

```<code>    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var item = parameter as Frame;
        ListViewContactsInfo model = null;

        if (item != null)
            model = (parameter as Frame).BindingContext as ListViewContactsInfo;

        //To change the background color for item[0].
        if (model != null && model.Index == 0)
            return Color.Red;

        else
        {
            //To change the background color for Frame and Label.
            if ((bool)value)
                return parameter as Frame != null ? Color.Blue : Color.Yellow;
        }
        return Color.Transparent;
    }
</code>```

Body:
I have been trying to change the color of the first item of my list[0] and also when I tapped on an Item - the color I need to change is the frame and the labels inside it.

I tried the following: BackgroundColor="{Binding IsActive, Converter={StaticResource colorConverter}}"

This works at the list level only, but nothing inside the data template. What else could I do?

what Im looking for , on selection change the border , background color and text

<sync:SfListView x:Name="list"
  SelectionMode="Single"
  SelectionGesture="Tap"
  ItemTapped="Day_ItemTapped">
    <sync:SfListView.ItemTemplate >
      <DataTemplate>
        <Frame x:Name="frame"
          BackgroundColor="{Binding IsActive, Converter={StaticResource colorConverter}}"
          BorderColor="#D9DADB">
            <StackLayout>

            </StackLayout>
          </Frame>
        </DataTemplate>
  </sync:SfListView.ItemTemplate>
</sync:SfListView>

-- @ Using template selector and frame , when you tapped the item again can comeback to its original colors ?

Body:
You can achieve your requirement using Converter for BackgroundColor property of Frame and Label on ListView’s ItemTapped event. Please refer the following code snippet for more reference,

Xaml: Bind IsActive model property to BackgroundColor property of Frame and Label to change the color

<syncfusion:SfListView x:Name="dayslist" Margin="10"
                               SelectionMode="Single"
                               SelectionGesture="Tap"
                               Orientation="Horizontal"
                               ItemTapped="Dayslist_ItemTapped"
                               ItemsSource="{Binding ContactsInfo}">
<syncfusion:SfListView.ItemTemplate>
                <DataTemplate>
                    <Frame x:Name="frame"
                           BackgroundColor="{Binding IsActive, Converter={StaticResource colorConverter}, ConverterParameter={x:Reference frame}}"
                           BorderColor="#D9DADB">
                        <StackLayout>
                            <Label x:Name="label" Text="{Binding ContactName}"
                                   BackgroundColor="{Binding IsActive, Converter={StaticResource colorConverter}, ConverterParameter={x:Reference label}}"/>
                        </StackLayout>
                    </Frame>
                </DataTemplate>
            </syncfusion:SfListView.ItemTemplate>
</syncfusion:SfListView>

C#: Change the IsActive property value on ItemTapped event

    private void Dayslist_ItemTapped(object sender, Syncfusion.ListView.XForms.ItemTappedEventArgs e)
    {
        var currentItem = e.ItemData as ListViewContactsInfo;

        currentItem.IsActive = true;

       //To reset the background color for previous selected item.
        if (previousItem != null)
        {
            previousItem.IsActive = false;
        }

        previousItem = currentItem;
    }

Converter: To return the color for Frame and Label based on selection

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var item = parameter as Frame;
        ListViewContactsInfo model = null;

        if (item != null)
            model = (parameter as Frame).BindingContext as ListViewContactsInfo;

        //To change the background color for item[0].
        if (model != null && model.Index == 0)
            return Color.Red;

        else
        {
            //To change the background color for Frame and Label.
            if ((bool)value)
                return parameter as Frame != null ? Color.Blue : Color.Yellow;
        }
        return Color.Transparent;
    }


问:
Firefox doens't update Silverlight Application
i have a problem with Firefox and Silverlight. I have a silverlight application (with version-number 1.0.0.0) on my website. Now I have modified the silverlight application(version-number is now 1.0.0.1) and replaced the old file on the server with my new application.

The Internet Explore loads the new application correctly. But unfortunally the Firefox 4 still loads the old Silverlight application.

Is there a trick to fix this issue or have i to rename the xap file on every update?

Than You

答:
May be Firefox cached that xap and load cahced one.

If you wont do load xap every time user opens the page, then replace

```<code> <param name="source" value="ClientBin/YourXapName.xap" />
</code>```

with this one

```<code>        <%
            string orgSourceValue = @"ClientBin/YourXapName.xap";
            string param;
            if (System.Diagnostics.Debugger.IsAttached)
                param = "<param name=\"source\" value=\"" + orgSourceValue + "\" />";
            else
            {
                string xappath = HttpContext.Current.Server.MapPath(@"") + @"\" + orgSourceValue;
                DateTime xapCreationDate = System.IO.File.GetLastWriteTime(xappath);
                param = "<param name=\"source\" value=\"" + orgSourceValue + "?ignore=" + xapCreationDate.ToString() + "\" />";
            }
            Response.Write(param);
         %>
</code>```

Body:
May be Firefox cached that xap and load cahced one.

If you wont do load xap every time user opens the page, then replace

 <param name="source" value="ClientBin/YourXapName.xap" />

with this one

        <%
            string orgSourceValue = @"ClientBin/YourXapName.xap";
            string param;
            if (System.Diagnostics.Debugger.IsAttached)
                param = "<param name=\"source\" value=\"" + orgSourceValue + "\" />";
            else
            {
                string xappath = HttpContext.Current.Server.MapPath(@"") + @"\" + orgSourceValue;
                DateTime xapCreationDate = System.IO.File.GetLastWriteTime(xappath);
                param = "<param name=\"source\" value=\"" + orgSourceValue + "?ignore=" + xapCreationDate.ToString() + "\" />";
            }
            Response.Write(param);
         %>