text:
Q: Parse user list from Github's Json response So I'm parsing Github user array using AsyncHttpClient library. And the result of this parsing is String object with Json response (its still a draft):
private String getResponse()
{
    AsyncHttpClient client=new AsyncHttpClient();
    RequestParams params=new RequestParams();
    params.put("since","0");
    client.get("https://api.github.com/users", params,
            new AsyncHttpResponseHandler() {

                @Override
                public void onFailure(int arg0, Header[] arg1, byte[] arg2,
                                      Throwable arg3) {

                }

                @Override
                public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

                    try {
                        String content = new String(arg2, "UTF-8");
                        //content is json response that can be parsed.
                        response = content;
                    } catch (UnsupportedEncodingException e1) {
                        e1.printStackTrace();
                    }
                }
            });
    if (response.isEmpty())
        return "Users not found";
    else
        return response;
}

The question is how do I parse from this response? I mean, how do you do this when you don't know the structure of Github user api?
I'm trying to solve this smth like this:
private ArrayList<String> parseResponse (String response)
{

    try {
        JSONObject reader = new JSONObject(response);
        JSONObject nameObject = reader.getJSONObject("????"); //I don't know
           //how that object is called since no idea about structure!
        name = nameObject.getString("name");

        userList.add(name);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return userList;
}

And how to iterate this properly to get every user?
Thanks in advance.

A: Just navigate to https://api.github.com/users in your browser and take a look.
Example:
[
  {
    "login": "",
    "id": 0,
    "avatar_url": "",
    "gravatar_id": "",
    "url": "",
    "html_url": "",
    "followers_url": "",
    "following_url": "",
    "gists_url": "",
    "starred_url": "",
    "subscriptions_url": "",
    "organizations_url": "",
    "repos_url": "",
    "events_url": "",
    "received_events_url": "",
    "type": "User",
    "site_admin": false
  },
  {...}
]

You can see from the [] that the top-level element is a JSONArray. So you need to get this array, and then access the JSONObject at each index.
JSONArray users = new JSONArray(response);
for(int i=0; i<users.length(); i++){
    JSONObject user = users.getJSONObject(i);
    String login = user.getString("login");
}

A: To parse the login from every user on the response, you have to iterate over the JSONArray, like this:
try {
    JSONArray readerArray = new JSONArray(result);
    for(int i=0;i<readerArray.length();i++){
        JSONObject userObject = (JSONObject) readerArray.get(i);
        String login = userObject.getString("login");
        //add login to your ArrayList here
    }
   } catch (JSONException e) {
    e.printStackTrace();
   }

Where result is a String with your Json response.


text:
Q: PostgreSQL installation done but commands are no working I have installed PostgreSQL on my CentOS 6.5
I have installed the same with
http://www.enterprisedb.com/products-services-training/pgdownload
Now Postgres is running on 5432 that I have checked with
netstat -ant|grep 5432

but when I run a command like postgres or psql
I am getting error that
command not found

Please find attached image of the same.

A: Are you sure you want to be doing this as the root user and not as the postgres user?
If you login as the postgres user you'll have the right path and "psql" will connect as the postgres user.
Alternatively, you could say "psql -U postgres" and then when you're prompted for a password, the one that you selected at install time should work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prototype img src swap doesnt work in Firefox? I was using the following code in a function activated onClick to swap an image (id=bigPicture).  It worked great (in Chrome) and I moved on.  I go into Firefox later to check and was flabbergasted when it didn't work as expected.  The src does not change.  Now, I am a noob when it comes to prototype so maybe this isn't the correct way to go about things.  What do you folks think?
$(bigPicture).src = filename;

A: String quote the element id~
$('bigPicture').src=filename;


text:
Q: Sharing a LinkedBlockingQueue between Container Managed Threads I have an application, where I have some Producer Threads which need an Input Queue and a Buffer. The Buffer has an Observer, that empties the buffer once it reached a certain limit and puts batches on another Queue2. Queue2 then is read by a consumer which writes the batches.
Currently what I'm lacking in my program achitecture is a neat way to get these Queues and Buffer into the Runnables, without doing Constructor magic or Setter.
I cannot use @Inject, since the CDI Context is not propagated to the subthreads. One could implement his own context, that does things similar to the ApplicationScopedContext, but currently I'm not willing to do this (if someone has a good implementation example please let me know).
Since the JNDI Tree is propagated to the Subthreads I thought about using it, but I fear the Serialization, which is definitely not what I want with Queues.
So my question is: Are Objects that are bound into the JNDI Tree in Wildfly 10 References or are they Serialized?


text:
Q: Serial Chart in amCharts showing different beahaviour I am using amCharts for my App. Recently I updated it from version 3.17.0 to 3.20.6.
In my App, I have used export with capture method to capture image as below:
if (window.fabric) {
                    clearTimeout(interval);

                    // CAPTURE CHART
                    chart.export.capture({}, function() {

                        // SAVE TO JPG
                        this.toPNG({}, function(base64) {

                            //some code
                                                    });
                    });
                }
 }, 10);

In my serial chart with Chart cursor, It was working fine as below in previous version. See image:
After updating version it shows weird behavior: ChartCursor gone, and on dragging cursor it is drawing line on Chart.
I have checked on amChart website, I have correctly set everything.
What can be wrong here?
If I will disable chart.export.capture, it' will working fine.
Here is my code to set properties chart:
"type": "serial",
                "theme": "none",
                "pathToImages": "resources/javascript/amcharts/images/",
                "marginTop": 1,
                "marginBottom": 1,
                "autoMarginOffset": offsetM,
                //left hand side space between container and chart
                "zoomOutButtonRollOverAlpha": 0.15,

                "zoomControl": {
                    "zoomControlEnabled": true,
                    "backgroundAlpha": "0.15",
                    "backgroundColor": "#000000"
                },

                "dataProvider": valueChartData,
                "columnWidth": 1,
                "categoryField": "date",
                "categoryAxis": {
                    "minPeriod": "DD",
                    "parseDates": true
                },

                "export": {
                    "enabled": false,
                    "menu": []
                }

for exporting and cloning chart:
var interval = setInterval(function() {
                    if (window.fabric) {
                        clearTimeout(interval);

                        // CAPTURE CHART
                        main.pageContainerBulkMarketing.bulkmarketing.pageContainerBMReports.reports.chart["export"].capture({}, function() {

                            // SAVE TO JPG
                            this.toPNG({}, function(base64) {

                                somewhere.OpenedTabGrpClone = "";
                                somewhere.OpenedTabGrpClone = base64;
                            });
                        });
                    }
                }, 10);

Note: I have observed one thing: It is adding one canvas tag over our chart div, it is like:
<canvas class="upper-canvas " style="position: absolute; width: 802px; height: 360px; left: 0px; top: 0px; -moz-user-select: none; cursor: crosshair;" width="802" height="360"></canvas>

UPDATE: Here I have added jsfiddle But, here it is working fine, I took this time to figure out that why it's not working my side; result :none.

A: Simple do this
1) Check your library links and plugin code , may it interfer with other js or plugin .
2) Also Test your code with live amchart libraries.
3) if every thing fine and working set Z-index by -1 for canvas tag.


text:
Q: Is there any implementation of database by perl Is there any perl modules implementing function of database and easy to use. I do not need modules used to connect to some database products. I need simple database writing by perl.
Thanks.

A: If you can live without SQL and relations, give DBM::Deep a try. Easiest of all, I wouldn't use it in production environment for sure, but it is ideal for rapid prototyping.

DESCRIPTION
A unique flat-file database module, written in pure perl. True multi-level hash/array support (unlike MLDBM, which is faked), hybrid OO / tie() interface, cross-platform FTPable files, ACID transactions, and is quite fast. Can handle millions of keys and unlimited levels without significant slow-down. Written from the ground-up in pure perl -- this is NOT a wrapper around a C-based DBM. Out-of-the-box compatibility with Unix, Mac OS X and Windows.

A: I would suggest using DBD::SQLite. This is a self-contained database management system with no dependency to external binaries (unlike most others DBI drivers). It has nice options such as creating in-memory databases.
SQLite is an open-source RDBMS that implements a significant subset of the SQL ANSI Standard.
DBD::SQLite is a legitimate DBI driver, so it conforms to the API of the great DBI module, which is the de-facto Perl standard interface for databases.
From the documentation:

DBD::SQLite is a Perl DBI driver for SQLite, that includes the entire thing in the distribution. So in order to get a fast transaction capable RDBMS working for your perl project you simply have to install this module, and nothing else.


text:
Q: Highchart spline Chart with no markers and legends markers as circle's Can anyone help me with this, I need the following legend marker symbol marked in the image as a circle?
I have tried adding marker: circle inside series but it is not working.
I am new to Highcharts. Is there any possible way to fix this?
Thanks in advance.

NOTE: My chart has multiple series.
{
  "series": [{
    "name": "Test series",
    "data": [{

      "y": 8,

    }, {

      "y": 10,

    }, {

      "y": 15,

    }, {

      "y": 8,

    }],
    "type": "spline",
    "color": "#dd0014",
    marker: {
      symbol: 'circle'
    }
  }],
  "xAxis": {
    "categories": ["cat-1", "cat-2", "cat-3"],
  },

  "plotOptions": {
    "series": {
      "marker": {
        "symbol": "circle",
        "enabled": false
      },

    },

  },
  "legend": {
    "align": "right",
    "enabled": true,
    "y": 35,
    "x": 0,
    "verticalAlign": "top",
    "layout": "vertical",
    "itemStyle": {
      "fontSize": "12px",
      "fontWeight": "light"
    },
    "reversed": true,
    "symbolRadius": 9,
    "itemMarginTop": 3,
    "itemMarginBottom": 3,
    "marker": "circle"
  },
  "colors": ["#00B19D", "#4E3363", "#3A99D5", "#00AE84", "#49494A", "#318ACA"],
  "credits": {
    "enabled": false
  },

}

JsFiddle Link here

A: I have found a workaround solution after going through the Highcharts documentation.
 chart: {
    events: {
      load: function() {
        $(".highcharts-legend-item path").attr('stroke-width', 10);
        $(".highcharts-legend-item path").attr('d', "M 8 14.75 Z 61.25 61.25 99 1 1 33.45 44.00");
        $(".highcharts-legend-item path").attr("stroke-linecap", "round");
      },
      redraw: function() {
        $(".highcharts-legend-item path").attr('stroke-width', 10);
        $(".highcharts-legend-item path").attr('d', "M 8 14.75 Z 61.25 61.25 99 1 1 33.45 44.00");
        $(".highcharts-legend-item path").attr("stroke-linecap", "round");
      }
    }
  },

added this to update legend symbols using JQUERY
DEMO LINK HERE


text:
Q: using public shared on a master page can't access it from a class I'm using asp.net and vb.net as the code behind.  In the masterpage of an existing website I had this
namespace WebAdminV2
{
public partial class WebAdmin : System.Web.UI.MasterPage
{
    public static SitePlumbing.CurrentSession oCurrentSession;

WebAdmin is the name of the masterpage.
In another class i was using this shared current session with this code
  CurrentSession O = WebAdminV2.WebAdmin.oCurrentSession;

That worked.  Now i'm trying to convert it to vb.net and having the problem where it does not see the WebAdminV2.WebAdmin.oCurrentSesion.  The master page looks like this
Namespace WebAdminV2
Partial Class WebAdmin
    Inherits System.Web.UI.MasterPage

    Public Shared oCurrentSession As SitePlumbing.CurrentSession

and the class trying to use oCurrentSession
Dim O As CurrentSession = WebAdminV2.WebAdmin.oCurrentSession

It tells me that WebAdminV2 is not declared.  If i comment out the line above the site does compile without errors.  The class that I'm trying to use that will reference the oCurrentSesion on the master page is not another page.
Anyway, I'd like to understand what i've done wrong.
Thanks
Shannon


text:
Q: A subset that is closed under multiplication but not addition? I can't get my head around subspaces despite having studied on them quite a lot. Here goes:
The problem statement, all given variables and data
Give an example of a non-empty subset U of R^2 such that U is closed under scalar multiplication but is not a subspace of R^2.
Attempt at a solution
So a set such as [x1, x2] | x1 >= 0 is NOT closed under scalar multiplication but is closed under addition. I get this but I cannot find an answer in reverse.
A wild guess is x1 + x2 + 2 = 0. I could multiply it and 2x1 + 2x2 + 4 = 0 would still hold true. However, if I wish to perform an addition on it, I don't exactly understand what I add to what equation exactly.. it's all so bogged up. Help would be appreciated. :-)

A: Since you only need a subset for this example- we can "cheat" a bit. We shall define our subset $U$ to be the union of $x$ axis, and the $y$ axis, i.e.
$U$= $\{(x,0):x \in \mathbb{R}\} \cup \{(0,y):y \in \mathbb{R}\}$


text:
Q: How to make a list of foreign key objects in Entityframework I'm developing in asp.net core 2 webApi with mysql DB (code first)
In my application I have models:

*

*country : that has: Id, Name.

*element : that one of it's variables should be List<Country> countries
The problem is that when the database is created the relation that it does is:
in country I have elementId and countries will be duplicated
Should I create element_country model that will have : elementId, CountryId?
If so, how should I pass the object to the view without creating special viewmodel for that purpose,
I believe it's something small that I am missing and I would appreciate the help.
Thanks


text:
Q: QDateEdit validations I'm trying validate two QDateEdits. I have two fields, startdate and enddate and i want to validate that the minimum date of enddate be the selected startdate date. But also, i want give the user opportunity that the enddate field can be empty.
I conected both fields
connect(startDate,SIGNAL(dateChanged(QDate)),endDate,SLOT(setMinDate(QDate)));

startDate and endDate are QDateEdit with a popup calendar.
So, where is the problem here?? When i click over endDate the minimun date it's ok but the next day (fisrt valid date) appears in blue color like it was selected, but when i clicked over that date the popup close and the date it's not set. For example:
When i open the form the startdate field have by default the current date. Latter i click over endDate field and the minimum allowed date is one more day  wich it's ok, but this minimum allowed date it's blue marked and when i clicked the date it's not set.
Sorry if my english it's so bad, i hope that you can help me. Thanks any way

A: I found what my problem is. I connected the slot to dateChanged(QDate) signal, so, by default the QDateEdit set the first allowed date as selected, so if you select it again the signal it's not emited and by result the date it's not set. My solution is use editingFinished() signal instead dateChanged(QDate) signal. I hope has been helpful. Regards,


text:
Q: Struggling with a few CSS things for my menu I'm trying to make my site's menu bar better for mobile-devices..
I currently have it so it will shrink down to a little click-to-open, drop-down menu that shows my links to other pages..
My first issue I found was my menu was longer than the screen size and I couldn't scroll to show the rest of the content, so I had a look around and have now solved the issue but created another..
Whats happening is, I can open the menu just fine, choose items and scroll inside the menu as expected.. but when I click the menu button again, to hide the menu again, the links 'pull out of sight' but it leaves the background of the menu on show..
@media (max-width: 767px) {
.scroll-to-top {
    display: none;
}
.show-menu {
    display: block !important;
    visibility: visible !important;
    position: fixed;
    width: 100%;
    height: 300px;
    z-index: 999;
    overflow-y: scroll;
    -webkit-transform: translate3d(0,0,0);
    -webkit-overflow-scrolling: touch;
}}

I had trouble getting the scrollable menu to work but finally, I found adding the "height: xx;" part solved that issue..
I'm not very clued up about all of this stuff but try and learn from editing existing examples etc.
Can anyone see anything obvious?
[Solved]
2
(Same menu as before.)
I found this last night that I have added to my site:
@media (min-width: 768px) {.dropdown-menu li:hover .menu {visibility: visible;}}
@media (min-width: 768px) {.dropdown:hover .dropdown-menu {display: block;}}

I believe it makes my menu's click-to-display, when they would normally be hovered over when your viewing the site on a mobile-device..
I'd like to add an additional statement that sort of does the opposite, so if you were to click on an open menu, it would close again..

3
(same menu)
The way my theme I am using on my site was constructed, makes 3rd level menu items appear as a bulleted list below the 2nd level link..
I would like to change this so the 3rd level links are also, not shown as a list but rather have their own menu that drops out as well..
echo '

';

        foreach ($context['menu_buttons'] as $act => $button)
        {
            echo '

                            ', !empty($modSettings['smi_enable']) ? ' ' : '', '', $button['title'], '', !empty($button['sub_buttons']) ? ' ' : '' ,'
                        ';
            if (!empty($button['sub_buttons']))
            {
                echo '

';

                foreach ($button['sub_buttons'] as $childact => $childbutton)
                {
                    echo '

                                    ', !empty($modSettings['smi_enable']) ? ' ' : '', '', $childbutton['title'], !empty($childbutton['sub_buttons']) ? '...' : '', '
                                ';
                    // 3rd level menus :)
                    if (!empty($childbutton['sub_buttons']))
                    {
                        echo '

';

                        foreach ($childbutton['sub_buttons'] as $grandchildbutton)
                            echo '

                                            ', $grandchildbutton['title'], '

';

                        echo '

';
                    }

                    echo '

';
                }
                    echo '

';
            }
            echo '

';
        }

        echo '

';

}
Like I've mention before, I really don't have much knowledge about this stuff, but I believe the above code constructs the menu..
Any help appreciated and I can provide more code chunks / links if needed! :)
Many thanks!

A: 2:
You need to add this jquery code under a script tag :
if(screen.width<=768){
$('.dropdown').on('click',function(){
    $('.dropdown-menu').toggle();
});
}

And you should delete the styling that you just posted in your question.
3:
This is the code for it :
echo '

';

        foreach ($context['menu_buttons'] as $act => $button)
        {
            echo '

                            ', !empty($modSettings['smi_enable']) ? ' ' : '', '', $button['title'], '', !empty($button['sub_buttons']) ? ' ' : '' ,'
                        ';
            if (!empty($button['sub_buttons']))
            {
                echo '

';

                foreach ($button['sub_buttons'] as $childact => $childbutton)
                {
                    echo '

                                    ', !empty($modSettings['smi_enable']) ? ' ' : '', '', $childbutton['title'], !empty($childbutton['sub_buttons']) ? '...' : '', '
                                ';
                    // 3rd level menus :)
                    if (!empty($childbutton['sub_buttons']))
                    {
                        echo '

';

                        foreach ($childbutton['sub_buttons'] as $grandchildbutton)
                            echo '

                                            ', $grandchildbutton['title'], '

';

                        echo '

';
                    }

                    echo '

';
                }
                    echo '

';
            }
            echo '

';
        }

        echo '

';

And you should add this jquery code as well (like in the 2) :
$('.dropdown-toggle1').on('click',function(){
        $('.dropdown-menu1').toggle();
    });

Note: I used the click event in those list items , so I should make the anchor href="#". If you want to make them appear at hovering, you should make it with CSS like your 2nd issue was.


text:
Q: Django how to get multiple context_object_name for multiple queryset from single view to single template I want to run multiple queryset from single view.
I have done for single get_queryset and single context_object_name to pass into index.html template :
class IndexView(generic.ListView):
    template_name = 'doorstep/index.html'
    context_object_name = 'all_hotels'

    def get_queryset(self):
        return Hotel.objects.all().order_by('rating').reverse()[:3]

Now, i need to run this queryset
Hotel.objects.all().order_by('star').reverse()[:3]
from same IndexView and pass context_object_name from this querset to same template_name.
I get the value as {% for hotel in all_hotels %} in the template

A: Override get_context_data and add any additional querysets to the context.
class IndexView(generic.ListView):
    template_name = 'doorstep/index.html'
    context_object_name = 'all_hotels'

    def get_queryset(self):
        return Hotel.objects.all().order_by('rating').reverse()[:3]

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['star_hotels'] = Hotel.objects.all().order_by('star').reverse()[:3]
        # Add any other variables to the context here
        ...
        return context

You can now access {{ star_hotels }} in your template.


text:
Q: How to insert Time with AM/PM to MySQL database using PHP I want to insert Time in MySQL database. In database I have two separate Fields for Date(date type) and Time(Time type). To insert a record I tried like below in my PHP. But Time only inserted(10:00:00). not AM/PM inserted. How to insert Time with AM/PM in PHP.
mysql_query("INSERT INTO Http(mobile, imei, time,date) VALUES ('1232456785', '123369584895544', TIME_FORMAT( '10:00:00', '%h:%i:%s %p' ),'2011/09/13')");

A: You can't do it. Here are formats for TIME type: http://dev.mysql.com/doc/refman/5.0/en/time.html


text:
Q: Why isn't my github project going live? I created a subbranch for gh-pages. I don't know why the page isn't getting created. I'm attaching the screen shot of the bash.
Even at the github page, when I hover over the tick mark, it says that github has successfully created the page.
Link to my github

A: To make a github pages site, you must follow the naming convention for your repository; in your case puneeth8994.github.io.
Also, the main html file should be called index.html.
The following is a great resource to get started on github pages:
https://24ways.org/2013/get-started-with-github-pages/


text:
Q: java.lang.ClassCastException: java.lang.String cannot be cast to com.example.service.AlbumService I using spring mvc and hibernate xml mapping. And I have error about  in jsp:
My jsp (storeManager.jsp):
<jsp:useBean id="albumService" type="com.example.service.AlbumService" scope="request" />

            Genre
            Artist
            Title
            Price

        <%for (Album myAlbum : albumService.getAllAlbums()) { %>
            <%int tempGenreId = myAlbum.getGenreId().getGenreId(); %>
            <%int tempArtistId = myAlbum.getArtistid().getArtistid(); %>
            <%=albumService.findGenreByIdFromAlbumRepository(tempGenreId).getName()%>
            <%=albumService.findArtistByIdFromAlbumRepository(tempArtistId).getName()%>
            <%=myAlbum.getTitle()%>
            <%=myAlbum.getPrice()%>
            <a href="EditAlbum?editAlbumId=<%=myAlbum.getAlbumId()%>">Edit
            <a href="DetailsAlbum?detailsAlbumId=<%=myAlbum.getAlbumId()%>">Details
            <a href="DeleteAlbum?deleteAlbumId=<%=myAlbum.getAlbumId()%>">Delete

        <%}%>

And my Controller(StoreManagerController.java)
@Controller
@RequestMapping("/StoreManager")
public class StoreManagerController
{
@Autowired
private AlbumService albumService;

@Autowired
private GenreService genreService;

@Autowired
private ArtistService artistService;

@RequestMapping(value="/", method = RequestMethod.GET)
public ModelAndView getStoreManagerPage(HttpServletRequest request, HttpSession session,ModelMap model) {

    logger.debug("JUST GOT STORE MANAGER PAGE");

    List<Album> albumList = albumService.getAllAlbums();
    model.put("albumList", albumList);

    return new ModelAndView("storeManager", "albumService" , "albumService");
}

When I deploy and run. it happent a error following:
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/storeManager.jsp at line 18

15: <%@page import="java.util.List" %>
16: <%@page import="java.util.Map" %>
17:
18: <jsp:useBean id="albumService" type="com.example.service.AlbumService" scope="request" />
19:
20:
21: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:510)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
ch.qos.logback.classic.selector.servlet.LoggerContextFilter.doFilter(LoggerContextFilter.java:70)

root cause

java.lang.ClassCastException: java.lang.String cannot be cast to com.example.service.AlbumService
org.apache.jsp.WEB_002dINF.jsp.storeManager_jsp._jspService(storeManager_jsp.java:78)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:377)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
ch.qos.logback.classic.selector.servlet.LoggerContextFilter.doFilter(LoggerContextFilter.java:70)

How can I solve this error?

A: Looks like the third parameter where you're creating the ModelAndView object is incorrect. You're passing in a string, but the jsp:useBean tag is expecting it to be an AlbumService object.
Change
return new ModelAndView("storeManager", "albumService" , "albumService");

to
return new ModelAndView("storeManager", "albumService" , albumService);


text:
Q: Export Excel to PPT and random Picture from File ok, so im stuck since a while and dont know how tackle this problem.
Situation: I have excel file with data where i filter down to the data that i want to export. There i already have a macro that exports me the selection to PowerPoint (and that works just fine).
Until now i have a dummy picture on the PPT slides that i have to change manually.
I want to change that.
I want to insert a random generator that inserts a random picture from a set of pictures in a folder on my pc on .
I do understand the basics of how a random generator works but im nowhere near understanding on how to apply that to my case, and where i have to insert the generator it into the code.
Here is my code for the excel to PPT.
Sub XLS_to_PPT()

Dim pptPres As Presentation
Dim strPfad As String
Dim strPOTX As String
Dim pptApp As Object
Dim strSave As String

strPfad = Application.ActiveWorkbook.Path
strPOTX = "Credential_PPT_Template.pptx"
strSave = Application.ActiveWorkbook.Path

Set pptApp = New PowerPoint.Application

pptVorlage = strPfad & "\" & strPOTX

pptApp.Presentations.Open Filename:=pptVorlage, untitled:=msoTrue

Set pptPres = pptApp.ActivePresentation

For Each tableRow In Sheets("Credentials").ListObjects("Credential_Submission").DataBodyRange.SpecialCells(xlCellTypeVisible).Rows
Set newSlide = pptPres.Slides(1).Duplicate
newSlide.Shapes("PMOTeamSize").TextFrame.TextRange.Characters.Text = tableRow.Columns(69).Value
newSlide.Shapes("TeamSize").TextFrame.TextRange.Characters.Text = tableRow.Columns(65).Value
newSlide.Shapes("Header").TextFrame.TextRange.Characters.Text = tableRow.Columns(4).Value
newSlide.Shapes("ClientChanlenge").TextFrame.TextRange.Characters.Text = tableRow.Columns(75).Value
newSlide.Shapes("HowWeHelped").TextFrame.TextRange.Characters.Text = tableRow.Columns(76).Value
newSlide.Shapes("ClientBenefitsDelivered").TextFrame.TextRange.Characters.Text = tableRow.Columns(77).Value

Next tableRow

pptPres.Slides(1).Delete

pptPres.SaveAs strSave & "\" & ("New_Request")

pptPres.Close

Set pptPres = Nothing
Set pptApp = Nothing

End Sub

A: One of approach is:
Public Function GetRandImageFile(imFolder As String) As String
    Static list As Collection
    Static lastFolder As String

    If list Is Nothing Or lastFolder <> imFolder Then
        On Error GoTo out
        lastFolder = imFolder
        Set list = New Collection
        cnt = 0
        Set fs = CreateObject("Scripting.FileSystemObject")
        Set fd = fs.getfolder(lastFolder)
        For Each f In fd.Files
            pos = InStrRev(f.Name, ".")
            ext = ""
            If pos > 0 Then ext = LCase(Mid(f.Name, pos))
            Select Case ext
                Case ".jpg", ".png", ".bmp" ' and so on
                    list.Add f.Name, CStr(cnt)
                    cnt = cnt + 1
            End Select
        Next
    End If

    Randomize
    slash = IIf(Right(lastFolder, 1) <> "\", "\", "")
    GetRandImageFile = lastFolder & slash & list(Rnd() * (list.Count - 1) + 1)
out:
End Function


text:
Q: How to avoid joining to a same dimension table twice I have table task_instances that has task_id, end_time , start_time.
end_time and start_time links to time_table which contains military_hour format (24 hour ranging from 0 -23).
I want to know all the tasks  where each tasks start time and end_time belong to the same military hour group ( there are 6 groups , each containing 4 hours).
  select (floor(td1.military_hour/4)*4) as td1_military_hour_group,
  (floor(td2.military_hour/4)*4) as td2_military_hour_group, wk_id
  from task_instances t1
  inner join time_table td1 on t1.end_time = td1.time_id
  inner join time_table td2 on t1.start_time = td2.time_id
  where  td1_military_hour_group = td2_military_hour_group

Is it required to join same time_table twice. Can we better the query or even the query seems correct?

A: You can't use the derived values td1_military_hour_group and td2_military_hour_group in the WHERE clause or you'll get an error, e.g. "Unknown column 'td1_military_hour_group' in 'where clause'". You'll need to repeat the calculations in the WHERE clause:
select wk_id,
       (floor(td1.military_hour/4)*4) as td1_military_hour_group,
       (floor(td2.military_hour/4)*4) as td2_military_hour_group
  from task_instances t1
  inner join time_table td1
    on t1.end_time = td1.time_id
  inner join time_table td2
    on t1.start_time = td2.time_id
  where (floor(td1.military_hour/4)*4) = (floor(td2.military_hour/4)*4)

Or else use a common table expression:
WITH cteTime_groups AS (SELECT time_id,
                               floor(military_hour/4)*4 AS military_hour_group
                          FROM time_table)
select wk_id,
       td1.military_hour_group as td1_military_hour_group,
       td2.military_hour_group as td2_military_hour_group
  from task_instances t1
  inner join cteTime_groups td1
    on t1.end_time = td1.time_id
  inner join cteTime_groups td2
    on t1.start_time = td2.time_id
  where td1.military_hour_group = td2.military_hour_group

SQLFiddle here


text:
Q: Intuition for why any square matrix is a sum of a symmetric matrix and a skew-symmetric matrix? I've seen proofs for this theorem and understood then. However, I feel like I can gain a better intuition.

*

*I would never think of this theorem myself. How could someone discover this theorem?

*Is there a visual intuition?

*Any other things that you think can help me gain a better intuition for that theorem?
(Feel free to answer even without answering all of the above questions. Such answers can still be helpful :) )

A: This is a nice question I had at one point, too. I'll echo the explanation I got at the time.
If $V$ is a vector space, a linear map $P\colon V\to V$ satisfying $P^2 = P$ is called a "projection." Given any projection, it is always possible to write a vector in a unique way as a sum of something in the kernel and something in the image. For matrices and the symmetric + skew-symmetric decomposition, you can check that
$$
P(A) = \frac12(A-A^T)
$$
is a projection whose kernel is the symmetric matrices and whose image is the skew symmetric matrices. In the case of functions on $\mathbb R$ and the even + odd decomposition, you can prove
$$
P(f)(x) = \frac12(f(x)-f(-x))
$$
is a projection whose kernel is the even functions and whose image is the odd functions.
Even more, these two specific projections both arise in the following way. An involution is a linear map $T\colon V\to V$ such that $T^2 = I$, where $I\colon V\to V$ is the identity map $I(v) = v$. If $T$ is an involution, then $\frac12(I-T)$ is a projection. The involution in the case of matrices is $T(A) = A^T$ (take the transpose), and the involution in the case of functions is the reflection map $T(f)(x) = f(-x)$.
Another involution you may like to think about is the complex conjugation map that takes a complex number $z = x + iy$ to the complex number $\bar z$ defined by
$$
\bar z = x - iy.
$$
Then we can also realize the decomposition
$$
z = \mathrm{re}(z) + i\mathrm{im}(z) = (\frac{z+\bar z}{2}) + i(\frac{z-\bar z}2)
$$
as an example of this phenomenon.

A: The intuition really is as follows: try to solve a $2\times 2$ system of linear equations!
Let's say you have a matrix $A$ and you want to write it as a sum of a symmetric matrix $X$ and a skew-symmetric matrix $Y$, i.e. you have the problem "Let $A=X+Y$, solve in $X,Y$".
Now, the only thing you know about $X$ and $Y$ is their behaviour around transpose, so you transpose the previous equation  (what else can you do?), and you get $A^\top=(X+Y)^\top=X^\top+Y^\top=X-Y$
Right, so now you have a system of two equations with two unknowns:
$$\begin{array}{rcl}X+Y&=&A\\X-Y&=&A^\top\end{array}$$
which you can then solve using your favourite method (Gaussian elimination or whatever else you can think of) to get $X=\frac{1}{2}(A+A^\top)$, $Y=\frac{1}{2}(A-A^\top)$.

A: Let us consider the set $S$ of symmetric matrices.
The answer of Alex Ortiz is in terms of projection :
$$s(A):=\frac12(A+A^T)$$
is the projection of $A$ onto $S$.
As you ask about intuition, there is a cousin way to arrive at the same concept : $s(A)$ as defined by (1) is the closest symmetric matrix to $A$ closest in terms of a matrix norm. Any norm could be taken (indeed, all matrix norms are equivalent). I choose here to use the spectral norm.
Proof :
Let $C$ be a generic element of $S$ (we have therefore $C=C^T$).
$$A-s(A)=A-\frac12(A+A^T)=\frac12(A-A^T)=\frac12((A-C)-(A-C)^T)$$
As a consequence :
$$\|A-s(A)\|\leq\frac12(\|A-C\|+\|(A-C)^T\|)=\|A-C\|$$
because the norm of a matrix is equal to the norm of its transposed matrix (see for example here a proof for the spectral norm : Squared norm of matrix equal to squared norm of its transpose).
A same kind of reasoning can be made for the closest antisymmetric matrix to a given matrix $A$.
In fact we could introduce the dot product $<A,B>=tr(A^TB)$  as here and prove that the two spaces, the space of symmetric matrices and the space of antisymmetric matrices are orthogonal.

A: Some stuff, sometimes, appear by magic, I remember when I was trying to play with matrices once, I wrote $B = A + A^t$, and I said hmm, isn't this symmetric?  Will yeah $B$ is in fact symmetric since $B^t = (A+ A ^t)^t = A^t + (A^t)^t = A^t + A = B$, what about if I chose $C = A - A^t$ is it symmetric too or maybe anti-symmetric? Redoing the same steps we observe that $C^t = -C$.
Now let's just remember we didn't mention anything regarding $A$, we didn't put any restriction on it (of course it has to be a square matrix), but the fact that
\begin{cases}
B^t = (A + A^t)^t = B\\
C^t = (A - A^t)^t = -C
\end{cases}
Is interesting since if we add $B$ to $C$ it would yield
$$
B + C = A + A^t + (A - A^t) = 2A = B^t - C^t \implies A = \frac{1}{2}\left(B^t - C^t\right)
$$
Which is really cool


text:
Q: Three issues (possibly) related to read-only filesystem Previously, I had a flash drive full of both Ubuntu images and other OSs. I moved them (didn't copy them) from that flash drive to another with more storage space. In the process, something went wrong and I ended up having to reformat both drives. I lost all of my OSs that I've spent months collecting and trying (I'm still new to Linux).
Now, I'm trying to re-download the Ubuntu images I had, however, when I click download on the website, nothing happens. When I click download now on the next page (if you click this, you'll probably be prompted to save the .iso), nothing happens either.
I don't know if this is an issue with Firefox or if my entire system is mounted read-only.

When I use wget to download the .iso, it says:
Cannot write to 'ubuntu-17.04-desktop-amd64.iso' (Read-only file system).

I don't know if this is my installation of Ubuntu or the flash drive that's mounted read-only.

I also can't use isohybrid to convert the two .iso files I do have of Manjaro and Gecko Linux because (Read-only file system) is output again.

Any help would be greatly appreciated. I'd really rather not have to format my USB stick again to download them with a Windows computer that I'd have to wait to use at the college.

Outputs
mount
sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime)
proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)
udev on /dev type devtmpfs (rw,nosuid,relatime,size=933748k,nr_inodes=233437,mode=755)
devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000)
tmpfs on /run type tmpfs (rw,nosuid,noexec,relatime,size=191320k,mode=755)
/dev/sda1 on / type ext4 (rw,relatime,errors=remount-ro,data=ordered)
securityfs on /sys/kernel/security type securityfs (rw,nosuid,nodev,noexec,relatime)
tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev)
tmpfs on /run/lock type tmpfs (rw,nosuid,nodev,noexec,relatime,size=5120k)
tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,mode=755)tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,mode=755)
cgroup on /sys/fs/cgroup/systemd type cgroup (rw,nosuid,nodev,noexec,relatime,xattr,release_agent=/lib/systemd/systemd-cgroups-agent,name=systemd)
pstore on /sys/fs/pstore type pstore (rw,nosuid,nodev,noexec,relatime)
cgroup on /sys/fs/cgroup/pids type cgroup (rw,nosuid,nodev,noexec,relatime,pids)
cgroup on /sys/fs/cgroup/freezer type cgroup (rw,nosuid,nodev,noexec,relatime,freezer)
cgroup on /sys/fs/cgroup/cpu,cpuacct type cgroup (rw,nosuid,nodev,noexec,relatime,cpu,cpuacct)
cgroup on /sys/fs/cgroup/net_cls,net_prio type cgroup (rw,nosuid,nodev,noexec,relatime,net_cls,net_prio)
cgroup on /sys/fs/cgroup/devices type cgroup (rw,nosuid,nodev,noexec,relatime,devices)
cgroup on /sys/fs/cgroup/memory type cgroup (rw,nosuid,nodev,noexec,relatime,memory)
cgroup on /sys/fs/cgroup/hugetlb type cgroup (rw,nosuid,nodev,noexec,relatime,hugetlb)
cgroup on /sys/fs/cgroup/cpuset type cgroup (rw,nosuid,nodev,noexec,relatime,cpuset)
cgroup on /sys/fs/cgroup/blkio type cgroup (rw,nosuid,nodev,noexec,relatime,blkio)
cgroup on /sys/fs/cgroup/perf_event type cgroup (rw,nosuid,nodev,noexec,relatime,perf_event)
debugfs on /sys/kernel/debug type debugfs (rw,relatime)
mqueue on /dev/mqueue type mqueue (rw,relatime)
systemd-1 on /proc/sys/fs/binfmt_misc type autofs (rw,relatime,fd=37,pgrp=1,timeout=0,minproto=5,maxproto=5,direct,pipe_ino=12262)
hugetlbfs on /dev/hugepages type hugetlbfs (rw,relatime)
fusectl on /sys/fs/fuse/connections type fusectl (rw,relatime)
tmpfs on /run/user/120 type tmpfs (rw,nosuid,nodev,relatime,size=191316k,mode=700,uid=120,gid=127)
tmpfs on /run/user/1000 type tmpfs (rw,nosuid,nodev,relatime,size=191316k,mode=700,uid=1000,gid=1000)
gvfsd-fuse on /run/user/1000/gvfs type fuse.gvfsd-fuse (rw,nosuid,nodev,relatime,user_id=1000,group_id=1000)


text:
Q: Custom list representation for list of objects I know that representation of an object can customized be using the __repr__ magic method.
class A:

    ...

    def __repr__(self):
        return 'A(id={})'.format(self.id)

Is there a way to customize the representation when it is a list of these objects, such that it doesn't just print a list of the object's representation [A(id=1), A(id=10), A(id=11)].
For example:
class AGroup:
    def __init__(self, lst):
        self.lst = lst

>>> lst = [A(1), A(10), A(11)]
>>> grp = AGroup(lst)
>>> grp.lst
<Group of 3 A's>  # instead of [A(id=1), A(id=10), A(id=11)]

I was thinking of wrapping the list into another object before assigning to self.lst so that I can modify its repr. Any other idea?

A: You can store the list passed to the AGroup constructor in an instance of a sub-class of list, so that you can override the __repr__ method of the list sub-class to return an output in your desired format:
class A:
    def __init__(self, id):
        self.id = id
    def __repr__(self):
        return 'A(id={})'.format(self.id)

class AGroup:
    class AList(list):
        def __repr__(self):
            return "<Group of %d A's>" % len(self)

    def __init__(self, lst):
        self.lst = self.AList(lst)

lst = [A(1), A(10), A(11)]
grp = AGroup(lst)
print(grp.lst)

This outputs:
<Group of 3 A's>

A: to group class instance we need to overwrite eq, ne, and hash function. by giving the static hash value will treat all instances of this class as one object.
from collections import Counter
class A:
    def __init__(self , id):
        self.id = id
    def __hash__(self): return hash('A')
    def __eq__(self, x): return type(x) is A
    def __ne__(self, x): return type(x) is not A

    def __repr__(self):
        return 'A'

class B:
    def __init__(self , id):
        self.id = id
    def __hash__(self): return hash('B')
    def __eq__(self, x): return type(x) is B
    def __ne__(self, x): return type(x) is not B

    def __repr__(self):
        return 'B'

class AGroup:
    def __init__(self, lst):
        count = Counter(lst)
        self.lst = []
        for cl in Counter(lst):
            self.lst.append('<Group of {} {}\'s>'.format(count[cl] , cl))

lst = [A(1), B(10), A(11)]
grp = AGroup(lst)
grp.lst

["<Group of 2 A's>", "<Group of 1 B's>"]


text:
Q: Error while Login with Facebook in Flutter SERVER_ERROR: [code] 1675030 [message]: Error performing query. [extra]: After initialising flutter login like this:
final LoginResult loginResult = await FacebookAuth.instance.login(permissions: const ['email', 'public_profile'],loginBehavior: LoginBehavior.dialogOnly);
it is getting loginResult message like:

SERVER_ERROR: [code] 1675030 [message]: Error performing query.
[extra]:

A: There are few things you could check

*

*Check if you are a tester in fb apps dashboard. If not add a tester account

*Add one more scope user_friends along with email and public profile

*Check the key hash value in fb dashboard which you obtained from the jks you are trying to build.

*Check if your fb app id is correct
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

Here

*You can also add android value here

<meta-data
        android:name="com.facebook.sdk.ApplicationId"
        tools:replace="android:value"
        android:value="@string/facebook_app_id" />


text:
Q: enforcing same type on multiple templates I have several small classes that are all peers of each other declared and defined in the same file. A lot of these classes share information. Currently, the type of the shared information is hard-coded for initial development and testing purposes, but I want to templatize (verb form?) the classes. However, if I write the template construct before each class, that creates the possibility that a user could create instances of each class with different type arguments, which will most likely lead to errors in the data or code. Is there a way to force all class instances to be created with the same type?
The only way I can think of doing this is to create an additional init or spawner class with members functions like createInstanceOfA(), createInstanceOfB(), etc., where the user would have to first create an instance of the spawner class with the desired type, then use its member functions to create instances of the other classes. Of course, this would mean that my spawner class would have to stay in sync with whatever utility classes I have (which shouldn't be a problem). However, is there a better way of doing this?
EDIT: As an example, my "ugly solution" (a simple case):
template <typename T>
struct A {
  void manipulate( T arg );
};

template <typename T>
struct B {
  void manipulate( T arg );
};

template <typename T>
struct C {
  void manipulate( T arg );
};

template <typename T>
struct Spawner {
  A<T> createInstanceOfA( void );
  B<T> createInstanceOfB( void );
  C<T> createInstanceOfC( void );
};

int main() {

  // don't allow
  A<int> a;
  B<float> b;
  C<double> c;

  // allow
  Spawner<int> s;
  A<int> s.createInstanceOfA();  // not sure if syntax is correct
  B<int> s.createInstanceOfB();
  C<int> s.createInstanceOfC();

  return 0;
}

A: What you're asking for doesn't make sense. foo<int> is a different type than foo<float> - you shouldn't be running into issues with the wrong types.
What it seems you want is for to require 3 classes to be instantiated of the same class at the same time. What you want isn't 3 separate classes, but 1 single one: (example is composed of several classes built into one)
template <typename T>
struct col {
  struct t1 {
    T data;
  } a;
  struct t2 {
    T data;
  } b;
};

col<int> foo;
foo.a.data = 5;
foo.b.data = 7;

void process_stuff(col<int>::t1 a) {
  // ...
}
process_stuff(foo.a);

A: What you're trying to achieve is called concepts by it's technical name, and there is a Boost library, ConceptCheck, that you can use to implement this.
You could also use std::enable_if and SFINAE (Substition Failure Is Not An Error).
But templates are meant to make code generic, and it doesn't really sound like that is what you want. I would reconsider your design.

A: You can specialize the templates.
So if you do:
template<typename T> class A;

template<>
class A<int>
{...};

template<>
class A<double>
{...};

Then if you or someone else tries to create a
A<std::string> a;

there will be a compile error because that type is not specialized.
But perhaps this is not what you want?
Edit:
I somewhat misunderstood the question. Perhaps you can solve this issue by controlling the creation of the classes? Like through a factory? If you only allow creation of the classes through the factory then you should be able to enforce the same type on multiple templates. Perhaps this is just pushing the problem to the factory class...
Good luck!


text:
Q: system.xml fields are not saving in magento Hi today i'm working on system.xml file. it's not saving correctly.
system.xml
<custom_field translate="label">
     <label>Add Class and it's Params</label>
     <frontend_model>hello/adminhtml_form_field_addclass</frontend_model>
     <backend_model>hello/system_config_backend_addclass</backend_model>
     <sort_order>6</sort_order>
     <show_in_default>1</show_in_default>
     <show_in_website>0</show_in_website>
     <show_in_store>0</show_in_store>
</custom_field>

Test\Block\Adminhtml\Form\Field\AddClass.php
<?php

class Test_Hello_Block_Adminhtml_Form_Field_AddClass extends Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract
{

    protected function _prepareToRender()
    {
        $this->addColumn('add_param', array(
            'label' => Mage::helper('hello')->__('Add Parameter'),
        ));
        $this->addColumn('add_param_class', array(
            'label' => Mage::helper('hello')->__('Add Parameter Class'),
            'style' => 'width:100px',
        ));
        $this->addColumn('add_param_class_field', array(
            'label' => Mage::helper('hello')->__('Add Parameter Class Fields'),
            'style' => 'width:100px',
        ));
        $this->_addAfter = false;
        $this->_addButtonLabel = Mage::helper('hello')->__('Add Class');
    }

}

Test\Model\System\Config\Backend\AddClass.php
<?php

/**
 * Backend for serialized array data
 *
 */
class Test_Hello_Model_System_Config_Backend_AddClass extends Mage_Core_Model_Config_Data
{
    /**
     * Process data after load
     */
    protected function _afterLoad()
    {
        $value = $this->getValue();
        Mage::log($value,null,'AddClass');
        //$this->setValue($value);
    }

    /**
     * Prepare data before save
     */
    protected function _beforeSave()
    {
        $value = $this->getValue();
        //$this->setValue($value);
        Mage::log($value,null,'AddClass');

    }
}

it's saving core_config_data table like below formate.
path = customtab/custom_attributes/custom_field

value = Array,Array,Array,

Logs are created like below formate
2015-08-10T10:42:55+00:00 DEBUG (7): Array,
2015-08-10T10:58:26+00:00 DEBUG (7): Array
(
    [_1439204268814_814] => Array
        (
            [add_param] => acceptNewClass
            [add_param_class] => AcceptNewClassFields
            [add_param_class_field] => ID,PrimariContact
        )

    [_1439204284271_271] => Array
        (
            [add_param] => TokenID
            [add_param_class] =>
            [add_param_class_field] =>
        )

    [_1439204298185_185] => Array
        (
            [add_param] => memberID
            [add_param_class] =>
            [add_param_class_field] =>
        )

    [__empty] =>
)

how to save & retrieve this?
Any help on this
Thanks.

A: Make your backend model look like this:
class Test_Hello_Model_System_Config_Backend_AddClass extends Mage_Core_Model_Config_Data
{
    /**
     * Process data after load
     */
    protected function _afterLoad()
    {
        $value = $this->getValue();
        $this->setValue(unserialize($value));
        Mage::log($value,null,'AddClass');
        //$this->setValue($value);
    }

    /**
     * Prepare data before save
     */
    protected function _beforeSave()
    {
        $value = $this->getValue();
        $this->setValue(serialize($value));
        Mage::log($value,null,'AddClass');

    }
}

A: Change your backend_model as
<backend_model>adminhtml/system_config_backend_serialized_array</backend_model>

So now the field value will be saved as serialized format.
And while get the value you need to unserialize the value
$myvals = unserialize(Mage::getStoreConfig('myvals'));

Refer this.


text:
Q: Symfony - Why do some variables get output escaped, and others do not? In a Symfony 1.4 view, why do some variables get output escaped, and others do not?
I have escaping_strategy = true, and escaping_method = ESC_SPECIALCHARS.
If I do
$this->form = new SearchForm();

then in my view, $form will be a SearchForm. Or model objects also seem to come through as regular model objects.
But other variables, like arrays or a MongoCursor, get transformed into sfOutputEscaper___Decorator objects, and I can't access the raw methods directly. Why?
I understand that I can get the raw variable and then use its methods, but it's a guessing game for me right now, which is frustrating.

A: There are a handfull of classes that will skip any output escaping (because they primarily render HTML). By default sfView.class.php will mark the following as safe:
sfForm, sfFormField, sfFormFieldSchema, sfModelGeneratorHelper
So objects of, or inheriting from these classes will not be output escaped.
If you look at the relevant code in sfView.class.php, you'll also find how to mark additional classes as safe if you would like to do so:
sfOutputEscaper::markClassesAsSafe(array('sfForm', 'sfFormField', 'sfFormFieldSchema', 'sfModelGeneratorHelper'));


text:
Q: SOQL error index out of bound : 0 I get this error if LargestRevision returns null. ie., fields revision and quote link have no values. Why isn't the else part handling null values? Following is the code I tried.
   if(quoteLink.Quote_Link__c!=null)
   LargestRevision=[SELECT Revision_Number__c FROM OPP_QuoteLink__c WHERE Quote_Link__c=:quoteLink.Quote_Link__c ORDER BY Revision_Number__c DESC LIMIT 1];

      if(LargestRevision.size()!=null){
          clonedQuteLink.Revision_Number__c=LargestRevision.get(0).Revision_Number__c+1;
          clonedQuteLink.Quote_Link__c = quoteLink.Quote_Link__c;
      }
      else
      {
          clonedQuteLink.Revision_Number__c=1;
          clonedQuteLink.Quote_Link__c = quoteLink.Id;
      }

Here

Revision_Number__c is a number field.
Quote_Link__c is a lookup field

A: LargestRevision.size() will never return null.
The size() method will return 0 if the list is empty.
From the documentation:

size()
  Returns the number of elements in the list.
Signature
public Integer size()
Return Value
  Type: Integer
Example
List<Integer> myList = new List<Integer>();
Integer size = myList.size();
system.assertEquals(size, 0);

List<Integer> myList2 = new Integer[6];
Integer size2 = myList2.size();
system.assertEquals(size2, 6);

Changing to the following should resolve this:
if(LargestRevision.size() > 0) {
    clonedQuteLink.Revision_Number__c=LargestRevision.get(0).Revision_Number__c+1;
    clonedQuteLink.Quote_Link__c = quoteLink.Quote_Link__c;
}

A: You should replace the first part of the if with
 if(LargestRevision!=null and LargestRevision.size()!=0){
      clonedQuteLink.Revision_Number__c=LargestRevision.get(0).Revision_Number__c+1;
      clonedQuteLink.Quote_Link__c = quoteLink.Quote_Link__c;
  }

because if LargestRevision is null (no values found) then you cannot call .size() on a null


text:
Q: Limitar la creación de usuario en firebase Estaba realizando un login para una web utilizando Firebase Authentication, este login sería para acceder al apartado de administración de una web, estoy utilizando la autenticación por email y contraseña, pero me gustaría que solo se pudiese crear un usuario, puesto que cualquiera con el método createUserWithEmailAndPassword y los parámetros de configuración podría crear un nuevo usuario y acceder al apartado de configuración.
Si esto no es posible, ¿me podrían aconsejar otro sistema?

A: Creo que no se puede limitar el número de usuarios, pero podrías limitar accesos de lectura y escritura a un solo usuario en la configuración de reglas de seguridad de la base de datos.
En adición podría sugerir que si solo necesitas un usuario no publiques el método createUserWithEmailAndPassword


text:
Q: Improving speed for solving linear equation I am working with huge data which are usually ill conditioned and runs extremely slow when I use np.linalg.lstsq(I'm using this function because my matrix is ill conditioned and the other functions such as np.linalg.solve(A, B) give wrong solution). B is calculated in each loop as its value changes. That is why I have placed it inside the loop although for this snipet, it is not necessary.
import numpy as np
A = np.random.randn(15000, 15000)
for i in range(50000):
    B[i] = np.random.randn(15000)
    C = np.linalg.lstsq(A, B[i], rcond=None)

How can improve significantly the speed of such a huge matrix? Is there a pythonic way to do this?


text:
Q: some weak conditions about Vitali convergence theorem As we have known,the Vitali convergence theorem is stated:
Let $(X,\mathbb{M},\mu)$ be a positive measure space.If
(i)$\mu(X)<\infty$;
(ii)$\{f_n\}$ is uniformly integrable;
(iii)$f_n(x)\to f(x)~~a.e.as~~n\to\infty$;
(iv)$|f(x)|<\infty~~a.e$;
then $f\in L^1(\mu)$ and
$$\lim_{n\to\infty}\int_X |f_n-f|d\mu=0.$$
Call a set $\Phi\subset L^1(\mu)$ uniformly integrable if to each $\varepsilon>0$ corresponds a $\delta>0$ such that $$|\int_E fd\mu|<\varepsilon$$
whenever $f\in\Phi$ and $\mu(E)<\delta$.
So I want to give some weaker conditions to verify whether the Vitali theorem is still valid or not.
First,if $\mu$ is Lebesgue measure on $(-\infty,\infty)$,and moreover,$\{\parallel f_n\parallel_1\}$ is assumed to be bounded.How about the Vitali theorem?
Second,can we omit the hypothesis (iv) when we consider the Lebesgue measure on a bounded interval?And can this be extended to finite measures?
Any help will be appreciated.

A: Here is the strongest version of Vitali's theorem (from O. Kavian, Introduction à la théorie des points critiques, Springer, 1993)
Definition. A sequence $\{f_n\}_n$ in $L^1(\Omega)$ is equi-integrable if the following condition is satisfied: for every $\varepsilon>0$ there exists a measurable set $A$ of finite measure and there exists $\delta>0$ such that

*

*for every $n \geq 1$, $\int_{\complement A} |f_n|<\varepsilon$;

*for every measurable $E \subset \Omega$ whose measure is less than $\delta$, there results $\int_E |f_n|<\varepsilon$ for every $n \geq 1$.

Theorem. Let $\{f_n\}_n$ be  a sequence in $L^1(\Omega)$ that converges almost everywhere to some measurable function $f$. The sequence $\{f_n\}_n$ converges to $f$ in $L^1(\Omega)$ if and only if it is equi-integrable.


text:
Q: Best model(s) & suggestion for correlation between two variables , "lag" effect, & forecasting time series I am looking for guidance or suggestions on the best model or method to solve the questions below.
My dataset is a time series that contains date, number of orders, and number of Customer Service (CS) calls.
Questions:
1) How correlated are the number of orders to the number of CS calls?
2) When orders increase, we can expect this increase to reflect in the number of CS calls within x time period by z quantity.
Or something like, for ever 1 orders, we can expect an increase of y calls within t days
3) Forecast - predict the next 7 days worth of values for number of orders and calls
Essentially I am trying to best answer the 3 questions above.
Here is my plan for each question so far
Plan for 1): Do some basic summary stats and find correlation coefficient?
Plan for 2): ARIMA maybe ?
Plan for 3): ARIMA or regular regression ?
I was thinking using ARIMA could help me answer these questions, but maybe it is only meant for question 3)? What part of the ARIMA model can actually quantify the "lag" effect in terms of number of days ?
THANK YOU SO MUCH IN ADVANCED !
I will be using python to implement methods.


text:
Q: Use Javascript / jQuery Replicate HTML Form POST with ISO-8859-1 charset My PHP web application is running on ISO-8859-1 encoding. When I post an HTML form with accept-charset="ISO-8859-1" to a PHP server, this is what I receive on server side
a. ASCII characters in their original form.
b. Special characters that can be represented in ISO-8859-1 in their original form.
c. Special characters that can not be represented in ISO-8859-1 converted to HTML entities.
All of the data is received as proper ISO-8859-1 encoded characters. I want to replicate the exact same behavior with JavaScript or jQuery. All the solutions I have tried end up sending all the special characters to PHP file as double encoded characters and I have to utf8_decode them.
I have made a working solution as follows:
a. convert unsupported special characters to HTML entities.
b. send JavaScript AJAX post request with XMLHttpRequest/ActiveXObject. To do that I have to 'encodeURIComponent()' the data.
c. receive the post data on server and 'utf8_decode()' it because 'encodeURIComponent()' encodes the special characters as UTF-8.
I want a JavaScript solution which makes sure that I receive proper ISO-8859-1 encoded data from POST on server side, so that I don't have to do 'utf8_decode()'. In other words, I want the JavaScript solution to exactly replicate the form behavior with accept-charset="ISO-8859-1".
Thank you

A: To my knowledge, there is no sure-fire way in javascript to do this. Character encoding is not a forte of Javascript and I believe it is mainly because it leaves such areas to the discretion to others such as the HTML that describes the content, the Server Language which does the parsing or the Web Server that provides the environment.
As far as any URI encoding/decoding function in JS is concerned, it is all UTF-8 and that is inbuilt, as in, there is no param you can pass to override it.
You could also try something in the lines of overriding the MimeType and specifying a new one like:
var xhr = new XMLHttpRequest();
if (xhr.overrideMimeType) {
    xhr.overrideMimeType('application/x-javascript; charset=ISO-8859-1');
}

Not sure how stable it is, but it is one direction you might want to explore..


text:
Q: Customize Windows Run Dialog Is it possible to customize the Windows Run dialog (invoked with Win+R)? For example, is it possible to replace the default Type the name of a program... message with something more interesting?
In particular, I'm interested in doing this on Windows 98 (after seeing this image).
Thanks in advance.

A: OK, so I figured it out for Windows 98, and it should also work on Windows XP. Here's the info for future generations.
The dialog box is stored in C:\Windows\System\Shell32.dll, and it is possible to edit it using Resource Hacker. After opening the DLL in the program, go to Dialog\1003\1033, and the rest should be pretty straightforward.

*

*All of the captions, strings, etc. are in the main window.

*To remove the context help button from the title bar, remove DS_CONTEXTHELP from the STYLE line at the top.

*To add an icon to the DLL, select Action-->Add a new Resource, then choose it from your computer and give it a unique resource name (a number).

*To replace the default icon already present in the dialog, right-click it, choose Edit control, then change the Caption to the resource name of the new icon.

Important: The OK button won't work if you just delete everything else and let it be. To fix this, set its ID property to anything other than 1.
Important 2: Windows won't let you replace the original Shell32.dll while it's running. Reboot into MS-DOS and copy from there.
Unfortunately, I don't know how to do this on Windows 7, as the Shell32.dll there doesn't contain the dialog box. If anyone has an idea, please share.


text:
Q: Delete option is not working with PDO ,php unable to delete i row using PDO in php. Here is my code given below
this is inc.common.php
<?php
    @session_start();
    include_once '../common/inc.config.php';
    include_once '../common/inc.globalConstants.php';
    $db = new PDO("mysql:host=$mdbhost;dbname=$mdbname",$mdbuser,$mdbpass );
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    include_once '../classes/cls.common.php';
    $Cobj=new common($db);
?>

this my cls.class.php
 <?php
class common {
    public function common($dbcon) {
        $this->dbCon = $dbcon;
    }
    public function getCustomData($tableName,$fields, $conditions = "") {
        $stmt = "";
        $sql = "";
        $sql = "SELECT $fields FROM $tableName  $conditions ";
        $stmt = $this->dbCon->query($sql);
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $result;
      }
    public function delet($tableName, $class_id){
        $inputArray['classId']=$class_id;
        $count = $this->$dbCon->prepare("DELETE FROM $tableName WHERE classId =:classId");
        $result = $stmt->execute($inputArray);
        return $result;
     }
 ?>

this is my addinfo.php
<?php
    include '../common/inc.common.php';
    $class_id=$_POST['refid'];
    if(isset($_POST['mode']))
    {
        $tableName="class";
        $class_id=$_POST['refid'];
        $res=$Cobj->delet($tableName, $class_id);
    }
?>

on passing variables using AJAX call i couldn't able to delete the row .Ajax call is success . only problem with PDO delete.
$.ajax({
        url: "../masters/addinfo.php",
        type: "POST",
        data:"refid="+class_id+"&mode=delete",
});

my class table has 4 fields  classId,name,date,stat.

A: The $stmt variable in function delet() is not defined.

A: public function delet($tableName, $class_id){
 $inputArray['classId']=$class_id;
 $stmt = $this->$dbCon->prepare("DELETE FROM $tableName WHERE classId =:classId");
 $result = $stmt->execute($inputArray);
 return $result;
}

Will fix this. Note what changed; $count changed to $stmt


text:
Q: Django - How can I debug code which POST's when a bug seems to be in the view? I thought I would ask a broad question so I get a better understanding of Django and can more readily deal with any similar problems I may encounter. The specific issue which I am having is that I have written my first formset code, which renders the forms correctly but when posted no new objects are created.
I can see from the server that the form has been posted, I get no errors but no data has been added to my database (checked from django admin and manage.py shell). Perhaps it is possible to read what has been posted in a manage.py shell? I would like to be able to check whether the form posted its data correctly and it has been received by the view. Then I can see why either the data isn't posting correctly or the view isn't handling it correctly.
For the specific issue I will place my code below, in case it's a simple beginner error which one of you wizards can spot. I tried to follow and adapt this tutorial for my own purposes.
Models.py
class Chunk(models.Model):
    name = models.CharField(max_length=250)
    text = models.CharField(max_length=500)
    images = models.FileField()
    question = models.CharField(max_length=250)
    expected_completion_time = models.IntegerField(default=1)
    keywords = models.CharField(max_length=250, blank=True, null=True)
    topic = models.CharField(max_length=250, blank=True, null=True)
    course = models.CharField(max_length=250, blank=True, null=True)
    is_flagged = models.BooleanField(default=False)

    def get_absolute_url(self):
        return reverse('detail', kwargs={'pk':self.pk})

    def __str__(self):
        return self.name

class Concept(Chunk):
    application = models.CharField(max_length=500)

    @property
    def mode(self):
        return "concept"

class Subconcepts(models.Model):
    subconcept = models.CharField(max_length=500)
    concept = models.ForeignKey(Concept, on_delete=models.CASCADE)

    def __str__(self):
        return self.concept.name + ' - Subconcept'

forms.py
class ConceptForm(forms.ModelForm):
    # Form for creating Concept objects
    class Meta:
        model = Concept
        fields = ['application', 'name', 'text', 'images', 'question', 'expected_completion_time', 'keywords', 'topic', 'course']

class SubconceptForm(forms.ModelForm):
    # Form for creating Subconcept objects which are linked by ManyToOne fields to Concept objects
    class Meta:
        model = Subconcepts
        fields = ['subconcept']  # Concept field excluded as will be set in view on form submission

class BaseSubconceptFormset(BaseFormSet):
    def clean(self):
        # Validate that all subconcepts are unique
        if any(self.errors):
            return
        subconcepts = []
        duplicates = False

        for form in self.forms:
            if form.cleaned_data:
                subconcept = form.cleaned_data('subconcept')

                if subconcept:
                    if subconcept in subconcepts:
                        duplicates = True
                    subconcepts.append(subconcept)

                if duplicates:
                    raise forms.ValidationError(
                        'Each key feature must be unique',
                        code='duplicate_subconcept'
                    )

views.py
def testformsets(request):

    # Forms for creating a concept with appropriate subconcepts
    SubconceptFormset = formset_factory(SubconceptForm, formset=BaseSubconceptFormset)

    if request.method == 'POST':
        concept_form = ConceptForm(request.POST)
        subconcept_formset = SubconceptFormset(request.POST)

        if concept_form.is_valid() and subconcept_formset.is_valid():
            concept = concept_form.save()

            new_subconcepts = []

            for subconcept_form in subconcept_formset:
                subconcept = subconcept_form.cleaned_data.get('subconcept')
                new_subconcepts.append(Subconcepts(subconcept=subconcept, concept=concept))

            try:
                with transaction.atomic():
                    # Add all new subconcepts at once
                    Subconcepts.objects.bulk_create(new_subconcepts)

                    # And notify our users that it worked
                    messages.success(request, 'You have added new material')

            except IntegrityError:  # If the transaction failed
                messages.error(request, 'There was an error saving your concept.')
                return redirect('pomodoro/index.html')

    else:
        concept_form = ConceptForm()
        subconcept_formset = SubconceptFormset()

    context = {
        'concept_form': concept_form,
        'subconcept_formset': subconcept_formset
    }
    return render(request, 'pomodoro/formset_test.html', context)

A: Add logging statements to your code.  A good place to start is to log the outcome of every decision and the result of every important function call, like so:
def myView(request):

    import logging
    logging.basicConfig(filename='mylog.log', level=logging.DEBUG)

    if request.method == 'POST':
        logging.debug('request.method=POST')
        form = MyForm(request.POST)
        logging.debug('form=%s', form)

        if concept_form.is_valid():
            logging.debug('form is valid')
            myform = form.save()
            logging.debug('called form.save(), result=%s', myform)

        else:
            logging.debug('form is not valid')
    else:
        logging.debug('request.method is not POST')


text:
Q: Form contents are printed outside of the form while using PHP tag I have created a table for category which fetches category data from database. The table have a column having icon. upon clicking that icon , a form pops up to edit name of that particular category.i used display:none for form id , but only form is being hidden. contents inside form(input,button,etc) are being displayed and when i click icon a complete blank form pops up because contents are already displayed outside of the form before clicking icon.
here's the part of the code:
HTML

                        Category ID
                        Category Name
                        Action

          <?php
            require("../PHP/connection.php");
               $select="SELECT *from category_details";
               $result=mysqli_query($con,$select);
               $num_rows= mysqli_num_rows($result);

               if($result){
                   if($num_rows>0){
                       while($row=$result->fetch_assoc()){

                          $id = $row["category_id"];
                          $catname = $row["category_name"];
                       echo "
                       <input type='checkbox' id='changecatcb' onclick='changecatfun()'>

                           <form id='changecatform' action='../HTML/AdminPanelChange.php' method='POST'>

Enter new name:

                              <input type='text' value=".$catname.">
                          <button type='submit' name='changecatbutton'>Save Changes</button>
                         </form>

                               ".$id."
                               ".$catname."

                            ";
                        }

                   }
                   else
                   echo "
 No Categories in Database
";
                   }
               }
                else
                echo "
 Can not run query
";
            ?>

JS
       function changecatfun(){
            var form = document.getElementById('changecatform');
            var checkbox = document.getElementById('changecatcb');
              if(checkbox.checked == true){
                   form.style.display='block';
              }
              else{
                  form.style.display='none';
              }
       }

CSS
         .changecat form{
            position: absolute;
            background-color: white;
            box-shadow: 0 0 10px 5px #555;
            height: 5%;
            width: 50%;
            left: 25%;
            display: none;

}
but contents are being printed inside form exactly like i want if i put the same code outside PHP tag like this:
works outside PHP tag
          <input type='checkbox' id='changecatcb' onclick='changecatfun()'>

                <form id='changecatform' action='../HTML/AdminPanelChange.php' method='POST'>

Enter new name:

                    <input type='text' value='.$catname.'>
                    <button type='submit' name='changecatbutton'>Save Changes</button>
              </form>

and yes, when i use PHP tag and inspect code in browser the form tag ends before form-contents like this:

              <form id="changecatform" action="../HTML/AdminPanelChange.php"method="POST" style="display: block;"></form>

Enter new name:

              <input type="text" value="Clothing">
              <button type="submit" name="changecatbutton">Save Changes</button>

I am a beginner and this is the first time i am asking question in here. any help would be appreciated. Thank you!

A: This has nothing to do with PHP.
You are trying to make input and div elements children of a table element, which is not allowed.
Using a markup validator would have highlighted this error.
If you want those element inside a table then they must be inside a td or th element that is, in turn, inside a tr element.


text:
Q: How do I remove MacPorts on an "unsupported OS" i.e. El Capitan Public beta? The MacPorts installation that I had on Yosemite doesn't work on the El Capitan since it isn't supported yet. I want to remove the Port installation here but I'm not able to run any of the Port commands. Does anyone have an idea how to clean it up?
On running any port command, I get the following error:
Error: Current platform "darwin 15" does not match expected platform "darwin 14"
Error: If you upgraded your OS, please follow the migration instructions: https://trac.macports.org/wiki/Migration
OS platform mismatch
    while executing
"mportinit ui_options global_options global_variations"
Error: /opt/local/bin/port: Failed to initialize MacPorts, OS platform mismatch

A: What I did successfully on my El Capitan:

*

*xcode-select --install

*xcodebuild -license

*Reinstall MacPorts by using the correct *.pkg matching your OSX from https://www.macports.org/install.php

*done.

A: This solution worked for me, without remove it:

*

*xcode-select --install

*xcodebuild -license

*wget https://distfiles.macports.org/MacPorts/MacPorts-2.3.3.tar.bz2

*tar xzvf MacPorts-2.3.3.tar.bz2

*cd MacPorts-2.3.3

*./configure && make && sudo make install

*cd ../

*rm -rf MacPorts-2.3.3*

Source

A: I just went ahead and manually removed the files (using rm):
sudo rm -rf /opt/local \
    /Applications/DarwinPorts \
    /Applications/MacPorts \
    /Library/LaunchDaemons/org.macports.* \
    /Library/Receipts/DarwinPorts*.pkg \
    /Library/Receipts/MacPorts*.pkg \
    /Library/StartupItems/DarwinPortsStartup \
    /Library/Tcl/darwinports1.0 \
    /Library/Tcl/macports1.0 \
    ~/.macports

It didn't seem to leave any leftovers or break anything.
One thing to note however is that mactex seems to have been installed in the same directory so that got removed as well. I didn't realize that I had that in the same directory. If you're going to repeat the same steps, keep this in mind.

A: wget is fetching a bz2 file but unzip instructions are for gz.
Try the following instead
tar xjvf MacPorts-2.3.3.tar.bz2

The rest worked fine on El Capitan.
Thanks.


text:
Q: Merging elements of tuples in a list in Prolog I need to create a list from a knowledgebase that could look like this:
fact1(3,3).
fact1(2,3).
fact1(3,5).
fact1(2,2).
fact1(2,10).
fact1(3,1).
fact1(1,1).
fact1(1,6).

fact2(3,a,b)
fact2(2,c,d)
fact2(1,e,f)

That list needs to contain tuples with each containing the second and third Value of fact2, and the added numbers of fact2, whenever the first value of fact1 and fact2 match up.
Maybe it gets clearer when I show what I have so far.
Here is my predicate with the findall statement, which to me seems to get me the closest to where I need to get:
collect_items(List):-
    findall((Out1,Out2,Nr),
        (fact2(Val1,Out1,Out2),
        fact1(Val1,Nr)),
        List).

The List I receive from this, looks like this:
List = [(a,b,3),(a,b,5),(a,b,1),(c,d,3),(c,d,2),(c,d,10),(e,f,1),(e,f,6)]

But really I need the list to look like this:
List = [(a,b,9),(c,d,15),(e,f,7)]

Meaning that, whenever the first two elements of a tuple match up, the numbers, which are the third element of the tuple, should be added together.
I do not know however how to even approach something like this, as I have always read, that as soon as the list is set, it cannot be changed, since prolog is functional and declarative.
So I think I somehow need to match every element against the one before or after it (since the list will always be sortet by the Out1 and Out2 variables), and if they match, add the third value in the tuple together. The problem is, that I have no idea how.
To me it looks like this can not realy be done within the findall itself but would need to be done after the findall
I am a true beginner and would appreciate any help. In this case it would be best, if the solution was all in one predicate.

A: Here is another solution that uses more than one predicate:
collect_items(Result):-
    findall([Out1,Out2,Nr],(fact2(Val1,Out1,Out2),fact1(Val1,Nr)),[[OutA, OutB, N]|B]),
    sumElements([[OutA, OutB, N]|B], Result).

sumElements([],[]).
sumElements([[Out, Outt, N]|B], [[Out, Outt, SumLocal]|RestOfList]):-
    findall([Out, Outt, X], member([Out, Outt, X], [[Out, Outt, N]|B]), SubList),
    sumLocal(SubList, SumLocal),
    subtract([[Out, Outt, N]|B], SubList, New),
    sumElements(New, RestOfList).

sumLocal([],0).
sumLocal([[_,_,S]|B], T):-
    sumLocal(B, R),
    T is S + R.

output:
?- collect_items(Result).
Result = [[a, b, 9], [c, d, 15], [e, f, 7]].

A: with library aggregate:
collect_items(L) :-
    setof((U,V,S),
          K^aggregate((set(X/Y),sum(N)), (
                          fact2(K,X,Y),
                          fact1(K,N)
                      ), ([U/V],S)), L).

we get
?- collect_items(L).
L = [(a, b, 9),  (c, d, 15),  (e, f, 7)].

You are not right here

since prolog is functional and declarative

Prolog is relational and declarative


text:
Q: C++ Constructor Initilizer I am trying to use constructor initializer for name and time but the visual studio is giving me errors, I do not see any issues with it, it seems fine to me, I tried to see the problem, I tried other things as well, Please Help. Thanks you in advance.
Any help really appreciated, I added all the header file and implementation of Entry class, I know it seems, I added so you can see it.
// Entry.h
#pragma once
#include <iostream>
#include <string>
#include "RelationType.h"

using namespace std;

class Name
{
    public:
    Name();

    Name(string firstName, string middleName, string lastName);

    string GetFristName() const;

    string GetLastName() const;

    string GetMiddleName() const;

    char GetMiddleInitial() const;

    RelationType ComparedTo(Name otherName) const;

    private:
    string first;
    string last;
    string middle;
};

//Entry.cpp
#include "Entry.h"
#include<iostream>
#include <string>

using namespace std;

Entry::Entry() {}

Entry::Entry(string firstName, string middleName, string lastName,
        int initHours, int initMinutes, int initSeconds)
        : name{ (firstName, middleName, lastName) ,      //name is where its mad at
          time(initHours, initMinutes, initSeconds) } {}

string Entry::GetNameStr () const
{
     return (name.GetFirstName() + ' ' + name.GetLastName());
}

string Entry::GetTimeStr () const
{
     return (name.FirstName() + ' ' + name.LastName());
}

// Name.h
#pragma once
#include <iostream>
#include <string>
#include "RelationType.h"

using namespace std;

class Name
{
    public:
    Name();

    Name(string firstName, string middleName, string lastName);

    string GetFristName() const;

    string GetLastName() const;

    string GetMiddleName() const;

    char GetMiddleInitial() const;

    RelationType ComparedTo(Name otherName) const;

    private:
    string first;
    string last;
    string middle;
};

// RealtionType.h

#pragma once
#ifndef RELATION
#define RELATION

enum RelationType { BEFORE, SAME, AFTER };

#endif

// TimeOfDay.h
#pragma once

class TimeOfDay
{

    public:

    //Intentionally missed const, see what happened without const
    TimeOfDay();                                 // zero timepfday object

    TimeOfDay(int hours, int minutes, int seconds); //takes 3 parameters

    TimeOfDay Increment() const;                //increment by 1 sec

    void Write() const;                         //write the timeofday obj to print

    bool Equal(TimeOfDay otherTime) const;     //true if timeofday obj equals othertime

    bool LessThan(TimeOfDay otherTime) const;  //const, true if the timeofday obj is
                                           //before itherTime
    private:

    int hours;
    int minutes;
    int seconds;
};

A: Your Entry class constructor code should be something like below
Entry::Entry(string firstName, string middleName, string lastName,
            int initHours, int initMinutes, int initSeconds)
            : name(firstName, middleName, lastName)
            , time(initHours, initMinutes, initSeconds) {}


text:
Q: Подключение Firebase пытаюсь подключить Firebase. Выбивает ошибку Failed to resolve: firebase-database-15.0.0. Удаляю 'com.google.firebase:firebase-database:16.0.1:15.0.0', добавляю 'com.google.firebase:firebase-database:16.0.5' и  'com.google.firebase:firebase-core:16.0.5'. Синхронизирую, вроде все ок. Нажимаю еще раз "Add the Realtime Database to your app"  и мне опять пишет, что хочет добавить в код 'com.google.firebase:firebase-database:16.0.1:15.0.0'.В чем проблема ?

A: Для того, чтобы подключить Firebase необходимо:
В build.gradle на уровне проекта добавить:
buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:4.2.0' // google-services plugin
    }
}

allprojects {
    // ...
    repositories {
        // ...
        google() // Google's Maven repository
        jcenter()
    }
}

В build.gradle на уровне приложения добавить:
apply plugin: 'com.android.application'

android {
  // ...
}

dependencies {
  // ...
  implementation 'com.google.firebase:firebase-core:16.0.4'
  implementation 'com.google.firebase:firebase-database:16.0.4'

  // Getting a "Could not find" error? Make sure you have
  // added the Google maven respository to your root build.gradle
}

// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

Актуальные версии на данный момент:

P.S. Советую пока не использовать 16.0.5

Источник


text:
Q: Proving that $\lim_{n\to\infty}s_n=0$
Prove: If $\lim_{n\to\infty}s_n=s$ and $\{s_n\}$ has a subsequence $\{s_{n_k}\}$ such that $(-1)^ks_{n_k}\geq0$ then $s=0$.

Proof. Since $\{s_n\}$ converges to $s$ then so does its subsequence $\{s_{n_k}\}$ . Again, if it is convergent then $\liminf=\limsup$, but for $k$ even the subsequence assumes the form $s_{n_{2k}}$, instead for odd the form  $-s_{n_{2k+1}}$. For these to be equal, for large $n$, both limits $s$ and $-s$ must be equal to $0$. Since $\liminf=\limsup=0$ then $s=0$.

A: Your proof is fine. Here a proof without $ \lim \inf$ and $\lim \sup$:
Suppose that $s \ne 0$. WLOG we assume thatb $s>0$. Since $s_{n_k} \to s$ as $ k \to \infty$, there is $K$ such that $s_{n_k}>0$ for all $k>K$. If $k>K$ and $k$ is odd, we get $(-1)^ks_{n_k}<0$, a contradiction.

A: $\lim_{n \rightarrow \infty} s_n=s.$
Then every subsequence converges to $s$.
Given:
$s_{n_k}$ converges to $s$, and $(-1)^k s_{n_k} \ge 0$.
1) $k =2m$ then $s_{n_{2m}} \ge 0$, and this subsequence of $s_{n_k}$ converges to $s$:
$\lim_{m \rightarrow \infty} s_{n_{2m}} =s \ge 0.$
Similarly;
2)$ k=(2m+1)$ then $s_{n_{2m+1}} \le 0$, and this subsequence of $s_{n_k}$ converges to $s$.
$\lim_{ m \rightarrow \infty}s_{n_{2m+1}}=s \le 0.$
Hence?
Used : If every term of a convergent sequence is $\ge 0,$ then the limit is $\ge 0$.


text:
Q: Without unwinding, translate a simple while loop iteration into SMT-LIB formula to prove correctness Consider proving correctness of the following while loop, i.e. I want show that given the loop condition holds to start with, it will eventually terminate and result in the final assertion being true.
int x = 0;
while(x>=0 && x<10){
   x = x + 1;
}
assert x==10;

What would be the correct translation into SMT-LIB for checking the correctness, without using loop unwinding?

A: Hoare logic and loop-invariants
Typical proof of such a statement would be done via the classic Hoare logic, which I assume you're already familiar with. If not, see: https://en.wikipedia.org/wiki/Hoare_logic
The idea is to come up with an invariant for your loop. This invariant must be true before the loop starts, it must be maintained by the loop body, and it must imply the final result when the loop condition is no longer true. Additionally, you also need to prove that the loop will eventually terminate, by means of a measure function. (More on that later.)
You can convince yourself why this would be sufficient: An invariant is something that's "always" true. And if it implies your final result, then your proof is complete. The proof steps I outlined above ensure that the invariant is indeed an invariant, i.e., its truth is always maintained by your program.
Coming up with the invariant
What would be a good invariant for your loop here? Let's give this invariant the name I. A moment of thinking reveals a good choice for I is:
I = x >= 0 && x <= 10

Note how similar (but not exactly the same!) this is to your loop-condition, and this is not by accident. Loop-invariants are not unique, and coming up with a good one can be really difficult. It's an active area of research (since 60's) to synthesize loop-invariants automatically. See the plethora of research out there. https://en.wikipedia.org/wiki/Loop_invariant is a good starting point.
Proof using SMT
Now that we "magically" came up with the loop invariant, let's use SMT to prove that it is indeed correct. Instead of writing SMTLib (which is verbose and mostly intended for machines only), I'll use z3-python interface as a close enough substitute. To finish the proof, I need to show 4 things:

*

*The invariant holds before the loop starts

*The invariant is maintained by the loop body

*The invariant and the negation of the loop-condition implies the desired post-condition

*The loop terminates

Let's look at each in turn.
(0) Preliminaries
Since we'll use z3's python interface, we'll have to do a little bit of leg-work to get us started. Here's the skeleton we need:
from z3 import *

def C(p):
  return And(p >= 0, p < 10)

def I(p):
  return And(p >= 0, p <= 10)

x = Int('x')

Note that we parameterized the loop-condition (C) and the invariant (I) with a parameter so it's easy to call them with different arguments. This is a common trick in programming, abstracting away the control from the data. This way of coding will simplify our life later on.
(1) The invariant holds before the loop starts
This one is easy. Right before the loop, we know that x = 0. So we need to ask the SMT solver if x == 0 implies our invariant:
>>> prove (Implies(x == 0, I(x)))
proved

Voila! If you want to see the SMTLib for the proof obligation, you can ask z3 to print it for you:
>>> print(Implies(x == 0, I(x)).sexpr())
(=> (= x 0) (and (>= x 0) (<= x 10)))

(2) The invariant is maintained by the loop-body
The loop body is only run when the loop condition (C) is true. The body increments x by one. So, what we need to show is that if our invariant (I) is true, if the loop condition (C) is true, and if I increment x by one, then I remains true. Let's ask z3 exactly that:
>>> prove(Implies(And(I(x), C(x)), I(x+1)))
proved

Almost too easy!
(3) The invariant implies the result when loop condition is false
This time, all we need to ask the solver is to prove the required conclusion when I holds, but C doesn't:
>>> prove(Implies(And(I(x), Not(C(x))), x == 10))
proved

And we have now completed what's known as the partial-correctness claim. That is, if the loop terminates, then x will indeed be 10 at the end. This is what you were trying to prove to start with.
(4) The loop terminates
What we've done so far is known as partial-correctness. It says if the loop terminates, then your post-condition (i.e., x == 10) holds. But it does not make any guarantees that the loop will always terminate.
To get a full-proof, we have to prove termination. This is done by coming up with a measure function: A measure function is a function that assigns (typically) a numeric value to the set of program variables, which is bounded from below. Then we show that it goes down in each iteration and has an initial value that's above its lower-bound. Then we know that the loop cannot continue forever: The measure has to go down in each iteration, but it cannot do so since it's bounded below.
Termination proofs are usually harder, and coming up with a good measure can be tricky. But in this case, it's easy to come up with it:
def M(x):
  return 10-x

The claim is that the measure is always non-negative in this case. Let's prove that before the loop starts, i.e., when x == 0:
>>> prove (Implies(x == 0, M(x) >= 0))
proved

It goes down in each iteration:
>>> prove (Implies(C(x), M(x) > M(x+1)))
proved

And finally, it's always positive if the loop executes:
>>> prove (Implies(C(x), M(x) >= 0))
proved

Now we know that the loop will terminate, so our proof is complete.
But wait!
You might wonder if I pulled a rabbit out of a hat here. How do we know that the above steps are sufficient? Or that I didn't make a mistake in my coding as I waved my hand over your program and magically translated it to z3-python?
For the first question: There's established research that for traditional imperative program semantics, Hoare-logic style reasoning is sound. Here's a good slide deck to start with: https://www.cl.cam.ac.uk/teaching/1617/HLog+ModC/slides/lecture2.pdf
For the second question: This is where the rubber hits the road. You have to put my argument to peer-review, possibly using an established theorem prover to code the whole thing up and trust that the mechanization is correct. Why3 (https://why3.lri.fr) is a good-platform to get started for this style of reasoning.
Picking the invariant
The trickiest part of this proof is coming up with the right invariant. A "good" invariant is one that's not only true, but one that allows you to prove the result you want. For instance, consider the following invariant:
def I(p):
  return True

This invariant is manifestly true for all programs as well! But if you attempt to run the proofs we had with this version of I, you'll see that it won't go through and you'll get a counter-example. (It's quite instructive to do so.) In general, you can:

*

*Pick an "invariant" that's not really enforced by your program, i.e., it doesn't stay true at all times as described above. Hopefully the counter-example you get from the solver will be helpful to identify what goes wrong.

*Or, and this is way more likely, the invariant you picked is indeed an invariant of the program, but it is not strong enough to prove the result you want. In this case the counter-example will be less useful, and for complicated programs it can be hard to track down the reason why.
An invariant that allows you to prove the final result is called an "inductive invariant." The process of "improving" the invariant to get to a proof is known as "strengthening the invariant." There's a plethora of research in all of these topics, especially in the realm of model-checking. A good paper to read in these topics is Bradley's "Understanding IC3:" https://theory.stanford.edu/~arbrad/papers/Understanding_IC3.pdf.
Summary
The strategy outlined here is a "meta"-level proof: It's equivalent to a paper-proof which identified the proof goals, and shipped them to an SMT solver (z3 in this case), to finish the job. This is common practice in modern day proofs, i.e., coming up with sub-goals and using an automated-solver to discharge them. Theorem-provers like ACL2, Isabelle, Coq, etc. mechanize the "coming up with subgoals" part to a large extent, making sure the whole proof is sound with respect to a trusted (but typically very small) set of core-axioms. (This is the so called LCF methodology, see https://www.cl.cam.ac.uk/~jrh13/slides/manchester-12sep01/slides.pdf for a nice slide-deck on it.)
Hopefully this is a detailed-enough level answer for you to get you started in program verification with SMT-solvers. Perhaps it's more than what you asked for; but the rule-of-thumb is there is no free lunch in verification. It is a lot of work! However, you get pretty close to push-button reasoning these days (at least for certain kinds of programs) with the advances in automated theorem provers, SMT-solvers, and other frameworks that many people built over the years. Best of luck, but be warned that program-verification remains the holy-grail of computer science after almost 7-decades of work on it. Things always get better/easier, but there's much more work to be done in the field.


text:
Q: WatchKit NSAppTransportSecurity error I get this error when I run my project:

I have read a lot of questions but these don't helped me to solved my issue. In fact, I have set the value of App Transport Security Settings to YES (like in my screenshot) in both of my iOS app and watchOS extension.

Any idea? Thanks!

A: It seems to be disallowed for the "watchkitapp"-target itself. You are still able to add the ATS-Key to the Info.plist of the "watchkitapp-extension"-Target.
You should be able to define a exception-domain like this: