问:
Can I use and return EF4 code-first POCO entities as their interface?
Given the code later in the question, I am getting the following error from the EF4 code-first API:

The given property 'Roles' is not a
  supported navigation property.  The
  property element type 'IRole' is
  not a supported entity type.
  Interface types are not supported.

Basically, I have a Repository similar to the following:

```<code>public class Repository : IRepository {
    private IEntityProvider _provider;
    public Repository(IEntityProvider provider) {
        _provider = provider;
    }
    public IUser GetUser(int id) {
        return _provider.FindUser(id);
    }
}
</code>```

Notice that the IRepository.GetUser returns an IUser.

Let's say my IEntityProvider implementation looks like this.

```<code>public class EntityProvider : IEntityProvider {
    public IUser FindUser(int id) {
        /* Using Entity Framework */
        IUser entity;
        using (var ctx = new MyDbContext()) {
            entity = (from n in ctx.Users
                  where n.Id == id
                  select (IUser)n).FirstOrDefault();
        }
        return entity;
    }
}
</code>```

The key here is that the IUser interface has a List<IRole> property called Roles.  Because of this, it seems, the Entity Framework code-first cannot figure out what class to use to fulfill the IRole interface that property needs.

Below are the interfaces and POCO entities which would be used throughout the system and hopefully also used with EF4.

```<code>public interface IUser {
    int Id { get; set; }
    string Name { get; set; }
    List<IRole> Roles { get; set; }
}

public interface IRole {
    int Id { get; set; }
    string Name { get; set; }
}

public class User : IUser {
    public int Id { get; set; }
    public string Name { get; set; }
    public List<IRole> Roles { get; set; }
}

public class Role : IRole {
    public int Id { get; set; }
    public string Name { get; set; }
}
</code>```

Am I going about this the wrong way? Is there a way to do this within the EF4 code-first API?

I can only think of the following:

Some sort of shadow property (List<Role> DbRoles) that is used by EF4 code-first. Then use Data Annotations to make sure the actual List<IRole> is ignored by EF4.

Create duplicate classes for all entities which EF4 code-first will use and then Map those to the official ones that implement the interface.

答: The use of Interfaces is not supported in EF 4 Code First (as of CTP5) and more than likely wont be supported in the RTM either. I would say make an abstract class in your DbContext to hold your objects.</p>

Body:
Given the code later in the question, I am getting the following error from the EF4 code-first API:

The given property 'Roles' is not a
  supported navigation property.  The
  property element type 'IRole' is
  not a supported entity type.
  Interface types are not supported.

Basically, I have a Repository similar to the following:

public class Repository : IRepository {
    private IEntityProvider _provider;
    public Repository(IEntityProvider provider) {
        _provider = provider;
    }
    public IUser GetUser(int id) {
        return _provider.FindUser(id);
    }
}

Notice that the IRepository.GetUser returns an IUser.

Let's say my IEntityProvider implementation looks like this.

public class EntityProvider : IEntityProvider {
    public IUser FindUser(int id) {
        /* Using Entity Framework */
        IUser entity;
        using (var ctx = new MyDbContext()) {
            entity = (from n in ctx.Users
                  where n.Id == id
                  select (IUser)n).FirstOrDefault();
        }
        return entity;
    }
}

The key here is that the IUser interface has a List<IRole> property called Roles.  Because of this, it seems, the Entity Framework code-first cannot figure out what class to use to fulfill the IRole interface that property needs.

Below are the interfaces and POCO entities which would be used throughout the system and hopefully also used with EF4.

public interface IUser {
    int Id { get; set; }
    string Name { get; set; }
    List<IRole> Roles { get; set; }
}

public interface IRole {
    int Id { get; set; }
    string Name { get; set; }
}

public class User : IUser {
    public int Id { get; set; }
    public string Name { get; set; }
    public List<IRole> Roles { get; set; }
}

public class Role : IRole {
    public int Id { get; set; }
    public string Name { get; set; }
}

Am I going about this the wrong way? Is there a way to do this within the EF4 code-first API?

I can only think of the following:

Some sort of shadow property (List<Role> DbRoles) that is used by EF4 code-first. Then use Data Annotations to make sure the actual List<IRole> is ignored by EF4.

Create duplicate classes for all entities which EF4 code-first will use and then Map those to the official ones that implement the interface.


来源: stackexchange

问:
Excel VBA - Determining Column or Row Target of Array UDF
I have a simple excel UDF for converting an array of mass values to mol fractions.  Most times, the output will be a column array (n rows by 1 column).

How, from within the VBA environment, do I determine the dimensions of the target cells on the worksheet to ensure that it should be returned as n rows by 1 column versus n columns by 1 row?

```<code>Function molPct(chemsAndMassPctsRng As Range)

Dim chemsRng As Range
Dim massPctsRng As Range
Dim molarMasses()
Dim molPcts()

Set chemsRng = chemsAndMassPctsRng.Columns(1)
Set massPctsRng = chemsAndMassPctsRng.Columns(2)

chems = oneDimArrayZeroBasedFromRange(chemsRng)
massPcts = oneDimArrayZeroBasedFromRange(massPctsRng)

'oneDimArrayZeroBasedFromRange is a UDF to return a zero-based array from a range.

ReDim molarMasses(UBound(chems))
ReDim molPcts(UBound(chems))

totMolarMass = 0

For chemNo = LBound(chems) To UBound(chems)

    molarMasses(chemNo) = massPcts(chemNo) / mw(chems(chemNo))
    totMolarMass = totMolarMass + molarMasses(chemNo)

Next chemNo

For chemNo = LBound(chems) To UBound(chems)

    molPcts(chemNo) = Round(molarMasses(chemNo) / totMolarMass, 2)

Next chemNo

molPct = Application.WorksheetFunction.Transpose(molPcts)

End Function
</code>```

I understand that, if nothing else, I could have an input parameter to flag if return should be as a row array.  I'm hoping to not go that route.

答:
You should return two dimensional arrays: n × 1 for row and 1 × n for column vectors.

So you need either

```<code>Redim molPcts(1, Ubound(chems) + 1)
</code>```

or

```<code>Redim molPcts(Ubound(chems) + 1, 1)
</code>```

To refer to them, you need to use both indices:

```<code>molPcts(1, chemNo + 1)
</code>```

or

```<code>molPcts(chemNo + 1, 1)
</code>```

If you prefer 0-based arrays, the redim should be like this:

```<code>Redim molPcts(0 To 0, 0 To Ubound(chems))
Redim molPcts(0 To Ubound(chems), 0 To 0)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a simple excel UDF for converting an array of mass values to mol fractions.  Most times, the output will be a column array (n rows by 1 column).

How, from within the VBA environment, do I determine the dimensions of the target cells on the worksheet to ensure that it should be returned as n rows by 1 column versus n columns by 1 row?

Function molPct(chemsAndMassPctsRng As Range)

Dim chemsRng As Range
Dim massPctsRng As Range
Dim molarMasses()
Dim molPcts()

Set chemsRng = chemsAndMassPctsRng.Columns(1)
Set massPctsRng = chemsAndMassPctsRng.Columns(2)

chems = oneDimArrayZeroBasedFromRange(chemsRng)
massPcts = oneDimArrayZeroBasedFromRange(massPctsRng)

'oneDimArrayZeroBasedFromRange is a UDF to return a zero-based array from a range.

ReDim molarMasses(UBound(chems))
ReDim molPcts(UBound(chems))

totMolarMass = 0

For chemNo = LBound(chems) To UBound(chems)

    molarMasses(chemNo) = massPcts(chemNo) / mw(chems(chemNo))
    totMolarMass = totMolarMass + molarMasses(chemNo)

Next chemNo

For chemNo = LBound(chems) To UBound(chems)

    molPcts(chemNo) = Round(molarMasses(chemNo) / totMolarMass, 2)

Next chemNo

molPct = Application.WorksheetFunction.Transpose(molPcts)

End Function

I understand that, if nothing else, I could have an input parameter to flag if return should be as a row array.  I'm hoping to not go that route.

Body:
You should return two dimensional arrays: n × 1 for row and 1 × n for column vectors.

So you need either

Redim molPcts(1, Ubound(chems) + 1)

or

Redim molPcts(Ubound(chems) + 1, 1)

To refer to them, you need to use both indices:

molPcts(1, chemNo + 1)

or

molPcts(chemNo + 1, 1)

If you prefer 0-based arrays, the redim should be like this:

Redim molPcts(0 To 0, 0 To Ubound(chems))
Redim molPcts(0 To Ubound(chems), 0 To 0)


问:
How store items of a dictionary to another dictionary with a key in swift?
I got a dictionary say dict1 with some keys and values and i want to store all the values of dict1 to another dictionary say dict2 with a key and i tried  parse them to JSON using SwiftyJson.
What i tried has been given below,

```<code>var dict1 = [String: String]()
var dict2 = [String: String]()

// Values of dict1
dict1["details"] = "XXXXX"

//trying to save values of dict1 to dict2
dict2["moreDetails"] = dict1 as? String
let jsonValue = JSON(dict2)
print(jsonValue)
</code>```

What i obtain is an empty jsonString like this {    }

What i actually want to get is

```<code>{
"moreDetails" :{
         "details" : "XXXXX"
      }
}
</code>```

How could i achieve the above

答:
As AshvinGudaliya's comment suggests, the issue is the type of dict2 - you've typed it as [String: String], and then you try to put an object of type [String: String] as a value - but it will only accept String values.

Creating dict2 as a [String: Any] will allow you to add a non-string value to it, in this case the contents of dict1, a [String: String]

Body:
I got a dictionary say dict1 with some keys and values and i want to store all the values of dict1 to another dictionary say dict2 with a key and i tried  parse them to JSON using SwiftyJson.
What i tried has been given below,

var dict1 = [String: String]()
var dict2 = [String: String]()

// Values of dict1
dict1["details"] = "XXXXX"

//trying to save values of dict1 to dict2
dict2["moreDetails"] = dict1 as? String
let jsonValue = JSON(dict2)
print(jsonValue)

What i obtain is an empty jsonString like this {    }

What i actually want to get is

{
"moreDetails" :{
         "details" : "XXXXX"
      }
}

How could i achieve the above


问:
How do I parallelise a for loop, using `omp parallel` or otherwise?
Assuming I have three integer vectors:

mainVect of size 8 million element

vect1 of size 1.5 million element

vect2 of size 1.5 million element

I want to run the following code:

```<code>int i,j;
for ( i = 0; i < vect1.size(); i++)
{
    for ( j = 0; j < mainVect.size(); j++)
    {
        if (vect1[i] == mainVect[j])
        {
            vect2[i]++;
        }
    }
}
</code>```

It took a very long time without finishing yet...How I can speed up the run, I have multiprocessors. As a try, I've added the following sentence before the previous code (I read that it run in parallel)

```<code>#pragma omp parallel for private(i, j) shared( mainVect, vect1, vect2)
</code>```

But still slow ...

If I divide the for loop into 4 sections; for example, how I can make these for loops run simultaneously such as

```<code>for ( i = 0; i < vect1.size()/4; i++)
{

}

for ( i = vect1.size()/4; i < vect1.size()/2; i++)
{

}
.... and so on
</code>```

Or any other methods ...

P.S.:
Windows google cloud machine, n1-standard-4 (4 vCPUs, 15 GB memory) .. CPU utilization only 27% when run the above code.

答:
8 million ints do not take much space. You may use unordered_map or some other efficient associative containers.

```<code>unordered_map<int, int> umap;
for (int v : mainVect) {
    umap[v]++;
}
for (int i = 0; i < vect1.size(); ++i) {
    if (umap.count(vect1[i])) {
        vect2[i] += umap[vect1[i]];
    }
}
</code>```

This one takes linear time to populate vect2 which is very fast.

Body:
Assuming I have three integer vectors:

mainVect of size 8 million element

vect1 of size 1.5 million element

vect2 of size 1.5 million element

I want to run the following code:

int i,j;
for ( i = 0; i < vect1.size(); i++)
{
    for ( j = 0; j < mainVect.size(); j++)
    {
        if (vect1[i] == mainVect[j])
        {
            vect2[i]++;
        }
    }
}

It took a very long time without finishing yet...How I can speed up the run, I have multiprocessors. As a try, I've added the following sentence before the previous code (I read that it run in parallel)

#pragma omp parallel for private(i, j) shared( mainVect, vect1, vect2)

But still slow ...

If I divide the for loop into 4 sections; for example, how I can make these for loops run simultaneously such as

for ( i = 0; i < vect1.size()/4; i++)
{

}

for ( i = vect1.size()/4; i < vect1.size()/2; i++)
{

}
.... and so on

Or any other methods ...

P.S.:
Windows google cloud machine, n1-standard-4 (4 vCPUs, 15 GB memory) .. CPU utilization only 27% when run the above code.

Body:
8 million ints do not take much space. You may use unordered_map or some other efficient associative containers.

unordered_map<int, int> umap;
for (int v : mainVect) {
    umap[v]++;
}
for (int i = 0; i < vect1.size(); ++i) {
    if (umap.count(vect1[i])) {
        vect2[i] += umap[vect1[i]];
    }
}

This one takes linear time to populate vect2 which is very fast.


问:
Django Queryset - Sort alphabetical then move specific entries to top

Edit (Background info)

I've created a custom UserModelChoiceField class that takes a QuerySet of users and populates a select field with their full names:

```<code>class UserModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return "{} ({})".format(obj.get_full_name(), obj.username)
</code>```

I'm now attempting to use this class like:

```<code>calibrated_by_internal = UserModelChoiceField(
                                              queryset=total_qs,
                                              required=False,
                                              widget=forms.Select(attrs={"class": "form-control"})
                                              )
</code>```

.

Original Question

I'm trying to create a custom sorted QuerySet that will allow me to put a User ModelChoice select field on a form that is sorted alphabetically, but 3 members of a particular permissions group are put at the top.

For example:

Members of the group:
Charlie, Alan, Brian

Not members of the group:
Ben, Chris, Alicia... etc.

Required QuerySet / Select Field ordering:
Alan, Brian, Charlie, Alicia, Ben, Chris... etc.

Given that I'm using Django 1.11 I thought I'd try the new .union ORM function:

```<code>group_members = User.objects.filter(groups__name="AddEditCalibrations").order_by("first_name", "last_name")
everyone_else = User.objects.exclude(username__in="group_members").order_by("first_name", "last_name")
total_qs = group_members.union(everyone_else)
</code>```

Which just raises the error:

```<code>DATABASE ERROR - ORDER BY not allowed in subqueries of compound statements
</code>```

It seems to work OK without the 2 ORDER_BYs, but then the list isn't sorted alphabetically and the members of that group that need to be at the top of the select (first in the QS) are just mixed in with everyone else.

So I tried the even simpler:

```<code>total_qs = User.objects.order_by(groups__name="AddEditCalibrations", "first_name", "last_name")
</code>```

Which raises error:

```<code>SyntaxError: positional argument follows keyword argument
</code>```

Edit

Following rajkris' suggestion of using itertools I tried:

```<code>total_list = list(chain(group_members, everyone_else))
</code>```

Given that I need a QS to populate the select field I then tried to convert it back to a QS with:

```<code>total_qs = User.objects.filter(username__in=total_list)
</code>```

But this only got me an unsorted list with all users mixed together without any ordering.

答:
Maybe try out chain from itertools to convert it into a list:

```<code>from itertools import chain
result_list = list(chain(group_members, everyone_else))
</code>```

AND maybe we can use something like this for obtaining the queryset.

```<code>pk_list = [each.id for each in result_list]
ordering = 'FIELD(`id`, %s)' % ','.join(str(id) for id in pk_list)
queryset = User.objects.filter(pk__in=pk_list).extra(
       select={'ordering': ordering}, order_by=('ordering',))
</code>```

Body:
Edit (Background info)

I've created a custom UserModelChoiceField class that takes a QuerySet of users and populates a select field with their full names:

class UserModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return "{} ({})".format(obj.get_full_name(), obj.username)

I'm now attempting to use this class like:

calibrated_by_internal = UserModelChoiceField(
                                              queryset=total_qs,
                                              required=False,
                                              widget=forms.Select(attrs={"class": "form-control"})
                                              )

.

Original Question

I'm trying to create a custom sorted QuerySet that will allow me to put a User ModelChoice select field on a form that is sorted alphabetically, but 3 members of a particular permissions group are put at the top.

For example:

Members of the group:
Charlie, Alan, Brian

Not members of the group:
Ben, Chris, Alicia... etc.

Required QuerySet / Select Field ordering:
Alan, Brian, Charlie, Alicia, Ben, Chris... etc.

Given that I'm using Django 1.11 I thought I'd try the new .union ORM function:

group_members = User.objects.filter(groups__name="AddEditCalibrations").order_by("first_name", "last_name")
everyone_else = User.objects.exclude(username__in="group_members").order_by("first_name", "last_name")
total_qs = group_members.union(everyone_else)

Which just raises the error:

DATABASE ERROR - ORDER BY not allowed in subqueries of compound statements

It seems to work OK without the 2 ORDER_BYs, but then the list isn't sorted alphabetically and the members of that group that need to be at the top of the select (first in the QS) are just mixed in with everyone else.

So I tried the even simpler:

total_qs = User.objects.order_by(groups__name="AddEditCalibrations", "first_name", "last_name")

Which raises error:

SyntaxError: positional argument follows keyword argument

Edit

Following rajkris' suggestion of using itertools I tried:

total_list = list(chain(group_members, everyone_else))

Given that I need a QS to populate the select field I then tried to convert it back to a QS with:

total_qs = User.objects.filter(username__in=total_list)

But this only got me an unsorted list with all users mixed together without any ordering.

Body:
Maybe try out chain from itertools to convert it into a list:

from itertools import chain
result_list = list(chain(group_members, everyone_else))

AND maybe we can use something like this for obtaining the queryset.

pk_list = [each.id for each in result_list]
ordering = 'FIELD(`id`, %s)' % ','.join(str(id) for id in pk_list)
queryset = User.objects.filter(pk__in=pk_list).extra(
       select={'ordering': ordering}, order_by=('ordering',))


问:
Bootstrap modal not working on loop scenarios
I am trying to create generalised method for ajax in my javascript and bootstrap modal is not working as expected.

HTML :

```<code><div class="modal fade" id="consult_modal_v2" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div style="background-color: #dc3d3e;color: #fff;height:85px !important;;" class="modal-header">
                <div>
                    <div class="row">
                        <div class="col-md-11">
                            <h4 id="message_v2" style="text-align:center;margin-top: 10px;"></h4>
                        </div>
                    </div>
                </div>
                <button id="con_close1_v2" type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button>
            </div>
            <div class="container"></div>
            <div class="modal-body">

                <div class="col-md-12" style="margin-top:3%;margin-bottom:2%;">

                    <div class="col-md-3" id="con_uname_v2" style="margin-top:11px">Admin Username</div>
                    <div class="col-md-9"><input type="text" id="con_sect_name_v2" class="form-control"></div>
                    <div class="col-md-3" id="con_pass_v2" style="margin-top:11px">Admin Password</div>
                    <div class="col-md-9"><input type="password" id="con_sect_pass_v2" class="form-control"></div>

                </div>

            </div>
            <div style="border:none;" class="modal-footer" >
                <button class="btn btn-default" id="con_close_v2" style="margin-top:3%;">Cancel</button>
                <button class="btn btn-default" id="con_sect_ok_v2" style="margin-right:2%;margin-top:3%;">Override</button>
                <button class="btn btn-default" id="con_upd_sect_ok_v2" style="display:none;margin-right:2%;margin-top:3%;">Override</button>

            </div>
        </div>
    </div>
</div>
</code>```

JavaScript:

Executed as

```<code>generalised_ajax('post_url',
    {
        'sub_id': sub_id,
        'status': status,
        '_token': csrf_token
    }, "POST", function () {
        console.log('success placing apt');
    }, {},
    function () {
        console.log('apt cancelled');
    }, {});

function generalised_ajax(url, data, type, post_success, post_success_params, post_cancel, post_cancel_params) {
    $.ajax({
        url: url,
        data: data,
        type: type,
        headers: {Accept: "application/json"},
        dataType: 'json',
        success: function (result, status, xhr) {
            post_success(post_success_params);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            if (xhr.responseJSON.type === "confirmation") {
                responseProcess = xhr.responseJSON;
                generalised_confirm(responseProcess.message, {
                    url: url,
                    data: data,
                    type: type,
                    post_success: post_success,
                    post_success_params: post_success_params,
                    post_cancel: post_cancel,
                    post_cancel_params: post_cancel_params
                }, responseProcess.config_name);
            } else if(xhr.responseJSON.type === "admin_auth"){
                generalised_authentication(responseProcess.message, {
                    url: url,
                    data: data,
                    type: type,
                    post_success: post_success,
                    post_success_params: post_success_params,
                    post_cancel: post_cancel,
                    post_cancel_params: post_cancel_params
                });
            }
        }
    });
}

function generalised_confirm(message, data, config_name) {
    var r = confirm(message);
    if (r === true) {
        data.data[config_name] = true;
        generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
    } else {
        data.post_cancel(data.post_cancel_params);
    }
}

var modelX = $("#consult_modal_v2");
function generalised_authentication(message, data){
    var uname = $("#con_sect_name_v2");
    var pass = $("#con_sect_pass_v2");
    $("#message_v2").val(message);
    modelX.modal('toggle');
    $("#con_sect_ok_v2").click(function(event){
        modelX.modal('toggle');
        data.data['a_uname'] = uname.val();
        data.data['a_pswd'] = pass.val();
        uname.val('');
        pass.val('');
        generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
    });
    $("#con_close_v2").click(function(event){
        modelX.modal('toggle');
        data.post_cancel(data.post_cancel_params);
    });
}
</code>```

Expected scenarios:

Sent ajax

Server responded with admin_auth error

Open modal

Input admin creds (wrong ones)

Close modal

Sent ajax

Server responded with admin_auth error

Repeat from stage 3

How it's working right now

Sent ajax

Server responded with admin_auth error

Open modal

Input admin creds (wrong ones)

Close modal

Sent ajax

Now server responded with same ajax as Point 2. But modal won't open again.
It is working fine with javascripts confirmation popup.

Update:

After I removed fade class from modal, it started appearing everytime. But now it sends double of ajax of previous attempt.
Like for first time once, second time twice, third time 4 times, 4th time 8 times and so on.

答:
I don't know what is the reason of this behaviour but
changing

```<code>$("#con_sect_ok_v2").click(function(event){
        modelX.modal('toggle');
        data.data['a_uname'] = uname.val();
        data.data['a_pswd'] = pass.val();
        uname.val('');
        pass.val('');
        generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
    });
</code>```

to

```<code>$("#con_sect_ok_v2").one('click',function(event){
        modelX.modal('toggle');
        data.data['a_uname'] = uname.val();
        data.data['a_pswd'] = pass.val();
        uname.val('');
        pass.val('');
        generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
    });
</code>```

solved it.

Credits https://stackoverflow.com/a/3393694/2598994

Body:
I am trying to create generalised method for ajax in my javascript and bootstrap modal is not working as expected.

HTML :

                <button id="con_close1_v2" type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button>

Admin Username

<input type="text" id="con_sect_name_v2" class="form-control">

Admin Password

<input type="password" id="con_sect_pass_v2" class="form-control">

                <button class="btn btn-default" id="con_close_v2" style="margin-top:3%;">Cancel</button>
                <button class="btn btn-default" id="con_sect_ok_v2" style="margin-right:2%;margin-top:3%;">Override</button>
                <button class="btn btn-default" id="con_upd_sect_ok_v2" style="display:none;margin-right:2%;margin-top:3%;">Override</button>

JavaScript:

Executed as

generalised_ajax('post_url',
    {
        'sub_id': sub_id,
        'status': status,
        '_token': csrf_token
    }, "POST", function () {
        console.log('success placing apt');
    }, {},
    function () {
        console.log('apt cancelled');
    }, {});

function generalised_ajax(url, data, type, post_success, post_success_params, post_cancel, post_cancel_params) {
    $.ajax({
        url: url,
        data: data,
        type: type,
        headers: {Accept: "application/json"},
        dataType: 'json',
        success: function (result, status, xhr) {
            post_success(post_success_params);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            if (xhr.responseJSON.type === "confirmation") {
                responseProcess = xhr.responseJSON;
                generalised_confirm(responseProcess.message, {
                    url: url,
                    data: data,
                    type: type,
                    post_success: post_success,
                    post_success_params: post_success_params,
                    post_cancel: post_cancel,
                    post_cancel_params: post_cancel_params
                }, responseProcess.config_name);
            } else if(xhr.responseJSON.type === "admin_auth"){
                generalised_authentication(responseProcess.message, {
                    url: url,
                    data: data,
                    type: type,
                    post_success: post_success,
                    post_success_params: post_success_params,
                    post_cancel: post_cancel,
                    post_cancel_params: post_cancel_params
                });
            }
        }
    });
}

function generalised_confirm(message, data, config_name) {
    var r = confirm(message);
    if (r === true) {
        data.data[config_name] = true;
        generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
    } else {
        data.post_cancel(data.post_cancel_params);
    }
}

var modelX = $("#consult_modal_v2");
function generalised_authentication(message, data){
    var uname = $("#con_sect_name_v2");
    var pass = $("#con_sect_pass_v2");
    $("#message_v2").val(message);
    modelX.modal('toggle');
    $("#con_sect_ok_v2").click(function(event){
        modelX.modal('toggle');
        data.data['a_uname'] = uname.val();
        data.data['a_pswd'] = pass.val();
        uname.val('');
        pass.val('');
        generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
    });
    $("#con_close_v2").click(function(event){
        modelX.modal('toggle');
        data.post_cancel(data.post_cancel_params);
    });
}

Expected scenarios:

Sent ajax

Server responded with admin_auth error

Open modal

Input admin creds (wrong ones)

Close modal

Sent ajax

Server responded with admin_auth error

Repeat from stage 3

How it's working right now

Sent ajax

Server responded with admin_auth error

Open modal

Input admin creds (wrong ones)

Close modal

Sent ajax

Now server responded with same ajax as Point 2. But modal won't open again.
It is working fine with javascripts confirmation popup.

Update:

After I removed fade class from modal, it started appearing everytime. But now it sends double of ajax of previous attempt.
Like for first time once, second time twice, third time 4 times, 4th time 8 times and so on.

Body:
I don't know what is the reason of this behaviour but
changing

$("#con_sect_ok_v2").click(function(event){
        modelX.modal('toggle');
        data.data['a_uname'] = uname.val();
        data.data['a_pswd'] = pass.val();
        uname.val('');
        pass.val('');
        generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
    });

to

$("#con_sect_ok_v2").one('click',function(event){
        modelX.modal('toggle');
        data.data['a_uname'] = uname.val();
        data.data['a_pswd'] = pass.val();
        uname.val('');
        pass.val('');
        generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
    });

solved it.

Credits https://stackoverflow.com/a/3393694/2598994


问:
Is there a way to stream a stored Flash video to multiple people in sync, but let one of them control playback (play/pause/seek/etc.)
I don't know much about deploying Flash video streaming solutions, and I want to know if the following can be accomplished in Flash.

I am creating an application where multiple people can watch a video at the same time , but one of those people controls the playback of the video for everyone. Furthermore, the controller is not always the same person, it can change if someone leaves or depending on other factors.

Please point me in the right direction.

Thanks!

答:
I'm sure it's possible. I don't do flash; but here is a high-level idea about how to accomplish this:

Play the video on each client; and make sure they are in sync. But when the "controller" pauses, skips or stops the video, send a signal to each client repeating the action on their own client. You could do this using a database (for MySQL a table with back-end of type MEMORY should be good for this). Each second the clients ask the server if their has been a change of the "controllers" actions. Each time the "controller" makes an action it gets queued in the database.

The only issue I see left is making sure each client's stream is in sync (like, instead of "slowing down" when there is lag it simply "skips" to the frame that the "controller" is at)

I hope this helps a bit :)

EDIT

Each second the "controller" sends a message to the clients with his current frame count of the video... it could work.

OwnerDisplayName: Karthik

ContentLicense: CC BY-SA 2.5


问:
How do I access my iPhone 4's UDID?
I have just bought an iPhone 4 for development.

Unfortunately, I forgot to register my phone to my development account before I tried installing the iOS 4.3 beta 2 software.

Now I can't restore my iPhone because I haven't got my UDID in my developer account, and I cannot get the UDID in iTunes because my phone is stuck in recovery mode.

Does anyone know how to restore my phone, or how to get the UDID into the developer account so it can be restored?

Thank you

答: Can't you downgrade the firmware by downloading the older version from the internet and hold shift and click restore and select the firmware file?</p>

Title: How do I access my iPhone 4's UDID?


问:
How to copy a 2016 excel to another(including formulas, cell style and date format) using apache poi.
How to copy a 2016 excel to another(including formulas, cell style and date format) using apache poi.Below is the code that i have tried. It copies the file, but does not copy cell style. Also the cell type method is shown as deprecated, is their a new approach to this ? Also i need to try it out using XSSF and not HSSF.</p>

```<code>public void copy(String origFileName,String newFileName) {
            // TODO Auto-generated method stub
            try {
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(origFileName));
                XSSFWorkbook origWorkbook = new XSSFWorkbook(bis);
                XSSFWorkbook copyWorkbook = new XSSFWorkbook();
                XSSFSheet origSheet = null;
                XSSFRow origRow = null;
                XSSFCell origCell = null;
                XSSFSheet copySheet = null;
                XSSFRow copyRow = null;
                XSSFCell copyCell = null;
                int origSheets = origWorkbook.getNumberOfSheets();
                int fCell = 0;
                int lCell = 0;
                int fRow = 0;
                int lRow = 0;
                for (int iSheet = 0; iSheet < origSheets; iSheet++) {
                    origSheet = origWorkbook.getSheetAt(iSheet);
                    if (origSheet != null) {
                        copySheet = copyWorkbook.createSheet(origSheet.getSheetName());
                        fRow = origSheet.getFirstRowNum();
                        lRow = origSheet.getLastRowNum();
                        for (int iRow = fRow; iRow <= lRow; iRow++) {
                            origRow = origSheet.getRow(iRow);
                            copyRow = copySheet.createRow(iRow);
                            if (origRow != null) {
                                fCell = origRow.getFirstCellNum();
                                lCell = origRow.getLastCellNum();
                                for (int iCell = fCell; iCell < lCell; iCell++) {
                                    origCell = origRow.getCell(iCell);
                                    copyCell = copyRow.createCell(iCell);
                                    if (origCell != null) {
                                        CellStyle cellStyle = setCellStyle(copyWorkbook, origCell);
                                        copyCell.setCellType(origCell.getCellType());
                                        switch (origCell.getCellType()) {
                                        case XSSFCell.CELL_TYPE_BLANK:
                                            copyCell.setCellValue("");
                                            break;

                                        case XSSFCell.CELL_TYPE_BOOLEAN:
                                            copyCell.setCellValue(origCell.getBooleanCellValue());
                                            break;

                                        case XSSFCell.CELL_TYPE_ERROR:
                                            copyCell.setCellErrorValue(origCell.getErrorCellValue());
                                            break;

                                        case XSSFCell.CELL_TYPE_FORMULA:
                                            copyCell.setCellFormula(origCell.getCellFormula());
                                            break;

                                        case XSSFCell.CELL_TYPE_NUMERIC:
                                            copyCell.setCellValue(origCell.getNumericCellValue());
                                            break;

                                        case XSSFCell.CELL_TYPE_STRING:
                                            copyCell.setCellValue(origCell.getStringCellValue());
                                            break;
                                        default:
                                            copyCell.setCellFormula(origCell.getCellFormula());
                                        }
                                        copyCell.setCellStyle(cellStyle);
                                    }
                                }
                            }
                        }
                    }
                }

                bis.close();
                BufferedOutputStream bos;
                bos = new BufferedOutputStream(new FileOutputStream(newFileName, true));
                copyWorkbook.write(bos);
                bos.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    private CellStyle setCellStyle(XSSFWorkbook copyWorkbook, XSSFCell origCell) {
            CellStyle cellStyle = copyWorkbook.createCellStyle();
            //cellStyle.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
            cellStyle.setFillForegroundColor(origCell.getCellStyle().getFillForegroundColor());
            cellStyle.setFont(origCell.getCellStyle().getFont());
            cellStyle.setBottomBorderColor(origCell.getCellStyle().getBottomBorderColor());
            cellStyle.setLeftBorderColor(origCell.getCellStyle().getLeftBorderColor());
            cellStyle.setLocked(origCell.getCellStyle().getLocked());
            cellStyle.setQuotePrefixed(origCell.getCellStyle().getQuotePrefixed());
            cellStyle.setRightBorderColor(origCell.getCellStyle().getRightBorderColor());
            cellStyle.setRotation(origCell.getCellStyle().getRotation());
            cellStyle.setShrinkToFit(origCell.getCellStyle().getShrinkToFit());
            cellStyle.setTopBorderColor(origCell.getCellStyle().getTopBorderColor());
            cellStyle.setVerticalAlignment(origCell.getCellStyle().getVerticalAlignmentEnum());
            cellStyle.setWrapText(origCell.getCellStyle().getWrapText());
            cellStyle.setHidden(origCell.getCellStyle().getHidden());
            cellStyle.setIndention(origCell.getCellStyle().getIndention());
            cellStyle.setAlignment(origCell.getCellStyle().getAlignmentEnum());
            cellStyle.setBorderBottom(origCell.getCellStyle().getBorderBottomEnum());
            cellStyle.setBorderLeft(origCell.getCellStyle().getBorderLeftEnum());
            cellStyle.setBorderRight(origCell.getCellStyle().getBorderRightEnum());
            cellStyle.setBorderTop(origCell.getCellStyle().getBorderTopEnum());
            cellStyle.setFillPattern(origCell.getCellStyle().getFillPatternEnum());
            return cellStyle;
        }
</code>```

答:
to copy the style see: Copy a XSSF/HSSF-Cells into a new XSSFWorkbook

I modified your code and its working fine.

See the modified code for new way to handle cell type.

Assuming workbook exist under c:\temp\1.xlsx

```<code>import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class CopyCat {

    public void copy(String origFileName,String newFileName) {
        // TODO Auto-generated method stub
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(origFileName));
            XSSFWorkbook origWorkbook = new XSSFWorkbook(bis);
            XSSFWorkbook copyWorkbook = new XSSFWorkbook();
            XSSFSheet origSheet = null;
            XSSFRow origRow = null;
            XSSFCell origCell = null;
            XSSFSheet copySheet = null;
            XSSFRow copyRow = null;
            XSSFCell copyCell = null;
            int origSheets = origWorkbook.getNumberOfSheets();
            int fCell = 0;
            int lCell = 0;
            int fRow = 0;
            int lRow = 0;
            for (int iSheet = 0; iSheet < origSheets; iSheet++) {
                origSheet = origWorkbook.getSheetAt(iSheet);
                if (origSheet != null) {
                    copySheet = copyWorkbook.createSheet(origSheet.getSheetName());
                    fRow = origSheet.getFirstRowNum();
                    lRow = origSheet.getLastRowNum();
                    for (int iRow = fRow; iRow <= lRow; iRow++) {
                        origRow = origSheet.getRow(iRow);
                        copyRow = copySheet.createRow(iRow);
                        if (origRow != null) {
                            fCell = origRow.getFirstCellNum();
                            lCell = origRow.getLastCellNum();
                            for (int iCell = fCell; iCell < lCell; iCell++) {
                                origCell = origRow.getCell(iCell);
                                copyCell = copyRow.createCell(iCell);
                                if (origCell != null) {
                                    // read more here
                                    //https://stackoverflow.com/questions/32067614/copy-a-xssf-hssf-cells-into-a-new-xssfworkbook

                                    XSSFCellStyle origCellStyle = origCell.getCellStyle();
                                    XSSFCellStyle copyCellStyle = copyWorkbook.createCellStyle();
                                    copyCellStyle.cloneStyleFrom(origCellStyle);
                                    copyCell.setCellStyle(copyCellStyle);

                                    CellType origCellType = origCell.getCellTypeEnum();
                                    copyCell.setCellType(origCellType);

// This is the new way :getCellTypeEnum

switch (origCellType) {
                                    case BLANK:
                                        copyCell.setCellValue("");
                                        break;

                                    case BOOLEAN:
                                        copyCell.setCellValue(origCell.getBooleanCellValue());
                                        break;

                                    case ERROR:
                                        copyCell.setCellErrorValue(origCell.getErrorCellValue());
                                        break;

                                    case FORMULA:
                                        copyCell.setCellFormula(origCell.getCellFormula());
                                        break;

                                    case NUMERIC:
                                        copyCell.setCellValue(origCell.getNumericCellValue());
                                        break;

                                    case STRING:
                                        copyCell.setCellValue(origCell.getStringCellValue());
                                        break;
                                    default:
                                        copyCell.setCellFormula(origCell.getCellFormula());
                                    }
                                }
                            }
                        }
                    }
                }
            }

            bis.close();
            BufferedOutputStream bos;
            bos = new BufferedOutputStream(new FileOutputStream(newFileName, true));
            copyWorkbook.write(bos);
            bos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

public static void main(String[] args) {
    new CopyCat().copy("c:\\temp\\1.xlsx", "c:\\temp\\2.xlsx");
}
}
</code>```

Body:
How to copy a 2016 excel to another(including formulas, cell style and date format) using apache poi.Below is the code that i have tried. It copies the file, but does not copy cell style. Also the cell type method is shown as deprecated, is their a new approach to this ? Also i need to try it out using XSSF and not HSSF.

public void copy(String origFileName,String newFileName) {
            // TODO Auto-generated method stub
            try {
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(origFileName));
                XSSFWorkbook origWorkbook = new XSSFWorkbook(bis);
                XSSFWorkbook copyWorkbook = new XSSFWorkbook();
                XSSFSheet origSheet = null;
                XSSFRow origRow = null;
                XSSFCell origCell = null;
                XSSFSheet copySheet = null;
                XSSFRow copyRow = null;
                XSSFCell copyCell = null;
                int origSheets = origWorkbook.getNumberOfSheets();
                int fCell = 0;
                int lCell = 0;
                int fRow = 0;
                int lRow = 0;
                for (int iSheet = 0; iSheet < origSheets; iSheet++) {
                    origSheet = origWorkbook.getSheetAt(iSheet);
                    if (origSheet != null) {
                        copySheet = copyWorkbook.createSheet(origSheet.getSheetName());
                        fRow = origSheet.getFirstRowNum();
                        lRow = origSheet.getLastRowNum();
                        for (int iRow = fRow; iRow <= lRow; iRow++) {
                            origRow = origSheet.getRow(iRow);
                            copyRow = copySheet.createRow(iRow);
                            if (origRow != null) {
                                fCell = origRow.getFirstCellNum();
                                lCell = origRow.getLastCellNum();
                                for (int iCell = fCell; iCell < lCell; iCell++) {
                                    origCell = origRow.getCell(iCell);
                                    copyCell = copyRow.createCell(iCell);
                                    if (origCell != null) {
                                        CellStyle cellStyle = setCellStyle(copyWorkbook, origCell);
                                        copyCell.setCellType(origCell.getCellType());
                                        switch (origCell.getCellType()) {
                                        case XSSFCell.CELL_TYPE_BLANK:
                                            copyCell.setCellValue("");
                                            break;

                                        case XSSFCell.CELL_TYPE_BOOLEAN:
                                            copyCell.setCellValue(origCell.getBooleanCellValue());
                                            break;

                                        case XSSFCell.CELL_TYPE_ERROR:
                                            copyCell.setCellErrorValue(origCell.getErrorCellValue());
                                            break;

                                        case XSSFCell.CELL_TYPE_FORMULA:
                                            copyCell.setCellFormula(origCell.getCellFormula());
                                            break;

                                        case XSSFCell.CELL_TYPE_NUMERIC:
                                            copyCell.setCellValue(origCell.getNumericCellValue());
                                            break;

                                        case XSSFCell.CELL_TYPE_STRING:
                                            copyCell.setCellValue(origCell.getStringCellValue());
                                            break;
                                        default:
                                            copyCell.setCellFormula(origCell.getCellFormula());
                                        }
                                        copyCell.setCellStyle(cellStyle);
                                    }
                                }
                            }
                        }
                    }
                }

                bis.close();
                BufferedOutputStream bos;
                bos = new BufferedOutputStream(new FileOutputStream(newFileName, true));
                copyWorkbook.write(bos);
                bos.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    private CellStyle setCellStyle(XSSFWorkbook copyWorkbook, XSSFCell origCell) {
            CellStyle cellStyle = copyWorkbook.createCellStyle();
            //cellStyle.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
            cellStyle.setFillForegroundColor(origCell.getCellStyle().getFillForegroundColor());
            cellStyle.setFont(origCell.getCellStyle().getFont());
            cellStyle.setBottomBorderColor(origCell.getCellStyle().getBottomBorderColor());
            cellStyle.setLeftBorderColor(origCell.getCellStyle().getLeftBorderColor());
            cellStyle.setLocked(origCell.getCellStyle().getLocked());
            cellStyle.setQuotePrefixed(origCell.getCellStyle().getQuotePrefixed());
            cellStyle.setRightBorderColor(origCell.getCellStyle().getRightBorderColor());
            cellStyle.setRotation(origCell.getCellStyle().getRotation());
            cellStyle.setShrinkToFit(origCell.getCellStyle().getShrinkToFit());
            cellStyle.setTopBorderColor(origCell.getCellStyle().getTopBorderColor());
            cellStyle.setVerticalAlignment(origCell.getCellStyle().getVerticalAlignmentEnum());
            cellStyle.setWrapText(origCell.getCellStyle().getWrapText());
            cellStyle.setHidden(origCell.getCellStyle().getHidden());
            cellStyle.setIndention(origCell.getCellStyle().getIndention());
            cellStyle.setAlignment(origCell.getCellStyle().getAlignmentEnum());
            cellStyle.setBorderBottom(origCell.getCellStyle().getBorderBottomEnum());
            cellStyle.setBorderLeft(origCell.getCellStyle().getBorderLeftEnum());
            cellStyle.setBorderRight(origCell.getCellStyle().getBorderRightEnum());
            cellStyle.setBorderTop(origCell.getCellStyle().getBorderTopEnum());
            cellStyle.setFillPattern(origCell.getCellStyle().getFillPatternEnum());
            return cellStyle;
        }

Body:
to copy the style see: Copy a XSSF/HSSF-Cells into a new XSSFWorkbook

I modified your code and its working fine.

See the modified code for new way to handle cell type.

Assuming workbook exist under c:\temp\1.xlsx

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class CopyCat {

    public void copy(String origFileName,String newFileName) {
        // TODO Auto-generated method stub
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(origFileName));
            XSSFWorkbook origWorkbook = new XSSFWorkbook(bis);
            XSSFWorkbook copyWorkbook = new XSSFWorkbook();
            XSSFSheet origSheet = null;
            XSSFRow origRow = null;
            XSSFCell origCell = null;
            XSSFSheet copySheet = null;
            XSSFRow copyRow = null;
            XSSFCell copyCell = null;
            int origSheets = origWorkbook.getNumberOfSheets();
            int fCell = 0;
            int lCell = 0;
            int fRow = 0;
            int lRow = 0;
            for (int iSheet = 0; iSheet < origSheets; iSheet++) {
                origSheet = origWorkbook.getSheetAt(iSheet);
                if (origSheet != null) {
                    copySheet = copyWorkbook.createSheet(origSheet.getSheetName());
                    fRow = origSheet.getFirstRowNum();
                    lRow = origSheet.getLastRowNum();
                    for (int iRow = fRow; iRow <= lRow; iRow++) {
                        origRow = origSheet.getRow(iRow);
                        copyRow = copySheet.createRow(iRow);
                        if (origRow != null) {
                            fCell = origRow.getFirstCellNum();
                            lCell = origRow.getLastCellNum();
                            for (int iCell = fCell; iCell < lCell; iCell++) {
                                origCell = origRow.getCell(iCell);
                                copyCell = copyRow.createCell(iCell);
                                if (origCell != null) {
                                    // read more here
                                    //https://stackoverflow.com/questions/32067614/copy-a-xssf-hssf-cells-into-a-new-xssfworkbook

                                    XSSFCellStyle origCellStyle = origCell.getCellStyle();
                                    XSSFCellStyle copyCellStyle = copyWorkbook.createCellStyle();
                                    copyCellStyle.cloneStyleFrom(origCellStyle);
                                    copyCell.setCellStyle(copyCellStyle);

                                    CellType origCellType = origCell.getCellTypeEnum();
                                    copyCell.setCellType(origCellType);

// This is the new way :getCellTypeEnum

switch (origCellType) {
                                    case BLANK:
                                        copyCell.setCellValue("");
                                        break;

                                    case BOOLEAN:
                                        copyCell.setCellValue(origCell.getBooleanCellValue());
                                        break;

                                    case ERROR:
                                        copyCell.setCellErrorValue(origCell.getErrorCellValue());
                                        break;

                                    case FORMULA:
                                        copyCell.setCellFormula(origCell.getCellFormula());
                                        break;

                                    case NUMERIC:
                                        copyCell.setCellValue(origCell.getNumericCellValue());
                                        break;

                                    case STRING:
                                        copyCell.setCellValue(origCell.getStringCellValue());
                                        break;
                                    default:
                                        copyCell.setCellFormula(origCell.getCellFormula());
                                    }
                                }
                            }
                        }
                    }
                }
            }

            bis.close();
            BufferedOutputStream bos;
            bos = new BufferedOutputStream(new FileOutputStream(newFileName, true));
            copyWorkbook.write(bos);
            bos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

public static void main(String[] args) {
    new CopyCat().copy("c:\\temp\\1.xlsx", "c:\\temp\\2.xlsx");
}
}


问:
Error adding enforce-valid-basic-auth-credentials to config.xml
I tried adding

```<code>  <enforce-valid-basic-auth-credentials>false</enforce-valid-basic-auth-credentials>
</code>```

inside the <security-configuration> tag in config.xml of weblogic server 12.1.3 After I add this line my weblogic server goes to shutdown whenever i start up my server.

is there something wrong? I have attached my config.xml contents below

```<code>            <domain-version>12.1.3.0.0</domain-version>
              <security-configuration>
                <name>mdm_domain</name>
                <realm>
                  <sec:authentication-provider xsi:type="wls:default-authenticatorType">
                    <sec:name>DefaultAuthenticator</sec:name>
                  </sec:authentication-provider>
                  <sec:authentication-provider xsi:type="wls:default-identity-asserterType">
                    <sec:name>DefaultIdentityAsserter</sec:name>
                    <sec:active-type>AuthenticatedUser</sec:active-type>
                  </sec:authentication-provider>
                  <sec:role-mapper xmlns:xac="http://xmlns.oracle.com/weblogic/security/xacml" xsi:type="xac:xacml-role-mapperType">
                    <sec:name>XACMLRoleMapper</sec:name>
                  </sec:role-mapper>
                  <sec:authorizer xmlns:xac="http://xmlns.oracle.com/weblogic/security/xacml" xsi:type="xac:xacml-authorizerType">
                    <sec:name>XACMLAuthorizer</sec:name>
                  </sec:authorizer>
                  <sec:adjudicator xsi:type="wls:default-adjudicatorType">
                    <sec:name>DefaultAdjudicator</sec:name>
                  </sec:adjudicator>
                  <sec:credential-mapper xsi:type="wls:default-credential-mapperType">
                    <sec:name>DefaultCredentialMapper</sec:name>
                  </sec:credential-mapper>
                  <sec:cert-path-provider xsi:type="wls:web-logic-cert-path-providerType">
                    <sec:name>WebLogicCertPathProvider</sec:name>
                  </sec:cert-path-provider>
                  <sec:cert-path-builder>WebLogicCertPathProvider</sec:cert-path-builder>
                  <sec:name>myrealm</sec:name>
                  <sec:password-validator xmlns:pas="http://xmlns.oracle.com/weblogic/security/providers/passwordvalidator" xsi:type="pas:system-password-validatorType">
                    <sec:name>SystemPasswordValidator</sec:name>
                    <pas:min-password-length>8</pas:min-password-length>
                    <pas:min-numeric-or-special-characters>1</pas:min-numeric-or-special-characters>
                  </sec:password-validator>
                </realm>
                <default-realm>myrealm</default-realm>
                <credential-encrypted>{AES}lWxYlHpEqfbODbLmeerJr6H86R6+lvszW466UpoYzuyh6X617HokRf/oKl3cZJM+JTXliBWwXFhAiC9G3JrbxYNBkXMUGqFSOicuMVJVD0tTCuTr6sfY7UPK9M40Vi4n</credential-encrypted>
                <node-manager-username>weblogic</node-manager-username>
                <node-manager-password-encrypted>{AES}loTlWUtqsyw7sq4ujEhLVDaHCv/s7k22k0KSacFO/Ww=</node-manager-password-encrypted>
                <enforce-valid-basic-auth-credentials>false</enforce-valid-basic-auth-credentials>
              </security-configuration>
</code>```

答:
If you get schema validation error, add tags as in below order.</p>

```<code><security-configuration>
......
<enforce-valid-basic-auth-credentials>false</enforce-valid-basic-auth-
credentials>
<use-kss-for-demo>true</use-kss-for-demo>
</security-configuration>
</code>```

Body:
I tried adding

  <enforce-valid-basic-auth-credentials>false</enforce-valid-basic-auth-credentials>

inside the <security-configuration> tag in config.xml of weblogic server 12.1.3 After I add this line my weblogic server goes to shutdown whenever i start up my server.

is there something wrong? I have attached my config.xml contents below

            <domain-version>12.1.3.0.0</domain-version>
              <security-configuration>
                <name>mdm_domain</name>
                <realm>
                  <sec:authentication-provider xsi:type="wls:default-authenticatorType">
                    <sec:name>DefaultAuthenticator</sec:name>
                  </sec:authentication-provider>
                  <sec:authentication-provider xsi:type="wls:default-identity-asserterType">
                    <sec:name>DefaultIdentityAsserter</sec:name>
                    <sec:active-type>AuthenticatedUser</sec:active-type>
                  </sec:authentication-provider>
                  <sec:role-mapper xmlns:xac="http://xmlns.oracle.com/weblogic/security/xacml" xsi:type="xac:xacml-role-mapperType">
                    <sec:name>XACMLRoleMapper</sec:name>
                  </sec:role-mapper>
                  <sec:authorizer xmlns:xac="http://xmlns.oracle.com/weblogic/security/xacml" xsi:type="xac:xacml-authorizerType">
                    <sec:name>XACMLAuthorizer</sec:name>
                  </sec:authorizer>
                  <sec:adjudicator xsi:type="wls:default-adjudicatorType">
                    <sec:name>DefaultAdjudicator</sec:name>
                  </sec:adjudicator>
                  <sec:credential-mapper xsi:type="wls:default-credential-mapperType">
                    <sec:name>DefaultCredentialMapper</sec:name>
                  </sec:credential-mapper>
                  <sec:cert-path-provider xsi:type="wls:web-logic-cert-path-providerType">
                    <sec:name>WebLogicCertPathProvider</sec:name>
                  </sec:cert-path-provider>
                  <sec:cert-path-builder>WebLogicCertPathProvider</sec:cert-path-builder>
                  <sec:name>myrealm</sec:name>
                  <sec:password-validator xmlns:pas="http://xmlns.oracle.com/weblogic/security/providers/passwordvalidator" xsi:type="pas:system-password-validatorType">
                    <sec:name>SystemPasswordValidator</sec:name>
                    <pas:min-password-length>8</pas:min-password-length>
                    <pas:min-numeric-or-special-characters>1</pas:min-numeric-or-special-characters>
                  </sec:password-validator>
                </realm>
                <default-realm>myrealm</default-realm>
                <credential-encrypted>{AES}lWxYlHpEqfbODbLmeerJr6H86R6+lvszW466UpoYzuyh6X617HokRf/oKl3cZJM+JTXliBWwXFhAiC9G3JrbxYNBkXMUGqFSOicuMVJVD0tTCuTr6sfY7UPK9M40Vi4n</credential-encrypted>
                <node-manager-username>weblogic</node-manager-username>
                <node-manager-password-encrypted>{AES}loTlWUtqsyw7sq4ujEhLVDaHCv/s7k22k0KSacFO/Ww=</node-manager-password-encrypted>
                <enforce-valid-basic-auth-credentials>false</enforce-valid-basic-auth-credentials>
              </security-configuration>

Body:
If you get schema validation error, add tags as in below order.

<security-configuration>
......
<enforce-valid-basic-auth-credentials>false</enforce-valid-basic-auth-
credentials>
<use-kss-for-demo>true</use-kss-for-demo>
</security-configuration>


问:
I keep getting a TypeError: 'str' object is not callable
This is part of a program that will tell the user what key stage they are in.

```<code>YearG = input("What year group are you in?");
if (YearG == ("Year 1") ("Year 2")):
</code>```

I expect the result to be You are in key stage X!

Instead, I get

TypeError: 'str' object is not callable

How can I fix that? EDIT:See answer below for how I fixed this issue, No further action needed.

答:
Python is not a parenthesis language, I believe you want the below.</p>

```<code>>>> YearG = input('What year group are you in?')
What year group are you in?10
>>> YearG
'10'
>>> if YearG == '10':
...     print('You entered 10')
... else:
...     print('You entered something other than 10')
...
You entered 10
</code>```

Body:
This is part of a program that will tell the user what key stage they are in.

YearG = input("What year group are you in?");
if (YearG == ("Year 1") ("Year 2")):

I expect the result to be You are in key stage X!

Instead, I get

TypeError: 'str' object is not callable

How can I fix that? EDIT:See answer below for how I fixed this issue, No further action needed.

Body:
Python is not a parenthesis language, I believe you want the below.

>>> YearG = input('What year group are you in?')
What year group are you in?10
>>> YearG
'10'
>>> if YearG == '10':
...     print('You entered 10')
... else:
...     print('You entered something other than 10')
...
You entered 10


问:
Low latency capture of button click
I want to have a physical button (not a software button) that I put into my custom rig. When I click this button, I want to receive a signal in my software e.g. by registering my callback function.

The goal is to have a panel of physical button that when click will perform certain tasks in the software. The interrupt (for lack of a better word) should be as low latency as possible.

What I have looked at so far:

Arduino: Use an Arduino board that is connected via RS232 and manually do the soldering necessary to hook a button from RadioShack to it. (Too much hardware work for my skill/time availability)

An Android application: Well not truly a hard button to click but it is a hardware. The Android app will communicate with my computer via Bluetooth. (I doubt the latency is good. But I would love to be proved wrong.)

A cross-platform solution is much appreciated.

Targeted platforms: 64-bit Linux and
Windows (in that order)

Language:
C++

Any idea what type of connection/device I should look into to achieve this?

答:
How about this?

http://www.orin.com/access/swifty/

Teeny weeny size. Huge possibilities. Swifty is a speedy USB switch interface in an extremely compact design. Working with up to two wired switches, or three wirelessly through Beam™, this pint-sized powerhouse can output mouse clicks, joystick buttons or keyboard functions.

Or even customize an old serial or USB mouse if your rig doesn't otherwise use one. Or maybe even if it does :)

Title: Low latency capture of button click


问:
Python function returning nothing when called
```<code>def my_test(some_function):

    def wrapper():

        num = 10

        if num == 10:
            print("Yes")
        else:
            print("No")

        some_function()

        print("Something is happening after some_function() is called")

    return wrapper

def just_some_function():
    print("Filler text")

my_test(just_some_function)
</code>```

When I run this script, it should display:

Yes

Filler text

Something is happening after some_function() is called

since my_test(just_some_function) calls my_test, goes through the wrapper function, checks if num == 10, prints "Yes," then goes to just_some_function() (since some_function is the "variable" for the function my_test()), prints "Filler text," then finally ends by printing "Something is happening after some_function() is called." But nothing happens in the console when I run the script.

答:
my_test is a higher-order function; all it does is return another function, in this case wrapper. You need to actually call that returned function:

```<code>my_test(just_some_function)()
</code>```

Note, other than for demonstration purposes - or as a decorator - this is a pretty pointless way to write code.

Body:
def my_test(some_function):

    def wrapper():

        num = 10

        if num == 10:
            print("Yes")
        else:
            print("No")

        some_function()

        print("Something is happening after some_function() is called")

    return wrapper

def just_some_function():
    print("Filler text")

my_test(just_some_function)

When I run this script, it should display:

Yes

Filler text

Something is happening after some_function() is called

since my_test(just_some_function) calls my_test, goes through the wrapper function, checks if num == 10, prints "Yes," then goes to just_some_function() (since some_function is the "variable" for the function my_test()), prints "Filler text," then finally ends by printing "Something is happening after some_function() is called." But nothing happens in the console when I run the script.

Body:
my_test is a higher-order function; all it does is return another function, in this case wrapper. You need to actually call that returned function:

my_test(just_some_function)()

Note, other than for demonstration purposes - or as a decorator - this is a pretty pointless way to write code.


问:
How to immediately re-render client-side using React + NextJS after initial server-side render?
I created a website using Next.js with React and really like to declare a js variable to define component styles like this:

```<code>const foo = {
  fontSize: '12px',
};
</code>```

And in the render method I do:

```<code>render() {
  return (
    <div style={foo}>bar</div>
  );
}
</code>```

Using ESLint I can quickly find unused styles/variables (if references are gone) and keep the code clean. Hence I do not use

bar

  );
}
```

The problem

The problem with using only js variables instead of

答:
The best way to trigger a render at any time in reactjs is to create the react element with that property. In your case I would calculate which font size to use first, then create the element with that property.

Font size would not seem to change, but if it did, you’ll probably have to put this state in a common parent element of the elements that use it.  This parent would take this state and give it as props to its children.

As a commenter suggests there are ways of triggering an update, but it’s better to reorganize your elements to do this through normal react methods.  Don’t be afraid of making more smaller react elements!

Body:
I created a website using Next.js with React and really like to declare a js variable to define component styles like this:

const foo = {
  fontSize: '12px',
};

And in the render method I do:

render() {
  return (

bar

  );
}

Using ESLint I can quickly find unused styles/variables (if references are gone) and keep the code clean. Hence I do not use

bar

  );
}

The problem

The problem with using only js variables instead of


问:
Postgres cursor calculation in Talend
Data was read from postgres table & written to file using Talend. Table size is 1.8GB with 1,050,000 records and has around 125 columns.

Assigned JVM as -Xms256M -Xmx1024M. The job failed due to being out of memory. Postgres keeps the result set in physical memory until the query completes. So the entire JVM was occupied and getting an out of memory issue. Please correct me if my understanding is wrong.

Enabled Cursor option and kept the value as 100,000 and JVM as -Xms256M -Xmx1024M. Job failed with java.lang.OutOfMemoryError: Java heap space

I don't understand the concept here. Cursor used here denotes the fetch size of rows. In my case, 100,000 was set. So 100,000 will be fetched and stored in physical memory and it will be pushed to file. Then, the occupied memory will be released and the next batch will be fetched. Please correct me if I'm wrong.

Considering my case, with 1,050,000 records it occupies 1.8GB. Each record occupies 1.8KB of size. 100,000 * 1.8 = 180,000KB. So entire size is just 175MB. Why is the job not running with a 1GB JVM? Someone please help me with, how does this process work?

Some records got dropped after setting the cursor option in talend. Cannot trace the problem in that.

答: Had the same problem with a tPostgresInput component. Disabling the Auto Commit setting in the tPostgresConnection component fixed the problem for me!</p>

Title: Postgres cursor calculation in Talend


问:
EntitySet could not be found
I'm working on an MVC site using EF4 as my data source. I've had no problems with other projects with EF4 until today. I'm getting an error stating EntitySet name Entities.Sites could not be found. I have another EDMX file for another dataset that is set up nearly the same (with different entity names) and it works fine when I try to run a LINQ query against it.

My EDMX has 2 tables (site and page) with a 1 to many association from the site to page table. Everything compiles fine, but in runtime, it's almost like the datamodel fails on every property list population. I do have Lazy Loading enabled (It's a .NET 4 project).

I stepped through the code on the designer class and it fails when it gets to a call like this

```<code>if((_Pages == null))
{
     _Pages = base.CreateObjectSet<Page>("Pages");
}
</code>```

I have not altered the code in the designer.cs. I'm at a major wall with this.
Any ideas what I could be doing wrong?

答: Try renaming your entity Page to something else, like EntityPage (for example) to see if this resolved it. As stated by @Yakimych this could simply be a case of Namespace clashing

Title: EntitySet could not be found

Body:
I'm working on an MVC site using EF4 as my data source. I've had no problems with other projects with EF4 until today. I'm getting an error stating EntitySet name Entities.Sites could not be found. I have another EDMX file for another dataset that is set up nearly the same (with different entity names) and it works fine when I try to run a LINQ query against it.

My EDMX has 2 tables (site and page) with a 1 to many association from the site to page table. Everything compiles fine, but in runtime, it's almost like the datamodel fails on every property list population. I do have Lazy Loading enabled (It's a .NET 4 project).

I stepped through the code on the designer class and it fails when it gets to a call like this

if((_Pages == null))
{
     _Pages = base.CreateObjectSet<Page>("Pages");
}

I have not altered the code in the designer.cs. I'm at a major wall with this.
Any ideas what I could be doing wrong?


问:
Where should I position this onClick logic for a ReactJS component?
I have a component that is a button that opens a dialog.

```<code>const myComponent = () => <div><button>click me</button></div>
</code>```

When the button is pressed I want the dialog to open.

Where should I position the onClick functionality (that will dispatch an action against the store to show the dialog)?

Should I use mapStateToProps to create a function on the props that will open the dialog, or is this overkill for such a small component?

答:
It's depend on many aspects of your design:

Is it a common button component? Do you reuse your button some where else?

Then you should pass the onClick event and the caption of the button from props.

Is it a button that only dispatch a function to open the dialog? Is it used to open the dialog only?

Then you can handle that inside the component.

If it's used to dispatch an action to a store, then use mapDispatchToProps to map to the action to props.

In my opinions, no need to use store here unless you have that dialog accessible somewhere else.

Body:
I have a component that is a button that opens a dialog.

const myComponent = () =>
<button>click me</button>

When the button is pressed I want the dialog to open.

Where should I position the onClick functionality (that will dispatch an action against the store to show the dialog)?

Should I use mapStateToProps to create a function on the props that will open the dialog, or is this overkill for such a small component?


问:
How to draw a border at top of the linear layout
I have followed the example in for the gradient dividers:
http://www.connorgarvey.com/blog/?p=34

I have tried to draw a horizontal line at the BOTTOM of my linear layout.

Here is my linear layout file:

```<code>        <LinearLayout android:id="@+id/test" android:layout_width="fill_parent"
            android:layout_height="wrap_content>

<ImageView android:id="@+id/icon1"
    android:layout_width="32dip"
    android:layout_height="32dip"
/>
</code>```

And I did add

```<code><View
android:background="@drawable/black_white_gradient"
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_above="@id/test"
/>
</code>```

But i don't see any line at the top of the LinearLayout. And when I go to Hierarchy View and see he View (for the hort separator), the getWidth() is 0 while getHeight() is 1.

Can you please tell me what am I missing?

Thank you.

答:
It will not be visible if the height is 1dp. Try 2dp instead:

<View
android:background="@drawable/black_white_gradient"
android:layout_width="fill_parent"
android:layout_height="2dp"
android:layout_above="@id/test"
/>

Body:
I have followed the example in for the gradient dividers:
http://www.connorgarvey.com/blog/?p=34

I have tried to draw a horizontal line at the BOTTOM of my linear layout.

Here is my linear layout file:

        <LinearLayout android:id="@+id/test" android:layout_width="fill_parent"
            android:layout_height="wrap_content>

<ImageView android:id="@+id/icon1"
    android:layout_width="32dip"
    android:layout_height="32dip"
/>

And I did add

<View
android:background="@drawable/black_white_gradient"
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_above="@id/test"
/>

But i don't see any line at the top of the LinearLayout. And when I go to Hierarchy View and see he View (for the hort separator), the getWidth() is 0 while getHeight() is 1.

Can you please tell me what am I missing?

Thank you.


问:
Create a table as combinations of ranges sqlite3
I am attempting to create a table that has combinations of 3 ranges.

Range 1 and Range 2 are equal.

Range 3 is different and a different length.

For any given row the value in Column 1 cannot be equal to the value in Column 2.

e.g. for Range 1: [1-2], Range 2: [1-2], Range 3: [5-7]

the expected result would be:

```<code>col1 | col2 | col3 |
1    | 2    | 5    |
1    | 2    | 6    |
1    | 2    | 7    |
2    | 1    | 5    |
2    | 1    | 6    |
2    | 1    | 7    |
</code>```

I'm using the python sqlite3 package so I can use ranges in python. Previously I have been constructing the table using a generator that iterates over the 3 nested ranges as follows:

```<code>def all_the_combos():
    for x in range(1,len(all_x)+1):
        for y in range(1,len(all_x)+1):
            if x == y:
                continue
            for z in range(min(all_z),max(all_z)+1):
            yield (x, y, z)

cur.execute('BEGIN TRANSACTION')
cur.executemany('INSERT into All_Combos (x, y, z) Values (?, ?, ?)', all_the_combos())
</code>```

However, this is slow for large ranges and I expect there is some clever way to use joins that would provide better performance. Any advice is appreciated.

答:
how about below. you need pandas module. if you don't have pandas execute "pip install pandas" before run this code.</p>

```<code>import sqlite3
import pandas as pd
from itertools import product

# your sample data
col1 = range(1,3)
col2 = range(1,3)
col3 = range(5,8)

# product -> dataframe -> sqlite3
con = sqlite3.connect("/path/to/sqlite3.db")
df = pd.DataFrame(
    row for row in product(col1, col2, col3)
        if not row[0]==row[1]
)
df.to_sql("output_table_name", con)
</code>```

Body:
I am attempting to create a table that has combinations of 3 ranges.

Range 1 and Range 2 are equal.

Range 3 is different and a different length.

For any given row the value in Column 1 cannot be equal to the value in Column 2.

e.g. for Range 1: [1-2], Range 2: [1-2], Range 3: [5-7]

the expected result would be:

col1 | col2 | col3 |
1    | 2    | 5    |
1    | 2    | 6    |
1    | 2    | 7    |
2    | 1    | 5    |
2    | 1    | 6    |
2    | 1    | 7    |

I'm using the python sqlite3 package so I can use ranges in python. Previously I have been constructing the table using a generator that iterates over the 3 nested ranges as follows:

def all_the_combos():
    for x in range(1,len(all_x)+1):
        for y in range(1,len(all_x)+1):
            if x == y:
                continue
            for z in range(min(all_z),max(all_z)+1):
            yield (x, y, z)

cur.execute('BEGIN TRANSACTION')
cur.executemany('INSERT into All_Combos (x, y, z) Values (?, ?, ?)', all_the_combos())

However, this is slow for large ranges and I expect there is some clever way to use joins that would provide better performance. Any advice is appreciated.

Body:
how about below. you need pandas module. if you don't have pandas execute "pip install pandas" before run this code.

import sqlite3
import pandas as pd
from itertools import product

# your sample data
col1 = range(1,3)
col2 = range(1,3)
col3 = range(5,8)

# product -> dataframe -> sqlite3
con = sqlite3.connect("/path/to/sqlite3.db")
df = pd.DataFrame(
    row for row in product(col1, col2, col3)
        if not row[0]==row[1]
)
df.to_sql("output_table_name", con)


问:
Changing the number of columns dynamically in SQL MS Access 2007
I am SQL beginner and woriking on MS Access 2007 I am trying to add multiple columns together but the number of columns to be included in query are going to change always. For example I have to calculate the Year to date budget, every time user will execute the query, a new date will be entered and I have Month1, Month2, Month3...Month 12 columns. I am confused on how can I decide on run time that how many columns I am going to include in the query.
If user enters 8/31/2017 I have to pick Month1, Month2, Month3, Month4, Month5 (They are Fiscal year-months)

.

答:
That's a horrible idea!!  Store your dates like this.

QryYTD:
Code:

```<code>SELECT
    Sum(qryNet.Net) AS YTD
FROM
   qryNet
WHERE
   (((qryNet.OrderDate) Between DateSerial(Year(Date()),1,1) AND   Date()))
</code>```

QryMTD:
Code:

```<code>SELECT
    Sum(qryNet.Net) AS MTD
FROM
   qryNet
WHERE
   (((qryNet.OrderDate) Between DateSerial(Year(Date()),Month(Date()),1)
AND
   Date()));
</code>```

QryWTD:
Code:

```<code>SELECT
    Sum(qryNet.Net) AS WTD
FROM
   qryNet
WHERE
   (((qryNet.OrderDate) Between DateAdd("d",-Weekday(Date()),Date()+2)
AND
   Date()));
</code>```

As written, qryWTD uses the current Monday as the starting date.

Once you have the three working, you could create a wrapper query by adding each of the previous queries and specifying YTD, MTD and WTD as the query's fields.

Body:
That's a horrible idea!!  Store your dates like this.

QryYTD:
Code:

SELECT
    Sum(qryNet.Net) AS YTD
FROM
   qryNet
WHERE
   (((qryNet.OrderDate) Between DateSerial(Year(Date()),1,1) AND   Date()))

QryMTD:
Code:

SELECT
    Sum(qryNet.Net) AS MTD
FROM
   qryNet
WHERE
   (((qryNet.OrderDate) Between DateSerial(Year(Date()),Month(Date()),1)
AND
   Date()));

QryWTD:
Code:

SELECT
    Sum(qryNet.Net) AS WTD
FROM
   qryNet
WHERE
   (((qryNet.OrderDate) Between DateAdd("d",-Weekday(Date()),Date()+2)
AND
   Date()));

As written, qryWTD uses the current Monday as the starting date.

Once you have the three working, you could create a wrapper query by adding each of the previous queries and specifying YTD, MTD and WTD as the query's fields.


问:
pass string from activity to fragment
My problem is passing string from activity to fragment. I researched for a whole day and my problem isn't solved.

activity :

```<code>if(email.matches(users.user1)&&password.matches(users.pass1)){

        Intent intent = new Intent(LoginActivity.this,MainActivity.class);

        Bundle bundle = new Bundle();
        bundle.putString("user", users.name);
        ProfileFragment fragobj = new ProfileFragment();
        fragobj.setArguments(bundle);

        startActivity(intent);

    }
</code>```

fragment :

```<code>public class ProfileFragment extends Fragment {

public static ProfileFragment newInstance() {
    return new ProfileFragment();

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_profile, container, false);

    String user = getArguments().getString("user");
    TextView textView = v.findViewById(R.id.namef1);
    textView.setText(user);

    return inflater.inflate(R.layout.fragment_profile, container, false);

}

}
</code>```

MainActivity

```<code>public class MainActivity extends Activity {

private BottomNavigationView mBottomNavigationView;

private Toolbar supportActionBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setupBottomNavigation();

    if (savedInstanceState == null) {

        loadHomeFragment();
    }

}

private void setupBottomNavigation() {

    mBottomNavigationView =findViewById(R.id.bottom_navigation);

    mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            switch (item.getItemId()) {
                case R.id.action_home:
                    loadHomeFragment();
                    return true;
                case R.id.action_profile:
                    loadProfileFragment();
                    return true;
                case R.id.action_settings:
                    loadSettingsFragment();
                    return true;
            }
            return false;
        }
    });
}

private void loadHomeFragment() {

    HomeFragment fragment = HomeFragment.newInstance();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_frame, fragment);
    ft.commit();
}

private void loadProfileFragment() {

    ProfileFragment fragment = ProfileFragment.newInstance();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_frame, fragment);
    ft.commit();
}

private void loadSettingsFragment() {

    SettingsFragment fragment = SettingsFragment.newInstance();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_frame, fragment);
    ft.commit();
}

public void setSupportActionBar(Toolbar supportActionBar) {
    this.supportActionBar=supportActionBar;
}
}
</code>```

as it shown in code user has login and one of his data display in a profile fragment . I wanna display this string as Textview in profilefragment .
anybody have an idea?

答:
Move below part of code to the place where you are adding the ProfileFragment to Activity.</p>

```<code>Bundle bundle = new Bundle();
    bundle.putString("user", users.name);
    ProfileFragment fragobj = new ProfileFragment();
    fragobj.setArguments(bundle);
</code>```

Title: pass string from activity to fragment

Body:
My problem is passing string from activity to fragment. I researched for a whole day and my problem isn't solved.

activity :

if(email.matches(users.user1)&&password.matches(users.pass1)){

        Intent intent = new Intent(LoginActivity.this,MainActivity.class);

        Bundle bundle = new Bundle();
        bundle.putString("user", users.name);
        ProfileFragment fragobj = new ProfileFragment();
        fragobj.setArguments(bundle);

        startActivity(intent);

    }

fragment :

public class ProfileFragment extends Fragment {

public static ProfileFragment newInstance() {
    return new ProfileFragment();

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_profile, container, false);

    String user = getArguments().getString("user");
    TextView textView = v.findViewById(R.id.namef1);
    textView.setText(user);

    return inflater.inflate(R.layout.fragment_profile, container, false);

}

}

MainActivity

public class MainActivity extends Activity {

private BottomNavigationView mBottomNavigationView;

private Toolbar supportActionBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setupBottomNavigation();

    if (savedInstanceState == null) {

        loadHomeFragment();
    }

}

private void setupBottomNavigation() {

    mBottomNavigationView =findViewById(R.id.bottom_navigation);

    mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            switch (item.getItemId()) {
                case R.id.action_home:
                    loadHomeFragment();
                    return true;
                case R.id.action_profile:
                    loadProfileFragment();
                    return true;
                case R.id.action_settings:
                    loadSettingsFragment();
                    return true;
            }
            return false;
        }
    });
}

private void loadHomeFragment() {

    HomeFragment fragment = HomeFragment.newInstance();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_frame, fragment);
    ft.commit();
}

private void loadProfileFragment() {

    ProfileFragment fragment = ProfileFragment.newInstance();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_frame, fragment);
    ft.commit();
}

private void loadSettingsFragment() {

    SettingsFragment fragment = SettingsFragment.newInstance();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_frame, fragment);
    ft.commit();
}

public void setSupportActionBar(Toolbar supportActionBar) {
    this.supportActionBar=supportActionBar;
}
}

as it shown in code user has login and one of his data display in a profile fragment . I wanna display this string as Textview in profilefragment .
anybody have an idea?

Body:
Move below part of code to the place where you are adding the ProfileFragment to Activity.

Bundle bundle = new Bundle();
    bundle.putString("user", users.name);
    ProfileFragment fragobj = new ProfileFragment();
    fragobj.setArguments(bundle);


问:
How to install OpenCV for python
HI! I'm trying to install opencv and use it with python, but when I compile it I get no errors but I can't import cv module from python:

```<code>patrick:release patrick$ python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named cv
</code>```

The code I used to compile it is this:

```<code>cd opencv
mkdir release
cd release
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_PYTHON_SUPPORT=ON
make
sudo make install
</code>```

how can I get it working with python?

答:
This worked for me (change python36 to whatever version you want)

sudo port install opencv +avx2 +python36 +qt5 +contrib +eigen

I got this error and had to apply the patch there (download link)

Apply the patch with:

```<code>sudo patch /opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_graphics_opencv/opencv/work/opencv-3.2.0/modules/highgui/src/window_QT.cpp ~/Downloads/patch-cpp11-narrowing-error.diff
</code>```

Then run sudo port install -N opencv +avx2 +python36 +qt5 +contrib +eigen again

Title: How to install OpenCV for python

Body:
HI! I'm trying to install opencv and use it with python, but when I compile it I get no errors but I can't import cv module from python:

patrick:release patrick$ python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named cv

The code I used to compile it is this:

cd opencv
mkdir release
cd release
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_PYTHON_SUPPORT=ON
make
sudo make install

how can I get it working with python?

Body:
This worked for me (change python36 to whatever version you want)

sudo port install opencv +avx2 +python36 +qt5 +contrib +eigen

I got this error and had to apply the patch there (download link)

Apply the patch with:

sudo patch /opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_graphics_opencv/opencv/work/opencv-3.2.0/modules/highgui/src/window_QT.cpp ~/Downloads/patch-cpp11-narrowing-error.diff

Then run sudo port install -N opencv +avx2 +python36 +qt5 +contrib +eigen again


问:
Bootstrap - Input not respecting Grid size/Restraints
I haven't been able to find any answers to my question elsewhere, nor previous posts here.

I am working on a website for internal purposes for work, and just playing trying to get things working at home. I am not sure if I am doing something wrong or if there is a bug, or maybe I should be using another JS UI.

What I need for a UI, is tabs, a grid system and form input. Bootstrap seems to be the best option I have found so far. I had settled on 4.0.0.beta2 since it is the most recent. Everything works except the Input elements, text, number and so on. When I put these in a grid system with bootstrap the input elements do not respect the grid sizing. All other form elements do.

Here is my current testing page without all the extra clutter. The input type flows outside of the grid to the right. I have tried form-groups, moving stuff around, different sizes, input types, pretty much anything I can think of. (Edit - changed detail-row to just row as it should have been, still did not fix the issue)

```<code><!DOCTYPE html>

    <html lang=en>
    <head>
      <!-- Standard Meta -->
  <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Site Properties -->
    <link rel="stylesheet" href="css/bootstrap.4.0.0.beta2.min.css">

<title> -- </title>
</head>

<body>
<div id="viewport" class="container">

<div class="row">
<div class="col-sm-2">Type</div>
<div class="col-sm-2">Vendor</div>
<div class="col-sm-3">Item</div>
<div class="col-sm-3">Note</div>
<div class="col-sm-1">Min Stock</div>
<div class="col-sm-1">To Order</div>
</div>

<div class="row">
  <div class="col-sm-2">Animal</div>
  <div class="col-sm-2">Bear</div>
  <div class="col-sm-3">Black</div>
  <div class="col-sm-3">Midnight</div>
  <div class="col-sm-1">0</div>
  <div class="col-sm-1">
    <input class="input-sm" id="item-87">
  </div>
  </div>
</div>

<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/bootstrap.bundle.4.0.0.beta2.min.js"></script>
</body>
</html>
</code>```

Side note:
If I encapsulate the input type in a Col / Row / Col, outside of the main with a label it will constrain itself to the column width. But it then falls out of alignment with the other row's since they are different sizes.

答:
Add .form-control to your <input> so that Bootstrap can responsively adjust the width of the form element to be 100% of the column.

<input class="input-sm form-control" id="item-87">

Also,
 is missing its .row class; perhaps you meant to use:

Without specifying a new .row your columns after the first will be offset improperly.

Body:
I haven't been able to find any answers to my question elsewhere, nor previous posts here.

I am working on a website for internal purposes for work, and just playing trying to get things working at home. I am not sure if I am doing something wrong or if there is a bug, or maybe I should be using another JS UI.

What I need for a UI, is tabs, a grid system and form input. Bootstrap seems to be the best option I have found so far. I had settled on 4.0.0.beta2 since it is the most recent. Everything works except the Input elements, text, number and so on. When I put these in a grid system with bootstrap the input elements do not respect the grid sizing. All other form elements do.

Here is my current testing page without all the extra clutter. The input type flows outside of the grid to the right. I have tried form-groups, moving stuff around, different sizes, input types, pretty much anything I can think of. (Edit - changed detail-row to just row as it should have been, still did not fix the issue)

<!DOCTYPE html>

  <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="css/bootstrap.4.0.0.beta2.min.css">

<title> -- </title>

Type

Vendor

Item

Note

Min Stock

To Order

Animal

Bear

Black

Midnight

0

    <input class="input-sm" id="item-87">

Side note:
If I encapsulate the input type in a Col / Row / Col, outside of the main with a label it will constrain itself to the column width. But it then falls out of alignment with the other row's since they are different sizes.

Body:
Add .form-control to your <input> so that Bootstrap can responsively adjust the width of the form element to be 100% of the column.

<input class="input-sm form-control" id="item-87">

Also, <div class="detail-row"> is missing its .row class; perhaps you meant to use:

<div class="detail row">

Without specifying a new .row your columns after the first will be offset improperly.


问:
Search and replace a word in directory and its subdirectories
I need to find and replace a word in all the files across a directory and its subdirectories.

I used this line of code:

```<code>perl -pi -w -e 's/foo/bar/g;' *.*
</code>```

But it changes the words only in files in the current directory and doesn't affect the subdirectories.

How can I change the word on every directory and subdirectory?

答:
Try that:

```<code>find -type f | xargs -r -I {} perl -pi -w -e 's/foo/bar/g;' {}
</code>```

That should run recursively

In case your file name contains space:

```<code>find -type f -print0 | xargs -r0 -I {} perl -pi -w -e 's/foo/bar/g;' {}
</code>```

Body:
I need to find and replace a word in all the files across a directory and its subdirectories.

I used this line of code:

perl -pi -w -e 's/foo/bar/g;' *.*

But it changes the words only in files in the current directory and doesn't affect the subdirectories.

How can I change the word on every directory and subdirectory?

Body:
Try that:

find -type f | xargs -r -I {} perl -pi -w -e 's/foo/bar/g;' {}

That should run recursively

In case your file name contains space:

find -type f -print0 | xargs -r0 -I {} perl -pi -w -e 's/foo/bar/g;' {}