问:
retrieving data and storing in three different objects and then to arraylist
Hello I want to retrieve data from database and that will be stored in three different objects and i want to store those objects into arraylist and again want to show that three objects data in to jsp as three types of data .I can do for one objects but how can I do for the three objects.Any idea?

this is my servlet code

```<code>public class ViewCasualStaff extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException{

        try {
            PrintWriter out =response.getWriter();
            response.setContentType("text/html");

            Connection conn = ConnectionManager.getConnection();
            PreparedStatement pst = conn.prepareStatement("");
            String sql = "SELECT LAST_NAME,FIRST_NAME FROM EMPLOYEE "
                    + "WHERE  JOB_TYPE = casual";

            pst.executeQuery(sql);
            ResultSet rs = pst.getResultSet();

            ArrayList<CasualStaff> casualStafflist = new ArrayList<>();

            while(rs.next()){

                CasualStaff cs = new CasualStaff();
                cs.setFname(rs.getString("FIRST_NAME"));
                cs.setLname(rs.getString("LAST_NAME"));
                casualStafflist.add(cs);

            }

            request.setAttribute("CSList",casualStafflist);

            RequestDispatcher dispatcher = request.getRequestDispatcher("/test.jsp");

            dispatcher.forward(request,response);
        } catch (InstantiationException | IllegalAccessException | SQLException ex) {
             Logger.getLogger(ViewCasualStaff.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
</code>```

Below this the interface class and other classes that implements interface class

```<code>* @author dipendra
*/

public interface Staff {

    public String FName= "Fname";
    public String LName ="Lname";
    public String Postion = "Position";

    public void setStaff(String Fname,String Lname,String Position);
}
</code>```

this class is implementing staff interface

```<code>public class  CasualStaff implements Staff{

    private String Fname;
    private String Lname;
    private String Position;

    @Override
    public void setStaff(String Fname, String Lname, String Position) {
        this.Fname= Fname;
        this.Lname=Lname;
        this.Position = Position;
    }
}
</code>```

答:
Suppose you are calculating average from three different tables using group by statement which returns multiple rows.
 - Fist I have written three different queries from different tables
 - Second I have  Created three Arraylist objects (firstArr, secondArr, thirdArr)     to store resultset
 - Third I have created one more arralist object and "Add three objects" into this finalArr object.

At the end you will have a finalArr Object which contains all the resultsets data.

Now you can iterate through the finalArr and show the result into your jsp or desired views

```<code>public ArrayList getAverage() {
    // TODO Auto-generated method stub`enter code here`
    String query1= "select sum(column)/count(Column) as avr1 from table1 group by(column1) order by desc";
    String query2= "Select sum(column)/count(Column) as avr2 from table2 group by(column1) order by desc";
    String query3= "select sum(column)/count(Column) as avr3 from table3 group by(column1) order by desc";

    Connection connection = null;
    ResultSet rs = null;
    PreparedStatement preparedStatement = null;
    ArrayList fisrtArr = new ArrayList();
    ArrayList secondArr = new ArrayList();
    ArrayList thirdArr = new ArrayList();
    float average1= 0;
    float average2= 0;
    float average3= 0;
    try {
         connection = dataSourceAbacus.getConnection();
         preparedStatement = connection.prepareStatement(query1);
         rs = preparedStatement.executeQuery();
    while (rs.next()) {
            average1= rs.getInt("avr1");
            firstArr.add(average1);
        }
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }if (rs != null){
            try{rs.close();
            }catch (Exception e){e.printStackTrace();
            }
        }if(preparedStatement != null){
            try{preparedStatement.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

    try {
         connection = dataSourceAbacus.getConnection();
         preparedStatement = connection.prepareStatement(query2);
         rs = preparedStatement.executeQuery();
    while (rs.next()) {
            average2= rs.getInt("avr2");
            secondArr.add(average2);
        }
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }if (rs != null){
            try{rs.close();
            }catch (Exception e){e.printStackTrace();
            }
        }if(preparedStatement != null){
            try{preparedStatement.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

    try {
         connection = dataSourceAbacus.getConnection();
         preparedStatement = connection.prepareStatement(query3);
         rs = preparedStatement.executeQuery();
    while (rs.next()) {
            average3 = rs.getFloat("avr3");
            thirdArr.add(average3);
        }
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }if (rs != null){
            try{rs.close();
            }catch (Exception e){e.printStackTrace();
            }
        }if(preparedStatement != null){
            try{preparedStatement.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
    finalArr.add(firstArr);
    finalArr.add(secondArr);
    finalArr.add(thirdArr);
    return finalArr;
}
</code>```

Body:
Hello I want to retrieve data from database and that will be stored in three different objects and i want to store those objects into arraylist and again want to show that three objects data in to jsp as three types of data .I can do for one objects but how can I do for the three objects.Any idea?

this is my servlet code

public class ViewCasualStaff extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException{

        try {
            PrintWriter out =response.getWriter();
            response.setContentType("text/html");

            Connection conn = ConnectionManager.getConnection();
            PreparedStatement pst = conn.prepareStatement("");
            String sql = "SELECT LAST_NAME,FIRST_NAME FROM EMPLOYEE "
                    + "WHERE  JOB_TYPE = casual";

            pst.executeQuery(sql);
            ResultSet rs = pst.getResultSet();

            ArrayList<CasualStaff> casualStafflist = new ArrayList<>();

            while(rs.next()){

                CasualStaff cs = new CasualStaff();
                cs.setFname(rs.getString("FIRST_NAME"));
                cs.setLname(rs.getString("LAST_NAME"));
                casualStafflist.add(cs);

            }

            request.setAttribute("CSList",casualStafflist);

            RequestDispatcher dispatcher = request.getRequestDispatcher("/test.jsp");

            dispatcher.forward(request,response);
        } catch (InstantiationException | IllegalAccessException | SQLException ex) {
             Logger.getLogger(ViewCasualStaff.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Below this the interface class and other classes that implements interface class

* @author dipendra
*/

public interface Staff {

    public String FName= "Fname";
    public String LName ="Lname";
    public String Postion = "Position";

    public void setStaff(String Fname,String Lname,String Position);
}

this class is implementing staff interface

public class  CasualStaff implements Staff{

    private String Fname;
    private String Lname;
    private String Position;

    @Override
    public void setStaff(String Fname, String Lname, String Position) {
        this.Fname= Fname;
        this.Lname=Lname;
        this.Position = Position;
    }
}

Body:
Suppose you are calculating average from three different tables using group by statement which returns multiple rows.
 - Fist I have written three different queries from different tables
 - Second I have  Created three Arraylist objects (firstArr, secondArr, thirdArr)     to store resultset
 - Third I have created one more arralist object and "Add three objects" into this finalArr object.

At the end you will have a finalArr Object which contains all the resultsets data.

Now you can iterate through the finalArr and show the result into your jsp or desired views

public ArrayList getAverage() {
    // TODO Auto-generated method stub`enter code here`
    String query1= "select sum(column)/count(Column) as avr1 from table1 group by(column1) order by desc";
    String query2= "Select sum(column)/count(Column) as avr2 from table2 group by(column1) order by desc";
    String query3= "select sum(column)/count(Column) as avr3 from table3 group by(column1) order by desc";

    Connection connection = null;
    ResultSet rs = null;
    PreparedStatement preparedStatement = null;
    ArrayList fisrtArr = new ArrayList();
    ArrayList secondArr = new ArrayList();
    ArrayList thirdArr = new ArrayList();
    float average1= 0;
    float average2= 0;
    float average3= 0;
    try {
         connection = dataSourceAbacus.getConnection();
         preparedStatement = connection.prepareStatement(query1);
         rs = preparedStatement.executeQuery();
    while (rs.next()) {
            average1= rs.getInt("avr1");
            firstArr.add(average1);
        }
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }if (rs != null){
            try{rs.close();
            }catch (Exception e){e.printStackTrace();
            }
        }if(preparedStatement != null){
            try{preparedStatement.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

    try {
         connection = dataSourceAbacus.getConnection();
         preparedStatement = connection.prepareStatement(query2);
         rs = preparedStatement.executeQuery();
    while (rs.next()) {
            average2= rs.getInt("avr2");
            secondArr.add(average2);
        }
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }if (rs != null){
            try{rs.close();
            }catch (Exception e){e.printStackTrace();
            }
        }if(preparedStatement != null){
            try{preparedStatement.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

    try {
         connection = dataSourceAbacus.getConnection();
         preparedStatement = connection.prepareStatement(query3);
         rs = preparedStatement.executeQuery();
    while (rs.next()) {
            average3 = rs.getFloat("avr3");
            thirdArr.add(average3);
        }
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }if (rs != null){
            try{rs.close();
            }catch (Exception e){e.printStackTrace();
            }
        }if(preparedStatement != null){
            try{preparedStatement.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
    finalArr.add(firstArr);
    finalArr.add(secondArr);
    finalArr.add(thirdArr);
    return finalArr;
}


来源: stackexchange

问:
How I delete custom dexterity objects in Plone 4?
I'm trying delete some custom dexterity objects, bellow have snipets code of this custom object.

```<code>class IDigitalFile(model.Schema):
        """Dexterity-Schema
        """

    ...

    directives.read_permission(auto="cmf.ManagePortal")
    directives.write_permission(auto="cmf.ManagePortal")
    fieldset('Admins Only', fields=['auto', 'uploded_at', 'codLote'] )
    auto = schema.Bool(
        title=_(u"Upload via Script?"),
        required=True,
        default=False,
    )
    ...
</code>```

And I try use sudo plone_daemon bin/client2 -O Plone debug and apply this code:

```<code>from zope.site.hooks import setSite
site = 'Plone'
context = app[site]
setSite(context)
portal_catalog = context.portal_catalog
itens = portal_catalog(portal_type='digitalfile', path='/ged/')
print itens
</code>```

After rum this script my output is [], just epmty but if i use the similar code in ZMI I have all brains.

So, in ZMI we can't user methods to delete 'cuz have restrictions.
And my goal is delete all objects digitalfileif flag Truein autofield.

How can I do it if my results are empties?
Or what I did wrong for output is empty?

[UPDATE 1]

This problem apper to me:

```<code>zero@srv-d:/opt/Plone439/zeocluster$ sudo -u plone_daemon bin/client2 -O Plone debug
Starting debugger (the name "app" is bound to the top-level Zope object)
2017-03-31 10:09:04 WARNING ZODB.blob (18048) Blob dir /opt/Plone439/zeocluster/var/blobstorage/ has insecure mode setting
Traceback (most recent call last):
  File "/opt/Plone439/zeocluster/parts/client2/bin/interpreter", line 281, in <module>
    exec(_val)
  File "<string>", line 1, in <module>
  File "/opt/Plone439/buildout-cache/eggs/Zope2-2.13.24-py2.7.egg/ZPublisher/BaseRequest.py", line 623, in traverse
    response.unauthorized()
  File "/opt/Plone439/buildout-cache/eggs/Zope2-2.13.24-py2.7.egg/ZPublisher/HTTPResponse.py", line 756, in unauthorized
    raise Unauthorized, m
zExceptions.unauthorized.Unauthorized: You are not authorized to access this resource.
</code>```

[UPDATE 2 - SOLVED]

Maybe have a easy way to do, but in this moment, this script solved my problem and I'm sharing if someone need...

```<code># -*- coding: utf-8 -*-
from zope.site.hooks import setSite
from plone import api
import transaction

# Setting the plone portal in var context
site = 'Plone'
context = app[site]
setSite(context)

# grabbing portal_catalog tool
portal_catalog = context.portal_catalog

# setting the user that have permission
with api.env.adopt_user(username='admin'):
    # grabbing all items digitalfile
    brains = portal_catalog(portal_type='digitalfile', path='/ged')

for brain in brains:
    if 'TO BE DELETE' in brain.Description:
        item = api.content.get(path=brain.getPath())
        api.content.delete(obj=item)
        transaction.commit()
</code>```

答:
It might mean that you need "security clearance" to access the brains/objects.

Normally portal catalog search will only return results for objects for which you have access permissions. In ZMI it works because you are logged-in as an admin (or a site manager), while command line scripts do not have user information set by default. For example, if objects are not published (in private state), they will not show up in catalog search in a command line script.

If you have plone.api installed, you can use "api.env.adopt_user" to run a command with the specified user:

```<code>from plone import api

with api.env.adopt_user(username="admin"):
    items = portal_catalog(portal_type='digitalfile', path='/ged/')
</code>```

Alternatively, you can use portal_catalog.unrestrictedSearchResults to ignore security checks when performing the search:

```<code>items = portal_catalog.unrestrictedSearchResults(
    portal_type='digitalfile', path='/ged/')
</code>```

I remember that in the later case sometimes I had to use brain._unrestrictedGetObject() to get the actual object, but now it seems to work also with regular brain.getObject() (perhaps depends on Zope/Plone version used).

ContentLicense: CC BY-SA 3.0

Body:
I'm trying delete some custom dexterity objects, bellow have snipets code of this custom object.

class IDigitalFile(model.Schema):
        """Dexterity-Schema
        """

    ...

    directives.read_permission(auto="cmf.ManagePortal")
    directives.write_permission(auto="cmf.ManagePortal")
    fieldset('Admins Only', fields=['auto', 'uploded_at', 'codLote'] )
    auto = schema.Bool(
        title=_(u"Upload via Script?"),
        required=True,
        default=False,
    )
    ...

And I try use sudo plone_daemon bin/client2 -O Plone debug and apply this code:

from zope.site.hooks import setSite
site = 'Plone'
context = app[site]
setSite(context)
portal_catalog = context.portal_catalog
itens = portal_catalog(portal_type='digitalfile', path='/ged/')
print itens

After rum this script my output is [], just epmty but if i use the similar code in ZMI I have all brains.

So, in ZMI we can't user methods to delete 'cuz have restrictions.
And my goal is delete all objects digitalfileif flag Truein autofield.

How can I do it if my results are empties?
Or what I did wrong for output is empty?

[UPDATE 1]

This problem apper to me:

zero@srv-d:/opt/Plone439/zeocluster$ sudo -u plone_daemon bin/client2 -O Plone debug
Starting debugger (the name "app" is bound to the top-level Zope object)
2017-03-31 10:09:04 WARNING ZODB.blob (18048) Blob dir /opt/Plone439/zeocluster/var/blobstorage/ has insecure mode setting
Traceback (most recent call last):
  File "/opt/Plone439/zeocluster/parts/client2/bin/interpreter", line 281, in <module>
    exec(_val)
  File "<string>", line 1, in <module>
  File "/opt/Plone439/buildout-cache/eggs/Zope2-2.13.24-py2.7.egg/ZPublisher/BaseRequest.py", line 623, in traverse
    response.unauthorized()
  File "/opt/Plone439/buildout-cache/eggs/Zope2-2.13.24-py2.7.egg/ZPublisher/HTTPResponse.py", line 756, in unauthorized
    raise Unauthorized, m
zExceptions.unauthorized.Unauthorized: You are not authorized to access this resource.

[UPDATE 2 - SOLVED]

Maybe have a easy way to do, but in this moment, this script solved my problem and I'm sharing if someone need...

# -*- coding: utf-8 -*-
from zope.site.hooks import setSite
from plone import api
import transaction

# Setting the plone portal in var context
site = 'Plone'
context = app[site]
setSite(context)

# grabbing portal_catalog tool
portal_catalog = context.portal_catalog

# setting the user that have permission
with api.env.adopt_user(username='admin'):
    # grabbing all items digitalfile
    brains = portal_catalog(portal_type='digitalfile', path='/ged')

for brain in brains:
    if 'TO BE DELETE' in brain.Description:
        item = api.content.get(path=brain.getPath())
        api.content.delete(obj=item)
        transaction.commit()

Body:
It might mean that you need "security clearance" to access the brains/objects.

Normally portal catalog search will only return results for objects for which you have access permissions. In ZMI it works because you are logged-in as an admin (or a site manager), while command line scripts do not have user information set by default. For example, if objects are not published (in private state), they will not show up in catalog search in a command line script.

If you have plone.api installed, you can use "api.env.adopt_user" to run a command with the specified user:

from plone import api

with api.env.adopt_user(username="admin"):
    items = portal_catalog(portal_type='digitalfile', path='/ged/')

Alternatively, you can use portal_catalog.unrestrictedSearchResults to ignore security checks when performing the search:

items = portal_catalog.unrestrictedSearchResults(
    portal_type='digitalfile', path='/ged/')

I remember that in the later case sometimes I had to use brain._unrestrictedGetObject() to get the actual object, but now it seems to work also with regular brain.getObject() (perhaps depends on Zope/Plone version used).


问:
Fading multiple divs with JS
I have two or in future may be more divs with background images in css. I would like to fade them in and out in a loop.

I am trying to do something like this but it doesn`t work.

$(window).load(function(){
var divs = $('.fade');

function fade() {
    var current = $('.current');
    var currentIndex = divs.index(current),
        nextIndex = currentIndex + 1;

    if (nextIndex >= divs.length) {
        nextIndex = 0;
    }

    var next = divs.eq(nextIndex);

    next.stop().fadeIn(2000, function() {
        $(this).addClass('current');
    });

    current.stop().fadeOut(2000, function() {
        $(this).removeClass('current');
        setTimeout(fade, 2500);
    });
}

fade();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#one {
   background-image: url("Test_bg.jpg");
margin-top: -150px;
min-height: 100%;
background-attachment: fixed;
}

#two {
   background-image: url("Test_bg1.jpg");
margin-top: -150px;
min-height: 100%;
display: block;
background-attachment: fixed;
}</code>```

```

答:
You are mising }) at the end with causes syntax error

$(window).load(function(){
var divs = $('.fade');

function fade() {
    var current = $('.current');
    var currentIndex = divs.index(current),
        nextIndex = currentIndex + 1;

    if (nextIndex >= divs.length) {
        nextIndex = 0;
    }

    var next = divs.eq(nextIndex);

    next.stop().fadeIn(2000, function() {
        $(this).addClass('current');
    });

    current.stop().fadeOut(2000, function() {
        $(this).removeClass('current');
        setTimeout(fade, 2500);
    });
}

fade();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#one {
  color: red
}

#two {
  color: blue
}</code>```

a

b

```

ContentLicense: CC BY-SA 4.0

Title: Fading multiple divs with JS

Body:
I have two or in future may be more divs with background images in css. I would like to fade them in and out in a loop.

I am trying to do something like this but it doesn`t work.

$(window).load(function(){
var divs = $('.fade');

function fade() {
    var current = $('.current');
    var currentIndex = divs.index(current),
        nextIndex = currentIndex + 1;

    if (nextIndex >= divs.length) {
        nextIndex = 0;
    }

    var next = divs.eq(nextIndex);

    next.stop().fadeIn(2000, function() {
        $(this).addClass('current');
    });

    current.stop().fadeOut(2000, function() {
        $(this).removeClass('current');
        setTimeout(fade, 2500);
    });
}

fade();

#one {
   background-image: url("Test_bg.jpg");
margin-top: -150px;
min-height: 100%;
background-attachment: fixed;
}

#two {
   background-image: url("Test_bg1.jpg");
margin-top: -150px;
min-height: 100%;
display: block;
background-attachment: fixed;
}

Body:
You are mising }) at the end with causes syntax error

$(window).load(function(){
var divs = $('.fade');

function fade() {
    var current = $('.current');
    var currentIndex = divs.index(current),
        nextIndex = currentIndex + 1;

    if (nextIndex >= divs.length) {
        nextIndex = 0;
    }

    var next = divs.eq(nextIndex);

    next.stop().fadeIn(2000, function() {
        $(this).addClass('current');
    });

    current.stop().fadeOut(2000, function() {
        $(this).removeClass('current');
        setTimeout(fade, 2500);
    });
}

fade();
})

#one {
  color: red
}

#two {
  color: blue
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one" class="fade current">a
</div>
<div id="two" class="fade">b
</div>


问:
How to extract innerText of "Who was your first employer? into Excel from the given HTML

    Who was your first employer?

```

<p>My code was </p>

<pre class="lang-vb prettyprint-override"><code>Set htmlsecurityquestion = htmldoc.getElementById("dnn_ctr1854_ChallengeQuestion_ChallengeQuestionCmnTextBox_ControlLabel")
Range("A1").Value = htmlsecurityquestion.innerText
</code>```

but it is not working

答:
You access this value through attributes collection, not through innerText. Your second line should be:

```<code>Range("A1").Value = htmlsecurityquestion.Attributes["title"].Value;
</code>```

Body:
    Who was your first employer?

My code was

Set htmlsecurityquestion = htmldoc.getElementById("dnn_ctr1854_ChallengeQuestion_ChallengeQuestionCmnTextBox_ControlLabel")
Range("A1").Value = htmlsecurityquestion.innerText

but it is not working

Body:
You access this value through attributes collection, not through innerText. Your second line should be:

Range("A1").Value = htmlsecurityquestion.Attributes["title"].Value;


问:
Error: TempsController could not be found.Cake PHP
I want files to be uploaded to files folder and their names to be submitted from temp.ctp to tbl_temps table of Temp database. I have created the Model by the name of Temp in models folder. But I am receiving following

Error: TempsController could not be found.Cake PHP.

Error: Create the class TempsController below in file: app\Controller\TempsController.php

temp.ctp

```<code><?php
echo $this->Form->Create("Temp",array("action"=>"temp","enctype"=>"multipart/form-data"));
echo $this->Form->input("file.",array("label"=>false,"div"=>false,"type"=>"file"));
echo $this->Form->input("file.",array("label"=>false,"div"=>false,"type"=>"file"));
?>
<input type="submit"/>
<?php
echo $this->Form->end();
?>
</code>```

PagesController

```<code><?php

App::uses('AppController', 'Controller');

public $uses = array("Temp");

public function temp(){

    if($this->request->is("post")){
        $uploaded_files="";
        foreach($this->data["Temp"]["file"] as $file1){
            $ret_value = $this->PImage->upload($file1,'/app/webroot/files');
            if (isset($ret_value[1]) && !empty($ret_value[1])) {
                                $msgString .= "- File not valid.<br>";
                            }
            else {
                if($uploaded_files){
                    $uploaded_files.= ",*".$ret_value[0];
                }
                else{
                    $uploaded_files=$ret_value[0];
                }
            }
        }
        $this->request->data["Temp"]["file"]=$uploaded_files;
        $this->Temp->save($this->data);
    }
}
}
</code>```

答:
The error message is pretty clear in what you should do:

Error: Create the class TempsController below in file: app\Controller\TempsController.php

You should first understand the Model-View-Controller principle and then move on to create the Controller for your Temp model.

You will have to create a file /app/Controller/TempsController.php:

```<code><?php
App::uses('AppController', 'Controller');

class TempsController extends AppController {

    /* this action will be accessible at '/temps/index' with default routing */

    public function index() {
        // do stuff here
    }
}
</code>```

Body:
I want files to be uploaded to files folder and their names to be submitted from temp.ctp to tbl_temps table of Temp database. I have created the Model by the name of Temp in models folder. But I am receiving following

Error: TempsController could not be found.Cake PHP.

Error: Create the class TempsController below in file: app\Controller\TempsController.php

temp.ctp

<?php
echo $this->Form->Create("Temp",array("action"=>"temp","enctype"=>"multipart/form-data"));
echo $this->Form->input("file.",array("label"=>false,"div"=>false,"type"=>"file"));
echo $this->Form->input("file.",array("label"=>false,"div"=>false,"type"=>"file"));
?>
<input type="submit"/>
<?php
echo $this->Form->end();
?>

PagesController

<?php

App::uses('AppController', 'Controller');

public $uses = array("Temp");

public function temp(){

    if($this->request->is("post")){
        $uploaded_files="";
        foreach($this->data["Temp"]["file"] as $file1){
            $ret_value = $this->PImage->upload($file1,'/app/webroot/files');
            if (isset($ret_value[1]) && !empty($ret_value[1])) {
                                $msgString .= "- File not valid.
";
                            }
            else {
                if($uploaded_files){
                    $uploaded_files.= ",*".$ret_value[0];
                }
                else{
                    $uploaded_files=$ret_value[0];
                }
            }
        }
        $this->request->data["Temp"]["file"]=$uploaded_files;
        $this->Temp->save($this->data);
    }
}
}

Body:
The error message is pretty clear in what you should do:

Error: Create the class TempsController below in file: app\Controller\TempsController.php

You should first understand the Model-View-Controller principle and then move on to create the Controller for your Temp model.

You will have to create a file /app/Controller/TempsController.php:

<?php
App::uses('AppController', 'Controller');

class TempsController extends AppController {

    /* this action will be accessible at '/temps/index' with default routing */

    public function index() {
        // do stuff here
    }
}


问:
Item position by css?
I am new to html and css. Sorry this too easy question, maybe stupit. vid2 under the vid1, it's ok. But, I try to put vid3 rigth of to vid1. But It isn't working.

Actually, I am tring to do something like that;

index.html;

[vid1]   [vid3]  [vid5]

[vid2]   [vid4]  [vid6]

Could you help me to fix code. Thank you.

.vid1
    {
    position: absolute; overflow:hidden; left: 10px; top: 10px; z-index:0;
    }
    .vid2
    {
    position : absolute; overflow:hidden; left::20px; top:180px;  z-index:0;
    }
    .vid3
    {
    position : absolute; overflow:hidden; left::200px; top:10px;  z-index:0;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe class="vid1" src="http://www.youtube.com/embed/r9dsH8H-4P8" frameborder="0" allowfullscreen></iframe>
<iframe class="vid2"  src="http://www.youtube.com/embed/i7sxqaC062A" frameborder="0" allowfullscreen></iframe>
<iframe class="vid3"  src="http://www.youtube.com/embed/YeJQBbtjgK8" frameborder="0" allowfullscreen></iframe></code>```

答: You should change the code left :: 200px; to left : 200px;, Then you can avoid position absolute to get 3 in a row..

Title: Item position by css?


问:
Cakephp use Froala Editor not show anythings
I use Froala Editor for my project cakephp
I've done every step as in the guidelines, but the results are not as expected
I downloaded it and follow the instructions as here enter link description here

download and put Froala folder in app/Plugin/

in boostrap.php i have loaded CakePlugin::load('Froala');

in controller: i have put line: public $helpers = array('Froala.Froala');

in view: my code is

```<code><div id="froala-editor">
  <p>froala-editor</p>
</div>
<?php $this->Froala->editor('#froala-editor'); ?>
</code>```

but Froala editor not appear, Please help me!!!! Thank so much

答:
I think, today Froala have release a solution for Cake php 3 which might help your problem.
https://github.com/froala/wysiwyg-cake </p>

Body:
I use Froala Editor for my project cakephp
I've done every step as in the guidelines, but the results are not as expected
I downloaded it and follow the instructions as here enter link description here

download and put Froala folder in app/Plugin/

in boostrap.php i have loaded CakePlugin::load('Froala');

in controller: i have put line: public $helpers = array('Froala.Froala');

in view: my code is

froala-editor

<?php $this->Froala->editor('#froala-editor'); ?>

but Froala editor not appear, Please help me!!!! Thank so much


问:
Why I get [Laravel - Undefined variable: users (View..] if I tried to use POST and GET on the same view?
I am trying to make a simple search form using laravel.
the search page is supposed to be the same for results.
but I can't make it work, and i'm not sure why
It works on a different Route but can't get it to work on the same route.

Routes:

```<code>Route::get('searchuser',function(){
return view('searchuser');

 })->middleware('auth');

Route::post('searchuser', function(){
$q = Input::get('name');
$users = App\User::where('name_en','like',$q)->get();

return view('searchuser', ['users' => $users]);

 });
</code>```

Blade:

```<code>                <div class="panel-body">
                    <form class="form-horizontal" role="form" method="POST" action="searchuser">
                    {{ csrf_field() }}

                    <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                        <label for="name" class="col-md-4 control-label">Name</label>

                        <div class="col-md-6">
                            <input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" placeholder="Search.." required autofocus>

                            @if ($errors->has('name'))
                                <span class="help-block">
                                    <strong>{{ $errors->first('name') }}</strong>
                                </span>
                            @endif
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-6 col-md-offset-4">
                            <button type="submit" class="btn btn-primary">
                                Search
                            </button>

                        </div>
                    </div>
                </form>
                <div>
                    @foreach($users as $user)
                        {{$user->name_ar . '<br />'}}
                    @endforeach
                </div>
            </div>
</code>```

答:
Got it fixed.
At the first I sent a different variable name as every one noticed.

But I forgot to check if the $users variable isset or not before looping it.

so when I was trying to run the Get route I get the error because the PHP is right, I didn't send the variable $users yet.

so the simple modification was:

```<code> @if(count($users))
      @foreach($users as $user)
            {{ $user->name_ar . '<br />' }}
      @endforeach
 @endif
</code>```

Body:
I am trying to make a simple search form using laravel.
the search page is supposed to be the same for results.
but I can't make it work, and i'm not sure why
It works on a different Route but can't get it to work on the same route.

Routes:

Route::get('searchuser',function(){
return view('searchuser');

 })->middleware('auth');

Route::post('searchuser', function(){
$q = Input::get('name');
$users = App\User::where('name_en','like',$q)->get();

return view('searchuser', ['users' => $users]);

 });

Blade:

                    <form class="form-horizontal" role="form" method="POST" action="searchuser">
                    {{ csrf_field() }}

has('name') ? ' has-error' : '' }}">
                        Name

                            <input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" placeholder="Search.." required autofocus>

                            @if ($errors->has('name'))

                                    {{ $errors->first('name') }}

                            @endif

                            <button type="submit" class="btn btn-primary">
                                Search
                            </button>

                </form>

                    @foreach($users as $user)
                        {{$user->name_ar . '
'}}
                    @endforeach

Body:
Got it fixed.
At the first I sent a different variable name as every one noticed.

But I forgot to check if the $users variable isset or not before looping it.

so when I was trying to run the Get route I get the error because the PHP is right, I didn't send the variable $users yet.

so the simple modification was:

 @if(count($users))
      @foreach($users as $user)
            {{ $user->name_ar . '<br />' }}
      @endforeach
 @endif


问:
Converting String to integer in Scheme
How can I convert a string of digits to an integer ?
I want "365" to be converted to 365.

What I have tried,
string->list then char->integer, but this returns ASCII value of that integer, how can I get that integer ?

Please help.

答:
An alternative solution to parse integers from strings:</p>

```<code>#lang typed/racket

(: numerical-char->integer (-> Char
                               Integer))
(define (numerical-char->integer char)
  (let ([num (- (char->integer char) 48)]) ; 48 = (char->integer #\0)
    (if
     (or (< num 0) (> num 9))
     (raise 'non-numerical-char #t)
     num)))

(: string->integer (-> String
                       Integer))
(define (string->integer str)
  (let ([char-list (string->list str)])
    (if (null? char-list)
        (raise 'empty-string #t)
        (foldl
         (λ([x : Integer] [y : Integer])
           (+ (* y 10) x))
         0
         (map numerical-char->integer char-list)))))
</code>```

Title: Converting String to integer in Scheme

Body:
An alternative solution to parse integers from strings:

#lang typed/racket

(: numerical-char->integer (-> Char
                               Integer))
(define (numerical-char->integer char)
  (let ([num (- (char->integer char) 48)]) ; 48 = (char->integer #\0)
    (if
     (or (< num 0) (> num 9))
     (raise 'non-numerical-char #t)
     num)))

(: string->integer (-> String
                       Integer))
(define (string->integer str)
  (let ([char-list (string->list str)])
    (if (null? char-list)
        (raise 'empty-string #t)
        (foldl
         (λ([x : Integer] [y : Integer])
           (+ (* y 10) x))
         0
         (map numerical-char->integer char-list)))))


答:
you are using the same route and the same blade template

within this blade template you are trying to access a variable .

which is defined in route POST and not defined the other GET

so your issue in your GET route not in your POST route;

to fix this , pass a default value to your GET route as follows :

```<code>Route::get('searchuser',function(){
return view('searchuser', ['users' => []]);

 })->middleware('auth');
</code>```

OR/AND in your blade template do a little confirmation that the users variable isset

```<code>@if(isset($users))
    @foreach($users as $user)
        {{$user->name_ar . '<br />'}}
    @endforeach
@endif
</code>```

Title: Why I get [Laravel - Undefined variable: users (View..] if I tried to use POST and GET on the same view?

Body:
you are using the same route and the same blade template

within this blade template you are trying to access a variable .

which is defined in route POST and not defined the other GET

so your issue in your GET route not in your POST route;

to fix this , pass a default value to your GET route as follows :

Route::get('searchuser',function(){
return view('searchuser', ['users' => []]);

 })->middleware('auth');

OR/AND in your blade template do a little confirmation that the users variable isset

@if(isset($users))
    @foreach($users as $user)
        {{$user->name_ar . '<br />'}}
    @endforeach
@endif


问:
Semicolon after closing curly bracket in PHP
I am writing a script to make chunks of a text and send it via SMS. Earlier today i was reviewing some code to split the string in chunks and i saw something I've never seen before. I'm talking about the ";" right after the "}" at the en of the snippet.

Why this colon? i know it works but i don't know if it adds some semantics or some instruction to the interpreter, anybody know what is this for?

```<code>while(1)
{
    $length = (strlen($output)+strlen($words[$i]));
    if($length>$new_max)
    {
        if(count($words) > 0)
        {
            $out_array[] = $output;
            $output = '';

        }
        else
        {
            break;
        }
    }
    else
    {
        $output = $output." ".$words[$i];
        ++$i;
    };
};
</code>```

EDIT: Looks clear that the semicolons as well as multiple semicolons together has no effect over the result, but, do you know if it has some effect to the interpreter? is it doing some task (internally) when it parses it?

答:
These are unnecessary. They don't hurt the script, just unnecessary. The programmer probably had a habit of adding semicolons to end of every statement. Maybe he got this habit from another programming language, maybe his IDE was showing errors without semicolons or maybe he is just a beginner. In any event, there neither hurt nor help.
Also the fact that programmer uses while(1) tells me that he is either extremely lazy, because usually a programmer would write while(true), the only reason to type while 1 is because it's less typing to do. A programmer with any type of formal training will not not write while(1) instead of while(true).
This is just my opinion, but it's based on over 10 years of programming in 3 languages.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am writing a script to make chunks of a text and send it via SMS. Earlier today i was reviewing some code to split the string in chunks and i saw something I've never seen before. I'm talking about the ";" right after the "}" at the en of the snippet.

Why this colon? i know it works but i don't know if it adds some semantics or some instruction to the interpreter, anybody know what is this for?

while(1)
{
    $length = (strlen($output)+strlen($words[$i]));
    if($length>$new_max)
    {
        if(count($words) > 0)
        {
            $out_array[] = $output;
            $output = '';

        }
        else
        {
            break;
        }
    }
    else
    {
        $output = $output." ".$words[$i];
        ++$i;
    };
};

EDIT: Looks clear that the semicolons as well as multiple semicolons together has no effect over the result, but, do you know if it has some effect to the interpreter? is it doing some task (internally) when it parses it?


问:
Image resize Plugin for Wordpress
I need a plugin in WOrdpress that would meets the following requirements-

I need a plgin where we can upload an image that appears behind the mask and can be moveable and scaleable.

The user can scale and move the images around how they like, once they are happy then we want to be able to download as a jpg.

So basically users need to upload there own picture, be able to move it around and scale behind the mask. Once they have finished download it to jpg.

Is their any plugin aroud in Wordpress?

Thanks in advance. Any help would appreciated !

答: You can try this one: Optimize Images Resizing.</p>

Title: Image resize Plugin for Wordpress


答:
Used this I think help for you.

.video{width:300px; float:left;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="video">
<iframe class="vid1" src="http://www.youtube.com/embed/r9dsH8H-4P8" frameborder="0" allowfullscreen></iframe>
<iframe class="vid2" src="http://www.youtube.com/embed/i7sxqaC062A" frameborder="0" allowfullscreen></iframe>
</div>
<div class="video">
<iframe class="vid3" src="http://www.youtube.com/embed/YeJQBbtjgK8" frameborder="0" allowfullscreen></iframe>
<iframe class="vid4" src="http://www.youtube.com/embed/YeJQBbtjgK8" frameborder="0" allowfullscreen></iframe>
</div></code>```

Title: Item position by css?

Body:
I am new to html and css. Sorry this too easy question, maybe stupit. vid2 under the vid1, it's ok. But, I try to put vid3 rigth of to vid1. But It isn't working.

Actually, I am tring to do something like that;

index.html;

[vid1]   [vid3]  [vid5]

[vid2]   [vid4]  [vid6]

Could you help me to fix code. Thank you.

.vid1
    {
    position: absolute; overflow:hidden; left: 10px; top: 10px; z-index:0;
    }
    .vid2
    {
    position : absolute; overflow:hidden; left::20px; top:180px;  z-index:0;
    }
    .vid3
    {
    position : absolute; overflow:hidden; left::200px; top:10px;  z-index:0;
    }

Body:
Used this I think help for you.

.video{width:300px; float:left;}

<div class="video">
<iframe class="vid1" src="http://www.youtube.com/embed/r9dsH8H-4P8" frameborder="0" allowfullscreen></iframe>
<iframe class="vid2" src="http://www.youtube.com/embed/i7sxqaC062A" frameborder="0" allowfullscreen></iframe>
</div>
<div class="video">
<iframe class="vid3" src="http://www.youtube.com/embed/YeJQBbtjgK8" frameborder="0" allowfullscreen></iframe>
<iframe class="vid4" src="http://www.youtube.com/embed/YeJQBbtjgK8" frameborder="0" allowfullscreen></iframe>
</div>


问:
Node .JS Crawler to JSON output is empty
So I am trying my hand at Node.js. I want to build a simple crawler which scans a page and then returns all links back in a json file. However, when I run the script it returns 0 links.

Here is my code in its entirety:

```<code>    var request = require('request');
    var cheerio = require('cheerio');
    var fs = require("fs");

    var url = 'https://stackoverflow.com/questions';

    //Create the blank array to fill:
    var obj = {
       table: []
    };

    var i = 0;

    request(url, function(err, resp, body){
      $ = cheerio.load(body);
      links = $('a'); //jquery get all hyperlinks

      $(links).each(function(i, link){
        var actualLink = $(link).attr('href');
          obj.table.push({id: i, url:actualLink}); //add some data
          i++;
      });

    });

    var json = JSON.stringify(obj);

    console.log(json);
</code>```

The output in the terminal is so:

$ !!

node nodetest.js

{"table":[]}

Can anyone see why this is blank? Bonus points for writing the final json to a file :)

答:
You must use obj inside the success callback of the request, that's where it gets populated:

```<code>request(url, function(err, resp, body) {
    $ = cheerio.load(body);
    links = $('a'); //jquery get all hyperlinks

    $(links).each(function(i, link) {
        var actualLink = $(link).attr('href');
        obj.table.push({id: i, url:actualLink}); //add some data
    });

    // Only here you can be sure that the "obj" variable is properly
    // populated because that's where the HTTP request completes
    var json = JSON.stringify(obj);
    console.log(json);
});
</code>```

In your code you have placed the console.log outside the request success which is asynchronous and thus the obj variable is not yet populated.

Also notice that you don't need the i variable. It will be passed to the each callback automatically, you don't need to be explicitly declaring or incrementing it.

As far as writing the result to a file is concerned, you could use the fs.writeFile function:

```<code>fs.writeFile("/tmp/test", json, function(err) {
    if(!err) {
        console.log("File successfully saved");
    }
});
</code>```

Body:
So I am trying my hand at Node.js. I want to build a simple crawler which scans a page and then returns all links back in a json file. However, when I run the script it returns 0 links.

Here is my code in its entirety:

    var request = require('request');
    var cheerio = require('cheerio');
    var fs = require("fs");

    var url = 'https://stackoverflow.com/questions';

    //Create the blank array to fill:
    var obj = {
       table: []
    };

    var i = 0;

    request(url, function(err, resp, body){
      $ = cheerio.load(body);
      links = $('a'); //jquery get all hyperlinks

      $(links).each(function(i, link){
        var actualLink = $(link).attr('href');
          obj.table.push({id: i, url:actualLink}); //add some data
          i++;
      });

    });

    var json = JSON.stringify(obj);

    console.log(json);

The output in the terminal is so:

$ !!

node nodetest.js

{"table":[]}

Can anyone see why this is blank? Bonus points for writing the final json to a file :)

Body:
You must use obj inside the success callback of the request, that's where it gets populated:

request(url, function(err, resp, body) {
    $ = cheerio.load(body);
    links = $('a'); //jquery get all hyperlinks

    $(links).each(function(i, link) {
        var actualLink = $(link).attr('href');
        obj.table.push({id: i, url:actualLink}); //add some data
    });

    // Only here you can be sure that the "obj" variable is properly
    // populated because that's where the HTTP request completes
    var json = JSON.stringify(obj);
    console.log(json);
});

In your code you have placed the console.log outside the request success which is asynchronous and thus the obj variable is not yet populated.

Also notice that you don't need the i variable. It will be passed to the each callback automatically, you don't need to be explicitly declaring or incrementing it.

As far as writing the result to a file is concerned, you could use the fs.writeFile function:

fs.writeFile("/tmp/test", json, function(err) {
    if(!err) {
        console.log("File successfully saved");
    }
});


问:
How to call / access a label in button action programmatically?
```<code>//This is the label

let changeLbl = UILabel(frame: CGRect(x: 20, y: 170, width: 300, height: 21))

self.view.addSubview(changeLbl)

//This is the button

let submitButton = UIButton(type: .system) // let preferred over var here

submitButton.addTarget(self, action: #selector(buttonAction) , for: UIControlEvents.touchUpInside)

self.view.addSubview(submitButton)

//and this is action of above button

func buttonAction(sender: UIButton!) {

}
</code>```

I want to call the above label in the following button function? like

```<code>func buttonAction(sender: UIButton!) {
    changeLbl.ishidden = true
</code>```

// want to access label here, but it's not working this way.
    }

答:
If You want access label then declare it Globally.
Below Code for that:</p>

```<code>class LabelDemo: UIViewController{
     var changeLbl: UILabel!
     override func viewDidLoad() {
         super.viewDidLoad()

         changeLbl = UILabel(frame: CGRect(x: 20, y: 170, width: 300, height: 21))
         changeLbl.backgroundColor = UIColor.black
         self.view.addSubview(changeLbl)

         //This is the button

         let submitButton = UIButton(type: .system) // let preferred over var here
        submitButton.backgroundColor = UIColor.green
        submitButton.frame = CGRect(x: 50, y: 150, width: 50, height: 30)
        submitButton.setTitle("hide", for: .normal)
        submitButton.addTarget(self, action: #selector(buttonAction) , for: UIControlEvents.touchUpInside)

        self.view.addSubview(submitButton)

     }
    func buttonAction(sender: UIButton!) {
        if changeLbl.isHidden {
            changeLbl.isHidden = false
        }else{
            changeLbl.isHidden = true
        }

     }
}
</code>```

Body:
//This is the label

let changeLbl = UILabel(frame: CGRect(x: 20, y: 170, width: 300, height: 21))

self.view.addSubview(changeLbl)

//This is the button

let submitButton = UIButton(type: .system) // let preferred over var here

submitButton.addTarget(self, action: #selector(buttonAction) , for: UIControlEvents.touchUpInside)

self.view.addSubview(submitButton)

//and this is action of above button

func buttonAction(sender: UIButton!) {

}

I want to call the above label in the following button function? like

func buttonAction(sender: UIButton!) {
    changeLbl.ishidden = true

// want to access label here, but it's not working this way.
    }

Body:
If You want access label then declare it Globally.
Below Code for that:

class LabelDemo: UIViewController{
     var changeLbl: UILabel!
     override func viewDidLoad() {
         super.viewDidLoad()

         changeLbl = UILabel(frame: CGRect(x: 20, y: 170, width: 300, height: 21))
         changeLbl.backgroundColor = UIColor.black
         self.view.addSubview(changeLbl)

         //This is the button

         let submitButton = UIButton(type: .system) // let preferred over var here
        submitButton.backgroundColor = UIColor.green
        submitButton.frame = CGRect(x: 50, y: 150, width: 50, height: 30)
        submitButton.setTitle("hide", for: .normal)
        submitButton.addTarget(self, action: #selector(buttonAction) , for: UIControlEvents.touchUpInside)

        self.view.addSubview(submitButton)

     }
    func buttonAction(sender: UIButton!) {
        if changeLbl.isHidden {
            changeLbl.isHidden = false
        }else{
            changeLbl.isHidden = true
        }

     }
}


答:
Hope this might help you it seems to be what you wanted.

https://wordpress.org/plugins/vectr-embedded-graphics-editor/

Title: Image resize Plugin for Wordpress

Body:
I need a plugin in WOrdpress that would meets the following requirements-

I need a plgin where we can upload an image that appears behind the mask and can be moveable and scaleable.

The user can scale and move the images around how they like, once they are happy then we want to be able to download as a jpg.

So basically users need to upload there own picture, be able to move it around and scale behind the mask. Once they have finished download it to jpg.

Is their any plugin aroud in Wordpress?

Thanks in advance. Any help would appreciated !


问:
Working with iOS Location Manager
I am developing an app that has many view. Into my app sometimes the user arrives to a view where he can ask for his position clicking over a button. I am trying to follow the Apple guide lines to only ask for the user position if the user allows to do it. What should I do, use the next first code into the app delegate and declare a location manager attribute into any view that the user invokes, passing the location manager attribute to the new view and from the old view and asking with the second next code anytime that the user clicks the button to locate himself?; or just use the second code, declaring a location manager attribute only into the views that allow to get the user location with a button, to check if the location services are enable?

First snippet.

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    // Add the navigation controller's view to the window and display.
    [window addSubview:navigationController.view];
    [window makeKeyAndVisible];

    // Create a location manager instance to determine if location services are enabled. This manager instance will be
    // immediately released afterwards.
    CLLocationManager *manager = [[CLLocationManager alloc] init];
    if (manager.locationServicesEnabled == NO) {
        UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:@"Location Services Disabled" message:@"You currently have all location services for this device disabled. If you proceed, you will be asked to confirm whether location services should be reenabled." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [servicesDisabledAlert show];
        [servicesDisabledAlert release];
    }
    [manager release];

    return YES;
}
</code>```

Second snippet.

```<code>- (IBAction)locateUser:(id)sender {

    if([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[[CLLocationManager alloc] init] autorelease];
        self.locationManager.delegate = self;
    } else {
        [[[[UIAlertView alloc] initWithTitle:@"Location services."
                                     message:@"Location services are disabled."
                                    delegate:nil
                           cancelButtonTitle:@"OK"
                           otherButtonTitles:nil] autorelease] show];
    }
}
</code>```

Thanks for reading.

答:
CoreLocation will handle all the alerts for you. If locations services are disabled and that you ask for the location, CoreLocation will show an alert telling so to the user with a button to go directly to Settings.app.

If you want to know what append you can check for the delegate call

```<code>- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
</code>```

The error here contains a code that will be kCLErrorDenied if the user doesn't let the app use location services.

Also, you should use CoreLocation when the user need it. It's not necessary to check for location services at launch and the overhead of multiple CLLocationManager is almost inexistent.

Title: Working with iOS Location Manager

Body:
I am developing an app that has many view. Into my app sometimes the user arrives to a view where he can ask for his position clicking over a button. I am trying to follow the Apple guide lines to only ask for the user position if the user allows to do it. What should I do, use the next first code into the app delegate and declare a location manager attribute into any view that the user invokes, passing the location manager attribute to the new view and from the old view and asking with the second next code anytime that the user clicks the button to locate himself?; or just use the second code, declaring a location manager attribute only into the views that allow to get the user location with a button, to check if the location services are enable?

First snippet.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    // Add the navigation controller's view to the window and display.
    [window addSubview:navigationController.view];
    [window makeKeyAndVisible];

    // Create a location manager instance to determine if location services are enabled. This manager instance will be
    // immediately released afterwards.
    CLLocationManager *manager = [[CLLocationManager alloc] init];
    if (manager.locationServicesEnabled == NO) {
        UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:@"Location Services Disabled" message:@"You currently have all location services for this device disabled. If you proceed, you will be asked to confirm whether location services should be reenabled." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [servicesDisabledAlert show];
        [servicesDisabledAlert release];
    }
    [manager release];

    return YES;
}

Second snippet.

- (IBAction)locateUser:(id)sender {

    if([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[[CLLocationManager alloc] init] autorelease];
        self.locationManager.delegate = self;
    } else {
        [[[[UIAlertView alloc] initWithTitle:@"Location services."
                                     message:@"Location services are disabled."
                                    delegate:nil
                           cancelButtonTitle:@"OK"
                           otherButtonTitles:nil] autorelease] show];
    }
}

Thanks for reading.

Body:
CoreLocation will handle all the alerts for you. If locations services are disabled and that you ask for the location, CoreLocation will show an alert telling so to the user with a button to go directly to Settings.app.

If you want to know what append you can check for the delegate call

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error

The error here contains a code that will be kCLErrorDenied if the user doesn't let the app use location services.

Also, you should use CoreLocation when the user need it. It's not necessary to check for location services at launch and the overhead of multiple CLLocationManager is almost inexistent.


问:
Get json via laravel command - Failed to open stream
I am writing a laravel command to read in reddit comments. I am running Laravel Framework version 5.2.45. My handle method looks like the following:

```<code><?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class reddit extends Command
{
    /**...**/
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $str = json_decode(file_get_contents('www.reddit.com/r/all/comments.json'));
        foreach ($str as $comments) {
            // dd($comments);
            foreach ($comments->data->children as $comment) {
                if ($comment->body_html == 'You') {
                    print_r($comment);
                } else {
                    print_r($comment);
                }
            }
        }
    }
}
</code>```

When executing the command I get the following error message:

[ErrorException]

  file_get_contents(www.reddit.com/r/all/comments.json): failed to open
  stream: No such file or directory

Any suggestions what I am doing wrong?

I appreciate your replies!

UPDATE
Using the following URL reddit.com/r/all/comments.json I get:

```<code> [ErrorException]
  file_get_contents(reddit.com/r/all/comments.json): failed to open stream: No such file or directory
</code>```

Exception trace:
       () at /home/ubuntu/workspace/app/Console/Commands/reddit.php:55
       Illuminate\Foundation\Bootstrap\HandleExceptions->handleError() at n/a:n/a
       file_get_contents() at /home/ubuntu/workspace/app/Console/Commands/reddit.php:55
       App\Console\Commands\reddit->handle() at n/a:n/a
       call_user_func_array() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Container/Container.php:507
       Illuminate\Container\Container->call() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Console/Command.php:169
       Illuminate\Console\Command->execute() at /home/ubuntu/workspace/vendor/symfony/console/Command/Command.php:256
       Symfony\Component\Console\Command\Command->run() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Console/Command.php:155
       Illuminate\Console\Command->run() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:794
       Symfony\Component\Console\Application->doRunCommand() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:186
       Symfony\Component\Console\Application->doRun() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:117
       Symfony\Component\Console\Application->run() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:107
       Illuminate\Foundation\Console\Kernel->handle() at /home/ubuntu/workspace/artisan:36

答:
Try this, worked for me: There is 307 Internal Redirect on http://www.reddit.com/r/all/comments.json

Try this:

```<code>  print_r(file_get_contents("https://www.reddit.com/r/all/comments.json"));
</code>```

Body:
I am writing a laravel command to read in reddit comments. I am running Laravel Framework version 5.2.45. My handle method looks like the following:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class reddit extends Command
{
    /**...**/
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $str = json_decode(file_get_contents('www.reddit.com/r/all/comments.json'));
        foreach ($str as $comments) {
            // dd($comments);
            foreach ($comments->data->children as $comment) {
                if ($comment->body_html == 'You') {
                    print_r($comment);
                } else {
                    print_r($comment);
                }
            }
        }
    }
}

When executing the command I get the following error message:

[ErrorException]

  file_get_contents(www.reddit.com/r/all/comments.json): failed to open
  stream: No such file or directory

Any suggestions what I am doing wrong?

I appreciate your replies!

UPDATE
Using the following URL reddit.com/r/all/comments.json I get:

 [ErrorException]
  file_get_contents(reddit.com/r/all/comments.json): failed to open stream: No such file or directory

Exception trace:
       () at /home/ubuntu/workspace/app/Console/Commands/reddit.php:55
       Illuminate\Foundation\Bootstrap\HandleExceptions->handleError() at n/a:n/a
       file_get_contents() at /home/ubuntu/workspace/app/Console/Commands/reddit.php:55
       App\Console\Commands\reddit->handle() at n/a:n/a
       call_user_func_array() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Container/Container.php:507
       Illuminate\Container\Container->call() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Console/Command.php:169
       Illuminate\Console\Command->execute() at /home/ubuntu/workspace/vendor/symfony/console/Command/Command.php:256
       Symfony\Component\Console\Command\Command->run() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Console/Command.php:155
       Illuminate\Console\Command->run() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:794
       Symfony\Component\Console\Application->doRunCommand() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:186
       Symfony\Component\Console\Application->doRun() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:117
       Symfony\Component\Console\Application->run() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:107
       Illuminate\Foundation\Console\Kernel->handle() at /home/ubuntu/workspace/artisan:36

Body:
Try this, worked for me: There is 307 Internal Redirect on http://www.reddit.com/r/all/comments.json

Try this:

  print_r(file_get_contents("https://www.reddit.com/r/all/comments.json"));


问:
How to pass checkbox input into a function in shinyServer()
I have this Shiny code, which is currently deployable via RStudio.
I expect it to take the user input from Checkbox and pass the value
to get_table() parameter logit.

```<code>library(ggplot2)
library(tidyverse)
library(ggrepel)
library(shiny)
library(DT)
#-------------------------
# Function
#-------------------------
get_table <- function (dat, logit=FALSE, wanted_cols = c("model","mpg","wt"), data_title="Foo table") {

  # This function creates a table
  # an perform log function if logit=TRUE

  dat_out <- select(dat, one_of(wanted_cols))
  if(logit) {
    dat_out <- select(dat, one_of(wanted_cols[2:length(wanted_cols)]))
    dat_out <- log(dat_out)
    dat_out <- bind_cols(dat[1], dat_out)

  }
  return(dat_out)

}

#-------------------------
# Begin Shiny App code (ui + server)
#-------------------------
# I literally want to use file as input
infile <- "https://gist.githubusercontent.com/seankross/a412dfbd88b3db70b74b/raw/5f23f993cd87c283ce766e7ac6b329ee7cc2e1d1/mtcars.csv"
dat <- read_delim(infile,delim=",", col_types = cols())
get_table(dat,logit=TRUE, wanted_cols=c("model","mpg","wt"), data_title="Cool Table")

ui <- shinyUI(
  fluidPage(

    #  Application title
    titlePanel("Checkbox"),

    # Sidebar with sliders that demonstrate various available
    # options
    sidebarLayout(
      sidebarPanel(
        checkboxInput("checkbox", label = "Log Scale", value = FALSE)
      ),

      # Show a table summarizing the values entered
      mainPanel(
        DT::dataTableOutput('myplot_table')
      )
    )
  )
)

server <- shinyServer(function(input, output, session) {

  output$value <- renderPrint({ input$checkbox })
  out_table <- get_table(dat,logit=FALSE, wanted_cols=c("model","mpg","wt"), data_title="Cool Table")
  output$myplot_table <- DT::renderDataTable(
    DT::datatable(out_table, options = list(pageLength = 10))
  )
})

shinyApp(ui = ui, server = server)
</code>```

Currently the Apps looks like this:

Now, when I checked the box, it doesn't pass the parameter to logit function.
If it works the value it the table will be log.

My question is how can I pass the checkbox value to the parameter in shinyServer() ? I tried this

```<code>out_table <- get_table(dat,logit=input$checkbox, wanted_cols=c("model","mpg","wt"), data_title="Cool Table")
</code>```

but gave error:

```<code>Warning: Error in .getReactiveEnvironment()$currentContext: Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
Stack trace (innermost first):
    47: .getReactiveEnvironment()$currentContext
    46: .subset2(x, "impl")$get
    45: $.reactivevalues
    44: $ [/Users/pduboois/Desktop/Test/toy_app/etc/allinone_app.R#11]
    43: get_table [/Users/pduboois/Desktop/Test/toy_app/etc/allinone_app.R#11]
    42: server [/Users/pdubooisa/Desktop/Test/toy_app/etc/allinone_app.R#57]
     1: runApp
Error in .getReactiveEnvironment()$currentContext() :
  Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
</code>```

答:
You're almost there! Simply make it reactive so that it will change according to its reactive values (the checkbox):

```<code>out_table <- reactive({
    return(get_table(dat,logit=input$checkbox, wanted_cols=c("model","mpg","wt"), data_title="Cool Table"))
})
</code>```

and use out_table() instead of out_table in output$myplot_table.

Body:
I have this Shiny code, which is currently deployable via RStudio.
I expect it to take the user input from Checkbox and pass the value
to get_table() parameter logit.

library(ggplot2)
library(tidyverse)
library(ggrepel)
library(shiny)
library(DT)
#-------------------------
# Function
#-------------------------
get_table <- function (dat, logit=FALSE, wanted_cols = c("model","mpg","wt"), data_title="Foo table") {

  # This function creates a table
  # an perform log function if logit=TRUE

  dat_out <- select(dat, one_of(wanted_cols))
  if(logit) {
    dat_out <- select(dat, one_of(wanted_cols[2:length(wanted_cols)]))
    dat_out <- log(dat_out)
    dat_out <- bind_cols(dat[1], dat_out)

  }
  return(dat_out)

}

#-------------------------
# Begin Shiny App code (ui + server)
#-------------------------
# I literally want to use file as input
infile <- "https://gist.githubusercontent.com/seankross/a412dfbd88b3db70b74b/raw/5f23f993cd87c283ce766e7ac6b329ee7cc2e1d1/mtcars.csv"
dat <- read_delim(infile,delim=",", col_types = cols())
get_table(dat,logit=TRUE, wanted_cols=c("model","mpg","wt"), data_title="Cool Table")

ui <- shinyUI(
  fluidPage(

    #  Application title
    titlePanel("Checkbox"),

    # Sidebar with sliders that demonstrate various available
    # options
    sidebarLayout(
      sidebarPanel(
        checkboxInput("checkbox", label = "Log Scale", value = FALSE)
      ),

      # Show a table summarizing the values entered
      mainPanel(
        DT::dataTableOutput('myplot_table')
      )
    )
  )
)

server <- shinyServer(function(input, output, session) {

  output$value <- renderPrint({ input$checkbox })
  out_table <- get_table(dat,logit=FALSE, wanted_cols=c("model","mpg","wt"), data_title="Cool Table")
  output$myplot_table <- DT::renderDataTable(
    DT::datatable(out_table, options = list(pageLength = 10))
  )
})

shinyApp(ui = ui, server = server)

Currently the Apps looks like this:

Now, when I checked the box, it doesn't pass the parameter to logit function.
If it works the value it the table will be log.

My question is how can I pass the checkbox value to the parameter in shinyServer() ? I tried this

out_table <- get_table(dat,logit=input$checkbox, wanted_cols=c("model","mpg","wt"), data_title="Cool Table")

but gave error:

Warning: Error in .getReactiveEnvironment()$currentContext: Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
Stack trace (innermost first):
    47: .getReactiveEnvironment()$currentContext
    46: .subset2(x, "impl")$get
    45: $.reactivevalues
    44: $ [/Users/pduboois/Desktop/Test/toy_app/etc/allinone_app.R#11]
    43: get_table [/Users/pduboois/Desktop/Test/toy_app/etc/allinone_app.R#11]
    42: server [/Users/pdubooisa/Desktop/Test/toy_app/etc/allinone_app.R#57]
     1: runApp
Error in .getReactiveEnvironment()$currentContext() :
  Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)

Body:
You're almost there! Simply make it reactive so that it will change according to its reactive values (the checkbox):

out_table <- reactive({
    return(get_table(dat,logit=input$checkbox, wanted_cols=c("model","mpg","wt"), data_title="Cool Table"))
})

and use out_table() instead of out_table in output$myplot_table.


问:
JDOQL subqueries - Class name _ could not be resolved
I'm new to JDOQL and I'm having troubles with the below. I'm trying to get the average salary for the department and then select the departments where the average salary is higher than a certain value.

```<code>Query averageSalaryByDep = pm.newQuery(Employee.class);
averageSalaryByDep.setResult("department, avg(salary)");
averageSalaryByDep.setGrouping("department");

Query qry = pm.newQuery(Department.class);
qry.setFilter("this.name == dep.name && averageSalary > 10000");
qry.declareVariables("Department dep, double averageSalary");
qry.addSubquery(averageSalaryByDep, "Department dep, double averageSalary", null);
</code>```

The error message I'm currently getting:

```<code>javax.jdo.JDOUserException: Class name averageSalary could not be resolved
    at org.datanucleus.api.jdo.NucleusJDOHelper.getJDOExceptionForNucleusException(NucleusJDOHelper.java:636)
    at org.datanucleus.api.jdo.JDOQuery.executeInternal(JDOQuery.java:391)
    at org.datanucleus.api.jdo.JDOQuery.execute(JDOQuery.java:216)
</code>```

答:
A subquery has a single variable name (and returns a single thing). If unsure about something, put what the single-string query would look like (and the resultant SQL) and then it ought to be clear. The JDO spec has some useful examples IIRC

Regarding what you wanted to retrieve, I'd suggest you look at something more like

```<code>Query averageSalarySubq = pm.newQuery(Employee.class);
averageSalarySubq.setResult("avg(salary)");
averageSalarySubq.setFilter("this.department = :outerDepartment");

Query qry = pm.newQuery(Department.class);
qry.setFilter("averageSalary > 10000");
qry.declareVariables("double averageSalary");
qry.addSubquery(averageSalarySubq, "double averageSalary", null, "this");
</code>```

which would equate to something like

```<code>SELECT FROM mydomain.Department WHERE
    (SELECT AVG(e.salary) FROM mydomain.Employee e WHERE e.department = this) > 10000
</code>```

hence subquery gets the average salary but joined to the outer query Department. Defining the SQL would reveal to you whether that is what you intend or not, but either way a subquery is for a single variable

Body:
I'm new to JDOQL and I'm having troubles with the below. I'm trying to get the average salary for the department and then select the departments where the average salary is higher than a certain value.

Query averageSalaryByDep = pm.newQuery(Employee.class);
averageSalaryByDep.setResult("department, avg(salary)");
averageSalaryByDep.setGrouping("department");

Query qry = pm.newQuery(Department.class);
qry.setFilter("this.name == dep.name && averageSalary > 10000");
qry.declareVariables("Department dep, double averageSalary");
qry.addSubquery(averageSalaryByDep, "Department dep, double averageSalary", null);

The error message I'm currently getting:

javax.jdo.JDOUserException: Class name averageSalary could not be resolved
    at org.datanucleus.api.jdo.NucleusJDOHelper.getJDOExceptionForNucleusException(NucleusJDOHelper.java:636)
    at org.datanucleus.api.jdo.JDOQuery.executeInternal(JDOQuery.java:391)
    at org.datanucleus.api.jdo.JDOQuery.execute(JDOQuery.java:216)

Body:
A subquery has a single variable name (and returns a single thing). If unsure about something, put what the single-string query would look like (and the resultant SQL) and then it ought to be clear. The JDO spec has some useful examples IIRC

Regarding what you wanted to retrieve, I'd suggest you look at something more like

Query averageSalarySubq = pm.newQuery(Employee.class);
averageSalarySubq.setResult("avg(salary)");
averageSalarySubq.setFilter("this.department = :outerDepartment");

Query qry = pm.newQuery(Department.class);
qry.setFilter("averageSalary > 10000");
qry.declareVariables("double averageSalary");
qry.addSubquery(averageSalarySubq, "double averageSalary", null, "this");

which would equate to something like

SELECT FROM mydomain.Department WHERE
    (SELECT AVG(e.salary) FROM mydomain.Employee e WHERE e.department = this) > 10000

hence subquery gets the average salary but joined to the outer query Department. Defining the SQL would reveal to you whether that is what you intend or not, but either way a subquery is for a single variable


答:
You store something in an output (output$value <- renderPrint(...)) but you never actually put that output in your UI. If you change your main panel to:

```<code>mainPanel(
        DT::dataTableOutput('myplot_table'),
        verbatimTextOutput('value')
      )
</code>```

at least you see the value appearing. This one is TRUE or FALSE.

Your second mistake is to forget that your out_table should be reactive. Otherwise it's only calculated once, being at the time of initialization of the app.

So change the assignment in your server to:

```<code>out_table <- reactive({
    get_table(dat,logit=input$checkbox,
              wanted_cols=c("model","mpg","wt"),
              data_title="Cool Table")})
output$myplot_table <- DT::renderDataTable(
    DT::datatable(out_table(), options = list(pageLength = 10))
  )
</code>```

pay attention: you get the value of a reactive value by calling it as a function (i.e. out_table() in the call to datatable)

Title: How to pass checkbox input into a function in shinyServer()

Body:
You store something in an output (output$value <- renderPrint(...)) but you never actually put that output in your UI. If you change your main panel to:

mainPanel(
        DT::dataTableOutput('myplot_table'),
        verbatimTextOutput('value')
      )

at least you see the value appearing. This one is TRUE or FALSE.

Your second mistake is to forget that your out_table should be reactive. Otherwise it's only calculated once, being at the time of initialization of the app.

So change the assignment in your server to:

out_table <- reactive({
    get_table(dat,logit=input$checkbox,
              wanted_cols=c("model","mpg","wt"),
              data_title="Cool Table")})
output$myplot_table <- DT::renderDataTable(
    DT::datatable(out_table(), options = list(pageLength = 10))
  )

pay attention: you get the value of a reactive value by calling it as a function (i.e. out_table() in the call to datatable)


问:
How to upload a picture with Ionic 2
I'm building an app with Ionic 2 and Django Rest Framework. I need to take a photo from gallery or camera and upload this picture to my server.

I have this code that opens the camera and takes a picture.

```<code>options = {}
Camera.getPicture(options).then((imageData) => {
    // imageData is either a base64 encoded string or a file URI
    // If it's base64:
    let base64Image = "data:image/jpeg;base64," + imageData;
}, (err) => {
});
</code>```

But I don't know where it saves the pictures or how can I send it to the server. I don't find anything on Internet.

Thanks

答:
To upload image to the server using Ionic 2 Framework, you have to use the Transfer plugin. Install transfer plugin using

```<code>ionic plugin add cordova-plugin-file-transfer
npm install --save @ionic-native/transfer
</code>```

Then call the upload function from Transfer class.

```<code>const fileTransfer: TransferObject = this.transfer.create();

  let options1: FileUploadOptions = {
     fileKey: 'file',
     fileName: 'name.jpg',
     headers: {}

  }

 fileTransfer.upload(imageDataLocalURL, 'http://localhost/ionic/upload',  options1)
.then((data) => {
 // success
 alert("success");
}, (err) => {
 // error
 alert("error"+JSON.stringify(err));
});
</code>```

Use the link to know more https://ampersandacademy.com/tutorials/ionic-framework-version-2/upload-an-image-to-the-php-server-using-ionic-2-transfer-and-camera-plugin

Title: How to upload a picture with Ionic 2

Body:
I'm building an app with Ionic 2 and Django Rest Framework. I need to take a photo from gallery or camera and upload this picture to my server.

I have this code that opens the camera and takes a picture.

options = {}
Camera.getPicture(options).then((imageData) => {
    // imageData is either a base64 encoded string or a file URI
    // If it's base64:
    let base64Image = "data:image/jpeg;base64," + imageData;
}, (err) => {
});

But I don't know where it saves the pictures or how can I send it to the server. I don't find anything on Internet.

Thanks

Body:
To upload image to the server using Ionic 2 Framework, you have to use the Transfer plugin. Install transfer plugin using

ionic plugin add cordova-plugin-file-transfer
npm install --save @ionic-native/transfer

Then call the upload function from Transfer class.

const fileTransfer: TransferObject = this.transfer.create();

  let options1: FileUploadOptions = {
     fileKey: 'file',
     fileName: 'name.jpg',
     headers: {}

  }

 fileTransfer.upload(imageDataLocalURL, 'http://localhost/ionic/upload',  options1)
.then((data) => {
 // success
 alert("success");
}, (err) => {
 // error
 alert("error"+JSON.stringify(err));
});

Use the link to know more https://ampersandacademy.com/tutorials/ionic-framework-version-2/upload-an-image-to-the-php-server-using-ionic-2-transfer-and-camera-plugin