text:
Q: Getting Leaflet to work with Datatable selection in R shiny I have a Massmpg dataset just like the mpg dataset from ggplot but with the addition of City (from Massachusetts) , lat, and lng attributes.  I have made  shiny app which lets me select the city in a datatable but I cannot figure out how to get the leaflet map to focus only on the lat and lng in that city.  Instead the map just shows all the locations in the state.
Here is the code
library(shiny)
library(DT)
library(leaflet)
Massmpg <- (read.csv("Massmpg.csv"))

ui <- fluidPage(titlePanel("Mass mpg by location"),

                # Create a new Row in the UI for selectInputs
                fluidRow(
                    column(4,
                           selectInput("City",
                                       "City:",
                                       c("All",
                                         unique(as.character(Massmpg$City))))
                    ),
                    column(4,
                           selectInput("cyl",
                                       "cyl:",
                                       c("All",
                                         unique(as.character(Massmpg$cyl))))
                    ),
                    column(4,
                           selectInput("trans",
                                       "trans:",
                                       c("All",
                                         unique(as.character(Massmpg$trans))))
                    )
                ),
                # Create a new row for the table.
                leafletOutput("map01"),
                DT::dataTableOutput("table")

)

server <- function(input, output) {

        # Filter data based on selections
        output$table <- DT::renderDataTable(DT::datatable({
            data <- Massmpg
            if (input$City != "All") {
                data <- data[data$City == input$City,]
            }
            if (input$cyl != "All") {
                data <- data[data$cyl == input$cyl,]
            }
            if (input$trans != "All") {
                data <- data[data$trans == input$trans,]
            }
            data
        }))

        # map
        output$map01 <- renderLeaflet({
            #pal <- colorNumeric("YlOrRd", domain=c(min(quakes$mag), max(quakes$mag)))
            qMap <- leaflet(data = (Massmpg)) %>%
                addTiles() %>%
                addCircles(radius =3, color="red")
            qMap
        })

    }

shinyApp(ui = ui, server = server)

Matt thak you for your answer on reactive object.  I am trying it but not getting it to work. Here is my code with changes below.  I have links to the shinyapps page https://michaelcardio2020.shinyapps.io/TestFrame2/ and the Massmpg data in Box https://app.box.com/s/ryowy2x0h2owm3b1s18ok3342p5gharu
library(shiny)
library(DT)
library(leaflet)
Massmpg <- (read.csv("Massmpg.csv"))

# Define UI for application that draws a histogram
ui <- fluidPage(titlePanel("Mass mpg by location"),

                # Create a new Row in the UI for selectInputs
                fluidRow(
                    column(4,
                           selectInput("City",
                                       "City:",
                                       c("All",
                                         unique(as.character(Massmpg$City))))
                    ),
                    column(4,
                           selectInput("cyl",
                                       "cyl:",
                                       c("All",
                                         unique(as.character(Massmpg$cyl))))
                    ),
                    column(4,
                           selectInput("trans",
                                       "trans:",
                                       c("All",
                                         unique(as.character(Massmpg$trans))))
                    )
                ),
                # Create a new row for the table.
                leafletOutput("map01"),
                DT::dataTableOutput("table")

)

server <- function(input, output) {

    data <- reactive({
        x <- Massmpg
    })

        # Filter data based on selections
        output$table <- DT::renderDataTable(DT::datatable({
            data <- Massmpg
            if (input$City != "All") {
                data <- data[data$City == input$City,]
            }
            if (input$cyl != "All") {
                data <- data[data$cyl == input$cyl,]
            }
            if (input$trans != "All") {
                data <- data[data$trans == input$trans,]
            }
            data
        }))

        # map
        output$map01 <- renderLeaflet({
            Massmpg <- data()
            #pal <- colorNumeric("YlOrRd", domain=c(min(quakes$mag), max(quakes$mag)))
            qMap <- leaflet(data = (Massmpg)) %>%
                addTiles() %>%
                addCircles(radius =3, color="red")
            qMap
        })

    }

# Run the application
shinyApp(ui = ui, server = server)

A: You need to reference a reactive element in your leaflet map output. You can solve your issue with the following:

*

*Create reactive object that mirrors your data table object

*Reference that reactive object in both your data table and leaflet map

Make sure that call your reactive element with (). For example, if « table » is the name of your reactive, call it with table() in your output objects.


text:
Q: Is the Laplace transform essentially a generalized version of the Fourier transform? As a beginner, my understanding of Fourier and Laplace transformations is limited. However, it appears to me that the Fourier decomposes functions into a combination of waves, while the Laplace does the same thing except using exponentials.
Additionally, I also often hear that the Laplace can be applied to a broader range of functions than the Fourier, though the reason for this is unclear to me.
I would appreciate if someone could explain the current relationship between Fourier and Laplace transforms and give a short summary comparison.

*

*What are the differences/similarities between Laplace & Fourier in what they accomplish?

*What does the Laplace do that the Fourier does not which makes it apply to more functions?
If possible, I would like the explanation to be in simple language and without relying heavily on advanced mathematical jargon. Thank you.

A: A Google request like "differences Fourier Laplace" will provide you many many answers.
I react, very politely, to what @user1952009 has said. For me, and I am not alone, "Fourier Transform" and "Laplace Transform" are very different not only on a mathematical point of view, but also for practical needs.
Fourier Transform belongs to the huge "realm" of harmonic analysis, with a far-reaching extension in group theory.
Whereas Laplace Transform belongs to the domain of complex function theory with abscissas of convergence., etc., that have no equivalent in Fourier Transform theory and vice versa. See (materia.fisica.unipd.it/salasnich/dfl/dfl.pdf)
What is misleading is the similarity of computation rules. But, even on an engineering point of view, one should not say "Fourier = Laplace with $s$ replaced by $2 i \pi \nu$ (or $ i t$)". There are too many differences. One big difference among others: with Laplace, convolutions become products, but not in the other way, whereas, for Fourier, it works in both directions.

A: The Laplace transform is an important tool to study linear time evolution
problems where the situation at time $t=0$ is given. Thus consider ($i$ is
added for later convenience)
\begin{equation*}
\partial _{t}f(t)=iAf(t),\;t\geqslant 0
\end{equation*}
where $A$ is some operator. Then the complex Laplace transform
\begin{equation*}
\hat{f}(z)=\int_{0}^{\infty }dt\exp [izt]f(t),\;Imz>0
\end{equation*}
satisfies
\begin{equation*}
i[z-A]\hat{f}(z)=f(0)\Rightarrow \hat{f}(z)=-i[z-A]^{-1}f(0)
\end{equation*}
In particular the situation where $A$ is a self-adjoint operator in a
Hilbert space is important (think of the Schrödinger equation of quantum
mechanics where $A=H$, the Hamiltonian) . The point is that it is much easier to study the properties of $
A$ through its resolvent $[z-A]^{-1}$ than through the time evolution
operator $\exp [iAt]$.
Actually the Laplace transform above can be considered as a Fourier
transform. Thus set
\begin{equation*}
z=\omega +i\delta ,\;\delta >0
\end{equation*}
Then ($\theta (t)$ is the Heaviside step function)
\begin{equation*}
\hat{f}(\omega +i\delta )=\int_{-\infty }^{+\infty }dt\exp [i\omega t]\theta
(t)\exp [-\delta t]f(t)
\end{equation*}
so we are dealing with the Fourier transform of $\theta (t)\exp [-\delta
t]f(t)$. In case $f(t)$ is square integrable this immediately gives the
inverse Laplace transform
\begin{eqnarray*}
\theta (t)\exp [-\delta t]f(t) &=&\frac{1}{2\pi }\int_{-\infty }^{+\infty
}d\omega \exp [-i\omega t]\hat{f}(\omega +i\delta ) \\
f(t) &=&\frac{1}{2\pi }\int_{-\infty }^{+\infty }d\omega \exp [-i(\omega
+i\delta )t]\hat{f}(\omega +i\delta ) \\
&=&\frac{1}{2\pi }\int_{\Gamma }dz\exp [-izt]\hat{f}(z),\;t\geqslant 0
\end{eqnarray*}
where $\Gamma $ is the familiar Bromwich contour, a straight line parallel
to and above the real axis.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Not able to perform Touch To Call functionality in android I have implemented 'Touch To Call' functionality in my app and I have 3 buttons from which I directly make calls just by clicking on button. I have made calls on 100,101,112 numbers. The code is working perfectly for 100 and 101 but when I click on 112 button then it re directs me to keypad screen where I can make calls instead to making direct call. This is only happening with 112 number. I am just fed up with this. Please help.
Code for the same
       @Override
public void onClick(View view) {

    switch (view.getId()) {

        case R.id.imgBell112:
            checkCallPermission("112");
            break;

    }
}

public void checkCallPermission(String mobile) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
            {
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:" + mobile));
                startActivity(intent);
            }
        } else {
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CALL_PHONE)) {
                Toast.makeText(getActivity(), getResources().getString(R.string.kentoren_office_details_msg), Toast.LENGTH_LONG).show();
            }
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, CALL_REQUEST);
        }
    } else {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + mobile));
        startActivity(intent);

    }
}

A: It's probably because 112 is an emergency number in some countries (Germany for example) and they prevent the 'direct calling' to these numbers. You can verify that using the number 911.

A: You need to give permission for emergency number Manifest Permission CALL_PRIVILEGED in manifest
Dial like this
Uri uri = Uri.parse("tel://911");
Intent dialIntent = new Intent(Intent.ACTION_CALL,uri);
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_NO_USER_ACTION);
startActivity(dialIntent);

Hope maybe useful to you!


text:
Q: Getting Member Data From WhishList Member on Register I contacted WLM tech support and asked:

"I'm using the WishList Member API is there a way I could figure out if a new member has been added to Wishlist? I'd like to capture the newest member's name and email address and then use that it in my plugin."

They responded with:

"You can use wishlistmember_shoppingcart_register (action).
Called when a new member is signed-up via one of the shopping cart integrations. Information about the registration can be found in the $_POST variable."

I'm wondering how to do this... should I use an action?
add_action('wishlistmember_shoppingcart_register', 'get_member_info'));

function get_member_info(){
    //get $_POST
   // do stuff here
}

A: Please refer to the link below and read on how to use add_action correctly.
https://developer.wordpress.org/reference/functions/add_action/
add_action('wishlistmember_shoppingcart_register', 'get_member_info'));

function get_member_info() {
    // Debug $_POST.
    echo '<pre>';
    var_dump($_POST);
    exit;
}


text:
Q: Reading ASCII file in Python (numpy-array?) I have a problem reading ASCII file in Python. Here's an example of the file: http://pastebin.com/CTwwPPKA
I tried using numpy's genfromtxt:
data = np.genfromtxt("example.txt")

But this way I cannot read dates and times properly since they should be datetime objects.
On the other hand, loadtxt can only read float values, which is also not acceptable.
Could you please suggest me a way to properly read that kind of file?

A: You want to use csv.reader() with the csv.excel_tab dialect.
Examples of csv usage

A: you have to use dtype option here.
x = np.genfromtxt("example.txt", dtype=None)
print(x[0])

and you will get
('DATA', 34967565, '2011-08-04', '19:00:00:081', 0.0272448, -0.17718500000000001, 4.2143899999999999, 524.57600000000002, 17.485499999999998, 101.07599999999999, 0.45927400000000002, 0.19031300000000001, 0.100296, 0.97492599999999996, 1.94354, 100.73399999999999, 12.538600000000001, 10.3786, 44318.5, 39605.5, 39234.5, 40298.0, 68)

The trick here is that you have to specify dtype to None so that numpy can automatically recognize strings and numbers, while the default dtype is float.
Then you can use datetime.strptime to convert the strings to datetime objects accordingly.


text:
Q: imacros extraction from a range of data Hi here is how my page looks like

 Beamer

 menu1

 menu2

 menu3

 menu4

 Beamer2

 menu21

 menu22

 menu23

 menu24

 Beamer3

 menu31

 menu32

 menu33

 menu34

How can I extract only elements  under  Beamer-1  only ?  Note the number of elements under this group may also vary from time to time. Thanks

A: I suggest solving this issue with a number of pseudo-URLs:
' get bounds
URL GOTO=javascript:{var<SP>doc=window.document;var<SP>els=doc.getElementsByTagName("div");for(i=0;i<els.length;i++){var<SP>b=(els[i].outerHTML.match("Beamer-1"))<SP>?<SP>(i+1)<SP>:<SP>b;var<SP>e=(els[i].outerHTML.match("Beamer-2"))<SP>?<SP>i<SP>:<SP>e;}}
' set extract
URL GOTO=javascript:{var<SP>ext="";for(i=b;i<e;i++){ext+=els[i].innerHTML.trim()+((i==e-1)<SP>?<SP>""<SP>:<SP>"[EXTRACT]");}underfined;}
' create dummy element
URL GOTO=javascript:{var<SP>elt=doc.createElement("input");elt.type="hidden";elt.id="myHiddenExtract";elt.value=ext;doc.getElementsByTagName("html")[0].appendChild(elt);underfined;}
' get extract
TAG POS=1 TYPE=INPUT ATTR=ID:myHiddenExtract EXTRACT=TXT
' remove dummy element
URL GOTO=javascript:{doc.getElementsByTagName("html")[0].removeChild(doc.getElementById("myHiddenExtract"));underfined;}


text:
Q: Animation problems in iOS I used some animations in my application.Its working fine.But while calling another animation previous animation comes old position.How to resolve these kind of problems.
Here my code:
    CGRect frame = self.PickerView.frame;
    frame.origin.x=0;
    frame.origin.y=730;

    [UIView beginAnimations:nil context:nil];

    [UIView setAnimationDuration:1.0];

    self.PickerView.frame=frame;

    [UIView commitAnimations];


text:
Q: Best way to find first non repeating character in a string What would be the best space and time efficient solution to find the first non repeating character for a string like aabccbdcbe?
The answer here is d. So the point that strikes me is that it can be done in two ways:

*

*For every index i loop i-1 times and check if that character occurs ever again. But this is not efficient: growth of this method is O(N^2) where N is the length of the string.

*Another possible good way could be if I could form a tree or any other ds such that I could order the character based on the weights (the occurrence count). This could take me just one loop of length N through the string to form the structure. That is just O(N) + O(time to build tree or any ds).

A: A list comprehension will give you the characters in the order they appear if they only appear once:
In [61]: s = 'aabccbdcbe'

In [62]: [a for a in s if s.count(a) == 1]
Out[62]: ['d', 'e']

Then just return the first entry of this:
In [63]: [a for a in s if s.count(a) == 1][0]
Out[63]: 'd'

If you just need the first entry, a generator would work as well:
In [69]: (a for a in s if s.count(a) == 1).next()
Out[69]: 'd'

A: I think that removing of the repeating characters from the string may significantly reduce the number of operations. For example:
s = "aabccbdcbe"
while s != "":
    slen0 = len(s)
    ch = s[0]
    s = s.replace(ch, "")
    slen1 = len(s)
    if slen1 == slen0-1:
        print ch
        break;
else:
    print "No answer"

A: The speed of the search depends on several factors:

*

*the length of the string

*the position before which there is not a one-time-occuring character

*the size of the string after this position

*the number of different characters occuring in the string

.
In the following code, I firstly define a string s
with the help of random.choice() and the a group of one-time-occurring characters named unik  ,
from two strings s1 and s2 that I concatenate : s1 + s2
where:

*

*s1 is a string of length nwo in which there is NOT ANY one-time-occurring character

*s2 is a string of length nwi in which THERE IS one-time-occurring characters

.
#### creation of s from s1 and s2 #########

from random import choice

def without(u,n):
    letters = list('abcdefghijklmnopqrstuvwxyz')
    for i in xrange(n):
        c = choice(letters)
        if c not in unik:
            yield c

def with_un(u,n):
    letters = list('abcdefghijklmnopqrstuvwxyz')
    ecr = []
    for i in xrange(n):
        c = choice(letters)
        #ecr.append('%d %s  len(letters) == %d' % (i,c,len(letters)))
        yield c
        if c in unik:
            letters.remove(c)
    #print '\n'.join(ecr)

unik = 'ekprw'
nwo,nwi = 0,500
s1 = ''.join(c for c in without(unik,nwo))
s2 = ''.join(c for c in with_un(unik,nwi))
s = s1 + s2

if s1:
    print '%-27ss2 : %d chars' % ('s1 : %d chars' % len(s1),len(s2))
    for el in 'ekprw':
        print ('s1.count(%s) == %-12ds2.count(%s) == %d'
               % (el,s1.count(el),el,s2.count(el)))
    others = [c for c in 'abcdefghijklmnopqrstuvwxyz' if c not in unik]
    print 's1.count(others)>1 %s' % all(s1.count(c)>1 for c in others)
else:
    print "s1 == ''     len(s2) == %d" % len(s2)
    for el in 'ekprw':
        print ('   -         s2.count(%s) == %d'
               % (el,s2.count(el)))
print 'len of s  == %d\n' % len(s)

Then there is the benchmarking.
Varying the numbers nwo and nwi we see the influence on the speed:
### benchmark of three solutions #################

from time import clock

# Janne Karila
from collections import Counter, OrderedDict
class OrderedCounter(Counter, OrderedDict):
    pass
te = clock()
c = OrderedCounter(s)
rjk = (item for item, count in c.iteritems() if count == 1).next()
tf = clock()-te
print 'Janne Karila  %.5f    found: %s' % (tf,rjk)

# eyquem
te = clock()
candidates = set(s)
li = []
for x in s:
    if x in candidates:
        li.append(x)
        candidates.remove(x)
    elif x in li:
        li.remove(x)
rey = li[0]
tf = clock()-te
print 'eyquem        %.5f    found: %s' % (tf,rey)

# TyrantWave
te = clock()
rty = (a for a in s if s.count(a) == 1).next()
tf = clock()-te
print 'TyrantWave    %.5f    found: %s' % (tf,rty)

.
Some results
With s1 of null length, nwo = 0 and nwi = 50:
s1 == ''     len(s2) == 50
   -         s2.count(e) == 1
   -         s2.count(k) == 1
   -         s2.count(p) == 1
   -         s2.count(r) == 1
   -         s2.count(w) == 1
len of s  == 50

Janne Karila  0.00077    found: e
eyquem        0.00013    found: e
TyrantWave    0.00005    found: e

TyrantWave's solutions is the faster because the first one-occurring-char is found rapidly in the first positions of the string
.
With nwo = 300 and nwi = 50
(hereafter 401 chars for s1 because occurrences of one-time-occurring chars weren't retained during construct of s1, see function without() )
s1 : 245 chars             s2 : 50 chars
s1.count(e) == 0           s2.count(e) == 1
s1.count(k) == 0           s2.count(k) == 1
s1.count(p) == 0           s2.count(p) == 1
s1.count(r) == 0           s2.count(r) == 1
s1.count(w) == 0           s2.count(w) == 1
s1.count(others)>1 True
len of s  == 295

Janne Karila  0.00167    found: e
eyquem        0.00030    found: e
TyrantWave    0.00042    found: e

This time TyrantWave's solution is longer than mine because it has to count occurrences of all the characters in the first part of s that is to say in s1 in which there are no one-time-occurring characters (they are in the second part s2)
However, to obtain a more short time with my solution, nwo needs to be notably greater than nwi
.
With nwo = 300 and nwi = 5000
s1 : 240 chars             s2 : 5000 chars
s1.count(e) == 0           s2.count(e) == 1
s1.count(k) == 0           s2.count(k) == 1
s1.count(p) == 0           s2.count(p) == 1
s1.count(r) == 0           s2.count(r) == 1
s1.count(w) == 0           s2.count(w) == 1
s1.count(others)>1 True
len of s  == 5240

Janne Karila  0.01510    found: p
eyquem        0.00534    found: p
TyrantWave    0.00294    found: p

If length of s2 is raised, then TyrantWave's solution is better again.
.
Conclude what you want
.
EDIT
Terrific idea of Roman !
I added the solution of Roman in my benchmarking, and it won !
I also did some tiny modifications that improve his solution.
# Roman Fursenko
srf = s[:]
te = clock()
while srf != "":
    slen0 = len(srf)
    ch = srf[0]
    srf = srf.replace(ch, "")
    slen1 = len(srf)
    if slen1 == slen0-1:
        rrf = ch
        break
else:
    rrf = "No answer"
tf = clock()-te
print 'Roman Fursenko %.6f    found: %s' % (tf,rrf)

# Roman Fursenko improved
srf = s[:]
te = clock()
while not(srf is ""):
    slen0 = len(srf)
    srf = srf.replace(srf[0], "")
    if len(srf) == slen0-1:
        rrf = ch
        break
else:
    rrf = "No answer"
tf = clock()-te
print 'Roman improved %.6f    found: %s' % (tf,rrf)

print '\nindex of %s in the string :  %d' % (rty,s.index(rrf))

.
The results are:
.
s1 == ''     len(s2) == 50
   -         s2.count(e) == 1
   -         s2.count(k) == 1
   -         s2.count(p) == 1
   -         s2.count(r) == 1
   -         s2.count(w) == 1
len of s  == 50

Janne Karila   0.0032538    found: r
eyquem         0.0001249    found: r
TyrantWave     0.0000534    found: r
Roman Fursenko 0.0000299    found: r
Roman improved 0.0000263    found: r

index of r in the string :  1

s1 == ''     len(s2) == 50
   -         s2.count(e) == 1
   -         s2.count(k) == 0
   -         s2.count(p) == 1
   -         s2.count(r) == 1
   -         s2.count(w) == 1
len of s  == 50

Janne Karila   0.0008183    found: a
eyquem         0.0001285    found: a
TyrantWave     0.0000550    found: a
Roman Fursenko 0.0000433    found: a
Roman improved 0.0000391    found: a

index of a in the string :  4

>
s1 : 240 chars             s2 : 50 chars
s1.count(e) == 0           s2.count(e) == 1
s1.count(k) == 0           s2.count(k) == 0
s1.count(p) == 0           s2.count(p) == 1
s1.count(r) == 0           s2.count(r) == 1
s1.count(w) == 0           s2.count(w) == 1
s1.count(others)>1 True
len of s  == 290

Janne Karila   0.0016390    found: e
eyquem         0.0002956    found: e
TyrantWave     0.0004112    found: e
Roman Fursenko 0.0001428    found: e
Roman improved 0.0001277    found: e

index of e in the string :  242

s1 : 241 chars             s2 : 5000 chars
s1.count(e) == 0           s2.count(e) == 1
s1.count(k) == 0           s2.count(k) == 1
s1.count(p) == 0           s2.count(p) == 1
s1.count(r) == 0           s2.count(r) == 1
s1.count(w) == 0           s2.count(w) == 1
s1.count(others)>1 True
len of s  == 5241

Janne Karila   0.0148231    found: r
eyquem         0.0053283    found: r
TyrantWave     0.0030166    found: r
Roman Fursenko 0.0007414    found: r
Roman improved 0.0007230    found: r

index of r in the string :  250

I've learned something thanks to the code of Roman:
s.replace() creates a new string and I thought that, because of that, it was a slow method.
But, I don't know for which reason, it is a really fast method.
.
EDIT 2
The Oin's solution is worst:
# Oin
from operator import itemgetter
seen = set()
only_appear_once = dict()
te = clock()
for i, x in enumerate(s):
  if x in seen and x in only_appear_once:
    only_appear_once.pop(x)
  else:
    seen.add(x)
    only_appear_once[x] = i
  fco = min(only_appear_once.items(),key=itemgetter(1))[0]
tf = clock()-te
print 'Oin            %.7f    found: %s' % (tf,fco)

results
s1 == ''     len(s2) == 50
Oin            0.0007124    found: e
Janne Karila   0.0008057    found: e
eyquem         0.0001252    found: e
TyrantWave     0.0000712    found: e
Roman Fursenko 0.0000335    found: e
Roman improved 0.0000335    found: e

index of e in the string :  2

s1 : 237 chars             s2 : 50 chars
Oin            0.0029783    found: k
Janne Karila   0.0014714    found: k
eyquem         0.0002889    found: k
TyrantWave     0.0005598    found: k
Roman Fursenko 0.0001458    found: k
Roman improved 0.0001372    found: k

index of k in the string :  246

s1 : 236 chars             s2 : 5000 chars
Oin            0.0801739    found: e
Janne Karila   0.0155715    found: e
eyquem         0.0044623    found: e
TyrantWave     0.0027548    found: e
Roman Fursenko 0.0007255    found: e
Roman improved 0.0007199    found: e

index of e in the string :  244

A: collections.Counter counts efficiently(*) and collections.OrderedDict remembers the order in which items were first seen. Let's use multiple inheritance to combine the benefits:
from collections import Counter, OrderedDict

class OrderedCounter(Counter, OrderedDict):
    pass

def first_unique(iterable):
    c = OrderedCounter(iterable)
    for item, count in c.iteritems():
        if count == 1:
            return item

print first_unique('aabccbdcbe')
#d
print first_unique('abccbdcbe')
#a

Counter uses its superclass dict to store the counts. Defining class OrderedCounter(Counter, OrderedDict) inserts OrderedDict between Counter and dict in method resolution order, adding the ability to remember insertion order.
(*) This is O(n) and efficient in that sense, but not the fastest solution, as benchmarks show.

A: Here's a very straightforward O(n) solution:
def fn(s):
  order = []
  counts = {}
  for x in s:
    if x in counts:
      counts[x] += 1
    else:
      counts[x] = 1
      order.append(x)
  for x in order:
    if counts[x] == 1:
      return x
  return None

We loop through the string once.  When we come across a new character, we store it in counts with a value of 1, and append it to order.  When we come across a character we've seen before, we increment its value in counts.  Finally, we loop through order until we find a character with a value of 1 in counts and return it.

A: Here is an approach with good set of chars and bad set of chars (which appear more than one time):
import timeit
import collections
import operator
import random

s = [chr(i) for i in range(ord('a'), ord('z')) for j in range(100)] + ['z']

random.shuffle(s)
s = ''.join(s)

def good_bad_sets(s):
    setbad = set()
    setgood = set()
    for char in s:
        if(char not in setbad):
            if(char in setgood):
                setgood.remove(char)
                setbad.add(char)
            else:
                setgood.add(char)
    return s[min([s.index(char) for char in setgood])] if len(s) > 0 else None

def app_once(s):
    seen = set()
    only_appear_once = set()
    for i in s:
      if i in seen:
        only_appear_once.discard(i)
      else:
        seen.add(i)
        only_appear_once.add(i)
    return s[min([s.index(char) for char in only_appear_once])] if len(only_appear_once) > 0 else None

print('Good bad sets: %ss' % timeit.Timer(lambda : good_bad_sets(s)).timeit(100))
print('Oin\'s approach: %ss' % timeit.Timer(lambda : app_once(s)).timeit(100))
print('LC: %ss' % timeit.Timer(lambda : [a for a in s if s.count(a) == 1][0]).timeit(100))

I've compared it to the LC approach and somewhere around 50 chars the good and bad set approach becomes faster. Comparison of this approach vs. Oin's vs LC:
Good bad sets: 0.0419239997864s
Oin's approach: 0.0803039073944s
LC: 0.647999048233s

A: So from the definition of the problem, it's clear that you need an O(n) solution, which means only going through the list once. All of the solutions which use a form of count are wrong, since they go through the list again in that operation. So you need to keep track of the counts yourself.
If you only had characters in that string, then you don't need to worry about storage and you could just use the character as a key in a dict. The values in that dict will be the index of the character in the string s. At the end we have to see which one was the first by calculating the minimum of the dictionary's values. This is an O(n) operation on a (possibly) shorter list than the first.
The total will still be O(c*n) therefore O(n).
from operator import itemgetter

seen = set()
only_appear_once = dict()

for i, x in enumerate(s):
  if x in seen and x in only_appear_once:
    only_appear_once.pop(x)
  else:
    seen.add(x)
    only_appear_once[x] = i

first_count_of_one = only_appear_once[min(only_appear_once.values(), key=itemgetter(1))]


text:
Q: Playing an HTTP audio stream on an HTTPS site without warnings In a site that otherwise fully uses HTTPS, I'm playing a HTTP radio stream using the <audio> element. This causes the browser to show a warning sign in the address bar that unsecure elements are present in the page.
I tried putting the <audio> inside an <iframe>, but at least Chrome wasn't fooled that easily.
The radio stream is outside my control and not available via HTTPS. I could pipe it through an HTTPS proxy, but that would be costly.
Is there any other way to play the stream without any warnings, in modern browsers? (I'm assuming there isn't, because I'd consider it a bug in that browser.)

A: Your assumption is correct. If you did find a way to do what you are asking, you should definitely file a bug report with the browser vendor, as that would be a serious security vulnerability. Not to mention the fact that, should you succeed, informed users would no longer be able to trust the security of your site.


text:
Q: Deleted Sudo and Can't Access Grub I deleted sudo, and I can't access grub so that I can restore it. I have a bad feeling that I don't have grub. Is there any possible way to restore it? apt-get doesn't work on my computer either.

A: You can work it out by chrooting into your Debian/Ubuntu system from any other LiveCD or LiveUSB distribution. Suppose you boot your computer with a Debian LiveCD:
# Mount your file systems as specified in your system's fstab
# e.g. into /mnt

# Mount the virtual filesystems before chrooting
for DIR in sys proc dev dev/pts; do mount -o bind $DIR /mnt/$DIR; done

# now chroot into your system
chroot /mnt /bin/bash

From then on just run commands as if you were in a terminal on your initial system. When you're done, run sync and reboot into your repaired system.
Note I think this might not work as expected if your system uses SELinux. You'll have to try first.


text:
Q: Use QTimer to run functions in an infinte loop I'm new to Python and still trying to learn, but I couldn't handle this problem. I want to run some functions (which are in class) in an infinite loop. Because it is a QApplication, I've learned that I should do it with a QTimer. However, when exploring how to do it, I couldn't find a working alternative. A common solution is:
timer = QTimer()
timer.timeout.connect(function)
timer.start(60000)

But when I insert these into my code it makes no difference. I have tried to insert it under functions, class, etc, but couldn't get a result. My functions to loop are here:
__author__ = 'pc'
import requests
from bs4 import BeautifulSoup
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
import sqlite3
import sys, getopt, time
from PyQt5.QtCore import QTimer

records = []
def scrape_page(url, html):
    soup = BeautifulSoup(html, 'html.parser')
    data = soup.find('div', class_='tablo_dual_board')
    try:
        datas = data.text.splitlines()
        datas1 = list(filter(None, datas))
        records.append(datas1)
    except:
        pass

def process_records():
    # add record to database ...
    print('process records:', len(records))

def generate_urls():
    onexurl = "https://1xbahis19.com/en/live/Football/"
    reply = requests.get(onexurl)
    soup = BeautifulSoup(reply.content, "html.parser")
    income = soup.find_all("ul", {"id":"games_content"})
    links = soup.find_all("a", {"class": "c-events__name"})
    urls = []
    for matchlink in links:
        urls.append("https://1xbahis19.com/en/"+(matchlink.get("href")))
    return urls

class WebPage(QtWebEngineWidgets.QWebEnginePage):
    def __init__(self):
        super(WebPage, self).__init__()
        self.loadFinished.connect(self.handleLoadFinished)

    def start(self, urls):
        self._urls = iter(urls)
        self.fetchNext()

    def fetchNext(self):
        try:
            url = next(self._urls)
        except StopIteration:
            return False
        else:
            self.load(QtCore.QUrl(url))
        return True

    def processCurrentPage(self, html):
        scrape_page(self.url().toString(), html)
        if not self.fetchNext():
            process_records()
            print(records)
            QtWidgets.qApp.quit()

    def handleLoadFinished(self):
        self.toHtml(self.processCurrentPage)

app = QtWidgets.QApplication(sys.argv)
webpage = WebPage()
webpage.start(generate_urls())
timer = QTimer()
timer.timeout.connect(WebPage)
timer.start(60000)
app.exec_()

Can anyone help with this please?

A: I assume you want to run the scraper at regular intervals. The script below will scrape all the urls once every 60 seconds. The signal part is there to provide a way to terminate the infinite loop - just do Ctrl+C (i.e. KeyboardInterrupt), and it will stop immediately.
import requests
from bs4 import BeautifulSoup
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
import sqlite3
import sys, getopt, time
from PyQt5.QtCore import QTimer

import signal
# press Ctrl+C to stop the script
signal.signal(signal.SIGINT, signal.SIG_DFL)

records = []
def scrape_page(url, html):
    print('scraping page:', url)
    soup = BeautifulSoup(html, 'html.parser')
    data = soup.find('div', class_='tablo_dual_board')
    try:
        datas = data.text.splitlines()
        datas1 = list(filter(None, datas))
        records.append(datas1)
    except:
        pass

def process_records():
    # add record to database ...
    print('processed records:', len(records))
    # clear the current records
    del records[:]
    # re-run after a timeout
    QTimer.singleShot(60000, run)

def run():
    print('running scraper...')
    webpage.start(generate_urls())

def generate_urls():
    print('generating urls...')
    onexurl = "https://1xbahis19.com/en/live/Football/"
    reply = requests.get(onexurl)
    soup = BeautifulSoup(reply.content, "html.parser")
    income = soup.find_all("ul", {"id":"games_content"})
    links = soup.find_all("a", {"class": "c-events__name"})
    urls = []
    for matchlink in links:
        urls.append("https://1xbahis19.com/en/"+(matchlink.get("href")))
    return urls

class WebPage(QtWebEngineWidgets.QWebEnginePage):
    def __init__(self):
        super(WebPage, self).__init__()
        self.loadFinished.connect(self.handleLoadFinished)

    def start(self, urls):
        self._urls = iter(urls)
        self.fetchNext()

    def fetchNext(self):
        try:
            url = next(self._urls)
        except StopIteration:
            return False
        else:
            self.load(QtCore.QUrl(url))
        return True

    def processCurrentPage(self, html):
        scrape_page(self.url().toString(), html)
        if not self.fetchNext():
            process_records()

    def handleLoadFinished(self):
        self.toHtml(self.processCurrentPage)

app = QtWidgets.QApplication(sys.argv)
webpage = WebPage()
run()
app.exec_()


text:
Q: print the content of a div I need to print whole content of a div. Notice scroll in the div.
But when I use Window.print() to print its content, it prints only the visible part on the screen. I want to print all 154 records in the grid, but it prints only 21 records.

Note: I don't want to open a new window.
EDIT:
javascript function()
{
1. Hide divs that you don't want to print
2. window.print()
3. show the divs you hide in step 1
}

A: The strongest solution I think is to create an iframe, copy the contents to be printed to that frame, then print it. There are JQuery plugins for this. Duplicate: Print the contents of a DIV
Another possibility is to have a print CSS that hides the stuff that you don't want to print (menus etc.), and also removes the min-height on your table, causing the scrollbar to be removed.

A: Use  style sheet with a media type of print -
link rel="stylesheet" type="text/css" media="print" href="print.css"

And change the DIV style -
height:auto;
overflow:auto

When printing (use window.print()) the DIV will increase in height, and hide all the other DIVs.

A: Try this, But first include this library
$('YourDiv').printElement();

Or
Read this article on Div Printing

A: https://github.com/jasonday/jquery.printThis
I wrote the above plugin based on several others, that allows for printing of an element on a page (no popup) and maintaining page styles or loading new css styles specifically for the print element.

A: I used printThis and it works great with div's that have a fixed height and scrollbar.   removeInline: true property prints the entire document even though you can see only a part of it in the div.
function printpage(divId, title) {
                    var divID = "#" + divId;
                    var divTitle = title;
                    $(divID).printThis({
                        debug: false,
                        importCSS: true,
                        importStyle: true,
                        printContainer: true,
                        pageTitle: divTitle,
                        removeInline: true,
                        printDelay: 333,
                        header: null,
                        formValues: true
                    });

                }


text:
Q: Rotating a Text Field in as3 I am working on a Flash Project in which i have to rotate a text field.I am Rotating the text field using this function---
**function rotateAroundCenter(ob:*, angleDegrees)
{

    var m:Matrix = ob.transform.matrix;
    m.tx -=  point.x;
    m.ty -=  point.y;
    m.rotate(angleDegrees*(Math.PI/180));
    m.tx +=  point.x;
    m.ty +=  point.y;
    ob.transform.matrix = m;
}**

var point:Point = new Point(mc.x+ mc.width / 2,mc.y+ mc.height / 2);

i am calculating the center point of mc containing the textfield using the above method.
I Have also povided the dragging feature so that one can drag the text field.
 The problem is when i rotate the text field say 45 degrees and then  i drag it to other position now if i rotate the text field again it is not rotating about its center or origin, it rotates about some other point that is calculated by the same method ---mc.x+ mc.width / 2,mc.y+ mc.height / 2---
How do i calculate the perfect origin of a  text field at any angle of rotation.

A: You're rotating mc or textfield? If you're rotating textfield, so you have to get width from it.
Rotating textfield and dragging mc is best for performance.
rotateAroundCenter(textField, 45);
var point:Point = new Point(textField.width / 2, textField.height / 2);

A: Use the search, man... here is example with Rotate effect. You can adapt the math from there.


text:
Q: Selenium cant find the xpath element So I am making a script to generate icloud mails and in the apple wbesite there is a button that selenium cant find and this error is displayed in the console:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/aside/div/div[1]/div/div/div[2]/section[1]/div/div/div[1]/div/div[1]/button"}

browser = webdriver.Chrome('chromedriver.exe')
browser.get(r'https://appleid.apple.com/sign-in?returnUrl=https%3A%2F%2Fappleid.apple.com%2Faccount%2Fmanage%2Fsection%2Fprivacy&appId=93')
print("login your icloud account and press keep me singed in")
login = input("Press enter when you have logged in")

#enter the email part
browser.find_element("xpath", '/html/body/div[1]/div[3]/main/div/div[2]/div[4]/div/div[1]/div/div[1]/div/button/div/div[1]/div').click()
time.sleep(5)

#press the add email button(doesnt work)
create= browser.find_element("xpath", '/html/body/aside/div/div[1]/div/div/div[2]/section[1]/div/div/div[1]/div/div[1]/button')
create.click()

so the last part is the part that doesnt work, where it tries to press the add email button but it displays the error shown above, ive tried selecting other elements and nothing seems to work. Would appriciate some help:)
This image is the button that I was trying to click with selenium.

I tried to click the button ut the error shows up whatever I do.


text:
Q: Cant link to Python with FindPython cmake module I'm trying to link to Python interpreter so I can run some python code in my C++ app. I'm using CMake 3.12 as a build system. It has a new module to load Python and the docs says that I should link to Python::Interpreter. This is my code:
In root CMakeLists.txt I have:
find_package(Python COMPONENTS Interpreter)

I have a subdirectory which adds some more subdirs depending on the found libraries:
if (TARGET Python::Interpreter)
    add_subdirectory(Plotter)
endif()

Finally, in my application I link to Python:
set(SOURCES
    main.cpp
    plotter.cpp
)

set(HEADERS
    plotter.h
)

set(RESOURCES
    resources.qrc)

add_executable(Plotter ${SOURCES} ${HEADERS} ${RESOURCES})
target_link_libraries(Plotter Qt5::Core fmt::fmt Python::Interpreter)

The error I'm getting is:
Target "Plotter" links to target "Python::Interpreter" but the target was not found.

This is really strange, because I'm explicitly checking the Python target exists before adding the application using it.
Any idea what its wrong here?


text:
Q: Is it possible to upgrade Tinymce to v5.x in Joomla? The current latest Joomla! v3.9.14 (August 2019)
The integrated tinymce is v4.5.11
Tinymce released the new V.5.0.0 in February 2019, including major improvements and a great new API
I want to use a plugin written with the new V5 API in Joomla!, so I wondered if it's possible to upgrade Tinymce to V5 in Joomla, or if we have no choice but to still use the old ugly Tinymce v4.x?
I tried to replace/edit files in media/editors/tinymce, just to see if it could lead to something, but of course it doesn't seem to be the right direction.

A: Rather than replacing the files (which could be overwritten in any future update), you're probably better off writing a new plugin for Joomla that installs Tiny 5.
The source code for the (v4) TinyMCE plugin is a good place to start to write your own - replicate how this plugin works, and you'll need to extend its functionality.
Doing it this way also means you could choose to use the Cloud version of Tiny, meaning you don't need to host the files locally, and receive updates as Tiny push them live. You do need a Tiny API key for this, but IMO, I feel it is a smarter way to host Tiny given that even during 5's life in 2019, some really useful features have been deployed, and if you're hosting all the files yourself, you'll need to keep updating them as you go.
The challenge with writing your own Tiny 5 Joomla plugin is that the core TinyMCE plugin for Joomla does not make it possible to have externally hosted Tiny plugins (such as a custom one you've created). So you would need to extend both the configuration and the instantiation to be able to store external plugin configuration, pull it in to Tiny's config, and also be able to manage your toolbars.
At Joomla Day Australia 2019 I spoke about developing external plugins for Tiny 5 in Joomla 4, and have a plugin that uses the cloud version of Tiny, and allows for external plugin configuration - but this was for an alpha version of Joomla 4.
Joomla 4 will come with Tiny 5, and I did a pull request to get external plugins in to the Editor config, so just waiting for Joomla 4 could be a more passive option.


text:
Q: Why can't I get the Text component of an Input Field I have a TextMeshPro Input Field but my various attempts at getting the Text component are producing null reference exceptions. The Input Field is called Name. I reference this object when the player clicks OK after submitting their name.
Here is the GetName script:
public class GetName : MonoBehaviour
{
    GameObject Name;

    // These two are left over from previous attempts.
    public TextMeshProUGUI player_name;
    public TMP_InputField player_inputField;

    private string monicker;

    // Integer function should be less bother than a bool when called from another script.

    public int IsNameEmpty()
    {
        monicker = Name.GetComponent<TMP_InputField>().text.ToString();

    // Program never gets this far.

The OK function in the other script is:
public class WelcomeButtons : MonoBehaviour
{
    public GetName getName;

    void TaskOnClick6()
    {
        Debug.Log("You have clicked the OK button!");

        int isName = getName.IsNameEmpty(); // Causes null reference exception.

        // Program never gets this far.

A: A simple method to get the text from the input field
public class GetName: MonoBehaviour
{
public TMP_InputField name;

public void TaskOnClick()
{
    if(name =="")
    {
     Debug.log("NO Name Found");
    }
    else
    {
    Debug.log("NAME: "+name);
    }
}

A: Yes, if you attached the script above to an empty GameObject, then your script is missing the Link to the GameObject containing the TMP_InputField-Component. You can fix this in two simple ways, just decide what fits best for you:
a) Attach the GetName-script to the same GameObject that also contains the TMP_InputField-Component. Replace the Line "Name.GetComponent<TMP_InputField>().text.ToString();" with "GetComponent<TMP_InputField>().text.ToString();".
b) Leave the GetName-script on the empty GameObject. Make the "GameObject Name;" line public by changing it to "public GameObject Name". Go to the Unity-Editor. When selecting the GameObject containing the GetName-script, you should see the Name-Property and an empty Field next to it in the Inspector. Drag&Drop the GameObject containing the TMP_InputField-Component into it.
So, why did your code not work before? Well, the GetName-script needs some kind of reference to your TMP_InputField-component, which was missing. You tried this by getting it from the Name-Property, but never assigned it any value.

A: Thanks for all the advice I've received. I now have a working version using the OnClick() approach:
public class GetName : MonoBehaviour
{
    public TMP_InputField user_inputField;      // User-entered name.

    public void SaveName()
    {
        Globals.player = user_inputField.text.ToString(); // Saved for later.
        Debug.Log("Globals.player is " + Globals.player);
    }

    public void ResetName()
    {
        user_inputField.text = "";
        Globals.player = "";
    }
}

A: just two lines will work :
using UnityEngine.UI;

and
 public  TMPro.TMP_InputField Name;


text:
Q: Insert an array in MySQL database I want to insert an array into my MySQL database in the format a,b,c.
 `var_dump($pvt_contacts)`

results
array(1) { [0]=> array(2) { [0]=> string(3) "102" [1]=> string(1) "3" } }

I tried
`implode(',',$pvt_contacts)'

but it echos Array not 102,3 as I expected . Please help me

A: If you just want 102,3, then you're off by one (your pointing to a parent array, and not the elements):
implode(',',$pvt_contacts[0]);

*

*If you're trying to store an array in a DB, I recommend serialize. (despite its prevalence in Drupal, ExpressionEngine, Wordpress, etc. this is not generally the best idea).

*If you're trying to sent an array to js, I recommend json_encode.

*If you're doing something else I need more information.

A: It is suggested to use multiple rows to store the data, instead of storing the whole array into it. If you insist, here is the way:
Convert your array to the following format:
[key1]{value1}#[key2]{value2}#.... etc

You can use explode to convert it back to array.

A: The easiest way should be either serialize() or var_export(). But you should only use those if you do not intend to use the data inside the database in any way. If you want to run e.g. SELECT queries on this array data you should store it in a normalized way.

A: You should use serialize(), unserialize()
or  json_encode() , json_decode()
That would make it easier for you to write , and retreive back original data without the need of parsing your stored data yourself .
Here are some good links to assist you :
Preferred method to store PHP arrays (json_encode vs serialize)
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.serialize.php

A: You can implode your array into a string then explode it back. Default separator is the ,. If you want to run SELECT queries then you can use the MySQL-specific FIND_IN_SET() function however this whole scenario is not recommened, you should use a normalized way as others suggested above.

A: One way is to convert array to JSON. It will convert array to string and you will be able to store it.

*

*json_encode,

*json_decode;

Anyway, I don't think that this it the right way how to deal with the problem. Say, for example, you would need to store blog entries and tags for them into database.
How you do it know?
Save blog entry and tag into one table, one row. You convert all entries tags and save all into database.
How you should do it?
Make two tables:

*

*entries,

*entry_tags;

All info that's related to entry save into entries. For example: title, description.
All tags save into entry_tags. In that table there are id (primary key), entry_id (ID that have relationships with entries ID) and tag that simply holds the name.
I hope this will help you!


text:
Q: Python truncates strings after 32 characters? So I wrote the following straightforward Python script that takes in data from a CSV and outputs these config files for a 3D printer. Everything is working great except when I add strings together in the double for loop it cuts off the string after 32 characters. Can anyone explain why this is happening and how to prevent it? Thanks in advance!
import numpy as np

file = open('QualityData.csv')

data = np.genfromtxt(file, delimiter=",",dtype=str) #importing data

headers=data[[0,1],:]
data = np.delete(data,(0,1),0) #delete rows

titles=data[:,0]
data = np.delete(data, 0,1) #delete columns

r,c=np.shape(data)
profs = np.zeros((r,c))
profs = np.array(profs,dtype=str) #build data array for config file

for i in range(r):  #fill data array
    for j in range(c):
        if i in (0,4,5,12,13):
            profs[i,j]=titles[i]
        else:
            profs[i,j]=titles[i]+' = '+data[i,j]
            print(profs[i,j])

for k in range(c): #create filename and save it
    varient=str(data[11,k])
    varient=varient.replace(' ','_')
    filename = str(data[10,k]) + '_' + varient + '_' + str(data[8,k])+'.inst.cfg'
    np.savetxt(filename, profs[:,k], newline='\n',fmt='%s')

There are strings longer than 32 characters that get put into the titles array without a problem, but when they're added together in the else statement it only accepts the first 32 characters.


text:
Q: Retrieve Custom Attributes for Standard View I've defined a custom Attribut testAttribute for EditText and applied it in the Layout.
This compiles as expected, so i think it's available.
<EditText android:layout_width="wrap_content"
cst:testAttribute="true"
android:layout_height="wrap_content"></EditText>

Know, i need to read the testAttribute programatically in my Action, which i don't know how to do it.
I know how to do it in a custom view, but i need it in the standard view.
Anyone ideas on that?

A: on your custom View you do the following:
    public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);

            final TypedArray a = context.obtainStyledAttributes(attrs,  R.styleable.MyCustomView, defStyle, 0);
            // the default value is true
            // get the custom value progammatically
            testAttribute = a.getBoolean(R.styleable.MyCustomView_testAttribute, true);

           // make sure to recycle
           a.recycle();
    }

Hope it helped


text:
Q: Checking the AsyncTask status seems not working correctly (log doesn't appear on log cat) I'm trying to see how works an Asynctask class in android. In particular i want reveal in real time the status of the class for see when it is running and when it has finished. For do this, i have created a class that extend the main activity and another class that is the asynctaks class.
This is my main class:
public class PhotoManagement extends Activity{
private String numberOfSelectedPhotos;
private Bitmap currentImage;
private String initConfiguration = "http://www.something.com";
private String response;
private ArrayList<String> formatPhotoList = new ArrayList<String>(); //create a list that will contains the available format of the photos downloaded from the server
private ArrayList<String> pricePhotoList = new ArrayList<String>(); //create a list that will contains the available price for each format of the photos
DownloadWebPageTask webPage = new DownloadWebPageTask();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
protected void onResume(){
    super.onResume();
    webPage.execute(initConfiguration);
    if(webPage.getStatus() == AsyncTask.Status.PENDING){
        Log.i("STATUS","PENDING");
    }
    if(webPage.getStatus() == AsyncTask.Status.RUNNING){
        Log.i("","RUNNING");
    }
    if(webPage.getStatus() == AsyncTask.Status.FINISHED){
        Log.i("","FINISHED");
    }
}
}

As you can see i want only see the passages of the status with a simple log.
And here there is the asynctask class.
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        for (String url : urls) {
            DefaultHttpClient client = new DefaultHttpClient(); //create a new http client
            HttpGet httpGet = new HttpGet(url); //create a new http request passing a valid url
            try {
                HttpResponse execute = client.execute(httpGet); //try to execute the http get request
                InputStream content = execute.getEntity().getContent(); //prepare the input stream to read the bytes of the request
                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    response += s; //until is present a line to read, the response variable store the value of the lines
                }

            } catch (Exception e) {
                Log.i("MyApp", "Download Exception : " + e.toString()); //Print the error if something goes wrong
            }
        }
        return response; //return the response
    }

    @Override
    protected void onPostExecute(String result) {
        result = doInBackground(initConfiguration); //take the result from the DownloadWebPageTask class
        result = result.replace("null", "");
        Log.i("RESULT",""+result);
        //find the price and format value from the result using XmlPullParser
        try {
           XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
           factory.setNamespaceAware(true);
            XmlPullParser xpp = factory.newPullParser();
            xpp.setInput( new StringReader ( result ) );
            int attributeNumber = xpp.getAttributeCount();
            int eventType = xpp.getEventType();
            String currentTag = null;
            while(eventType != XmlPullParser.END_DOCUMENT){
                if(eventType == XmlPullParser.START_TAG) {
                    currentTag = xpp.getName();
                    if (currentTag.equals("product")){
                        xpp.getAttributeValue(null, "name");
                        formatPhotoList.add(xpp.getAttributeValue(null, "name"));
                        Log.i("FORMAT PHOTO",""+xpp.getAttributeValue(null, "name"));
                    }
                }
                eventType = xpp.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
            Log.i("","ERROR XML PULL PARSER");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.i("","ERROR IOEXCEPTION");
        }
    }

}
}

As you can see i have implemented also the method onPostExecute that should be called when the asynctask method has finished to execute the instructions right?
So at this point i don't understand why my log RUNNING and my log FINISHED never appear on the log cat.
What i'm doing wrong?
I'm tried to follow this topic Android, AsyncTask, check status? but in my case it isn't working.
Thanks

A: Problem :
You are creating object like
DownloadWebPageTask webPage = new DownloadWebPageTask();

But you are calling asynctask on different object,
new DownloadWebPageTask().execute(initConfiguration);

Solution :
It should be like
webPage.execute(initConfiguration);

A: @Override
protected void onResume(){
    super.onResume();
    new DownloadWebPageTask().execute(initConfiguration);

here do like this
@Override
protected void onResume(){
    super.onResume();
    webPage.execute(initConfiguration);

A: You didn't implement webPage.execute(), add it

A: Most probably the task hasn't finished or even started yet. As you probably know the AsyncTask is doing it's (background) work on a different thread, so your onResume is running in parallel with it. You can either use the task's get() method to wait for it to finish and get the result of the doInBackground() method and then query for it's status or notify your activity from the task's onPostExecute() method to let it know (and log) that it has finished. I don't recommend you the first option because it will actually block the UI thread and will make your usage of AsyncTask pointless.


text:
Q: WebParts with JavaScript don't work with managed path I developed a SharePoint 2010 WebParts with JavaScript and CSS(inside a module). I haven't problem on development environment but in production environment.
In production environment I have a WebApplication (http://productionapplication/) with managed path "corp" (http://productionapplication/corp/) and a SiteCollection "product"  (http://productionapplication/corp/product).
GET HTTP request fail for my JavaScript and CSS on loading my WebParts. Script and CSS are correctly deployed inside "http://productionapplication/corp/product/MyDocumentLibrary/"
How can I resolve my problem?
Thanks for your support.

A: Try the SPUrl token:
<link rel="stylesheet" type="text/css" media="screen" href='<% $SPUrl:~site/MyDocumentLibrary/Css/example.css %>' />

If that doesn't work, try the full relative path to you managed path:
<link rel="stylesheet" type="text/css" media="screen" href="corp/product/MyDocumentLibrary/Css/example.css" />

A: Because you're on SharePoint Foundation (thus you cannot use the $SPUrl expression), I would suggest that you resort to some classic ASP.Net tricks to workaround your issue:
Add a runat="server" and id attributes to the link element
<link id="css1" runat="server" rel="stylesheet" type="text/css" media="screen" href="" />

Within the Page_Load method, add this code:
css1.Attributes["href"] = SPUrlUtility.CombineUrl(SPContext.Current.Web.ServerRelativeUrl, "/MyDocumentLibrary/Css/example.css");


text:
Q: How to install Boost on Windows 7 with VS So I am trying for whole day to integrate Boost with Visual Studio (2008) on Windows 7.
I firstly I went twice trough this How to use Boost in Visual Studio 2010.
I searched over all (there are at least 3 of them) simiral topics and none of them worked.
Some people proposed using this one : www.boostpro.com/download/ but link is not active.
Someone proposed to change runtime library to Multi-threaded DLL but is also didnt work.
I just try to include #include <boost/thread.hpp> and got this error

fatal error LNK1104: cannot open file 'libboost_thread-vc90-mt-s-1_53.lib'.

Before installing Boost the error was that it cannot find the thread.hpp so it seems like the Boost is installed somewhat correctly.
The problem is that  the libraries were not build while I was using the tutorial. How can I build them manually?

A: There's no such thing like one-click boost install, you still need to do something manually. In your case it seems you need to compile Boost.Thread library and then add directory where resulting .lib file is to your library path. The link you provided looks pretty good. If you followed it probably you already built Boost.Thread. Make sure you did #6 from the second part.

A: There are prebuild binaries - installation packages:
http://sourceforge.net/projects/boost/files/boost-binaries/1.53.0/

A: Use this command:
bjam --build-dir=build-directory toolset=toolset-name --build-type=complete stage
this build the libraries manually. Then add the new directory to additional libraries path
as it is indicated in this link:
http://www.boost.org/doc/libs/1_43_0/more/getting_started/windows.html#or-build-binaries-from-source

A: I found this article quite helpful:
http://www.codeproject.com/Articles/11597/Building-Boost-libraries-for-Visual-Studio

*

*The article explains how to build the build tool BJam (mainly by locating the boostrapper.bat)

*How to build the libraries, e.g. bjam toolset=msvc-11.0 variant=debug threading=multi link=static (in this case the VS2012 multi-threaded, statically linked debug version).

*It also features build batches, but I haven't tried them.

*It has some additional information on how to specifiy the used C-Runtime


text:
Q: Limit number of request per unit of time In spring MVC or security is it possible to limit number of request per unit of time e.g 2 search request per second.
I want to avoid malicious request.

A: Request throttling is typically configured in application server/container or reverse proxy/load balancer. Also some ESB and integration products (like Mule and Camel) have relevant features.
To my knowledge neither Spring MVC nor Spring Security have any capabilities allowing limiting of request amounts, apart from possibility to limit number of concurrent authenticated sessions for a single user inside Spring Security.


text:
Q: Workflow.xaml - Copy to SharePoint root When I'm writing Assemblies, I can copy to GAC and avoid re-deploying them each time I want to make a code change.
When I'm writing ASPX forms, I can copy them to SharePoint root, maybe give an IIS reset and I'm done.
With workflows, I'm forced to go through the whole process. I've tried copying to SharePoint root, writing a script to replace the Workflow.xaml file, restarting the "Workflow Manager Backend" and all other SharePoint services.
It just doesn't work. Every time I make a change to my SharePoint 2013, visual studio workflow, I'm forced to redeploy the solution and re-attach the workflow to it's respective list. This takes less than 5 minutes, but imagine having to do that each time you have a minor change?
Is there a way of speeding up the debugging process?

A: You can write the following command mentioned in the following link
https://stackoverflow.com/questions/19286924/sharepoint-2013-visual-studio-workflow-not-updating
So you don't have to attach the workflow again. But you have to deploy the solution again.


text:
Q: Obtain sha1 key In android I have try to obtain a google apikey version 2 ,
I tried to obtain the sha 1 key as follows  keytool -list -v -keystore "C:\Users\sapu.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android but in command prompt keytool is not recogenize as internal or external command how can I overcome this

A: Where is the command keytool stored? Is it in your path? If not, then you need to give the full path.
More instructions can be found at this earlier question

A: Probably this happens because the Java home is not in your Path. Add the full path to the jdk folder to the Path variable and you'll be fine.


text:
Q: xdotool output gets intercepted by xbindkeys I have a broken key on my keyboard, The dot "." to be specific.
It behaves very oddly, about 7/10 times the keyboard types a double dot ".." when clicked once.
I use xbindkeys to intercept when the dot key is pressed and trigger my bash script to start.
The bash script I wrote checks how many instances of it are running and only types the "." once.
  #!/bin/bash
  let "target=2"
  curr=$(ps -A | grep 'dot-writer.sh' | wc -l)
  if [ "$curr" -eq "$target" ]
  then
    numlockx on
    xdotool key KP_Delete
    sleep 0.1
  fi

As you can see from the script I am not actually typing the "." key with xdotool, but instead, I am enabling Numlock and typing the other"." on my keyboard located on the keypad on the same button as delete.
As you can probably guess this is not a perfect solution because those two keys do not exactly act the exact same way 100% of the time.
I tried telling xdotool to type the "." as a Unicode character
xdotool key U002E

I tried telling xdotool to type the "." as a string generated by Bash
xdotool type $'.'

I tried telling xdotool to type the "." as a string generated by Bash containing the Unicode character "."
xdotool type $'\u002E'

None of this seems to work as it get intercepted as if the dot key has been pressed by xbindkeys and triggers the same script again and again.
Is there anything I can do?
Can I use some other tool to imitate a key press?


text:
Q: How do I know if a url returns an image PHP? I have folowing problem. I use curl for downloading images from server. I generating automaticly name for images and downloaded it. Some of the generated image names are not returned image. How do I know if a url returns an image?
Sorry for my "broken" English.
Thank's in advance!

A: $content_type = curl_getinfo ( $curl_obj, CURLINFO_CONTENT_TYPE);

http://www.php.net/manual/en/function.curl-getinfo.php

A: Vytautas' answer is correct, but incomplete.
$url = 'http://test.com/test/test/something';

$c = curl_init($url);

// Here you would want to set more curl settings, such as
// enabling redirection and setting a valid user agent.

curl_exec($c);

$t = curl_getinfo($c, CURLINFO_CONTENT_TYPE);

After that, $t should contain the mimetype (together with some other stuff), except when an error occurs, at which point you get a NULL.
That said, there are 3 points you should check to ensure the returned data is of a certain type:

*

*file extension

*content-type header

*file's magic number

A: I'd suggest you keep streaming your data to your server like you already do. To check before you try to convert, you could use finfo-file.
A more complex way could be to set the Accept header when e.g. using cUrl to only get the response if the header matches. Example:
curl_setopt($cURL,CURLOPT_HTTPHEADER,array (
        "Accept: application/json"
    ));

Or use CURLINFO_CONTENT_TYPE, see http://ch.php.net/manual/en/function.curl-setopt.php


text:
Q: How to edit color of button I have a edit form of a task list, i am  using the content type "Workflow Task (Sharepoint 2013)", it has 2 buttons, one for Approve and other for Deny.
I need to change the color of the Approve and Deny buttons, i have tried with Sharepoint Designer (Doesn't allow me to edit the form, even if I have full control permissions) and i have tried with Content Editor as well using below code inside a script tag:
  function changeColors () {
    documento.getElementById("Status_c15b34c3-ce7d-490a-b133-3f4de8801b76_$DropDownChoice_Aprobado").style.backgroundColor = "green";
  }

  document.onload= changeColors();

But, it doesn't work until I fire the event in the developer console.
Can someone help me?

A: 1.Create new txt file and add this code (put your color code)
<style>
#Status_c15b34c3-ce7d-490a-b133-3f4de8801b76_\$DropDownChoice_Approved {
    background-color: greenyellow;
}
#Status_c15b34c3-ce7d-490a-b133-3f4de8801b76_\$DropDownChoice_Rejected {
    background-color: red;
}
</style>

2.Save file as for ex buttonColor.txt
3.Upload file to SiteAssets (site/SiteAssets/Forms/AllItems.aspx)
4.Add content editor webpart on editform.aspx (edit page add webpart).
Edit content webpart properties > link txt file from siteassets to webpart /SiteAssets/buttonColor.txt


text:
Q: When should give ax.imshow() a variable name? I'm a beginner of matplotlib, I found that the ax.imshow() and im = ax.imshow() are both used in some coding templates, so I'm confused, when should give a return name?

A: You should use im = ax.imshow() when you want add something to the existing axis, for example, a colorbar. If you don't need to add anything to the axis, then it is fine to just use ax.imshow(). See this: https://www.geeksforgeeks.org/matplotlib-axes-axes-imshow-in-python/
Example from the link:
c = ax.imshow(z, cmap ='Greens', vmin = z_min,
              vmax = z_max, extent =[x.min(),
                                     x.max(),
                                     y.min(),
                                     y.max()],
              interpolation ='nearest',
              origin ='lower')

fig.colorbar(c, ax = ax)


text:
Q: Instantiating an N-ary tree from a CSV file I'm coding up an N-ary tree representation of file system hierarchies, where each node contains some information about the file/folder it represents.
public class TreeNode {

    private FileSystemEntry data;
    private boolean directory;
    private TreeNode parent;
    private ArrayList<TreeNode> children;
    private int numChildren;
    private int key;

The tree is stored as its own object because I'm going to compare several trees
public class DirectoryTree {

    private TreeNode Root;
    private int numNodes;
    private TreeNode Focus;
    private LocalDateTime date;
    private long totalSizeOnDisk;

And here's the FileSystemEntry class for reference
public class FileSystemEntry {

    private Path path;
    private String name;
    private long sizeOnDisk;
    private FileTime created;
    private FileTime lastModified;

I need to write each node to a file so that it can be reloaded at a later date, in order to compare the trees at two different times. I can easily write the variables from FileSystemEntry, and the Date from DirectoryTree to a CSV in order to recreate each FSE and its respective node, but I can't wrap my head around how I would then know for sure which node is a given nodes parent, in order to rebuild the tree.
At first glance, a breadth first traversal and the numChildren or even key from TreeNode seems to be enough information, but I haven't been able to implement a solution. Am I thinking along the right lines or am I over complicating the problem

A: Use a ObjectOutputStream to write your DirectoryTree objects into files. Therefore you have to implement the Serializable interface to all of you classes that you want to write.
This will preserve your structure/hierarchy and you wont have to mess around with the relation between the nodes.
Example:
public class TreeNode imlpements Serializable {

    private FileSystemEntry data;
    private boolean directory;
    private TreeNode parent;
    private ArrayList<TreeNode> children;
    private int numChildren;
    private int key;

}

public class DirectoryTree imlpements Serializable {

    private TreeNode Root;
    private int numNodes;
    private TreeNode Focus;
    private LocalDateTime date;
    private long totalSizeOnDisk;

}

public class FileSystemEntry imlpements Serializable {

    private Path path;
    private String name;
    private long sizeOnDisk;
    private FileTime created;
    private FileTime lastModified;

}

To write an object into a file:
public class IOTest {

    public static void main(String[] args) {

        File file;

        // create your Tree
        DirectoryTree dirTree;
        file = new File("filename");
        dirTree = createTree();

        // write object into file
        writeTree( dirTree, file );

        // read object from file
        DirectoryTree newDirTree;
        file = new File("filename");
        newDirTree = readTree( file );

    }

    public static DirectoryTree createTree() {

       // create here your tree

    }

    public static void writeTree( DirectoryTree tree, File file ) {

       FileOutputStream fos;
       ObjectOutputStream oos;

       try {
           fos = new FileOutputStream( file );
           oos = new ObjectOutputStream( fos );

           oos.writeObject( tree );
           oos.flush();

           oos.close();
       } catch( IOException ioe ) {
           ioe.printStackTrace();
       }

    }

    public static DirectoryTree readTree( File file ) {

       DirectoryTree loadedTree = null;
       FileInputStream fos;
       ObjectInputStream oos;

       try {
           fos = new FileInputStream( file );
           oos = new ObjectInputStream( fos );

           // you have to cast your object into a DirectoryTree,
           // because read() will return an object of type `Object`
           loadedTree = (DirectoryTree) oos.read();

           oos.close();
       } catch( IOException ioe ) {
           ioe.printStackTrace();
       }

       return loadedTree;

    }

}


text:
Q: Multisite, multi user login, same server Is it possible to run multiple websites on the same windows server under different user logins/iis managers? Basically we have multiple web masters accessing the same login/iis manager and want to split them up, it is possible for the sites to all run at the same time from 2 iis managers?

A: Check out the IIS Manager permission settings.  This option allows you to configure permissions and delegate permissions to different sites and applications.  This would allow you to create multiple sets of credentials and control permissions to them.
Your issue with doing this may however end up being that you consume all of the remote desktop connections, instead you may want to enable remove administration of IIS and install the manager MMC Snap-In on the client machines as well.


text:
Q: GNU-C-preprocessing FORTRAN source to change array indices causes recursion whilst expanding macro I am parallelizing an existing FORTRAN application. I don't want to directly change parts of its code   so I am using preprocessor directives to accomplish my goal. This way I am able to maintain the readability of the code and I won't induce errors in parts of the code that have already been tested. However, when I try to preprocess my source with the GNU C preprocessor I get the following error message (gcc version 4.7.2 (Debian 4.7.2-5)):
test.f:9:0: error: detected recursion whilst expanding macro "ARR""

This simple test program demonstrates my problem:
      PROGRAM TEST

        IMPLICIT NONE
        INTEGER I,OFFSET,ARR(10)

#define ARR(I) ARR(OFFSET+I)

        DO I=1,10
          ARR(I)=I
        END DO

#undef ARR(I)

      END PROGRAM TEST

This is the commandline output:
    testing$ gfortran -cpp -E test.f
# 1 "test.f"
# 1 "<command-line>"
# 1 "test.f"
      PROGRAM TEST

[...]
test.f:9:0: error: detected recursion whilst expanding macro "ARR"
        DO I=1,10
          ARR(OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+OFFSET+I)=I
        END DO

[...]
      END PROGRAM TEST

This site provides some information on the preprocessor I am using:
http://tigcc.ticalc.org/doc/cpp.html#SEC10
As it seems I am using a function-like macro with macro arguments.
Why is the preprocessor detecting a recursion? [EDIT] - Maybe because I use the same name for Makro and Identifier?
Why isn't the preprocessor capable of interpreting upper case directives (#DEFINE instead of #define)? - I am asking, because I haven't had this problem with the ifort preprocessor.
BTW: I am able to preprocess the original code either using the ifort preprocessor -fpp, or by changing the source in the following way:
      PROGRAM TEST

        IMPLICIT NONE
        INTEGER I,OFFSET,ARR(10)

#define ARR_T(I) ARR(OFFSET+I)

        DO I=1,10
          ARR_T(I)=I
        END DO

#undef ARR_T(I)

      END PROGRAM TEST

A: Why is the preprocessor detecting a recursion? [EDIT] - Maybe because I use the same name for Makro and Identifier?
The preprocessor is detecting recursion because your macro name and array name are the same.
Why isn't the preprocessor capable of interpreting upper case directives (#DEFINE instead of #define)? - I am asking, because I haven't had this problem with the ifort preprocessor.
When using gfortran, you are using a C preprocessor.  #DEFINE is not a recognized preprocessor directive in C.  No idea about ifort.  I thought in ifort you had to prefix macros with !$MS or !$DEC.
Your change to the program to get it to work for ifort will also work for gfortran.


text:
Q: Ptrace in C language : What does void *addr refer to? I'm using ptrace system call in C language:
long ptrace(enum __ptrace_request requête, pid_t pid, void *addr, void *data);

But I don't know what void *addr refers to...
In this example, I wanted to get the address of the current instruction which is in RIP:
unsigned long ip = ptrace(PTRACE_PEEKUSER, child, 8 * RIP, NULL);

Where child refers to the PID of the child process, I don't understand why do we need to multiply RIP by 8 and why RIP is used as an integer constant (defined in <sys/reg.h> as 16).
16*8 = 128 is an integer constant: is it a valid (void *addr) ?

A: ptrace() is actually a variadic function as stated in the manual:

Although arguments to ptrace() are interpreted according to the
prototype given, glibc currently declares ptrace() as a variadic
function with only the request argument fixed.  It is recommended
to always supply four arguments, even if the requested operation
does not use them, setting unused/ignored arguments to 0L or
(void *) 0.

Hence, depending on the request (1st parameter), the following parameters will be interpreted accordingly as the function should be actually viewed as something like long ptrace(enum __ptrace_request request, ...);.
In the source code of the GLIBC, it is defined as follow in sysdeps/unix/sysv/linux/ptrace.c:
long int
ptrace (enum __ptrace_request request, ...)
{
  long int res, ret;
  va_list ap;
  pid_t pid;
  void *addr, *data;

  va_start (ap, request);
  pid = va_arg (ap, pid_t);
  addr = va_arg (ap, void *);
  data = va_arg (ap, void *);
  va_end (ap);

  if (request > 0 && request < 4)
    data = &ret;

  res = INLINE_SYSCALL (ptrace, 4, request, pid, addr, data);
  if (res >= 0 && request > 0 && request < 4)
    {
      __set_errno (0);
      return ret;
    }

  return res;
}

In the preceding, you can see that it is a variadic function which uses va_arg() to get a pid followed by two void * before passing them to the actual ptrace() system call.
Concerning the 8 * RIP multiplication, it is said in the header file (</sys/reg.h>) that RIP constant is a index in a array of 8 bytes longs. Hence the multiplication:
#ifdef __x86_64__
/* Index into an array of 8 byte longs returned from ptrace for
   location of the users' stored general purpose registers.  */

# define R15    0
# define R14    1
# define R13    2
# define R12    3
# define RBP    4
# define RBX    5
# define R11    6
# define R10    7
# define R9 8
# define R8 9
# define RAX    10
# define RCX    11
# define RDX    12
# define RSI    13
# define RDI    14
# define ORIG_RAX 15
# define RIP    16
[...]


text:
Q: Is SQL Express 2008 subject to the same 5 connection limitation as file sharing on Windows XP? File sharing on Windows XP has a 5 client limitation.  Our solution uses both file sharing and SQL Express.
The way I see it, we have 2 options here:
-Reload the machine that they want to use as a server with Windows Server, or;
-Supply them with a dedicated NAS server, and keep their server machine on Windows XP
The second option is the preferred one, for reasons I'm not going to go into.  I just need to confirm that the 5 client limitation applies to the file sharing only.

A: Looking at this feature comparison chart, it seems there is no limit on the number of connections. The big differences seem to be CPU, RAM, and database size limitations.
EDIT
While there is nothing in the SQL Server Express docs about Windows connection limits, I did find this MS KB article, Inbound connections limit in Windows XP. It appears that Windows XP Professional has a 10-connection limit, and Windows XP Home has a 5-connection limit.

Note For Windows XP Professional, the
  maximum number of other computers that
  are permitted to simultaneously
  connect over the network is ten. This
  limit includes all transports and
  resource sharing protocols combined.
  For Windows XP Home Edition, the
  maximum number of other computers that
  are permitted to simultaneously
  connect over the network is five. This
  limit is the number of simultaneous
  sessions from other computers the
  system is permitted to host. This
  limit does not apply to the use of
  administrative tools that attach from
  a remote computer.

A: If you run it on XP, then it is limited. I don't know if the limit is enforced, but if you pass it it you are still in violation of XP's license agreement.  If you have multiple users connecting to your server, you really should run it on a server operating system.  Windows Server 2008 R2 is current, but SQL Server Express should work down to Server 2003.

A: I know it's been "answered" for a while but for the reference of others who may happen upon this question, there is no and has never been a CONNECTION limit to MSDE/SQL Express.
There is a workload governer in MSDE 1.0 and MSDE 2000 that would cause things to slow down if more than 5 (and subsequently 8 in 2000) operations were occurring at once, but that was dropped in SQL Express 2005 and later.
For reference, see:
Link


text:
Q: I want to write a location based app using Yelp api. How do I add new locations? I want to write react native app. The main functionality of the app is location based - I fetch some locations from Yelp api, but how do I tackle new businesses?
My current solution: I fetch location places with this yelp api. I can search for "bars", or "pizza". Then I have some results, coming in the following format:
{
  "total": 8228,
  "businesses": [
    {
      "rating": 4,
      "price": "$",
      "phone": "+14152520800",
      "id": "E8RJkjfdcwgtyoPMjQ_Olg",
      "alias": "four-barrel-coffee-san-francisco",
      "is_closed": false,
      "categories": [
        {
          "alias": "coffee",
          "title": "Coffee & Tea"
        }
      ],
      "review_count": 1738,
      "name": "Four Barrel Coffee",
      "url": "https://www.yelp.com/biz/four-barrel-coffee-san-francisco",
      "coordinates": {
        "latitude": 37.7670169511878,
        "longitude": -122.42184275
      },
      "image_url": "http://s3-media2.fl.yelpcdn.com/bphoto/MmgtASP3l_t4tPCL1iAsCg/o.jpg",
      "location": {
        "city": "San Francisco",
        "country": "US",
        "address2": "",
        "address3": "",
        "state": "CA",
        "address1": "375 Valencia St",
        "zip_code": "94103"
      },
      "distance": 1604.23,
      "transactions": ["pickup", "delivery"]
    },
    // ...
  ],

What if there is a new location/business which is not yet in Yelp? Should I just let users to create new locations, and tag them, so they can appear in appropriate searches? This means I will have to do 2 endpoint calls - one to the Yelp api, and one to my own database. Is this a good approach?


text:
Q: Arithmetic overflow error for smallint--but the datatype is int? I have a stored procedure that inserts values into a table:
ALTER PROCEDURE [dbo].[spSaveAddresses_LegalDescriptions_Determinations]
   @idAddresses_LegalDescriptions_Determinations INT    = NULL OUTPUT,
   @idLogin INT = -32768,
   @idAddress INT = NULL,
   @idLegalDescription INT = NULL,
   @idDetermination INT = NULL
AS
   SET NOCOUNT ON
   SET ROWCOUNT 0
   SET XACT_ABORT ON

   BEGIN TRY
      /* Declare and initialize variables */
      DECLARE   @RC         INT,
                @TranCount  INT

      SELECT
          @RC = 0,
          @TranCount = @@TRANCOUNT

      /* Insert record into Table #1] */
      IF @TranCount = 0
      BEGIN TRANSACTION
      BEGIN
           INSERT INTO [TOD].[dbo].[Table#1](idAddress, idLegalDescription,
                                             idDetermination, UpdatedidLogin,
                                             UpdatedDate)
           VALUES(@idAddress, @idLegalDescription,
                  @idDetermination, @idLegalDescription, GETDATE())
     END

     IF @TranCount = 0 AND (XACT_STATE()) = 1
        COMMIT TRANSACTION
END TRY

BEGIN CATCH
IF (XACT_STATE()) = -1 ROLLBACK TRANSACTION
    EXEC [TOD].[dbo].[spRethrowError]
    SET @RC = 1
END CATCH

SET NOCOUNT OFF
SET ROWCOUNT 0
RETURN @RC
GO

The structure of table #1:
CREATE TABLE [dbo].[Addresses_LegalDescriptions_Determinations]
(
    [idAddresses_LegalDescriptions_Determinations] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
    [idAddress] [int] NULL,
    [idLegalDescription] [int] NULL,
    [idDetermination] [int] NULL,
    [UpdatedidLogin] [smallint] NOT NULL
         CONSTRAINT [DF_Addresses_LegalDescriptions_Determinations_UpdatedidLogin]  DEFAULT ((0)),
    [UpdatedDate] [datetime] NOT NULL,

    CONSTRAINT [pkAddresses_LegalDescriptions_Determinations]
        PRIMARY KEY CLUSTERED ([idAddresses_LegalDescriptions_Determinations] ASC)
) ON [DATA]
GO

ALTER TABLE [dbo].[Addresses_LegalDescriptions_Determinations] WITH NOCHECK
   ADD CONSTRAINT [FK_Addresses_LegalDescriptions_Determinations_Addresses]
       FOREIGN KEY([idAddress])
       REFERENCES [dbo].[Addresses] ([idAddress])
            ON DELETE CASCADE
            NOT FOR REPLICATION
GO

ALTER TABLE [dbo].[Addresses_LegalDescriptions_Determinations]
      CHECK CONSTRAINT [FK_Addresses_LegalDescriptions_Determinations_Addresses]
GO

ALTER TABLE [dbo].[Addresses_LegalDescriptions_Determinations] WITH NOCHECK
ADD CONSTRAINT [FK_Addresses_LegalDescriptions_Determinations_Determinations]
    FOREIGN KEY([idDetermination])
    REFERENCES [dbo].[Determinations] ([idDetermination])
ON DELETE CASCADE
NOT FOR REPLICATION
GO

ALTER TABLE [dbo].[Addresses_LegalDescriptions_Determinations] CHECK    CONSTRAINT [FK_Addresses_LegalDescriptions_Determinations_Determinations]
GO

ALTER TABLE [dbo].[Addresses_LegalDescriptions_Determinations]  WITH NOCHECK   ADD  CONSTRAINT     [FK_Addresses_LegalDescriptions_Determinations_LegalDescriptions] FOREIGN   KEY([idLegalDescription])
REFERENCES [dbo].[LegalDescriptions] ([idLegalDescription])
ON DELETE CASCADE
NOT FOR REPLICATION
GO

ALTER TABLE [dbo].[Addresses_LegalDescriptions_Determinations] CHECK    CONSTRAINT [FK_Addresses_LegalDescriptions_Determinations_LegalDescriptions]
GO

The structure of the table causing the error:
CREATE TABLE [dbo].[LegalDescriptions](
[idLegalDescription] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[LotNumber] [varchar](15) NULL,
[BlockNumber] [varchar](15) NULL,
[SubDivision] [varchar](255) NULL,
[UpdatedDate] [datetime] NOT NULL,
[InsertedDate] [datetime] NULL,
[SubDivisionPhase] [varchar](5) NULL,
[Township] [varchar](20) NULL,
[UpdatedidLogin] [smallint] NOT NULL CONSTRAINT [DF_LegalDescriptions_UpdatedidLogin]  DEFAULT ((0)),
[InsertedIDLogin] [smallint] NULL,
[LegalDescription] [varchar](255) NULL,
[PinNumber] [varchar](30) NULL,
[Range] [varchar](15) NULL,
[SectionLegalDescription] [varchar](15) NULL,
 CONSTRAINT [pkLegalDescriptions] PRIMARY KEY CLUSTERED
(
    [idLegalDescription] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,  ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [DATA]
) ON [DATA]

GO

SET ANSI_PADDING OFF
GO

The error I am receiving when I try to execute the stored procedure:

Msg 50000, Level 16, State 1, Procedure spRethrowError, Line 42
  Error 220, Level 16, State 1, Procedure spSaveAddresses_LegalDescriptions_Determinations, Line 42
  Message: Arithmetic overflow error for data type smallint, value = 171922.

My question:
All data types for this column that throws the error [idLegalDescription] are INT, why is the stored procedure calling for a smallint data type? I'm sure it's something simple that I'm missing.

A: Your column
 [UpdatedidLogin] [smallint]

Is populated by
@idLegalDescription                             INT


text:
Q: Will equivalence between $\|\cdot\|_1, \|\cdot\|_2$ preserver the order between $\|x\|_i, \|y\|_i (i = 1, 2)$ $\hspace{0.44cm}$In a infinitely dimensional Banach space $X$, given two linearly independent elements $x, y$ in the closed unit ball of $X$ and two positive real numbers $r_1, r_2 > 0$ such that $r_1+r_2 = 1$, are there any sufficient conditions on $x, y$ or the entire $X$, or $r$, which can imply:
$$
\|r_1x+r_2y\| \geq r\|x+y\|\,\forall\,r \leq \min(r_1, r_2)
$$
$\hspace{0.44cm}$As the first comment mentioned, in $\operatorname{Span}(x, y)$, define $\|ax+by\|_m = \max(\vert\,a\,\vert, \vert\,b\,\vert)$ and then in $\operatorname{Span}(x, y), \|\cdot\|, \|\cdot\|_m$ will be equivalent and hence for any $0 < r \leq \max(r_1, r_2)$ we will have $\|r_1x+r_2y\|_m \geq r\|x+y\|_m$ but how to compare $\|r_1x+r_2y\|$ and $r\|x+y\|$? When $x, y$ are fixed, we can find $0 < a < b$ such that $a\|r_1x+r_2y\|_m \leq \|r_1x+r_2y\| \leq b\|r_1x+r_2y\|_m\,\forall\,r_1, r_2 \in \mathbb{R}$ but how to know the range of $a, b$?
Given $r_2 > r_1 > 0, r_1+r_2 = 1$, an infinitely dimensional Banach space $X$ and $x, y$ in the closed unit ball:

*

*Is there a suffcient condition on $x, y$ or $X$ such that:
$$
\|r_1x+r_2y\|\geq r\|x+y\|\,\forall\,r \leq r_1
$$
Can we find the $\sup$ of $r > 0$ such that the statement above holds?

*Is there a sufficient condition on $x, y$ or $X$ such that:
$$
\|r_1x+r_2y\|\geq r\|x+y\|\,\forall\,r \in (r_1, r_2)
$$
Can we find $\sup$ or $\inf$ for this $r$?

*Is there a sufficient condition on $x, y$ or $X$ or $r_1, r_2$ such that:
$$
\|r_1x+r_2y\|\geq r\|x+y\|\,\forall\,r \geq r_2
$$
Again I would like to know the $\sup$ of $r$ in this case. Could one of $\sup$ or $\inf$ be $r_2$?


text:
Q: Problems with SQL delete statement I'm getting an error stating that I need a second argument in my remove command, but I believe I already have two in here. I'm pretty new to SQL and C# so maybe I'm not understanding it correctly.
private void RemoveFromRecipeButton_Click(object sender, EventArgs e)
{
    string query = "DELETE FROM RecipeIngredient WHERE Id = @RecipeId & @IngredientId";

    using (connection = new SqlConnection(connectionstring))
    using (SqlCommand command = new SqlCommand(query, connection))
    {
        connection.Open();

        command.Parameters.Remove("@RecipeId", ListRecipes.SelectedValue);
        command.Parameters.Remove("@IngredientId", ListAllIngredients.SelectedValue);

        command.ExecuteScalar();
    }

    PopulateRecipes();
}

I'm thinking it might be because I put both RecipeID and IngredientID in the same line with an &, but that works on my add statement.
So I'm really unsure of how remove should work. Can anyone assist in identifying the issue?

A: You are calling Parameters.Remove when it looks like you want to be calling Parameters.AddWithValue. You're executing a delete statement, but that doesn't mean you want to remove parameters. You still need to add the parameters that specifies what to delete.
Your actual SQL statement is suspect as well - you're currently deleting rows where the bitwise AND of your two parameters matches the Id of the row. Is that what you want?

A: There are a few different problems here.
The first one is I'm not sure what your sql is trying to do. Are you actually trying to perform a bitwise AND, or are you just trying to see if Id is equal to both the @RecipeId and @IngredientID?
Additionally, just because your SQL statement has parameters in it, doesn't mean you can use cmd.Parameters.Remove() to remove them. The Command.Parameters collection is used to associate values in your program to specific parameters in  your sql statement. You will have to remove the parameters from the literal sql string, if you are truly looking to remove them from the statement.


text:
Q: Each time I press submit I want input text box change text So basically I have a simple form and I want to change the input boxes text different every time you press submit by using PHP. I know my code doesn't work but I don't understand how to solve this problem. Maybe the array is not the best way to do this?
<body>
    <?php
        if(isset($_GET['submit'])) exit();
        $msg= ['One', 'Two', 'Three', '']
    ?>

    <form action="<?php echo $_SERVER['PHP_SELF']?>">
    <input type="submit" name="submit" value="Paina nappi">
    <input type="text" name="msg" value="<?php echo (isset($msg)) ? $viesti : ''; ?>">
    </form>
</body>

A: You could write something like this:
<?php
    session_start();

    $msgArray= array('One', 'Two', 'Three', '');
    // if $_SESSION['msgIndex'] is not set, we initialize it, or it will take 0 value every loading page
    if (!isset($_SESSION['msgIndex'])) { $_SESSION['msgIndex'] = 0;  }

    if (isset($_GET['submit'])) {
        getMessage();
    }

    // We save msgIndex in a $_SESSION variable cause even if the user reload the page, we keep the value
    function getMessage() {
        if ($_SESSION['msgIndex'] >= 0) {
            $_SESSION['msgIndex'] += 1;
        } if ($_SESSION['msgIndex'] > 3) {
            $_SESSION['msgIndex'] = 0;
        }
    }
?>

<form action="<?php echo $_SERVER['PHP_SELF']?>">
    <input type="submit" name="submit" value="Paina nappi">
    <input type="text" name="msg" value="<?= $msgArray[$_SESSION['msgIndex']] ?>">
</form>


text:
Q: Can not configure Require.js baseUrl I have the following application structure:
+ project
  + app
  + script
    + vendors
      + backbone
      + underscore
      - require.js
      - require.config.js
  package.json

I have installed all dependencies using jam.js. The package.json is looks like this:
{
   "name": "Project",
   "jam": {
             "packageDir": "app/scripts/vendor",
         "baseUrl": "app",
         "dependencies": {
                 "backbone": null
         }
   }
}

The baseUrl is set to the app folder, and if I run my application from
localhost/project/app it's working just fine. But eventually in the back-end my app index.html is included in a php web page so all modules urls are broken, for example:
GET http://builder1.localhost/user/scripts/vendor/require.js 404 (Not Found)

instead of loading:
localhost/project/app/scripts/vendor/require.js

How can I configure the 'baseUrl' so it will know that I'm been load via http://builder1.localhost/user/?

A: Your entry script (the first script loaded by require.js) should have something similar to the following
require.config({
   baseUrl: "/another/path",
    paths: {
        "some": "some/v1.0"
    },
    waitSeconds: 15
});
require( ["some/module", "my/module", "a.js", "b.js"],
    function(someModule,    myModule) {
        //This function will be called when all the dependencies
        //listed above are loaded. Note that this function could
        //be called before the page is loaded.
        //This callback is optional.
    }
);

That is taken straight from there documentation. Double check your code. Base URL is better if its an absolute path and not relative.


text:
Q: Is is true? A semi-Eulerian graph cannot exist if we can find a complete graph with the same number of edges I was trying out some Graphs and wondered if what I found was true. I am reasonably confident up to where I placed the asterix.
Take a semi-Eulerian graph $G$ with $m$ edges. A complete graph with $n$ vertices has $\frac{1}{2}n(n-1)$ edges.
For a complete graph, all the vertices have the same degrees and hence there can never be a complete semi-Eulerian graph. Hence a complete graph satisfying $\frac{1}{2}n(n – 1) = m$ cannot have integer values of $n$, or this complete semi-Eulerian graph would actually exist. Using the quadratic formula gives $\frac{1}{2}((1 + 8m)^{1/2} + 1)$ as the values of $n$ (discarding the negative sign as $n > 0$), which are not integers.
*However, this is an integer for certain $m$ – if this is true, then it means that, as all $K_n$ exist, then a semi-Eulerian graph cannot exist if we can find a complete graph with the same number of edges. So $m$ cannot equal $\frac{1}{2}n(n-1)$, where $n$ is an integer. One example using this is $m = 3$ and I can't seem to draw it.

A: By way of counter-example - if I understood your assertion correctly -  here is a semi-eulerian graph with $21$ edges:

Maybe that was unnecessarily flashy... here's one with only $6$ edges:

Effectively by adding extra degree-$2$ nodes into the bottom loop (square) of the 6-edge graph, you can make a semi-eulerian graph with any number of edges you want.


text:
Q: Determinants of matrices; Does the equation $\det M=\det(I_n-M)$ have a solution? Suppose $M$ is some $n\times n$ real matrix. Then is it always true that $\det M\neq\det(I_n-M)$, where $I_n$ is the $n\times n$ identity matrix? I have a feeling that it is yes, but I am not sure... Thanks.

A: Let $M$ be half of the identity, $$M=\frac{1}{2} I_n.$$

A: The question has been raised in the comments, given $\det M=\det(I-M)$, what values can $\det M$ take?
Note that $\det M=\prod\lambda$ and $\det(I-M)=\prod(1-\lambda)$, where the products are over all the eigenvalues $\lambda$ of $M$, with multiplicity. In the case $n=2$, we get $ab=(1-a)(1-b)$, which becomes $a+b=1$, so we are looking for the range of $ab$ over pairs such that $a+b=1$. If $a$ and $b$ are real, this implies $ab$ can be any real not exceeding $1/4$. But $a$ and $b$ need not be real. If $a=(1/2)+it$ and $b=(1/2)-it$, then $ab=t^2+(1/4)$, which can take on any real value not less than $1/4$. In short, the range is all of $\bf R$.
For $n=3$, you don't have to go to the complex numbers to get arbitrarily large $\det M$. We want $abc=(1-a)(1-b)(1-c)$. Pick a large number $Q$, let $a=b=Q$, and solve for $c$; $c=(Q-1)^2/(Q^2+(Q-1)^2)$. So $\det M=Q^2(Q-1)^2/(Q^2+(Q-1)^2)$, which is unbounded.