问:
Ho to write Select query for EAV - Entity Attribute Value model
I have following schema. In which

Types represent DB Table

TypeProperty represents Column of Table

TypeRow represent Row of table

I want to write a select query to which I will pass single Type and it should give me all its TypeProperty, TypeRow and TypeValue that are associated with these Properties and Rows.

I will be showing this data in a web application in which user will select a Type from dropdown and application will get Properties, Rows and associated values and will show them as a complete grid.

I am using SQL Server 2014.

Can anyone help me please?

答:
So, i'm going to try and take a crack at what you have been getting help with Kannan on.
It sounds like you have two different queries to the database:
    1) Query results of the list of 'Type(s)' for your dropdown,(You should be able to do this fairly easily)
    2) query results of the list of 'Propert(ies)', 'Row(s)', and 'value(s) that match the selected 'Type' in the dropdown  as a table with the properties as the header to set table.

To me it seems the easest and best way to handle this would be to get the data back using Kannan's script (probably inside of a stored procedure and maybe a view?)  and create the grid in code from your back-end application, or front end client. However, if you cant, here is a script that should work or at the least get you started.

I would suggest maybe creating two stored procs, one to retrieve the data, and another to pivot using dynamic sql.

```<code>CREATE PROCEDURE dbo.EAV_GridGenerator
    @TypeId int = 0,
    @param2 int
AS
BEGIN TRY
DECLARE @cols varchar(max),
        @query varchar(max);
        --TODO: CLEAN UP VARIABLE NAMES THROUGHOUT
SELECT trow.TypesId, tprop.PropertyName AS [Column], trow.TypeRowId AS [RowID], tval.Value AS [Data]
INTO #TT2
FROM dbo.[Types] AS t
    JOIN dbo.TypeRow trow
        ON t.typesId = trow.typesId
        JOIN dbo.TypeValue tval
            ON tval.TypeRowsId = trow.TypeRowId
            JOIN dbo.[TypeProperty] tprop
                ON tval.TypesPropertyId = tprop.TypePropertyId
WHERE trow.TypesId = @TypeId
    --AND  t.IsActive = 1   AND  tprop.IsActive = 1 AND  trow.IsActive = 1  AND  tval.IsActive = 1--TODO: IDK but you should probably add both of these
--      AND t.IsDelete = 1  AND  tprop.IsDelete = 1 AND  trow.IsDelete = 1  AND  tval.IsDelete = 1--TODO: IDK but you should probably add both of these
ORDER BY RowID, [Column], Data

SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
                                '],[' + t.[Column]
                        FROM    #TT2 AS t
                        --ORDER BY '],[' + t.ID
                        FOR XML PATH('')
                      ), 1, 2, '') + ']'

SET @query = N'SELECT RowID,'+ @cols +' FROM
(SELECT tt2.RowID,tt2.[Column] , tt2.Data FROM #tt2 AS tt2) p
PIVOT (max([data]) FOR [Column] IN ( '+ @cols +'))
AS pvt;'

EXECUTE(@query)

drop table #TT2

END TRY
BEGIN CATCH
    --TODO: PROPER CATCH
END CATCH
</code>```

Body:
So, i'm going to try and take a crack at what you have been getting help with Kannan on.
It sounds like you have two different queries to the database:
    1) Query results of the list of 'Type(s)' for your dropdown,(You should be able to do this fairly easily)
    2) query results of the list of 'Propert(ies)', 'Row(s)', and 'value(s) that match the selected 'Type' in the dropdown  as a table with the properties as the header to set table.

To me it seems the easest and best way to handle this would be to get the data back using Kannan's script (probably inside of a stored procedure and maybe a view?)  and create the grid in code from your back-end application, or front end client. However, if you cant, here is a script that should work or at the least get you started.

I would suggest maybe creating two stored procs, one to retrieve the data, and another to pivot using dynamic sql.

CREATE PROCEDURE dbo.EAV_GridGenerator
    @TypeId int = 0,
    @param2 int
AS
BEGIN TRY
DECLARE @cols varchar(max),
        @query varchar(max);
        --TODO: CLEAN UP VARIABLE NAMES THROUGHOUT
SELECT trow.TypesId, tprop.PropertyName AS [Column], trow.TypeRowId AS [RowID], tval.Value AS [Data]
INTO #TT2
FROM dbo.[Types] AS t
    JOIN dbo.TypeRow trow
        ON t.typesId = trow.typesId
        JOIN dbo.TypeValue tval
            ON tval.TypeRowsId = trow.TypeRowId
            JOIN dbo.[TypeProperty] tprop
                ON tval.TypesPropertyId = tprop.TypePropertyId
WHERE trow.TypesId = @TypeId
    --AND  t.IsActive = 1   AND  tprop.IsActive = 1 AND  trow.IsActive = 1  AND  tval.IsActive = 1--TODO: IDK but you should probably add both of these
--      AND t.IsDelete = 1  AND  tprop.IsDelete = 1 AND  trow.IsDelete = 1  AND  tval.IsDelete = 1--TODO: IDK but you should probably add both of these
ORDER BY RowID, [Column], Data

SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
                                '],[' + t.[Column]
                        FROM    #TT2 AS t
                        --ORDER BY '],[' + t.ID
                        FOR XML PATH('')
                      ), 1, 2, '') + ']'

SET @query = N'SELECT RowID,'+ @cols +' FROM
(SELECT tt2.RowID,tt2.[Column] , tt2.Data FROM #tt2 AS tt2) p
PIVOT (max([data]) FOR [Column] IN ( '+ @cols +'))
AS pvt;'

EXECUTE(@query)

drop table #TT2

END TRY
BEGIN CATCH
    --TODO: PROPER CATCH
END CATCH


来源: stackexchange

问:
Add slideshow function to gallery using Jquery or javascript
What I would like to achieve is a button on toggle that will trigger an automatic slideshow. Like a play/pause button.

I'm using an image gallery from html5up.net the template is here:

https://html5up.net/lens

The next image is currently triggered on click with:

```<code><div class="nav-next"></div>
</code>```

Within the HTML the gallery appears as so, and clicking a thumb will activate the appropriate image.

```<code><section id="thumbnails">
<article>
<a class="thumbnail" href="images/fulls/114.png">
<img src="images/thumbs/114.jpg"/></a>
</article>

<article>
<a class="thumbnail" href="images/fulls/116.png">
<img src="images/thumbs/116.jpg"/></a>
</article>

<article>
<a class="thumbnail" href="images/fulls/168.png">
<img src="images/thumbs/168.jpg"/></a>
</article>
</section>
</code>```

I'm trying variations of attempts as such:

```<code>function slideSwitch() {
    var $active = $('.thumbnail');
    var $next = $active.next();

    $next.addClass('active');

    $active.removeClass('active');
}

$(function() {
    setInterval( "slideSwitch()", 5000 );
});
</code>```

However have only achieved frustration at this point as I'm not sure what I'm missing.

Here's a minimal version of the gallery if you want to experiment:

https://codepen.io/anon/pen/VWwVqd

答:
Have you included the jQuery Plugin on your page head?</p>

```<code><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What I would like to achieve is a button on toggle that will trigger an automatic slideshow. Like a play/pause button.

I'm using an image gallery from html5up.net the template is here:

https://html5up.net/lens

The next image is currently triggered on click with:

Within the HTML the gallery appears as so, and clicking a thumb will activate the appropriate image.

I'm trying variations of attempts as such:

function slideSwitch() {
    var $active = $('.thumbnail');
    var $next = $active.next();

    $next.addClass('active');

    $active.removeClass('active');
}

$(function() {
    setInterval( "slideSwitch()", 5000 );
});

However have only achieved frustration at this point as I'm not sure what I'm missing.

Here's a minimal version of the gallery if you want to experiment:

https://codepen.io/anon/pen/VWwVqd

Body:
Have you included the jQuery Plugin on your page head?

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>


问:
Can i publish android studio project on iphone app store?
I am still a beginner and I really don't know much and am working on my first app on android studio.
So is it possible to publish android studio project on iPhone App Store? If not is there any other way to do that?</p>

答:
android application is mainly build based on java program. ios application is build based on objective C.Its not because of programming language but rather due to final package its get compressed.

You can try learning xamarin cross platform native app development.

or

use ionic 2 framework. App Development based on HTML5,jss,css. Which use simple webview to display the content. That can be converted to any platform.


问:
Tips for Securing a LAMP Server
what are the absolute security guidelines for  a server with LAMP stack?</p>

答:
I recommend you try denyhosts if you are using ssh to auto-ban IPs that try to hack your server using basic scripting techniques.

Also be sure your site folders (i.e. /var/www/) are owned by the server "user" this is somtimes "www-data" or "nobody" and I think even occasionally "apache", depending on your distro etc. From then on, be careful about the permissions, I'm sure you can google for permissions for web folders.

Update early and often (make backups before you do).

ContentLicense: CC BY-SA 2.5

Title: Tips for Securing a LAMP Server


问:
how do I get only text field data from django modelform for email submission?
how do I get only the text field data from a django modelform for email submission?  Ive tried a lot of variations in the view, cleaned_data.get() def clean(self): methods etc.  Not sure why this is so hard.

```<code># models.py - service model
class Service(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    service_type = models.ManyToManyField('ServiceType')
    description = models.TextField(blank=True)

    def __str__(self):
        return "Service Order for: {user}".format(user=self.user)

class ServiceType(models.Model):
    label = models.CharField(max_length=200, unique=True)

    def __str__(self):
        return self.label

# forms.py
class NewServiceForm(forms.ModelForm):
    accept_tos = forms.BooleanField(required=True)

    class Meta:
        model = Service
        fields = '__all__'
        exclude = ('user', 'created_at',)

# views.py
@login_required
def newservice(request):
    if request.method == 'POST':
        form = NewServiceForm(request.POST)
        if form.is_valid():
            form.instance.user = request.user
            service = form.save()

# SEND EMAIL - send copy of project/service modelform data to user and site owner

            name = request.user.first_name+request.user.last_name
            username = request.user.username
            subject = 'New Service Order'
            from_email = request.user.email
            service_data = form.cleaned_data
            message = ''' From:    {}    {}    {}
            \n {}
            \n {}
            '''.format(name, from_email, username, subject, service_data)
            recipients = ['mytestemail@gmail.com', request.user.email]
            try:
                send_mail(subject, message, from_email, recipients)
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
# END EMAIL
            messages.warning(request, 'Success! Your service order has been submitted.')
            return redirect('projects')

        else:
            messages.error(request, 'Invalid submission, check and try again.')
    else:
        form = NewServiceForm()

    return render(request, 'dashboard/newservice.html', {'form': form})

# newservice.html

<form method="post" id="newprojectform">
            {% csrf_token %}

         Service Type <br> {{ form.service_type }} <br><br>
                  {{ form.accept_tos }} <br><br>
       Description  {{ form.description }} <br><br>
       <button class="btn btn-sm" type="submit">Submit</button>
                </div>
</form>
</code>```

Im getting wrong output sent to my email inbox below: I just want text output of choices, and description sent to my email inbox (and not boolean=True), ie  'Edit Content Add Content  Test Description goes here'

```<code> {'service_type': <QuerySet [<ServiceType: Edit Content>, <ServiceType: Add Content>, 'accept_tos': True, 'description': 'Test Description goes here'}
</code>```

答: after lots of issues with m2m form field data retrieval I pulled data from the created model using project = form.save()  object.  much strife, but somewhat easier solution.</p>

Body:
how do I get only the text field data from a django modelform for email submission?  Ive tried a lot of variations in the view, cleaned_data.get() def clean(self): methods etc.  Not sure why this is so hard.

# models.py - service model
class Service(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    service_type = models.ManyToManyField('ServiceType')
    description = models.TextField(blank=True)

    def __str__(self):
        return "Service Order for: {user}".format(user=self.user)

class ServiceType(models.Model):
    label = models.CharField(max_length=200, unique=True)

    def __str__(self):
        return self.label

# forms.py
class NewServiceForm(forms.ModelForm):
    accept_tos = forms.BooleanField(required=True)

    class Meta:
        model = Service
        fields = '__all__'
        exclude = ('user', 'created_at',)

# views.py
@login_required
def newservice(request):
    if request.method == 'POST':
        form = NewServiceForm(request.POST)
        if form.is_valid():
            form.instance.user = request.user
            service = form.save()

# SEND EMAIL - send copy of project/service modelform data to user and site owner

            name = request.user.first_name+request.user.last_name
            username = request.user.username
            subject = 'New Service Order'
            from_email = request.user.email
            service_data = form.cleaned_data
            message = ''' From:    {}    {}    {}
            \n {}
            \n {}
            '''.format(name, from_email, username, subject, service_data)
            recipients = ['mytestemail@gmail.com', request.user.email]
            try:
                send_mail(subject, message, from_email, recipients)
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
# END EMAIL
            messages.warning(request, 'Success! Your service order has been submitted.')
            return redirect('projects')

        else:
            messages.error(request, 'Invalid submission, check and try again.')
    else:
        form = NewServiceForm()

    return render(request, 'dashboard/newservice.html', {'form': form})

# newservice.html

<form method="post" id="newprojectform">
            {% csrf_token %}

         Service Type
 {{ form.service_type }}

                  {{ form.accept_tos }}

       Description  {{ form.description }}

       <button class="btn btn-sm" type="submit">Submit</button>

</form>

Im getting wrong output sent to my email inbox below: I just want text output of choices, and description sent to my email inbox (and not boolean=True), ie  'Edit Content Add Content  Test Description goes here'

 {'service_type': <QuerySet [<ServiceType: Edit Content>, <ServiceType: Add Content>, 'accept_tos': True, 'description': 'Test Description goes here'}


问:
In JavaScript, can you force a loop to not process the next iteration before the current iteration is complete?
I have a data set which contains an array of layers for an HTML5 canvas. I’m using fabric.js to manage all elements of my canvas. The layers are supposed to load in order, forming different scenes. I’m looping through the data set via a forEach loop. (EDIT - after further research, I see that both for and forEach loops are synchronous).

The problem is, once the code gets to the point of loading an image, asynchronous behavior kicks in and the process jumps to the next iteration of my loop to start processing the next layer. As you can imagine, this leads to layers appearing out of order on the canvas and ultimately distorted scenes.

I’ve been working on this and researching it for weeks and haven’t had much luck.

Is there any way to prevent a forEach loop (or a for loop for that matter) to not start the next iteration before the current one finishes?

Here is my code for the forEach loop:

```<code>$.ajax({
    url: url,
    method: "GET"
}).done(function (data) {
    data.forEach(function (data) {
        switch (data.layer_type) {
            case "texture":
                {
                    addTexture(data)
                    break;
                }
            case "color":
                {
                    addColor(data)
                    break;
                }
            case "room":
                {
                    addBaseImg(data);
                    break;
                }
            case "decor":
                {
                    addBaseImg(data);
                    break;
                }
            case "floor":
                {
                    addBaseImg(data);
                    break;
                }
            default:
                {
                    addOtherObjects(data);
                }
        }
    });
});
</code>```

Here is an example of a case that loads an image:

The initial function triggers a click event:

```<code>function addTexture(data) {
    $('img[data-obj-id="' + data.object_id + '"]').trigger("click");
}
</code>```

that leads to this function:

```<code>$(document).on("click", ".img-patt", function () {

    var imgURL = $(this).data("src");

    var _this = this;

    //this is where the process skips to the next iteration, before the image is loaded and added to the canvas

    fabric.Image.fromURL(imgURL, function (img) {

        //some code to handle the pattern removed from here just to shorten up the snippet

        var rect = new fabric.Rect({
            name: "texture",
            visible: true,
            selectable: false,
            data: {
                type: $(_this).data("type"),
                objid: $(_this).data("obj-id")
            },
            top: 0,
            left: 0,
            width: fabCanvas.width,
            height: fabCanvas.height,
            fill: pattern
        });

        fabCanvas.add(rect);
        fabCanvas.renderAll();
    });

});
</code>```

答:
If you want to handle it manually instead of relying on some kind of Promise implementation ( bluebird for example ) you can use this logic.

Overall looks more complicated, but apart the fact that should work, when you see and undertand this, adding your application knowledge you will be able to do something smaller, better.

The concept is not adding the images on canvas but create an ordered array of objects already loaded, then when you load them all, add that array of object on the canvas.

Your onclick becomes:

```<code>function addToCanvas(object) {
  canvas.add(object);
}

$(document).on("click", ".img-patt", function () {

   var imgURL = $(this).data("src");

   addSomething(imgUrl, null, null, addToCanvas)

});
</code>```

Your add something is:

```<code>function addSomething(imgUrl, index, objectStack, callback) {

        //this is where the process skips to the next iteration, before the image is loaded and added to the canvas

        fabric.Image.fromURL(imgURL, function (img) {

            //some code to handle the pattern removed from here just to shorten up the snippet

            var rect = new fabric.Rect({
                name: "texture",
                visible: true,
                selectable: false,
                data: {
                    type: $(_this).data("type"),
                    objid: $(_this).data("obj-id")
                },
                top: 0,
                left: 0,
                width: fabCanvas.width,
                height: fabCanvas.height,
                fill: pattern
            });

            objectStack && objectStack[index] = rect;
            callback(rect)
          });
}
</code>```

You main loop becomes: (for loop and forEach are both sincronous)

```<code>$.ajax({
    url: url,
    method: "GET"
}).done(function (data) {
    var objectStack = new Array(data.length);
    var loaded = data.length;
    var onFinish = function() {
      loaded--
      if (loaded === 0) {
        objectStack.forEach(function(object) {
          canvas.add(object);
        });
      }
    }
    data.forEach(function (data, index) {
        var src = $('img[data-obj-id="' + data.object_id + '"]').data('src');
        switch (data.layer_type) {
            case "texture":
                {
                    addSomething(src, index, objectStack, onFinish)
                    break;
                }
            case "color":
                {
                   ...
                }
            case "room":
                {
                    ...
                }
            case "decor":
                {
                   ...
                }
            case "floor":
                {
                    ...
                }
            default:
                {
                    ...
                }
        }
    });
});
</code>```

Body:
I have a data set which contains an array of layers for an HTML5 canvas. I’m using fabric.js to manage all elements of my canvas. The layers are supposed to load in order, forming different scenes. I’m looping through the data set via a forEach loop. (EDIT - after further research, I see that both for and forEach loops are synchronous).

The problem is, once the code gets to the point of loading an image, asynchronous behavior kicks in and the process jumps to the next iteration of my loop to start processing the next layer. As you can imagine, this leads to layers appearing out of order on the canvas and ultimately distorted scenes.

I’ve been working on this and researching it for weeks and haven’t had much luck.

Is there any way to prevent a forEach loop (or a for loop for that matter) to not start the next iteration before the current one finishes?

Here is my code for the forEach loop:

$.ajax({
    url: url,
    method: "GET"
}).done(function (data) {
    data.forEach(function (data) {
        switch (data.layer_type) {
            case "texture":
                {
                    addTexture(data)
                    break;
                }
            case "color":
                {
                    addColor(data)
                    break;
                }
            case "room":
                {
                    addBaseImg(data);
                    break;
                }
            case "decor":
                {
                    addBaseImg(data);
                    break;
                }
            case "floor":
                {
                    addBaseImg(data);
                    break;
                }
            default:
                {
                    addOtherObjects(data);
                }
        }
    });
});

Here is an example of a case that loads an image:

The initial function triggers a click event:

function addTexture(data) {
    $('img[data-obj-id="' + data.object_id + '"]').trigger("click");
}

that leads to this function:

$(document).on("click", ".img-patt", function () {

    var imgURL = $(this).data("src");

    var _this = this;

    //this is where the process skips to the next iteration, before the image is loaded and added to the canvas

    fabric.Image.fromURL(imgURL, function (img) {

        //some code to handle the pattern removed from here just to shorten up the snippet

        var rect = new fabric.Rect({
            name: "texture",
            visible: true,
            selectable: false,
            data: {
                type: $(_this).data("type"),
                objid: $(_this).data("obj-id")
            },
            top: 0,
            left: 0,
            width: fabCanvas.width,
            height: fabCanvas.height,
            fill: pattern
        });

        fabCanvas.add(rect);
        fabCanvas.renderAll();
    });

});

Body:
If you want to handle it manually instead of relying on some kind of Promise implementation ( bluebird for example ) you can use this logic.

Overall looks more complicated, but apart the fact that should work, when you see and undertand this, adding your application knowledge you will be able to do something smaller, better.

The concept is not adding the images on canvas but create an ordered array of objects already loaded, then when you load them all, add that array of object on the canvas.

Your onclick becomes:

function addToCanvas(object) {
  canvas.add(object);
}

$(document).on("click", ".img-patt", function () {

   var imgURL = $(this).data("src");

   addSomething(imgUrl, null, null, addToCanvas)

});

Your add something is:

function addSomething(imgUrl, index, objectStack, callback) {

        //this is where the process skips to the next iteration, before the image is loaded and added to the canvas

        fabric.Image.fromURL(imgURL, function (img) {

            //some code to handle the pattern removed from here just to shorten up the snippet

            var rect = new fabric.Rect({
                name: "texture",
                visible: true,
                selectable: false,
                data: {
                    type: $(_this).data("type"),
                    objid: $(_this).data("obj-id")
                },
                top: 0,
                left: 0,
                width: fabCanvas.width,
                height: fabCanvas.height,
                fill: pattern
            });

            objectStack && objectStack[index] = rect;
            callback(rect)
          });
}

You main loop becomes: (for loop and forEach are both sincronous)

$.ajax({
    url: url,
    method: "GET"
}).done(function (data) {
    var objectStack = new Array(data.length);
    var loaded = data.length;
    var onFinish = function() {
      loaded--
      if (loaded === 0) {
        objectStack.forEach(function(object) {
          canvas.add(object);
        });
      }
    }
    data.forEach(function (data, index) {
        var src = $('img[data-obj-id="' + data.object_id + '"]').data('src');
        switch (data.layer_type) {
            case "texture":
                {
                    addSomething(src, index, objectStack, onFinish)
                    break;
                }
            case "color":
                {
                   ...
                }
            case "room":
                {
                    ...
                }
            case "decor":
                {
                   ...
                }
            case "floor":
                {
                    ...
                }
            default:
                {
                    ...
                }
        }
    });
});


问:
how to skip constructor call from unit test?
I am executing unit test for one of class method "Execute", but don't want to execute class constructor code.

Is there any way to skip constructor code call from the unit test execution?

Class Code,

```<code>public class DemoCls
{
    public DemoCls()
    {
        string ConfigFolderPath = Path.Combine(Environment.CurrentDirectory, @"\Config");
        //string dataFolder = @"C:\Data1";
        foreach (string X in Directory.EnumerateFiles(ConfigFolderPath, "test" + "*.xml"))
        {
        }
    }

    public void Execute()
    {

    }
}
</code>```

Unit Test Code,

```<code>[TestClass()]
public class DemoClsTests
{
    [TestMethod()]
    public void ExecuteTest()
    {
        var X = new DemoCls();
        X.Execute();
    }
}
</code>```

答:
You can use a unit testing frameworks that allows you to mock concrete classes in order to fake a class without an interface, for example i'm using Typemock Isolator and with that i can mock almost any class and decide what is happening with all the class's members and its constructor.
here is a test for the class that you had in your question:</p>

```<code>[TestMethod,Isolated]
public void TestMethod()
{
    var fake = Isolate.Fake.Instance<DemoCls>(Members.CallOriginal, ConstructorWillBe.Ignored);
    fake.Execute();

    Isolate.Verify.WasCalledWithAnyArguments(() => fake.Execute());
}
</code>```

Body:
I am executing unit test for one of class method "Execute", but don't want to execute class constructor code.

Is there any way to skip constructor code call from the unit test execution?

Class Code,

public class DemoCls
{
    public DemoCls()
    {
        string ConfigFolderPath = Path.Combine(Environment.CurrentDirectory, @"\Config");
        //string dataFolder = @"C:\Data1";
        foreach (string X in Directory.EnumerateFiles(ConfigFolderPath, "test" + "*.xml"))
        {
        }
    }

    public void Execute()
    {

    }
}

Unit Test Code,

[TestClass()]
public class DemoClsTests
{
    [TestMethod()]
    public void ExecuteTest()
    {
        var X = new DemoCls();
        X.Execute();
    }
}

Body:
You can use a unit testing frameworks that allows you to mock concrete classes in order to fake a class without an interface, for example i'm using Typemock Isolator and with that i can mock almost any class and decide what is happening with all the class's members and its constructor.
here is a test for the class that you had in your question:

[TestMethod,Isolated]
public void TestMethod()
{
    var fake = Isolate.Fake.Instance<DemoCls>(Members.CallOriginal, ConstructorWillBe.Ignored);
    fake.Execute();

    Isolate.Verify.WasCalledWithAnyArguments(() => fake.Execute());
}


问:
How to enable/access the Confluence API from a Confluence Server running in a Docker container
I am running a Confluence server using the official Docker container: atlassian/confluence-server: https://hub.docker.com/r/atlassian/confluence-server/

I would like now to access the Confluence REST API: https://docs.atlassian.com/atlassian-confluence/REST/latest-server/

I see that the container exposes 2 ports: 8090 and 8091. I can get the Confluence UI on the former. Is the latter supposed to be an API port?

I have checked also the plugins if I have to install a plugin. But I haven't found anything.

Maybe I have to send more variables or expose more ports from the docker command?

答:
Found it!

The API need no further configuration. It is available on the same port as the UI. So, in the case of the default configuration of the atlassian/confluence-server, the API is available under:

```<code>http://localhost:8090/rest/api/content
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Found it!

The API need no further configuration. It is available on the same port as the UI. So, in the case of the default configuration of the atlassian/confluence-server, the API is available under:

http://localhost:8090/rest/api/content


问:
To modify SecurityContext only for Current request
I am using Spring Boot+spring session data rediss

My scenario is UserA has logged in and JSESSIONID is created for UserA, now he issues a token which will be sent to some machine and is valid for few minutes to work on his behalf.
Issue is if accidently some client passes both Cookie and token then I want to give preference to TOKEN rather than JSESSIONID is it possible in Spring Session.
I cannot invalidate the cookie session as it will logout the UserA which is not desired.

So, I want to tell spring wether to use existing session or create a new one based on some condition and want to give preference to TOKEN. And to create a completely new session without invalidating Cookie session.

答:
Reading the official documentation.

From this

```<code>@EnableRedisHttpSession
public class Config {

        @Bean
        public LettuceConnectionFactory connectionFactory() {
                return new LettuceConnectionFactory();
        }
}
</code>```

It's done by default.

The @EnableRedisHttpSession annotation creates a Spring Bean with the name of springSessionRepositoryFilter that implements Filter. The filter is what is in charge of replacing the HttpSession implementation to be backed by Spring Session. In this instance Spring Session is backed by Redis.

We create a RedisConnectionFactory that connects Spring Session to the Redis Server. We configure the connection to connect to localhost on the default port (6379) For more information on configuring Spring Data Redis, refer to the reference documentation.

The DelegatingFilterProxy will look up a Bean by the name of springSessionRepositoryFilter and cast it to a Filter. For every request that DelegatingFilterProxy is invoked, the springSessionRepositoryFilter will be invoked.

So, what you have to do, it's avoid the Spring Configuration, or looking for if you want modify this default behavior somehow to create your own DelegatingFilterProxy implementation and setup it in your ServletContext Filter chain.

Body:
Reading the official documentation.

From this

@EnableRedisHttpSession
public class Config {

        @Bean
        public LettuceConnectionFactory connectionFactory() {
                return new LettuceConnectionFactory();
        }
}

It's done by default.

The @EnableRedisHttpSession annotation creates a Spring Bean with the name of springSessionRepositoryFilter that implements Filter. The filter is what is in charge of replacing the HttpSession implementation to be backed by Spring Session. In this instance Spring Session is backed by Redis.

We create a RedisConnectionFactory that connects Spring Session to the Redis Server. We configure the connection to connect to localhost on the default port (6379) For more information on configuring Spring Data Redis, refer to the reference documentation.

The DelegatingFilterProxy will look up a Bean by the name of springSessionRepositoryFilter and cast it to a Filter. For every request that DelegatingFilterProxy is invoked, the springSessionRepositoryFilter will be invoked.

So, what you have to do, it's avoid the Spring Configuration, or looking for if you want modify this default behavior somehow to create your own DelegatingFilterProxy implementation and setup it in your ServletContext Filter chain.


问:
sort 2D int array JAVA
I have one 2 dimensional array
It's an array with 7 int in line and more lines.

```<code>int[][] new arr=new[7][100];
</code>```

number in line is ranked.

I need a ranked array.

for example

```<code>9 4 15 22 32 47 50
1 5 9 12 19 25 36
22 23 25 29 36 55 99
1 5 11 12 19 25 36
</code>```

after sort

```<code>1 5 9 12 19 25 36
1 5 11 12 19 25 36
9 4 15 22 32 47 50
22 23 25 29 36 55 99
</code>```

答:
I would do something like this,or something similar:

I saw something similar  in Stack Overflow: https://stackoverflow.com/a/15452462/8024829.

```<code> double[][] array= {
   {1, 5},
   {13, 1.55},
   {12, 100.6},
   {12.1, .85} };

   java.util.Arrays.sort(array, new java.util.Comparator<double[]>() {
       public int compare(double[] a, double[] b) {
           return Double.compare(a[0], b[0]);
       }
   });
</code>```

Title: sort 2D int array JAVA

Body:
I have one 2 dimensional array
It's an array with 7 int in line and more lines.

int[][] new arr=new[7][100];

number in line is ranked.

I need a ranked array.

for example

9 4 15 22 32 47 50
1 5 9 12 19 25 36
22 23 25 29 36 55 99
1 5 11 12 19 25 36

after sort

1 5 9 12 19 25 36
1 5 11 12 19 25 36
9 4 15 22 32 47 50
22 23 25 29 36 55 99

Body:
I would do something like this,or something similar:

I saw something similar  in Stack Overflow: https://stackoverflow.com/a/15452462/8024829.

 double[][] array= {
   {1, 5},
   {13, 1.55},
   {12, 100.6},
   {12.1, .85} };

   java.util.Arrays.sort(array, new java.util.Comparator<double[]>() {
       public int compare(double[] a, double[] b) {
           return Double.compare(a[0], b[0]);
       }
   });


问:
AVFoundation - Adding blur background to video
I am working on a video editing app in Swift. In my case my output video looks like as following

I am trying to fill the black portion with blur effect exactly like this

I searched but didn't get any working solution. Any assistance would be a great help.

答:
Starting from iOS 9.0 You can use AVAsynchronousCIImageFilteringRequest

see docs for more info

Or You can use AVVideoCompositing
see example of usage


问:
Applescript: Strange characters ("¬†") replacing space
I've got a simple code reading a text file into a list. It's a list of CMYK values in this format: 00, 100, 64, 33. For some reason, the output is replacing spaces with strange characters... "¬†" (return and dagger?).

So this script:

```<code>set cmykList to {}
set eachLine to paragraphs of (read POSIX file "/Users/me/Desktop/cmyk.txt")
repeat with nextLine in eachLine
    if length of nextLine is greater than 0 then
        copy (nextLine as text) to the end of cmykList
    end if
end repeat
choose from list cmykList
</code>```

returns:
00,¬†100,¬†64,¬†33,
00,¬†00,¬†00,¬†00,
100,¬†72,¬†00,
100,¬†35,¬†00,¬†100

Any ideas on why this is, and how I can avoid this?

The text file is set up like so:

```<code>00, 100, 64, 33
00, 00, 00, 00
100, 72, 00, 18
100, 35, 00, 100
00, 16, 100, 00
00, 100, 63, 29
00, 66, 100, 07
03, 00, 00, 32
100, 35, 00, 100
00, 100, 81, 04
04, 02, 00, 45
00, 00, 00, 00
03, 00, 00, 32
100, 35, 00, 100
</code>```

Edit: Resolved this issue doing a find / replace:

```<code>set cmykList to {}
set eachLine to paragraphs of (read POSIX file "/Users/me/Desktop/cmyk.txt")
repeat with nextLine in eachLine
    if length of nextLine is greater than 0 then
        set theText to (nextLine as text)
        set AppleScript's text item delimiters to "¬†"
        set theTextItems to text items of theText
        set AppleScript's text item delimiters to " "
        set theText to theTextItems as string
        set AppleScript's text item delimiters to {""}
        copy (theText as text) to the end of cmykList
    end if
end repeat
set chooseList to choose from list cmykList
</code>```

But still very curious as to why this happened in the first place.

答:
Those two characters (ASCII 194 160) are the UTF-8 representation of a Unicode NO-BREAK SPACE character.

You don't specify the source of your text file but wherever it's coming from is using non-breaking spaces instead of regular spaces. As you found out, you can fix the issue by replacing them with regular spaces when you read the file in.

Body:
I've got a simple code reading a text file into a list. It's a list of CMYK values in this format: 00, 100, 64, 33. For some reason, the output is replacing spaces with strange characters... "¬†" (return and dagger?).

So this script:

set cmykList to {}
set eachLine to paragraphs of (read POSIX file "/Users/me/Desktop/cmyk.txt")
repeat with nextLine in eachLine
    if length of nextLine is greater than 0 then
        copy (nextLine as text) to the end of cmykList
    end if
end repeat
choose from list cmykList

returns:
00,¬†100,¬†64,¬†33,
00,¬†00,¬†00,¬†00,
100,¬†72,¬†00,
100,¬†35,¬†00,¬†100

Any ideas on why this is, and how I can avoid this?

The text file is set up like so:

00, 100, 64, 33
00, 00, 00, 00
100, 72, 00, 18
100, 35, 00, 100
00, 16, 100, 00
00, 100, 63, 29
00, 66, 100, 07
03, 00, 00, 32
100, 35, 00, 100
00, 100, 81, 04
04, 02, 00, 45
00, 00, 00, 00
03, 00, 00, 32
100, 35, 00, 100

Edit: Resolved this issue doing a find / replace:

set cmykList to {}
set eachLine to paragraphs of (read POSIX file "/Users/me/Desktop/cmyk.txt")
repeat with nextLine in eachLine
    if length of nextLine is greater than 0 then
        set theText to (nextLine as text)
        set AppleScript's text item delimiters to "¬†"
        set theTextItems to text items of theText
        set AppleScript's text item delimiters to " "
        set theText to theTextItems as string
        set AppleScript's text item delimiters to {""}
        copy (theText as text) to the end of cmykList
    end if
end repeat
set chooseList to choose from list cmykList

But still very curious as to why this happened in the first place.


问:
Python For i in range(len(str)): last iteration prints None
```<code>def fun(str):
    for i in range(len(str)):
        print(i)

string = 'abc'

print(fun(string))
</code>```

print results are

```<code>0
1
2
None
</code>```

if I change

```<code>for i in range(len(str)-1):
</code>```

the last result is still None

Why is this?
And how do I stop it?

答:
When you call print(fun('abc')), you first call fun, which indeed prints 1, 2 and 3, once fun completes, you print its return value. Since you didn't explicitly return anything, Python implicitly returns None for you.

To make a long story short - don't call print on fun, just call fun:

```<code>string = 'abc'

fun(string) # Here
</code>```

Body:
def fun(str):
    for i in range(len(str)):
        print(i)

string = 'abc'

print(fun(string))

print results are

0
1
2
None

if I change

for i in range(len(str)-1):

the last result is still None

Why is this?
And how do I stop it?

Body:
When you call print(fun('abc')), you first call fun, which indeed prints 1, 2 and 3, once fun completes, you print its return value. Since you didn't explicitly return anything, Python implicitly returns None for you.

To make a long story short - don't call print on fun, just call fun:

string = 'abc'

fun(string) # Here


答:
You are getting 0, 1, 2 from the print statement in fun function while None is getting printed by:

```<code>print(fun(string))
</code>```

Since, by default a python function returns None that's why you are getting it here. You can directly call it without print statement.

```<code>fun(string)
</code>```

Title: Python For i in range(len(str)): last iteration prints None

Body:
You are getting 0, 1, 2 from the print statement in fun function while None is getting printed by:

print(fun(string))

Since, by default a python function returns None that's why you are getting it here. You can directly call it without print statement.

fun(string)


问:
Start search after 3 characters typed in selectize.js single item select
In Selectize single item select, a search is started after the first character is typed into the select box.

I need the search to not start until after inputing three characters in the search box.

Can any one suggest how to do this?

答:
In Selectize demo examples you can find this line:

```<code>if (!query.length) return callback();
</code>```

You can change that to:

```<code>if (query.length < 3) return callback();
</code>```

As example, in my case where I get form Ajax call some "car/vechicles" list:

```<code>jQuery('#select-car').selectize({
    valueField: 'id',
    labelField: 'title',
    searchField: 'title',
    options: [],
    load: function(query, callback) {
    if (query.length < 3) return callback(); //if (!query.length)
    $.ajax({
        url: 'search/',
        type: 'GET',
        dataType: 'json',
        data: {
            car: query,
        },
        error: function() {
            callback();
        },
        success: function(res) {
            callback(res);
        }
    });
  }
});
</code>```

Regards.

Body:
In Selectize demo examples you can find this line:

if (!query.length) return callback();

You can change that to:

if (query.length < 3) return callback();

As example, in my case where I get form Ajax call some "car/vechicles" list:

jQuery('#select-car').selectize({
    valueField: 'id',
    labelField: 'title',
    searchField: 'title',
    options: [],
    load: function(query, callback) {
    if (query.length < 3) return callback(); //if (!query.length)
    $.ajax({
        url: 'search/',
        type: 'GET',
        dataType: 'json',
        data: {
            car: query,
        },
        error: function() {
            callback();
        },
        success: function(res) {
            callback(res);
        }
    });
  }
});

Regards.


问:
How to simulate sleep mode on Android emulator
Some users of my Android application report bugs when the mobile enters sleep/power saving mode.

I would like to test that issue on the Android Virtual Device. Is it possible to simulate the mobile entering in sleep/power saving mode on the AVD ?

Thanks in advance.

答:
On emulator, go Settings/Security/Screen lock change from 'None' to 'Swipe'

Then, click 'power' button on right control bar to turn off screen, and press again to turn on screen. Now the lock screen will show up.


问:
what is the purpose of this & symbol in this context?
```<code>public class WeatherAggregator {
    private List<WeatherSource> weatherSources;

    public WeatherAggregator(List<WeatherSource> weatherSources) {
        this.weatherSources = weatherSources;
    }

    public double getTemperature() {
        return weatherSources
            .stream()
            .mapToDouble(WeatherSource::getTemperatureCelcius)
            .average()
            .getAsDouble();
    }
}
</code>```

I searched about what does the & symbol here mean but I could not find any meaning to it ?!
can you tell what is going on in this line ?

```<code>private List<WeatherSource>weatherSources;
</code>```

答:
It is just HTML source encoding of the < and >. The following:

```<code>List<WeatherSource>
</code>```

is actually

```<code>List<WeatherSource>
</code>```

See here for the HTML escape characters

Body:
public class WeatherAggregator {
    private List<WeatherSource> weatherSources;

    public WeatherAggregator(List<WeatherSource> weatherSources) {
        this.weatherSources = weatherSources;
    }

    public double getTemperature() {
        return weatherSources
            .stream()
            .mapToDouble(WeatherSource::getTemperatureCelcius)
            .average()
            .getAsDouble();
    }
}

I searched about what does the & symbol here mean but I could not find any meaning to it ?!
can you tell what is going on in this line ?

private List<WeatherSource>weatherSources;

Body:
It is just HTML source encoding of the < and >. The following:

List&lt;WeatherSource&gt;

is actually

List<WeatherSource>

See here for the HTML escape characters


问:
classes of same module not available after using import
Below are my code in typescript

I have the below module which imports ts-events

```<code>import {SyncEvent} from 'ts-events'

module MyModule{
export class MyService{
    }
}
</code>```

I am trying to extend this MyService class in same module but in different file

```<code>module MyModule {

export class MyExtendedService extends MyService{ //this line throws compilation error
    }
}
</code>```

If I remove importing ts-events, its not throwing exception and working fine.
I tried the solution as in link, but not working. How can I overcome this

答:
module MyModule { ... } is the deprecated form of namespace MyModule { ... }

When you are writing module (ES2015/ES6/ESM or CommonJS), you typically do not need namespace.

The problem you have is that the namespace Mymodule in these two files are not shared. They don't mix together.

That's why you get the error of cannot find name MyService.

What you need to do is to get rid of the module MyModule {...}

```<code>// a.ts
export class MyService { ... }

// b.ts
import { MyService } form './a'
export class MyExtendedService extends MyService { ... }
</code>```

Body:
Below are my code in typescript

I have the below module which imports ts-events

import {SyncEvent} from 'ts-events'

module MyModule{
export class MyService{
    }
}

I am trying to extend this MyService class in same module but in different file

module MyModule {

export class MyExtendedService extends MyService{ //this line throws compilation error
    }
}

If I remove importing ts-events, its not throwing exception and working fine.
I tried the solution as in link, but not working. How can I overcome this

Body:
module MyModule { ... } is the deprecated form of namespace MyModule { ... }

When you are writing module (ES2015/ES6/ESM or CommonJS), you typically do not need namespace.

The problem you have is that the namespace Mymodule in these two files are not shared. They don't mix together.

That's why you get the error of cannot find name MyService.

What you need to do is to get rid of the module MyModule {...}

// a.ts
export class MyService { ... }

// b.ts
import { MyService } form './a'
export class MyExtendedService extends MyService { ... }


问:
Resolving spark dependencies using sbt
I was trying to build a very basic scala script having spark dependencies .
But I am not able to make the jar out of it .

The error generated :

sbt.ResolveException: unresolved dependency: org.apache.spark#spark-core_2.12;1.6.0-SNAPSHOT: not found

My build.sbt :

```<code>    import Dependencies._

    lazy val root = (project in file(".")).
     settings(
               inThisBuild(List(
                                 organization := "com.example",
                                 scalaVersion := "2.12.1",
                                 version      := "0.1.0-SNAPSHOT"
                              )),
               name := "Hello",
               libraryDependencies +=  "org.apache.spark" %% "spark-core" % "1.6.0-SNAPSHOT",
               resolvers += Resolver.mavenLocal
                )
</code>```

`

```<code>package example
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf

object Hello  {
     def main(args: Array[String]) {
           val logFile = "/Users/dhruvsha/Applications/spark/README.md"
           val conf = new SparkConf().setAppName("Simple Application")
           val sc = new SparkContext(conf)
           val logData = sc.textFile(logFile, 2).cache()
           val numAs = logData.filter(line => line.contains("a")).count()
           val numBs = logData.filter(line => line.contains("b")).count()
           println(s"Lines with a: $numAs, Lines with b: $numBs")
           sc.stop()
         }
}
</code>```

My source scala is in :

/exampleapp/main/scala/example/Hello.scala

Project name is exampleapp .

scala version 2.12.2

spark version 1.6.0

sbt version   0.13.13

Any sort of help will be appreciated and would be great if you could provide resources for learning about sbt and spark dependencies .

Please see I am new to scala, spark and sbt .

答:
The library dependencies line in build.sbt seems wrong

correct should be as

```<code>libraryDependencies += "org.apache.spark" % "spark-core_2.10" % "1.6.0"
</code>```

Title: Resolving spark dependencies using sbt

Body:
I was trying to build a very basic scala script having spark dependencies .
But I am not able to make the jar out of it .

The error generated :

sbt.ResolveException: unresolved dependency: org.apache.spark#spark-core_2.12;1.6.0-SNAPSHOT: not found

My build.sbt :

    import Dependencies._

    lazy val root = (project in file(".")).
     settings(
               inThisBuild(List(
                                 organization := "com.example",
                                 scalaVersion := "2.12.1",
                                 version      := "0.1.0-SNAPSHOT"
                              )),
               name := "Hello",
               libraryDependencies +=  "org.apache.spark" %% "spark-core" % "1.6.0-SNAPSHOT",
               resolvers += Resolver.mavenLocal
                )

`

package example
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf

object Hello  {
     def main(args: Array[String]) {
           val logFile = "/Users/dhruvsha/Applications/spark/README.md"
           val conf = new SparkConf().setAppName("Simple Application")
           val sc = new SparkContext(conf)
           val logData = sc.textFile(logFile, 2).cache()
           val numAs = logData.filter(line => line.contains("a")).count()
           val numBs = logData.filter(line => line.contains("b")).count()
           println(s"Lines with a: $numAs, Lines with b: $numBs")
           sc.stop()
         }
}

My source scala is in :

/exampleapp/main/scala/example/Hello.scala

Project name is exampleapp .

scala version 2.12.2

spark version 1.6.0

sbt version   0.13.13

Any sort of help will be appreciated and would be great if you could provide resources for learning about sbt and spark dependencies .

Please see I am new to scala, spark and sbt .

Body:
The library dependencies line in build.sbt seems wrong

correct should be as

libraryDependencies += "org.apache.spark" % "spark-core_2.10" % "1.6.0"


问:
How to resolve a jinja2.exceptions.TemplateSyntaxError?
I have HTML code like below:

 <title>Booking Lah</title>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      Booking Lah

 Sign Up

 Login

{{% for row in rows %}}

{{row["name"]}}

{{% endfor %}}

```

and I got an error like this:

jinja2.exceptions.TemplateSyntaxError
  TemplateSyntaxError: unexpected '%'
  File "/home/m26415086/UHTOS/templates/home.html", line 55, in template
  {{% for row in rows %}}

I'm already trying all I could but nothing change.

答:
in your template you are using {{% and %}} instead of {% and %}.

{% is for directives (loops, conditionals, ...) and {{ for substitution. here is the doc for further reference.

Body:
I have HTML code like below:

 <title>Booking Lah</title>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      Booking Lah

 Sign Up

 Login

{{% for row in rows %}}

{{row["name"]}}

{{% endfor %}}

and I got an error like this:

jinja2.exceptions.TemplateSyntaxError
  TemplateSyntaxError: unexpected '%'
  File "/home/m26415086/UHTOS/templates/home.html", line 55, in template
  {{% for row in rows %}}

I'm already trying all I could but nothing change.


问:
Persistence object cannot find persistence unit from persistence.xml
Environment: Windows 7, NetBean 6.9 (the one including GlassFish v3, Java EE 6), MySQL server

I've created tables in MySQL database and using NetBean's capability by right click on the project and choose "create entity from database" (Sorry if the wording is wrong because my NetBean is in Japanese)

This will create Entities.

Now I went to test if I can access DB through Entity Manager.

Tmp.java

```<code>package local.test.tmp;
import Resources.Users;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import java.util.List;
/**
 *
 * @author m-t
 */
public class Tmp {

    private static EntityManagerFactory factory;
    private static final String WEB_PU = "WebApplication1PU";

    public static void main(String args[]) {
        factory = Persistence.createEntityManagerFactory(WEB_PU);
        EntityManager em = factory.createEntityManager();
        //read existing entries and write to concole
        Query q = em.createQuery("select * from users");

        List<Users> userList = q.getResultList();
        for(Users u : userList) {
            System.out.println(u);
        }
    }
}
</code>```

persistence.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <!--   orignal
  <persistence-unit name="WebApplication1PU" transaction-type="JTA">
    <jta-data-source>masatoJNDI</jta-data-source>
    <properties/>
  </persistence-unit>
  -->

  <persistence-unit name="WebApplication1PU" transaction-type="JTA">
    <jta-data-source>masatoJNDI</jta-data-source>
    <properties>
        <property name="toplink.jdbc.user" value="masato" />
        <property name="toplink.jdbc.password" value="foobar" />
    </properties>
  </persistence-unit>
</persistence>
</code>```

When I run Tmp.java, I can see it fails at:

```<code>factory = Persistence.createEntityManagerFactory(WEB_PU);
</code>```

Error msg:

```<code>Exception in thread "main" javax.persistence.PersistenceException: No Persistence
provider for EntityManager named WebApplication1PU
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:84)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at local.test.tmp.Tmp.main(Tmp.java:24)
</code>```

I've checked the spelling of persistence unit "WebApplication1PU" in test code matches with with persistence.xml and it is correct.

persistence.xml is located ... it's in Japanese I don't know how in English :(

Let me try..

```<code>project
 |-------web page
 |-------test package
 |-------lib
 |-------enterprise bean
 |-------*** file  //blah file, I can't translate..
               |-----MNIFEST.MF
               |-----faces-cofig.xml
               |-----persistence.xml  //HERE!!
</code>```

Since the failure is at the beginning where Factory tries to locate persistence unit in persistence.xml, I am totally confused. Is there anything I should be verifying?

please let me know if you need more clarification.

UPDATE

I've tried suggested possible solutions but no luck.. Same error message is returned.
Yes, netbean 6.9 default provider is toplink.

What I did:

Added provider to persistence.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

  <persistence-unit name="NoJSFPU" transaction-type="JTA">
    <provider>oracle.toplink.essentials.PersistenceProvider</provider>
    <jta-data-source>masatoJNDI</jta-data-source>

    <properties>
        <property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/mytest"/>
        <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="toplink.jdbc.user" value="masato" />
        <property name="toplink.jdbc.password" value="mocha123" />
    </properties>
  </persistence-unit>
</persistence>
</code>```

Seems like most of people are being success with my situation. I am now start thinking there may be problem with how I run the test file or where the file is located?

Tmp.java that I executes from netbean is located at:

```<code>project
|------web page
|------source package
|          |-----------local.test.session
           |-----------local.test.tmp
                           |------------------Tmp.java //HERE
</code>```

I'm not sure if it matters though.

UPDATE 2

I've added toplink lib containing toplink-essential.jar and toplink-essential-agent.jar to the lib directory of my project and now I'm getting new error on top of original one but I believe I'm getting closer.

Looks like version attribute in persistence.xml has an issue...???

```<code>Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named WebApplication1PU: Provider named oracle.toplink.essentials.PersistenceProvider threw unexpected exception at create EntityManagerFactory:
oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Local Exception Stack:
Exception [TOPLINK-30005] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader@f6a746
Internal Exception: Exception [TOPLINK-30004] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while processing persistence.xml from URL: file:/C:/Users/m-takayashiki/Documents/NetBeansProjects/NoJSF/build/web/WEB-INF/classes/
Internal Exception:
(1. cvc-complex-type.3.1: Value '2.0' of attribute 'version' of element 'persistence' is not valid with respect to the corresponding attribute use. Attribute 'version' has a fixed value of '1.0'.)
        at oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:143)
        at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:169)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:110)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)
        at local.test.tmp.Tmp.main(Tmp.java:24)
</code>```

UPDATE 3

After some research, find out version number needs to be 1.0 compliant so did I applied the fix and got new error.

```<code> <?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="NoJSFPU" transaction-type="JTA">
    <provider>oracle.toplink.essentials.PersistenceProvider</provider>
    <jta-data-source>masatoJNDI</jta-data-source>
    <class>local.test.session.Addresses</class>
    <class>local.test.session.Users</class>
    <properties>
        <property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/mytest"/>
        <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="toplink.jdbc.user" value="masato" />
        <property name="toplink.jdbc.password" value="mocha123" />
    </properties>
  </persistence-unit>
</persistence>
</code>```

It's weird because I already specified class in persistence.xml above :(

```<code>Exception in thread "main" javax.persistence.PersistenceException: Exception [TOPLINK-7060]
 (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
Exception Description: Cannot acquire data source [masatoJNDI].
Internal Exception: javax.naming.NoInitialContextException: Need to specify class name in
 environment or system property, or as an applet parameter, or in an application resource
file:  java.naming.factory.initial
</code>```

UPDATE 4

I don't think this is called "solved" but after long try, I decided to just run my test code in the web app instead of running individually from netbean. I had to create web.xml myself since GlassFish does not provide it. (I see sun-web.xml but it wasn't the substitution) Then created servlet, define mapping in the web.xml and added my test code snippet to the servlet and tried on the browser. It worked, successfully obtained data from database.

I wonder what is the reason why it wasn't working when I try running just the Tmp.java (my test file) from Netbean...

答:
I think you may need to specify your persistence provider. See here.

For example:

```<code><provider>org.hibernate.ejb.HibernatePersistence</provider>
</code>```

or

```<code><provider>oracle.toplink.essentials.PersistenceProvider</provider>
</code>```

Your "original" persistence unit relies on the server to wire in details like the provider, but when you run it outside of the server context you need to specify a few things - one of them being the provider.

See here.

Body:
Environment: Windows 7, NetBean 6.9 (the one including GlassFish v3, Java EE 6), MySQL server

I've created tables in MySQL database and using NetBean's capability by right click on the project and choose "create entity from database" (Sorry if the wording is wrong because my NetBean is in Japanese)

This will create Entities.

Now I went to test if I can access DB through Entity Manager.

Tmp.java

package local.test.tmp;
import Resources.Users;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import java.util.List;
/**
 *
 * @author m-t
 */
public class Tmp {

    private static EntityManagerFactory factory;
    private static final String WEB_PU = "WebApplication1PU";

    public static void main(String args[]) {
        factory = Persistence.createEntityManagerFactory(WEB_PU);
        EntityManager em = factory.createEntityManager();
        //read existing entries and write to concole
        Query q = em.createQuery("select * from users");

        List<Users> userList = q.getResultList();
        for(Users u : userList) {
            System.out.println(u);
        }
    }
}

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

  <persistence-unit name="WebApplication1PU" transaction-type="JTA">
    <jta-data-source>masatoJNDI</jta-data-source>
    <properties>
        <property name="toplink.jdbc.user" value="masato" />
        <property name="toplink.jdbc.password" value="foobar" />
    </properties>
  </persistence-unit>
</persistence>

When I run Tmp.java, I can see it fails at:

factory = Persistence.createEntityManagerFactory(WEB_PU);

Error msg:

Exception in thread "main" javax.persistence.PersistenceException: No Persistence
provider for EntityManager named WebApplication1PU
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:84)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at local.test.tmp.Tmp.main(Tmp.java:24)

I've checked the spelling of persistence unit "WebApplication1PU" in test code matches with with persistence.xml and it is correct.

persistence.xml is located ... it's in Japanese I don't know how in English :(

Let me try..

project
 |-------web page
 |-------test package
 |-------lib
 |-------enterprise bean
 |-------*** file  //blah file, I can't translate..
               |-----MNIFEST.MF
               |-----faces-cofig.xml
               |-----persistence.xml  //HERE!!

Since the failure is at the beginning where Factory tries to locate persistence unit in persistence.xml, I am totally confused. Is there anything I should be verifying?

please let me know if you need more clarification.

UPDATE

I've tried suggested possible solutions but no luck.. Same error message is returned.
Yes, netbean 6.9 default provider is toplink.

What I did:

Added provider to persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

  <persistence-unit name="NoJSFPU" transaction-type="JTA">
    <provider>oracle.toplink.essentials.PersistenceProvider</provider>
    <jta-data-source>masatoJNDI</jta-data-source>

    <properties>
        <property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/mytest"/>
        <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="toplink.jdbc.user" value="masato" />
        <property name="toplink.jdbc.password" value="mocha123" />
    </properties>
  </persistence-unit>
</persistence>

Seems like most of people are being success with my situation. I am now start thinking there may be problem with how I run the test file or where the file is located?

Tmp.java that I executes from netbean is located at:

project
|------web page
|------source package
|          |-----------local.test.session
           |-----------local.test.tmp
                           |------------------Tmp.java //HERE

I'm not sure if it matters though.

UPDATE 2

I've added toplink lib containing toplink-essential.jar and toplink-essential-agent.jar to the lib directory of my project and now I'm getting new error on top of original one but I believe I'm getting closer.

Looks like version attribute in persistence.xml has an issue...???

Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named WebApplication1PU: Provider named oracle.toplink.essentials.PersistenceProvider threw unexpected exception at create EntityManagerFactory:
oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Local Exception Stack:
Exception [TOPLINK-30005] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader@f6a746
Internal Exception: Exception [TOPLINK-30004] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while processing persistence.xml from URL: file:/C:/Users/m-takayashiki/Documents/NetBeansProjects/NoJSF/build/web/WEB-INF/classes/
Internal Exception:
(1. cvc-complex-type.3.1: Value '2.0' of attribute 'version' of element 'persistence' is not valid with respect to the corresponding attribute use. Attribute 'version' has a fixed value of '1.0'.)
        at oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:143)
        at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:169)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:110)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)
        at local.test.tmp.Tmp.main(Tmp.java:24)

UPDATE 3

After some research, find out version number needs to be 1.0 compliant so did I applied the fix and got new error.

 <?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="NoJSFPU" transaction-type="JTA">
    <provider>oracle.toplink.essentials.PersistenceProvider</provider>
    <jta-data-source>masatoJNDI</jta-data-source>
    <class>local.test.session.Addresses</class>
    <class>local.test.session.Users</class>
    <properties>
        <property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/mytest"/>
        <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="toplink.jdbc.user" value="masato" />
        <property name="toplink.jdbc.password" value="mocha123" />
    </properties>
  </persistence-unit>
</persistence>

It's weird because I already specified class in persistence.xml above :(

Exception in thread "main" javax.persistence.PersistenceException: Exception [TOPLINK-7060]
 (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
Exception Description: Cannot acquire data source [masatoJNDI].
Internal Exception: javax.naming.NoInitialContextException: Need to specify class name in
 environment or system property, or as an applet parameter, or in an application resource
file:  java.naming.factory.initial

UPDATE 4

I don't think this is called "solved" but after long try, I decided to just run my test code in the web app instead of running individually from netbean. I had to create web.xml myself since GlassFish does not provide it. (I see sun-web.xml but it wasn't the substitution) Then created servlet, define mapping in the web.xml and added my test code snippet to the servlet and tried on the browser. It worked, successfully obtained data from database.

I wonder what is the reason why it wasn't working when I try running just the Tmp.java (my test file) from Netbean...

Body:
I think you may need to specify your persistence provider. See here.

For example:

<provider>org.hibernate.ejb.HibernatePersistence</provider>

or

<provider>oracle.toplink.essentials.PersistenceProvider</provider>

Your "original" persistence unit relies on the server to wire in details like the provider, but when you run it outside of the server context you need to specify a few things - one of them being the provider.

See here.


问:
How can I tell if I'm in a child shell
If I'm using bash and type bash I'm in the child shell and need to type exit to go back to the original parent shell. If I forget which one I'm in how do I check?

答:
Use the SHLVL environment variable.

man bash:

SHLVL : Incremented by one each time an instance of bash is started.

```<code>$ echo "$SHLV"
1

$ bash

$ echo "$SHLV"
2

$ exit

$ echo "$SHLV"
1
</code>```

Title: How can I tell if I'm in a child shell

Body:
Use the SHLVL environment variable.

man bash:

SHLVL : Incremented by one each time an instance of bash is started.

$ echo "$SHLV"
1

$ bash

$ echo "$SHLV"
2

$ exit

$ echo "$SHLV"
1


问:
Why reordering takes place with two volatile variables?
I'm trying to investigate the behaviour of reordering in java environment(using JDK 9-ea+170) and found one thing that i can't explain for myself, so i will be glad to hear some notes about it. Here's an example:

```<code>public class Client {
    int x;
    int y;
    public void test() {
        x++;
        y++;
    }
    public static void main(String[] args) {
        Client c = new Client();
        while(c.y <= c.x) new Thread(() -> c.test()).start();
        System.out.println(c.x + " " + c.y);
    }
}
</code>```

This program has a test() method which just increments x and y values. I'm creating new Threads and call this test() until some internal java optimizations are not changes an order of x++; y++; instructions(). This way i prove that reordering really takes place. And the program ends most of the time(which is expected).
 Now i've added volatile modifier to y:

```<code>public class Client {
    int x;
    volatile int y;
    public void test() {
        x++;
        y++;
    }
    public static void main(String[] args) {
        Client c = new Client();
        while(c.y <= c.x) new Thread(() -> c.test()).start();
        System.out.println(c.x + " " + c.y);
    }
}
</code>```

This program never ends because volatile guarantees that all of the instructions before volatile will be flushed into the memory so x++; always executed before y++; and it's not possible to have y > x. This is also expected from my understanding. But after that i've added volatile to int x; too and now i can see reorderings again so program ends most of the time:

```<code>public class Client {
    volatile int x;
    volatile int y;
    public void test() {
        x++;
        y++;
    }
    public static void main(String[] args) {
        Client c = new Client();
        while(c.y <= c.x) new Thread(() -> c.test()).start();
        System.out.println(c.x + " " + c.y);
    }
}
</code>```

Why reordering takes place here also?

答:
This is not evidence of reordering.  In fact, what is happening is a result of ++ on a volatile not being atomic.  For example, consider the following interleaving of operations by two threads (A and B) when updating one of the variables (x):

```<code>thread A: load x -> temp
thread B: load x -> temp
thread A: temp = temp + 1
thread B: temp = temp + 1
thread A: save temp -> x
thread B: save temp -> x
</code>```

and if you work through those operations with that interleaving, you will see that you have lost a count on x.  That is sufficient for the c.y <= c.x to fail occasionally.

(The "lost count" behavior could also happen with y ... which explains why this experiment only fails some of the time.)

Body:
I'm trying to investigate the behaviour of reordering in java environment(using JDK 9-ea+170) and found one thing that i can't explain for myself, so i will be glad to hear some notes about it. Here's an example:

public class Client {
    int x;
    int y;
    public void test() {
        x++;
        y++;
    }
    public static void main(String[] args) {
        Client c = new Client();
        while(c.y <= c.x) new Thread(() -> c.test()).start();
        System.out.println(c.x + " " + c.y);
    }
}

This program has a test() method which just increments x and y values. I'm creating new Threads and call this test() until some internal java optimizations are not changes an order of x++; y++; instructions(). This way i prove that reordering really takes place. And the program ends most of the time(which is expected).
 Now i've added volatile modifier to y:

public class Client {
    int x;
    volatile int y;
    public void test() {
        x++;
        y++;
    }
    public static void main(String[] args) {
        Client c = new Client();
        while(c.y <= c.x) new Thread(() -> c.test()).start();
        System.out.println(c.x + " " + c.y);
    }
}

This program never ends because volatile guarantees that all of the instructions before volatile will be flushed into the memory so x++; always executed before y++; and it's not possible to have y > x. This is also expected from my understanding. But after that i've added volatile to int x; too and now i can see reorderings again so program ends most of the time:

public class Client {
    volatile int x;
    volatile int y;
    public void test() {
        x++;
        y++;
    }
    public static void main(String[] args) {
        Client c = new Client();
        while(c.y <= c.x) new Thread(() -> c.test()).start();
        System.out.println(c.x + " " + c.y);
    }
}

Why reordering takes place here also?

Body:
This is not evidence of reordering.  In fact, what is happening is a result of ++ on a volatile not being atomic.  For example, consider the following interleaving of operations by two threads (A and B) when updating one of the variables (x):

thread A: load x -> temp
thread B: load x -> temp
thread A: temp = temp + 1
thread B: temp = temp + 1
thread A: save temp -> x
thread B: save temp -> x

and if you work through those operations with that interleaving, you will see that you have lost a count on x.  That is sufficient for the c.y <= c.x to fail occasionally.

(The "lost count" behavior could also happen with y ... which explains why this experiment only fails some of the time.)


问:
Why is the data connection non-persistent in FTP? What advantage does this offer over keeping it as a persistent connection?
The control connection in FTP is persistent but the data connection is created and disposed after each data transfer (aka. non-persistent). What are the advantages to making the data connection non-persistent? Does making the data connection non-persistent free up resources for the server?</p>

答: So that end of file equals end of stream, so that there doesn't have to be a superimposed protocol on the data connection.</p>


问:
What is .NET Equivalent of InterruptedException (Java)?
I am converting Java program into C#.

I am wondering what is the .NET equivalent of Java's InterruptedException?

答: It is ThreadInterruptedException.

Body: It is ThreadInterruptedException.


问:
Mongodb Schemas for different types of Posts/Articles
I'm developing an application with Mongodb, Mongoose and Expressjs in which there are articles or posts of different types. For example there's URL post which only includes of a URL or address and doesn't have text inside of it. There's normal posts, Map posts, Image posts and bunch of other types.

Now I want to define the schema of Posts in my Application. I'm a bit confused if I should be defining different schemas for each of these since they should have different attributes and properties when they share some properties or, put all possible properties inside the Post schema and use an attribute with the name of type to specify the type of the post that's been shared.

What's the best practice to do such thing?

答:
I would recommend putting all common attributes in one schema and let your posts be of dynamic type (e.g. your posts could have images as well as text and videos). And you could end up with something like this: </p>

```<code>post {
  (_)id : ...,
  user_id: ...,
  .
  .
  .
},
post_images{
  (_)id:...,
  post_id:...,
  uri:...,
  .
  .
  .
}
</code>```

Body:
I would recommend putting all common attributes in one schema and let your posts be of dynamic type (e.g. your posts could have images as well as text and videos). And you could end up with something like this:

post {
  (_)id : ...,
  user_id: ...,
  .
  .
  .
},
post_images{
  (_)id:...,
  post_id:...,
  uri:...,
  .
  .
  .
}


问:
global variables scope in php
I didn't understand this sentence from php.net:
Note:
Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.

what does it mean? can anyone demonstrate briefly?

答:
"It can be used if the file is included from inside a function" means that it will even work like this:

page.php

```<code><?php
  global $d;
  $d = "HI";
?>
</code>```

index.php

```<code><?php
  getpage();

  function getpage(){
     include 'page.php';
     echo $d;
  }
?>
</code>```

Title: global variables scope in php

Body:
"It can be used if the file is included from inside a function" means that it will even work like this:

page.php

<?php
  global $d;
  $d = "HI";
?>

index.php

<?php
  getpage();

  function getpage(){
     include 'page.php';
     echo $d;
  }
?>


问:
How to change a checked event to an onclick event?
How I would change this simple function into an onclick event using a button, rather than a checkbox? I am really new to JavaScript.</p>

```<code>function showhide() {
        if (document.getElementById('toggle').checked == true) {
            document.getElementById('hidethis').style.display = 'block';
        } else {
            document.getElementById('hidethis').style.display = 'none';
        }
    }
</code>```

答:
Better use with classList.toggle function .It toggle the className

function showhide() {
  document.getElementById('hidethis').classList.toggle('hide');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide {
  display: none;
}</code>```

<button onclick="showhide()">Click Me</button>

Text
```

Body:
How I would change this simple function into an onclick event using a button, rather than a checkbox? I am really new to JavaScript.

function showhide() {
        if (document.getElementById('toggle').checked == true) {
            document.getElementById('hidethis').style.display = 'block';
        } else {
            document.getElementById('hidethis').style.display = 'none';
        }
    }

Body:
Better use with classList.toggle function .It toggle the className

function showhide() {
  document.getElementById('hidethis').classList.toggle('hide');
}

.hide {
  display: none;
}

<button onclick="showhide()">Click Me</button>
<div id="hidethis">Text</div>


问:
How to get values from table valued function in C#
I have a program where i have to display

The Event Description (OpisDogodka)

Location (Lokacija)

Time (ura)
My table valued function:

```<code>     [dbo].[DobiDogodek](
     @Ime nvarchar(100), @Datum date)
     RETURNS TABLE AS RETURN (SELECT OpisDogodka AS 'Opisdogodka',Lokacija, Ura FROM Dogodek WHERE Ime=@Ime AND Datum=@Datum)
</code>```

My method to connect to the server:

```<code> public string Dobi_dogodek(string ime,string datum)
{
    string a="";
    cmd = new SqlCommand("SELECT * FROM dbo.DobiDogodek(@Ime,@Datum)",povezava); //povezava = connectio and it succeeds to connect to the server.

    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@Ime", ime);
    cmd.Parameters.AddWithValue("@Datum", datum); //how to pass date only?
    try
    {
        SqlDataReader Reader = cmd.ExecuteReader();
        while(Reader.Read())
        {

            a = Reader.GetString(0)+" "+Reader.GetString(1)+" "+Reader.GetString(3).ToString(); // get what?

                }
            Uspeh = true;
    }
    catch (Exception e)
    {
        ex = e;
    }
    finally
    {
        povezava.Close();
    }

    return a;
}
</code>```

I tried also using Datatable and datarow. I am also unsure how to work with Date. I know how to work with DateTime, but I need Date and Time separate. What I am doing wrong?

4.6.2017 (11.40 am CET)Update:
It seems I get the desired result

```<code>  public List<string> Dobi_dogodek(string ime,string datum)
{
    s = new List<string>();
    cmd = new SqlCommand("SELECT * FROM dbo.DobiDogodek(@Ime,@Datum)",povezava);

    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@Ime", ime);
    cmd.Parameters.AddWithValue("@Datum", Convert.ToDateTime(datum));
    dt = new DataTable();
    da = new SqlDataAdapter(cmd);
    da.Fill(dt);

    try
    {
        foreach (DataRow dr in dt.Rows)
        {
            s.Add(dr["Opis dogodka"].ToString() + "\\" + dr["Lokacija"].ToString() + "\\" + dr["Ura"].ToString());
        }

        Uspeh = true;
    }
    catch (Exception e)
    {
        ex = e;
    }
    finally
    {
        povezava.Close();
    }

    return s;
}
</code>```

Now I just need to split the strings according to my requirements, but is the a better (not necessarily an easy) way?

答:
what is happening when you run it? are you getting an error message? is it getting it as an int? did you see what the sql server is getting from application by using sql profiler?
I will double check but I think your problem is you are not putting quotes around your variables in our statement so when it runs it is evaluating them as ints. try "SELECT * FROM dbo.DobiDogodek('@Ime','@Datum')". It been a long time since I havnt used something like EF...

Body:
I have a program where i have to display

The Event Description (OpisDogodka)

Location (Lokacija)

Time (ura)
My table valued function:

     [dbo].[DobiDogodek](
     @Ime nvarchar(100), @Datum date)
     RETURNS TABLE AS RETURN (SELECT OpisDogodka AS 'Opisdogodka',Lokacija, Ura FROM Dogodek WHERE Ime=@Ime AND Datum=@Datum)

My method to connect to the server:

 public string Dobi_dogodek(string ime,string datum)
{
    string a="";
    cmd = new SqlCommand("SELECT * FROM dbo.DobiDogodek(@Ime,@Datum)",povezava); //povezava = connectio and it succeeds to connect to the server.

    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@Ime", ime);
    cmd.Parameters.AddWithValue("@Datum", datum); //how to pass date only?
    try
    {
        SqlDataReader Reader = cmd.ExecuteReader();
        while(Reader.Read())
        {

            a = Reader.GetString(0)+" "+Reader.GetString(1)+" "+Reader.GetString(3).ToString(); // get what?

                }
            Uspeh = true;
    }
    catch (Exception e)
    {
        ex = e;
    }
    finally
    {
        povezava.Close();
    }

    return a;
}

I tried also using Datatable and datarow. I am also unsure how to work with Date. I know how to work with DateTime, but I need Date and Time separate. What I am doing wrong?

4.6.2017 (11.40 am CET)Update:
It seems I get the desired result

  public List<string> Dobi_dogodek(string ime,string datum)
{
    s = new List<string>();
    cmd = new SqlCommand("SELECT * FROM dbo.DobiDogodek(@Ime,@Datum)",povezava);

    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@Ime", ime);
    cmd.Parameters.AddWithValue("@Datum", Convert.ToDateTime(datum));
    dt = new DataTable();
    da = new SqlDataAdapter(cmd);
    da.Fill(dt);

    try
    {
        foreach (DataRow dr in dt.Rows)
        {
            s.Add(dr["Opis dogodka"].ToString() + "\\" + dr["Lokacija"].ToString() + "\\" + dr["Ura"].ToString());
        }

        Uspeh = true;
    }
    catch (Exception e)
    {
        ex = e;
    }
    finally
    {
        povezava.Close();
    }

    return s;
}

Now I just need to split the strings according to my requirements, but is the a better (not necessarily an easy) way?


问:
iPhone, cocos2d and accelerometer
I'm reading 'Learn iPhone and iPad Cocos2D Game Development' and in chapter 4, there's a simple sample using accelerometer. It works well if I use x-axis only as the book but with y-axis, sprite's movement is not smooth if it on the edge of the screen.

```<code>+ (id)scene
{
    CCScene*    scene   = [CCScene node];
    CCLayer*    layer   = [GameScene node];
    [scene addChild:layer];
    return scene;
}

- (id)init
{
    if ((self = [super init]))
    {
        CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);

        self.isAccelerometerEnabled = YES;

        player  = [CCSprite spriteWithFile:@"alien.png"];
        [self addChild:player z:0 tag:1];

        CGSize  screenSize  = [[CCDirector sharedDirector] winSize];
        float   imageHeight = [player texture].contentSize.height;
        player.position = CGPointMake(screenSize.width / 2, imageHeight / 2);

        [self scheduleUpdate];
    }

    return self;
}

- (void)dealloc
{
    CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);

    [super dealloc];
}

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    float   deceleration    = 0.4f;
    float   sensitivity     = 6.0f;
    float   maxVelocity     = 100;

    playerVelocity.x    = playerVelocity.x * deceleration + acceleration.x * sensitivity;
    playerVelocity.y    = playerVelocity.y * deceleration + acceleration.y * sensitivity;

    if (playerVelocity.x > maxVelocity)
    {
        playerVelocity.x    = maxVelocity;
    }
    else if (playerVelocity.x < -maxVelocity)
    {
        playerVelocity.x    = -maxVelocity;
    }

    if (playerVelocity.y > maxVelocity)
    {
        playerVelocity.y    = maxVelocity;
    }
    else if (playerVelocity.y < -maxVelocity)
    {
        playerVelocity.y    = -maxVelocity;
    }
}

- (void)update:(ccTime)delta
{
    CGPoint pos = player.position;
    pos.x   += playerVelocity.x;
    pos.y   += playerVelocity.y;

    CGSize  screenSize  = [[CCDirector sharedDirector] winSize];
    float   imageWidthHalved    = [player texture].contentSize.width * 0.5f;
    float   leftBorderLimit     = imageWidthHalved;
    float   rightBorderLimit    = screenSize.width - imageWidthHalved;

    if (pos.x < leftBorderLimit)
    {
        pos.x   = leftBorderLimit;
        playerVelocity  = CGPointZero;
    }
    else if (pos.x > rightBorderLimit)
    {
        pos.x   = rightBorderLimit;
        playerVelocity  = CGPointZero;
    }

    float   imageHeightHalved   = [player texture].contentSize.height * 0.5f;
    float   topBorderLimit      = screenSize.height - imageHeightHalved;
    float   bottomBorderLimit   = imageHeightHalved;

    if (pos.y < bottomBorderLimit)
    {
        pos.y   = bottomBorderLimit;
        playerVelocity  = CGPointZero;
    }
    else if (pos.y > topBorderLimit)
    {
        pos.y   = topBorderLimit;
        playerVelocity  = CGPointZero;
    }

    player.position = pos;
}
</code>```

What's the problem?

答:
First of all, thanks for reading my book! :)

You can find an improved filtering method (ease exponential) that I'm using in this article, it also contains basic info on how the accelerometer works.

You can learn more about accelerometer input from the Tilt to Live developers and their approach, comes with a sample project.

Title: iPhone, cocos2d and accelerometer

Body:
I'm reading 'Learn iPhone and iPad Cocos2D Game Development' and in chapter 4, there's a simple sample using accelerometer. It works well if I use x-axis only as the book but with y-axis, sprite's movement is not smooth if it on the edge of the screen.

+ (id)scene
{
    CCScene*    scene   = [CCScene node];
    CCLayer*    layer   = [GameScene node];
    [scene addChild:layer];
    return scene;
}

- (id)init
{
    if ((self = [super init]))
    {
        CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);

        self.isAccelerometerEnabled = YES;

        player  = [CCSprite spriteWithFile:@"alien.png"];
        [self addChild:player z:0 tag:1];

        CGSize  screenSize  = [[CCDirector sharedDirector] winSize];
        float   imageHeight = [player texture].contentSize.height;
        player.position = CGPointMake(screenSize.width / 2, imageHeight / 2);

        [self scheduleUpdate];
    }

    return self;
}

- (void)dealloc
{
    CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);

    [super dealloc];
}

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    float   deceleration    = 0.4f;
    float   sensitivity     = 6.0f;
    float   maxVelocity     = 100;

    playerVelocity.x    = playerVelocity.x * deceleration + acceleration.x * sensitivity;
    playerVelocity.y    = playerVelocity.y * deceleration + acceleration.y * sensitivity;

    if (playerVelocity.x > maxVelocity)
    {
        playerVelocity.x    = maxVelocity;
    }
    else if (playerVelocity.x < -maxVelocity)
    {
        playerVelocity.x    = -maxVelocity;
    }

    if (playerVelocity.y > maxVelocity)
    {
        playerVelocity.y    = maxVelocity;
    }
    else if (playerVelocity.y < -maxVelocity)
    {
        playerVelocity.y    = -maxVelocity;
    }
}

- (void)update:(ccTime)delta
{
    CGPoint pos = player.position;
    pos.x   += playerVelocity.x;
    pos.y   += playerVelocity.y;

    CGSize  screenSize  = [[CCDirector sharedDirector] winSize];
    float   imageWidthHalved    = [player texture].contentSize.width * 0.5f;
    float   leftBorderLimit     = imageWidthHalved;
    float   rightBorderLimit    = screenSize.width - imageWidthHalved;

    if (pos.x < leftBorderLimit)
    {
        pos.x   = leftBorderLimit;
        playerVelocity  = CGPointZero;
    }
    else if (pos.x > rightBorderLimit)
    {
        pos.x   = rightBorderLimit;
        playerVelocity  = CGPointZero;
    }

    float   imageHeightHalved   = [player texture].contentSize.height * 0.5f;
    float   topBorderLimit      = screenSize.height - imageHeightHalved;
    float   bottomBorderLimit   = imageHeightHalved;

    if (pos.y < bottomBorderLimit)
    {
        pos.y   = bottomBorderLimit;
        playerVelocity  = CGPointZero;
    }
    else if (pos.y > topBorderLimit)
    {
        pos.y   = topBorderLimit;
        playerVelocity  = CGPointZero;
    }

    player.position = pos;
}

What's the problem?


问:
How to Remove Background Color of Button to get Default Background in Android
I am Working on a Test Application in which every question is presented with Four options [those options are via Button]. When a User clicks a button and his answer is correct then background of that button Turns Green, and if his answer is incorrect it turns Red.
What i want to do is Reset the Button Background on Next Question.

After Searching a lot of People have asked the same Question and Accepted the answer as

```<code>  btnChoiceB.setBackgroundColor(0x00000000);
</code>```

But the problem is, it turns the Whole Button Transparent, which is not my requirement. I Just want the default color Back.

Do Not Suggest

```<code>btnChoiceB.setBackgroundColor(null);
</code>```

as it does not work.

This is What i want Back.

UPDATE/ANSWERED

As Suggested by quick learner,

```<code>btnChoiceB.setBackgroundResource(android.R.drawable.btn_default);
</code>```

worked pretty cleanly.

答:
Try this</p>

```<code>btnChoiceB.setBackgroundResource(android.R.drawable.btn_default);
</code>```

Body:
I am Working on a Test Application in which every question is presented with Four options [those options are via Button]. When a User clicks a button and his answer is correct then background of that button Turns Green, and if his answer is incorrect it turns Red.
What i want to do is Reset the Button Background on Next Question.

After Searching a lot of People have asked the same Question and Accepted the answer as

  btnChoiceB.setBackgroundColor(0x00000000);

But the problem is, it turns the Whole Button Transparent, which is not my requirement. I Just want the default color Back.

Do Not Suggest

btnChoiceB.setBackgroundColor(null);

as it does not work.

This is What i want Back.

UPDATE/ANSWERED

As Suggested by quick learner,

btnChoiceB.setBackgroundResource(android.R.drawable.btn_default);

worked pretty cleanly.

Body:
Try this

btnChoiceB.setBackgroundResource(android.R.drawable.btn_default);


问:
How to transfer GET/POST data when using pagination Using Session in PHP
This is my code: </p>

```<code>$tag1 = $_GET['tag1'];
$tag2 = $_GET['tag2'];

$stmt = $conn->prepare("SELECT name FROM info WHERE tag1='$tag1' OR tag2='$tag2' LIMIT $limit OFFSET $start");

// Pagination
while ($pagenumber != $totalpages)
    {
    ++$pagenumber;

    echo "<a href='?page=".$pagenumber."'>".$pagenumber."</a>";
    }
</code>```

<p>Everything is working fine, but when i go to any other page, I get this 2 errors: </p>

```<code>Notice: Undefined index: tag1

Notice: Undefined index: tag2
</code>```

答:
you can pass your get value into your link, be sure that vars are set before

try this please

```<code>echo "<a href='?page=".$pagenumber."&tag1=".$tag1."&tag2=".$tag2."'>".$pagenumber."</a>";
</code>```

Body:
This is my code:

$tag1 = $_GET['tag1'];
$tag2 = $_GET['tag2'];

$stmt = $conn->prepare("SELECT name FROM info WHERE tag1='$tag1' OR tag2='$tag2' LIMIT $limit OFFSET $start");

// Pagination
while ($pagenumber != $totalpages)
    {
    ++$pagenumber;

    echo "".$pagenumber."";
    }

Everything is working fine, but when i go to any other page, I get this 2 errors:

Notice: Undefined index: tag1

Notice: Undefined index: tag2

Body:
you can pass your get value into your link, be sure that vars are set before

try this please

echo "<a href='?page=".$pagenumber."&tag1=".$tag1."&tag2=".$tag2."'>".$pagenumber."</a>";


问:
Error in arff module
I am working in Python 2.7.12 in linux. I have installed the liac-arff and arff modules for the machine. The following line throws an error.

```<code>arff_frame = arff.load(
        open(filename, 'r'), encode_nominal=encode_nominal, return_type=arff.DENSE)
</code>```

The error is, AttributeError: 'module' object has no attribute 'DENSE'
Any suggestions about how to address this error?

答:
Make sure that your script file is not named arff.py. It prevents import of arff module you installed.

Also make sure there's no arff.pyc remained.

UPDATE

Make sure that you installed liac-arff (not arff) package.

```<code>>>> import arff
>>> arff.DENSE
0
</code>```

Title: Error in arff module

Body:
I am working in Python 2.7.12 in linux. I have installed the liac-arff and arff modules for the machine. The following line throws an error.

arff_frame = arff.load(
        open(filename, 'r'), encode_nominal=encode_nominal, return_type=arff.DENSE)

The error is, AttributeError: 'module' object has no attribute 'DENSE'
Any suggestions about how to address this error?

Body:
Make sure that your script file is not named arff.py. It prevents import of arff module you installed.

Also make sure there's no arff.pyc remained.

UPDATE

Make sure that you installed liac-arff (not arff) package.

>>> import arff
>>> arff.DENSE
0