问:
Firefox 53 launched with gecko 0.16.1 but fail to connect to internet
I'm using the following configuration:

Win 10 64-bit

VS Enterprise 2017

C# testing project

Firefox 53.0.3 (64-bit)

Gecko driver geckodriver-v0.16.1-win64

Selenium.WebDriver v3.4.0

and this snippet:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace Test
{
    class Program
    {
        static void Main(string args)
        {
            IWebDriver driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://www.google.com");
        }
    }
}
</code>```

When I run this program the Gecko driver starts and displays this:

1496673391949 geckodriver INFO Listening on 127.0.0.1:62736
1496673393128 geckodriver::marionette INFO Starting browser \\?\C:\Program Files\Mozilla Firefox\firefox.exe with args ["-marionette"]

A Firefox page is opened but after a while a timeout error is displayed:

Could you please tell me what I did wrong?

答:
```<code>FirefoxProfile profile = new FirefoxProfile();
Proxy proxy = new Proxy();
proxy.IsAutoDetect = true;
profile.SetProxyPreferences(proxy);
IWebDriver driver = new FirefoxDriver(profile);
driver.Navigate().GoToUrl("http://www.google.com/");
</code>```

Body:
I'm using the following configuration:

Win 10 64-bit

VS Enterprise 2017

C# testing project

Firefox 53.0.3 (64-bit)

Gecko driver geckodriver-v0.16.1-win64

Selenium.WebDriver v3.4.0

and this snippet:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace Test
{
    class Program
    {
        static void Main(string args)
        {
            IWebDriver driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://www.google.com");
        }
    }
}

When I run this program the Gecko driver starts and displays this:

1496673391949 geckodriver INFO Listening on 127.0.0.1:62736
1496673393128 geckodriver::marionette INFO Starting browser \\?\C:\Program Files\Mozilla Firefox\firefox.exe with args ["-marionette"]

A Firefox page is opened but after a while a timeout error is displayed:

Could you please tell me what I did wrong?


来源: stackexchange

问:
Alter table structure to match copy table
I have 2 tables corporate and corporate_copy. Initially they were same in structure but people started added new columns into corporate and forgot do do so for corporate_copy.

Somewhere in the application there is less used functionality that copies data from corporate to corporate_copy and that kept failing without anyone noticing. Now I have to add 28 columns (ofcourse with same type and length and constraints etc....).

I know it can be done in one ALTER TABLE statement but I still feel it is lengthy task.

Do we have any luxury that will make copy table same as main table by keeping data and adding default values in newly added columns?

I am asking much but is there anything like that?

答:
You could use schema compare, found in SQL Server data tools (free) to generate a change script automatically.

But if this is just a copy, you could just run this:

```<code>DROP TABLE Corporate_Copy;

SELECT *
INTO Corporate_Copy
FROM Corporate;
</code>```

It's not clear whether you really need to preserve the data in the copy. If so, it's not really a copy is it?

ContentLicense: CC BY-SA 3.0

Body:
You could use schema compare, found in SQL Server data tools (free) to generate a change script automatically.

But if this is just a copy, you could just run this:

DROP TABLE Corporate_Copy;

SELECT *
INTO Corporate_Copy
FROM Corporate;

It's not clear whether you really need to preserve the data in the copy. If so, it's not really a copy is it?


问:
Redirect www.siteName.net to www.siteName.com via IIS
I submit number domain for my site. I need to redirect all domain such as  www.siteName.net , www.siteName.ir , www.siteName.co  to www.siteName.com via IIS.

Is this Possible?

If not Possible what is current solution?

答:
It is possible with this rule:

```<code><rule name="all domains www.siteName* to www.siteName.com" stopProcessing="true">
    <match url="(.*)" />
    <conditions logicalGrouping="MatchAll">
        <add input="{HTTP_HOST}" pattern="^www.siteName" ignoreCase="true" />
        <add input="{HTTP_HOST}" pattern="^www.siteName.com" negate="true" ignoreCase="true" />
    </conditions>
    <action type="Redirect" url="http://www.siteName.com/{R:1}" />
</rule>
</code>```

It will redirect everything for domains www.siteName* to www.siteName.com

Body:
It is possible with this rule:

<rule name="all domains www.siteName* to www.siteName.com" stopProcessing="true">
    <match url="(.*)" />
    <conditions logicalGrouping="MatchAll">
        <add input="{HTTP_HOST}" pattern="^www.siteName" ignoreCase="true" />
        <add input="{HTTP_HOST}" pattern="^www.siteName.com" negate="true" ignoreCase="true" />
    </conditions>
    <action type="Redirect" url="http://www.siteName.com/{R:1}" />
</rule>

It will redirect everything for domains www.siteName* to www.siteName.com


问:
How to listen for both keypress and keydown events in Elm?
I want to listen to both keypress and keydown events in Elm. But if I have the following, only the keydown events will be listened to:

```<code>textarea
    [ onWithOptions "keypress" (Options False True) <| Json.Decode.map KeyPress keyCode
    , onWithOptions "keydown" (Options False True) <| Json.Decode.map KeyDown keyCode
    ] []
</code>```

If I change the Options to not preventDefault, then both events will be listened to. But I need to preventDefault in order to not let tab keys from changing focus.

Any way to do this in Elm?

答:
Pre Elm 0.19, I recommend you to use elm-lang/keyboard. This package uses subscriptions and it's very easy to use. You can subscribe to keydown and keyup at the same time.

For your specific case:
The default action for a keydown event is to trigger a keypress event. If you prevent that default behaviour, you will not get the keypress events.

You can read more about keydown events here

Maybe you just need to use keyup and keydown.

I hope it helps you.

Body:
I want to listen to both keypress and keydown events in Elm. But if I have the following, only the keydown events will be listened to:

textarea
    [ onWithOptions "keypress" (Options False True) <| Json.Decode.map KeyPress keyCode
    , onWithOptions "keydown" (Options False True) <| Json.Decode.map KeyDown keyCode
    ] []

If I change the Options to not preventDefault, then both events will be listened to. But I need to preventDefault in order to not let tab keys from changing focus.

Any way to do this in Elm?

ContentLicense: CC BY-SA 4.0


问:
How can you export the Visual Studio Code extension list?
I need to send all my installed extensions to my colleagues. How can I export them?

The extension manager seems to do nothing... It won't install any extension.

答:
Generate a Windows command file (batch) for installing extensions:</p>
```<code>for /F "tokens=*" %i in ('code --list-extensions')
   do @echo call code --install-extension %i >> install.cmd
</code>```

Body:
Generate a Windows command file (batch) for installing extensions:

for /F "tokens=*" %i in ('code --list-extensions')
   do @echo call code --install-extension %i >> install.cmd


问:
kermit - how to redirect output into a file
i'm using kerimt to print the data coming from /dev/ttyS1.
i'm running kermit as root user( sudo ) because setting the stream source command:

set line /dev/ttyS1

doesn't work otherwise.
i'm trying to redirect the output using this command:

set session ./out.log

but i get this error:

?Write permission denied - ./out.log

if i run kermit with my regular user( without sudo ), i'm able to set the log file but i can't set the stream source ( the set line command ), i'm getting this error:

/var/lock: Permission denied

  Sorry, write access to UUCP lockfile directory denied.

how can i solve these permission issues?
is there a better way to redirect the output into a file?

答:
If you want all your session to be logged (including carriage-return and line-feed characters) try:

```<code>set session-log binary
log session <filename>
</code>```

if you are still having problems with the permission try to change the ownership of your output file with:

```<code>sudo chown <username>:<username> out.log
</code>```

For further information on log-session types with Kermit see this page: http://www.columbia.edu/kermit/logserial.html

Body:
If you want all your session to be logged (including carriage-return and line-feed characters) try:

set session-log binary
log session <filename>

if you are still having problems with the permission try to change the ownership of your output file with:

sudo chown <username>:<username> out.log

For further information on log-session types with Kermit see this page: http://www.columbia.edu/kermit/logserial.html


问:
Cons for defining logger non-static
Comments for this answer How do you reduce Java logging boilerplate code? strongly suggest not to use loggers as instance member variables. I can think of two negative side-effects:

1) superclass logs with the subclass's logger

2) object cannot be serialized (unless marked transient)

But if serializing is not necessary and logging with subclass name is not a problem, is there anything else why it should be avoided? I think it reduces boilerplate code and avoids copy-paste errors while copying logger variable definition from one class to another. Even Spring framework (which I believe has very good coding standards) uses this method.

答:
The major difference asides from the Superclass logging with subclass name, of course, is that you'll have one Logger object per member of your class.  Depending on how many classes are using logging, this can be a huge amount of Loggers, so memory bloat may be an issue.

Plus from an abstract point of view, the logger really does belong to the class and can be shared between all instances, rather than each instance needing its own private copy, so it makes sense to declare it as static.  Flipping your question around, what advantages does it have to making it non-static?  (Being able to pass getClass() into the getLogger() call instead of passing in the class constant is the only thing I can think of, and that's such a tiny thing).

OwnerDisplayName: martsraits

ContentLicense: CC BY-SA 2.5

Title: Cons for defining logger non-static

OwnerDisplayName: dtsazza


问:
EF4: LINQ 2 Entities query works in C# but not in VB
[EDITED: I left the original question below, with some more context and code to reproduce the problem. The short version below contains the essence of the question]

Short version: the query below throws a System.NotSupportedException: "Unable to cast the type 'System.Linq.IOrderedQueryable1' to type 'System.Linq.IQueryable1'. LINQ to Entities only supports casting Entity Data Model primitive types." The exception is only raised in the VB.Net version. When translated to C#, no exception is raised.

```<code>   Dim doesThisCrash = From outerOrder In orders
        Where outerOrder.ProductId =
        (From p In products Join o In orders On p.Id Equals o.ProductId
         Order By p.Id
         Select p.Id).FirstOrDefault()
        Select outerOrder
    doesThisCrash.ToList()
</code>```

So, to make it crash, it seems that we need a subquery where the original ObjectSet (orders) is joined with another ObjectSet (products), and ordered. When using just the orders or the products set, no crash occurs. When leaving out the Order By, also no crash.

I'm inclined to think this is a (VB.Net) compiler bug, unless there is something obvious that I'm overlooking here...

For now my question still stands:

why does a seemingly exact same query work in C# but not in VB?

can this query be made to work in VB.Net?

[/EDIT]

Optional, longer version (original question):

My domain looks very different, but I translated the problem to a simpler version, with the following entities (note: I actually defined these using the .edmx designer, so this is a simplified version):

```<code>    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime DateCreated { get; set; }
    }

    public class Order
    {
        public int Id { get; set; }
        public int CustomerId { get; set; }
        public int ProductId { get; set; }
        public DateTime OrderDate { get; set; }
    }

    public class Customer
    {
        public int Id { get; set; }
    }
</code>```

I'm trying to work out a linq-to-entities query that should strucurally look like this, in VB.Net:

```<code>    Dim db = New SampleEntities()
    Dim orders As IQueryable(Of Order) = db.Orders
    Dim products As IQueryable(Of Product) = db.Products
    Dim currentDate = DateTime.Now

    Dim qLinq = From outerOrder In orders
                Where outerOrder.OrderDate = currentDate AndAlso
                outerOrder.ProductId =
                    (From p In products Join o In orders On p.Id Equals o.ProductId
                     Where o.OrderDate = outerOrder.OrderDate AndAlso
                            outerOrder.CustomerId = o.CustomerId
                     Order By p.DateCreated
                     Select p.Id).FirstOrDefault()
                Select outerOrder
</code>```

This raises a System.NotSupportedException:

"Unable to cast the type 'System.Linq.IOrderedQueryable1' to type 'System.Linq.IQueryable1'. LINQ to Entities only supports casting Entity Data Model primitive types."

When leaving out the 'Order By' part, no exception is raised.

I don't really see a reason why this query would not be supported... So I decided to try the same thing in C#:

```<code>var qLinq = from oOut in orders
            where oOut.OrderDate == currentDate
                  && oOut.ProductId ==
                          (from p in products join o in orders on p.Id equals o.ProductId
                           where oOut.OrderDate == o.OrderDate
                           && oOut.CustomerId == o.CustomerId
                           orderby p.DateCreated
                           select p.Id).FirstOrDefault()
                    select oOut;
</code>```

To my surprise, this works! Then I translated the C# query to extension method syntax, and then back to VB, but got the same results (the C# version works, the VB.Net version raises the same exception).

So I guess my question is twofold:

why does a seemingly exact same query work in C# but not in VB?

can this query be made to work in VB.Net?

For reference, here are the queries in extension method syntax:

C# version:

```<code>        var q = orders.Where(outerOrder =>
            outerOrder.OrderDate == currentDate &&
            outerOrder.ProductId ==
            (products
                .Join(orders,
                    f => f.Id,
                    o => o.ProductId,
                    (f, o) => new { f, o })
                .Where(t => t.o.OrderDate == outerOrder.OrderDate
                           && outerOrder.CustomerId == t.o.CustomerId)
                .OrderByDescending(t => t.f.DateCreated)
                .Select(t => t.f.Id))
                .FirstOrDefault());
</code>```

VB.Net version:

```<code>    Dim q = orders.Where(Function(outerOrder) outerOrder.OrderDate = currentDate AndAlso
                             outerOrder.ProductId = (products.Join(orders,
                               Function(p) p.Id,
                               Function(o) o.ProductId,
                               Function(p, o) New With {.p = p, .o = o}).
                           Where(Function(x) x.o.OrderDate = outerOrder.OrderDate AndAlso
                                     outerOrder.CustomerId = x.o.CustomerId).
                           OrderByDescending(Function(x) x.p.DateCreated).
                           Select(Function(x) x.p.Id).
                           FirstOrDefault()))
</code>```

答:
I think the following works, the SQL is ugly though:</p>

```<code>Dim qLinq = From outerOrder In orders
                Where outerOrder.OrderDate = currentDate AndAlso
                outerOrder.ProductId =
                    (From x In (From p In products
                                 Join o In orders On p.Id Equals o.ProductId
                                 Where o.OrderDate = outerOrder.OrderDate AndAlso
                                        outerOrder.CustomerId = o.CustomerId
                                 Select p.Id)
                    Order By x).FirstOrDefault()
                Select outerOrder
</code>```

Body:
[EDITED: I left the original question below, with some more context and code to reproduce the problem. The short version below contains the essence of the question]

Short version: the query below throws a System.NotSupportedException: "Unable to cast the type 'System.Linq.IOrderedQueryable1' to type 'System.Linq.IQueryable1'. LINQ to Entities only supports casting Entity Data Model primitive types." The exception is only raised in the VB.Net version. When translated to C#, no exception is raised.

   Dim doesThisCrash = From outerOrder In orders
        Where outerOrder.ProductId =
        (From p In products Join o In orders On p.Id Equals o.ProductId
         Order By p.Id
         Select p.Id).FirstOrDefault()
        Select outerOrder
    doesThisCrash.ToList()

So, to make it crash, it seems that we need a subquery where the original ObjectSet (orders) is joined with another ObjectSet (products), and ordered. When using just the orders or the products set, no crash occurs. When leaving out the Order By, also no crash.

I'm inclined to think this is a (VB.Net) compiler bug, unless there is something obvious that I'm overlooking here...

For now my question still stands:

why does a seemingly exact same query work in C# but not in VB?

can this query be made to work in VB.Net?

[/EDIT]

Optional, longer version (original question):

My domain looks very different, but I translated the problem to a simpler version, with the following entities (note: I actually defined these using the .edmx designer, so this is a simplified version):

    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime DateCreated { get; set; }
    }

    public class Order
    {
        public int Id { get; set; }
        public int CustomerId { get; set; }
        public int ProductId { get; set; }
        public DateTime OrderDate { get; set; }
    }

    public class Customer
    {
        public int Id { get; set; }
    }

I'm trying to work out a linq-to-entities query that should strucurally look like this, in VB.Net:

    Dim db = New SampleEntities()
    Dim orders As IQueryable(Of Order) = db.Orders
    Dim products As IQueryable(Of Product) = db.Products
    Dim currentDate = DateTime.Now

    Dim qLinq = From outerOrder In orders
                Where outerOrder.OrderDate = currentDate AndAlso
                outerOrder.ProductId =
                    (From p In products Join o In orders On p.Id Equals o.ProductId
                     Where o.OrderDate = outerOrder.OrderDate AndAlso
                            outerOrder.CustomerId = o.CustomerId
                     Order By p.DateCreated
                     Select p.Id).FirstOrDefault()
                Select outerOrder

This raises a System.NotSupportedException:

"Unable to cast the type 'System.Linq.IOrderedQueryable1' to type 'System.Linq.IQueryable1'. LINQ to Entities only supports casting Entity Data Model primitive types."

When leaving out the 'Order By' part, no exception is raised.

I don't really see a reason why this query would not be supported... So I decided to try the same thing in C#:

var qLinq = from oOut in orders
            where oOut.OrderDate == currentDate
                  && oOut.ProductId ==
                          (from p in products join o in orders on p.Id equals o.ProductId
                           where oOut.OrderDate == o.OrderDate
                           && oOut.CustomerId == o.CustomerId
                           orderby p.DateCreated
                           select p.Id).FirstOrDefault()
                    select oOut;

To my surprise, this works! Then I translated the C# query to extension method syntax, and then back to VB, but got the same results (the C# version works, the VB.Net version raises the same exception).

So I guess my question is twofold:

why does a seemingly exact same query work in C# but not in VB?

can this query be made to work in VB.Net?

For reference, here are the queries in extension method syntax:

C# version:

        var q = orders.Where(outerOrder =>
            outerOrder.OrderDate == currentDate &&
            outerOrder.ProductId ==
            (products
                .Join(orders,
                    f => f.Id,
                    o => o.ProductId,
                    (f, o) => new { f, o })
                .Where(t => t.o.OrderDate == outerOrder.OrderDate
                           && outerOrder.CustomerId == t.o.CustomerId)
                .OrderByDescending(t => t.f.DateCreated)
                .Select(t => t.f.Id))
                .FirstOrDefault());

VB.Net version:

    Dim q = orders.Where(Function(outerOrder) outerOrder.OrderDate = currentDate AndAlso
                             outerOrder.ProductId = (products.Join(orders,
                               Function(p) p.Id,
                               Function(o) o.ProductId,
                               Function(p, o) New With {.p = p, .o = o}).
                           Where(Function(x) x.o.OrderDate = outerOrder.OrderDate AndAlso
                                     outerOrder.CustomerId = x.o.CustomerId).
                           OrderByDescending(Function(x) x.p.DateCreated).
                           Select(Function(x) x.p.Id).
                           FirstOrDefault()))

Body:
I think the following works, the SQL is ugly though:

Dim qLinq = From outerOrder In orders
                Where outerOrder.OrderDate = currentDate AndAlso
                outerOrder.ProductId =
                    (From x In (From p In products
                                 Join o In orders On p.Id Equals o.ProductId
                                 Where o.OrderDate = outerOrder.OrderDate AndAlso
                                        outerOrder.CustomerId = o.CustomerId
                                 Select p.Id)
                    Order By x).FirstOrDefault()
                Select outerOrder


问:
VBA - Deleting duplicated in one string which are separated by semicolon
I have got in one string like 800 adress emails. They are separated by semicolon. How should I do it to delete duplicates in that string?</p>

答:
Please update your question to show what you have already tried. It is very possible that your current code only needs a bit of tweaking.

Below is a more general way to accomplish what you're after, but like I said, there may be an easier way to fix your current code and you won't really learn by copying and pasting code.

```<code>Function RemoveDuplicates(rng as Range) As String
    Dim dict As Object
    Dim var As Variant, v As Variant

    Set dict = CreateObject("Scripting.Dictionary")

    var = Split(rng.Value,";")

    For each v in var
        If Not dict.Exists(v) Then
            dict.Add v, v
        End If
    Next v

    RemoveDuplicates = Join(dict.Keys, ";")
End Function
</code>```

Body:
Please update your question to show what you have already tried. It is very possible that your current code only needs a bit of tweaking.

Below is a more general way to accomplish what you're after, but like I said, there may be an easier way to fix your current code and you won't really learn by copying and pasting code.

Function RemoveDuplicates(rng as Range) As String
    Dim dict As Object
    Dim var As Variant, v As Variant

    Set dict = CreateObject("Scripting.Dictionary")

    var = Split(rng.Value,";")

    For each v in var
        If Not dict.Exists(v) Then
            dict.Add v, v
        End If
    Next v

    RemoveDuplicates = Join(dict.Keys, ";")
End Function


问:
APL / APLX - What does the Omega (⍵) do?
I'm learning APL through APLX. I see a lot of code using the omega character, but whenever I try to look up what it means, I can't find any information. None of the APLX documentation mentions it, yet it appears in some of the sample code in the very same files. Additionally, the Wikipedia article on APL Syntax and Symbols uses an ⍵ in a block of sample code, yet does not have an explanation of what ⍵ does. </p>

<p>Does the omega even have a meaning in APLX? If not, what is its meaning in other versions of APL? </p>

答: In "APL: the language and it's usage" by Polivka, Raymond, P.  1975  ISBN:0-13-038885-8  omega and alpha are shown as "undefined" on page 500. Therefore I imagine one can use them as variable names generally within APL.</p>

Body:
I'm learning APL through APLX. I see a lot of code using the omega character, but whenever I try to look up what it means, I can't find any information. None of the APLX documentation mentions it, yet it appears in some of the sample code in the very same files. Additionally, the Wikipedia article on APL Syntax and Symbols uses an ⍵ in a block of sample code, yet does not have an explanation of what ⍵ does.

Does the omega even have a meaning in APLX? If not, what is its meaning in other versions of APL?


问:
Less wrong TryGetValue then null check syntax
I'm a little new to C# still... I'm finding myself reusing a specific procedure over and over. Before I go writing a helper method for personal laziness, is there a shorter or less wrong way to write this sort of statement?

```<code>Dictionary<string, string> data = someBigDictionary;
string createdBy;
data.TryGetValue("CreatedBy", out createdBy);
//do that for 15 other values
...
MyEntity me = new MyEntity{
    CreatedBy = createdBy ?? "Unknown",
    //set 15 other values
    ...
}
</code>```

Essentially, set a property on an object by trying to get a value, then if it's null use a default value. I have a LOT of properties, it would be better if I could just

```<code>MyEntity me = new MyEntity{
    CreatedBy = TryToGetValueOrReturnNull(data, "CreatedBy") ?? "Unknown",
    ...
}
</code>```

Again, I am perfectly capable of writing my own helper function. I'm looking for an existing native functionality or shorthand before I do so.

答:
There are many similar questions (like this and this) which propose different solutions from extension methods to inheriting from dictionary and overriding indexer. However they are written before C# 7, and with C# 7 you can do this in one line:</p>

```<code>CreatedBy = data.TryGetValue("CreatedBy", out var value) ? value : "Unknown"
</code>```

Body:
I'm a little new to C# still... I'm finding myself reusing a specific procedure over and over. Before I go writing a helper method for personal laziness, is there a shorter or less wrong way to write this sort of statement?

Dictionary<string, string> data = someBigDictionary;
string createdBy;
data.TryGetValue("CreatedBy", out createdBy);
//do that for 15 other values
...
MyEntity me = new MyEntity{
    CreatedBy = createdBy ?? "Unknown",
    //set 15 other values
    ...
}

Essentially, set a property on an object by trying to get a value, then if it's null use a default value. I have a LOT of properties, it would be better if I could just

MyEntity me = new MyEntity{
    CreatedBy = TryToGetValueOrReturnNull(data, "CreatedBy") ?? "Unknown",
    ...
}

Again, I am perfectly capable of writing my own helper function. I'm looking for an existing native functionality or shorthand before I do so.

Body:
There are many similar questions (like this and this) which propose different solutions from extension methods to inheriting from dictionary and overriding indexer. However they are written before C# 7, and with C# 7 you can do this in one line:

CreatedBy = data.TryGetValue("CreatedBy", out var value) ? value : "Unknown"


问:
Is it possible to pass additional arguments or form instances to django formset?
My models.py:

```<code>class Company(models.Model):
   company_name = models.CharField(max_length=255)

class TimePeriod(models.Model):
   period = models.CharField(max_length=4)

class Unit(models.Model):
   unit_name = models.CharField(max_length=50)
   unit_type = models.CharField(max_length=50)

class DataElement(models.Model):
   data_element_name = models.CharField(max_length=50)

class Source(models.Model):
   source_name = models.CharField(max_length=50)

class CompanyData(models.Model):
   company = models.ForeignKey(Company)
   time_period = models.ForeignKey(TimePeriod)
   data_element = models.ForeignKey(DataElement)
   unit = models.ForeignKey(Unit)
   source = models.ForeignKey(Source)
   value = models.DecimalField(max_digits=15, decimal_places=2)
</code>```

I'd like to have form similar to:

--company--, --time period--

data element1: --value--, --unit--, --source--

data element2: --value--, --unit--, --source--

...

data elementN: --value--, --unit--, --source--

My forms.py now:

```<code>class CompanyTimeForm(ModelForm):
    class Meta:
        model = CompanyData
        fields = ('company', 'time_period')

class CompanyDataForm(ModelForm):
#    data_element = forms.IntegerField(widget=forms.HiddenInput())
#    def __init__(self, extra):
#        ... init data_element ...
    class Meta:
        model = CompanyData
        fields = ('value', 'unit', 'source')
</code>```

and usage:

```<code>top_form = CompanyChainTimeForm(request.POST or None)
CompanyDataFormSet = formset_factory(CompanyDataForm, extra=X)
formset = CompanyDataFormSet()
</code>```

Is it possible to initialize empty formset, then fetch DataElement.objects.all() and make something similar to
formset.add(CompanyDataForm(...DataElement.pk...))

Or what would be the best option for my case?

答:
It seems as it's impossible to use formset here.
I've done it via forms set with prefixes:</p>

```<code>...
data_forms = []
is_valid = True
for de in DataElement.objects.all():
    data_form = CompanyDataForm(request.POST or None, initial={'data_element': de.pk}, value_label=de, prefix="de-%s" % de.pk)
    if request.method == 'POST':
        if not data_form.is_valid():
            is_valid = False
    data_forms.append(data_form)
</code>```

Body:
My models.py:

class Company(models.Model):
   company_name = models.CharField(max_length=255)

class TimePeriod(models.Model):
   period = models.CharField(max_length=4)

class Unit(models.Model):
   unit_name = models.CharField(max_length=50)
   unit_type = models.CharField(max_length=50)

class DataElement(models.Model):
   data_element_name = models.CharField(max_length=50)

class Source(models.Model):
   source_name = models.CharField(max_length=50)

class CompanyData(models.Model):
   company = models.ForeignKey(Company)
   time_period = models.ForeignKey(TimePeriod)
   data_element = models.ForeignKey(DataElement)
   unit = models.ForeignKey(Unit)
   source = models.ForeignKey(Source)
   value = models.DecimalField(max_digits=15, decimal_places=2)

I'd like to have form similar to:

--company--, --time period--

data element1: --value--, --unit--, --source--

data element2: --value--, --unit--, --source--

...

data elementN: --value--, --unit--, --source--

My forms.py now:

class CompanyTimeForm(ModelForm):
    class Meta:
        model = CompanyData
        fields = ('company', 'time_period')

class CompanyDataForm(ModelForm):
#    data_element = forms.IntegerField(widget=forms.HiddenInput())
#    def __init__(self, extra):
#        ... init data_element ...
    class Meta:
        model = CompanyData
        fields = ('value', 'unit', 'source')

and usage:

top_form = CompanyChainTimeForm(request.POST or None)
CompanyDataFormSet = formset_factory(CompanyDataForm, extra=X)
formset = CompanyDataFormSet()

Is it possible to initialize empty formset, then fetch DataElement.objects.all() and make something similar to
formset.add(CompanyDataForm(...DataElement.pk...))

Or what would be the best option for my case?

Body:
It seems as it's impossible to use formset here.
I've done it via forms set with prefixes:

...
data_forms = []
is_valid = True
for de in DataElement.objects.all():
    data_form = CompanyDataForm(request.POST or None, initial={'data_element': de.pk}, value_label=de, prefix="de-%s" % de.pk)
    if request.method == 'POST':
        if not data_form.is_valid():
            is_valid = False
    data_forms.append(data_form)


问:
Comparing edittext input with a string (android)
I want to compare user input in my edittext with the string provided in the code. If they are matching, I want to increment the value of the integer score. I read many similar questions and adjusted my code but still, it seems not to work as the value of the integer does not change.
I put it in the method that is called while clicking a button, it also allows to go to another question(change layout)</p>

```<code>int score=0;
public void nextPage3(View v) {
    findViewById(R.id.q2).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            EditText input = (EditText) findViewById(R.id.editText1);
            String a = input.getText().toString();
            String p = "poet";
            if (p.equalsIgnoreCase(a))
                score++;
       }});

    setContentView(R.layout.question3);

}
</code>```

答:
Write Like This

```<code>public class MainActivity extends AppCompatActivity
{
    onCreate
     {
          setContentView(R.layout.question3);
     }
public void nextPage3(View v) {
    findViewById(R.id.q2).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            EditText input = (EditText) findViewById(R.id.editText1);
            String a = input.getText().toString();
            String p = "poet";
            if (p.equalsIgnoreCase(a))
                score++;
       }});
}
}
</code>```

Do Not Forget To add On Click Event In Xml File.
If You Do Not Declare Then Get Button Using FindViewById And btnName.setOnClickListenr() Method

Body:
I want to compare user input in my edittext with the string provided in the code. If they are matching, I want to increment the value of the integer score. I read many similar questions and adjusted my code but still, it seems not to work as the value of the integer does not change.
I put it in the method that is called while clicking a button, it also allows to go to another question(change layout)

int score=0;
public void nextPage3(View v) {
    findViewById(R.id.q2).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            EditText input = (EditText) findViewById(R.id.editText1);
            String a = input.getText().toString();
            String p = "poet";
            if (p.equalsIgnoreCase(a))
                score++;
       }});

    setContentView(R.layout.question3);

}

Body:
Write Like This

public class MainActivity extends AppCompatActivity
{
    onCreate
     {
          setContentView(R.layout.question3);
     }
public void nextPage3(View v) {
    findViewById(R.id.q2).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            EditText input = (EditText) findViewById(R.id.editText1);
            String a = input.getText().toString();
            String p = "poet";
            if (p.equalsIgnoreCase(a))
                score++;
       }});
}
}

Do Not Forget To add On Click Event In Xml File.
If You Do Not Declare Then Get Button Using FindViewById And btnName.setOnClickListenr() Method


问:
Android Application Lifecycle
I see a lot of answers concerning the Activity Lifecycle and that for most part is clear to me. What I'm looking for is the Application Lifecycle. I have the following case:

Application starts - Invalidate PIN

A PIN has to be entered if it is stale of invalid

Application is backgrounded (Android Home screen is visible) - Invalidate PIN

The applicatiion is foregrounded (App becomes visible again) - goto step 2

With the Activity Lifecycle it is hard if not impossible to achieve. Any suggestions?

答:
Inspired by the solution Doomsknight pointed me to I constructed this solution without the Timer as proposed in the proposed answer. Here's the code from my mainapplication.cs:</p>

```<code>    public void OnActivityPaused(Activity activity)
    {
        _lastActivity = DateTime.Now;
    }

    public void OnActivityResumed(Activity activity)
    {
        CrossCurrentActivity.Current.Activity = activity;

        DateTime now = DateTime.Now;
        TimeSpan span = now - _lastActivity;

        if (span.TotalMilliseconds > 2000)
        {
            Notifier.Classes.Settings.IsPinValid = false;
        }

        _lastActivity = now;
    }
</code>```

Title: Android Application Lifecycle

Body:
Inspired by the solution Doomsknight pointed me to I constructed this solution without the Timer as proposed in the proposed answer. Here's the code from my mainapplication.cs:

    public void OnActivityPaused(Activity activity)
    {
        _lastActivity = DateTime.Now;
    }

    public void OnActivityResumed(Activity activity)
    {
        CrossCurrentActivity.Current.Activity = activity;

        DateTime now = DateTime.Now;
        TimeSpan span = now - _lastActivity;

        if (span.TotalMilliseconds > 2000)
        {
            Notifier.Classes.Settings.IsPinValid = false;
        }

        _lastActivity = now;
    }


问:
Shiny dateInput not including minViewMode option
I am using Shiny to develop an application in R and I would like to use the datepicker option of minViewMode for the dateInput I am using.

I have checked in Shiny official documentation and it seems that this option has not been considered for dateInput widgets. How could I use this option in my R code? This is my ui.R code:

```<code>dateInput("InitialDateGlobalViewTrafficSplit"
          ,h4("Initial date")
          ,value=as.Date(InitialDate)
          ,min = ("2012-01-01")
          ,weekstart = 1
          # ,minViewMode = 1 # Ideal solution :)
          )
</code>```

Thanks

答:
Try defining this custom input and use it with your proposed call:</p>

```<code> mydateInput <- function(inputId, label, value = NULL, min = NULL, max = NULL,
                  format = "yyyy-mm-dd", startview = "month", weekstart = 0, language = "en", minviewmode="months",
                       width = NULL) {

   # If value is a date object, convert it to a string with yyyy-mm-dd format
   # Same for min and max
   if (inherits(value, "Date"))  value <- format(value, "%Y-%m-%d")
   if (inherits(min,   "Date"))  min   <- format(min,   "%Y-%m-%d")
   if (inherits(max,   "Date"))  max   <- format(max,   "%Y-%m-%d")

   htmltools::attachDependencies(
     tags$div(id = inputId,
              class = "shiny-date-input form-group shiny-input-container",
              style = if (!is.null(width)) paste0("width: ", validateCssUnit(width), ";"),

              controlLabel(inputId, label),
              tags$input(type = "text",
                         # datepicker class necessary for dropdown to display correctly
                         class = "form-control datepicker",
                         `data-date-language` = language,
                         `data-date-weekstart` = weekstart,
                         `data-date-format` = format,
                         `data-date-start-view` = startview,
                         `data-date-min-view-mode` = minviewmode,
                         `data-min-date` = min,
                         `data-max-date` = max,
                         `data-initial-date` = value
              )
     ),
     datePickerDependency
   )
 }

 `%AND%` <- function(x, y) {
   if (!is.null(x) && !is.na(x))
     if (!is.null(y) && !is.na(y))
       return(y)
   return(NULL)
 }

 controlLabel <- function(controlName, label) {
   label %AND% tags$label(class = "control-label", `for` = controlName, label)
 }

 datePickerDependency <- htmlDependency(
   "bootstrap-datepicker", "1.0.2", c(href = "shared/datepicker"),
   script = "js/bootstrap-datepicker.min.js",
   stylesheet = "css/datepicker.css")
</code>```

Body:
I am using Shiny to develop an application in R and I would like to use the datepicker option of minViewMode for the dateInput I am using.

I have checked in Shiny official documentation and it seems that this option has not been considered for dateInput widgets. How could I use this option in my R code? This is my ui.R code:

dateInput("InitialDateGlobalViewTrafficSplit"
          ,h4("Initial date")
          ,value=as.Date(InitialDate)
          ,min = ("2012-01-01")
          ,weekstart = 1
          # ,minViewMode = 1 # Ideal solution :)
          )

Thanks

Body:
Try defining this custom input and use it with your proposed call:

 mydateInput <- function(inputId, label, value = NULL, min = NULL, max = NULL,
                  format = "yyyy-mm-dd", startview = "month", weekstart = 0, language = "en", minviewmode="months",
                       width = NULL) {

   # If value is a date object, convert it to a string with yyyy-mm-dd format
   # Same for min and max
   if (inherits(value, "Date"))  value <- format(value, "%Y-%m-%d")
   if (inherits(min,   "Date"))  min   <- format(min,   "%Y-%m-%d")
   if (inherits(max,   "Date"))  max   <- format(max,   "%Y-%m-%d")

   htmltools::attachDependencies(
     tags$div(id = inputId,
              class = "shiny-date-input form-group shiny-input-container",
              style = if (!is.null(width)) paste0("width: ", validateCssUnit(width), ";"),

              controlLabel(inputId, label),
              tags$input(type = "text",
                         # datepicker class necessary for dropdown to display correctly
                         class = "form-control datepicker",
                         `data-date-language` = language,
                         `data-date-weekstart` = weekstart,
                         `data-date-format` = format,
                         `data-date-start-view` = startview,
                         `data-date-min-view-mode` = minviewmode,
                         `data-min-date` = min,
                         `data-max-date` = max,
                         `data-initial-date` = value
              )
     ),
     datePickerDependency
   )
 }

 `%AND%` <- function(x, y) {
   if (!is.null(x) && !is.na(x))
     if (!is.null(y) && !is.na(y))
       return(y)
   return(NULL)
 }

 controlLabel <- function(controlName, label) {
   label %AND% tags$label(class = "control-label", `for` = controlName, label)
 }

 datePickerDependency <- htmlDependency(
   "bootstrap-datepicker", "1.0.2", c(href = "shared/datepicker"),
   script = "js/bootstrap-datepicker.min.js",
   stylesheet = "css/datepicker.css")


问:
pyLucene Installation
I am on Ubuntu 10.04, Python 2.6.5 & having some trouble installing pyLucene.

Here's what I have done so far, installed these packages -

```<code>sudo apt-get install ant
sudo apt-get install sun-java6-jdk
sudo update-java-alternatives -s java-1.5.0-sun
sudo apt-get install gcc
sudo apt-get install g++
sudo apt-get install gcj
sudo apt-get install python-dev
</code>```

After that got the source code of pyLucene from http://www.apache.org/dyn/closer.cgi/lucene/pylucene/. I got version pylucene-3.0.1-1.

Untared it. Since JCC needs to be built first; went to JCC dir & then typed python setup.py install. got an error about some setuptools patch. it told me to do this -
sudo patch -d /usr/lib/python2.6/dist-packages -Nup0 < /home/code/python/lucene/pylucene-3.0.1-1/jcc/jcc/patches/patch.43.0.6c11

and I did. but I got this on the terminal -

```<code>patching file setuptools/extension.py
patching file setuptools/command/build_ext.py
Hunk #1 FAILED at 85.
Hunk #2 succeeded at 177 (offset 7 lines).
Hunk #3 succeeded at 259 (offset 7 lines).
1 out of 3 hunks FAILED -- saving rejects to file setuptools/command/build_ext.py.rej
</code>```

Now my build fails - i.e. when I do sudo python setup.py build I get -

```<code>...
error: command 'gcc' failed with exit status 1
</code>```

答:
What version do you need? There's a PPA with 2.9.2-1 here:

https://launchpad.net/~owenmorris/+archive/ppa

OwnerDisplayName: Inception

Title: pyLucene Installation

Body:
I am on Ubuntu 10.04, Python 2.6.5 & having some trouble installing pyLucene.

Here's what I have done so far, installed these packages -

sudo apt-get install ant
sudo apt-get install sun-java6-jdk
sudo update-java-alternatives -s java-1.5.0-sun
sudo apt-get install gcc
sudo apt-get install g++
sudo apt-get install gcj
sudo apt-get install python-dev

After that got the source code of pyLucene from http://www.apache.org/dyn/closer.cgi/lucene/pylucene/. I got version pylucene-3.0.1-1.

Untared it. Since JCC needs to be built first; went to JCC dir & then typed python setup.py install. got an error about some setuptools patch. it told me to do this -
sudo patch -d /usr/lib/python2.6/dist-packages -Nup0 < /home/code/python/lucene/pylucene-3.0.1-1/jcc/jcc/patches/patch.43.0.6c11

and I did. but I got this on the terminal -

patching file setuptools/extension.py
patching file setuptools/command/build_ext.py
Hunk #1 FAILED at 85.
Hunk #2 succeeded at 177 (offset 7 lines).
Hunk #3 succeeded at 259 (offset 7 lines).
1 out of 3 hunks FAILED -- saving rejects to file setuptools/command/build_ext.py.rej

Now my build fails - i.e. when I do sudo python setup.py build I get -

...
error: command 'gcc' failed with exit status 1


问:
'render' is not defined when running create react app
When I am using create react app when compliling I get the following errors ./src/Grid.js
 "Line 3:  Your render method should have return statement" and "Line 5:  'render' is not defined"
this is the contents of the the Grid.js file

```<code>import React, { Component } from 'react';

class Grid extends Component {
    render(){
        return <p>Hello, World</p>;
    }
}

export default Grid;
</code>```

I can't see that is wrong here? any help appreciated

```<code>import React, { Component } from 'react';
import Grid from './Grid.js';

class App extends Component
{
  render()
  {
    return(
      <div>
        <Grid />
      </div>
    );
  }
}

export default App;
</code>```

This is where I am using the component

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

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

Where ReactDOM render is used

答:
It should be:

```<code>import React, { Component } from 'react';

class Grid extends Component {
    render(){
        return(<p>Hello, World</p>);
    }
}

export default Grid;
</code>```

The above quote no longer applies.

I tried your exact code for Grid.js and App.js from the question and it works well on my machine. Whatever reason why your thing isn't working isn't in your Grid.js or App.js.

Body:
When I am using create react app when compliling I get the following errors ./src/Grid.js
 "Line 3:  Your render method should have return statement" and "Line 5:  'render' is not defined"
this is the contents of the the Grid.js file

import React, { Component } from 'react';

class Grid extends Component {
    render(){
        return
Hello, World
;
    }
}

export default Grid;

I can't see that is wrong here? any help appreciated

import React, { Component } from 'react';
import Grid from './Grid.js';

class App extends Component
{
  render()
  {
    return(

        <Grid />

    );
  }
}

export default App;

This is where I am using the component

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

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

Where ReactDOM render is used

Body:
It should be:

import React, { Component } from 'react';

class Grid extends Component {
    render(){
        return(<p>Hello, World</p>);
    }
}

export default Grid;

The above quote no longer applies.

I tried your exact code for Grid.js and App.js from the question and it works well on my machine. Whatever reason why your thing isn't working isn't in your Grid.js or App.js.


问:
Get DropdownList text in a Repeater Control ASP.NET
I'm trying to get the selected text on selected index change of the DropDownList. here is the Mock up.

```<code>   ```
                    <ItemTemplate>

                            <%# Eval("Teaenter code herem_Name")%>
                            <a href="http://localhost:4886/Payments/<%#Eval("Team_Payment")%>">View

                                <asp:DropDownList ID="drlApplicationStatus" runat="server" AutoPostBack="true" CssClass="form-control" CommandName="Update" CommandArgument='<%#Eval("Team_ID")%>'OnSelectedIndexchanged="Selected_IndexChanged" >
    <asp:ListItem CssClass="text-center" Text="--Select--" Value="0"></asp:ListItem>
                                    <asp:ListItem CssClass="text-center" Text="Active" Value="1"></asp:ListItem>
                                    <asp:ListItem CssClass="text-center" Text="Pending" Value="2 "></asp:ListItem>
                                </asp:DropDownList>

                    </ItemTemplate>
```
</code>```

Code Behind

```<code>protected void TeamList_ItemCommand(object source, RepeaterCommandEventArgs e)
{

    DropDownList drlApplicationStatus = (DropDownList)source;

    if (drlApplicationStatus.SelectedIndex == 1 && e.CommandArgument !=null)
    {
        Teams.UpdateTeamStatus(int.Parse(e.CommandArgument.ToString()), "Active");
    }
    else if(drlApplicationStatus.SelectedIndex == 2 && e.CommandArgument != null)
    {
        Teams.UpdateTeamStatus(int.Parse(e.CommandArgument.ToString()), "Pending");
    }

}
</code>```

答:
I don’t know why the DropDownList SelectedIndexChanged doesn’t trigger the ItemCommand event. But you can do this:

```<code>    protected void repeater_ItemCreated(object sender, RepeaterItemEventArgs e)
    {
        var drlApplicationStatus = (DropDownList)e.Item.FindControl("drlApplicationStatus");
        drlApplicationStatus.SelectedIndexChanged += drlApplicationStatus_SelectedIndexChanged;

    }

    private void drlApplicationStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        var drlApplicationStatus = (DropDownList)sender;
        Response.Write(drlApplicationStatus.SelectedValue);
        Response.Write(drlApplicationStatus.SelectedItem.Text);

    }
</code>```

Body:
I'm trying to get the selected text on selected index change of the DropDownList. here is the Mock up.

                    <ItemTemplate>

                            <%# Eval("Teaenter code herem_Name")%>
                            <a href="http://localhost:4886/Payments/<%#Eval("Team_Payment")%>">View

                                <asp:DropDownList ID="drlApplicationStatus" runat="server" AutoPostBack="true" CssClass="form-control" CommandName="Update" CommandArgument='<%#Eval("Team_ID")%>'OnSelectedIndexchanged="Selected_IndexChanged" >
    <asp:ListItem CssClass="text-center" Text="--Select--" Value="0"></asp:ListItem>
                                    <asp:ListItem CssClass="text-center" Text="Active" Value="1"></asp:ListItem>
                                    <asp:ListItem CssClass="text-center" Text="Pending" Value="2 "></asp:ListItem>
                                </asp:DropDownList>

                    </ItemTemplate>

Code Behind

protected void TeamList_ItemCommand(object source, RepeaterCommandEventArgs e)
{

    DropDownList drlApplicationStatus = (DropDownList)source;

    if (drlApplicationStatus.SelectedIndex == 1 && e.CommandArgument !=null)
    {
        Teams.UpdateTeamStatus(int.Parse(e.CommandArgument.ToString()), "Active");
    }
    else if(drlApplicationStatus.SelectedIndex == 2 && e.CommandArgument != null)
    {
        Teams.UpdateTeamStatus(int.Parse(e.CommandArgument.ToString()), "Pending");
    }

}

Body:
I don’t know why the DropDownList SelectedIndexChanged doesn’t trigger the ItemCommand event. But you can do this:

    protected void repeater_ItemCreated(object sender, RepeaterItemEventArgs e)
    {
        var drlApplicationStatus = (DropDownList)e.Item.FindControl("drlApplicationStatus");
        drlApplicationStatus.SelectedIndexChanged += drlApplicationStatus_SelectedIndexChanged;

    }

    private void drlApplicationStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        var drlApplicationStatus = (DropDownList)sender;
        Response.Write(drlApplicationStatus.SelectedValue);
        Response.Write(drlApplicationStatus.SelectedItem.Text);

    }


问:
Update Angular2 component only once after multiple onNgChange
I have a component with ChangeDetectionStrategy.OnPush and multiple @Input properties.

When more than one property changes at the same time i have multiple calls to ngOnChanges.

I need to recalculate the size after all the ngOnChanges have finished (for that tick/digest/change detection cycle).

So instead of having

```<code>ngOnChanges(a) -> recalculate()
ngOnChanges(b) -> recalculate()
ngOnChanges(c) -> recalculate()
</code>```

i want

```<code>ngOnChanges(a)
ngOnChanges(b)
ngOnChanges(c)
recalculate()
</code>```

A setTimeout would probably work but i want to know how to do it properly using ng2 tools.

答:
try this :</p>

```<code>ngOnChanges(changes: SimpleChange}) {
   if(changes['a'] && changes['b'] && changes['c']){
     recalculate();
   }
  }
</code>```

Body:
I have a component with ChangeDetectionStrategy.OnPush and multiple @Input properties.

When more than one property changes at the same time i have multiple calls to ngOnChanges.

I need to recalculate the size after all the ngOnChanges have finished (for that tick/digest/change detection cycle).

So instead of having

ngOnChanges(a) -> recalculate()
ngOnChanges(b) -> recalculate()
ngOnChanges(c) -> recalculate()

i want

ngOnChanges(a)
ngOnChanges(b)
ngOnChanges(c)
recalculate()

A setTimeout would probably work but i want to know how to do it properly using ng2 tools.

Body:
try this :

ngOnChanges(changes: SimpleChange}) {
   if(changes['a'] && changes['b'] && changes['c']){
     recalculate();
   }
  }


问:
R Function to write 3 calculated columns to a data.table
This may have already been answered, but couldn't quite find the answer I am looking for. I am trying to write the output of a function that calculates 3 variables to a data.table.

Currently I am copying the function three times (with three different names), each time returning a different variable. This is taking a lot more time as it runs thrice. I understand
there may be a better way to do it, using list or some unique data.table command.

I would greatly appreciate any input you can provide to simplify this. Below is the example of how I am calling it one variable at a time.

Example

```<code>  fn_1 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_1)
  }

  data[ ,column_1 := fn_1(a,b,c,d) ,by= .(e,f) ]

  fn_2 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_2)
  }

  data[ ,column_2 := fn_2(a,b,c,d) ,by= .(e,f) ]
</code>```

答:
You're in the second circle of hell. To solve the problem, pre-allocate what you want to add.

```<code>data <- data.table(c(1, 2, 3), c(4, 5, 6), c(7, 8, 9))
</code>```

Then, make a vectorized function to do the calculation, which returns the whole column to append.

```<code>calculation <- Vectorize(function(x) mean(c(x, 3)))
</code>```

Write fn in terms of this new function, and return the whole block of columns to be added, then cbind it with data to add all the columns at once. It's extremely slow to do all the calculations every time, and then only return one part.

```<code>fn <- function(b, c, d) {
  toBeAdded <- data.table(matrix(nrow = nrow(data), ncol = 3))
  toBeAdded[ , 1] <- calculation(b)
  toBeAdded[ , 2] <- calculation(b)
  toBeAdded[ , 3] <- calculation(b)
  toBeAdded
}

data <- cbind(data, fn(data[1,], data[2,], data[3,]))
</code>```

Body:
This may have already been answered, but couldn't quite find the answer I am looking for. I am trying to write the output of a function that calculates 3 variables to a data.table.

Currently I am copying the function three times (with three different names), each time returning a different variable. This is taking a lot more time as it runs thrice. I understand
there may be a better way to do it, using list or some unique data.table command.

I would greatly appreciate any input you can provide to simplify this. Below is the example of how I am calling it one variable at a time.

Example

  fn_1 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_1)
  }

  data[ ,column_1 := fn_1(a,b,c,d) ,by= .(e,f) ]

  fn_2 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_2)
  }

  data[ ,column_2 := fn_2(a,b,c,d) ,by= .(e,f) ]

Body:
You're in the second circle of hell. To solve the problem, pre-allocate what you want to add.

data <- data.table(c(1, 2, 3), c(4, 5, 6), c(7, 8, 9))

Then, make a vectorized function to do the calculation, which returns the whole column to append.

calculation <- Vectorize(function(x) mean(c(x, 3)))

Write fn in terms of this new function, and return the whole block of columns to be added, then cbind it with data to add all the columns at once. It's extremely slow to do all the calculations every time, and then only return one part.

fn <- function(b, c, d) {
  toBeAdded <- data.table(matrix(nrow = nrow(data), ncol = 3))
  toBeAdded[ , 1] <- calculation(b)
  toBeAdded[ , 2] <- calculation(b)
  toBeAdded[ , 3] <- calculation(b)
  toBeAdded
}

data <- cbind(data, fn(data[1,], data[2,], data[3,]))


问:
Search function not working in html table
I have huge data records in my table which I will be fetching from my database table and for that I will need search option to filter data.
the search function is not working.
When I enter any words in search box it does not show anything,neither it says record does not exist nor throws any error.
***Expected:***When user enters anything in search box,the record related with those words should be displayed.Please check the code and let me know how can I resolve it.</p>

```<code>       <?php
$db_host = 'localhost'; // Server Name
$db_user = 'root'; // Username
$db_pass = ''; // Password
$db_name = 'contacts'; // Database Name

$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
 }

$sql = 'SELECT *
    FROM contact';

$query = mysqli_query($conn, $sql);

if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<html>
<head>
<title>Displaying MySQL Data in HTML Table</title>
<style type="text/css">
    body {
        font-size: 15px;
        color: #343d44;
        font-family: "segoe-ui", "open-sans", tahoma, arial;
        padding: 0;
        margin: 0;
    }
    table {
        margin: auto;
        font-family: "Lucida Sans Unicode", "Lucida Grande", "Segoe Ui";
        font-size: 12px;
    }

    #myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 50%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myTable {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid #ddd;
  font-size: 18px;
}

#myTable th, #myTable td {
 text-align: left;
 padding: 12px;
}

#myTable tr {
 border-bottom: 1px solid #ddd;
}

 #myTable tr.header, #myTable tr:hover {
 background-color: #f1f1f1;
}

    /* Table */
    .data-table {
        border-collapse: collapse;
        font-size: 14px;
        min-width: 537px;
    }

    .data-table th,
    .data-table td {
        border: 1px solid #e1edff;
        padding: 7px 17px;
    }
    .data-table caption {
        margin: 7px;
    }

    /* Table Header */
    .data-table thead th {
        background-color: #508abb;
        color: #FFFFFF;
        border-color: #6ea1cc !important;
        text-transform: uppercase;
    }

    /* Table Body */
    .data-table tbody td {
        color: #353535;
    }
    .data-table tbody td:first-child,
    .data-table tbody td:nth-child(4),
    .data-table tbody td:last-child {
        text-align: right;
    }

    .data-table tbody tr:nth-child(odd) td {
        background-color: #f4fbff;
    }
    .data-table tbody tr:hover td {
        background-color: #ffffa2;
        border-color: #ffff0f;
    }

    /* Table Footer */
    .data-table tfoot th {
        background-color: #e5f5ff;
        text-align: right;
    }
    .data-table tfoot th:first-child {
        text-align: left;
    }
    .data-table tbody td:empty
    {
        background-color: #ffcccc;
    }
  </style>
</head>
<body>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
<table class="data-table" id="example">
    <caption class="title">US Data</caption>
    <thead>
        <tr>
            <th>ContactID</th>
            <th>ContactOwner</th>
            <th>LeadSource</th>
            <th>First_name</th>
            <th>Last_name</th>
            <th>AccountName</th>
            <th>Title</th>
            <th>EmailID</th>
            <th>Department</th>
            <th>Industry</th>
            <th>Phone</th>
            <th>Mobile</th>
            <th>Fax</th>
            <th>DOB</th>
            <th>Assistant</th>
            <th>AsstPhone</th>
            <th>ReportsTo</th>
            <th>LinkedIn</th>
            <th>CallStatus</th>
            <th>Street</th>
            <th>OtherStreet</th>
            <th>City</th>
            <th>State</th>
            <th>Zip</th>
            <th>Country</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
    <?php
    $no     = 1;
    $total  = 0;
    while ($row = mysqli_fetch_array($query))
    {

        echo '<tr>
                <td>'.$row['ContactID'].'</td>
                <td>'.$row['ContactOwner'].'</td>
                <td>'.$row['LeadSource'].'</td>
                <td>'.$row['First_name'].'</td>
                <td>'.$row['Last_name'].'</td>
                <td>'.$row['AccountName'].'</td>
                <td>'.$row['Title'].'</td>
                <td>'.$row['EmailID'].'</td>
                <td>'.$row['Department'].'</td>
                <td>'.$row['Industry'].'</td>
                <td>'.$row['Phone'].'</td>
                <td>'.$row['Mobile'].'</td>
                <td>'.$row['Fax'].'</td>
                <td>'.$row['DOB'].'</td>
                <td>'.$row['Assistant'].'</td>
                <td>'.$row['AsstPhone'].'</td>
                <td>'.$row['ReportsTo'].'</td>
                <td>'.$row['LinkedIn'].'</td>
                <td>'.$row['CallStatus'].'</td>
                <td>'.$row['Street'].'</td>
                <td>'.$row['OtherStreet'].'</td>
                <td>'.$row['City'].'</td>
                <td>'.$row['State'].'</td>
                <td>'.$row['Zip'].'</td>
                <td>'.$row['Country'].'</td>
                <td>'.$row['Description'].'</td>
            </tr>';

        $no++;
    }?>
    </tbody>
</table>
<script>
function myFunction() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("example");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
  td = tr[i].getElementsByTagName("td")[0];
   if (td) {
  if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
      tr[i].style.display = "";
   } else {
    tr[i].style.display = "none";
  }
 }
}
}
</script>
</body>
</html>
</code>```

答:
Your statement that it's "not working" is not strictly true. It does work, but only in limited circumstances. If you'd tested it thoroughly you could have provided this data in the question - that's what I meant by explaining the problem in detail and providing full information.

Anyway, there are a number of issues with the code.

1) It only ever searches the first column of any row (getElementsByTagName("td")[0] returns only the first column)

2) If any of your  elements were to contain further HTML for any reason, it would search the HTML tags as well. innerHTML should be replaced with innerText to avoid that.

3) Once you search through all columns, the simple if/else logic to show/hide the whole
 will fail because each time you loop through a column, it could cause the column to be hidden again, when the previous iteration had caused it to be shown. Instead, assume it will be hidden, and then only show it if there's at least one match to the search text within the columns.

4) I think once you get lots of rows you will get performance and usability problems because the search begins as soon as the user types a single character. If you type "s" and there are thousands of rows with thousands of cells, chances are 70% of them will contain "s" (in English, at least). It will slow down the system and provide no value to the user. I have written my example so that it doesn't start until the user enters 3 characters. You might want to provide some instructions to that effect in your finished product (or associated training materials).

Here is a working version, using some basic not-quite-random sample data. Note that the "example" ID is moved onto the
 element, to avoid hiding the table header by accident.

function myFunction() {
  var input, filter, table, tr, td, i;
  var input = document.getElementById("myInput");
  var filter = input.value.toUpperCase();

  var table = document.getElementById("example");
  var trList = table.getElementsByTagName("tr");

  for (i = 0; i < trList.length; i++)
  {
    //don't initiate search unless user types at least 3 characters. This will greatly improve performance and usability especially with large tables.
    if (filter.length >= 3)
    {
   var match = false;
      var tdList = trList[i].getElementsByTagName("td");

   //loop through every td
   for (j = 0; j < tdList.length; j++)
   {
     var td = tdList[j];

        if (td)
     {
          if (td.innerText.toUpperCase().indexOf(filter) > -1) {
      match = true;
          }
     }
      }

   if (match == true)
   {
        trList[i].style.display = "";
   }
   else
   {
  trList[i].style.display = "none";
   }
 }
    else
    {
      trList[i].style.display = "";
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<table class="data-table">
 <thead>
        <tr>
            <th>ContactID</th>
            <th>ContactOwner</th>
            <th>LeadSource</th>
  </tr>
 </thead>
 <tbody id="example">
  <tr>
   <td>Fish</td>
   <td>Fishing</td>
   <td>Test</td>
  </tr>
  <tr>
   <td>Hello</td>
   <td>World</td>
   <td>Estate</td>
  </tr>
  <tr>
   <td>Yellow</td>
   <td>Calling</td>
   <td>Bring</td>
  </tr>
 </tbody>
</table></code>```

Body:
I have huge data records in my table which I will be fetching from my database table and for that I will need search option to filter data.
the search function is not working.
When I enter any words in search box it does not show anything,neither it says record does not exist nor throws any error.
***Expected:***When user enters anything in search box,the record related with those words should be displayed.Please check the code and let me know how can I resolve it.

       <?php
$db_host = 'localhost'; // Server Name
$db_user = 'root'; // Username
$db_pass = ''; // Password
$db_name = 'contacts'; // Database Name

$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
 }

$sql = 'SELECT *
    FROM contact';

$query = mysqli_query($conn, $sql);

if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>

<title>Displaying MySQL Data in HTML Table</title>

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

US Data

            ContactID
            ContactOwner
            LeadSource
            First_name
            Last_name
            AccountName
            Title
            EmailID
            Department
            Industry
            Phone
            Mobile
            Fax
            DOB
            Assistant
            AsstPhone
            ReportsTo
            LinkedIn
            CallStatus
            Street
            OtherStreet
            City
            State
            Zip
            Country
            Description

    <?php
    $no     = 1;
    $total  = 0;
    while ($row = mysqli_fetch_array($query))
    {

        echo '

                '.$row['ContactID'].'
                '.$row['ContactOwner'].'
                '.$row['LeadSource'].'
                '.$row['First_name'].'
                '.$row['Last_name'].'
                '.$row['AccountName'].'
                '.$row['Title'].'
                '.$row['EmailID'].'
                '.$row['Department'].'
                '.$row['Industry'].'
                '.$row['Phone'].'
                '.$row['Mobile'].'
                '.$row['Fax'].'
                '.$row['DOB'].'
                '.$row['Assistant'].'
                '.$row['AsstPhone'].'
                '.$row['ReportsTo'].'
                '.$row['LinkedIn'].'
                '.$row['CallStatus'].'
                '.$row['Street'].'
                '.$row['OtherStreet'].'
                '.$row['City'].'
                '.$row['State'].'
                '.$row['Zip'].'
                '.$row['Country'].'
                '.$row['Description'].'

';

        $no++;
    }?>

Body:
Your statement that it's "not working" is not strictly true. It does work, but only in limited circumstances. If you'd tested it thoroughly you could have provided this data in the question - that's what I meant by explaining the problem in detail and providing full information.

Anyway, there are a number of issues with the code.

1) It only ever searches the first column of any row (getElementsByTagName("td")[0] returns only the first column)

2) If any of your <td> elements were to contain further HTML for any reason, it would search the HTML tags as well. innerHTML should be replaced with innerText to avoid that.

3) Once you search through all columns, the simple if/else logic to show/hide the whole <tr> will fail because each time you loop through a column, it could cause the column to be hidden again, when the previous iteration had caused it to be shown. Instead, assume it will be hidden, and then only show it if there's at least one match to the search text within the columns.

4) I think once you get lots of rows you will get performance and usability problems because the search begins as soon as the user types a single character. If you type "s" and there are thousands of rows with thousands of cells, chances are 70% of them will contain "s" (in English, at least). It will slow down the system and provide no value to the user. I have written my example so that it doesn't start until the user enters 3 characters. You might want to provide some instructions to that effect in your finished product (or associated training materials).

Here is a working version, using some basic not-quite-random sample data. Note that the "example" ID is moved onto the <tbody> element, to avoid hiding the table header by accident.

function myFunction() {
  var input, filter, table, tr, td, i;
  var input = document.getElementById("myInput");
  var filter = input.value.toUpperCase();

  var table = document.getElementById("example");
  var trList = table.getElementsByTagName("tr");

  for (i = 0; i < trList.length; i++)
  {
    //don't initiate search unless user types at least 3 characters. This will greatly improve performance and usability especially with large tables.
    if (filter.length >= 3)
    {
   var match = false;
      var tdList = trList[i].getElementsByTagName("td");

   //loop through every td
   for (j = 0; j < tdList.length; j++)
   {
     var td = tdList[j];

        if (td)
     {
          if (td.innerText.toUpperCase().indexOf(filter) > -1) {
      match = true;
          }
     }
      }

   if (match == true)
   {
        trList[i].style.display = "";
   }
   else
   {
  trList[i].style.display = "none";
   }
 }
    else
    {
      trList[i].style.display = "";
    }
  }
}

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<table class="data-table">
 <thead>
        <tr>
            <th>ContactID</th>
            <th>ContactOwner</th>
            <th>LeadSource</th>
  </tr>
 </thead>
 <tbody id="example">
  <tr>
   <td>Fish</td>
   <td>Fishing</td>
   <td>Test</td>
  </tr>
  <tr>
   <td>Hello</td>
   <td>World</td>
   <td>Estate</td>
  </tr>
  <tr>
   <td>Yellow</td>
   <td>Calling</td>
   <td>Bring</td>
  </tr>
 </tbody>
</table>


问:
Inserting Multiple Contacts in Android 2.3.5
I am trying to add multiple contacts from my application. I am reading in data from an xml file and then wrapping this up into a list of strongly typed objects. These objects and then looped through and I am calling an insert into the users contacts for each one.

However I am getting some very bizarre results whilst testing where I am getting either 1 or two working contacts and then a number of empty (Unknown) entries. The number of successful entries over (Unknowns) appears to be random but I am at a loss as to why I cannot perform something that should be fairly simple to do.

My click event which initiates the command to fetch the data and then add it to the contacts is below. I can confirm that the data is being read into the contacts list each time so it is not a problem with the data.

```<code>public void onClick(View v) {
    List<AddressContent> contacts = GetAddresses();
    int counter = 0;

    if (!contacts.isEmpty()) {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        for (int i = 0; i < contacts.size(); i++) {

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.RawContacts.CONTENT_URI)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE,
                            null)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_NAME,
                            null)
                    .withValue(ContactsContract.RawContacts.AGGREGATION_MODE,
                            ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED).build());

            // ------------------------------------------------------ Name

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, i)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                            contacts.get(i).getName()).build());

            // ------------------------------------------------------ Work
            // Number

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, i)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                    .withValue(
                            ContactsContract.CommonDataKinds.Phone.NUMBER,
                            contacts.get(i).getPhone())
                    .withValue(
                            ContactsContract.CommonDataKinds.Phone.TYPE,
                            ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
                    .build());

            // ------------------------------------------------------ Fax
            // Number

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, i)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                    .withValue(
                            ContactsContract.CommonDataKinds.Phone.NUMBER,
                            contacts.get(i).getFax())
                    .withValue(
                            ContactsContract.CommonDataKinds.Phone.TYPE,
                            ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK)
                    .build());

            // ------------------------------------------------------ Email

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, i)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Email.DATA,
                            contacts.get(i).getEmail())
                    .withValue(
                            ContactsContract.CommonDataKinds.Email.TYPE,
                            ContactsContract.CommonDataKinds.Email.TYPE_WORK)
                    .build());

            // ------------------------------------------------------
            // Organisation

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, i)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                    .withValue(
                            ContactsContract.CommonDataKinds.Organization.COMPANY,
                            contacts.get(i).getCompany())
                    .withValue(
                            ContactsContract.CommonDataKinds.Organization.TYPE,
                            ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
                    .build());

            // ------------------------------------------------------
            // Address

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, i)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                            contacts.get(i).getStreet())
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredPostal.CITY,
                            contacts.get(i).getCity())
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
                            contacts.get(i).getPostcode())
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
                            contacts.get(i).getCountry())
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                            ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK)
                    .build());
            counter++;
        }

        try {
            getContentResolver().applyBatch(ContactsContract.AUTHORITY,
                    ops);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "Error adding contact", Toast.LENGTH_SHORT).show();
            counter--;
        }

        if (counter > 0) {
            if (counter > 1) {
                Toast.makeText(this, "Contacts added", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Contact added", Toast.LENGTH_SHORT).show();
            }
        }
    }

    if (counter == 0) {
        Toast.makeText(this, "Unable to add contact", Toast.LENGTH_SHORT).show();
    }
}
</code>```

答:
Above answer is not correct you are able to insert multiple contacts at once as long as you set the proper backreference id like this:</p>

```<code>    int backReference;
    ArrayList<ContentProviderOperation> ops = new ArrayList<>();
    for (int i = 0; i < contacts.size(); i++)  {
        Contact contact = contacts.get(i);
        backReference = ops.size();
        ops.add(ContentProviderOperation.newInsert(addCallerIsSyncAdapterParameter(RawContacts.CONTENT_URI, true))
                .withYieldAllowed(true)
                .withValue(RawContacts.ACCOUNT_NAME, contact.fullName)
                .withValue(RawContacts.ACCOUNT_TYPE, ACCOUNT_TYPE)
                .withValue(RawContacts.SOURCE_ID, contact.contactId)
                .build());

        ops.add(ContentProviderOperation.newInsert(addCallerIsSyncAdapterParameter(ContactsContract.Settings.CONTENT_URI, true))
                .withValue(RawContacts.ACCOUNT_NAME, contact.fullName)
                .withValue(RawContacts.ACCOUNT_TYPE, ACCOUNT_TYPE)
                .withValue(ContactsContract.Settings.UNGROUPED_VISIBLE, 1)
                .build());

        ops.add(ContentProviderOperation.newInsert(addCallerIsSyncAdapterParameter(Data.CONTENT_URI, true))
                .withValueBackReference(Data.RAW_CONTACT_ID, backReference)
                .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
                .withValue(StructuredName.GIVEN_NAME, contact.firstName)
                .withValue(StructuredName.DISPLAY_NAME, contact.fullName)
                .withValue(StructuredName.FAMILY_NAME, ((contact.preposition != null && !contact.preposition.equals("")) ? contact.preposition + " " : "") + contact.lastName)
                .build());

        for (Number number : contact.numbers) {
            ops.add(ContentProviderOperation.newInsert(addCallerIsSyncAdapterParameter(Data.CONTENT_URI, true))
                    .withValueBackReference(Data.RAW_CONTACT_ID, backReference)
                    .withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM)
                    .withValue(ContactsContract.CommonDataKinds.Phone.LABEL, TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number.number)
                    .build());
        }

        for (Email email : contact.emails) {
            ops.add(ContentProviderOperation.newInsert(addCallerIsSyncAdapterParameter(Data.CONTENT_URI, true))
                    .withValueBackReference(Data.RAW_CONTACT_ID, backReference)
                    .withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
                    .withValue(Email.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM)
                    .withValue(Email.DATA, email.email)
                    .withValue(Email.LABEL, TYPE)
                    .build());
        }
        if (contacts.size() > i+1 && ops.size() + contacts.get(i+1).getTotalInsertions() > 499) {
            try {
                resolver.applyBatch(ContactsContract.AUTHORITY, ops);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            ops.clear();
        } else if (contacts.size() == i+1) {
            try {
                resolver.applyBatch(ContactsContract.AUTHORITY, ops);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
</code>```

Body:
I am trying to add multiple contacts from my application. I am reading in data from an xml file and then wrapping this up into a list of strongly typed objects. These objects and then looped through and I am calling an insert into the users contacts for each one.

However I am getting some very bizarre results whilst testing where I am getting either 1 or two working contacts and then a number of empty (Unknown) entries. The number of successful entries over (Unknowns) appears to be random but I am at a loss as to why I cannot perform something that should be fairly simple to do.

My click event which initiates the command to fetch the data and then add it to the contacts is below. I can confirm that the data is being read into the contacts list each time so it is not a problem with the data.

public void onClick(View v) {
    List<AddressContent> contacts = GetAddresses();
    int counter = 0;

    if (!contacts.isEmpty()) {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        for (int i = 0; i < contacts.size(); i++) {

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.RawContacts.CONTENT_URI)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE,
                            null)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_NAME,
                            null)
                    .withValue(ContactsContract.RawContacts.AGGREGATION_MODE,
                            ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED).build());

            // ------------------------------------------------------ Name

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, i)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                            contacts.get(i).getName()).build());

            // ------------------------------------------------------ Work
            // Number

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, i)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                    .withValue(
                            ContactsContract.CommonDataKinds.Phone.NUMBER,
                            contacts.get(i).getPhone())
                    .withValue(
                            ContactsContract.CommonDataKinds.Phone.TYPE,
                            ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
                    .build());

            // ------------------------------------------------------ Fax
            // Number

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, i)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                    .withValue(
                            ContactsContract.CommonDataKinds.Phone.NUMBER,
                            contacts.get(i).getFax())
                    .withValue(
                            ContactsContract.CommonDataKinds.Phone.TYPE,
                            ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK)
                    .build());

            // ------------------------------------------------------ Email

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, i)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Email.DATA,
                            contacts.get(i).getEmail())
                    .withValue(
                            ContactsContract.CommonDataKinds.Email.TYPE,
                            ContactsContract.CommonDataKinds.Email.TYPE_WORK)
                    .build());

            // ------------------------------------------------------
            // Organisation

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, i)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                    .withValue(
                            ContactsContract.CommonDataKinds.Organization.COMPANY,
                            contacts.get(i).getCompany())
                    .withValue(
                            ContactsContract.CommonDataKinds.Organization.TYPE,
                            ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
                    .build());

            // ------------------------------------------------------
            // Address

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, i)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                            contacts.get(i).getStreet())
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredPostal.CITY,
                            contacts.get(i).getCity())
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
                            contacts.get(i).getPostcode())
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
                            contacts.get(i).getCountry())
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                            ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK)
                    .build());
            counter++;
        }

        try {
            getContentResolver().applyBatch(ContactsContract.AUTHORITY,
                    ops);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "Error adding contact", Toast.LENGTH_SHORT).show();
            counter--;
        }

        if (counter > 0) {
            if (counter > 1) {
                Toast.makeText(this, "Contacts added", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Contact added", Toast.LENGTH_SHORT).show();
            }
        }
    }

    if (counter == 0) {
        Toast.makeText(this, "Unable to add contact", Toast.LENGTH_SHORT).show();
    }
}

Body:
Above answer is not correct you are able to insert multiple contacts at once as long as you set the proper backreference id like this:

    int backReference;
    ArrayList<ContentProviderOperation> ops = new ArrayList<>();
    for (int i = 0; i < contacts.size(); i++)  {
        Contact contact = contacts.get(i);
        backReference = ops.size();
        ops.add(ContentProviderOperation.newInsert(addCallerIsSyncAdapterParameter(RawContacts.CONTENT_URI, true))
                .withYieldAllowed(true)
                .withValue(RawContacts.ACCOUNT_NAME, contact.fullName)
                .withValue(RawContacts.ACCOUNT_TYPE, ACCOUNT_TYPE)
                .withValue(RawContacts.SOURCE_ID, contact.contactId)
                .build());

        ops.add(ContentProviderOperation.newInsert(addCallerIsSyncAdapterParameter(ContactsContract.Settings.CONTENT_URI, true))
                .withValue(RawContacts.ACCOUNT_NAME, contact.fullName)
                .withValue(RawContacts.ACCOUNT_TYPE, ACCOUNT_TYPE)
                .withValue(ContactsContract.Settings.UNGROUPED_VISIBLE, 1)
                .build());

        ops.add(ContentProviderOperation.newInsert(addCallerIsSyncAdapterParameter(Data.CONTENT_URI, true))
                .withValueBackReference(Data.RAW_CONTACT_ID, backReference)
                .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
                .withValue(StructuredName.GIVEN_NAME, contact.firstName)
                .withValue(StructuredName.DISPLAY_NAME, contact.fullName)
                .withValue(StructuredName.FAMILY_NAME, ((contact.preposition != null && !contact.preposition.equals("")) ? contact.preposition + " " : "") + contact.lastName)
                .build());

        for (Number number : contact.numbers) {
            ops.add(ContentProviderOperation.newInsert(addCallerIsSyncAdapterParameter(Data.CONTENT_URI, true))
                    .withValueBackReference(Data.RAW_CONTACT_ID, backReference)
                    .withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM)
                    .withValue(ContactsContract.CommonDataKinds.Phone.LABEL, TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number.number)
                    .build());
        }

        for (Email email : contact.emails) {
            ops.add(ContentProviderOperation.newInsert(addCallerIsSyncAdapterParameter(Data.CONTENT_URI, true))
                    .withValueBackReference(Data.RAW_CONTACT_ID, backReference)
                    .withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
                    .withValue(Email.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM)
                    .withValue(Email.DATA, email.email)
                    .withValue(Email.LABEL, TYPE)
                    .build());
        }
        if (contacts.size() > i+1 && ops.size() + contacts.get(i+1).getTotalInsertions() > 499) {
            try {
                resolver.applyBatch(ContactsContract.AUTHORITY, ops);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            ops.clear();
        } else if (contacts.size() == i+1) {
            try {
                resolver.applyBatch(ContactsContract.AUTHORITY, ops);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }