text:
Q: Some MySQL queries don't take effect I've written a python script that adds student data (name and classes) to a table one at a time. The table is structured so that there is a primary key column, a student name column, and then a column for each class. The script checks to see if the class it's adding already exists as a column, and if not it creates it. Then it writes 'true' under that column for the current student.
Here's my problem: from the log file I can see that every single query is sent to the database correctly, but some don't show up in the table. When I run these queries:
CREATE TABLE Students (idStudents INT NOT NULL, Name VARCHAR(255) NOT NULL, PRIMARY KEY (idStudents)) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8
SET NAMES 'utf8'
INSERT INTO Students (idStudents, Name) VALUES ('1', 'Bror Tao Sjørslev Bojlen')
SELECT column_name FROM information_schema.columns WHERE table_name='Students'
ALTER TABLE Students ADD 3ubmSL5 VARCHAR(20)
UPDATE Students SET 3ubmSL5='true' WHERE idStudents='1'
ALTER TABLE Students ADD 3uchSL3 VARCHAR(20)
UPDATE Students SET 3uchSL3='true' WHERE idStudents='1'
ALTER TABLE Students ADD 3udaBH3 VARCHAR(20)
UPDATE Students SET 3udaBH3='true' WHERE idStudents='1'
ALTER TABLE Students ADD 3uenA1H1 VARCHAR(20)
UPDATE Students SET 3uenA1H1='true' WHERE idStudents='1'
ALTER TABLE Students ADD 3umaHL4 VARCHAR(20)
UPDATE Students SET 3umaHL4='true' WHERE idStudents='1'
ALTER TABLE Students ADD 3uphH2 VARCHAR(20)
UPDATE Students SET 3uphH2='true' WHERE idStudents='1'
ALTER TABLE Students ADD 3uth1 VARCHAR(20)
UPDATE Students SET 3uth1='true' WHERE idStudents='1'

the table looks like this.
That is, the final query
UPDATE Students SET 3uth1='true' WHERE idStudents='1'

doesn't go through.
I hope this makes sense, and someone can shed some light on this issue - it's driving me crazy.

A: I suspect the final statement is being rolled back.  I'm guessing that your client is wrapping the statements implicitly in a transaction.  I have seen specifically Navicat roll back transactions containing inserts or updates that aren't explicitly committed unless they are accompanied by another statement.  It's odd behavior, but I've watched it through a trace.
As an aside, your table design is rather unconventional.  Students and classes are distinct entities and should not be stored in the same table.  You are combining at least three different tables here; this will not scale well.
EDIT:
In fact, the first question I posted here involved this issue:
Unable to insert record from stored procedure called from web service
I just remembered that. :)

A: Could it be a problem with commiting updates to the database? I seem to recall that a couple of databases I've used have commited the changes from the previous query either when there's an explicit COMMIT or when you make a new query, so in this case, the final update wouldn't be commited when the script terminated, and the changes would be rolled back.


text:
Q: automapper works fine in debug mode but throws mappingexception in release mode Automapper is a good tool. But i have some problems .
While debugging the project it works fine , all mapping operations are succeded. But in release mode it throws mappingexception with exactly the same data.
What can be the problem ?
my environment is Win7 , 32 bit, VS 2010 .  projects works on .net 4.0 profile.
 Mapper.CreateMap<V_Person_Details,Person>();
 Mapper.Map(curr_V_Person, cur_Person); /// exception throws here in just release mode , not in debug mode
   ///Trying to map System.String to System.nullable .... Destination property  SSS_ID : exception of the Automapper.AutomapperMappingException was thrown.

 ....

A: Run the Mapper.AssertConfigurationIsValid() method in debug mode to verify that you don't have any configuration errors that is only showing up in release mode.

A: We had the same Issue.
By us the problem was a another version of AutoMapper dll on our Server(Release).

redpajama_set_name: RedPajamaStackExchange


text: Q: Create text tattoo in Gimp Is there a way to append a tattoo on somebody's arm in Gimp? The tattoo will not be an image but writing from a text tool with some nice font (or another fast way). So, I need to create a fitting effect from this writing. I already found how to do a tattoo from images but it would be slow for me to create an image from every writing. I need to do many fitting writings like in memento movie.


text:
Q: How to create Android App which work online as well as offline? I want to create one app which should work online as well as offline. If internet connectivity is there it should use otherwise use the history.
I am confused about some possibilities, like this:
How to manage the physical resources like a images, video etc..
How to update the local database according to the webservice?
How to get new physical resources from net when local database update?
About this I do some work which explain below.
I get the all database of webserver and dump in to the sqlite and store in system folder.
I get the all resources like a images and font and video store in system folder like a drawable and assest and raw folder.
My main problem is there when any update in webservice then how I can update the local resources.
One big problem is physical resources how I can manage and get this and store in local?
Please give some ideas i am stuck
thanks in advance

A: For the first start app without network you can put resources into assets folder. Then on the server you can store version of each category of data and increase it when data changed. In the app you can download all resources on the SD card and read it from there until version of data changed. If version of some category increased you update it during app starts and if you want to update data during app works you can use Service which ckecks for updates (every period of time). You can work without database just save your xml (json) and images in special hidden folder.

A: IMHO - If you are going to have lot of data and varies everytime, then you might need to go with the database that way you have lot of control to store and retrieve the data you need. You can store and retrieve the images in the database itself. Basically, you have to check whether he has access to internet, if not, then take the data from the database and present it to the user. As you are going to use Web services, I would say Database is a good option to think before you start implementing.
Note: You can purge the old data in the database whenever no longer needed. Anyone can accidentally delete your data from your sd card, but with the database, users may not be ...


text:
Q: What "linguistic and philosophical problems" might be inherent in trigonometry? In "A Mathematician's Lament", Paul Lockhart derides the "status quo" of math education, claiming that "mathematics is an art form done by human beings for pleasure" but instead is taught "devoid of creative expression of any kind". His writing is provocative, and I'm sure his accusations and suggestions could spark lively debate wherever they might circulate. I'm also sure such debate would be against the rules of this site…
My question is not about the essay's arguments per se, but rather what Lockhart might be referring to near the end of his essay, as he criticizes a typical trigonometry class wherein:

The measurement of triangles will be discussed without mention of the transcendental nature of the trigonometric functions, or the consequent linguistic and philosophical problems inherent in making such measurements.

This topic seems like it'd be interesting to learn more about — but what is he alluding to here? What "linguistic and philosophical problems" would he claim come about in trigonometry? Are they inherent in "triangle measurement" itself, or do they come about more specifically with the use of transcendental functions?

A: Here's my own best guess, even though the grammar Lockhart uses seems to most simply reduce to:

The measurement of triangles will be discussed without … [mentioning] the consequent linguistic and philosophical problems inherent in making such measurements.

My guess is that he really means something more like:

[Trigonometry] will be discussed without mention of the transcendental nature of the trigonometric functions, or the consequent linguistic and philosophical problems inherent in [that class of functions].

Lockhart places a significant emphasis on the history of mathematics in his essay. For just one example (the stem "histor" appears eighteen times in his paper!), he asserts:

Technique in mathematics, as in any art, should be learned in context.
  The great problems, their history, the creative process— that is the proper setting

So I looked a bit into the history of transcendental functions. They were first defined by Euler, who also had a major influence over our conception of functions in general. I found one page on The function concept to be particularly relevant. I'll isolate one particular thread, which runs through several paragraphs in the original:

[I]n 1748 the concept of a function leapt to prominence in mathematics … due to Euler[, who] divides his functions into different types such as algebraic and transcendental. … However there was a difficulty in Euler's work which was to lead to confusion, for he failed to distinguish between a function and its representation.

There's whiffs of philosophy and linguistics already in this summary ("concept", "types", "representation"), which might come through more strongly in the original sources and books cited. Perhaps the "problems inherent" are semantic, e.g. what does it mean for a function to "transcend", and Lockhart has just fissioned that into its constituent linguistic and philosophical parts.
This answer seems the "easy" one, and certainly not as interesting as awakening dormant existential and semiotic dilemmas, merely holding a ruler up to a three-sided shape! (Like Schrödinger's cat, but now an ethical dilemma concerning the metaphysical welfare of a polygon?) So I hope this is the wrong answer, or at least that someone more competent in math history can give a more definitive one.

A: What Lockhart seems to be referring to is the fact that in order to express the sine of a rational angle (for example an integer number of degrees) you will in general need transcendental numbers. In other words, working with trigonometric functions forces you to broaden the range of allowable numbers. The history of such "broadenings" is very interesting and Lockhart seems to lament the lost potential for classroom excitement when this history is not explored.


text:
Q: Compare values inside for loop and stop if the value less than the previous value I have a dataset that consists of id numbers, but this data repeats itself at a certain point. I'm trying to separate the data when it starts to repeat, so I made a for loop to do that, but it's not quite correct.
Here is the code.
res = []
res1 = []
for i, element in enumerate(df.id):
    if i > 0 :
    previous_element = df.id[i-1]

current_element = element
    if i < len(df.id)-1:
        next_element = df.id[i+1]
print(next_element)
    if  current_element > previous_element and current_element< next_element :

         res.append(current_element)
    else:
         res1.append(current_element)

A: Possible solution is the following:
import pandas as pd
import collections

# set test data and create datafarme
data = {"id": [33, 46, 46, 50, 63, 63, 70, 71,72]}
df = pd.DataFrame(data)

# convert dataframe column to list
lst = df['id'].tolist()

temp = collections.Counter(lst)

results = [[i] * j for i, j in temp.items()]

print(results)

Prints
[[33], [46, 46], [50], [63, 63], [70], [71], [72]]

Each item in results can be accessed by index like:
results[0] # >> [33]

or in loop like:
for item in results:
    print(item)

Prints
[33]
[46, 46]
[50]
[63, 63]
[70]
[71]
[72]


text:
Q: How can I generate a scatter plot from lmm in R? The models are:
Model1 = lmer(V1 ~ V2 * V3 + V4 + (1|V5), data=data)

Model2 = lmer(V1 ~ V2 + V3 + V4 + (1|V5), data=data)

V1: numerical
V2: numerical
V3: factor with two levels
V4: factor with two levels
V5: Random variable
I want to generate a dispersion graph with V1 on the Y ax and V3 on the X ax, with two curves for the two levels of V4. I tried the function coef(), but I don't know the values I should use:
Model1
(Intercept)       V2  V3 V4  V2:V3
Model2
(Intercept)         V2   V3 V4
Thanks!


text:
Q: Find the solution of the given initial value problem (differential equations) Question: $$\frac{dy}{dt}+ty=1+t$$ where $y(\frac{3}{2})=0$.
So I know this is a non-homogeneous equation and as I started working on it, I ended up with:
$$e^{\frac{t^2}{2}}y=\int_{\frac{3}{2}}^{t} e^{\frac{\tau^2}{2}}d\tau$$
and I'm stuck at this step. Any help?

A: This is a first order linear differential equation of the form:

The general solution is given by:

where:

called the integrating factor.
In your question,
$p(x) =t$ and $q(x) =t+1$.
I guess you can solve it from here.

A: This is a linear first order first degree ODE of the form y'+P(x)y=Q(x).
Here, P(x)=t and Q(x)=1-t.
Now you already found the correct integrating factor(I.F.) i.e. exp(t^2/2).
solution of this form of ode is given by : y*(I.F.)= ∫(I.F.)*Q(x) dx + c , c is a constant of integration
You can easily evaluate this integral without putting the limits of integration and then using the initial value you can find the value of c.

A: As commented by Frank Lu, this is a very complex differential equation. For $$\frac{dy}{dt}+ty=0$$ the solution is simple $$y=C e^{-\frac{t^2}{2}}$$ and the variation of parameters leads to $$\frac{dC}{dt}=(1+t)e^{\frac{t^2}{2}}$$ so $$C=e^{\frac{t^2}{2}}+\int e^{\frac{t^2}{2}}\,dt+K$$ and the problem comes from the last integral since $$\int e^{\frac{t^2}{2}}\,dt=\sqrt{\frac{\pi }{2}} \text{erfi}\left(\frac{t}{\sqrt{2}}\right)$$ where appears the imaginary error function $\frac{\text{erf(i t)}}{i}$. So, no solution in terms of  elementary functions.


text:
Q: Find indices of zero array into an array I have a numpy array
my_array = np.array([[1,2,3,4],[5,6,7,8],[0,0,0,0],[1,2,3,4],[0,0,0,0],[0,0,0,1]])

and I would like to get all index when array contains only zero values :
index 2 -> [0,0,0,0]
index 4 -> [0,0,0,0]

Discussion with the similar problem exists : Find indices of elements equal to zero in a NumPy array
but in this solution we get values equal to zero, instead of get array with zero as I want.
Thank for your help.

A: You can use np.argwhere with np.all to get indices of rows where all elements == 0:
In [11] np.argwhere((my_array == 0).all(axis=1))
Out[11]:
array([[2],
       [4]], dtype=int64)

Or np.nonzero instead of np.argwhere gives slightly nicer output:
In [12] np.nonzero((my_array == 0).all(axis=1))
Out[12]: (array([2, 4], dtype=int64),)


text:
Q: Weighting loss function using Voronoi-tessellation of response space Let's say you have some Real-valued features $\mathbf{X}$ and Real-valued univariate responses $\mathbf{y}$. We want to fit a regression model to this data:
$$\mathbf{y} = f\left(\mathbf{X};\beta\right) + \mathbf{\varepsilon}$$
Where fitting is done by minimizing some loss function $L(f(x;\beta),y)$:
$$\hat{\beta} = \min_{\beta} \sum_i L(f(x_i;\beta),y_i)$$
I noticed that although $L$ is a function of $\mathbf{X}$ and the true responses $\mathbf{y}$, it is not sensitive to the distribution of $\mathbf{y}$ or $\mathbf{X}$. The loss assigned to each point does not appear to depend on the distribution of points around it.
I'd like to weight the loss for each training point by a scalar $s_i$ to reflect the "novelty" of each $y_i \in \mathbf{y}$. I was thinking of using a 1-d Voronoi tessellation on $\mathbf{y}$ (with the extreme points serving as outer bounds/convex hull for the tessellation) and setting $s_i$ to be the length of the Voronoi cell associated with $y_i$, such that the new, weighted loss function becomes:
$$L_w(f(x_i;\beta),y_i) = s_iL(f(x_i;\beta),y_i)$$
I'd be appreciative of any references to the statistical properties of this approach, whether applied to the response space (as above) or to the feature space (provided s suitable Voronoi tessellation can be developed for the feature space)


text:
Q: Trouble Passing dynamic entries using variable The below JavaScript code displays line chart using chart.js. The code works fine however, if you look at the part of the code  near labels I am trying to pass it dynamically using a variable instead of having a static list of months. For example I just want to pass from Jan - May.
I am using a variable x to do that but it would not work as a separate labels it would display as one label example in the image. Is there a way i can pass those label dynamically ? I don't want to use separate variables since my list will be based on n.

Original
var lineChartData = {
            labels : ["January","February","March","April","May","June","July","August","September","October","November","December"],
            datasets : [
                {
                    label: "My First dataset",
                    fillColor : "rgba(54,61,251,0.2)",
                    strokeColor : "rgba(54,61,251,1)",
                    pointColor : "rgba(54,61,251,1)",
                    pointStrokeColor : "#fff",
                    pointHighlightFill : "#fff",
                    pointHighlightStroke : "rgba(54,61,251,1)",
                    data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
                }

Modified Version
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};

        var x = ' \"January\" , \"February\" ';
        var lineChartData = {
            labels : [x,"March","April","May","June","July","August","September","October","November","December"],
            datasets : [
                {
                    label: "My First dataset",
                    fillColor : "rgba(54,61,251,0.2)",
                    strokeColor : "rgba(54,61,251,1)",
                    pointColor : "rgba(54,61,251,1)",
                    pointStrokeColor : "#fff",
                    pointHighlightFill : "#fff",
                    pointHighlightStroke : "rgba(54,61,251,1)",
                    data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
                }
            ]

        }

    window.onload = function(){
        var ctx = document.getElementById("canvas").getContext("2d");
        window.myLine = new Chart(ctx).Line(lineChartData, {
            responsive: true
        });
    }

A: What you want is to declare x (currently declared as a string) as an array instead. The, you join the two arrays together using .concat so that your labels property has the full list:
    var x = ["January", "February"];
    var lineChartData = {
        labels : x.concat(["March","April","May","June","July","August","September","October","November","December"]),


text:
Q: Deny access but allow robots i.e. Google to sitemap.xml Is there a method where you can only allow robots such as Google, Yahoo, or other search engine robots to my sitemap which is located at http://www.mywebsite.com/sitemap.xml. Is this possible to not allow direct access by a user but only to robots?

A: Well basically no, but you could do something with the user-agent string and disallow access (assuming Apache)
<Location /sitemap.xml>
  SetEnvIf User-Agent GodBot GoAway=1
  Order allow,deny
  Allow from all
  Deny from env=!GoAway
</Location>

But as it says here (where I found the syntax)

Warning:
Access control by User-Agent is an
  unreliable technique, since the
  User-Agent header can be set to
  anything at all, at the whim of the
  end user.

A: It is in Red in my source:

$ip = $_SERVER["REMOTE_PORT"];
$host = gethostbyaddr($ip);

if(strpos($host, ".googlebot.com") !== false){
    readfile("sitemap.xml");
}else{
    header("Location: /");

A: sitemap.php
<?php

    $ip = $_SERVER["REMOTE_PORT"];
    $host = gethostbyaddr($ip);

    if(strpos($host, ".googlebot.com") !== false){
        readfile("sitemap.xml");
    }else{
        header("Location: /");
    }


text:
Q: poco httpclientsession giving host not found errors even though host resolves I'm having a strange problem with poco.  I can build it fine, and link it to a test application.   However when I download a url, no matter what url I use it reports a HostNotFound exception.   The file is accessible in incognito browsers everywhere and resolvable in dns.... I'm somewhat at a loss for troubleshooting this... any ideas?
// dns on the machine showing error
nslookup s3.amazonaws.com
Server:  UnKnown
Address:  192.168.0.1
Non-authoritative answer:
Name:    s3-1.amazonaws.com
Address:  72.21.215.196
Aliases:  s3.amazonaws.com
          s3.a-geo.amazonaws.com
    // calling helper
CString host("http://s3.amazonaws.com");
CString path("/mybucket.mycompany.com/myfile.txt");
CString errmsg;
CString data = GetURL(host,path,errmsg);

    // poco helper code
 CString  GetURL(CString host, CString path_query, CString &debmsg)
{

    debmsg = CString("");
    try
    {
        // convert request
        std::string tmphost((LPCTSTR)host);
        std::string tmppath((LPCTSTR)path_query);
        // creation session and request
        HTTPClientSession session(tmphost,80);
        // disable proxy
        session.setProxyHost("");
        HTTPRequest req(HTTPRequest::HTTP_GET,tmppath,HTTPMessage::HTTP_1_1);

        // send request
        session.sendRequest(req);
        // get response
        HTTPResponse res;

        std::istream * response = &session.receiveResponse(res);

        // convert it back to mfc string
        streambuf *pbuf = response->rdbuf();
        std::ostringstream ss;
        ss << pbuf;

        CString data(ss.str().c_str());

        return data;
    }
    catch (Poco::Exception& ex)
    {
        CString err(ex.displayText().c_str());
        debmsg.Format("error getting url: %s%s err: %s",host,path_query,err);
    }

    return CString("<error>");

}

A: Just had a similar problem. Note your host name is "http://s3.amazonaws.com".
The actual name of the host is "s3.amazonaws.com". The "http://" part specifies the protocol. The class HTTPClientSession is only to be used for the http protocol anyway.
In my case, stripping off the "http://" and just using the actual host name worked correctly: "s3.amazonaws.com":
HTTPClientSession session("s3.amazonaws.com");

(Well, in my case it was "http://ws.audioscrobbler.com", but that's beside the point). Probably too late to find out if this was really the answer to your problem, the error does look a bit different to mine, but hopefully it might help someone arriving here through search, as I did.

A: rebuilt poco net library, still got the same error.
to avoid wasting time with something so simple, just switched to use CHttpConnection (which also saved about 20MB of library requirements).
perhaps experienced poco developers will come up with a better idea.


text:
Q: Metro has encountered an error: While trying to resolve module '@react-native/normalize-color' I just wanted to try react-native.However, after run the script "npm run ios",I got this error in the Xcode's simulator.

react-native version: v0.66.0,
platform: Mac OS Big Sur 11.6.2,
How can I fix this?

A: install '@react-native/normalize-color' using command line npm i @react-native/normalize-color

A: Try installing '@react-native/normalize-color@2.0.0' if you are using 'react-native-maps'. This worked for me. It's probably because we may be using an older version of 'react-native' which included an older version of 'normalize-color'.


text:
Q: Firestore not updating after screen is turned off I am running my app on my physical device and the real time Firestore update works fine till the screen is turned off.
Here is the function I use to update my data:
private void updateNotifyGroup(String groupCreator, final String groupKey) {

    // IT WORKS EXACTLY AS IN addChildEventListener()
    // ADD groupRepository.getCreatorGroup(groupKeyMsg) instead of currentUser
    Log.i("debinf callfrag", "groupCreator" + groupCreator);
    Log.i("debinf callfrag", "groupKey" + groupKey);
    CollectionReference collectionReference = CallRoot.collection(groupCreator).document(groupKey).collection("ClientList");

    collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {

            if (e != null) {
                Log.i("debinf callfrag", "Listen failed.", e);
                return;
            }

            if (queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()){

                for (DocumentChange documentChange : queryDocumentSnapshots.getDocumentChanges()) {
                    //Log.i("debinf callfrag", "entering in loop = " + documentChange.getDocument().getData());
                    switch (documentChange.getType()) {
                        case ADDED:
                            Log.i("debinf callfrag", "data added = " + documentChange.getDocument().getData().get("notifyGroup"));

                            for (int i = 0; i < clientList.size(); i++) {

                                if (clientList.get(i).getCid().equals(documentChange.getDocument().getId())) {
                                    //Toast.makeText(getContext(), "Client name is " + clientList.get(i).getName(), Toast.LENGTH_SHORT).show();
                                    clientList.get(i).setNotifygroup(documentChange.getDocument().getData().get("notifyGroup").toString());
                                    mClientListAdapter.notifyDataSetChanged();
                                    break;

                                }
                            }
                            break;

                        case MODIFIED:
                            Log.i("debinf callfrag", "data modified = " + documentChange.getDocument().getId());
                            for (int i = 0; i < clientList.size(); i++) {

                                if (clientList.get(i).getCid().equals(documentChange.getDocument().getId())) {
                                    Toast.makeText(getContext(), "Client name is " + clientList.get(i).getName(), Toast.LENGTH_SHORT).show();
                                    clientList.get(i).setNotifygroup(documentChange.getDocument().getData().get("notifyGroup").toString());
                                    mClientListAdapter.notifyDataSetChanged();
                                    break;

                                }
                            }
                            break;

                        case REMOVED:
                            Log.i("debinf callfrag", "data removed = " + documentChange.getDocument().getData());
                            break;
                    }
                }

            }

        }
    });

}

That is the result before the screen is turned off:
02-10 16:42:32.890 20019-20019/com.example.aliton.myapp I/debinf callfrag: groupCreatorAJ0uyrTm95ODvCuua71cB17ueBt2
02-10 16:42:32.890 20019-20019/com.example.aliton.myapp I/debinf callfrag: groupKey-LXM0N48OOHTpwa8kNmJ
02-10 16:42:32.981 20019-20019/com.example.aliton.myapp I/debinf callfrag: data added = Desligado
02-10 16:42:32.982 20019-20019/com.example.aliton.myapp I/debinf callfrag: data added = Agendado
02-10 16:42:32.983 20019-20019/com.example.aliton.myapp I/debinf callfrag: data added = Ligar
02-10 16:42:32.984 20019-20019/com.example.aliton.myapp I/debinf callfrag: data added = Nao Atende
02-10 16:42:32.985 20019-20019/com.example.aliton.myapp I/debinf callfrag: data added = Andamento
02-10 16:42:32.987 20019-20019/com.example.aliton.myapp I/debinf callfrag: data added = Finalizado
02-10 16:42:32.988 20019-20019/com.example.aliton.myapp I/debinf callfrag: data added = Recusado

When my device turns the screen off , the lifecycle is onPause and onStop. When turning the screen on, the lifecycle is onStart and onResume.
My app works similarly to the app presented in this link:
android fragment to fragment communication : update recyclerView of the ReceiverFragment via interface
After I turn the screen on, I manually change the value of the field from Ligar to AnyThing and my physical device does not get notified about the change in Firestore.
Just my Emulator gets notified about the change in Firestore.
My physical device only gets notified after re-running on Android Studio:
02-10 17:25:33.296 21287-21287/com.example.aliton.myapp I/debinf callfrag: groupCreatorAJ0uyrTm95ODvCuua71cB17ueBt2
02-10 17:25:33.296 21287-21287/com.example.aliton.myapp I/debinf callfrag: groupKey-LXM0N48OOHTpwa8kNmJ
02-10 17:25:33.903 21287-21287/com.example.aliton.myapp I/debinf callfrag: data added = Desligado
02-10 17:25:33.904 21287-21287/com.example.aliton.myapp I/debinf callfrag: data added = Agendado
02-10 17:25:33.905 21287-21287/com.example.aliton.myapp I/debinf callfrag: data added = AnyThing
02-10 17:25:33.906 21287-21287/com.example.aliton.myapp I/debinf callfrag: data added = Nao Atende
02-10 17:25:33.907 21287-21287/com.example.aliton.myapp I/debinf callfrag: data added = Andamento
02-10 17:25:33.908 21287-21287/com.example.aliton.myapp I/debinf callfrag: data added = Finalizado
02-10 17:25:33.909 21287-21287/com.example.aliton.myapp I/debinf callfrag: data added = Recusado
02-10 17:25:34.945 21287-21287/com.example.aliton.myapp I/debinf callfrag: data modified = 629584107

How do I make permanent connection to Firestore even atfer the screen is turned on again?

A: Android will stop your app from functioning when the user isn't actively using it.  This is to prevent apps from draining the battery.  You should allow for this to happen - read about doze and app standby modes in the Android documentation.
If you really must continue doing work when the screen is off, you need to create a foreground service.  Note that the documentation warns you about limiting use of foreground services.  If you are just trying to maintain a connection to Firestore, that is not a very good use of a foreground service.

A: This is not a solution, but it made me think that it solved the problem.
I do not know if the solution that I am presenting here is the appropriated solution, but it seems to solve the problem of reestablishing the connection with Firestore after turning on the screen (returning from Doze Mode).
I implemented a connection with Firestore in onStart:
@Override
public void onStart() {
    super.onStart();
    Log.i("debinf callfrag", "onStart");
    if (groupKeyFromSender != null) {
        updateNotifyGroup(groupCreatorFromSender, groupKeyFromSender);
    }

}

For those who are starting in Android Studio like me and are interested in the code to understand new functionalities, here comes the code:
public class CallFragment extends Fragment {

    View view;
    private RecyclerView mClientList;
    private RecyclerView.Adapter mClientListAdapter;
    private RecyclerView.LayoutManager mClientListLayoutManager;

    private String receivedFromSender;
    private String currentUser, groupKeyFromSender, groupCreatorFromSender;

    ArrayList<ClientObject> clientList;

    SQLiteDatabase clientListTable;
    ClientRepository clientRepository;

    private FirebaseAuth mAuth;
    FirebaseFirestore CallRoot;

    static Context mContext;

    private static String rootPath = Environment.getExternalStorageDirectory()+"/";

    public CallFragment() {
        // Required empty public constructor
    }

    public void getDataFromGroupFragment(String groupCreatorFromSender, String groupKeyFromSender, boolean addToCall) {
        if (groupKeyFromSender != null) {
            this.groupCreatorFromSender = groupCreatorFromSender;
            this.groupKeyFromSender = groupKeyFromSender;
            if (new File(rootPath + groupKeyFromSender, "client.db").isFile()) {
                if (addToCall) {
                    addClientToCall(groupCreatorFromSender, groupKeyFromSender);
                } else if (!addToCall) {
                    removeClientOfCall(groupKeyFromSender);
                }
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.call_fragment, container, false);

        setHasOptionsMenu(true);

        mAuth = FirebaseAuth.getInstance();
        currentUser = mAuth.getCurrentUser().getUid();
        CallRoot = FirebaseFirestore.getInstance();

        mContext = container.getContext();
        //Log.i("debinf recgfrag", "mContext in onCreate : " + getContext());

        clientList = new ArrayList<>();

        initializeRecyclerView();

        return view;
    }

    private void removeClientOfCall(String pathToClientTable) {

        //Log.i("debinf recgfrag", "mContext in clientReading" + mContext);

        ClientDatabaseHelper clientDatabaseHelper = new ClientDatabaseHelper(mContext,"client.db", rootPath+pathToClientTable+"/");

        clientListTable = clientDatabaseHelper.getReadableDatabase();
        clientRepository = new ClientRepository(clientListTable);
        ArrayList<ClientObject> clientObjects = clientRepository.SearchAllClients();

        clientList.removeAll(clientObjects);
        Log.i("debinf recfrag", "clientList.size() Remove in clientReading is " + clientList.size());
        mClientListAdapter = new CallAdapter(mContext,clientList);
        //Log.i("debinf recfrag", "mClientList in clientReading is " + mClientList);
        mClientList.setAdapter(mClientListAdapter);
        mClientListAdapter.notifyDataSetChanged();

    }

    private void addClientToCall(String groupCreator, String groupKey) {

        ClientDatabaseHelper clientDatabaseHelper = new ClientDatabaseHelper(mContext,"client.db", rootPath+groupKey+"/");

        clientListTable = clientDatabaseHelper.getReadableDatabase();
        clientRepository = new ClientRepository(clientListTable);
        ArrayList<ClientObject> clientObjects = clientRepository.SearchAllClients();

        clientList.addAll(clientObjects);
        Log.i("debinf recfrag", "clientList in clientReading is " + clientList.get(0).getName());

        updateNotifyGroup(groupCreator, groupKey);

        mClientListAdapter = new CallAdapter(mContext,clientList);
        //Log.i("debinf recfrag", "mClientList in clientReading is " + mClientList);
        mClientList.setAdapter(mClientListAdapter);
        //mClientListAdapter.notifyDataSetChanged();

    }

    private void updateNotifyGroup(String groupCreator, final String groupKey) {

        // IT WORKS EXACTLY AS IN addChildEventListener()
        // ADD groupRepository.getCreatorGroup(groupKeyMsg) instead of currentUser
        Log.i("debinf callfrag", "groupCreator" + groupCreator);
        Log.i("debinf callfrag", "groupKey" + groupKey);
        CollectionReference collectionReference = CallRoot.collection(groupCreator).document(groupKey).collection("ClientList");

        collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {

                if (e != null) {
                    Log.i("debinf callfrag", "Listen failed.", e);
                    return;
                }

                if (queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()){

                    for (DocumentChange documentChange : queryDocumentSnapshots.getDocumentChanges()) {
                        //Log.i("debinf callfrag", "entering in loop = " + documentChange.getDocument().getData());
                        switch (documentChange.getType()) {
                            case ADDED:
                                Log.i("debinf callfrag", "data added = " + documentChange.getDocument().getData().get("notifyGroup"));

                                for (int i = 0; i < clientList.size(); i++) {

                                    if (clientList.get(i).getCid().equals(documentChange.getDocument().getId())) {
                                        //Toast.makeText(getContext(), "Client name is " + clientList.get(i).getName(), Toast.LENGTH_SHORT).show();
                                        clientList.get(i).setNotifygroup(documentChange.getDocument().getData().get("notifyGroup").toString());
                                        mClientListAdapter.notifyDataSetChanged();
                                        break;

                                    }
                                }
                                break;

                            case MODIFIED:
                                Log.i("debinf callfrag", "data modified = " + documentChange.getDocument().getId());
                                for (int i = 0; i < clientList.size(); i++) {

                                    if (clientList.get(i).getCid().equals(documentChange.getDocument().getId())) {
                                        Toast.makeText(getContext(), "Client name is " + clientList.get(i).getName(), Toast.LENGTH_SHORT).show();
                                        clientList.get(i).setNotifygroup(documentChange.getDocument().getData().get("notifyGroup").toString());
                                        mClientListAdapter.notifyDataSetChanged();
                                        break;

                                    }
                                }
                                break;

                            case REMOVED:
                                Log.i("debinf callfrag", "data removed = " + documentChange.getDocument().getData());
                                break;
                        }
                    }

                }

            }
        });

    }

    private void initializeRecyclerView() {

        mClientList = (RecyclerView) view.findViewById(R.id.clientList);
        mClientList.setNestedScrollingEnabled(false);
        mClientList.setHasFixedSize(false);
        mClientListLayoutManager = new LinearLayoutManager(mContext,LinearLayout.VERTICAL,false);
        mClientList.setLayoutManager(mClientListLayoutManager);

        mClientListAdapter = new CallAdapter(mContext,clientList);
        mClientList.setAdapter(mClientListAdapter);

    }

    @Override
    public void onStart() {
        super.onStart();
        Log.i("debinf callfrag", "onStart");
        if (groupKeyFromSender != null) {
            updateNotifyGroup(groupCreatorFromSender, groupKeyFromSender);
        }

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.options_call, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        switch (item.getItemId()){
            case R.id.play_option:
                Toast.makeText(getContext(), "PlayOption Selected", Toast.LENGTH_SHORT).show();
                doSomething();
                return true;

            case R.id.stop_option:
                Toast.makeText(mContext, "option Stop", Toast.LENGTH_SHORT).show();
                return true;

        }

        return false;

    }

    private void doSomething() {
        Toast.makeText(mContext, "didSomething", Toast.LENGTH_SHORT).show();
    }

}

To make my code a bit clearer, I am updating the button text:
Good luck!


text:
Q: How to know what augmentation has been carried out tf.image.stateless_random_flip_up_down or similar API In TF 2.x, there are a whole set of image augmentation API, take tf.image.stateless_random_flip_up_down for example. Most of these will perform the said operation at random. What I like to find out is if there's a way to interrogate what exactly has been perform for a specific image in a specific batch. This info is critical if the target prediction involve localization like points, bounding boxes, etc. Since affine transform (like translate) performed on image, the same operation should be used to "augment" the targets (y) in a consistent manner.
I think all the image transform API in TF2.X do not return this piece of info. I would like to see if there's easier way than creating custom ones of my own. I have done this for the older Keras data augmentation API in the past by subclasses, and would prefer not to repeat the tedium if possible.

A: I guess your main goal is to write a data augmentation pipeline that changes both image and its labels.
Well, then I would recommend you to use Albumentaitons library instead. It is a very popular open-source library that can easily be integrated with Tensorflow and PyTorch frameworks.
Here is its documentation: https://albumentations.ai/
Let me know if it helps!


text:
Q: Data Formatters temporarily Unavailable, will re-try after a continue I am working on Objective C to develop an app in I Pad. When I run the program its getting executed in Simulator of IPad. When I do the same connecting the device then I am facing an Error as GDB:Data Formatters temporarily unavailable,will re-try after a 'continue'.
Someone guide how to solve this issue.
Regards,
Vani.

A: This can be because of several reasons:

*

*Memory issue. Try running your app with instruments to check

*When it is unable to find a linked in shared library at launch time.

*Also you can try running in a different target xcode and check if that works

*Check all you breakpoints. In the Debugger window, click on "Show Breakpoints" and see if there are any unusually placed breakpoints

A: I also got the same problem in cocoa application.
Take a look at Data Formatters temporarily unavailable, will re-try after a 'continue'.

"Data Formatters temporarily unavailable, will re-try after a
  'continue'." means that something has gone so horribly wrong in your
  code that even the debugger bailed. As dragyn said, this usually
  involves some form of rapid object creation or recursion calling. Add
  a few NSLog lines into your code to help you see how far your code is
  getting and where it might be looping/calling itself.


text:
Q: Issues trying to fetch data from PHP JSON multidimensional array with JQuery I have a multidimensional array which, when echoed in PHP, looks like this:
{
    "11-12-20":{"visits":0,"pageviews":0}
    "11-12-21":{"visits":0,"pageviews":0}
    "11-12-22":{"visits":0,"pageviews":0}
}// etc.

As you can see, the date is the key to the arrays inside the multidimensional array. So I can select an array from the multidimensional array using the date as the key:
$my_multi_array['12-12-12'];

JSON:
$.getJSON('file.php', function(data){
    var test='11-12-29';
    document.write(data.test);
});

When I test that in a browser, nothing is printed on the screen. Also, how would I go about looping through the whole of that array in jQuery and use the data inside that array's array.
I've been at this for hours now, and am pretty frustrated.

A: Use data[test]. Your data.test is equal to data["test"], and there is no "test" property in your object.

A: The PHP output that you have echoed is not an array, it's a JSON object without comma separators, which means it's not correctly formed.
If you correct the syntax, you can access the objects in data through the index notation ([]), not the dot operator (.). So instead of accessing data like data.test, you should try data[test].
Assuming you name your JSON object myJson, here's how you can iterate thought it:
var myJson = {
    "11-12-20":{"visits":0,"pageviews":0},
    "11-12-21":{"visits":0,"pageviews":0},
    "11-12-22":{"visits":0,"pageviews":0}
}

for (var item in myJson)
{
    alert(myJson[item].visits + ", " + myJson[item].pageviews);
}


text:
Q: Spring Bean with Factory Method from XML to Java Config Which is the properly way to translate this bean:
<bean id="velocityEngine" class="org.springframework.security.saml.util.VelocityFactory" factory-method="getEngine"/>

from XML to Java-Config (note the factory-method)?
Is the following solution right?
@Bean
public VelocityEngine veloctyEngine() {
        return VelocityFactory.getEngine();
}

Is there a better implementation according to the Spring-philosophy?
Cheers, V.

A: The way you are doing it seems right.
Check out this blog post.


text:
Q: Maximum Number of Folders Windows Server I'm building a site(asp.net) that needs save images for each product, so I'm not sure how implement it. I think i can do it saving all photos in the same folder but i do not like that i would prefer to create a new subfolder for each product and save the images in that subfolder but maybe in the future i have problems due to limitations with number of folders or subfolders.
Do you think that second option (creating subfolders) is better and secure?

A: You can see in the following link the limits of windows file system
http://technet.microsoft.com/en-gb/library/bb457112.aspx
taken from
https://serverfault.com/questions/18692/what-is-the-maximum-number-of-files-or-folders-that-can-be-stored-in-a-single
the limits of files and sub folders changed depending the kind of server/netapp.
you can read in the link above the limits for each one.
I would use subfolders but it is up to you, the important thing is that you need to know the limits and then decide.


text:
Q: Get graphviz to draw nodes above edges Is there any way to force graphviz to always draw the nodes above edges even if the edge is drawn over (or preferably under) the node?
So far I have tried ordering them and different layer options but not found a way that works.

A: You'll want to specify outputorder="edgesfirst".  This can be found in the documentation.


text:
Q: How does closure reify the data encapsulation? In traditional OOP language, we usually use private/public to implement data encapsulation.
In Javascript, there is no private or public anymore; someone told me; by using closure, the data encapsulation can be implemented. I am wondering how and what's the behind logic?

A: You can encapsulate data in a 'Class' (no real class before JavaScript 6) this way
var yourClass = function() {
   var privateProp = 'sometext'; //private prop
   this.prop = 1; //public

   this.getPrivateProp = function() {
       return privateProp; //access to your private prop with a closure
   }
}

var test = new yourClass();
//when you use 'new', everything in 'this' is returned in your object.
//'privateProp' is not in 'this' but 'getPrivateProp' is.
//You got your private data not directly accessible from outside.

test.prop; // 1
test.privateProp;//undefined
test.getPrivateProp();// 'sometext'

A: Actually isn't creating actual private members.
Check the following code:
function A() {
    var doStuff1 = function() { };
    this.doStuff2 = function() {
        doStuff1();
    };
};

var instance = new A();
instance.doStuff2();

Since doStuff2 is declared and added to this, it's part of A instance while doStuff1 is declared as a local variable within the constructor function, and thus, it's only accessible using closures within the same constructor.
BTW I don't like this pattern since it works great when you don't use prototypal inheritance.
Let's say I want to use prototypes:
function A() {
     var doStuff1 = function() {}; // ??????
};

A.prototype = {
     doStuff2: function() {
        // How do I access a local variable defined
        // in the constructor function local scope?
     }
};

So, the whole pattern works in simple scenarios where you don't want to use prototypal inheritance.
Also, this pattern won't work in scenarios where you want to use Object.create(...), since there's no constructor function at all...
// Constructor isn't ever called...
var instance = Object.create(A.prototype);

So, how you would implement this kind of encapsulation in JavaScript? For now isn't possible, but many libraries and frameworks have opted-in to use naming conventions to let developers know what's consumed by the library/framework code and what's intended for use in actual third-party developments.
For example:
function A() {

};

A.prototype = {
    ___doStuff1___: function() {},
    doStuff2: function() {
         this.___doStuff1___();
    }
};

After all, this is a naming convention, where members which are sorrounded by ___ are considered private or not intended for third-party developers.
Other libraries/framework use $$ (f.e. Angular, $$privateMember).


text:
Q: How can a $\mathbb{R}$-vector space not be a $\mathbb{C}$-vector space How can $V = \begin{Bmatrix}\begin{pmatrix} a & b \\c & d\\ \end{pmatrix} \ \ |\ \ \  a,b,c,d \in \mathbb {C} \ \ and \ \ a+d \in \mathbb{R}\end{Bmatrix} $ be a $\mathbb{R}$-vector space and at the same time not a $\mathbb{C}$ vector space?
If it were an $\mathbb{R}$-vector space, would it not also be an $\mathbb {C}$-vector space because $\mathbb{R} \subset \mathbb{C}$, so every $a,b,c,d$ could be written as $a + 0 \cdot i$, $b + 0 \cdot i$, ...?

A: In a $\Bbb R$-vector space, the scalar product $\lambda v$ with $\lambda\in \Bbb C$ isn't defined. You can define a complexification of a $\Bbb R$-vector space, but it will be another structure.

A: It is isomorphic, as an abelian group, to $\mathbf C^4$. However it cannot be a $\mathbf C$-vector space for the very simple following reason:
Matrices $\begin{pmatrix}a&b\\c&d\end{pmatrix}$ are characterised by the fact that its diagonal elements $a$ and $d$ are conjugate.
Now if $d=\overline a$,and if we multiply the matrix by, say, $1+i$, we have
$$ (1+i)d=(1+i)\overline a\neq\overline{(1+i)a}. $$


text:
Q: How can I configure by CodeBuild to not trigger CodePipeline recursively Currently my CodeBuild is cloning the source CodeCommit Repository, making some changes on it and pushing it to the origin, this causes the pipeline to be triggered recursively since the source code is changing every time.  I want to stop the pipeline trigger after pushing the changes to the Source Repository

A: Two quick and simple solutions:

*

*The simplest solution is to disable your Pipeline and enable it when you want to it to work again.

*Or depends on which branch your Pipeline tracks, assuming it is the main/master branch. A better practice is to do your development in a different git branch. Then merge that branch to your main/master branch to trigger the Pipeline.


text:
Q: Необходимо правильно извлечь данные из API JS Вопрос такой, мне необходимо получить из этого кода данные API, в консоль.log выводится то что мне нужно
return cc.coinList()
         .then((coinList) => {
              console.log(coinList);
              return coinList;
          })
         .catch(console.error);

Тут в data() я получаю этот объект
coinLista : this.checkAllPrices()

но он выглядит из-за
return cc.coinList()

с лишними элементами пути

Как получить доступ к необходимой мне Data и правильно записать данные в [[]]?
Или еще лучше, как вернуть этот объект coinList в исходном виде?

A: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Promise
Прочитайте про промисы и всё станет понятно. К свойствам в [[]] вы не имеете доступа, т. к. они внутренние.
Если вы хотите получить работающий код, то дайте пример на codepen, jsfiddle или codesanbox или, хотя бы, ссылку на документацию по вашему API.


text:
Q: Label refresh automático Gostaria de saber como poderia fazer refresh automaticamente a uma LABEL que está numa Master Page. Essa Label mostra a soma da quantidade dos produtos, e sempre que adiciono um produto ao carrinho a Label não faz refresh, apenas faz refresh se eu fizer refresh da próprio página ou se mudar de página. Basicamente queria que a label fizesse o refresh da quantidade, assim que o produto fosse adicionado ao carrinho, e não quando se muda de página.
A Label está inserida numa Form View dentro da Master.
<asp:FormView ID="FormViewNE" runat="server" DataSourceID="SqlDataSourceNE">
 <ItemTemplate>
 <asp:Label ID="lblNE" runat="server" Text='<%# Bind("NE") %>' />
 </ItemTemplate>
 </asp:FormView>
 <asp:SqlDataSource ID="SqlDataSourceNE" runat="server" ConnectionString="<%$      ConnectionStrings:ConnectionString %>" SelectCommand="SELECT SUM (Quantidade) AS  NE FROM Carrinho WHERE (IDUtilizador = @IDUtilizador)">
<SelectParameters>
<asp:SessionParameter Name="IDUtilizador" SessionField="IDUtilizador" />
</SelectParameters>
</asp:SqlDataSource>

A: Tenta experimentar substituir a tua 3ª linha de código por esta:
<asp:Label ID="lblNE" runat="server" Text="<%= Bind("NE") %>" />


text:
Q: how to insert value and use subquery to insert the last value? I have two tables customer and shipping_details,
customer

first_name
last_name
phone
shipping_detail_id

shipping_details

shipping_detail_id
address

where the shipping id that I need to insert has an address of 'fakeadressstreet'
The values I want to insert are 'Jackson,' mike',12345,(shipping detail id where address is = fakeadressstreet).
the last value I need to insert depends on another column which is my second table no sure how to insert that value but  I hope it makes sense.

A: Something like this should work:
insert into customer ( first_name,
                       last_name,
                       phone,
                       shipping_detail_id
                     )

(SELECT   'Jackson' as first_name,
          'Mike' as last_name,
          12345 as phone,
          t1.shipping_detail_id
FROM shipping_details
WHERE address = fakeadressstreet
) as t1 ;


text:
Q: Should I add an arbitrary length limit to VARCHAR columns? According to PostgreSQL's docs, there's no performance difference between VARCHAR, VARCHAR(n) and TEXT.
Should I add an arbitrary length limit to a name or address column?
Edit: Not a dupe of:

*

*Would index lookup be noticeably faster with char vs varchar when all values are 36 chars
I know the CHAR type is a relic of the past and I'm interested not only in performance but other pros and cons like Erwin stated in his amazing answer.

A: The question is specifically whether adding an arbitrary length limit to VARCHAR columns?
To that, the answer is simply "no". There is nothing that can justify adding an arbitrary limit like you would in inferior databases that support varchar(max) or use conventions like varchar(255). However, if the spec addresses a limit, I think the answer becomes much more complex especially on modern versions of PostgreSQL. And, for that, I would lean towards YES.
In my opinion, the limit is a wise-choice if the spec requires it. Especially for more reasonable workloads. If for no other reason then to preserve meta-data.
From my answer here, index performance for CHAR vs VARCHAR (Postgres), where I address the value of meta-data.

If I found a spec that had variable-length text-keys that were meaningful and that I trusted to have a constant max-length, I would use varchar too. However, I can't think of anything that fits that criteria.

A: If you see the length limit as a kind of check constraint to make sure you validate the data, then yes add one. Actually you might want to not use a length definition but a real check constraint instead, to make changing the limit faster.
To change (increase) a length limit you need to run an ALTER TABLE which might take a long time to finish (due to a possible re-write of the table) during which an exclusive table lock is necessary.
Changing (i.e. dropping and re-creating) a check constraint is a very brief operation and only requires reading the table's data, it will not change any rows. So that is going to be a lot quicker (which in turn means the exclusive table lock will be held for a much shorter amount of time).
During operation there is no difference whatsovever between a text, a varchar or a varchar(5000) column.

A: The answer is no.
Related advice in the Postgres Wiki.
Don't add a length modifier to varchar if you don't need it. (Most of the time, you don't.) Just use text for all character data. Make that varchar (standard SQL type) without length modifier if you need to stay compatible with RDBMS which don't have text as generic character string type.
Performance is almost the same, text is a bit faster in rare situations, and you save the cycles for the check on the length. Related:

*

*Any downsides of using data type "text" for storing strings?
If you actually need to enforce a maximum length, varchar(n) is a valid choice, but I would still consider text with a CHECK constraint like:
ALTER TABLE tbl ADD CONSTRAINT tbl_col_len CHECK (length(col) < 51);

You can modify or drop such a constraint at any time without having to mess with the table definition and depending objects (views, functions, foreign keys, ...). And you can enforce other requirements in the (same) constraint.
Length modifiers used to cause problems like this or this or this ...
PostgreSQL 9.1 introduced a new feature to alleviate the pain somewhat. The release notes:

Allow ALTER TABLE ... SET DATA TYPE to avoid table rewrites in
appropriate cases (Noah Misch, Robert Haas)
For example, converting a varchar column to text no longer requires a
rewrite of the table. However, increasing the length constraint on a
varchar column still requires a table rewrite.

More issues with varchar(n) have been fixed in later releases.

A: It looks like there might be some performance difference if VARCHAR is regularly used to store very large strings, since "long strings are compressed by the system automatically" and "very long values are also stored in background tables." Theoretically this would mean that a high volume of requests for a very long string field would be slower than for a short string field. You'll probably never run into this problem, since names and addresses aren't going to be very long.
However, depending on how you're using these strings outside your database, you might want to add a practical limit to prevent abuse of the system. For example, if you're displaying the name and address on a form somewhere, you might not be able to display a whole paragraph of text in the "name" field, so it would make sense to limit the name column to something like 500 characters.


text:
Q: Delete words using regular expressions How can I remove the SUPPORTED SOFTWARE VERSIONS*: ONLY impacted versions are listed. line from the text?
text = (
  'SUPPORTED SOFTWARE VERSIONS*: ONLY impacted versions are listed.HP-UX B.11.00, B.11.11, and B.11.22.',
  'SUPPORTED SOFTWARE VERSIONS*: ONLY impacted versions are listed.HP-UX B.11.00, B.11.04, B.11.11 running',
  'SUPPORTED SOFTWARE VERSIONS*: ONLY impacted versions are listed.HP-UX B.11.11 and B.11.23'
)

A: You don't need regex, just a simple replace function:
text = tuple(item.replace("SUPPORTED SOFTWARE VERSIONS*: ONLY impacted versions are listed.", "")
       for item in text)

A: You can use replace since it is easier.
text = text.replace("SUPPORTED SOFTWARE VERSIONS*: ONLY impacted versions are listed.", "")

But if you really want a regex to do this job for you (which I do not recommend on this particular case), you can do:
text = "SUPPORTED SOFTWARE VERSIONS*: ONLY impacted versions are listed.HP-UX B.11.00, B.11.11, and B.11.22."
text = re.sub("SUPPORTED SOFTWARE VERSIONS\*: ONLY impacted versions are listed\.", "", text)
# 'HP-UX B.11.00, B.11.11, and B.11.22.'

A: You can use the string replace function in python. documentation
toRemove = "SUPPORTED SOFTWARE VERSIONS*: ONLY impacted versions are listed."
modifiedText = tuple(map(lambda x: x.replace(toRemove, ''), text))

Note: You can use the replace function in the re library to use regex.


text:
Q: How can I solve this hive sql problem? (Like join in Hive) I know Hive only provide equi join. For example, below sql statement.
select *
from A join B
on A.c1 = B.c2
where 1=1;
But I want to execute Like join Query in Hive. For example, below sql statement.
select *
from A join B
on A.c1 like B.c2
where 1=1;
Please let me know if you know the solution in Hive.

A: How about -
ON A.c1 LIKE concat('%',B.c2,'%')

concat will concatenate % to the c2 data so like operator will work properly.
whole sql will be like -
select * from A join B on A.c1 LIKE concat('%',B.c2,'%') where 1=1;

version - hive 2.1.1


text:
Q: Add class to element on submit of form when fields are null I have a form that has several fields all within the class Contact that have a common header.
I need that header to turn red whenever the user hits submit with any contact field unfilled. These fields (first_name, last_name, company, Marketing_Phone, email) already have the class error added when submitted empty.
These fields are all in the class wrap_contact with the label Contact Information *. This label does not receive the class error on submit. This is what I need to add. I gave the label an id of label2. So my if then is if first_name, last_name, company, Marketing_phone, or email is null on submit then label2 has the error class added.
I attempted adding the following code, but it did not work.
 $( "#pardot-form" ).submit(function( event ) {
    var someElements = document.querySelector("p.error,input[name=263882_11763pi_263882_11763]}");

    if (someElements !== "") {
       document.getElementById('p.label2').addClass = 'error';
    }

 };

This form is visible online at http://link.rubiconglobal.com/l/263882/2017-03-24/7ssj.

A: The problem is that your submit still occurs and the page is reloaded. You will need to add event.preventDefault() and event.stopPropagation() to prevent submit action from occurring and reloading the page. Alternatively, since you are using jQuery, you can simply return false which does both. See: https://stackoverflow.com/a/1357151/1736092

A: If x element has a class then add class to y element:
     <script>
     if( $('.first_name, .last_name, .company, .zip, .Marketing_Phone, .email').hasClass('error') === true )
    {
    $('p#label2').addClass('label2error');
    }
    </script>


text:
Q: Why is Unity for iOS causing Memory Leaks without WWW class being called? I am using Unity AssetBundles for async loading. On iOS this seems to cause a memory leak. Every time I load a new bundle it adds on to the used memory but never seems to release the previous memory even though the unload function and destroy are called. I am not using WWW on iOS because it didn't seem necessary on Unity 5.6.7. The loading works just fine, just an issue with unloading.
I have gone through and compressed all the assets for iOS so that I could get further along in the game. It will still eventually crash on me because it runs out of memory. If it was actually unloading assets it should never use enough memory to crash.
Here is what my UnloadBundle function looks like:
public void UnloadBundle(string bundleName)
{
  if(!m_bundles.ContainsKey(bundleName)) return;

  Hashtable bundle = (Hashtable)m_bundles[bundleName];
  if (bundle.ContainsKey("asset"))
  {
    AssetBundle assetBundle = (AssetBundle)bundle["asset"];
    assetBundle.Unload(true);
    Destroy(assetBundle);
  }

  Resources.UnloadUnusedAssets();

  m_bundles.Remove(bundleName);
}

It should unload the bundle and remove the assets from memory when UnloadBundle("bundlename"); is called. Instead it doesn't free the memory and it continues to climb. The game starts with ~1GB of memory in use and slowly climbs until it gets to ~1.4GB and crashes on iPhone 7.


text:
Q: ' Column 'PropertyAddress' in field list is ambiguous' after I run my update statement portion SELECT a.ParcelID, a.PropertyAddress, b.ParcelID, b.PropertyAddress, ifnull(a.PropertyAddress,b.PropertyAddress)
FROM mytable a
join mytable b on a.ParcelID = b.ParcelID
and a.UniqueID <> b.UniqueID
where  a.PropertyAddress is null;

update mytable a
join mytable b on a.ParcelID = b.ParcelID
and a.UniqueID <> b.UniqueID
set PropertyAddress = updat
where  a.PropertyAddress is null;

Column 'PropertyAddress' in field list is ambiguous' after I run my update statement portion


text:
Q: Create class according to type identifier Is there a design pattern, or any other way, for creating a class according to type?
My server receives a json message, containing an action to perform.
I have a several Action classes, that should be mapped to the corresponding class.
{ TYPE: 'MOVE' ... } => class ActionMove
{ TYPE: 'KILL' ... } => class ActionKill

(All Action classes implement Action interface).
How can I create the class according to the type?

A: If you need to keep trace of your action instances (i.e. for logs), use the Factory Pattern:
public class ActionFactory{
    public Action createAction(String type){
        if (type.equals("MOVE"))
            return new ActionMove();
        if (type.equals("KILL"))
            return new ActionKill();
        ... // so on for the other types

        return null; //if the type doesn't have any of the expected values
    }
    ...
}

A: Create a HashMap mapping strings to Action objects:
Map<String,Action> map = new HashMap<String,Action>();

map.put("MOVE", new ActionMove());
map.put("KILL", new ActionKill());

And then get the prefered value:
Action a = map.get(type);
a.perform();

Or whatever you need.

If you're looking for classes with static methods, you can do reflection, but you're doing it wrong. You probably want to modify your code to use objects instead of classes.

A: Ok ...
Thanks to your help I created a Factory method, which return an object according to type.
public class ActionFactory {
public static Action createAction(JSONObject object){

    try{
        String username = object.getString("USERNAME");
        String type = object.getString("TYPE");
        String src= object.getString("SRC");
        String dest = object.getString("DEST");

        if(type == "MOVE"){
            return new ActionMove(username,src,dest);
        }
        else if(type == "KILL"){
            return new ActionKill(username,src,dest);
        }

        else if(type == "DIED"){
            return new ActionDied(username, src, dest);
        }
        else if(type == "TIE"){
            // TODO: implement
        }
    }
    catch(JSONException e){
        e.printStackTrace();
    }

    return null;

}

}


text:
Q: prevent jquery validation submitting upon error when I use this in jquery it works as should however when live it is not and it is the exact same code as I copied and pasted.
When live when i select yes for the radio button it asks me to select colour and shade as it should but then it submits when i click ok. If i select attendance1 yes and select the 2 drop down values it submits without error on attendance1 or attendance2

A: It's possible you're running jQuery in "noclobber" mode (where it avoids setting itself as the $ variable).
Try putting this around the whole above code snippet:
(function($) {
    // ... code here
})(jQuery)


text:
Q: REACT JS : Error 300 and error 310 render error I am getting "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." and "Rendered more hooks than during the previous render." errors. I think everything is clear. How can I fix that? Here is my code:
 const [isSecure, setIsSecure] = useState<boolean>(true)
  const [isTabEmpty, setIsTabEmpty] = useState<boolean>(false)

  const history = useHistory()
  const curTab = useSelector(getCurrTab)
  const tabHosts = useSelector(getTabHosts)

  const hosts = curTab && curTab.id ? tabHosts[curTab.id] : []
  const url = curTab && curTab.url ? curTab.url.split('/')[2] : undefined
  const urlWithoutSplit = curTab ? curTab.url : undefined
  const host = urlWithoutSplit ? new URL(urlWithoutSplit) : undefined
  const protocol = host ? host.protocol : undefined

  useEffect(() => {
    if (hostIsSecure() !== isSecure) {
      setIsSecure(hostIsSecure)
    } else if (tabEmpty() !== isTabEmpty) {
      setIsTabEmpty(tabEmpty)
    }
  }, [host])

  function hostIsSecure(): boolean {
    if (protocol && protocol === 'https:') {
      return true
    } else return false
  }

  function tabEmpty(): boolean {
    const curTabId = curTab ? curTab.id : undefined
    if (curTabId && tabHosts[curTabId] && tabHosts[curTabId].length === 0)
      return true
    else return false
  }


text:
Q: Target Unreachable, identifier 'bean' resolved to null error I'm trying to build simple JSF app using Glassfish as app server, and it's starting but after that this error is happening:
javax.el.PropertyNotFoundException: /index.xhtml @10,75 value="#{bean.genre}": Target Unreachable, identifier 'bean' resolved to null
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:100)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:95)....

I tried to change my Bean annotations to @Model and tried different kind of Scopes but that didn't helped.
this is my index.xhtml page:
<!DOCTYPE html>

<h:head></h:head>
<h:body>
    <h:form id="genreForm">
        <h:outputLabel for="genre" value="genre" />
        <h:inputText id="genre" value="#{bean.genre}" label="genre" />

        <h:dataTable  id="genreList" value="#{bean.getGenreList()}" var="g" border="1">
            <h:column>
                <f:facet name="header">
                    Genre id
                </f:facet>
                #{g.genreId}
            </h:column>
            <h:column>
                <f:facet name="header">
                    Name
                </f:facet>
                #{g.genre}
            </h:column>
        </h:dataTable>
    </h:form>
</h:body>

this is my Bean:
@ManagedBean(name = "Bean", eager = true)
@SessionScoped
public class Bean {

private int genreId;
private String genre;

public void addGenre() {
    GenreDAO dao = new GenreDAOImpl();
    Genre myGenre = new Genre();
    myGenre.setGenre(genre);
    dao.save(myGenre);
}

public String getGenre() {
    return genre;
}

public void setGenre(String genre) {
    this.genre = genre;
}

public int getGenreId() {
    return genreId;
}

public void setGenreId(int genreId) {
    this.genreId = genreId;
}

public List<Genre> getGenreList() {
    GenreDAO dao = new GenreDAOImpl();
    List<Genre> list = dao.findAll();
    return list;
}
}

A: By default if you do not provide the managed bean name inside your @ManagedBean annotation the expression language expression used to acess your bean shouldn begin with first letter being in lower case. For example, if you have a following managed bean declaration
@ManagedBean
public class Bean {
    //some fields and methods
}

then you should access your bean with first letter being in lower case
<h:inputText value="#{bean.somePropertyName}">

But you can customize the name used to refer to the bean via @ManagedBean annotation's name attribute. In this case the EL expression you use to refer to your bean should spell the bean's name exactly as provided in your name attribute including the first letter. So if you have this in your code
@ManagedBean (name="Bean")
public class Bean

your bean should be accessed like this
<h:inputText value="#{Bean.somePropertyName}">

A: @ManagedBean(name = "Bean", eager = true)

Here you are setting the bean's name as "Bean" but you are trying to access it as "bean" in your el. Change either of them ot get it working.


text:
Q: Connecting Jetbrains DataGrip to a remote database via SSH I have an AWS Lightsail instance running the Bitnami configuration for Ubuntu 16.04.5 LTS and PHP7.
I can connect the the MySQL database using phpMyAdmin on the server via an SSH Tunnel.  But when I try to configure DataGrip for SSH access to the database I receive the error message "Host '127.0.0.1' is not allowed to connect to this MySQL server".
When I remove "localhost" from the host field of the General tab then I receive the error "ExecutionException: SSH: Unable to find host/port in URL".
The following test and response appears to show a successful connection to the port:
cat < /dev/tcp/###.###.###.###/22
SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.6

I'm using keypair auth. Both the user name and the Private key file are the same used for the ssh tunnel when running phpMyAdmin.
Not sure what to try next.  Any help appreciated.


text:
Q: File path from Camera Intent I'm trying to get the file path of pictures that I took with Camera Intent as a String, but the String filePath is always null. What am I doing wrong?
       public void onClick(View arg0) {
        switch (arg0.getId()) {
         case R.id.btnImageCapture:
            Intent openCamera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
               startActivityForResult(openCamera, OPEN_CAMERA);
                 break;
           }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         switch(requestCode){
         case OPEN_CAMERA:
             if (resultCode == RESULT_OK && data != null) {
                 Uri captureImage = data.getData();
                 String filePath = captureImage.getPath();
                 break;
              }
           }
        }

A: This is how I get the image that was taken with the camera.
I create the file before and when the image gets saved then it gets saved to my file..
File externalFile = new File("Whatever you want the path to be...");
Uri uriSavedImage=Uri.fromFile(externalFile);
Intent launchcameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
launchcameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(launchcameraIntent,CAMERA_PIC_REQUEST);

Then when the result is received.
protected void onActivityResult(int requestCode,int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CAMERA_PIC_REQUEST) {
                  Bitmap photo = BitmapUtils.decodeFileForDisplay(new File("Whatever your file's path is");
            }
        }
}

A: try the following passing your captureImage Uri as parameter:
    public String getRealPathFromURI(Uri contentUri) {
        String[] projx = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentUri, projx, null, null, null);
         int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

EDIT:
that is a common bug that getData() returns null on some devices. You need to use a pre-inserted Uri to prevent that. Example:
  Intent cameraIntent = new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
 preinsertedUri = getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new ContentValues());

        startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

Getting the result:
         @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {

    case CAMERA_PIC_REQUEST:

        if (resultCode != 0 && data != null) {

            Uri imageUri = preinsertedUri;
            }
              break;
                 }


text:
Q: Generic lambda, inheritance and trailing return type: is this valid code? Note: I'm opening an issue to clang, but I would like to be sure that my code is valid too.

I was trying to reply to another answer and I found some difficulties while playing with lambdas and inheritance.
Consider the following, minimal example:
template<typename Func>
struct Base: Func {
    Base(Func func): Func{func} {}

    template<typename... Args>
    auto operator()(Args... args)
    -> decltype(Func::operator()(args...), void()) {
        Func::operator()(args...);
    }
};

int main() {
    auto l = [](auto &&) {};
    Base<decltype(l)> mixin{l};
    mixin(0);
}

GCC 6.1 compiles it, clang 4.0 crashes.
Note that both compile just fine using the following definition:
auto l = [](int) {};

Is this valid code or I'm doing something that is not allowed by the standard?

Here is the link to the issue I've just opened.

A: Just if you need a solution for clang - the following code should work with clang
#include <utility>
#include <iostream>

template <typename F>
struct Base : F
{
  Base (F f) : F {f} {}

  template <typename... Args>
  decltype(auto) operator () (Args&&... args)
  {
    std::cout << "(";
    F::operator () (std::forward<Args> (args)...);
    std::cout << ")" << std::endl;
  }
};

int
main ()
{
  auto l = [] (auto && i) {
    std::cout << i;
  };
  Base<decltype(l)> mixin {l};
  mixin (0);
  return 0;
}


text:
Q: My cuda code crash using unified memory I'm newbie in cuda programmation. I have a problem with this code (it was written by my teacher):
#include <stdio.h>

#define THREAD_PER_BLOCK 128

__global__ void add(int *a,const int N){
    int index=threadIdx.x+blockIdx.x*blockDim.x;
    if (index<N)
      a[index] = a[index]+10;
}
int main( void ){
    int *a;
    // managed
    int i;
    int N=1024;
    int size = N * sizeof( int );

    cudaMallocManaged( &a, size );
    for(i=0; i<N; i++) {
        a[i]=i;
    }

    add<<< N/THREAD_PER_BLOCK, THREAD_PER_BLOCK >>>( a,N);
    cudaDeviceSynchronize();
    for (int i=0; i<10; i++){
        printf("%d %d\n", i, a[i]);
    }
    cudaFree( a );
    return 0;
}

I've detected a seg fault on fist for-loop, I have no idea of why the program crashes. My operative system is Ubuntu 14.04 and this is the output of querydevice:
Detected 1 CUDA Capable device(s)

Device 0: "GeForce 820M"
 CUDA Driver Version / Runtime Version          8.0 / 8.0
 CUDA Capability Major/Minor version number:    2.1
 Total amount of global memory:                 1985 MBytes (2081095680 bytes)
  ( 2) Multiprocessors, ( 48) CUDA Cores/MP:     96 CUDA Cores
  GPU Max Clock rate:                            1550 MHz (1.55 GHz)
  Memory Clock rate:                             900 Mhz
  Memory Bus Width:                              64-bit
  L2 Cache Size:                                 131072 bytes
  Maximum Texture Dimension Size (x,y,z)         1D=(65536), 2D=(65536, 65535), 3D=(2048, 2048, 2048)
  Maximum Layered 1D Texture Size, (num) layers  1D=(16384), 2048 layers
  Maximum Layered 2D Texture Size, (num) layers  2D=(16384, 16384), 2048 layers
  Total amount of constant memory:               65536 bytes
  Total amount of shared memory per block:       49152 bytes
  Total number of registers available per block: 32768
  Warp size:                                     32
  Maximum number of threads per multiprocessor:  1536
  Maximum number of threads per block:           1024
  Max dimension size of a thread block (x,y,z): (1024, 1024, 64)
  Max dimension size of a grid size    (x,y,z): (65535, 65535, 65535)
  Maximum memory pitch:                          2147483647 bytes
  Texture alignment:                             512 bytes
  Concurrent copy and kernel execution:          Yes with 1 copy engine(s)
  Run time limit on kernels:                     No
  Integrated GPU sharing Host Memory:            No
  Support host page-locked memory mapping:       Yes
  Alignment requirement for Surfaces:            Yes
  Device has ECC support:                        Disabled
  Device supports Unified Addressing (UVA):      Yes
  Device PCI Domain ID / Bus ID / location ID:   0 / 1 / 0
  Compute Mode:
     < Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >

deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 8.0, CUDA Runtime  Version = 8.0, NumDevs = 1, Device0 = GeForce 820M
Result = PASS

A: The problem here is that your GPU is a Fermi GPU (compute capability 2.x):
Device 0: "GeForce 820M"
 ...
 CUDA Capability Major/Minor version number:    2.1
                                                ^^^

and unified memory (for cudaMallocManaged) requires a compute capability 3.0 or higher GPU.
Any time you are having trouble with a CUDA code, it's good practice to use proper CUDA error checking before asking others for help.  Even if you don't understand the error output, it will be useful to others trying to help you.  In this case you would have gotten a concise error message that says that the cudaMallocManaged function is not supported.


text:
Q: how to Array inside Array Data in laravel I am trying to get array value in BLADE file. My array is shown below but I am not able to get value inside array.
I have get [student_levels]=> [level]  Data
laravel Code
foreach($items as $item)
{
    echo $item['student_levels']['level'];
}

$items is Array
Array
(
    [0] => Array
        (
            [_id] => 5c1e4295b0dace71ec62e325
            [email] => dhavalpansuriya1195@gmail.com
            [franchisecode] => MELHH
            [title] => Mr
            [firstname] => dhaval s
            [lastname] => patel
            [gender] => Male
            [age] => 16-18
            [phone] => 9601354880
            [address] => rajkot
            [city] => Ahmedabad
            [country] => India
            [tempcode] => hUmoEF
            [studentid] => HTNKLF
            [updated_at] => 2019-11-21 13:32:31
            [created_at] => 2018-12-22 19:26:37
            [student_status] => eda
            [student_levels] => Array
                (
                    [_id] => 5c8b11d2b0dace2f9a044d86
                    [student_id] => HTNKLF
                    [teacher_id] => 5c1e1ab5b0dace716e429654
                    [level_name] => recomended_level
                    [level] => Level 1
                    [comments] => hhbhhhh
                    [exam_type] => eda
                    [student_course] =>
                    [updated_at] => 2019-03-15 08:15:38
                    [created_at] => 2019-03-15 08:15:38
                )

        )

A: You have an array inside an array..so you can use foreach loop as
 @foreach($items as $item)
   {{$item['student_levels']['level']}}
 @endforeach

Or directly
{{$items[0]['student_levels']['level']}}

A: It seems your array is returning an array of students, you have an extra level in your array. So to fetch the first student level, you need to use the following code:
echo $item[0]['student_levels']['level'];

Maybe the code that fetches this data could be optimized to only fetch a single student, could you post this code?


text:
Q: Iterating over all unsigned integers in a for loop Let's say I want to iterate over all integers in a for loop. For the sake of discussion, assume I am calling some unknown function f(unsigned x) for each integer:
for (unsigned i = 0; i < UINT_MAX; i++) {
     f(i);
}

Of course, the above fails to iterate over all integers, because it misses one: UINT_MAX. Changing the condition to i <= UINT_MAX just results in an infinite loop, because that's a tautology.
You can do it with a do-while loop, but you lose all the niceties of the for syntax.
Can I have my cake (for loops) and eat it too (iterate over all integers)?

A: You'll have to perform the test at the end of the loop body, much like a do-while:
for (unsigned int i = 0; /* nothing */; i++) {
    ...
    if (i == UINT_MAX) {
        break;
    }
}

For a test in the standard for loop test position to work, you would need to track the current iteration in a way that can distinguish between UINT_MAX+2 states: one for each time you enter the loop body, and one for the one time you don't. A single unsigned int can't handle that, so you'd need at least one auxiliary variable or a bigger loop counter.

A:
You can do it with a do-while loop, but you lose all the niceties of
  the for syntax.

It is still doable with do-while loop by using an anonymous block scope:
{
    unsigned i = 0;
    do { f(i); } while (++i != 0);
}

While this construct may not be most idiomatic, it is an obvious candidate for clear assembly code. For example, gcc -O compiles it as:
.L2:
        mov     edi, ebx   ; ebx starts with zero
        call    f
        add     rbx, 1
        cmp     rbx, rbp   ; rbp is set with 4294967296
        jne     .L2

A: You could use another variable to detect when you've looped around.
for (unsigned int i = 0, repeat = 0; !(i == 0 && repeat); i++, repeat = 1) {
    ...
}

A: The classic way to implement your iteration efficiently, with a single test, is a do / while loop:
unsigned i = 0;
do { f(i); } while (i++ != UINT_MAX);

If you insist on using a for loop:
for (unsigned i = 0;; i++) {
    f(i);
    if (i == UINT_MAX)
        break;
}

Here is another variant with 2 variables where all the logic is inside the for expressions:
for (unsigned int i = 0, not_done = 1; not_done; not_done = (i++ - UINT_MAX)) {
    f(i);
}

It might produce slower code because of the extra variable, but as BeeOnRope commented, clang and icc compile it to very efficient code.

A: An easy solution would be,
unsigned i;
for (i=0; i<UINT_MAX; i++) {
  f(i);
}
f(i);  // i will be UINT_MAX at this time.

A: Use a larger integer type:
#include <limits.h>
#include <stdio.h>

int main() {
    for (unsigned long i = 0; i <= UINT_MAX; i++) {
        f(i);
    }
}

This version uses stdint for more consistency
#include <stdio.h>
#include <stdint.h>

int main() {
    for (uint_fast64_t i = 0; i <= UINT32_MAX; ++i) {
        f(i);
    }
}


text:
Q: Replace last 2 numeric values in pandas data frame by row with NAN's The last 2 real numbers in each row of my data were measured with error. I want to replace them with np.NAN. The number of real numbers differs by row (i.e., each row already has some NAN's at differing amount). Column headers indicate measurement number, index was a experimental trial.Values in a cell equal a measurement reading. Some trials had more measurement readings than others;thus, some rows have more NAN's than others.  The below code creates a data frame similar to mine.
   import pandas as pd
   import numpy as np
   data = np.array(([1,2,3,4,5,2,np.NaN],
   [2,2,3,2,3,np.NaN,np.NaN],[4,4,5,1,np.NaN,np.NaN,np.nan]))
   df1 = pd.DataFrame(data, columns = ['0','1','2','3','4','5','6'])

The data frame yielded from code that looks similar to mine:
       0    1   2   3   4   5   6
    0 1.0  2.0 3.0 4.0 5.0 2.0 NAN
    1 2.0  2.0 3.0 2.0 3.0 NAN NAN
    2 4.0  4.0 5.0 1.0 NAN NAN NAN

This is what I want the new data frame to look like:
      0    1    2   3   4   5   6
    0 1.0  2.0 3.0 4.0 NAN NAN NAN
    1 2.0  2.0 3.0 NAN NAN NAN NAN
    2 4.0  4.0 NAN NAN NAN NAN NAN

I have tryed counting the NAN and using that to locate the position of the last and second to last numeric values, but it gets me no where.
Ultimately, what I want to do is ignore the NAN's in the original data frame and take the last two real values (i.e., the integers) in a row and replace them with np.NAN. One of the main issues is the position of the last 2 real numbers in a row can differ by row. Making the original data frame look like the new data frame in the above examples.

A: Method #1 would be simply to shift everything over by 2 and keep the values which remain non-null:
In [61]: df.where(df.shift(-2, axis=1).notnull())
Out[61]:
     0    1    2    3   4   5   6
0  1.0  2.0  3.0  4.0 NaN NaN NaN
1  2.0  2.0  3.0  NaN NaN NaN NaN
2  4.0  4.0  NaN  NaN NaN NaN NaN

Method #2 would be to count the number of non-null values from the right, and only keep non-null values after the second:
In [62]: df.where((df.notnull().iloc[:, ::-1].cumsum(axis=1) > 2))
Out[62]:
     0    1    2    3   4   5   6
0  1.0  2.0  3.0  4.0 NaN NaN NaN
1  2.0  2.0  3.0  NaN NaN NaN NaN
2  4.0  4.0  NaN  NaN NaN NaN NaN

This isn't as pretty, but would allow for finer levels of customization if we needed to shift differently for each row, for example if it weren't true that we had a row of non-null values followed by null values.


text:
Q: paypal integration with .net application possibly a web service not a website i wanted to know if it is possible to integrate the paypal soap api with a .net wpf application or wcf service....i keep reading stuff about people integrating paypal with websites...thats not what i need...has anyone done this here??? if so can someone recommend which api package i need to use from paypal...what kind of account needs to be setup....
heres the scenario...i am writing a cc server that processes credit card transactions...the customers will not have and should not be required to have a paypal account...they just present the credit card info and my app/service should be able to either do a single auth or do an entire batch depending on the situation...i am not the seller in this scenario...and reading the docs is confusing me even more as to what are the basic requirements in terms of merchant account setup and other api requirements...
if paypal is not ideal for this scenario is there any other option....keep in mind there is no notion of a shopping cart here....
thanks

A: If it's a SOAP service, any website that integrates its functionality is just a GUI on top of code that's calling PayPal's webservices.
So, the short answer is yes, you should be able to call the service from any application, including your own SOA service interface.


text:
Q: One time retrieving data with Select2 jquery I have a problem with the select2 component (jQuery).
I have this as code:
        $('#username').select2({
        width: "400px",
        placeholder: "Selecteer 1 of meerder paritaire comités",
        style: "display; inline-block",
        minimumInputLength: 2,
        multiple: true,
        ajax: {
            url: "/Prospect/_LoadParComs/",
            dataType: "json",
            type: "GET",
            data: function (searchTerm) {
                return {
                    query: searchTerm
                }
            },
            results: function (data, page) {
                return { results: data }
            }
        }
    });

Now it works, everytime I click on the htmlelement my data gets called and I see the result. When I click an item the item gets on the htmlelement and ok. But everytime I click the element it goes back to retrieve my data and this takes time, 5 seconds at least.
Isn't it possible to load the data 1 time and work with it ? Without always having to get the data over and over again ?
kind regards


text:
Q: attach Firebase listeners to tableViewCell I have a chat feature in an iOS app. the chat previews are presented in a tableView and I am using a class for the TableView cells themselves. I want to listen for new messages so I can put a "new Message" label on the cells. The relevant parts of the tableView Cell are:
    var chat: Chat! {
    didSet {
        self.updateUI()
        self.observeNewMessages()
    }
    }

    extension ChatTableViewCell {

        func observeNewMessages() {

        let chatMessageIdsRef = chat.ref.child("messageIds")
        chatMessageIdsRef.observe(.childAdded, with: { snapshot in

        let messageId = snapshot.value as! String
        DatabaseReference.messages.reference().child(messageId).observe(.childAdded, with: { snapshot in
            //let message = Message(dictionary: snapshot.value as! [String : Any])

            print("looks like there is a new message") //works
            self.messageLabel.text = "New Message!"
            //self.delegate?.newMessage()
        })
        })
        }
    }

The print statement is there to test the listener. The problem I am having is when the table view loads and the cells get created, observeNewMessages() is executing the print statement regardless of whether there were new messages. It is just reading the old children that are already there first? Obviously this is going to cause the message label to always read "New Message." I'm not too good with Firebase so is there a better Firebase function to use or a better way to do this?
*I am using 2 queries because the Message dictionary will allow me to see if the current user made the message or not. The delegate is there because my next step will be to reload the tableview -- as it is now, this will also cause an infinite print statement loop...


text:
Q: Chain iterable with strip Is it possible to strip the iterable below without resorting to a list comprehension?
>>> values=f.df['AvailableInTerritories'].tolist()
>>> values
['AU, CA,GB,US', 'AU, CA, GB, US', 'AU, AT, CA, GB, US', 'AU, CA, GB, US', 'AU, CA, GB, US']
>>> list_separator=','

>>> [item.strip() for item in itertools.chain.from_iterable((str(_val).split(list_separator) for _val in values))]
['AU', 'CA', 'GB', 'US', 'AU', 'CA', 'GB', 'US', 'AU', 'AT', 'CA', 'GB', 'US', 'AU', 'CA', 'GB', 'US', 'AU', 'CA', 'GB', 'US']

A: Change your list_separator to ', ', so you don't need to use strip():
list_separator = ', '

And then use:
>>> list(itertools.chain.from_iterable((str(_val).split(list_separator) for _val in values)))
['AU', 'CA', 'GB', 'US', 'AU', 'CA', 'GB', 'US', 'AU', 'AT', 'CA', 'GB', 'US', 'AU', 'CA', 'GB', 'US', 'AU', 'CA', 'GB', 'US']

I assume you're interested in a non-list comprehension version. You can do:
values = ['AU, CA, GB, US', 'AU, CA, GB, US', 'AU, AT, CA, GB, US', 'AU, CA, GB, US', 'AU, CA, GB, US']
list_separator = ', '

lst = []
for x in values:
    lst.extend(x.split(list_separator))

print(lst)
# ['AU', 'CA', 'GB', 'US', 'AU', 'CA', 'GB', 'US', 'AU', 'AT', 'CA', 'GB', 'US', 'AU', 'CA', 'GB', 'US', 'AU', 'CA', 'GB', 'US']

A: You actually don't need itertools.chain, there's another much cleaner and efficient solution:
print([x for i in values for x in i.split(', ')])

Output:
['AU', 'CA', 'GB', 'US', 'AU', 'CA', 'GB', 'US', 'AU', 'AT', 'CA', 'GB', 'US', 'AU', 'CA', 'GB', 'US', 'AU', 'CA', 'GB', 'US']

A: One way using re.split
import re
print (re.split(',\s*', ','.join(values)))
#['AU', 'CA', 'GB', 'US', 'AU', 'CA', 'GB', 'US', 'AU', 'AT', 'CA', 'GB', 'US', 'AU', 'CA', 'GB', 'US', 'AU', 'CA', 'GB', 'US']