问:
Testing Django Views with an ImageField
I have the following Model and Form

```<code>class AdImage(models.Model):
    advertiser = models.ForeignKey(Advertiser)
    picture = models.ImageField('Ad picture',
                            upload_to='ad_pics/%Y-%m-%d/')

class AdImageForm(forms.ModelForm):

    class Meta:
        model = AdImage
        exclude = ['advertiser']

    helper = FormHelper()

    helper.layout = Layout(
        Div('picture'),
        FormActions(
            Submit('submit', "Sichern")
        )
    )
</code>```

This is presented via :

```<code>class CreateAdImage(LoginRequiredMixin, CreateView):

    form_class = AdImageForm
    template_name = 'advertis/adimage_form.html'

    def form_valid(self, form):

        slug = self.kwargs.get('slug', None)
        advertiser = Advertiser.objects.get(slug=slug)
        form.instance.advertiser=advertiser

        form.save()

        ret = render(self.request, 'modal_form_success.html',
                 {
                     'success_message': "Bild gespeicher fuer %s gespeichert" %
                                        (advertiser.user.get_full_name()),
                     'reload' : True,
                 })

        return ret
</code>```

This works pretty well. I can Test the Form with

```<code>class AdImageFormTestCase(TestCase):

    def setUp(self):

        self.creator = ShrUser.objects.create_user(username="foo",
                         email="hallo.ich@localhost.de", password="bla")
        self.advertiser = Advertiser.objects.create(user=self.creator,
                             city='Chicago')

        self.uploaded_image = get_temporary_image()

        self.form_data = {}
        self.file_dict = {
            'picture': self.uploaded_image,
        }

    def test_AdImageCreate(self):

        form = AdImageForm(self.form_data, self.file_dict)
        self.assertTrue(form.is_valid())
</code>```

Where self.uploaded_image is

```<code>def get_temporary_image():
    io = BytesIO()
    size = (200,200)
    color = (255,0,0,0)
    image = Image.new("RGBA", size, color)
    image.save(io, format='JPEG')
    image_file = InMemoryUploadedFile(io, None, 'foo.jpg', 'jpeg',
                     image.size, None)
    image_file.seek(0)
    return image_file
</code>```

But I cant get the view Test to run. I allways run into field required with :

```<code>    def test_create_adimage(self):

        advertiser = Advertiser.objects.create(user=self.user)

        response = self.client.get(reverse('create_adimage', kwargs={'slug' : advertiser.slug,}))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'advertis/adimage_form.html')

        self.uploaded_image = get_temporary_image()

        post_data = {
        }

        file_dict = {
            'picture': self.uploaded_image,
        }

        response = self.client.post(reverse('create_adimage', kwargs={'slug': advertiser.slug,}),
                                post_data=post_data, file_dict=file_dict)

        self.assertEqual(response.status_code, 200)
</code>```

Does anybode know how to set post_data and file_dict in order to have a valid form ?

Kind regards

Michael

答:
Regarding to AKS comment the following works perfect</p>

```<code>response = self.client.post(reverse('create_adimage', kwargs={'slug': advertiser.slug,}),
                                post_data=post_data, data=file_dict)

self.assertEqual(response.status_code, 200)
self.assertContains(response, 'Bild fuer %s gespeichert' % (advertiser.user.get_full_name()))
</code>```

Title: Testing Django Views with an ImageField

Body:
I have the following Model and Form

class AdImage(models.Model):
    advertiser = models.ForeignKey(Advertiser)
    picture = models.ImageField('Ad picture',
                            upload_to='ad_pics/%Y-%m-%d/')

class AdImageForm(forms.ModelForm):

    class Meta:
        model = AdImage
        exclude = ['advertiser']

    helper = FormHelper()

    helper.layout = Layout(
        Div('picture'),
        FormActions(
            Submit('submit', "Sichern")
        )
    )

This is presented via :

class CreateAdImage(LoginRequiredMixin, CreateView):

    form_class = AdImageForm
    template_name = 'advertis/adimage_form.html'

    def form_valid(self, form):

        slug = self.kwargs.get('slug', None)
        advertiser = Advertiser.objects.get(slug=slug)
        form.instance.advertiser=advertiser

        form.save()

        ret = render(self.request, 'modal_form_success.html',
                 {
                     'success_message': "Bild gespeicher fuer %s gespeichert" %
                                        (advertiser.user.get_full_name()),
                     'reload' : True,
                 })

        return ret

This works pretty well. I can Test the Form with

class AdImageFormTestCase(TestCase):

    def setUp(self):

        self.creator = ShrUser.objects.create_user(username="foo",
                         email="hallo.ich@localhost.de", password="bla")
        self.advertiser = Advertiser.objects.create(user=self.creator,
                             city='Chicago')

        self.uploaded_image = get_temporary_image()

        self.form_data = {}
        self.file_dict = {
            'picture': self.uploaded_image,
        }

    def test_AdImageCreate(self):

        form = AdImageForm(self.form_data, self.file_dict)
        self.assertTrue(form.is_valid())

Where self.uploaded_image is

def get_temporary_image():
    io = BytesIO()
    size = (200,200)
    color = (255,0,0,0)
    image = Image.new("RGBA", size, color)
    image.save(io, format='JPEG')
    image_file = InMemoryUploadedFile(io, None, 'foo.jpg', 'jpeg',
                     image.size, None)
    image_file.seek(0)
    return image_file

But I cant get the view Test to run. I allways run into field required with :

    def test_create_adimage(self):

        advertiser = Advertiser.objects.create(user=self.user)

        response = self.client.get(reverse('create_adimage', kwargs={'slug' : advertiser.slug,}))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'advertis/adimage_form.html')

        self.uploaded_image = get_temporary_image()

        post_data = {
        }

        file_dict = {
            'picture': self.uploaded_image,
        }

        response = self.client.post(reverse('create_adimage', kwargs={'slug': advertiser.slug,}),
                                post_data=post_data, file_dict=file_dict)

        self.assertEqual(response.status_code, 200)

Does anybode know how to set post_data and file_dict in order to have a valid form ?

Kind regards

Michael

Body:
Regarding to AKS comment the following works perfect

response = self.client.post(reverse('create_adimage', kwargs={'slug': advertiser.slug,}),
                                post_data=post_data, data=file_dict)

self.assertEqual(response.status_code, 200)
self.assertContains(response, 'Bild fuer %s gespeichert' % (advertiser.user.get_full_name()))


来源: stackexchange

问:
Notepad++ autocomplete text file adjustments?
I would like to have the Notepad++ autocomplete feature

ignore dashes

include apostrophes

when working on plain text files. I cannot find a plain text XML definition file in the autocomplete directory: C:\Program Files (x86)\Notepad++\plugins\APIs\

Is there any way to change the standard search functionality for plain text files in Notepad++?

答: I don't know if you can change the search functionnality, but you can create a normal.xml file under C:\Program Files (x86)\Notepad++\plugins\APIs\ directory to change the autocomplete feature for normal text files

ContentLicense: CC BY-SA 3.0


问:
AngularJS $resource - POST with id param
I have an angularJS $resource:

```<code>$resource("http://localhost:3000/:id",{
   id: '@id'
},
{
   get: {
      method:'GET',
      isArray: false
   },
   foo: {
      method:'POST',
      url: 'http://localhost:3000/:id/foo',
      isArray: false
   }
});
</code>```

Now if I call:

```<code>User.foo({id:'123', anotherParam: 'bar'});
</code>```

This results in the URL 'http://localhost:3000/foo' being called and passing the id and anotherParam parameters as POST fields.

I actually want it to call 'http://localhost:3000/123/foo' and only pass the anotherParam parameter as a POST field.

How do I get the id parameter to behave correctly?

答:
The accepted solution didn't work for me (AngularJS v1.4.8).
Have to manually set content type and transform to form data.

Sample:

```<code>var DirectoryApi = $resource('api/directories', null, {
    move: {
        url: 'api/directories/:name/_move',
        params: {"name" : "@name"},
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
        transformRequest: function (param) {
            return $.param(param);
        },
        method: 'POST'
    },
});
</code>```

And usage:

```<code>function moveDirectory(name, parent, after) {
    return DirectoryApi.move({name: name}, {parent: parent, after: after});
}
</code>```

Body:
I have an angularJS $resource:

$resource("http://localhost:3000/:id",{
   id: '@id'
},
{
   get: {
      method:'GET',
      isArray: false
   },
   foo: {
      method:'POST',
      url: 'http://localhost:3000/:id/foo',
      isArray: false
   }
});

Now if I call:

User.foo({id:'123', anotherParam: 'bar'});

This results in the URL 'http://localhost:3000/foo' being called and passing the id and anotherParam parameters as POST fields.

I actually want it to call 'http://localhost:3000/123/foo' and only pass the anotherParam parameter as a POST field.

How do I get the id parameter to behave correctly?

Body:
The accepted solution didn't work for me (AngularJS v1.4.8).
Have to manually set content type and transform to form data.

Sample:

var DirectoryApi = $resource('api/directories', null, {
    move: {
        url: 'api/directories/:name/_move',
        params: {"name" : "@name"},
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
        transformRequest: function (param) {
            return $.param(param);
        },
        method: 'POST'
    },
});

And usage:

function moveDirectory(name, parent, after) {
    return DirectoryApi.move({name: name}, {parent: parent, after: after});
}


问:
pg_send_query(): Cannot set connection to blocking mode?
I have a long-running script that seems to occasionally report the following NOTICE-level error:
    pg_send_query(): Cannot set connection to blocking mode

It seems to continue to send queries afterward, but it's unclear if it successfully sends the query that generates the error.

What is this a symptom of?

Edit: There are no entries in the postgres log at the time the error occurred, suggesting this is solely a connection error, not something going wrong on postgres' side (e.g. probably not the result of postgres crashing and restarting or something)

Edit: As far as I can tell, my INSERT statements are succeeding, one way or another, when this error is triggered.

Edit: Looks like this may have been fixed in June 2013: https://bugs.php.net/bug.php?id=65015

答: I got that error too. I solve my problem by restarting the web server (Apache).</p>


问:
Renumbering a set of rows
I have a table with data which looks something like the following:

```<code># the columns #
url
title
group
id_within_group

http://www.google.com
google
search engine
1

http://www.yahoo.com
yahoo
search engine
2

http://www.bing.com
bing
search engine
3

http://www.facebook.com
facebook
social media
1

http://www.twitter.com
twitter
social media
2
</code>```

if I do

```<code>select * from table1 where group = "search engine"
</code>```

I will get

```<code>http://www.google.com
google
search engine
1

http://www.yahoo.com
yahoo
search engine
2

http://www.bing.com
bing
search engine
3
</code>```

I would like to be able to delete any of these rows, but somehow get it to renumber the id_within_group.

SO if I delete the second one from the 3 above, it should automatically renumber then leaving me with

```<code>http://www.google.com
google
search engine
1

http://www.bing.com
bing
search engine
2
</code>```

Is this possible?

答:
My suggestion would be to do this in the SELECT if you just need to display a sequential integer.

```<code>SELECT   url             ,
         title           ,
         [group]         ,
         id_within_group ,
         ROW_NUMBER() over (partition BY [group] ORDER BY id_within_group) AS sequential_index
FROM     YourTable
</code>```

ContentLicense: CC BY-SA 2.5

Title: Renumbering a set of rows

Body:
I have a table with data which looks something like the following:

# the columns #
url
title
group
id_within_group

http://www.google.com
google
search engine
1

http://www.yahoo.com
yahoo
search engine
2

http://www.bing.com
bing
search engine
3

http://www.facebook.com
facebook
social media
1

http://www.twitter.com
twitter
social media
2

if I do

select * from table1 where group = "search engine"

I will get

http://www.google.com
google
search engine
1

http://www.yahoo.com
yahoo
search engine
2

http://www.bing.com
bing
search engine
3

I would like to be able to delete any of these rows, but somehow get it to renumber the id_within_group.

SO if I delete the second one from the 3 above, it should automatically renumber then leaving me with

http://www.google.com
google
search engine
1

http://www.bing.com
bing
search engine
2

Is this possible?

Body:
My suggestion would be to do this in the SELECT if you just need to display a sequential integer.

SELECT   url             ,
         title           ,
         [group]         ,
         id_within_group ,
         ROW_NUMBER() over (partition BY [group] ORDER BY id_within_group) AS sequential_index
FROM     YourTable


问:
jQuery ID Return is undefined although HTML ID is defined
I'm trying to retrieve the ID of one element, store it as a variable and then use that ID value to interact with other elements in that section with the same ID.

```<code><div class="mainContent">
<div class="articleContent">
     <h1>header1</h1>
     <p class="articlePara" id="one">para1</p>
</div>
<div class="articleFooter" id="one" onclick="readMore()">
</div>
</div>

<div class="mainContent">
<div class="articleContent">
     <h1>header2</h1>
     <p class="articlePara" id="two">para2</p>
</div>
<div class="articleFooter" id="two" onclick="readMore()">
</div>
</div>
</code>```

And then the JS/jQuery

```<code>function readMore() {
var subID = event.target.id;

var newTarget = document.getElementById(subID).getElementsByClassName("articlePara");

alert(newTarget.id);
}
</code>```

At this point I'm only trying to display the ID of the selected element but it is returning undefined and in most cases people seem to notice that jQuery is getting confused because of the differences between DOM variables and jQuery ones.

jsfiddle: https://jsfiddle.net/dr0f2nu3/

To be completely clear, I want to be able to click on one element, retrieve the ID and then select an element in the family of that clicked element using that ID value.

答:
You have forgotten to pass in event as parameter in your onclick= call in html.

In your javascript, you need to include event in the parenthesis as well.

```<code>window.readMore = function(event) {...}
</code>```

if you write document.getElementById(subID).getElementsByClassName("articlePara"); That's saying you want to get your clicked element's CHILD elements that have class equal to articlePara . There is none. So you get undefined.

If you want to find all element with a ID one and a class articlePara, it can be done easily with jQuery:

```<code>newtarget = $("#one.articlePara");
</code>```

You can insert a line: debugger; in your onclick handler function to trigger the browser's debugging tool and inspect the values of variables. Then you will know whether you are getting what you want.

Body:
I'm trying to retrieve the ID of one element, store it as a variable and then use that ID value to interact with other elements in that section with the same ID.

header1

para1

header2

para2

And then the JS/jQuery

function readMore() {
var subID = event.target.id;

var newTarget = document.getElementById(subID).getElementsByClassName("articlePara");

alert(newTarget.id);
}

At this point I'm only trying to display the ID of the selected element but it is returning undefined and in most cases people seem to notice that jQuery is getting confused because of the differences between DOM variables and jQuery ones.

jsfiddle: https://jsfiddle.net/dr0f2nu3/

To be completely clear, I want to be able to click on one element, retrieve the ID and then select an element in the family of that clicked element using that ID value.

Body:
You have forgotten to pass in event as parameter in your onclick= call in html.

In your javascript, you need to include event in the parenthesis as well.

window.readMore = function(event) {...}

if you write document.getElementById(subID).getElementsByClassName("articlePara"); That's saying you want to get your clicked element's CHILD elements that have class equal to articlePara . There is none. So you get undefined.

If you want to find all element with a ID one and a class articlePara, it can be done easily with jQuery:

newtarget = $("#one.articlePara");

You can insert a line: debugger; in your onclick handler function to trigger the browser's debugging tool and inspect the values of variables. Then you will know whether you are getting what you want.


问:
razor - how to dynamicaly insert id into div element
In my view I have:

```<code>@foreach (var comment in Model.commentList)
{
    var id = comment.CommentId;
    <div id="@(id)" style="height:100px; width: 100px; background-color: red; display:none;"></div>
    <a id=@id onClick="ShowForm(this.id)" href="#">Comment</a>
}
</code>```

And then I have a script:

```<code>function ShowForm(clicked_id) {
    var element = "#" + clicked_id;
    $(element).fadeIn(1000);
}
</code>```

What I want to achieve is to show a certain element after clicking a link but it is not working. Where is my mistake?

答:
The problem is you're setting two elements with the same id

Try changing your cshtml like this

```<code>@foreach (var comment in Model.commentList)
{
    var id = comment.CommentId;
    <div id="@id" style="height:100px; width: 100px; background-color: red; display:none;"></div>
    <a onClick="ShowForm(@id)" href="#">Comment</a>
}
</code>```

Body:
In my view I have:

@foreach (var comment in Model.commentList)
{
    var id = comment.CommentId;

    Comment
}

And then I have a script:

function ShowForm(clicked_id) {
    var element = "#" + clicked_id;
    $(element).fadeIn(1000);
}

What I want to achieve is to show a certain element after clicking a link but it is not working. Where is my mistake?

Body:
The problem is you're setting two elements with the same id

Try changing your cshtml like this

@foreach (var comment in Model.commentList)
{
    var id = comment.CommentId;
    <div id="@id" style="height:100px; width: 100px; background-color: red; display:none;"></div>
    <a onClick="ShowForm(@id)" href="#">Comment</a>
}


问:
In-Memory Table on SQL 2014 HA cluster not queriable on Secondary nodes
I've set up a simple in-memory table on a high-availability group database on SQL 2014.
Querying the table from the primary node directly or from the Listener works fine.
If I change the query string to ReadOnly Intent or try to query directly from either of the 2 secondary nodes I get the following error: -

Msg 41341, Level 16, State 1, Line 1
Table 'tbl_GetMakes' is not yet available on the secondary replica.

There is very little information on this message online.  It talks about it being replicated properly when the "REDO" process takes place.  As far as I read it, the "REDO" process should be automatic, the table has been in place now for just over 24 hours and still isn't working.
Any ideas anyone?
Thanks,
Jon

答:
Thanks to Sean Gallardy who answered this over on the Microsoft Forum

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/a6cbeb89-bc99-491c-8c2f-9937d5ddfa6a/inmemory-table-on-sql-2014-ha-cluster-not-queriable-on-secondary-nodes?forum=sqldisasterrecovery

I've reproduced the answer from the above link below: -

That's not correct, they can absolutely be read from a readable secondary, assuming:
The in memory table was made with Durability = schema_and_data
A checkpoint has run on the primary
The proper isolation level is used
I can easily get this to work, here is a repro:
  1. Create Database on primary and put in AG

```<code>CREATE DATABASE [Test1]
 CONTAINMENT = NONE
 ON  PRIMARY
( NAME = N'Test1',
  FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\Test1.mdf' ,
  SIZE = 4096KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ),
  FILEGROUP [IMOLTP] CONTAINS MEMORY_OPTIMIZED_DATA  DEFAULT
  ( NAME = N'imoltp_dir',
  FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\imoltp_dir' ,
  MAXSIZE = UNLIMITED)
LOG ON
( NAME = N'Test1_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\Test1_log.ldf' , SIZE = 1280KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO
</code>```

Create the IM Table and populate

CREATE TABLE dbo.IMOLTP
     (
     C1 INT NOT NULL PRIMARY KEY NONCLUSTERED HASH WITH (BUCKET_COUNT = 1000)
     )
     WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_AND_DATA)

INSERT INTO dbo.IMOLTP(C1) VALUES (1), (2), (3)
     GO

CHECKPOINT

SELECT * FROM dbo.IMOLTP

Read from a READABLE secondary

Use Test1
     GO

SELECT * FROM dbo.IMOLTP
     GO

It works just fine for me on: Microsoft SQL Server 2014 (SP2-CU3) (KB3204388) - 12.0.5538.0 (X64)

-Sean

Body:
Thanks to Sean Gallardy who answered this over on the Microsoft Forum

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/a6cbeb89-bc99-491c-8c2f-9937d5ddfa6a/inmemory-table-on-sql-2014-ha-cluster-not-queriable-on-secondary-nodes?forum=sqldisasterrecovery

I've reproduced the answer from the above link below: -

That's not correct, they can absolutely be read from a readable secondary, assuming:
The in memory table was made with Durability = schema_and_data
A checkpoint has run on the primary
The proper isolation level is used
I can easily get this to work, here is a repro:
  1. Create Database on primary and put in AG

CREATE DATABASE [Test1]
 CONTAINMENT = NONE
 ON  PRIMARY
( NAME = N'Test1',
  FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\Test1.mdf' ,
  SIZE = 4096KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ),
  FILEGROUP [IMOLTP] CONTAINS MEMORY_OPTIMIZED_DATA  DEFAULT
  ( NAME = N'imoltp_dir',
  FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\imoltp_dir' ,
  MAXSIZE = UNLIMITED)
LOG ON
( NAME = N'Test1_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\Test1_log.ldf' , SIZE = 1280KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO

Create the IM Table and populate

CREATE TABLE dbo.IMOLTP
     (
     C1 INT NOT NULL PRIMARY KEY NONCLUSTERED HASH WITH (BUCKET_COUNT = 1000)
     )
     WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_AND_DATA)

INSERT INTO dbo.IMOLTP(C1) VALUES (1), (2), (3)
     GO

CHECKPOINT

SELECT * FROM dbo.IMOLTP

Read from a READABLE secondary

Use Test1
     GO

SELECT * FROM dbo.IMOLTP
     GO

It works just fine for me on: Microsoft SQL Server 2014 (SP2-CU3) (KB3204388) - 12.0.5538.0 (X64)

-Sean


问:
Get Alfresco NodeRef by path
I want to get the NodeRef of a document (or space) stored in Alfresco.

My code is in Java, running within Alfresco (for instance in an AMP).

How to do?

答:
The easiest way is probably using the NodeLocatorService and the XPath locatorName + an xpath expression

Under the hood, that uses the search service, but it wraps up a lot of the complexity for you!

To use it, get the NodeLocatorService injected into your bean, then do something like:

```<code> Map<String,Serializable> params = new HashMap<>();
 params.put("query", "/x:path/to:node/pa:th");
 NodeRef nodeRef = nodeLocatorService.getNode("xpath",null,params);
</code>```

Other NodeLocators exist for other lookups, and it's also available remotely via /alfresco/service/api/nodelocator/{node_locator_name}?params

ContentLicense: CC BY-SA 4.0

Title: Get Alfresco NodeRef by path

Body:
The easiest way is probably using the NodeLocatorService and the XPath locatorName + an xpath expression

Under the hood, that uses the search service, but it wraps up a lot of the complexity for you!

To use it, get the NodeLocatorService injected into your bean, then do something like:

 Map<String,Serializable> params = new HashMap<>();
 params.put("query", "/x:path/to:node/pa:th");
 NodeRef nodeRef = nodeLocatorService.getNode("xpath",null,params);

Other NodeLocators exist for other lookups, and it's also available remotely via /alfresco/service/api/nodelocator/{node_locator_name}?params


问:
Float random with value from "1.3000 to 1.4000" is possible?
Its possible to make float random from range 1.3000 to 1.4000? That give me numbers like 13405, 13855 etc.
I know double is more flexible with range floating point, but i cant use it.

So i create something like:

```<code>  float highmax = 0.6500f;
        float highlow = 0.7000f;
        float generatedFloatHigh = highmax + new Random().nextFloat() * (highlow - highmax);
</code>```

But this not work what i want.

Any suggestion? Or maybe i should look for other libraly?

答:
You can try to get a random number(for example x) between 0 and 1000, then you can get a number from range 1.3000 to 1.4000 like this : </p>

```<code>int x = new Random(1000).nextInt();
float result = 1.3000f + x*0.0001f;
</code>```

Body:
Its possible to make float random from range 1.3000 to 1.4000? That give me numbers like 13405, 13855 etc.
I know double is more flexible with range floating point, but i cant use it.

So i create something like:

  float highmax = 0.6500f;
        float highlow = 0.7000f;
        float generatedFloatHigh = highmax + new Random().nextFloat() * (highlow - highmax);

But this not work what i want.

Any suggestion? Or maybe i should look for other libraly?

Body:
You can try to get a random number(for example x) between 0 and 1000, then you can get a number from range 1.3000 to 1.4000 like this :

int x = new Random(1000).nextInt();
float result = 1.3000f + x*0.0001f;


问:
How to use ViewDataDictionary with Html.Partial in asp.net core?
My case looks like this:

Model:

```<code>public class Book
{
    public string Id { get; set; }

    public string Name { get; set; }
}

public class Comment
{
    public string Id { get; set; }

    public string BookId { get; set; }

    public string Content { get; set; }
}
</code>```

Controller:

```<code>public IActionResult Detail(string id)
{
    ViewData["DbContext"] = _context; // DbContext

    var model = ... // book model

    return View(model);
}
</code>```

View:

Detail view:

```<code>@if (Model?.Count > 0)
{
    var context = (ApplicationDbContext)ViewData["DbContext"];
    IEnumerable<Comment> comments = context.Comments.Where(x => x.BookId == Model.Id);

    @Html.Partial("_Comment", comments)
}
</code>```

Comment partial view:

```<code>@model IEnumerable<Comment>

@if (Model?.Count > 0)
{
    <!-- display comments here... -->
}

<-- How to get "BookId" here if Model is null? -->
</code>```

I've tried this:

```<code>@Html.Partial("_Comment", comments, new ViewDataDictionary { { "BookId", Model.Id } })
</code>```

Then

```<code>@{
    string bookid = ViewData["BookId"]?.ToString() ?? "";
}

@if (Model?.Count() > 0)
{
    <!-- display comments here... -->
}

<div id="@bookid">
    other implements...
</div>
</code>```

But error:

'ViewDataDictionary' does not contain a constructor that takes 0
  arguments

When I select ViewDataDictionary and press F12, it hits to:

```<code>namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
    public ViewDataDictionary(IModelMetadataProvider metadataProvider, ModelStateDictionary modelState);
}
</code>```

I don't know what are IModelMetadataProvider and ModelStateDictionary?

My goal: Send model comments from view Detail.cshtml to partial view _Comment.cshtml with a ViewDataDictionary which contains BookId.

My question: How can I do that?

答:
Another way to use this is to pass the ViewData of the current view into the constructor. That way the new ViewDataDictionary gets extended with the items you put in using the collection initializer.

```<code>@Html.Partial("MyPartial", new ViewDataDictionary(ViewData) { { "BookId", Model.Id } })
</code>```

Body:
My case looks like this:

Model:

public class Book
{
    public string Id { get; set; }

    public string Name { get; set; }
}

public class Comment
{
    public string Id { get; set; }

    public string BookId { get; set; }

    public string Content { get; set; }
}

Controller:

public IActionResult Detail(string id)
{
    ViewData["DbContext"] = _context; // DbContext

    var model = ... // book model

    return View(model);
}

View:

Detail view:

@if (Model?.Count > 0)
{
    var context = (ApplicationDbContext)ViewData["DbContext"];
    IEnumerable<Comment> comments = context.Comments.Where(x => x.BookId == Model.Id);

    @Html.Partial("_Comment", comments)
}

Comment partial view:

@model IEnumerable<Comment>

@if (Model?.Count > 0)
{

}

<-- How to get "BookId" here if Model is null? -->

I've tried this:

@Html.Partial("_Comment", comments, new ViewDataDictionary { { "BookId", Model.Id } })

Then

@{
    string bookid = ViewData["BookId"]?.ToString() ?? "";
}

@if (Model?.Count() > 0)
{

}

    other implements...

But error:

'ViewDataDictionary' does not contain a constructor that takes 0
  arguments

When I select ViewDataDictionary and press F12, it hits to:

namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
    public ViewDataDictionary(IModelMetadataProvider metadataProvider, ModelStateDictionary modelState);
}

I don't know what are IModelMetadataProvider and ModelStateDictionary?

My goal: Send model comments from view Detail.cshtml to partial view _Comment.cshtml with a ViewDataDictionary which contains BookId.

My question: How can I do that?

Body:
Another way to use this is to pass the ViewData of the current view into the constructor. That way the new ViewDataDictionary gets extended with the items you put in using the collection initializer.

@Html.Partial("MyPartial", new ViewDataDictionary(ViewData) { { "BookId", Model.Id } })


问:
How to create android button bar?
I need to create a horizontal list of buttons without a separating space like this one

each button will contain a text and an icon I know about buttonbarlayout but it didn't work for me, please can someone help me, Thanks in advance

答:
```<code>private LinearLayout tabLayout;

   FrameLayout tab1 = (FrameLayout) LayoutInflater.from(this).inflate(R.layout.tab_cell, null);
    tab1.findViewById(R.id.click_view).setOnClickListener(this);
    tab1.findViewById(R.id.click_view).setTag(First_TAB);
    textviewone = (TextView) tab1.findViewById(R.id.tab_header);
    textviewone.setWidth(SMALL_TAB_WIDTH);
    textviewone.setText("Rewards");
    textviewone.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.picture_s, 0, 0);
    tabLayout.addView(tab1);

    FrameLayout tab2 = (FrameLayout) LayoutInflater.from(this).inflate(R.layout.tab_cell,, null);
    tab2.findViewById(R.id.click_view).setOnClickListener(this);
    tab2.findViewById(R.id.click_view).setTag(Second_TAB);
    secondtab = (TextView) tab2.findViewById(R.id.tab_header);
    secondtab.setWidth(SMALL_TAB_WIDTH);
    secondtab.setText(R.string.roster);
    secondtab.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon_selector_s, 0, 0);
    tabLayout.addView(tab2);

    FrameLayout tab3 = (FrameLayout) LayoutInflater.from(this).inflate(R.layout.tab_cell, null);
    tab3.findViewById(R.id.click_view).setOnClickListener(this);
    tab3.findViewById(R.id.click_view).setTag(Third_TAB);
    thirdtab = (TextView) tab3.findViewById(R.id.tab_header);
    thirdtab.setWidth(SMALL_TAB_WIDTH);
    thridtab.setText(R.string.copy_entry);
    thridtab.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.select_activity_selector_s, 0, 0);
    tabLayout.addView(tab3);
</code>```

tab_cell.xml is below:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content">
    <TextView
        android:id="@+id/tab_header"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:layout_weight="1"
        android:gravity="center"
        android:maxLines="1"
        android:textSize="10.5sp"/>
    <RelativeLayout
        android:id="@+id/click_view"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_gravity="center"></RelativeLayout>
</FrameLayout>
</code>```

Below is the linear layout in the activity declared as tabLayout in the code:

```<code> <LinearLayout
                        android:id="@+id/tabs" android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal"
                        android:weightSum="10"></LinearLayout>
</code>```

Title: How to create android button bar?

Body:
private LinearLayout tabLayout;

   FrameLayout tab1 = (FrameLayout) LayoutInflater.from(this).inflate(R.layout.tab_cell, null);
    tab1.findViewById(R.id.click_view).setOnClickListener(this);
    tab1.findViewById(R.id.click_view).setTag(First_TAB);
    textviewone = (TextView) tab1.findViewById(R.id.tab_header);
    textviewone.setWidth(SMALL_TAB_WIDTH);
    textviewone.setText("Rewards");
    textviewone.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.picture_s, 0, 0);
    tabLayout.addView(tab1);

    FrameLayout tab2 = (FrameLayout) LayoutInflater.from(this).inflate(R.layout.tab_cell,, null);
    tab2.findViewById(R.id.click_view).setOnClickListener(this);
    tab2.findViewById(R.id.click_view).setTag(Second_TAB);
    secondtab = (TextView) tab2.findViewById(R.id.tab_header);
    secondtab.setWidth(SMALL_TAB_WIDTH);
    secondtab.setText(R.string.roster);
    secondtab.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon_selector_s, 0, 0);
    tabLayout.addView(tab2);

    FrameLayout tab3 = (FrameLayout) LayoutInflater.from(this).inflate(R.layout.tab_cell, null);
    tab3.findViewById(R.id.click_view).setOnClickListener(this);
    tab3.findViewById(R.id.click_view).setTag(Third_TAB);
    thirdtab = (TextView) tab3.findViewById(R.id.tab_header);
    thirdtab.setWidth(SMALL_TAB_WIDTH);
    thridtab.setText(R.string.copy_entry);
    thridtab.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.select_activity_selector_s, 0, 0);
    tabLayout.addView(tab3);

tab_cell.xml is below:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content">
    <TextView
        android:id="@+id/tab_header"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:layout_weight="1"
        android:gravity="center"
        android:maxLines="1"
        android:textSize="10.5sp"/>
    <RelativeLayout
        android:id="@+id/click_view"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_gravity="center"></RelativeLayout>
</FrameLayout>

Below is the linear layout in the activity declared as tabLayout in the code:

 <LinearLayout
                        android:id="@+id/tabs" android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal"
                        android:weightSum="10"></LinearLayout>


问:
How to Fill the data in google spreadsheet after creation of sheet?
I have a script that create's an empty google spreadsheet.
after creation of google spreadsheet. how i can add some data in it?

just some string is enough

script for creating the file :

```<code>function createSpread()
{

                var name =   $('[name=id]').val();
                gapi.client.load('drive', 'v2', function() {

                var request = gapi.client.request({
                   'path': '/drive/v2/files/',
                   'method': 'POST',
                   'headers': {
                       'Content-Type': 'application/json',
                   },
                   'body':{
                       "title" : name,
                       "mimeType" : "application/vnd.google-apps.spreadsheet",
                       "parents": [{
                            "kind": "drive#file",
                            "id": FOLDER_ID,
                        }],
                   }
                });
                request.execute(function(resp) { console.log(resp)

                });
            });
}
</code>```

Can you please help anyone

Thanks in advance

答:
You will need to use the Google Sheets API, which allows you to read and write to individual cells or cell ranges. See https://developers.google.com/sheets/api

Also, if this is a new application, you should probably start using v3 of the Drive API to save having to upgrade at some point.

Body:
I have a script that create's an empty google spreadsheet.
after creation of google spreadsheet. how i can add some data in it?

just some string is enough

script for creating the file :

function createSpread()
{

                var name =   $('[name=id]').val();
                gapi.client.load('drive', 'v2', function() {

                var request = gapi.client.request({
                   'path': '/drive/v2/files/',
                   'method': 'POST',
                   'headers': {
                       'Content-Type': 'application/json',
                   },
                   'body':{
                       "title" : name,
                       "mimeType" : "application/vnd.google-apps.spreadsheet",
                       "parents": [{
                            "kind": "drive#file",
                            "id": FOLDER_ID,
                        }],
                   }
                });
                request.execute(function(resp) { console.log(resp)

                });
            });
}

Can you please help anyone

Thanks in advance


问:
Almost identical recursive functions
I have a function called myFunction1 whose definition is the following:

```<code>function myFunction1()
{
    if condition1 then
        doSomething1();
        myFunction1();
    else if condition2 then
        doSomething2();
        myFunction1();
    else if condition3 then
        doSomething3();
        myFunction1();
    else throw Exception;
}
</code>```

Now I want to write a second function myFunction2 which is almost identical to myFunction1 except for a single case, i.e.,

```<code>function myFunction2()
{
    if condition1 then
        doSomething4();
        myFunction2();
    else if condition2 then
        doSomething2();
        myFunction2();
    else if condition3 then
        doSomething3();
        myFunction2();
    else throw Exception;
}
</code>```

Note that it is only the first if which differs from myFuction1. How could I write myFuction2 so as to avoid duplicating code?

答: If it is easy to read and maintenance, have some duplicates is good!</p>

Title: Almost identical recursive functions

Body:
I have a function called myFunction1 whose definition is the following:

function myFunction1()
{
    if condition1 then
        doSomething1();
        myFunction1();
    else if condition2 then
        doSomething2();
        myFunction1();
    else if condition3 then
        doSomething3();
        myFunction1();
    else throw Exception;
}

Now I want to write a second function myFunction2 which is almost identical to myFunction1 except for a single case, i.e.,

function myFunction2()
{
    if condition1 then
        doSomething4();
        myFunction2();
    else if condition2 then
        doSomething2();
        myFunction2();
    else if condition3 then
        doSomething3();
        myFunction2();
    else throw Exception;
}

Note that it is only the first if which differs from myFuction1. How could I write myFuction2 so as to avoid duplicating code?


问:
Sizable input file and submit button on same line
I want to display a label, an input file and a submit button on the same line. The input file needs to be sizable (this means it will change size when the parent changes size and NOT dragable to resize). I tried to use display: table and display: table-cell and for some reason it works for other combinations but not this one

        Text
        <input type="file" style="display:table-cell; width: 100%;"/>
        <input style="display: table-cell; width:50px;" type="submit" value = "Upload"/>

```

Here is the fiddle: https://jsfiddle.net/danbenedek/wxn976oe/2/

Here is the original fiddle: http://jsfiddle.net/danbenedek/un9qae0x/1/ from where I got inspired but all the elements are div and it works. The moment I changed them to label and input it stop working.

答:
Is this what you want?

https://jsfiddle.net/wxn976oe/4/

.Column {
  background-color: red;
  float: left;
}
label.Column {
    width: 80px;
}
input[type="submit"] {
    width: 50px;
}
input[type="file"] {
    width: calc(100% - (80px + 50px));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Row">
    <label class="Column">Text</label>
    <input class="Column" type="file"/>
    <input class="Column" type="submit" value = "Upload"/>
</div></code>```

Body:
I want to display a label, an input file and a submit button on the same line. The input file needs to be sizable (this means it will change size when the parent changes size and NOT dragable to resize). I tried to use display: table and display: table-cell and for some reason it works for other combinations but not this one

        Text
        <input type="file" style="display:table-cell; width: 100%;"/>
        <input style="display: table-cell; width:50px;" type="submit" value = "Upload"/>

Here is the fiddle: https://jsfiddle.net/danbenedek/wxn976oe/2/

Here is the original fiddle: http://jsfiddle.net/danbenedek/un9qae0x/1/ from where I got inspired but all the elements are div and it works. The moment I changed them to label and input it stop working.

Body:
Is this what you want?

https://jsfiddle.net/wxn976oe/4/

.Column {
  background-color: red;
  float: left;
}
label.Column {
    width: 80px;
}
input[type="submit"] {
    width: 50px;
}
input[type="file"] {
    width: calc(100% - (80px + 50px));
}

<div class="Row">
    <label class="Column">Text</label>
    <input class="Column" type="file"/>
    <input class="Column" type="submit" value = "Upload"/>
</div>


问:
Automatically wrapping/converting JavaBeans into case classes
We are using Kryo to communicate between a Scala application and a Java application. Since the class definitions have to be used from Java (and we don't want to include the Scala library as a dependency in the Java applicaton) we are using JavaBeans to define the transfer objects.

However, using JavaBeans directly in Scala is a bit of a hassle. No pattern matching, having to use new, etc. What we're doing right now is defining extractors and apply methods in separate objects on the Scala side to make it nicer to work with these classes.

Since most of what we need is boilerplate, we are wondering if there would be a way of doing this automatically. For example, we have this JavaBean (there are about 20+ different message types):

```<code>public class HandshakeRequest extends Request {
    private String gatewayId;
    private String requestId;
    private Date timestamp = new Date();

    public HandshakeRequest(String gatewayId, String requestId) {
        this.gatewayId = gatewayId;
        this.requestId = requestId;
    }

    public String getGatewayId() { return gatewayId; }
    public String getRequestId() { return requestId; }
    public Date getTimestamp() { return timestamp; }
    private HandshakeRequest() { /* For Kryo */ }
}
</code>```

This is an example of the object we use to bridge to Scala:

```<code>object Handshake {
  def unapply(msg: HandshakeRequest): Option[ (DateTime, String, String) ] = {
    (
      new DateTime(msg.getTimestamp.getTime),
      msg.getRequestId,
      msg.getGatewayId
    ).some
  }

  def apply(gatewayId: String, requestId: String) = new HandshakeRequest(gatewayId, requestId)
}
</code>```

Since all of our object have the Timestamp, it is also part of the boilerplate. We'd like some way (perhaps a macro?) to automatically generate the unapply and apply methods (and ideally, the whole object itself).

Does anyone know of an easy way to accomplish this?

答: I've started a project https://github.com/limansky/beanpuree which allows convertions from beans to case classes. I'm going to add some more features, like automatic type convertion between Java number classes and Scala classes. </p>

Body:
We are using Kryo to communicate between a Scala application and a Java application. Since the class definitions have to be used from Java (and we don't want to include the Scala library as a dependency in the Java applicaton) we are using JavaBeans to define the transfer objects.

However, using JavaBeans directly in Scala is a bit of a hassle. No pattern matching, having to use new, etc. What we're doing right now is defining extractors and apply methods in separate objects on the Scala side to make it nicer to work with these classes.

Since most of what we need is boilerplate, we are wondering if there would be a way of doing this automatically. For example, we have this JavaBean (there are about 20+ different message types):

public class HandshakeRequest extends Request {
    private String gatewayId;
    private String requestId;
    private Date timestamp = new Date();

    public HandshakeRequest(String gatewayId, String requestId) {
        this.gatewayId = gatewayId;
        this.requestId = requestId;
    }

    public String getGatewayId() { return gatewayId; }
    public String getRequestId() { return requestId; }
    public Date getTimestamp() { return timestamp; }
    private HandshakeRequest() { /* For Kryo */ }
}

This is an example of the object we use to bridge to Scala:

object Handshake {
  def unapply(msg: HandshakeRequest): Option[ (DateTime, String, String) ] = {
    (
      new DateTime(msg.getTimestamp.getTime),
      msg.getRequestId,
      msg.getGatewayId
    ).some
  }

  def apply(gatewayId: String, requestId: String) = new HandshakeRequest(gatewayId, requestId)
}

Since all of our object have the Timestamp, it is also part of the boilerplate. We'd like some way (perhaps a macro?) to automatically generate the unapply and apply methods (and ideally, the whole object itself).

Does anyone know of an easy way to accomplish this?


问:
Android listview clicking on item multiple times
I have a listview with several items. When clicking on an item, an Activity is opened. However, when I click fast several times on the item, the activity, asociated with it, is opened several times. How to open the item only once?

I use the following code:

```<code>private OnItemClickListener newsfeedClickHandler = new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        MyObject newsfeed = adapter.getItem(position);
        onNewsfeedClick(newsfeed);
    }
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_newsfeed, container, false);
    ...
    listView = (ListView) view.findViewById(R.id.newsfeeds);
    listView.setOnItemClickListener(newsfeedClickHandler);
    listView.setAdapter(adapter);
    ...
    return view;
}
private void onNewsfeedClick(MyObject newsfeed) {
    Intent intent = createIntent(newsfeed);
    startActivity(intent);
}
</code>```

答:
To prevent multiple clicks on ListView Items, add the following code in your listview click listener:</p>

```<code>if (SystemClock.elapsedRealtime() - mLastClickTimeListViewItem < 1000){
    return;
}
</code>```

Body:
I have a listview with several items. When clicking on an item, an Activity is opened. However, when I click fast several times on the item, the activity, asociated with it, is opened several times. How to open the item only once?

I use the following code:

private OnItemClickListener newsfeedClickHandler = new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        MyObject newsfeed = adapter.getItem(position);
        onNewsfeedClick(newsfeed);
    }
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_newsfeed, container, false);
    ...
    listView = (ListView) view.findViewById(R.id.newsfeeds);
    listView.setOnItemClickListener(newsfeedClickHandler);
    listView.setAdapter(adapter);
    ...
    return view;
}
private void onNewsfeedClick(MyObject newsfeed) {
    Intent intent = createIntent(newsfeed);
    startActivity(intent);
}

Body:
To prevent multiple clicks on ListView Items, add the following code in your listview click listener:

if (SystemClock.elapsedRealtime() - mLastClickTimeListViewItem < 1000){
    return;
}


问:
Debugging SQL Server 2008
I have Visual Studio .Net project which uses ADO connection to call stored procedure of SQL Server database.

It is possible to set a breakpoing at stored procedure and debug it. I have local SQL Server
and SQL Enterprise Edition installed.

答:
I would strongly suggest that you take a look at the built in tooling in SQL management studio.

i have written a pretty detailed blog post about it here:

http://www.diaryofaninja.com/blog/2010/11/23/debugging-sql-queries-function-amp-stored-procedures-with-sql-management-studio

basically the gist of it is that you enter you sql query to execute your stored procedure, and instead of pressing F5 or hitting the exclamation, you hit the play button and use F10 and F11 to step through and step into your stored procs.

very very handy - and no one seems to use it.

Title: Debugging SQL Server 2008


问:
Angular-cli ignores tsconfig.json
Using

```<code>"@angular/cli": "^1.0.0"
</code>```

@angular/cli ignores tsconfig.json

The project compiles just fine editing / removing tsconfig.json

Why is that?

答:
As stupid as it may seem, the angular-cli 's tsconfig.json file is located inside src/tsconfig.app.json

The root tsconfig.json will be used by editors (such as vscode).

Title: Angular-cli ignores tsconfig.json

Body:
Using

"@angular/cli": "^1.0.0"

@angular/cli ignores tsconfig.json

The project compiles just fine editing / removing tsconfig.json

Why is that?


问:
Find pages with tag
In a Umbraco 7 solution, i have a Tags Content picker on all pages. Pages can with this, set tags on each page.

I then want to get alle pages, within the intire site, that has, lets say tag 111 (id, not name).

I have tried with:

```<code>var ids = Model.MacroParameters["tags"]; //the tags to show
CurrentPage.AncestorOrSelf(1).Descendants().Where(x => ids.Contains(x.tags.ToString()));
</code>```

But that gives me the error:

```<code>Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type
</code>```

Whats the correct way?

答:
Always try to avoid using Descendants, especially on the root node.
To get the tags for a property:

```<code>ApplicationContext.Current.Services.TagService.GetTagsForProperty(Model.Content.Id, "propertyname")
</code>```

To find content with a specific tag:

```<code>ApplicationContext.Current.Services.TagService.GetTaggedContentByTag("tag")
</code>```

Title: Find pages with tag

Body:
In a Umbraco 7 solution, i have a Tags Content picker on all pages. Pages can with this, set tags on each page.

I then want to get alle pages, within the intire site, that has, lets say tag 111 (id, not name).

I have tried with:

var ids = Model.MacroParameters["tags"]; //the tags to show
CurrentPage.AncestorOrSelf(1).Descendants().Where(x => ids.Contains(x.tags.ToString()));

But that gives me the error:

Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type

Whats the correct way?

Body:
Always try to avoid using Descendants, especially on the root node.
To get the tags for a property:

ApplicationContext.Current.Services.TagService.GetTagsForProperty(Model.Content.Id, "propertyname")

To find content with a specific tag:

ApplicationContext.Current.Services.TagService.GetTaggedContentByTag("tag")


问:
PHP - Updating or Creating Multi-Dimensional Arrays
In my code I am checking if two variables are false. If both are false, then I want to update an array called responseArray with the value. I am unable to figure out how to update the array twice without overwriting the value if both variables are false. This is being used to capture if username and email address already registered.

Here is the code:

```<code>if($usernameAvailable == false)
    {
      /*Update validation error array that username taken*/
      if(isset($responseArray['ErrorArray']['Validation']))
      {
        /*Already another validation error exist in the array, add to it*/
        $utilitiesInstance->array_push_assoc($responseArray['ErrorArray']['Validation'], "Username", "Username Already Taken");
      }else{
        /*No array with validation errors is created...create it.*/
        $responseArray = array("ErrorArray"=>array("Validation"=>array("Username"=>"Username Already Taken")), "requestSuccessful"=>false);
      }
    }

    if($emailAvailable == false)
    {
      /*Update validation error array that Email already registered*/
      if(isset($responseArray['ErrorArray']['Validation']))
      {
        /*Already another validation error exist in the array, add to it*/
        $utilitiesInstance->array_push_assoc($responseArray['ErrorArray']['Validation'], "Email", "Email Already Registered");
      }else{
        /*No array with validation errors is created...create it.*/
        $responseArray = array("ErrorArray"=>array("Validation"=>array("Email"=>"Email Already Registered")), "requestSuccessful"=>false);
      }
    }
</code>```

What I am getting when I enter both username and email that deliver a false on both is the following output:

{"ErrorArray":{"Validation":{"Username":"Username Already
  Taken"}},"requestSuccessful":false}

while it should also include the email item in the Validation array above because that also is false. This is exactly what I want to have as an output in this scenario:

{"ErrorArray":{"Validation":{"Username":"Username Already Taken",
  "Email":"Email already registered"}},"requestSuccessful":false}

Here is the code I use for the function array_push_assoc() just in case:

```<code>function array_push_assoc($array, $key, $value){
    $array[$key] = $value;
    return $array;
  }
</code>```

答:
Try this mate:</p>

```<code>if($usernameAvailable == false) {
    $responseArray['ErrorArray']['Validation'][] = array("Username"=>"Username Already Taken");
    $responseArray['ErrorArray']['requestSuccessful'] = false;
}

if($emailAvailable == false) {
    $responseArray['ErrorArray']['Validation'][] = array("Email"=>"Email Already Registered");
    $responseArray['ErrorArray']['requestSuccessful'] = false;
}
</code>```

Body:
In my code I am checking if two variables are false. If both are false, then I want to update an array called responseArray with the value. I am unable to figure out how to update the array twice without overwriting the value if both variables are false. This is being used to capture if username and email address already registered.

Here is the code:

if($usernameAvailable == false)
    {
      /*Update validation error array that username taken*/
      if(isset($responseArray['ErrorArray']['Validation']))
      {
        /*Already another validation error exist in the array, add to it*/
        $utilitiesInstance->array_push_assoc($responseArray['ErrorArray']['Validation'], "Username", "Username Already Taken");
      }else{
        /*No array with validation errors is created...create it.*/
        $responseArray = array("ErrorArray"=>array("Validation"=>array("Username"=>"Username Already Taken")), "requestSuccessful"=>false);
      }
    }

    if($emailAvailable == false)
    {
      /*Update validation error array that Email already registered*/
      if(isset($responseArray['ErrorArray']['Validation']))
      {
        /*Already another validation error exist in the array, add to it*/
        $utilitiesInstance->array_push_assoc($responseArray['ErrorArray']['Validation'], "Email", "Email Already Registered");
      }else{
        /*No array with validation errors is created...create it.*/
        $responseArray = array("ErrorArray"=>array("Validation"=>array("Email"=>"Email Already Registered")), "requestSuccessful"=>false);
      }
    }

What I am getting when I enter both username and email that deliver a false on both is the following output:

{"ErrorArray":{"Validation":{"Username":"Username Already
  Taken"}},"requestSuccessful":false}

while it should also include the email item in the Validation array above because that also is false. This is exactly what I want to have as an output in this scenario:

{"ErrorArray":{"Validation":{"Username":"Username Already Taken",
  "Email":"Email already registered"}},"requestSuccessful":false}

Here is the code I use for the function array_push_assoc() just in case:

function array_push_assoc($array, $key, $value){
    $array[$key] = $value;
    return $array;
  }

Body:
Try this mate:

if($usernameAvailable == false) {
    $responseArray['ErrorArray']['Validation'][] = array("Username"=>"Username Already Taken");
    $responseArray['ErrorArray']['requestSuccessful'] = false;
}

if($emailAvailable == false) {
    $responseArray['ErrorArray']['Validation'][] = array("Email"=>"Email Already Registered");
    $responseArray['ErrorArray']['requestSuccessful'] = false;
}


问:
Javascript regex between string delimiters
I have the following string:

```<code>%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%
</code>```

PROBLEM: I am trying to match all occurrences between %||....||% and process those substring matches

MY REGEX: /%([\s\S]*?)(?=%)/g

MY CODE

```<code>var a = "%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%";

var pattern = /%([\s\S]*?)(?=%)/g;

a.replace( pattern, function replacer(match){
    return match.doSomething();
} );
</code>```

Now the patterns seems to be selecting the everything between the first and last occurrence of %||  .... %||

MY
FIDDLE

WHAT I NEED:

I want to iterate over the matches

%||1234567890||Joe||%

AND

%||1234567890||Robert||%

and do something

答:
Because he tries to take as much as possible, and [\s\S] basically means "anything". So he takes anything.</p>

```<code>RegExp parts without escaping, exploded for readability
start tag : %||
first info: ([^|]*) // will stop at the first |
separator : ||
last info : ([^|]*) // will stop at the first |
end tag   : ||%

Escaped RegExp:
/%\|\|([^\|]*)\|\|([^\|]*)\|\|%/g
</code>```

Body:
I have the following string:

%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%

PROBLEM: I am trying to match all occurrences between %||....||% and process those substring matches

MY REGEX: /%([\s\S]*?)(?=%)/g

MY CODE

var a = "%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%";

var pattern = /%([\s\S]*?)(?=%)/g;

a.replace( pattern, function replacer(match){
    return match.doSomething();
} );

Now the patterns seems to be selecting the everything between the first and last occurrence of %||  .... %||

MY
FIDDLE

WHAT I NEED:

I want to iterate over the matches

%||1234567890||Joe||%

AND

%||1234567890||Robert||%

and do something

Body:
Because he tries to take as much as possible, and [\s\S] basically means "anything". So he takes anything.

RegExp parts without escaping, exploded for readability
start tag : %||
first info: ([^|]*) // will stop at the first |
separator : ||
last info : ([^|]*) // will stop at the first |
end tag   : ||%

Escaped RegExp:
/%\|\|([^\|]*)\|\|([^\|]*)\|\|%/g


问:
Printer.print to text document in VB6
Im not 100% about this, so bear with me and hopefully you can help me make sense and solve the issue.

So in my code there are a lot of printer.print "Some String" and right at the end, like there should be, is a printer.enddoc.

Occasionally we get an issue where, for what ever reason, the printer isnt ready and crashes the software out with an error 482 which basically means the printer isnt ready.

What I want to do is push the document that will be printed into a text file before printing so if there is an issue, the document isnt lost, and it also helps with saving data to be reprinted at a later date.

I assumed (wrongly, I think) that printer.print pushes data into something that will be fired to the printer and can be viewed before hand, but I am not convinced.

I want to just clarify that the code I am working on is at least 15 years old, been played with by at least 5 different coders and its all a bit of a jumble.

答:
Show the code you use to print.

You are using a Error Handler ?

Your code check if printer is ready, before to print?

Title: Printer.print to text document in VB6


问:
selenium 2.53.0 with firefox 46
I am new to selenium and I am using selenium 2.53.0 with firefox 46 and executing very simple code
import org.openqa.selenium.firefox.FirefoxDriver;

```<code>public class test {

public static void main(String[] args) {
    FirefoxDriver driver=new FirefoxDriver();
    driver.get("http://google.com");

}
</code>```

}

when I execute this code ,my firefox browser opens but it doesnot open the "google.com"

```<code>    org.openqa.selenium.firefox.NotConnectedException: Unable to connect to
       host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output:
       fee SiteAdvisor Enterprise","description":null,"creator":"McAfee

  Inc.","homepageURL":"http://www.siteadvisor.com/"},"visible":true,"active":false,"userDisabled":true,"appDisabled":false,"descriptor":"C:\\Program Files (x86)\\McAfee\\SiteAdvisor Enterprise\\saeffplg.xpi","installDate":1455580102000,"updateDate":1455580102000,"applyBackgroundUpdates":1,"bootstrap":false,"skinnable":false,"size":349132,"sourceURI":null,"releaseNotesURI":null,"softDisabled":false,"foreignInstall":true,"hasBinaryComponents":false,"strictCompatibility":false,"locales":[],"targetApplications":[{"id":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","minVersion":"15.0","maxVersion":"47.0"}],"targetPlatforms":[],"multiprocessCompatible":false,"signedState":2,"seen":true}
1490946675982   DeferredSave.extensions.json    DEBUG   Save changes
1490946675982   addons.xpi  DEBUG   Updating database with changes to installed add-ons
1490946675983   addons.xpi-utils    DEBUG   Updating add-on states
1490946675988   addons.xpi-utils    DEBUG   Writing add-ons list
1490946676009   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\e10srollout@mozilla.org.xpi
1490946676010   addons.xpi  DEBUG   Calling bootstrap method startup on e10srollout@mozilla.org version 1.0
1490946676010   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\firefox@getpocket.com.xpi
1490946676012   addons.xpi  DEBUG   Calling bootstrap method startup on firefox@getpocket.com version 1.0.2
1490946676013   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\loop@mozilla.org.xpi
1490946676015   addons.xpi  DEBUG   Calling bootstrap method startup on loop@mozilla.org version 1.3.2
1490946676032   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\websensehelper@mozilla.org.xpi
1490946676033   addons.xpi  DEBUG   Calling bootstrap method startup on websensehelper@mozilla.org version 1.0
1490946676036   addons.manager  DEBUG   Registering shutdown blocker for XPIProvider
1490946676038   addons.manager  DEBUG   Provider finished startup: XPIProvider
1490946676038   addons.manager  DEBUG   Starting provider:
     LightweightThemeManager
1490946676038   addons.manager  DEBUG   Registering shutdown blocker for LightweightThemeManager
1490946676038   addons.manager  DEBUG   Provider finished startup: LightweightThemeManager
1490946676039   addons.manager  DEBUG   Starting provider: GMPProvider
1490946676045   addons.manager  DEBUG   Registering shutdown blocker for GMPProvider
1490946676046   addons.manager  DEBUG   Provider finished startup: GMPProvider
1490946676046   addons.manager  DEBUG   Starting provider: PluginProvider
1490946676046   addons.manager  DEBUG   Registering shutdown blocker for PluginProvider
1490946676046   addons.manager  DEBUG   Provider finished startup: PluginProvider
1490946676046   addons.manager  DEBUG   Completed startup sequence
1490946677662   addons.manager  DEBUG   Starting provider: <unnamed-provider>
1490946677662   addons.manager  DEBUG   Registering shutdown blocker for <unnamed-provider>
1490946677663   addons.manager  DEBUG   Provider finished startup: <unnamed-provider>
1490946677955   DeferredSave.extensions.json    DEBUG   Write succeeded
1490946677955   addons.xpi-utils    DEBUG   XPI Database saved, setting schema version preference to 17
1490946677955   DeferredSave.extensions.json    DEBUG   Starting timer
1490946678047   DeferredSave.extensions.json    DEBUG   Starting write
1490946678069   addons.repository   DEBUG   No addons.json found.
1490946678070   DeferredSave.addons.json    DEBUG   Save changes
1490946678075   DeferredSave.addons.json    DEBUG   Starting timer
1490946678174   addons.manager  DEBUG   Starting provider: PreviousExperimentProvider
1490946678174   addons.manager  DEBUG   Registering shutdown blocker for PreviousExperimentProvider
1490946678174   addons.manager  DEBUG   Provider finished startup: PreviousExperimentProvider
1490946678177   DeferredSave.addons.json    DEBUG   Starting write
1490946678192   DeferredSave.extensions.json    DEBUG   Write succeeded
1490946678224   DeferredSave.addons.json    DEBUG   Write succeeded

    at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.start(NewProfileExtensionConnection.java:112)
    at org.openqa.selenium.firefox.FirefoxDriver.startClient(FirefoxDriver.java:271)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:119)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:218)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:211)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:207)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:120)
    at test.main(test.java:7)
Exception in thread "main" org.openqa.selenium.WebDriverException: Failed to connect to binary FirefoxBinary(C:\Program Files (x86)\Mozilla Firefox\firefox.exe) on port 7055; process output follows:
fee SiteAdvisor Enterprise","description":null,"creator":"McAfee Inc.","homepageURL":"http://www.siteadvisor.com/"},"visible":true,"active":false,"userDisabled":true,"appDisabled":false,"descriptor":"C:\\Program Files (x86)\\McAfee\\SiteAdvisor Enterprise\\saeffplg.xpi","installDate":1455580102000,"updateDate":1455580102000,"applyBackgroundUpdates":1,"bootstrap":false,"skinnable":false,"size":349132,"sourceURI":null,"releaseNotesURI":null,"softDisabled":false,"foreignInstall":true,"hasBinaryComponents":false,"strictCompatibility":false,"locales":[],"targetApplications":[{"id":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","minVersion":"15.0","maxVersion":"47.0"}],"targetPlatforms":[],"multiprocessCompatible":false,"signedState":2,"seen":true}
1490946675982   DeferredSave.extensions.json    DEBUG   Save changes
1490946675982   addons.xpi  DEBUG   Updating database with changes to installed add-ons
1490946675983   addons.xpi-utils    DEBUG   Updating add-on states
1490946675988   addons.xpi-utils    DEBUG   Writing add-ons list
1490946676009   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\e10srollout@mozilla.org.xpi
1490946676010   addons.xpi  DEBUG   Calling bootstrap method startup on e10srollout@mozilla.org version 1.0
1490946676010   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\firefox@getpocket.com.xpi
1490946676012   addons.xpi  DEBUG   Calling bootstrap method startup on firefox@getpocket.com version 1.0.2
1490946676013   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\loop@mozilla.org.xpi
1490946676015   addons.xpi  DEBUG   Calling bootstrap method startup on loop@mozilla.org version 1.3.2
1490946676032   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\websensehelper@mozilla.org.xpi
1490946676033   addons.xpi  DEBUG   Calling bootstrap method startup on websensehelper@mozilla.org version 1.0
1490946676036   addons.manager  DEBUG   Registering shutdown blocker for XPIProvider
1490946676038   addons.manager  DEBUG   Provider finished startup: XPIProvider
1490946676038   addons.manager  DEBUG   Starting provider: LightweightThemeManager
1490946676038   addons.manager  DEBUG   Registering shutdown blocker for LightweightThemeManager
1490946676038   addons.manager  DEBUG   Provider finished startup: LightweightThemeManager
1490946676039   addons.manager  DEBUG   Starting provider: GMPProvider
1490946676045   addons.manager  DEBUG   Registering shutdown blocker for GMPProvider
1490946676046   addons.manager  DEBUG   Provider finished startup: GMPProvider
1490946676046   addons.manager  DEBUG   Starting provider: PluginProvider
1490946676046   addons.manager  DEBUG   Registering shutdown blocker for PluginProvider
1490946676046   addons.manager  DEBUG   Provider finished startup: PluginProvider
1490946676046   addons.manager  DEBUG   Completed startup sequence
1490946677662   addons.manager  DEBUG   Starting provider: <unnamed-provider>
1490946677662   addons.manager  DEBUG   Registering shutdown blocker for <unnamed-provider>
1490946677663   addons.manager  DEBUG   Provider finished startup: <unnamed-provider>
1490946677955   DeferredSave.extensions.json    DEBUG   Write succeeded
1490946677955   addons.xpi-utils    DEBUG   XPI Database saved, setting schema version preference to 17
1490946677955   DeferredSave.extensions.json    DEBUG   Starting timer
1490946678047   DeferredSave.extensions.json    DEBUG   Starting write
1490946678069   addons.repository   DEBUG   No addons.json found.
1490946678070   DeferredSave.addons.json    DEBUG   Save changes
1490946678075   DeferredSave.addons.json    DEBUG   Starting timer
1490946678174   addons.manager  DEBUG   Starting provider: PreviousExperimentProvider
1490946678174   addons.manager  DEBUG   Registering shutdown blocker for PreviousExperimentProvider
1490946678174   addons.manager  DEBUG   Provider finished startup: PreviousExperimentProvider
1490946678177   DeferredSave.addons.json    DEBUG   Starting write
1490946678192   DeferredSave.extensions.json    DEBUG   Write succeeded
1490946678224   DeferredSave.addons.json    DEBUG   Write succeeded

Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 16:57:40'
System info: host: 'EQ-EQ5000787', ip: '10.237.211.31', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_91'
Driver info: driver.version: FirefoxDriver
    at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.start(NewProfileExtensionConnection.java:124)
    at org.openqa.selenium.firefox.FirefoxDriver.startClient(FirefoxDriver.java:271)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:119)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:218)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:211)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:207)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:120)
    at test.main(test.java:7)
Caused by: org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output:
fee SiteAdvisor Enterprise","description":null,"creator":"McAfee Inc.","homepageURL":"http://www.siteadvisor.com/"},"visible":true,"active":false,"userDisabled":true,"appDisabled":false,"descriptor":"C:\\Program Files (x86)\\McAfee\\SiteAdvisor Enterprise\\saeffplg.xpi","installDate":1455580102000,"updateDate":1455580102000,"applyBackgroundUpdates":1,"bootstrap":false,"skinnable":false,"size":349132,"sourceURI":null,"releaseNotesURI":null,"softDisabled":false,"foreignInstall":true,"hasBinaryComponents":false,"strictCompatibility":false,"locales":[],"targetApplications":[{"id":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","minVersion":"15.0","maxVersion":"47.0"}],"targetPlatforms":[],"multiprocessCompatible":false,"signedState":2,"seen":true}
1490946675982   DeferredSave.extensions.json    DEBUG   Save changes
1490946675982   addons.xpi  DEBUG   Updating database with changes to installed add-ons
1490946675983   addons.xpi-utils    DEBUG   Updating add-on states
1490946675988   addons.xpi-utils    DEBUG   Writing add-ons list
1490946676009   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\e10srollout@mozilla.org.xpi
1490946676010   addons.xpi  DEBUG   Calling bootstrap method startup on e10srollout@mozilla.org version 1.0
1490946676010   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\firefox@getpocket.com.xpi
1490946676012   addons.xpi  DEBUG   Calling bootstrap method startup on firefox@getpocket.com version 1.0.2
1490946676013   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\loop@mozilla.org.xpi
1490946676015   addons.xpi  DEBUG   Calling bootstrap method startup on loop@mozilla.org version 1.3.2
1490946676032   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\websensehelper@mozilla.org.xpi
1490946676033   addons.xpi  DEBUG   Calling bootstrap method startup on websensehelper@mozilla.org version 1.0
1490946676036   addons.manager  DEBUG   Registering shutdown blocker for XPIProvider
1490946676038   addons.manager  DEBUG   Provider finished startup: XPIProvider
1490946676038   addons.manager  DEBUG   Starting provider: LightweightThemeManager
1490946676038   addons.manager  DEBUG   Registering shutdown blocker for LightweightThemeManager
1490946676038   addons.manager  DEBUG   Provider finished startup: LightweightThemeManager
1490946676039   addons.manager  DEBUG   Starting provider: GMPProvider
1490946676045   addons.manager  DEBUG   Registering shutdown blocker for GMPProvider
1490946676046   addons.manager  DEBUG   Provider finished startup: GMPProvider
1490946676046   addons.manager  DEBUG   Starting provider: PluginProvider
1490946676046   addons.manager  DEBUG   Registering shutdown blocker for PluginProvider
1490946676046   addons.manager  DEBUG   Provider finished startup: PluginProvider
1490946676046   addons.manager  DEBUG   Completed startup sequence
1490946677662   addons.manager  DEBUG   Starting provider: <unnamed-provider>
1490946677662   addons.manager  DEBUG   Registering shutdown blocker for <unnamed-provider>
1490946677663   addons.manager  DEBUG   Provider finished startup: <unnamed-provider>
1490946677955   DeferredSave.extensions.json    DEBUG   Write succeeded
1490946677955   addons.xpi-utils    DEBUG   XPI Database saved, setting schema version preference to 17
1490946677955   DeferredSave.extensions.json    DEBUG   Starting timer
1490946678047   DeferredSave.extensions.json    DEBUG   Starting write
1490946678069   addons.repository   DEBUG   No addons.json found.
1490946678070   DeferredSave.addons.json    DEBUG   Save changes
1490946678075   DeferredSave.addons.json    DEBUG   Starting timer
1490946678174   addons.manager  DEBUG   Starting provider: PreviousExperimentProvider
1490946678174   addons.manager  DEBUG   Registering shutdown blocker for PreviousExperimentProvider
1490946678174   addons.manager  DEBUG   Provider finished startup: PreviousExperimentProvider
1490946678177   DeferredSave.addons.json    DEBUG   Starting write
1490946678192   DeferredSave.extensions.json    DEBUG   Write succeeded
1490946678224   DeferredSave.addons.json    DEBUG   Write succeeded

    at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.start(NewProfileExtensionConnection.java:112)
    ... 7 more
</code>```

What can i do make my firefox working again.?

Thanks a lot

答:
From the exception you got, I could understand that turn off you Macfee firewall and use this piece of code for invoking firefox driver. Let me know if there is any issue.</p>

```<code>   File pathToBinary = new File("C:\\Mozilla Firefox\\firefox.exe");
   FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
   FirefoxProfile firefoxProfile = new FirefoxProfile();
   driver = new FirefoxDriver(ffBinary,firefoxProfile);
</code>```

Title: selenium 2.53.0 with firefox 46

Body:
I am new to selenium and I am using selenium 2.53.0 with firefox 46 and executing very simple code
import org.openqa.selenium.firefox.FirefoxDriver;

public class test {

public static void main(String[] args) {
    FirefoxDriver driver=new FirefoxDriver();
    driver.get("http://google.com");

}

}

when I execute this code ,my firefox browser opens but it doesnot open the "google.com"

    org.openqa.selenium.firefox.NotConnectedException: Unable to connect to
       host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output:
       fee SiteAdvisor Enterprise","description":null,"creator":"McAfee

  Inc.","homepageURL":"http://www.siteadvisor.com/"},"visible":true,"active":false,"userDisabled":true,"appDisabled":false,"descriptor":"C:\\Program Files (x86)\\McAfee\\SiteAdvisor Enterprise\\saeffplg.xpi","installDate":1455580102000,"updateDate":1455580102000,"applyBackgroundUpdates":1,"bootstrap":false,"skinnable":false,"size":349132,"sourceURI":null,"releaseNotesURI":null,"softDisabled":false,"foreignInstall":true,"hasBinaryComponents":false,"strictCompatibility":false,"locales":[],"targetApplications":[{"id":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","minVersion":"15.0","maxVersion":"47.0"}],"targetPlatforms":[],"multiprocessCompatible":false,"signedState":2,"seen":true}
1490946675982   DeferredSave.extensions.json    DEBUG   Save changes
1490946675982   addons.xpi  DEBUG   Updating database with changes to installed add-ons
1490946675983   addons.xpi-utils    DEBUG   Updating add-on states
1490946675988   addons.xpi-utils    DEBUG   Writing add-ons list
1490946676009   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\e10srollout@mozilla.org.xpi
1490946676010   addons.xpi  DEBUG   Calling bootstrap method startup on e10srollout@mozilla.org version 1.0
1490946676010   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\firefox@getpocket.com.xpi
1490946676012   addons.xpi  DEBUG   Calling bootstrap method startup on firefox@getpocket.com version 1.0.2
1490946676013   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\loop@mozilla.org.xpi
1490946676015   addons.xpi  DEBUG   Calling bootstrap method startup on loop@mozilla.org version 1.3.2
1490946676032   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\websensehelper@mozilla.org.xpi
1490946676033   addons.xpi  DEBUG   Calling bootstrap method startup on websensehelper@mozilla.org version 1.0
1490946676036   addons.manager  DEBUG   Registering shutdown blocker for XPIProvider
1490946676038   addons.manager  DEBUG   Provider finished startup: XPIProvider
1490946676038   addons.manager  DEBUG   Starting provider:
     LightweightThemeManager
1490946676038   addons.manager  DEBUG   Registering shutdown blocker for LightweightThemeManager
1490946676038   addons.manager  DEBUG   Provider finished startup: LightweightThemeManager
1490946676039   addons.manager  DEBUG   Starting provider: GMPProvider
1490946676045   addons.manager  DEBUG   Registering shutdown blocker for GMPProvider
1490946676046   addons.manager  DEBUG   Provider finished startup: GMPProvider
1490946676046   addons.manager  DEBUG   Starting provider: PluginProvider
1490946676046   addons.manager  DEBUG   Registering shutdown blocker for PluginProvider
1490946676046   addons.manager  DEBUG   Provider finished startup: PluginProvider
1490946676046   addons.manager  DEBUG   Completed startup sequence
1490946677662   addons.manager  DEBUG   Starting provider: <unnamed-provider>
1490946677662   addons.manager  DEBUG   Registering shutdown blocker for <unnamed-provider>
1490946677663   addons.manager  DEBUG   Provider finished startup: <unnamed-provider>
1490946677955   DeferredSave.extensions.json    DEBUG   Write succeeded
1490946677955   addons.xpi-utils    DEBUG   XPI Database saved, setting schema version preference to 17
1490946677955   DeferredSave.extensions.json    DEBUG   Starting timer
1490946678047   DeferredSave.extensions.json    DEBUG   Starting write
1490946678069   addons.repository   DEBUG   No addons.json found.
1490946678070   DeferredSave.addons.json    DEBUG   Save changes
1490946678075   DeferredSave.addons.json    DEBUG   Starting timer
1490946678174   addons.manager  DEBUG   Starting provider: PreviousExperimentProvider
1490946678174   addons.manager  DEBUG   Registering shutdown blocker for PreviousExperimentProvider
1490946678174   addons.manager  DEBUG   Provider finished startup: PreviousExperimentProvider
1490946678177   DeferredSave.addons.json    DEBUG   Starting write
1490946678192   DeferredSave.extensions.json    DEBUG   Write succeeded
1490946678224   DeferredSave.addons.json    DEBUG   Write succeeded

    at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.start(NewProfileExtensionConnection.java:112)
    at org.openqa.selenium.firefox.FirefoxDriver.startClient(FirefoxDriver.java:271)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:119)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:218)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:211)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:207)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:120)
    at test.main(test.java:7)
Exception in thread "main" org.openqa.selenium.WebDriverException: Failed to connect to binary FirefoxBinary(C:\Program Files (x86)\Mozilla Firefox\firefox.exe) on port 7055; process output follows:
fee SiteAdvisor Enterprise","description":null,"creator":"McAfee Inc.","homepageURL":"http://www.siteadvisor.com/"},"visible":true,"active":false,"userDisabled":true,"appDisabled":false,"descriptor":"C:\\Program Files (x86)\\McAfee\\SiteAdvisor Enterprise\\saeffplg.xpi","installDate":1455580102000,"updateDate":1455580102000,"applyBackgroundUpdates":1,"bootstrap":false,"skinnable":false,"size":349132,"sourceURI":null,"releaseNotesURI":null,"softDisabled":false,"foreignInstall":true,"hasBinaryComponents":false,"strictCompatibility":false,"locales":[],"targetApplications":[{"id":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","minVersion":"15.0","maxVersion":"47.0"}],"targetPlatforms":[],"multiprocessCompatible":false,"signedState":2,"seen":true}
1490946675982   DeferredSave.extensions.json    DEBUG   Save changes
1490946675982   addons.xpi  DEBUG   Updating database with changes to installed add-ons
1490946675983   addons.xpi-utils    DEBUG   Updating add-on states
1490946675988   addons.xpi-utils    DEBUG   Writing add-ons list
1490946676009   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\e10srollout@mozilla.org.xpi
1490946676010   addons.xpi  DEBUG   Calling bootstrap method startup on e10srollout@mozilla.org version 1.0
1490946676010   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\firefox@getpocket.com.xpi
1490946676012   addons.xpi  DEBUG   Calling bootstrap method startup on firefox@getpocket.com version 1.0.2
1490946676013   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\loop@mozilla.org.xpi
1490946676015   addons.xpi  DEBUG   Calling bootstrap method startup on loop@mozilla.org version 1.3.2
1490946676032   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\websensehelper@mozilla.org.xpi
1490946676033   addons.xpi  DEBUG   Calling bootstrap method startup on websensehelper@mozilla.org version 1.0
1490946676036   addons.manager  DEBUG   Registering shutdown blocker for XPIProvider
1490946676038   addons.manager  DEBUG   Provider finished startup: XPIProvider
1490946676038   addons.manager  DEBUG   Starting provider: LightweightThemeManager
1490946676038   addons.manager  DEBUG   Registering shutdown blocker for LightweightThemeManager
1490946676038   addons.manager  DEBUG   Provider finished startup: LightweightThemeManager
1490946676039   addons.manager  DEBUG   Starting provider: GMPProvider
1490946676045   addons.manager  DEBUG   Registering shutdown blocker for GMPProvider
1490946676046   addons.manager  DEBUG   Provider finished startup: GMPProvider
1490946676046   addons.manager  DEBUG   Starting provider: PluginProvider
1490946676046   addons.manager  DEBUG   Registering shutdown blocker for PluginProvider
1490946676046   addons.manager  DEBUG   Provider finished startup: PluginProvider
1490946676046   addons.manager  DEBUG   Completed startup sequence
1490946677662   addons.manager  DEBUG   Starting provider: <unnamed-provider>
1490946677662   addons.manager  DEBUG   Registering shutdown blocker for <unnamed-provider>
1490946677663   addons.manager  DEBUG   Provider finished startup: <unnamed-provider>
1490946677955   DeferredSave.extensions.json    DEBUG   Write succeeded
1490946677955   addons.xpi-utils    DEBUG   XPI Database saved, setting schema version preference to 17
1490946677955   DeferredSave.extensions.json    DEBUG   Starting timer
1490946678047   DeferredSave.extensions.json    DEBUG   Starting write
1490946678069   addons.repository   DEBUG   No addons.json found.
1490946678070   DeferredSave.addons.json    DEBUG   Save changes
1490946678075   DeferredSave.addons.json    DEBUG   Starting timer
1490946678174   addons.manager  DEBUG   Starting provider: PreviousExperimentProvider
1490946678174   addons.manager  DEBUG   Registering shutdown blocker for PreviousExperimentProvider
1490946678174   addons.manager  DEBUG   Provider finished startup: PreviousExperimentProvider
1490946678177   DeferredSave.addons.json    DEBUG   Starting write
1490946678192   DeferredSave.extensions.json    DEBUG   Write succeeded
1490946678224   DeferredSave.addons.json    DEBUG   Write succeeded

Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 16:57:40'
System info: host: 'EQ-EQ5000787', ip: '10.237.211.31', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_91'
Driver info: driver.version: FirefoxDriver
    at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.start(NewProfileExtensionConnection.java:124)
    at org.openqa.selenium.firefox.FirefoxDriver.startClient(FirefoxDriver.java:271)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:119)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:218)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:211)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:207)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:120)
    at test.main(test.java:7)
Caused by: org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output:
fee SiteAdvisor Enterprise","description":null,"creator":"McAfee Inc.","homepageURL":"http://www.siteadvisor.com/"},"visible":true,"active":false,"userDisabled":true,"appDisabled":false,"descriptor":"C:\\Program Files (x86)\\McAfee\\SiteAdvisor Enterprise\\saeffplg.xpi","installDate":1455580102000,"updateDate":1455580102000,"applyBackgroundUpdates":1,"bootstrap":false,"skinnable":false,"size":349132,"sourceURI":null,"releaseNotesURI":null,"softDisabled":false,"foreignInstall":true,"hasBinaryComponents":false,"strictCompatibility":false,"locales":[],"targetApplications":[{"id":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","minVersion":"15.0","maxVersion":"47.0"}],"targetPlatforms":[],"multiprocessCompatible":false,"signedState":2,"seen":true}
1490946675982   DeferredSave.extensions.json    DEBUG   Save changes
1490946675982   addons.xpi  DEBUG   Updating database with changes to installed add-ons
1490946675983   addons.xpi-utils    DEBUG   Updating add-on states
1490946675988   addons.xpi-utils    DEBUG   Writing add-ons list
1490946676009   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\e10srollout@mozilla.org.xpi
1490946676010   addons.xpi  DEBUG   Calling bootstrap method startup on e10srollout@mozilla.org version 1.0
1490946676010   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\firefox@getpocket.com.xpi
1490946676012   addons.xpi  DEBUG   Calling bootstrap method startup on firefox@getpocket.com version 1.0.2
1490946676013   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\loop@mozilla.org.xpi
1490946676015   addons.xpi  DEBUG   Calling bootstrap method startup on loop@mozilla.org version 1.3.2
1490946676032   addons.xpi  DEBUG   Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\websensehelper@mozilla.org.xpi
1490946676033   addons.xpi  DEBUG   Calling bootstrap method startup on websensehelper@mozilla.org version 1.0
1490946676036   addons.manager  DEBUG   Registering shutdown blocker for XPIProvider
1490946676038   addons.manager  DEBUG   Provider finished startup: XPIProvider
1490946676038   addons.manager  DEBUG   Starting provider: LightweightThemeManager
1490946676038   addons.manager  DEBUG   Registering shutdown blocker for LightweightThemeManager
1490946676038   addons.manager  DEBUG   Provider finished startup: LightweightThemeManager
1490946676039   addons.manager  DEBUG   Starting provider: GMPProvider
1490946676045   addons.manager  DEBUG   Registering shutdown blocker for GMPProvider
1490946676046   addons.manager  DEBUG   Provider finished startup: GMPProvider
1490946676046   addons.manager  DEBUG   Starting provider: PluginProvider
1490946676046   addons.manager  DEBUG   Registering shutdown blocker for PluginProvider
1490946676046   addons.manager  DEBUG   Provider finished startup: PluginProvider
1490946676046   addons.manager  DEBUG   Completed startup sequence
1490946677662   addons.manager  DEBUG   Starting provider: <unnamed-provider>
1490946677662   addons.manager  DEBUG   Registering shutdown blocker for <unnamed-provider>
1490946677663   addons.manager  DEBUG   Provider finished startup: <unnamed-provider>
1490946677955   DeferredSave.extensions.json    DEBUG   Write succeeded
1490946677955   addons.xpi-utils    DEBUG   XPI Database saved, setting schema version preference to 17
1490946677955   DeferredSave.extensions.json    DEBUG   Starting timer
1490946678047   DeferredSave.extensions.json    DEBUG   Starting write
1490946678069   addons.repository   DEBUG   No addons.json found.
1490946678070   DeferredSave.addons.json    DEBUG   Save changes
1490946678075   DeferredSave.addons.json    DEBUG   Starting timer
1490946678174   addons.manager  DEBUG   Starting provider: PreviousExperimentProvider
1490946678174   addons.manager  DEBUG   Registering shutdown blocker for PreviousExperimentProvider
1490946678174   addons.manager  DEBUG   Provider finished startup: PreviousExperimentProvider
1490946678177   DeferredSave.addons.json    DEBUG   Starting write
1490946678192   DeferredSave.extensions.json    DEBUG   Write succeeded
1490946678224   DeferredSave.addons.json    DEBUG   Write succeeded

    at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.start(NewProfileExtensionConnection.java:112)
    ... 7 more

What can i do make my firefox working again.?

Thanks a lot

Body:
From the exception you got, I could understand that turn off you Macfee firewall and use this piece of code for invoking firefox driver. Let me know if there is any issue.

   File pathToBinary = new File("C:\\Mozilla Firefox\\firefox.exe");
   FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
   FirefoxProfile firefoxProfile = new FirefoxProfile();
   driver = new FirefoxDriver(ffBinary,firefoxProfile);


问:
What's a good way to remove all of the subviews of a UIScrollView?
I have a scroll view and I need to reload the contents often while my app is running. Right now, I'm using the following line of code to remove the subviews before adding them back again:

```<code>[scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
</code>```

Should I be using the following instead?

```<code>scrollView.subviews = nil;
</code>```

For some reason, the (first) above line of code seems to crash the app every 16 times it is run. Am I leaking memory somewhere? The following method takes an array of views, the scroller (which is a constant) and the direction.

Edit:

```<code>- (void)loadViews:(NSArray *)views IntoScroller:(UIScrollView *)scroller withDirection:(NSString *)direction{
//Set up the scrollView

[scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

if([direction isEqualToString:@"horizontal"]){
    scrollView.frame = CGRectMake(0, 0, 1024, 768);
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * [[NSNumber numberWithUnsignedInt:[views count]] floatValue], scrollView.frame.size.height);
}else if([direction isEqualToString:@"vertical"]){
    scrollView.frame = CGRectMake(0, 0, 1024, 768);
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, scrollView.frame.size.height * [[NSNumber numberWithUnsignedInt:[views count]] floatValue]);
}

for (int i=0; i<[[NSNumber numberWithUnsignedInt:[views count]] intValue]; i++) {

    [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:scrollView.frame];

    if([direction isEqualToString:@"horizontal"]){
        [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:CGRectMake(i * [[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view].frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height)];//CGRectMake(i * announcementView.view.frame.size.width, -scrollView.frame.origin.x, scrollView.frame.size.width, scrollView.frame.size.height)];
    }else if([direction isEqualToString:@"vertical"]){
        [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:CGRectMake(0, i * [[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view].frame.size.height, scrollView.frame.size.width, scrollView.frame.size.height)];
    }

    [scrollView addSubview:[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view]];
}
</code>```

}

答:
Below is the code to remove all the sub views from the scroll view:</p>

```<code>for(UIView *subview in [scrollview  subviews])
        {
         [subview removeFromSuperview];

        }
</code>```

Body:
I have a scroll view and I need to reload the contents often while my app is running. Right now, I'm using the following line of code to remove the subviews before adding them back again:

[scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

Should I be using the following instead?

scrollView.subviews = nil;

For some reason, the (first) above line of code seems to crash the app every 16 times it is run. Am I leaking memory somewhere? The following method takes an array of views, the scroller (which is a constant) and the direction.

Edit:

- (void)loadViews:(NSArray *)views IntoScroller:(UIScrollView *)scroller withDirection:(NSString *)direction{
//Set up the scrollView

[scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

if([direction isEqualToString:@"horizontal"]){
    scrollView.frame = CGRectMake(0, 0, 1024, 768);
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * [[NSNumber numberWithUnsignedInt:[views count]] floatValue], scrollView.frame.size.height);
}else if([direction isEqualToString:@"vertical"]){
    scrollView.frame = CGRectMake(0, 0, 1024, 768);
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, scrollView.frame.size.height * [[NSNumber numberWithUnsignedInt:[views count]] floatValue]);
}

for (int i=0; i<[[NSNumber numberWithUnsignedInt:[views count]] intValue]; i++) {

    [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:scrollView.frame];

    if([direction isEqualToString:@"horizontal"]){
        [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:CGRectMake(i * [[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view].frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height)];//CGRectMake(i * announcementView.view.frame.size.width, -scrollView.frame.origin.x, scrollView.frame.size.width, scrollView.frame.size.height)];
    }else if([direction isEqualToString:@"vertical"]){
        [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:CGRectMake(0, i * [[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view].frame.size.height, scrollView.frame.size.width, scrollView.frame.size.height)];
    }

    [scrollView addSubview:[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view]];
}

}

Body:
Below is the code to remove all the sub views from the scroll view:

for(UIView *subview in [scrollview  subviews])
        {
         [subview removeFromSuperview];

        }