text:
Q: Mouse click on an input element with ng-currency places the caret at the begining of the input field (IE11) i have an input element with ng-currency directive. If i add a value to the input ,click away and then click back on the input using IE11, the caret is moved to the begining of the input. The correct behaviour would be to place the caret at the position in the value where the mouse click occured.
Here is a demo
As a solution i tried to use ng-focus and ng-blur directives to catch the element.selectionStart value before it is changed and then restore it on ng-click. This works for IE11 but not in Chrome, as the element.selectionStart value is not correct.
Any ideas on how to workaround this issue?

A: Long story short, here is a solution i ended up with:
<input
    ng-currency="$ctrl.getCurrencyDirectiveState()"
    ng-mousedown="$ctrl.setCurrencyDirectiveState(false)"
    ng-blur="$ctrl.setCurrencyDirectiveState(true)"
    ...>
</input>

Disabling the directive on mouse down so that the caret location is preserved and enabling it again when the focus is lost to show the formatted value.
Here is a link to the issue I opened in ng-currency repo.


text:
Q: Some HTML data is missing when I am trying to do webscraping using BeautifulSoup This is my code where I am trying to scrape data from this website https://community.hackernoon.com/u/
import requests
from bs4 import BeautifulSoup
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"}

r=requests.get("https://community.hackernoon.com/u/",headers=headers)
c=r.content

soup=BeautifulSoup(c,"html.parser")
print(soup.prettify())

When I print soup.prettify(), some HTML code is missing, as when I try to find the name of a writer from the website, in that HTML code, it shows no result found and I think that is why this all list is showing an empty list in the output
all=soup.find_all("div",{"id":"ember28"})
all

Can somebody help me see what is wrong?

A: Some websites like your example don't load all the data on the first load.
In your example, It loads the website base first and then loads the rest of the info using javascript.
(You can test this by disabling javascript in your browser)
You need to simulate a browser (for example, using selenium) to execute the website javascript and then scrape the data after it's been loaded.
Start here: https://selenium-python.readthedocs.io/

A: try:
from bs4 import BeautifulSoup as bs
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time

url = 'https://community.hackernoon.com/u/'
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.set_window_size(1024, 600)
driver.maximize_window()
driver.get(url)

soup=bs(driver.page_source,'html.parser')
time.sleep(3)
all_list=soup.find_all("span",{"class":"username"})
username_li = [user.text for user in all_list]

all_list:
[daria,
 alexcg,
 daytona500-live-tv,
 David,
 kunalmishra
.
.
.
]

username_li:
['daria',
 'alexcg',
 'daytona500-live-tv',
 'David',
 'kunalmishra',
 'Hackern00n457',
 'm15o',
 'mobphone22',
 'KeyReel',
 'msarica',
 'jeffsoo2',
 'bforgan',
 'paulandre',
 'kristinamulford24',
 'hgcontent',
 'anthony1',
 'aydin.sakar',
 'jeevansirela',
 'abhikdeora',
 'ce.roso398',
 'michaeltgately',
 'SweetHeartache',
 'max',
 'jgrossman28',
 'alek.shnayder',
 'derwiki',
 'daniel.h.heyman',
 'jmuller',
 'Vadim',
 'jessekorzan',
 'PitBullCH',
 'mbroudy4',
 'kevin.pang.w',
 'tnichols',
 'arpy',
 'list_startengine',
 'pratik.ropia',
 'davidyang',
 'avantika',
 'magneticmessages',
 'ben',
 'rob',
 'doron',
 'rich.kolasa',
 'jjfleagle',
 'B17Z',
 'eugeniya.korotya',
 'will.howard',
 'colin',
 'daniel.henrique.sc']

redpajama_set_name: RedPajamaStackExchange


text:
Q: JSP page omitting attribute values when visited for the second time I have a Java webapp, and it has a SpringMVC-like structure.

I have a problem with a jsp page which works fine the first time I invoke it, but on the second time, it just wont read the values from a session attribute named "student_subjects".
This is the teacher-edit-student-view-content.jsp :
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page import="dbbroker.DBBroker"%>

    <form action="./aplikacija" method="POST">

                    ${migrant_logged_in.countryOfOrigin}

                    ${migrant_logged_in.motherTongue}

                <c:forEach var="subj" items="${student_subjects}">

                        ${subj.subject.subjectName}
                        Evaluation: <textarea class="form-control" name="input${subj.subject.subjectName}" size="160">${subj.evaluation}</textarea>
                        Level

                                    <input type="radio" name="radio${subj.subject.subjectName}" ${subj.level == 'low' ? 'checked="checked"' : ''} value="low"> Low

                                    <input type="radio" name="radio${subj.subject.subjectName}" ${subj.level == 'medium' ? 'checked="checked"' : ''} value="medium"> Medium

                                    <input type="radio" name="radio${subj.subject.subjectName}" ${subj.level == 'high' ? 'checked="checked"' : ''} value="high"> High

                </c:forEach>

                    Enter new subject name:
                    <input type="text" class="new-field-name" id="new-subject-name"/>
                    <input class="btn btn-default" type="button" value="Add new subject" onclick="addField()" />

        <input class="btn btn-default pull-right" id="btn-edit-st-data" type="submit" value="Edit" name="editStudentView" />
        <input type="hidden" id="akcija" name="akcija" value="izmeniStudentovPogled" />
    </form>

The jsp page displays all fields the first time I invoke it:
But, on the second time I call the page, the  loop seems to skip all the variables from student_subjects session attribute, even though I checked the attribute and it contains all the values:

The jsp page is called from within an action class for that specific view (it has an execute(HttpRequest request) method, which receives the request from the FrontController class and this action sets the student_subjects attribute for the session.
Please help, I am struggling with this for two days and just when I think I got it it turns out not to work again.
The closest I was is when I put an if clause that tells the action not to pull data for student_subjects from the database if the attribute already exist for the session. The data was displayed properly, but it was old data and then I don't get the updated values displayed when I want to edit them again.
EDIT:
Java class that updates database with new values and sets the session attribute to new values:
package action;

import constants.WebConstants;
import dbbroker.DBBroker;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import model.Migrant;
import model.Studentsubjects;

public class UpdateStudentViewDataAction extends AbstractAction {

    public UpdateStudentViewDataAction() {
    }

    @Override
    @Transactional
    public String execute(HttpServletRequest request) {
        Migrant m = (Migrant) request.getSession().getAttribute(WebConstants.MIGRANT_LOGGED_IN);
        String studCode = m.getStudentCode();
        System.out.println(m.getStudentCode());
        List<Studentsubjects> listOfSubjects = new ArrayList<>();//DBBroker.getInstance().getSubjects(m.getStudentCode());
        Map map = request.getParameterMap();
        Enumeration en = request.getParameterNames();
        List<String> listOfSubjectNames = new ArrayList<>();
        for (Object parameter : Collections.list(en)) {
            String parnam = (String) parameter;
            if (parnam.startsWith("input")) {
                listOfSubjectNames.add(parnam.substring(5));
            }
        }
        for (String subjName : listOfSubjectNames) {
            Studentsubjects ssub = new Studentsubjects(studCode, subjName);
            String eval = Arrays.toString((String[]) map.get("input" + subjName)).replace("[", "");
            eval = eval.replace("]", "");
            ssub.setEvaluation(eval);
            String level = Arrays.toString((String[]) map.get("radio" + subjName)).replace("[", "");
            level = level.replace("]", "");
            ssub.setLevel(level);
            listOfSubjects.add(ssub);
        }
        DBBroker.getInstance().addSubjects(listOfSubjectNames);
        System.out.println("Lista predmeta: " + listOfSubjects);
        for (Studentsubjects subject : listOfSubjects) {
            DBBroker.getInstance().updateSubjectStudent(subject);
        }
        request.getSession(false).setAttribute(WebConstants.STUDENT_SUBJECTS, listOfSubjects);
        request.getSession(false).setAttribute(WebConstants.STUDENT_VIEW_DATA_SUCCESSFULLY_UPDATED, true);
        return WebConstants.PAGE_TEACHER_SELECT_ACTION;
    }

}

A: Ok, I finally got it. The problem was that I referenced the wrong field from my Studentsubjects class. Namely, JPA creates some weird StudentsubjectsPK field, which is actually what I needed in order to access the needed fields, which are a part of the primary key (PK).


text:
Q: How Do I Move Objects Inside An ng-Repeat on Button Click? I have a nifty list of items in an ng-repeat with an up and down button on each. I just want the up button to move the list item up one place and the down button should move it down one place.
The problem is that I get an error saying "Cannot read property 'NaN' of undefined."
It seems "position" is undefined on the second line. What can I do to fix that?
Heres the javascript I'm working with (thanks to Rishul Matta):
$scope.moveUp = function(ind, position) {
       $scope.temp = $scope.list[position - 1];
       $scope.list[position - 1] = $scope.list[position];
       $scope.list[position = temp];
  };

Here's my HTML:

      {{step.Name}}
      <input class="orderUpBtn" type="button" ng-click="moveUp($index, step)" style="z-index:50" value="U" />
      <input class="orderDownBtn" type="button" style="z-index:50" value="D" />

Thanks!

A: A simple list with up/down buttons is pretty straightforward, here's some rough generic code. The ngRepeat directive will honor the order of items in your array so moving things around the view is just a matter of moving them in the array itself.
view:

    {{item}}
    <button ng-click="demo.moveUp($index)">up</button>
    <button ng-click="demo.moveDown($index)">down</button>

controller:
app.controller('DemoCtrl', function() {
  this.list = list = ['one', 'two', 'three', 'four'];

  this.moveUp = function(ix) {
    if(ix > -1 && ix < list.length - 1) {
      var tmp = list[ix+1];
      list[ix+1] = list[ix];
      list[ix] = tmp;
    }
  };

  this.moveDown = function(ix) {
    // similar...
  };
});

There were a few strange items in your code (for example did you mean $scope.list[position] = temp; when you wrote ($scope.list[position = temp];), my example isn't perfect but it should get you going on the right path. Here's the full working demo: http://jsbin.com/vatekodeje, note that in my code I use "up" to mean increasing index rather than toward the top of the page.
Also in your controller you use position as an index (it's not clear that it should be) and make reference to, presumably, an array called $scope.list when in your view you use selectedWorkflow.Steps. Maybe your $scope.list and selectedWorkflow.Steps are meant to be the same thing?

A: Thanks for posting this question (+1) and the answer jtrussell (+1). I wanted to share what I believe to be a more re-usable/modular answer for other folks (inspired by odetocode.com post).
For the HTML, jtrussell's code is perfect because he fixed/simplified everything. For a better user experience I just added ng-disabled for the first/last elements.
HTML:

        {{item}}
        <button class="move-up"
            ng-click="listItemUp($index)"
            ng-disabled="$first">
                Move Up
        </button>
        <button class="move-down"
            ng-click="listItemDown($index)"
            ng-disabled="$last">
            Move Down
    </button>

For the JS, Notice the moveItem() function which I believe to be more re-usable. You can use this function for other drag+drop swapping functionality as well.
JS within Controller (tested on Angular 1.3.15):
// Move list items up or down or swap
$scope.moveItem = function (origin, destination) {
    var temp = $scope.list[destination];
    $scope.list[destination] = $scope.list[origin];
    $scope.list[origin] = temp;
};

// Move list item Up
$scope.listItemUp = function (itemIndex) {
    $scope.moveItem(itemIndex, itemIndex - 1);
};

// Move list item Down
$scope.listItemDown = function (itemIndex) {
    $scope.moveItem(itemIndex, itemIndex + 1);
};

I hope it is helpful to someone out there. Thanks SO community!


text:
Q: Second order partial derivative 9 I am following a work where the authors start a production function and get this first order partial derivative (with respect to $ k $):
$$ f'(k)=\frac{a(1+bk)}{k^{1-a}(1+abk)^{a}} $$
And by deriving it again obtain the following second order partial derivative:
$$ f''(k)=a(a-1)k^{a-2}(1+abk)^{-a-1} $$
I managed to get the first one but not the second one. Is there someone who can help me with this? Thank u so much and Happy Christmas!! :)

A: I think that this is a good problem for logarithmic differentiation.
Consider
$$y=\frac{a(1+bk)}{k^{1-a}(1+abk)^{a}}$$ $$\log(y)=\log(a)+\log(1+bk)-(1-a)\log(k)-a\log(1+abk)$$ Differentiate both sides
$$\frac{y'}y=\frac {b}{1+bk}-\frac{1-a}k-\frac{a^2b}{1+abk}=\frac{a-1}{k (1+b k) (1+a b k)}$$
Now
$$y'=y \times \frac{y'}y=\frac{a(1+bk)}{k^{1-a}(1+abk)^{a}}\times \frac{a-1}{k (1+b k) (1+a b k)}$$
Just simplify.
Merry Xmas

A: Ugly exercise.
You can write $f'(k)=a(1+bk)k^{a-1}(1+abk)^{-a}$. Therefore
$$f''(k)=abk^{a-1}(1+abk)^{-a}+a(1+bk)(a-1)k^{a-2}(1+abk)^{-a} +a(1+bk)k^{a-1}(-a)ab(1+abk)^{-a-1} $$
$$ = ak^{a-2}(1+abk)^{-a-1}[ bk(1+abk) + (1+bk)(a-1)(1+abk) + k(1+bk)(-a)ab] = $$
$$ = ak^{a-2}(1+abk)^{-a-1}(bk+ab^2k + a + a^2bk -1 - abk + bka +a^2b^2k^2 -bk -ab^2k^2 - a^2bk - a^2b^2k^2) $$
and after simplifications you get the required results. Happy Christmas!


text:
Q: How to count number of records on the same time interval in past? We have two inputs DATE_FROM and DATE_TO in the format of 'YYYY-mm-dd', the question is to count the number of records in the period [DATE_FROM, DATE_TO) and [DATE_FROM -INTERVAL(DATE_TO,DATE_FROM), DATE_FROM).
To count the number of records in the first interval we perform the following query
SELECT
    count(*) as num_records
FROM mytable
WHERE
    mytable.date_doc >= 'DATE_FROM 00:00:00'
AND mytable.date_doc <= 'DATE_TO 23:59:59'

here the date is appended by the midnight hour:minute:second to heap all records of the days on the boundary.
How to construct the query that perform the same count on the second inteval of time?
Is it possible to do it in one query to database or propose any optimal way to do it?
EDIT
Interval 1 (10 days): DATE_FROM = '2012-11-03 00:00:00', DATE_TO = '2012-11-12 23:59:59'
Interval 2 (10 days): DATE_FROM = '2012-10-24 00:00:00', DATE_TO = '2012-11-02 23:59:59'
SELECT
   SUM(IF(DATE(mytable.date_doc) BETWEEN '2012-11-03 00:00:00' AND '2012-11-12 23:59:59', 1, 0)) AS count_interval1,
   SUM(IF(DATE(mytable.date_doc) BETWEEN '2012-10-24 00:00:00' AND '2012-11-03 00:00:00', 1, 0)) AS count_interval2
FROM mytable

Thank you for your expertise!

A: Try this:
SELECT
   SUM(IF(DATE(mytable.date_doc) BETWEEN '2012-11-03' AND '2012-11-12', 1, 0)) AS count_interval1,
   SUM(IF(DATE(mytable.date_doc) BETWEEN SUBDATE('2012-11-03', DATEDIFF('2012-11-12', '2012-11-03') + 1) AND SUBDATE('2012-11-03', 1), 1, 0)) AS count_interval2
FROM mytable

No need to specify the time.


text:
Q: How can I block ads on Windows 8.1 Book Reader? When I read epub books using Windows 8.1 Book Reader, I see ads at the bottom of the screen. I have tried to change settings in the default firewall included with Windows to no avail.  I downloaded and installed http://www.privacyware.com/personal_firewall.html but the Book Reader program is not listed as a running application.
Edit: I suspect that this is because this program runs as a metro apps under WWAHost.exe, one of potentially many such programs.  Since WWAHost.exe is a generic program, it might be counterproductive to prevent it from accessing the internet.  This is just guesswork of my part.

A: There is no default app in Windows 8.1 called "Book Reader". There are third-party apps made by independent developed with this title. These probably use the ads to support the developers (that's how they can give the app away for "free" even though it took hard work to develop it.
If you wish to use an ad-free ebook reader app, look for one that specifies it is ad-free.


text:
Q: How to synchronize SerialPort operations? I have an application that communicates with a microcontroller via serial port. I want to check the controller's status periodically in a Background Worker, and also allow the user to interact with the controller asynchronously (via user interface), by sending commands and receiving responses.
The UI and Background Worker use the SerialCommunication static class:
static class SerialCommunication
{
    static SerialPort serialPort;
    static int readWriteTimeout = 1000; // [ms]
    static int waitForTransmissionTimeout = 2; // [s]
    static string rxData = "", endOfString = "" + char.MinValue;
    static bool WaitingForSerialData = false; // Set in SerialWrite(), cleared in SerialRead()

    [...]
    public static string SerialRead()
    {
        try
        {
            rxData = serialPort.ReadTo(endOfString);
        }
        catch (TimeoutException)
        {
            WaitingForSerialData = false;
            throw new Exception(Properties.Resources.serial_read_timeout);
        }
        WaitingForSerialData = false;
        return rxData;
    }

    public static void SerialWrite(string text)
    {
        DateTime start = DateTime.Now;
        while (WaitingForSerialData) // Avoids the situation in which a command executed on a thread receives the response for the command executed from a different thread
        {
            if (!WaitingForSerialData)
            {
                try
                {
                    WaitingForSerialData = true; // All commands wait for confirmation/data, so it is normal to set this boolean value for every serial transmission
                    serialPort.Write(text);
                }
                catch (TimeoutException)
                {
                    throw new Exception(Properties.Resources.serial_write_timeout);
                }
            }
            else
            {
                System.Threading.Thread.Sleep(100);
                if ((DateTime.Now - start).Seconds >= waitForTransmissionTimeout)
                {
                    throw new Exception("Timeout");
                }
            }
        }
    }
}

The serial port is initialized at application startup. SerialWrite and SerialRead are called in the UI or Background Worker consecutively.
I want to avoid situations in which a command receives the response from another command executed in a different thread. Currently, I've implemented waiting in SerialWrite for the command to be received (for SerialRead to finish) before sending the command, but I'm afraid that this can block the UI (for up to waitForTransmissionTimeout seconds), if SerialWrite is executed from there.
So what is the best way to synchronize the SerialPort operations?

A: I don't know the whole situation, but it seems to me you can just use a simple lock to serialize your write followed by read, like this:
static class SerialCommunication
{
    static SerialPort serialPort;
    static string endOfString = "" + char.MinValue;
    static readonly object _commandLock = new object();

    public static string SendCommand(string text) {
        lock (_commandLock) {
            SerialWrite(text);
            return SerialRead();
        }
    }

    private static string SerialRead() {
        try {
            return serialPort.ReadTo(endOfString);
        }
        catch (TimeoutException) {
            throw new Exception(Properties.Resources.serial_read_timeout);
        }
    }

    private static void SerialWrite(string text) {
        try {
            serialPort.Write(text);
        }
        catch (TimeoutException) {
            throw new Exception(Properties.Resources.serial_write_timeout);
        }
    }
}


text:
Q: Receiving error: actual and formal argument lists differ in length I am receiving the error:

actual and formal argument lists differ in length

However; the Login class is configured to only two strings?
Can anyone shed some light on this issue?
This is my code:
/**
 *
 * @author vince
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //Attempt to Login
        System.out.println(login("username","password"));
    }

    private static LoginResponse login(Login authParameters) throws DispatchServiceFault {
        client.DispatchService_Service service = new client.DispatchService_Service();
        client.DispatchService port = service.getDispatchServicePort();
        return port.login(authParameters);
    }
}


text:
Q: volley imageloader imagelistener just show the the errorImageResId For fetching images and showing them in a recycler view I used volley imageloader,
Pic_class.java
    public class Pic_class {
    //Data Variables
    private String url;
    private String name;

    //Getters and Setters
    public String geturl() {
        return url;
    }

    public void seturl(String imageUrl) {
        this.url = imageUrl;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

CardAdapter.java
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {

    //Imageloader to load image
    private ImageLoader imageLoader;
    private Context context;

    //List to store all superheroes
    List<Pic_class> superHeroes;

    //Constructor of this class
    public CardAdapter(List<Pic_class> superHeroes, Context context){
        super();
        //Getting all superheroes
        this.superHeroes = superHeroes;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.pic_recycler, parent, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        //Getting the particular item from the list
        Pic_class superHero =  superHeroes.get(position);

        Log.i("superHero(position)",superHero.geturl());

        //Loading image from url
        imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
        imageLoader.get(superHero.geturl(),
                ImageLoader.getImageListener(
                        holder.imageView,
                        R.drawable.exit,
                        android.R.drawable.ic_dialog_alert));

        Log.i("imageLoader",imageLoader.toString());

        //Showing data on the views
        holder.imageView.setImageUrl(superHero.geturl(), imageLoader);
        holder.textViewName.setText(superHero.getName());
        //holder.textViewPublisher.setText(superHero.getPublisher());

    }

    @Override
    public int getItemCount() {
        return superHeroes.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{
        //Views
        public NetworkImageView imageView;
        public TextView textViewName;
       // public TextView textViewPublisher;

        //Initializing Views
        public ViewHolder(View itemView) {
            super(itemView);
            imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
            textViewName = (TextView) itemView.findViewById(R.id.textViewName);
           // textViewPublisher = (TextView) itemView.findViewById(R.id.textViewPublisher);
        }
    }
}

Last_pics.java
    public class Last_pics extends Fragment /*implements RecyclerView.OnScrollChangeListener*/{

    //Data URL
    public static final String DATA_URL = "http://10.0.3.2:90/android/pic_list.php?page=";
    //JSON TAGS
    public static final String TAG_TEN = "ten";
    public static final String TAG_URL = "url";

    //Creating a List of superheroes
    private List<Pic_class> listSuperHeroes;

    //Creating Views
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.Adapter adapter;

    //Volley Request Queue
    private RequestQueue requestQueue;

    //The request counter to send ?page=1, ?page=2  requests
    private int requestCount = 1;

    LinearLayout ll;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /** Inflating the layout for this fragment **/
        ll = (LinearLayout) inflater.inflate(R.layout.last_pics, container, false);

        //Initializing Views
        recyclerView = (RecyclerView) ll.findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);

        //Initializing our superheroes list
        listSuperHeroes = new ArrayList<>();
        requestQueue = Volley.newRequestQueue(getActivity());

        //Calling method to get data to fetch data
        getData();

        //Adding an scroll change listener to recyclerview
//        recyclerView.setOnScrollChangeListener(this);

        //initializing our adapter
        adapter = new CardAdapter(listSuperHeroes, getActivity());

        //Adding adapter to recyclerview
        recyclerView.setAdapter(adapter);

        return ll;
    }

    //Request to get json from server we are passing an integer here
    //This integer will used to specify the page number for the request ?page = requestcount
    //This method would return a JsonArrayRequest that will be added to the request queue
    private JsonArrayRequest getDataFromServer(int requestCount) {
        //Initializing ProgressBar
        final ProgressBar progressBar = (ProgressBar) ll.findViewById(R.id.progressBar1);

        //Displaying Progressbar
        progressBar.setVisibility(View.VISIBLE);
        getActivity().setProgressBarIndeterminateVisibility(true);

        //JsonArrayRequest of volley
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL + String.valueOf(requestCount),
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        //Calling method parseData to parse the json response
                       parseData(response);
                        //Hiding the progressbar
                        progressBar.setVisibility(View.GONE);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressBar.setVisibility(View.GONE);
                        //If an error occurs that means end of the list has reached
                        Toast.makeText(getActivity(), "No More Items Available", Toast.LENGTH_SHORT).show();
                    }
                });

        //Returning the request
        return jsonArrayRequest;
    }

    //This method will get data from the web api
    private void getData() {
        //Adding the method to the queue by calling the method getDataFromServer
        requestQueue.add(getDataFromServer(requestCount));
        //Incrementing the request counter
        requestCount++;
    }

    //This method will parse json data
    private void parseData(JSONArray array) {
        for (int i = 0; i < array.length(); i++) {
            //Creating the superhero object
            Pic_class superHero = new Pic_class();
            JSONObject json = null;
            try {
                //Getting json
                json = array.getJSONObject(i);

                //Adding data to the superhero object
                superHero.seturl(json.getString(TAG_URL));
                superHero.setName(json.getString(TAG_TEN));

                Log.i("dooghaie",superHero.getName()+superHero.geturl());
                //superHero.setPublisher(json.getString(Config.TAG_PUBLISHER));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //Adding the superhero object to the list
            listSuperHeroes.add(superHero);
        }

        //Notifying the adapter that data has been added or changed
        adapter.notifyDataSetChanged();
    }

    //This method would check that the recyclerview scroll has reached the bottom or not
    private boolean isLastItemDisplaying(RecyclerView recyclerView) {
        if (recyclerView.getAdapter().getItemCount() != 0) {
            int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
            if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
                return true;
        }
        return false;
    }

}

But in run, in emulator, in the recyclerview, just there are android.R.drawable.ic_dialog_alert in imageviews
instead of images from database.
What is wrong? Why it doesn't show images from database?


text:
Q: How do i remove blank lines from code filled list I have a problem and have modified "jlore" code of =if(d3 = "PS588", c3, "")
 which works, but is there a way to populate so I don't get blank lines? My task is to generate an Excel HV switching program on one sheet then on the next an isolation list. I am attempting to auto populate the Isolation list with the code =IF(HVSP!H30 = "APPLY ISOL LOCK & TAG", HVSP!E30, "").
However as stated if the "APPLY ISOL LOCK &TAG" isn't in the cell my isolation list creates a blank line.
Regards
Steve Mack

A: If i have understood your question correctly, you are getting a blank cell because of the ,"") at the end.  If you change this to ,"DON'T APPLY ISOL LOCK & TAG") or wording of your choice you will not get a blank cell.
Hope this helps.


text:
Q: remove nomenclature header in elsarticle appendix I have the following code:
\documentclass[authoryear, review]{elsarticle} %preprint

\usepackage{xpatch}
\usepackage{nomencl}

\xpatchcmd{\thenomenclature}{%
  \section*{\nomname}% Look for `\section*... etc.
}{% Replace it by 'nothing'
}{\typeout{Success}}{\typeout{Failure}}

\makenomenclature

\begin{document}
\section{Section example}
This is my text, where variables appear.
\nomenclature[1]{$\mu$}{Example variable}

\appendix
\section{Definition of model variables}
\printnomenclature[0.9in]
\end{document}

As you see I have the nomenclature within an appendix, and I use xpatch to remove the nomenclature header added by the nomenclature package. This used to work, but I updated my elsarticle class, and I think this is the reason it stopped working. I would be grateful if I could get some help addressing this issue.
Also, related to the appendix, I would like to remove the word Appendix including the space after it from the appendix heading. I added:
\let\appendixname\relax

... to the preamble, but while this removes the word Appendix, it also leaves the pre-existing space between Appendix and A. Any solutions to this additional question would be very welcome as well.


text:
Q: Load-balancing Database Connection Pool What database connection pool could be used to load-balance connections from a Tomcat web container to one of several Oracle database servers without using RAC clustering?

A: Look into DRCP if using 11g

A: I'm assuming these are read-only databases or you're not concerned connections will get different data.  If you want the data to be the same, you can use streams replication which is doesn't require RAC.
The connection load balancing and failover happens in the listener.  There's a lot of flexibility in how this works and this should get you started:
http://download.oracle.com/docs/cd/E11882_01/network.112/e10836/advcfg.htm#sthref858
The first part shows a simple client based load balance which is essentially picking a connection at random.  Farther down it shows how to load balance based on actual server load.


text:
Q: Renaming file name in asset folder dynamically I have database(say x.db) stored in asset folder(path = "\app\src\main\assets"). I am trying to change its name before it is loaded in runtime but for some reason, I am unable to do so. My goal is to rename the database per user. So if there is 3 user I want to have 3 new databases plus the initial database.
My code snipped when it runs for the first time,
    try {
        File oldFile = new File("\\app\\src\\main\\assets");
        File[] listOfFiles = oldFile.listFiles();//this is always empty.
        for (File listOfFile : listOfFiles) {
            if (listOfFile.isFile() && listOfFile.getName().equals("x.db")) {
                return listOfFile.renameTo(new File("y" + ".db"));
            }
        }
        return false;
    } catch (Exception e) {
        return false;
    }

A:
My goal is to rename the database per user.

Then you do not need to rename the asset file, which you cannot as it's part of the APK and thus protected. What you do is copy the asset into the the location where the database is to be stored using the database name that you require per user.
Example
The following example creates 3 databases copying them from the single asset (mydb in this case). The core code is what is termed as the DatabaseHelper (a subclass of SQLiteOpenHelper). Typically this is written to be constructed from just the Context. In this case the user name is passed thus allowing seperate database per user. The database name being the user name suffixed by the asset name.
The database helper MultiUserDBHelper.java :-
public class MultiUserDBHelper extends SQLiteOpenHelper {

    public static final String ASSET_NAME = "mydb";
    public String DB_PATH;

    Context mContext;
    SQLiteDatabase mDataBase;

    public MultiUserDBHelper(Context context, String User) {

        super(context, User+ASSET_NAME, null, 1);
        DB_PATH = context.getDatabasePath(User+ASSET_NAME).getPath();
        this.mContext = context;
        if (!checkDataBase()) {
            copyDataBase();
        }
        mDataBase = this.getWritableDatabase(); //Forces open and therefore creation if db doesn exist.
    }

    public void copyDataBase() {
        try {
            InputStream myInput = mContext.getAssets().open(ASSET_NAME);
            String outputFileName = DB_PATH;
            OutputStream myOutput = new FileOutputStream(outputFileName);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0)
                myOutput.write(buffer, 0, length);

            myOutput.flush();
            myOutput.close();
            myInput.close();
            ;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Error copying database from asset");
        }
    }

    public boolean checkDataBase() {
        File dbfile = new File(DB_PATH);
        if (dbfile.exists()) return true;
        if (!(dbfile.getParentFile()).exists()) dbfile.getParentFile().mkdirs();
        return false;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

An Activity that demonstrates use of the above for 3 users :-
public class MainActivity extends AppCompatActivity {

    MultiUserDBHelper dbuser1, dbuser2, dbuser3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbuser1 = new MultiUserDBHelper(this,"User1");
        dbuser2 = new MultiUserDBHelper(this,"User2");
        dbuser3 = new MultiUserDBHelper(this,"User3");
    }
}

*

*Obviously you would introduce a methodlogy for selecting/switching users. The abve is intended only to demonstrate the copying/access to each individual database.

After running the above Device Explorer has :-


text:
Q: How to create plain text representations of tables in PHP? I will give a little background.  I'm working on a pay-per-click engine, and I am running into a problem generating reports (daily, weekly, monthly) that contain a user's listings and clicks with a rate / total column.  I want to represent this information in plain-text format for compatibility reasons, and also because I hate HTML mail.
Should I try to do this?  Or just send them a notification that their invoice / summary is available in the application?

A: in case you prefer not to reinvent the wheel, there's pear console_table or a tiny but working function of mine http://stereofrog.com/blok/on/070116.

A: You can loop through the lists of data and use the sprintf function (http://php.net/manual/en/function.sprintf.php) to display each line while maintaining consistent spacing.
You can similarly accomplish maintaining constitent spacing with the str_pad function (http://us3.php.net/manual/en/function.str-pad.php)


text:
Q: Wakanda ssjs logging library needed Is there a recommended logging library for Wakanda ssjs that provides configurable levels with development/production switches?

A: Try this one it handles log levels, log format, flush delay


text:
Q: Convert multiple level list of nested dictionaries into single list of dictionaries I want to convert multiple level list of nested dictionaries into a single list of dictionary
input:
list_ = [
 {'Name': 'Paras Jain',
  'Student': [{'Exam': 90,
               'Grade': 'a',
               'class': [{'age': 10, 'subject': 'hindi'},
                         {'age': 11, 'subject': 'maths'}]},
              {'Exam': 99,
               'Grade': 'b',
               'class': [{'age': 14, 'subject': 'evs'},
                         {'age': 15, 'subject': 'science'}]},
              {'Exam': 97,
               'Grade': 'c',
               'class': [{'age': 10, 'subject': 'history'}]}]},
 {'Name': 'Chunky Pandey',
  'Student': [{'Exam': 89,
               'Grade': 'a',
               'class': [{'age': 9, 'subject': 'no'}]},
              {'Exam': 80, 'Grade': 'b', 'class': []}]},
 {'Name': 'abc', 'Student':[]}
]

Required output:
[{'Exam': 90, 'Grade': 'a', 'Name': 'Paras Jain', 'age': 10, 'subject': 'hindi'},
 {'Exam': 90, 'Grade': 'a', 'Name': 'Paras Jain', 'age': 11, 'subject': 'maths'},
 {'Exam': 90, 'Grade': 'b', 'Name': 'Paras Jain', 'age': 14, 'subject': 'evs'},
 {'Exam': 90, 'Grade': 'b', 'Name': 'Paras Jain', 'age': 15, 'subject': 'science'},
 {'Exam': 97, 'Grade': 'c', 'Name': 'Paras Jain', 'age': 10, 'subject': 'history'},
 {'Exam': 89, 'Grade': 'a', 'Name': 'Chunky Pandey', 'age': 9, 'subject': 'no'},
 {'Exam': 89, 'Grade': 'a', 'Name': 'Chunky Pandey', 'age': 'NA', 'subject': 'NA'},
 {'Exam': 'NA', 'Grade': 'NA', 'Name': 'abc', 'age': 'NA', 'subject': 'NA'}]

A: Let's try
for d in list_:
    if not d.get('Student', []):
        if 'Student' in d:
            d['Student'].append({})
        else:
            d['Student'] = [{}]

df = pd.json_normalize(list_, record_path='Student', meta='Name').explode('class', ignore_index=True)
out = df.join(df.pop('class').apply(pd.Series)).drop(columns=0).to_dict(orient='records')

print(df)

   Exam Grade                              class           Name
0  90.0     a    {'age': 10, 'subject': 'hindi'}     Paras Jain
1  90.0     a    {'age': 11, 'subject': 'maths'}     Paras Jain
2  99.0     b      {'age': 14, 'subject': 'evs'}     Paras Jain
3  99.0     b  {'age': 15, 'subject': 'science'}     Paras Jain
4  97.0     c  {'age': 10, 'subject': 'history'}     Paras Jain
5  89.0     a        {'age': 9, 'subject': 'no'}  Chunky Pandey
6  80.0     b                                NaN  Chunky Pandey
7   NaN   NaN                                NaN            abc

pprint(out, width=150)

[{'Exam': 90.0, 'Grade': 'a', 'Name': 'Paras Jain', 'age': 10.0, 'subject': 'hindi'},
 {'Exam': 90.0, 'Grade': 'a', 'Name': 'Paras Jain', 'age': 11.0, 'subject': 'maths'},
 {'Exam': 99.0, 'Grade': 'b', 'Name': 'Paras Jain', 'age': 14.0, 'subject': 'evs'},
 {'Exam': 99.0, 'Grade': 'b', 'Name': 'Paras Jain', 'age': 15.0, 'subject': 'science'},
 {'Exam': 97.0, 'Grade': 'c', 'Name': 'Paras Jain', 'age': 10.0, 'subject': 'history'},
 {'Exam': 89.0, 'Grade': 'a', 'Name': 'Chunky Pandey', 'age': 9.0, 'subject': 'no'},
 {'Exam': 80.0, 'Grade': 'b', 'Name': 'Chunky Pandey', 'age': nan, 'subject': nan},
 {'Exam': nan, 'Grade': nan, 'Name': 'abc', 'age': nan, 'subject': nan}]

A: Optimized, Tested with 72 million records produced in 41 seconds
For your completely blank [{}] * 900000 example, it finished in 0.42 seconds:
from itertools import chain
from pprint import pprint
from time import time

def make_record(name: str,
                exam: str='NA',
                grade: str='NA',
                age: str='NA',
                subject: str='NA') -> dict:
    return {'Name': name,
            'Exam': exam,
            'Grade': grade,
            'age': age,
            'subject': subject}

def fix_record(data: dict) -> list:
    new_data = []
    name = data.get('Name', 'NA')
    students = data.get('Student', [])
    if students:
        for student in students:
            exam = student.get('Exam', 'NA')
            grade = student.get('Grade', 'NA')
            classes = student.get('class', [])
            if classes:
                for c in classes:
                    age = c.get('age', 'NA')
                    subject = c.get('subject', 'NA')
                    new_data.append(make_record(name, exam, grade, age, subject))
            else:
                new_data.append(make_record(name, exam, grade))
    else:
        new_data.append(make_record(name))
    return new_data

list_ = [
 {'Name': 'Paras Jain',
  'Student': [{'Exam': 90,
               'Grade': 'a',
               'class': [{'age': 10, 'subject': 'hindi'},
                         {'age': 11, 'subject': 'maths'}]},
              {'Exam': 99,
               'Grade': 'b',
               'class': [{'age': 14, 'subject': 'evs'},
                         {'age': 15, 'subject': 'science'}]},
              {'Exam': 97,
               'Grade': 'c',
               'class': [{'age': 10, 'subject': 'history'}]}]},
 {'Name': 'Chunky Pandey',
  'Student': [{'Exam': 89,
               'Grade': 'a',
               'class': [{'age': 9, 'subject': 'no'}]},
              {'Exam': 80, 'Grade': 'b', 'class': []}]},
 {'Name': 'abc', 'Student':[]}
]
list_ *= 9e6

if __name__ == '__main__':
    start = time()

    list_ = list(chain.from_iterable(map(fix_record, list_)))

    print(f'{time()-start:.2f} seconds')
    print('Total Records: ', len(list_))
    print('First 10 Records:')
    pprint(list_[:10], width=150)

    list2 =  [{}] * 9e6
    start = time()
    list2 = list(chain.from_iterable(map(fix_record, list2)))
    print(f'{time()-start:.2f} seconds')
    pprint(list2[:10], width=150)

Output:
41.02 seconds
Total Records:  72000000
First 10 Records:
[{'Exam': 90, 'Grade': 'a', 'Name': 'Paras Jain', 'age': 10, 'subject': 'hindi'},
 {'Exam': 90, 'Grade': 'a', 'Name': 'Paras Jain', 'age': 11, 'subject': 'maths'},
 {'Exam': 99, 'Grade': 'b', 'Name': 'Paras Jain', 'age': 14, 'subject': 'evs'},
 {'Exam': 99, 'Grade': 'b', 'Name': 'Paras Jain', 'age': 15, 'subject': 'science'},
 {'Exam': 97, 'Grade': 'c', 'Name': 'Paras Jain', 'age': 10, 'subject': 'history'},
 {'Exam': 89, 'Grade': 'a', 'Name': 'Chunky Pandey', 'age': 9, 'subject': 'no'},
 {'Exam': 80, 'Grade': 'b', 'Name': 'Chunky Pandey', 'age': 'NA', 'subject': 'NA'},
 {'Exam': 'NA', 'Grade': 'NA', 'Name': 'abc', 'age': 'NA', 'subject': 'NA'},
 {'Exam': 90, 'Grade': 'a', 'Name': 'Paras Jain', 'age': 10, 'subject': 'hindi'},
 {'Exam': 90, 'Grade': 'a', 'Name': 'Paras Jain', 'age': 11, 'subject': 'maths'}]

0.42 seconds
[{'Exam': 'NA', 'Grade': 'NA', 'Name': 'NA', 'age': 'NA', 'subject': 'NA'},
 {'Exam': 'NA', 'Grade': 'NA', 'Name': 'NA', 'age': 'NA', 'subject': 'NA'},
 {'Exam': 'NA', 'Grade': 'NA', 'Name': 'NA', 'age': 'NA', 'subject': 'NA'},
 {'Exam': 'NA', 'Grade': 'NA', 'Name': 'NA', 'age': 'NA', 'subject': 'NA'},
 {'Exam': 'NA', 'Grade': 'NA', 'Name': 'NA', 'age': 'NA', 'subject': 'NA'},
 {'Exam': 'NA', 'Grade': 'NA', 'Name': 'NA', 'age': 'NA', 'subject': 'NA'},
 {'Exam': 'NA', 'Grade': 'NA', 'Name': 'NA', 'age': 'NA', 'subject': 'NA'},
 {'Exam': 'NA', 'Grade': 'NA', 'Name': 'NA', 'age': 'NA', 'subject': 'NA'},
 {'Exam': 'NA', 'Grade': 'NA', 'Name': 'NA', 'age': 'NA', 'subject': 'NA'},
 {'Exam': 'NA', 'Grade': 'NA', 'Name': 'NA', 'age': 'NA', 'subject': 'NA'}]

A: I tried below two ways but looking for a more optimized way:
How I tested for 2700000 records. Just multiple [{}] * 900000
1st way
# tested with 2700000 records
import time
start_time = time.time()
rows = []
for data in list_:
    if data['Student']:
        for row in data['Student']:
            row['Exam'] = row['Exam']
            row['Grade'] = row['Grade']
            row['class'] = row['class']
            row['Name'] = data['Name']
            rows.append(row)
    else:
        rows.append({
            'Exam': '',
            'Grade': '',
            'class': [],
            'Name': data['Name']
        })

res = []

for data in rows:
    if data["class"]:
        for in_row in data['class']:
            in_row['Exam'] = data['Exam']
            in_row['Grade'] = data['Grade']
            in_row['age'] = in_row['age']
            in_row['subject'] = in_row['subject']
            in_row['Name'] = data['Name']
            res.append(in_row)
    else:
        res.append({
            'Exam': data['Exam'],
            'Grade': data['Grade'],
            'age': '',
            'subject': '',
            'Name': data['Name']
        })

end_time = time.time()
print(end_time-start_time)
# 15.956519842147827

2nd way
# First, fix your empty class list, so pd.json_normalize doesn't ignore it:
import time
import pandas as pd
start_time = time.perf_counter()
for i, x in enumerate(list_1):
    if not x['Student']:
        list_1[i]['Student'] = [{'Exam': 'NA', 'Grade': 'NA', "class": [{}]}]
    else:
        for j, y in enumerate(x['Student']):
            if not y['class']:
                list_1[i]['Student'][j]['class'] = [{}]

# https://towardsdatascience.com/
#all-pandas-json-normalize-you-should-know-for-flattening-json-13eae1dfb7dd
df = pd.json_normalize(list_1, record_path=['Student', 'class'], meta=['Name', ['Student', 'Exam'], ['Student', 'Grade']])
# df.columns = df.columns.str.replace('Student.', '', regex=False)
# df.columns = df.columns.str.replace('age', 'Student.class.age', regex=False)
# df.columns = df.columns.str.replace('subject', 'Student.class.subject', regex=False)

dict_ = {
    'age': 'Student.class.age',
    'subject': 'Student.class.subject'
}
# inplace = true because we just modify the working data frame if we pass #inplace = false then it returns a new data frame.
df.rename(columns=dict_, inplace=True)
df = df.fillna('NA')

out = df.to_dict('records')
end_time = time.perf_counter()
print(end_time-start_time)
# 54.662456035614014


text:
Q: How to connect Node.js application to MongoDB Atlas Cloud using certificate with Mongoose? I try to connect to MongoDB Cloud database. I chose authentication with X509 certificate. I can connect to with mongosh or MongoDB Compass.
For example:
mongosh "mongodb+srv://somewhere.d3m3rrv.mongodb.net/macau-game?authSource=%24external&authMechanism=MONGODB-X509" --apiVersion 1 --tls --tlsCertificateKeyFile rootCA.pem

works well but with Node.js:
mongoose.connect(config.db.mongoUri, {
    tls: true,
    authMechanism: 'MONGODB-X509',
    authSource: "$external",
    tlsCAFile: `rootCA.pem`
});

logger.info("Trying to connect to database " + config.db.mongoUri)

mongoose.connection
    .once("open", () => {
        logger.info("MongoDB Connection success");
    })
    .on("error", (error) => {
        logger.error("MongoDB Connection to " + config.db.mongoUri + "failed");
    })

I get this error:
MongooseServerSelectionError: unable to get local issuer certificate
    at Connection.openUri (/root/app/dist/node_modules/mongoose/lib/connection.js:807:32)

IP address is added to whitelist, .pem file chmod is set to 400. Please help me.
UPDATE:
I updated mongoose connect options. Current version:
mongoose.connect(config.db.mongoUri, {
    ssl: true,
    sslCert: credentials,
    sslKey: credentials,
});

Server connects to the database, but when try load any data I get this error:
MongoServerError: user is not allowed to do action [find] on [my-db.chats]
    at Connection.onMessage (/Users/me/Projects/my-project/node_modules/mongodb/src/cmap/connection.ts:450:20)

On the MongoDB Cloud database access cnofiguration user of this cert has privilages to read and write to any database.


text:
Q: How to populate list of list json in jqgrid? that is list for main grid under list is for subgrid How to populate list of list json in jqgrid? that is list for main grid under list is for subgrid,
Jqgrid code as below,
    jQuery("#sg1").jqGrid({
    url: 'server.php?q=1',
    datatype: "json",
    height: 190,
    colNames: ['Inv No', 'Date', 'Client', 'Amount', 'Tax', 'Total', 'Notes'],
    colModel: [{
        name: 'id',
        index: 'id',
        width: 55
    }, {
        name: 'invdate',
        index: 'invdate',
        width: 90
    }, {
        name: 'name',
        index: 'name',
        width: 100
    }, {
        name: 'amount',
        index: 'amount',
        width: 80,
        align: "right"
    }, {
        name: 'tax',
        index: 'tax',
        width: 80,
        align: "right"
    }, {
        name: 'total',
        index: 'total',
        width: 80,
        align: "right"
    }, {
        name: 'note',
        index: 'note',
        width: 150,
        sortable: false
    }],
    rowNum: 8,
    rowList: [8, 10, 20, 30],
    pager: '#psg1',
    sortname: 'id',
    viewrecords: true,
    sortorder: "desc",
    multiselect: false,
    subGrid: true,
    caption: "Custom Icons in Subgrid", // define the icons in subgrid
    subGridOptions: {
        "plusicon": "ui-icon-triangle-1-e",
        "minusicon": "ui-icon-triangle-1-s",
        "openicon": "ui-icon-arrowreturn-1-e"
    },
    subGridRowExpanded: function(subgrid_id, row_id) {
        var subgrid_table_id, pager_id;
        subgrid_table_id = subgrid_id + "_t";
        pager_id = "p_" + subgrid_table_id;
        $("#" + subgrid_id).html("

");
        jQuery("#" + subgrid_table_id).jqGrid({
            url: "subgrid.php?q=2&id=" + row_id,
            datatype: "json",
            colNames: ['No', 'Item', 'Qty', 'Unit', 'Line Total'],
            colModel: [{
                name: "num",
                index: "num",
                width: 80,
                key: true
            }, {
                name: "item",
                index: "item",
                width: 130
            }, {
                name: "qty",
                index: "qty",
                width: 70,
                align: "right"
            }, {
                name: "unit",
                index: "unit",
                width: 70,
                align: "right"
            }, {
                name: "total",
                index: "total",
                width: 70,
                align: "right",
                sortable: false
            }],
            rowNum: 20,
            pager: pager_id,
            sortname: 'num',
            sortorder: "asc",
            height: '100%'
        });
        jQuery("#" + subgrid_table_id).jqGrid('navGrid', "#" + pager_id, {
            edit: false,
            add: false,
            del: false
        })
    }
});
jQuery("#sg1").jqGrid('navGrid', '#psg1', {
    add: false,
    edit: false,
    del: false
});

Sample list of list json as below
[{
    "id": "01",
    "name": "AA",
    "age": "29",
    "subData": [{
        "id": "01",
        "name": "AA",
        "age": "29"
    }, {
        "id": "02",
        "name": "BB",
        "age": "30"
    }, {
        "id": "03",
        "name": "CC",
        "age": "31"
    }, {
        "id": "04",
        "name": "DD",
        "age": "32"
    }]
}, {
    "id": "02",
    "name": "BB",
    "age": "30",
    "subData": [{
        "id": "01",
        "name": "AA",
        "age": "29"
    }, {
        "id": "02",
        "name": "BB",
        "age": "30"
    }, {
        "id": "03",
        "name": "CC",
        "age": "31"
    }, {
        "id": "04",
        "name": "DD",
        "age": "32"
    }]
}, {
    "id": "03",
    "name": "CC",
    "age": "31",
    "subData": [{
        "id": "01",
        "name": "AA",
        "age": "29"
    }, {
        "id": "02",
        "name": "BB",
        "age": "30"
    }, {
        "id": "03",
        "name": "CC",
        "age": "31"
    }, {
        "id": "04",
        "name": "DD",
        "age": "32"
    }]
}, {
    "id": "04",
    "name": "DD",
    "age": "32",
    "subData": [{
        "id": "01",
        "name": "AA",
        "age": "29"
    }, {
        "id": "02",
        "name": "BB",
        "age": "30"
    }, {
        "id": "03",
        "name": "CC",
        "age": "31"
    }, {
        "id": "04",
        "name": "DD",
        "age": "32"
    }]
}]

Jqgrid gave as url based fetch the data then how to put list of list to subgrid? please help me.....

A: There are different ways to implement your requirements. The answer for example describes how one can fill userdata inside of beforeProcessing based on subData part of every item. I would recommend you additionally to read the answer which seems could makes visualization of your data more comfortable for the user.


text:
Q: Wanted: Elegant validateUserInterfaceItem implementation for protocol composition I have an NSOutlineView with an underlying model composed of Nodes. These Nodes have many different capabilities built up with protocols.
EDIT -- to clarify, the capabilities described by each protocol are implemented as protocol defaults in extensions, so currently, subclasses are not having to contain any methods to conform to the protocol.
I have an NSMenu that contains actions that might be done on the Nodes in the view.
I would like to validate the menu items for the currently selected Node, but I can't think of a way to do it without writing one massive function on the base class.
The checks I need are not simply Protocol conformance - for example a Node that implements an Indentable protocol can not be indented in all circumstances. I need a canIndent() to complement the indent() method.
In C++, a long time ago, I implemented something similar by building a validation table as a static array on the base class. Subclasses registered their methods at startup. However, when using Swift I can't put expressions at the top level to do this cleanly, and there is no init code at the protocol level.
The only way I can think to do this at the moment is with a method on Node in this form:
func validAction(_ action: Selector) -> Bool
{
    switch(action)
    {
    case #selector(indent):
        if self is Indentable {
            return (self as! Indentable).canIndent

        ...

EDIT -- As Willeke has noted, I could write this on each subclass that conforms to a protocol, but that would involve a lot of repetition.
Ideally, I would build a method on Node of the form:
func validAction(_ action: Selector) -> Bool
{
    if self.responds(to: action) {
        return validations[action].valid
    }

    return false
}

Has anyone done this nicely!?
EDIT -- One idea might be to do something with the Selector description to build a validation Selector with a naming convention - e.g. indent() -> indentValid()


text:
Q: Segmentation fault on a dynamic programming program I'm trying to solve the problem of the cut-rod problem using recursion.
The problem is my program is giving a segmentation fault.
When running at gdb it gives me this error:
Program received signal SIGSEGV, Segmentation fault.
0x000055555555514f in cut_rod (
    array=<error reading variable: Cannot access memory at address 0x7fffff7fefd8>,
    n=<error reading variable: Cannot access memory at address 0x7fffff7fefd0>) at cut_rod_rec.c:18

What am I doing wrong?
#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
#include<limits.h>

typedef int32_t s32;

s32 max(s32 n1,s32 n2)
{
    return n1>n2?n1:n2;
}

s32 cut_rod(int *array,int *n)
{

    if(*n == 0)
    {
        return 0;
    }
    s32 q = INT_MIN;
    for(s32 i = 0;i<*n;i++)
    {
        q = max( q,array[i] + cut_rod(array,n-i )) ;
    }
    return q;
}

s32 main(void)
{
    s32 array[] = {1,5,8,9,10,17,17,20};
    s32 size = sizeof(array) / sizeof(array[0]);
    fprintf(stdout,"Valor máximo obtido é %d\n",cut_rod(&array[0],&size));
}

Link to the problem:
https://www.geeksforgeeks.org/cutting-a-rod-dp-13/

A: You have infinite recursion
s32 cut_rod(int* array, int* n)
{

    if (*n == 0)
    {
        return 0;
    }
    s32 q = INT_MIN;
    for (s32 i = 0; i < *n; i++)
    {
        q = max(q, array[i] + cut_rod(array, n - i)); <<<=======
    }
    return q;
}

when i is 0, first loop, you call cut_rod(array, n)
then when i is 0 you call cut_rod(array, n)
etc
forever
= stackoverflow


text:
Q: Problem while scrolling a JScrollPane - Threads The situation is like this:
Upon clicking on a menu item, some components are added to a JScrollPane, the components are resized, then setVisible method of JScrollPane is called. Resizing of components are out of my control. (TextAreas getting resized according to their contents. Caret updates are disabled.)
I want to scroll the JScrollPane to the bottom. Using invokeLater and a Runnable that scrolls the list down by using getMaximumValue method does not seem to work in this case (while it normally does for other parts of the program).
Is there a way to make the Runnable thread get notified after making sure that everything related to the operations above are done?
Thanks in advance.

A: Why are you doing that with another Thread?  Could you instead use
JViewPort view = new JViewPort();
view.setPoint(new Point(0, heightOfContents));
scrollPane.setViewPort(view);

That, or something similar should do what you need.

A: You colud try to create new thread and call dummy invokeAndWait on that thread. After that, all pending events should be finished and your scroll code should work.


text:
Q: Unresponsive Firefox
Possible Duplicate:
Firefox unresponsive - Lockfiles stuck

My firefox is unresponsive: it keeps coming up with a message that says

firefox is already running, but is not responding, to open a new window, you must first close the existing firefox process, or restart your system

now restarting the system doesn't work, does anyone know what else I can do?


text:
Q: Как найти ноль после точки и отсечь все лишнее в переменной? Есть переменная double в ней число допустим 8590.330123
Как найти ноль после точки и отсечь все лишнее ? чтобы было 8590.33

A: Если результат отсечения будет такой же double то ничего не получится...Ибо такова природа плавающей точки...где недавно был .30, никто не запретит поставить .29)... Подробнее о представлении плавающей точки и как ее сравнивать, можно почитать тут например http://www.ibm.com/developerworks/library/j-jtp0114/index.html ...
Как альтернативу плавающей точки можно предложить BigDecenal, там уже можно искать 0 и обрезать точность...
Если речь о текстовом представлении то тут все тривиально
    String numberAsString = Double.toString(number);
    int first0idx = numberAsString.indexOf('0',
    numberAsString.indexOf('.')+1);
    numberAsString = numberAsString.substring(0, first0idx)

писал с телефона, но концепция должна быть ясна
хотя честно говоря пока не ясно зачем так делать

A: Немного странный подход. Уточните задачу, на всякий. Есть опасения что вы выбрали не самое удачное для нее решение и просите подсказать его реализацию.
Если нужно именно то, о чем вы просите, то можно пойти в лоб:
public double cut(Double d){
    String s = String.valueOf(d);
    StringBuilder sb = new StringBuilder();
    int i = 0;
    //закидываем все до точки
    while(s.get(i) != '.' && i< s.length){
        sb.append(s.get(i++));
    }
    //закидываем точку
    sd.append(',');
    i++;
    //закидываем поле точки до нуля
    while(s.get(i) != '0' && i< s.length){
        sb.append(s.get(i++));
    }
    return Double.parse(sb.toString());
}

Даже идей нет как можно решить без представления в строке. Из-за особенностей битовой записи числа с плавающей точкой решусь предположить, что в общем случае это вообще нереально...

A: А почему не сгонять дабл в стринг? Найти требуемое регуляркой, и обратно конвернуть, если требуется? Регулярочка может выглядеть так "([0-9]*\.[0-9]*)0"
Мб лишний оверхед конечно, но коротко и элегантно в коде получится


text:
Q: How did Newton find the relationship between force, mass and acceleration? I have been told always that
$F$ is directly proportional to acceleration.
My question is that for finding such a relationship there should be source that produces desired force and in which the force can be adjusted i.e. Twice, thrice and more.
But the problem is initially before the discovery of laws of motion how can one say that a force is twice the other, how can he even judge the relationship between two forces without knowing the quantitative definition of force?

A:
how can he even judge the relationship between two forces without
  knowing the quantitative defination of force ??

One can't.  The concept "Force" is an abstraction from observation and must be well defined before quantitative relationships (once, twice, thrice, etc.) can be established.
But this was Newton's accomplishment, correctly recognizing and defining (net) force as that which acts to change an object's momentum (an abstraction which also must be correctly recognized and defined).


text:
Q: Soap confusion with maven I've done the following:

*

*Generated a SOAP request and received a response

*Added the jaxws-maven-plugin maven plugin - and generated some .class files in my target directory

So the question is what do I do next - I assume I somehow would like to bind my SOAPResponse to my .class files but I'm not sure what to do.
How does my java class access the .class files - it doesn't seem to know about them.

A: are you generating a server or a client?
What do you mean with 'generated a soap request and received a response'? To receive a response you have to send a request to some server, so apparently you are creating a client?
Supposing you have configured your pom to generate the sources for you in
${project.build.directory}/generated-sources/java/

then you should also include the maven add-source plugin to add the generated source directory to source directories as maven sees them at build time:
    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>1.7</version>
        <executions>
            <execution>
                <id>add-source</id>
                <phase>generate-sources</phase>
                <goals>
                    <goal>add-source</goal>
                </goals>
                <configuration>
                    <sources>
                        <source>${project.build.directory}/generated-sources/java/</source>
                    </sources>
                </configuration>
            </execution>
        </executions>
     </plugin>


text:
Q: Traversals through Tree.. In order problem with memory access violation So I wrote up this little peace of code as practice for myself...
But i am getting in travers_inorder function at line *traverse_inorder(p->left)*  memory access violation and program crashes.
Why???
Any ideas?
UPDATE: I am using visual studio 2008 SP1 an visual C++ compiler
#include <iostream>
#include <time.h>

using namespace std;

struct tree_node
{
tree_node *left;
tree_node *right;
int value;
};
void populate_rnd_tree(tree_node *root, int cnt);
void traverse_inorder(tree_node *p);

int main()
{
srand(time(NULL));
tree_node * nTmp = new tree_node;

populate_rnd_tree(nTmp, 10);

traverse_inorder(nTmp);

return 1;
}

void populate_rnd_tree(tree_node *root, int cnt)
{
tree_node *old = root, *left, *right;

left = new tree_node;
right = new tree_node;

int val = 0;
// exit condition
if (cnt == 0) return;

val = rand()%50;
old->value = val;
old->left = left;
old->right = right;

populate_rnd_tree(left, cnt-1);
populate_rnd_tree(right, cnt-1);

return;
}

void traverse_inorder(tree_node *p)
{
if (p != NULL)
{
    traverse_inorder(p->left);
    cout << p->value << endl;
    traverse_inorder(p->right);
}
}

A: My best guess: looks like you never actually set your final child nodes to NULL in your tree generation procedure.  As such, your conditional to stop traversing is never hit, as left and right are just uninitialized pointers.  In populate_rand_tree, do the following:
if (cnt == 0)
{
    old->left = NULL;
    old->right = NULL;
    return;
}

Alternatively, since you are using C++...
struct tree_node
{
    tree_node() : left(NULL), right(NULL) { }

    tree_node *left;
    tree_node *right;
    int val;
}


text:
Q: What does ring and cylinder symbol mean? I'm seeing an odd symbol in a schematic provided in a datasheet for the power management chip ADP5091: a ring that goes through a cylinder. The cylinder is connected to the inductor (SW pin) and the ring is connected to the low side transistor of the boost converter. I've tried googling this symbol but unfortunately I can't find anything. Could someone please help me out with this? Thanks in advance!

A: It looks like a current transformer. It would make a lot of sense if there was a current sensor of some type in the circuit. It monitors the current swing in the boost inductor, to switch off the low side FET when the inductor current exceeds some threshhold.
Whether it's a real current transformer (I'm not sure how they could integrate the magnetics in an IC) or an active device that behaves like one is another matter. There's no description of it in the data sheet. Hearth in comments suggests it could be a Hall sensor, which I think is probably more likely than a flux coupled transformer.


text:
Q: Hello,How can I run swagger editor on tomcat? I searched but I didn't find the good explanation.

A: Download swagger editor from: https://github.com/swagger-api/swagger-editor/releases/download/v2.10.4/swagger-editor.zip
Extract it as a webapp.
You can configure it with config/default.json


text:
Q: Training loss after last epoch differs from training loss (same data!) during evaluation I am building a deep convolutional model with a custom loss function. As a first step, I am trying to bring training loss down as far as possible to see if my model can overfit.
Training with on only one batch, the model can reduce the training loss to almost zero. But when I evaluate it on the same data it has been trained on, the loss is by magnitudes larger than even the test loss. It is even considerably larger than the loss for randomly generated predictions.
For training and evaluation I use the standard Keras model.fit and model.evaluate functions:
history = model.fit(x=training_batch_generator,
                epochs=500,
                validation_data=validation_batch_generator,
                callbacks = [stop_early, tensorboard, checkpoints])

training_loss = model.evaluate(x=yolo_training_batch_generator)

I use subclassed keras.utils.Sequence for the data:
class YoloSequence(Sequence):

def __init__(self, x_set, y_set, batch_size, grid_len):
    self.x, self.y = x_set, y_set
    self.batch_size = batch_size
    self.grid_len = grid_len

def __len__(self):
    return (np.ceil(len(self.x) / self.batch_size)).astype(np.int)

def __getitem__(self, idx):
    batch_x = self.x[idx * self.batch_size : (idx + 1) * self.batch_size]
    batch_y = self.y[idx * self.batch_size : (idx + 1) * self.batch_size]

    image_batch = [preprocess_image(path) for path in batch_x]
    label_batch = [preprocess_label(path, self.grid_len) for path in batch_y]

    return np.array(image_batch), np.array(label_batch)

And a custom loss function:
class YoloLoss(keras.losses.Loss):
def __init__(self, name="yolo_loss", **kwargs):
    super().__init__(name=name, **kwargs)

def call(self, y_true, y_pred):
    # shape of y_true: batch-size, GRID_SIZE, GRID_SIZE, 19
    # 19: [conf, x, y, w, h, 0, 0, 0, 0, 0, p[0], p[1], ..., p[8]]

    # get y_pred into same format as y_true:
    y_pred = tf.cast(K.reshape(y_pred, (-1, GRID_LEN, GRID_LEN, 19)), dtype=tf.float32)
    y_true = tf.cast(y_true, dtype=tf.float32)

    # compute ious (each iou of shape [1, batchsize, gridsize, gridsize, 1], one iou for each cell):
    iou_bb1 = K.expand_dims(self.compute_iou(y_pred[..., 1:5], y_true[..., 1:5]), axis=0)
    iou_bb2 = K.expand_dims(self.compute_iou(y_pred[..., 6:10], y_true[..., 1:5]), axis=0)

    ious = K.concatenate([iou_bb1, iou_bb2], axis=0) # shape:  [2, batchsize, gridsize, gridsize, 1]

    # bestbox: box that is responsible for a given cell [batchsize, gridsize, gridsize, 1]:
    bestbox = K.cast(K.argmax(ious, axis=0), dtype=tf.float32)

    # exists_box: for each cell in every batch, does there exist a box? shape: [batchsize, gridsize, gridsize, 1]
    exists_box = K.expand_dims(y_true[..., 0], axis=3)

    ################
    ### box loss ###
    ################
    # if a box exists, use predictions of best box:
    xy_pred = (bestbox * y_pred[..., 6:8]) + ((1 - bestbox) * y_pred[..., 1:3])
    box_predictions_xy = (exists_box * xy_pred)
    box_targets_xy = (exists_box * y_true[..., 1:3])

    # square-root of width and height(same change is less important in larger box):
    wh_pred = ((bestbox * y_pred[..., 8:10]) + (1 - bestbox) * y_pred[..., 3:5])
    box_predictions_wh = (K.sign(exists_box * wh_pred) * K.sqrt(K.abs(exists_box * wh_pred)+ 1e-6)) # derivative of squareroot as you go to zero: infinity, so add 1e-6 for numerical stability
    box_targets_wh = (K.sqrt(exists_box * y_true[..., 3:5]))

    mse = tf.keras.losses.MeanSquaredError(reduction=tf.keras.losses.Reduction.SUM)
    box_loss = mse(box_predictions_xy, box_targets_xy) + mse(box_predictions_wh, box_targets_wh)

    ###################
    ### object loss ###
    ###################
    confidence = (bestbox * y_pred[..., 5:6]) + ((1 - bestbox) * y_pred[..., 0:1])
    best_ious = tf.where(
        K.cast(bestbox, tf.bool),
        K.reshape(iou_bb2, (-1, GRID_LEN, GRID_LEN, 1)),
        K.reshape(iou_bb1, (-1, GRID_LEN, GRID_LEN, 1))
    )
    object_loss = mse((exists_box * confidence), (best_ious * y_true[..., 0:1]))

    ######################
    ### no object loss ###
    ######################
    no_object_loss = mse(((1 - exists_box) * confidence), ((1 - exists_box) * y_true[..., 0:1])) # second term is all zeros

    ##################
    ### class loss ###
    ##################
    class_loss = mse((exists_box * y_pred[..., 10:]), (exists_box * y_pred[..., 10:]))

    ##################
    ### total loss ###
    ##################
    lambda_coord = 5
    lambda_noobj = 0.5
    loss = (
        lambda_coord * box_loss
        + object_loss
        + lambda_noobj * no_object_loss
        + class_loss
    )

    return loss

A: In comments, OP writes that the network uses batch-normalization. This explains the observed behavior, because  neural networks with batch norm change how statistics are computed, depending on whether the network is in training mode or evaluation mode.
During training, batch norm updates a running estimate of the mean and standard deviation of the inputs. When computing results outside of training (e.g. when applied validation or production data), these values are not changed by the input, so there will be a different result.

*

*In Keras, this behavior is exposed as the difference between model.fit(), model.evaluate() and model.predict(). See: https://stackoverflow.com/questions/44843581/what-is-the-difference-between-model-fit-an-model-evaluate-in-keras

*In pytorch, you can set this behavior using model.train() to set train mode, or model.eval() to set evaluation mode (colloquially "eval mode"). See: https://stackoverflow.com/questions/60018578/what-does-model-eval-do-in-pytorch
More information can be found in Ioffe, Sergey, and Christian Szegedy. "Batch normalization: Accelerating deep network training by reducing internal covariate shift." International conference on machine learning. PMLR, 2015.


text:
Q: Tablekit: sortable not working if table rows are loaded with ajax I saw this topic before here, but it didnt solve my problem.
I have a table that looks like this in html;

            Order

        <?php //data generated by ajax ?>

On page load, the rows are loaded into tbody via ajax.
The problem is, tablekit's sorting doesn't work from there (only works if i output the rows from php).
I tried adding setTimeout() in ajax success, reinitialize the table with
TableKit.Sortable.init('tablekit-table-1')

etc, nothing helped. Googled alot aswell. Thanks in advance.

A: I have the same problem. The solution I find out is using the Tablekit.Sortable.init(id) onSuccess.
But still I have another problem: it only worked on the first call, so I put a different id for every table I'm calling, and initializing the Sortable on this new ids.


text:
Q: How to show that $e^x$ is differentiable? I tried to search for a few minutes but I didn't find this question so I hope it's not a duplicate.
So I want to show that $(e^x)' = e^x$. To do that, I must proof that the limit:
$$\lim_{h\to0}\frac{f(x+h) - f(x)}{h} = \lim_{h\to0}\frac{e^{x+h} - e^x}{h}$$
exists and equals to $e^x$.
So I have:
$$\frac{e^{x+h} - e^x}{h} = \frac{e^x \cdot e^h - e^x}{h} = e^x \bigg(\frac{e^h - 1}{h}\bigg) \\ e^h - 1 = z \implies e^h = 1+z >0 \implies h = \ln(1+z)$$
Because of the continuity of the $\ln$ and $e^x$ functions, we have:
$$h\to 0 \iff e^h \to 1 \implies z\to0 \\
z > 0 \implies \frac{1}{z} \to +\infty \\
z < 0 \implies \frac{1}{z} \to -\infty \\
\frac{e^h - 1}{h} = \frac{z}{\ln(1+z)} = \frac{1}{\frac{1}{z}\ln(1+z)} = \bigg[ y = \frac{1}{z} \bigg] =  \frac{1}{y\ln(1+\frac{1}{y})} = \frac{1}{\ln(1+\frac{1}{y})^y} \\
h \to 0 \implies |y| \to +\infty \implies \bigg(1+\frac{1}{y}\bigg)^y \to e \implies \\
\lim_{h\to0}\frac{e^h - 1}{h} = \frac{1}{\ln e} = 1
\implies (e^x)' = e^x \cdot 1 = e^x$$
But how do I prove that $\lim_{\pm\infty}(1 + \frac{1}{x})^x = e$ ?
We defined $e$ like this:
$$\lim_{n\to\infty} \bigg(1 + \frac{1}{n}\bigg)^n = e \space \,, \space n\in\mathbb{N}$$
I thought of the sandwich theorem:
$\forall x \geq 1 \,, x\in\mathbb{R} \,, \lfloor x \rfloor \leq x < \lfloor x \rfloor + 1$ and $\lfloor x \rfloor , \lfloor x \rfloor + 1 \in \mathbb{N} $ and if I denote $\mathbb{N} \ni n = \lfloor x \rfloor$ I have:
$$ \bigg(1 + \frac{1}{n+1}\bigg)^n \leq  \bigg(1 + \frac{1}{x}\bigg)^x \leq \bigg(1 + \frac{1}{n}\bigg)^{n+1} \\
 \lim_{n\to+\infty}\bigg(1 + \frac{1}{n+1}\bigg)^n = \frac{\lim_{n\to+\infty}\bigg(1 + \frac{1}{n+1}\bigg)^{n+1}}{\lim_{n\to+\infty}\bigg(1 + \frac{1}{n+1}\bigg)} = \frac{e}{1+0} = e \\
 \lim_{n\to+\infty}\bigg(1 + \frac{1}{n}\bigg)^{n+1} =  \lim_{n\to+\infty}\bigg(1 + \frac{1}{n}\bigg)^n \cdot \lim_{n\to+\infty}\bigg(1 + \frac{1}{n}\bigg) = e \cdot (1 + 0) = e$$
and now I could apply the theorem but then again, how do I show that this: $\bigg(1 + \frac{1}{n+1}\bigg)^n \leq  \bigg(1 + \frac{1}{x}\bigg)^x \leq \bigg(1 + \frac{1}{n}\bigg)^{n+1}$ is true? I mean, I can say that (left side):
$$ n+1 > x \implies \frac{1}{n+1} < \frac{1}{x} \implies 1 + \frac{1}{n+1} < 1 + \frac{1}{x} \\
\forall y\in\mathbb{R_+} \space n \leq x \implies y^n \leq y^x \\
\implies \bigg(1 + \frac{1}{n+1}\bigg)^n \leq  \bigg(1 + \frac{1}{x}\bigg)^x$$
and by analogy the right side but is this a proof in terms of limits?
and that's just $+\infty$ for $x \geq 1$, what do I do for $-\infty$ ?
For $x\in\langle 0, 1\rangle$, a substitution $y = \frac{1}{x}$ gives me:
$$\lim_{y\to 0}\bigg(1 + y\bigg)^\frac{1}{y}$$
I'll stop here to see if I'm on the right track, any hints, suggestions, edits, comments and answers are welcome!

A: We will use the basic derivative definition: $$\lim_{h\to0}\frac{f(x+h) - f(x)}{h} = \lim_{h\to0}\frac{e^{x+h} - e^x}{h}.$$
After some algebraic manipulations you will find that it is equal to: $$e^x\cdot\color{blue}{\lim_{h\to0}\frac{e^h-1}h}.$$
Here's a proof that $\color{blue}{\rm this\, term}$ is equal to one, hence $(e^x)'=e^x$, taken from proofWiki:
$$\eqalign{
\frac{e^ h - 1} h&=
\frac{\lim\limits_{n \to \infty} \left({1 + \dfrac h n}\right)^n - 1} h \\
&= \frac{\displaystyle \lim_{n \to \infty} \sum_{k \mathop = 0}^n {n \choose k} \left({\frac h n}\right)^k - 1} h\\
&= \lim_{n \to \infty} \frac{\displaystyle \sum_{k \mathop = 0}^n {n \choose k} \left({\frac h n}\right)^k - 1} h\\
&= \lim_{n \to \infty} \left({ {n \choose 0} 1 - 1 + {n \choose 1} \left({\frac h n}\right)\frac 1 h + \sum_{k \mathop = 2}^n {n \choose k} \left({\frac h n}\right)^k \frac 1 h }\right)\\
&=\lim_{n \to \infty}1 + \lim_{n \to \infty} \sum_{k \mathop = 2}^n {n \choose k} \frac {h^{k-1} }{n^k}\\
&=1 + h \lim_{n \to \infty} \sum_{k \mathop = 2}^n {n \choose k} \frac{h^{k-2} } {n^k}.\\
}$$
The right summand converges to zero as $h\to0$, and so:
$$\lim_{h\to0}\frac{e^h-1}h=1.$$


text:
Q: JS/jquery updating numbers in HTML turns into NaN on mobile I have a made a little page for my fantasy football league:
http://www.legendary.no/gamecenter
It simply loads html from nfl.com, and updates the scores every 60 seconds. (I've set it to 6 seconds for testing purposes)
Works great on desktop, but on my iPhone, both in Safari and Chrome, when 6 seconds pass and it updates the numbers, they all turn into a NaN instead.
Anybody know what's wrong here, why it works fine in chrome and safari on desktop, but on mobile it doesn't?
Edit: This is the script from the page:

       $("#hide").load("http://fantasy.nfl.com/league/1444853/team/1/gamecenter?week=14 #teamMatchupNav");
       window.setInterval(function() {
         for (i = 1; i < 11; i++) {
           newScore = parseInt($(".teamTotal.teamId-" + [i]).text(), 10);
           oldScore = parseInt($("span.team" + [i]).text(), 10);
           $('span.team' + [i]).text(newScore);
           if (newScore > oldScore) {
             $('li.team' + [i]).removeClass("up down none").addClass("up");
           } else if (newScore < oldScore) {
             $('li.team' + [i]).removeClass("up down none").addClass("down");
           } else {
             $('li.team' + [i]).removeClass("up down none").addClass("none");
           }
         }

         function sortEm(a, b) {
           return parseInt($('.teamscore', a).text()) < parseInt($('.teamscore', b).text()) ? 1 : -1;
         }
         $('.semi1').sort(sortEm).prependTo($('ul#Semi1'));
         $('.semi2').sort(sortEm).prependTo($('ul#Semi2'));
         $('.semi3').sort(sortEm).prependTo($('ul#Semi3'));
         $('.semi4').sort(sortEm).prependTo($('ul#Semi4'));
         $('.semi5').sort(sortEm).prependTo($('ul#Semi5'));
       }, 6000);

And a code example:

Thomas

    0

Jonas

    0


text:
Q: intel++: warning #1563: taking the address of a temporary - false positive? I got this class:
class myClass
{
private:
      struct tm minDate, maxDate;
public:
      myClass();

      struct tm GetMinDate()  {return minDate;};
      struct tm GetMaxDate()  {return maxDate;};
};

and this function call
SetMinMaxDate(struct tm *MinDate, struct tm *MaxDate);

the follwing code
myClass myInstance;
SetMinMaxDate(&myInstance.GetMinDate(), &myInstance.GetMaxDate());

Works well and with MSVC 2010 and 2005 no warnings are generated. But if i compile it with intel C++ i get the warning
warning #1563: taking the address of a temporary

According to this related thread

The lifetime of the temporary object (also known as an rvalue) is tied
  to the expression and the destructor for the temporary object is
  called at the end of the full expression

SetMinMaxDate copies the content passed with pointers. The pointer itself is not stored.
So the 2 temporary tm elements should be valid until SetMinMaxDate has returned.
Is there a problem in this code or is this a false positive of intel C++?
EDIT:
I found another very interesting post that gives a reason for this behavior:
Why is it illegal to take the address of an rvalue temporary?

A: It is a valid warning because SetMinMaxDate() makes no guarantees that it will not store that pointer for later use.  And since you are passing a pointer to a temporary, if SetMinMaxDate stored it for later use, it would be a problem.
Another reason for the warning is that with the declaration you have, maybe SetMinMaxDate is modifying the tm structs passed in via pointer and such modifications would get lost since it is a pointer to a temp object.
SetMinMaxDate would be better declared as:
SetMinMaxDate(const struct tm & MinDate, const struct tm & MaxDate);

there would be no warning in this case.  The const lets the compiler know it will not be modifying the object and the & indicates that it is unlikely to be trying to store the address for later.

A: Per paragraph 5.3.1/3 of the C++11 Standard:

The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id. [...]

Not only the warning is appropriate, I am rather wondering why it is not an error. Your program  is ill-formed, since temporaries are not lvalues. Probably, MSVC supports this as a compiler extension - but the value of this extension is rather arguable.

A: myClass myInstance;
{
struct tm a,b;
a = myInstance.GetMinDate();
b = myInstance.GetMaxDate();
SetMinMaxDate(&a, &b);
}

how you should implement it.
According to my gray rememberings you may not get the address of an rvalue - that is what you do.
So short: Intel C is right

A: Q: Is there a problem in this code or is this a false positive of intel C++?
A: I see this a problem in this code.
The function GetMinDate() returns a value which, theoretically, could be stored in a processor register(s).  Thus it has no address.  Most compilers will store the return value in a temporary whose lifetime is fleeting.  So far, no problem.
 struct tm GetMinDate()  {return minDate;};

Later you reference the "address" of this result in
... &myInstance.GetMinDate() ...

Now you have a problem.  The address of the temporary could quickly be used by another operation like the result of myInstance.Get*Max*Date().
@drahnr recommended implementation is a good solution.
Another, but poor approach as struct tm is large, would be to pass the parameters to SetMinMaxDate() as values
SetMinMaxDate(struct tm MinDate, struct tm MaxDate);


text:
Q: AJAX call updates data attribute, but reading attribute returns pre-AJAX value I have an AJAX call that successfully updates the data-attribute of a div. However, when I read the data-attribute using
matchupid = $('#matchupID').data('matchupid')

after an AJAX update (which successfully changes the attribute when I inspect the element using DevTools), it returns the original matchupID, instead of the new ID input by the AJAX call. Any idea why this would be happening? Thanks!
EDIT:
I think I fixed it. I was updating the data using
.attr('data-matchupID', $('#matchupID').data('matchupid'))

and reading the data using
.data('matchupID')

Should that make a difference?


text:
Q: Unable to create a form for Order and Contact I have created a visualforce page and apex controller for an order from. When the user enters his details and click on submit, the code will check if a contact with those details exist in the org. If the contact is already there, the order will be associated with that user or else a new contact will be created. However, when the user is clicking submit, I am getting an error. Here is the code I have:
<apex:page standardController="Online_Orders__c" extensions="OnlineOrders" sidebar="false" showHeader="false">

    <apex:pageMessages ></apex:pageMessages>
    <apex:form id="theForm">
     <apex:panelGrid columns="2" id="theGrid" width="40%" cellspacing="10px">

         <apex:outputText value="First Name" id="first"/>
         <apex:inputText id="firstname" value="{!firstName}"/>
         <apex:outputText value="Last Name" id="last"/>
         <apex:inputText id="lastname" value="{!Lastname}"/>
            <apex:outputText value="Email" id="email"/>
         <apex:inputText id="emailfield" value="{!email}"/>
         <apex:outputText value="Program Type" id="Program_Type"/>
         <apex:inputField id="ProgramType" value="{!onlineOrder.Program_Type__c}"/>
         <apex:outputText value="Price" id="price"/>
         <apex:outputPanel id="out">
          <apex:outputField id="Onlineprice" value="{!onlineOrder.Price__c}"/>
            </apex:outputPanel>
          <apex:outputText value="Promo Code" id="promo"/>
         <apex:outputPanel id="out1">
          <apex:inputField id="promocode" value="{!onlineOrder.Promo_Code__c}"/>
          <button type="button" onclick="checkPromo()">Apply PromoCode</button>
         </apex:outputPanel>
         <apex:actionFunction name="checkPromo" action="{!checkPromo}" rerender="out"/>
         <apex:outputPanel id="out3">
          <button type="button" onclick="validatedetails()" style="padding: 4px;">Proceed</button>
          <apex:commandButton action="{!cancel}" value="cancel"/>
         </apex:outputPanel>

     </apex:panelGrid>
        <apex:actionFunction name="submitForm" action="{!submit}"  rerender="out"/>
    </apex:form>
</apex:page>

The apex Controller is:
public class OnlineOrders
{
    public Online_Orders__c onlineOrder {get;set;}
    public String firstName {get;set;}
    public String Lastname {get;set;}
    public String email {get;set;}

    public OnlineOrders(ApexPages.StandardController controller)
    {
        onlineOrder=new Online_Orders__c();
    }
    public Pagereference cancel()
    {
        return null;
    }
    public Pagereference submit()
    {
        List<Contact> contactlist=[select id from Contact where firstname=:firstname and lastname=:Lastname and email=:email];
        if(contactlist.size()>0){
         onlineOrder.Contact__c=contactlist[0].id;
        }else{
            Contact con=new Contact(firstname=firstname,lastname=lastname,email=email);
            insert con;
            onlineOrder.Contact__c=con.id;
        }
        insert onlineOrder;
        return null;
    }
    public void checkPromo()
    {
        if(onlineOrder.Promo_Code__c=='Promocode1')
        {
            system.debug('###650###'+onlineOrder.Price__c);
            onlineOrder.Price__c=650;
        }
        else
        {
            system.debug('###750###'+onlineOrder.Price__c);
            onlineOrder.Price__c=750;        }
    }

}

Even though the test user is entering the first and last name, I am still getting the below error

Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [First Name, Last Name]: [First Name, Last Name]
  Error is in expression '{!submit}' in page onlineorders: Class.OnlineOrders.submit: line 26, column 1

What am I doing wrong here?


text:
Q: How to put element on top of all other elements withouth using explicit number for z-index? I have an element E which works as a pop-up windows. When I open this windows I want it to be displayed on top of everything else. E.g. if there are multiple pop-up windows open, my particular element E should be on top of everything else.
I'm familiar with the z-index but this approach sounds very buggy. If someone else uses a higher z-index my pop up windows will vanish in the background.
How can I prevent this from happening? Is there an attribute which declares an element to be always on top?


text:
Q: Should symlinked programs be put on drives with fast write speeds? When deciding where to symlink-move a program, should it be to a drive that has a fast write speed, in lieu of program's needing to cache/write to disk? OR, if/when a program needs to cache to disk, will it always use the main system (Windows) pagefile?
NOTES
I've been symlinking program folders off my SSD and onto my external to make space on my nearly full SSD. I realized that the write speed of this external drive is pretty slow. Other than the initial symlink-transfer to the drive, would I need to worry about moved programs having to cache/write to this slow external? Or do programs stick to writing to the main system pagefile (or Windows AppData folders, etc)?

A: A well written program generally won't be writing to its Program Files folder unless you're upgrading / reinstalling. Most programs do their writing to/from various folders in the user's home directory (My Documents, AppData, Temp, etc.). The paging file is wherever you have it configured in windows, and generally applications don't have much control over that.


text:
Q: How can one type access a private setter of another type's property? All I need is a way to make a property of one class only 'settable' from one other class (a sort of manager class).
Is this even possible in c#?
My colleague 'reliably' informs me that I have a design flaw, but I feel I should at least ask the community before I concede defeat!

A: No, it's not really possible to do this in any clean way in C#.  You probably have a design flaw ;-)

A: You can use the internal modifier, which lets all types in the same assembly access the data (or nominated assemblies if using [InternalsVisibleTo] - but no: there is no friend equivalent in C#.
For example:
public string Foo {get; internal set;}

A: You have a design flaw.  Also, don't be paranoid about data hiding.  Here's 3.5's way to do it:
class Program
    {
        static void Main(string[] args)
        {
            Managed m = new Managed();
            Console.WriteLine(m.PrivateSetter);
            m.Mgr.SetProperty("lol");
            Console.WriteLine(m.PrivateSetter);
            Console.Read();
        }
    }

    public class Managed
    {
        private Manager _mgr;
        public Manager Mgr
        {
            get { return _mgr ?? (_mgr = new Manager(s => PrivateSetter = s)); }
        }
        public string PrivateSetter { get; private set; }
        public Managed()
        {
            PrivateSetter = "Unset";
        }
    }

    public class Manager
    {
        private Action<string> _setPrivateProperty;
        public Manager(Action<string> setter)
        {
            _setPrivateProperty = setter;
        }
        public void SetProperty(string value)
        {
            _setPrivateProperty(value);
        }
    }

Here's how we'd do it in pre-lambda days:
public class Managed
{
    private Manager _mgr;
    public Manager Mgr
    {
        get { return _mgr ?? (_mgr = new Manager(this)); }
    }
    public string PrivateSetter { get; private set; }
    public Managed()
    {
        PrivateSetter = "Unset";
    }
    public class Manager
    {
        public void SetProperty(string value)
        {
            m.PrivateSetter = value;
        }
        private Managed m;
        public Manager(Managed man)
        {
            m = man;
        }
    }
}

A: The best way to do it would be:
/// <summary>
/// Gets or sets foo
/// <b>Setter should only be invoked by SomeClass</b>
/// </summary>
public Object Foo
{
    get { return foo; }
    set { foo = value; }
}

When you have some complex access or inheritance restriction, and enforcing it demands too much complexity in the code, sometimes the best way to do it is just properly commenting it.
Note however that you cannot rely on this if this restriction has some security implications, as you are depending on the goodwill of the developer that will use this code.

A: You cannot do that on that way, but you can access a property's setter method from a derived class, so you can use inheritance for the purpose. All you have to do is to place protected access modifier. If you try to do so, your colleague is right :). You can try doing it like this:
public string Name
{
    get{ return _name; }
    protected set { _name = value; }
}

keep in mind that the set method of the property is only accessible from the derived class.

A: Or you could have these two classes in an assembly alone and have the setter as internal. I would vote up for the design flaw though, unless the previous answer by milot (inheriting and protected) makes sense.

A: You could do:
public void setMyProperty(int value, Object caller)
{
    if(caller is MyManagerClass)
    {
        MyProperty = value;
    }
}

This would mean that you could use a 'this' pointer from the calling class. I would question the logic of what you're attempting to achieve, but without knowing the scenario I can't advise any futher. What I will say is this: if it is possible to refactor your code to make it clearer, then it is often worthwhile doing so.
But this is pretty messy and certinly NOT fool-proof ... you have been warned!
Alternativly...
You could pass a delegate from the Class with the Property (Class A) to the Manager Class (Class B). The delegate can refer to a private function within A to allow B to call that delegate as any normal function. This precludes that A knows about B and potentially that A is created before B. Again... messy and not fool-proof!

A: You can achieve to this by making a Public property in your "settable class" that will inherit from the real class that will have a protected property... this way only the inherit class can SET and not class that doesn't inherit. But the drawback is that you will require to have an inherit class...

A: Reflection, though I would agree that having to do this just to get around an access modifier is probably an indication of a bad design.
public class Widget
{
   private int count;
   public int Count
   {
      get { return this.count; }
      private set { this.count = value; }
   }
}

public static class WidgetManager
{
    public static void CatastrophicErrorResetWidgetCount( Widget widget )
    {
       Type type = widget.GetType();
       PropertyInfo info = type.GetProperty("Count",BindingFlags.Instance|BindingFlags.NonPublic);
       info.SetValue(widget,0,null);
    }
}

A: The reason this is a design flaw is because it seems muddled between the scope of the two objects.
The properties of a class should be accessible in the context of that class, at least internally.
It sounds like the settable property on your item class is really a property of the manager class.
You could do something similar to what you want by closely coupling the two classes:
public class MyItem {

    internal MyItemManager manager { get;set; }

    public string Property1 {
        get { return manager.GetPropertyForItem( this ); }
    }
}

Unfortunately this isn't great design either.

A: What your looking for is what C++ calls a Friend class but neither c# or vb has this functionality.  There is a lot of debate as to the merit of such functionality since it almost encourages very strong coupling between classes. The only way you could implement this in c# would be with reflection.

A: If your goal is to have a class Foo let some property (e.g. Bar, of type Biz) to be changed by some other object, without exposing it publicly, a simple way to do that is to have an instance of Foo which is supposed to be changeable by some other object to pass that other object an Action<Biz> which points to a private method that changes Bar to the passed-in value.  The other object may use that delegate to change the Bar value of the object that supplied it.
If one wishes to have give all instances of some type Woozle the ability to set the Bar value of any instance of Foo, rather than exposing such abilities on a per-instance basis, one may require that Woozle have a public static method Woozle.InstallFooBarSetter which takes a parameter of type Action<Foo, Biz> and one of type Object.  Foo should then have a static method WoozleRequestBarSetter which takes an Object, and passes it to Woozle.InstallFooBarSetter along with an Action<Foo,Biz>.  The class initializer for Woozle should generate a new Object, and pass it to Foo.RequestBarSetter; that will pass the object to Woozle.InstallFooBarSetter along with a delegate.  Woozle can then confirm that the passed-in object is the one that it generated, and--if so--install the appropriate delegate.  Doing things this way will ensure that nobody but Woozle can get the delegate (since the delegate is only passed to Woozle.InstallFooBarSetter), and Woozle can be sure its delegate comes from Foo (since nobody else would have access to the object that Woozle created, and Woozle.InstallFooBarSetter won't do anything without it).

A: if it is a design flaw depends on what you want to do. You could use the StackTrace class from System.Diagnostics to get the Type of the class setting your property and then compare to the type you want to allow setting yor property..but maybe there are better ways for performing something like this (e.g. boxing)


text:
Q: Rhythmbox is invisible I tried various solutions for fixing "No Sound" problem under the Ubuntu 13.04, which got me to an odd situation in which the music or any sound plays but the Rhythmbox is neither visible at the top status bar nor anywhere on the desktop screen.
Though it is visible in the system monitor but is not accessible to bring out the GUI of the player to operate upon.
 What should I do?

No, sudo apt-get install --reinstall rhythmbox did not work.
Can someone suggest any other solution, Rhythmbox is still invisible but the music is playing fine.

A: open your terminal and do this .
sudo apt-get install --reinstall rhythmbox

that will bring it back.