text:
Q: findElementById finding every element in every tab I have an Android application that uses 4 tabs:
Registry | Delivery | Invoice | Note

Every one of them is a Fragment loaded in a "container" activity.
In ContainerActivity I have a save button and, when I click it, I want to save everything from the tabs.
At this purpose I use findElementById(R.id.myElementName).
Doing some debug I've noticed that this trick works only for loaded and pre-loaded fragment: if I'm in Registry fragment I can "find" only elements within RegistryFragment and DeliveryFragment, but not in InvoiceFragment.
How can I get EVERY element of EVERY fragment?
SOLVED
Thanks @Okas:
Using viewPager.setOffscreenPageLimit(3); ('cause I have max 3 tabs excluding the one I'm rendering) make possible to reach every element within every fragment in my activity.

A: findElementById does not find elements from some fragments because these fragments are not created yet or are already destroyed.
You should use separate data objects to hold your important data and let fragments update these objects or alternatively try to increase ViewPager offScreenPageLimit so that fragments are not destroyed (this will increase memory footprint).


text:
Q: plot with two columns side by side in R I'm new to coding so this question might seem dumb to others.
I'm trying to recreate this plot in R:
enter image description here
My code is:
population <- c(894, 15736, 42147)
household <- c(215, 4357, 13622)
year <- c(2000, 2010, 2020)
df <- data.frame(year, population, household)

library(ggplot2)

pl <- ggplot(df, aes(x= factor(year), y= factor(population), fill= factor(household)))
pl2 <- pl+ geom_col(position="Dodge")+ labs(x="Year", y= "Population")

print(pl2)

and that's the result:
enter image description here
As you can see the household column doesn't appear as a column here, although I'm using dodge position. I can't figure out what the problem is. I'd appreciate any helps.

A: I think what you are trying to do is something like that :
population <- c(894, 15736, 42147)
household <- c(215, 4357, 13622)
year <- c(2000, 2010, 2020)
df <- data.frame(year, population, household)

library(tidyr)
df=df%>%pivot_longer(!year)
library(ggplot2)

pl <- ggplot(df, aes(x= year, y=value,fill= name))
pl2 <- pl+ geom_col(position="Dodge")+ labs(x="Year", y= "Population")

print(pl2)

From your code I would do :
pl2=ggplot(df, aes(x= factor(year), y=value,fill= name))+
 geom_bar(stat='identity',position = "dodge")+ labs(x="Year", y= "Population")+
  theme_bw()+
  geom_text(aes(label = value),position=position_dodge(width=0.9),size = 4,vjust=-0.5)
print(pl2)

This way you have number above column (theme_bw gives a nice looking plot but it is personnal taste)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como escrever esse algoritmo em C A equação A^5+B^5+C^5+D^5+E^5=F^5 tal que 0<a<=b<=c<=d<=e<f<=75 tem exatamente uma solução inteira. escreva uma programa para encontra-la.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int main(void){
int a=1,b=1,c=1,d=1,e=1,f=2,r,f5,ac,bc,cc,dc,ec,fc;

    for(a=1;a<=b;a++){
        for(b=1;b<=c;b++){
            for(c=1;c<=d;c++){
                for(d=1;d<=e;d++){
                    for(e=1;e<f;e++){
                        f=e+1;
                        for(;f<=75;f++){
                            r=pow(a,5)+pow(b,5)+pow(c,5)+pow(d,5)+pow(e,5);
                            f5=pow(f,5);
                            if(r==f5){
                                ac=a;
                                bc=b;
                                cc=c;
                                dc=d;
                                ec=e;
                                fc=f;
                                a=b=c=d=e=f=76;
                            }
                        }
                    }
                }
            }
        }
    }
printf("A=%d,B=%d,C=%d,D=%d,E=%d,F=%d\n\n\n",ac,bc,cc,dc,ec,fc);

system("pause");
return (0);
}

Esse código entra em um loop infinito, minha cabeça travou, alguém sabe onde está o erro?

A: Tem mais de um problema na sua solução. Alguns deles:
A função pow() retorna um double e isso é problemático tanto quanto porque doubles não são exatos e pode ocorrer um erro na conversão para o int e tanto porque doubles possuem um range muito maior do que int e, portanto a conversão é perigosa.
No seu caso em determinado momento a função pow() retorna um valor superior ao range do int e as variáveis r e f5 ficam com um valor indefinido. Quando eu testei o seu código, ambas assumiram o valor de -2.147.483.648
Isso leva ao segundo problema, o seguinte trecho  a=b=c=d=e=f=76; não faz com que as condições do loop sejam fechadas. Na realidade, os primeiros dois loops são fechados, mas quando chega neste for(d=1;d <= e;d++) tanto d como e são iguais a 76 e o loop prossegue infinitamente.
Enfim, eu corrigi os principais erros, mas mantive, em parte, a lógica que você adotou, confira-se:
#include <stdio.h>
//incluido o header stdint.h para usar o tipo int64_t
//já que em alguns momentos os valores podem
//ultrapassar o range do tipo int
#include <stdint.h>

//essa função substitui a pow() para evitar o uso de doubles
int64_t P(int x) {
    return x * x * x * x * x;
}

int main(){

    int AC, BC, CC, DC, EC, FC;

    //iniciar pelo F ao invés do A me pareceu mais legível
    for (int F = 1; F <= 75; F++) {
        for (int E = 1; E <= F; E++) {
            for (int D = 1; D <= E; D++) {
                for (int C = 1; C <= D; C++) {
                    for (int B = 1; B <= C; B++) {
                        for (int A = 1; A <= B; A++) {
                            int64_t F5 = P(F);
                            int64_t R = P(A) + P(B) + P(C) + P(D) + P(E);
                            if (F5 - R == 0){
                                AC = A;
                                BC = B;
                                CC = C;
                                DC = D;
                                EC = E;
                                FC = F;
                                A = 81;// isso garante que todos os loops serão fechados
                                B = 80; // quando  a resposta correta for encontrada
                                C = 79;
                                D = 78;
                                E = 77;
                                F = 76;
                            }
                        }
                    }
                }
            }
        }
    }

    printf("A=%d,B=%d,C=%d,D=%d,E=%d,F=%d\n",
            AC, BC, CC, DC, EC, FC);

    return 0;
}

Contudo, mesmo resolvendo o problema. Algo me incomoda nessa solução. Ela me parece bastante ineficiente porque verifica todas as combinações possíveis até encontrar a solução correta e é evidente que em determinadas circunstâncias muitas soluções podem ser descartadas. Por exemplo, se F = 70 e E = 10, é completamente desnecessário verificar o valor das outras variáveis já que ainda que elas tenham o mesmo valor que E, A^5+...+E^5 será menor que F^5. Por isso apresento uma versão dos loops aninhados otimizada. Confira-se:
//iniciar pelo F ao invés do A me pareceu mais legível
    //os trechos com continue e break servem para otimizar o algoritmo
    //as condições com continue verificam se é possível que no restante do loop R tenha o mesmo valor que F5
    //as condições com break verificam se R já não possuí um valor mais alto que F5
    for (int F = 1; F <= 75; F++) {
        for (int E = 1; E <= F; E++) {
            if (P(F) > 5 * P(E)) continue;
            for (int D = 1; D <= E; D++) {
                if (P(F) > P(E) + 4 * P(D)) continue;
                if (P(F) < P(E) + P(D)) break;
                for (int C = 1; C <= D; C++) {
                    if (P(F) > P(E) + P(D) + 3* P(C)) continue;
                    if (P(F) < P(E) + P(D) + P(C)) break;
                    for (int B = 1; B <= C; B++) {
                        if (P(F) > P(E) + P(D) + P(C) + 2* P(B)) continue;
                        if (P(F) < P(E) + P(D) + P(C) + P(B)) break;
                        for (int A = 1; A <= B; A++) {
                            int64_t F5 = P(F);
                            int64_t R = P(A) + P(B) + P(C) + P(D) + P(E);
                            if (F5 - R == 0) {
                                AC = A;
                                BC = B;
                                CC = C;
                                DC = D;
                                EC = E;
                                FC = F;
                                A = 81;// isso garante que todos os loops serão fechados
                                B = 80; // qunado  a resposta correta for encontrada
                                C = 79;
                                D = 78;
                                E = 77;
                                F = 76;
                            }
                            else if (F5 - R < 0) break;
                        }
                    }
                }
            }
        }
    }

E por fim, acrescento o algoritmo otimizado escrito de forma recursiva. Confira-se:
#include <stdio.h>
#include <stdint.h>

int64_t P(int x) {
    return x * x * x * x * x;
}

int compare(int* S, int index, int64_t f5, int64_t sum) {
    if (index == 1) return f5 == sum ? 0 : (f5 > sum ? 1 : -1);
    else return compare(S, index - 1, f5, sum + P(S[index - 1]));
}

int solve(int* S, int index) {
    if (index == 6)
        return (compare(S, index, P(S[0]), 0) == 0);

    if (index > 1) {
        if (compare(S, index, P(S[0]), 0) == -1) return 2;
        if (compare(S, index, P(S[0]), (6 - index) * P(S[index - 1])) == 1) return 3;
    }

    int max = index ? S[index - 1] : 75;

    for (int i = 1; i <= max; i++) {
        S[index] = i;
        int s = solve(S, index + 1);
        if (s == 1) return 1;
        if (s == 2) break;
        if (s == 3) continue;
    }
    return  0;
}

int main(){

    int S[6] = { 1, 1, 1, 1, 1, 1 };
    solve(S, 0);
    printf("A=%d,B=%d,C=%d,D=%d,E=%d,F=%d\n",
            S[5], S[4],S[3],S[2],S[1], S[0]);
    return 0;
}


text:
Q: Is it possible to use both CommonJS and ES6 module in a Node.JS command-line program? I'm working on a CLI tool. I used "commander", which is a CommonJS module, to parse command-line arguments. I also want to use "p-map" to manage concurrency. However, "p-map" is a ES6 module.
Also I'm using Typescript.
Now both code editor and Typescript compiler won't complain. However I cannot execute my CLI tool. If I compile with "module":"commonjs", node would not load p-map and complains "Must use import to load ES Module... node_modules/p-map/index.js...require() of ES modules is not supported.". If I compile with "module":"es2015", use "require" to import the CommonJS modules, and add "type":"module" in my package.json, node would complain "ReferenceError: require is not defined".
I love the flexibility of Typescript/Javascript, however, it's time like this makes me miss Java. Java might be too prissy, but I don't spend hours trying to figure out import / export......
So, is it possible to use both CommonJS and ES6 module in a Node.JS command-line program?

A: To enhance compatibility, the (moderately new) node esm loader can import cjs-modules (e.g. import identifier from 'cjs-module-name';).
The other way around doesn't work, you can't require an esm-module, but dynamic import should work, if really necessary.
A related read may be the statement from p-map's owner regarding the topic.


text:
Q: Making a time adding function in python I'm trying to build a function that recieves a date and adds days, updating everything in case it changes, so far i've come up with this:
def addnewDate(date, numberOfDays):

    date = date.split(":")
    day = int(date[0])
    month = int(date[1])
    year = int(date[2])
    new_days = 0
    l = 0
    l1 = 28
    l2 = 30
    l3 = 31
    #l's are the accordingly days of the month

    while numberOfDays > l:
        numberOfDays  = numberOfDays - l
        if month != 12:
            month += 1
        else:
            month = 1
            year += 1

        if month in [1, 3, 5, 7, 8, 10, 12]:
            l = l3
        elif month in [4, 6, 9, 11]:
            l = l2
        else:
            l = l1

    return  str(day) + ':' + str(month) + ':' + str(year) #i'll deal
    #with fact that it doesn't put the 0's in the < 10 digits later

Desired output:
addnewDate('29:12:2016', 5):

'03:01:2017'

I think the problem is with either the variables, or the position i'm using them in, kinda lost though..
Thanks in advance!
p.s I can't use python build in functions :)

A: Since you cannot use standard library, here's my attempt. I hope I did not forget anything.

*

*define a table for month lengths

*tweak it if leap year detected (every 4 year, but special cases)

*work on zero-indexed days & months, much easier

*add the number of days. If lesser that current month number of days, end, else, substract current month number of days and retry (while loop)

*when last month reached, increase year

*add 1 to day and month in the end

code:
def addnewDate(date, numberOfDays):
    month_days = [31,28,31,30,31,30,31,31,30,31,30,31]

    date = date.split(":")
    day = int(date[0])-1
    month = int(date[1])-1
    year = int(date[2])
    if year%4==0 and year%400!=0:
        month_days[1]+=1

    new_days = 0
    #l's are the accordingly days of the month

    day += numberOfDays

    nb_days_month = month_days[month]

    done = False   # since you don't want to use break, let's create a flag
    while not done:
        nb_days_month = month_days[month]
        if day < nb_days_month:
            done = True
        else:
            day -= nb_days_month
            month += 1
            if month==12:
                year += 1
                month = 0

return  "{:02}:{:02}:{:04}".format(day+1,month+1,year)

test (may be not exhaustive):
for i in ("28:02:2000","28:02:2004","28:02:2005","31:12:2012","03:02:2015"):
    print(addnewDate(i,2))
    print(addnewDate(i,31))

result:
02:03:2000
31:03:2000
01:03:2004
30:03:2004
02:03:2005
31:03:2005
02:01:2013
31:01:2013
05:02:2015
06:03:2015

of course, this is just for fun. Else use time or datetime modules!


text:
Q: Tesseract: High CPU Usage and slow speed, only when running multiple processes in parallel Problem
pytesseract.image_to_string() takes too much time when I run the script through supervisordd, but executes almost instantaneously when run directly in  shell (on the same server and simultaneously with supervisor scripts).
Apart from taking too much time, the processes are also showing high CPU usage.
Time taken by pytesseract.image_to_string() when run via Supervisord: ~30s
Time taken by pytesseract.image_to_string() when run via Bash: 0.1s
This problem only occurs, if there are a lot of processes, executing pytesseract.image_to_string(), being run via supervisord (around 22 instances). If I reduce the number of instances (to around 10), the scripts executed via supervisord also run smoothly.
System Information
OS: Ubuntu 18.04.2 LTS (bionic)
Supervisord: Version 3.3.1
Tesseract: Version 4.0.0-beta.1
Python: Version 3.6
PyTesseract: Version 0.2.5
ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 127357
max locked memory       (kbytes, -l) 16384
max memory size         (kbytes, -m) unlimited
open files                      (-n) 8096
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 127357
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

Let me know if you need any more information.
Edit 1 (or I know what's NOT the source of this problem)
I am fairly certain that it is not an issue with Supervisord.
When I run one instance from an ssh shell, the function (pytesseract.image_to_string()) is executed smoothly (i.e takes only 0.1s), while there are 10 instances being run via Supervisord.
When I start another instance from a new ssh shell, both the instances (ones started from ssh) run smoothly most of the time.
When I start yet another instance from a new ssh shell, all the three instances start choking, taking around 10s to execute the function. This time keeps on increasing as I add more instances via shell.
So the problem can be replicated even with a shell.
More Information
I ran the program with strace -T -f but I could not figure out what exactly is causing the spike in time.
For a function call that takes 1s
Top 10 system calls sorted by time taken
1.504530    [pid 29921] <... wait4 resumed> [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 30166
0.503915    [pid 29932] <... select resumed> )      = 0 (Timeout)
0.503472    [pid 29932] <... select resumed> )      = 0 (Timeout)
0.500524    [pid 29933] <... select resumed> )      = 0 (Timeout)
0.500515    [pid 29933] <... select resumed> )      = 0 (Timeout)
0.500514    [pid 29932] <... select resumed> )      = 0 (Timeout)
0.500512    [pid 29933] <... select resumed> )      = 0 (Timeout)
0.069869    [pid 30169] <... futex resumed> )       = ? ERESTARTSYS (To be restarted if SA_RESTART is set)
0.035989    [pid 30167] <... futex resumed> )       = 0
0.016002    [pid 30168] <... futex resumed> )       = 0

For a function call that takes 9s
Top 10 system calls sorted by time taken
9.795787    [pid 29921] <... wait4 resumed> [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 30106
0.515960    [pid 29933] <... select resumed> )      = 0 (Timeout)
0.511955    [pid 29933] <... select resumed> )      = 0 (Timeout)
0.507979    [pid 29932] <... select resumed> )      = 0 (Timeout)
0.507968    [pid 29932] <... select resumed> )      = 0 (Timeout)
0.505257    [pid 29932] <... select resumed> )      = 0 (Timeout)
0.503988    [pid 29932] <... select resumed> )      = 0 (Timeout)
0.503978    [pid 29932] <... select resumed> )      = 0 (Timeout)
0.503975    [pid 29932] <... select resumed> )      = 0 (Timeout)
0.503974    [pid 29932] <... select resumed> )      = 0 (Timeout)

A: Disabling multiprocessing in tesseract fixed the issue. It can be done by setting OMP_THREAD_LIMIT=1 in the environment.
See https://github.com/tesseract-ocr/tesseract/issues/898#issuecomment-315202167

A: In python process:
import os
os.environ['OMP_THREAD_LIMIT'] = '1'

It fixes threading overhead.


text:
Q: Two code bases in one repository... is there ever a good reason to do this? I work on two code bases that are related, but independent. One is written in PHP, the other is Node JS. Currently, they are in a single repository. The repo is deployed to Heroku for the Node code, and a different hosting provider for the PHP code. I didn't set up the repo, but I now maintain the applications.
Is there any good reason that these code bases should be in the same repo? Would it make a difference if they were in the same language?
PS - the code bases are related but do not share any dependencies, even the databases used are different.

A: The previous project I worked in grouped a lot of different languages and services in the same repository and provided a Vagrant box which provisioned a complete development environment from this.
This meant that all external pages, client facing APIs, internal microservices and so on were accessible from the get go. It just took two commands to get a new developer a workable set of services to start coding away. As Doc Brown points out in his comment it's very important how related the code is. All of the services in this setup were strictly interlinked and unusable without each other - That's not to say there couldn't have been other reasons to split the code base.
Most definitely separate repositories shine at times. The biggest reasons I can see off the top of my head;

*

*If you want to strictly limit access - Perhaps some users are not supposed to be able to access certain applications/languages/code

*Different people work on the different code bases and they have no relation to each other

*The size of an individual language/code base/application is big enough to warrant it

*You start building and utilizing internal/external package repositories - I strongly believe that you should have one repository per package/module you distribute with repositories

With this said, for most in-house development projects where everyone can or should be able to access all the code and no fancy deployment processes are needed a coarser approach is fine. In my current project we've divided the front end and back end code into two separate repositories since there are distinct groups working on their separate sides.
I think the best guiding advice I can give is:

Use one repository until you have a reason to divide the code base into multiple repositories, then ask yourself again if you really have a reason to divide it.

In your case there seems to be reason to divide the repositories but if neither of the above bullet points above are satisfied or it's making you unable to sleep at night I'd strongly advice against splitting the code up right now.


text:
Q: (pyqtgraph) How do I show actual (non-scientific) tick values on a logarithmic Y axis? My first StackOverflow question, apologies for poor format or if this has been asked before (I can't find the answer anywhere). I'm using Python 3 and pyqtgraph.
I want to graph (price) data on a logarithmic y scale, but I want to retain the actual values, not the scientific notation.
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui

pg.mkQApp()

pw = pg.PlotWidget()
pw.show()

myplot = pg.PlotDataItem([1,2,4,8,16,32,64,128])

p1 = pw.plotItem
p1.hideAxis('left')
p1.showAxis('right')
p1.showGrid(y = True, alpha = 1.0)
p1.addItem(myplot)
p1.setLogMode(y=True)

QtGui.QApplication.instance().exec_()

myplot is a straight line as intended in logMode, but tick values are scientific:

I modified a subclass from a related question (PyQtgraph y axis label non scientific notation) and tried to override the AxisItem, but it doesn't seem to 'activate' via myplot. :
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui

class NonScientific(pg.AxisItem):
    def __init__(self, *args, **kwargs):
        super(NonScientific, self).__init__(*args, **kwargs)

    def tickStrings(self, values, scale, spacing):
        return [int(value*1) for value in values] #This line return the NonScientific notation value

    def logTickStrings(self, values, scale, spacing):
        return [int(value*1) for value in values] #This line return the NonScientific notation value

pg.mkQApp()

pw = pg.PlotWidget()
pw.show()

myplot = pg.PlotDataItem([1,2,4,8,16,32,64,128], axisItems={'right': NonScientific(orientation='right')})

p1 = pw.plotItem
p1.hideAxis('left')
p1.showAxis('right')
p1.showGrid(y = True, alpha = 1.0)
p1.addItem(myplot)
p1.setLogMode(y=True)

QtGui.QApplication.instance().exec_()

My questions are:

*

*Am I overriding a subclass correctly? Is AxisItem even the right class to override? If so, is there a way to 'get' the AxisItem of the p1 plotItem? I tried p1.getAxis('right') but don't know how to override the class that way

*Is there a way to retain the actual values along the y axis in a log scale, rather than simply modifying strings, without transforming to log numbers?

What I mean by question 2 is, I have tried a workaround that is probably the wrong way to do it. I added these lines just before the end:
yaxticks = [[(1, '1.00'), (2, '2.00'), (4, '4.00'), (8, '8.00'), (16, '16.00'), (32, '32.00'), (64, '64.00'), (128, '128.00')]]
yax = p1.getAxis('right')
yax.setTicks(yaxticks)

As well as tried this:
yaxticks = [[(0.1, '1.00'), (0.2, '2.00'), (0.4, '4.00'), (0.8, '8.00'), (1.6, '16.00'), (3.2, '32.00'), (6.4, '64.00'), (12.8, '128.00')]]

Results were as follows, compared with original:

Based on where those lines are falling, I can tell I could get this to work by referencing the log values at each point, but this seems unpythonic and a band-aid solution. My application works intimately with price data and I worry all graphical functions that reference price data would need to transform to and from log values.
Is there a better way?


text:
Q: BaseAdapter: ViewHolder/Recycle + SwipeListView = trouble Using BaseAdapter without recycling (inflating views everytime getView(...) is called) my animation and functionality to swipe inside my list item works fine (it also has images thats loading from web).
@Override
public View getView( final int position, View convertView, ViewGroup parent ) {

    View view = myViews.get( position );
    final Promotion i = getItem( position );
    view = a.getLayoutInflater().inflate( R.layout.butik_item, parent, false );
    /* More code */
    }
}

Experience: Poor performance and scrolling is not smooth, animation + swipe works.

Using BaseAdapter with Recycling (array with views and nullchecks with ViewHolder)
Map<Integer, View> myViews = new HashMap<Integer, View>();

@Override public View getView( int position, View convertView, ViewGroup parent ) {
    final ViewHolder holder;
    View v = myViews.get( position );

    if ( v == null ) {
        v = a.getLayoutInflater().inflate( R.layout.butik_item, parent, false );
        /* More code */
    }

    v.setTag( position + "" );
    myViews.put( position, v );
}

Experience: Great performance and scrolling is smooth, animations do not work and swipe is veeeery laggy.

What can I do to fix this?


text:
Q: TPL Data Flow Optimization I have a TPL dataflow set up in this manner:

*

*Download byte array

*Process data

*Stream processed data to another location

This flow works great, but occasionally it runs into a backup while downloading file, connection hiccup, etc.  What I'd like to do is have parallel downloads but still ensure that step 3 is executed such that the receiving party gets the payload in the correct order.
var broadcaster = new BroadcastBlock<string>(d => d);

var downloader = new TransformBlock<string, byte[]>(async data => {
  // Download and return data
});

var processor = new TransformBlock<byte[], byte[]> (async data => {
  // Process and return data
});

var uploader = new ActionBlock<byte[]>(async input => {
  // Upload file to another location
});

broadcaster.LinkTo(downloader);
downloader.LinkTo(processor);
processor.LinkTo(uploader);

broadcaster.SendAsync("http://someUrl");
broadcaster.SendAsync("http://someOtherUrl")

So in the above code snippet, I'd want the two urls to download simultaneously, but it's important that the first one gets processed by the uploader before the second url.  Can somebody point me in the correct direction?

A:
I'd want the two urls to download simultaneously, but it's important that the first one gets processed by the uploader before the second url

Then just set MaxDegreeOfParallelism on that block and it will behave like this. When URLs 1 and 2 are being downloaded simultaneously and 2 completes before 1 does, it will still wait for 1 to complete before 2 is sent to the following block.
This might not be the most efficient approach, but it does ensure that the order of processing is maintained across all blocks in a pipeline.


text:
Q: C# Regular expression contains specific word i try to write a regular expression.
Considers this string [converter:mystringornotmystring]
I want get mystringornotmystring
See my bad code
regEx = new Regex(@"\[((?:.|\n)*?).\]");
            foreach (Match m in regEx.Matches(stb.ToString()))
            {
                myfunction (m.Value);
            }

[converter:] is keyword
Can you help me and complete my regex please,
thanks

A: Cédirc, It's slightly unclear what you need here, given your comment:

my string can contains a lot of "[converter:xxx]"

However, if we're talking just about a single instance of this string, as per the original question, then the pattern you need is simpler than your initial attempt.
I am assuming that you don't care what the keyword is since you didn't address this in your initial attempt - you only want to pull the 'parameter' from the string.
Basically, what you want is a [ followed by some characters (we don't care what) then a : then some characters (that we want to identify) then a ].
regEx = new Regex(@"\[.*:(.*)\]");
        foreach (Match m in regEx.Matches(stb.ToString()))
        {
            myfunction (m.Value);
        }

The first thing to do (which you tackled correctly) is to match an opening [.  This is a special character in RegEx so needs to be escaped - \[.
To identify a single character (when we don't care what the character is) we use a dot (.).
Where we want to identify more than one of something, we have to tell the regex how many - we do this by applying "cardinality".  A * indicates zero-or-more, a + indicates one-or-more.  There are other more specific ways of stating the number of matches, which I'll leave you to look up.  There are also "greedy" and "lazy" versions of cardinality - but let's stick to the problem at hand.
So - .* means zero-or-more characters.
And \[.* means a [ followed by zero-or-more characters.
We then specify the :.  This is a specific character to match.
So - [\.*: means a [ followed by zero-or-more characters and then a :.
This is easy, right?
Now to complete the pattern we want another set of zero-or-more characters and a closing ] (which we escape).
\[.*:.*\]
We use brackets () to surround a group we want to "capture".  In this instance, we only want to capture the second set of zero-or-more characters:
\[.*:(.*)\]
And there you have it.
Check out the link that L.Gutgart left you - it has lots of information that you may find useful in future.
You can also test your patterns at sites such as http://regexstorm.net/tester.


text:
Q: Is there a quantile function in R that includes both given x and given probs? Sorry for my bad english.
I need a function in R that calculates x values similar as the quantile function does, but considering that the x values were already calculated with a quantile function.
As example: I have a simple data frame that consists of two columns as given:

probs
x

0.06
-120

0.1
-100

0.2
-97

0.24
-90

0.3
-80

0.5
-70

0.7
-60

0.89
-50

1
-40

(in fact the data is more detailed but for an example it will be enough)
The x values are calculated by a quantile function in the past but I have no access to the original x data. Is there a function like the quantile function that doesn't ignore the weighting and that calculates more quantiles in between those values?

A: I think you just want to do a linear interpolation.  For example,
dat <- structure(list(probs = c(0.06, 0.1, 0.2, 0.24, 0.3, 0.5, 0.7,
                                0.89, 1), x = c(-120, -100, -97, -90, -80, -70, -60, -50, -40
                                )), class = "data.frame", row.names = c(NA, -9L))

fn <- approxfun(dat$probs, dat$x)
fn(c(0.1, 0.15, 0.2))
#> [1] -100.0  -98.5  -97.0

Created on 2022-02-15 by the reprex package (v2.0.1.9000)


text:
Q: How add directory or all files in a directory by nodegit? I am new on node js and on git as well, i am building an app that will write results on text files and will push on git rapidly.
After many struggle I have figured out following code that is writing file and pushing on github. But I am seeking a way by which I can push whole directory instead of each file by name. So please let me know the way how to push whole directory.
My current code is as following...
var nodegit = require("nodegit");
var path = require("path");
var promisify = require("promisify-node");
var fse = promisify(require("fs-extra"));
var fileName = "urls.txt";
var fileContent = "hello world";
var directoryName = "./";
fse.ensureDir = promisify(fse.ensureDir);
var repo;
var index;
var oid;
var remote;

nodegit.Repository.open('data')
.then(function(repoResult) {
  repo = repoResult;
  return fse.ensureDir(path.join(repo.workdir(), directoryName));
}).then(function(){
  return fse.writeFile(path.join(repo.workdir(), fileName), fileContent);
})
.then(function() {
  return fse.writeFile(
     path.join(repo.workdir(), directoryName, fileName),
     fileContent
  );
})
.then(function() {
  return repo.refreshIndex();
})
.then(function(indexResult) {
  index = indexResult;
})
.then(function() {
  // this file is in the root of the directory and doesn't need a full path
  return index.addByPath(fileName);
})
.then(function() {
  // this file is in a subdirectory and can use a relative path
  return index.addByPath(path.join(directoryName, fileName));
})
.then(function() {
  // this will write both files to the index
  return index.write();
})
.then(function() {
  return index.writeTree();
})
.then(function(oidResult) {
  oid = oidResult;
  return nodegit.Reference.nameToId(repo, "HEAD");
})
.then(function(head) {
  return repo.getCommit(head);
})
.then(function(parent) {
  var author = nodegit.Signature.create("Scott Chacon",
    "schacon@gmail.com", 123456789, 60);
  var committer = nodegit.Signature.create("Scott A Chacon",
    "scott@github.com", 987654321, 90);

  return repo.createCommit("HEAD", author, committer, "message", oid, [parent]);
})
.then(function() {
  return repo.getRemote("origin")
  .then(function(remoteResult) {
    remote = remoteResult;

    // Create the push object for this remote
    return remote.push(
      ["refs/heads/master:refs/heads/master"],
      {
        callbacks: {
          credentials: function(url, userName) {

            return nodegit.Cred.userpassPlaintextNew('username', 'password');
          }
        }
      }
    );
  });
})
.done(function(res) {
  console.log("Done");
});

A: You should be able to use index.addAll to do what you are asking.
See: https://github.com/nodegit/nodegit/issues/131


text:
Q: Error on Latitude and Longitude - Google Maps API JS 3.0 After a while, Google Maps seems to change the property name (Qa or Pa) to Na or another name.
var map;
function initialize() {
  var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
  var myOptions = {
    zoom: 4,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  google.maps.event.addListener(map, 'click', function(event) {
    AlertPos(event.latLng);
  });
}

function AlertPos (location) {

    // try to show the latitude and longitude
    document.getElementById('lat').value = location.Qa;
    document.getElementById('long').value = location.Pa;
    alert(location.Qa)
    alert(location.Pa)
}

This affects my application. Can any body help?

A: Use lat() and lng():
function AlertPos (location) {
    // try to show the latitude and longitude
    document.getElementById('lat').value = location.lat();
    document.getElementById('long').value = location.lng();
    alert(location.lat());
    alert(location.lng());
}


text:
Q: Can I set an end time for AlarmManager in Android? I have set up an AlarmManager to go off at a specific time, and then repeat in intervals. Is it possible to tell it after how many intervals to stop? Or even at what time to stop?
This is what I have so far:
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 13);
    calendar.set(Calendar.MINUTE, 56);
    Intent intent = new Intent(this, MyService.class);
    alarmIntent = PendingIntent.getService(this, 0, intent, 0);
    alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            1000 * 60 * 60, alarmIntent);

Also do I need to do anything to ensure it will go off every day? Or is it already doing that?

A:
Is it possible to tell it after how many intervals to stop? Or even at what time to stop?

There's no way to specify an end time for an AlarmManager, but what you can do is, every time you receive your pending intent in your broadcast receiver, check to see if you need to cancel that alarm.  To cancel the alarm, you need to call alarmManager.cancel(pendingIntent), where pendingIntent has the same requestCode that you used for the PendingIntent that you originally created the alarm with.

Also do i need to do anything to ensure it will go off every day?

You need to set the interval to:  1000 * 60 * 60 * 24  if you want it to fire once per day.
You also need to take care of the situation of a device reboot.  If the user reboots the device, the alarms will be cleared and you need to recreate them.  You will need to implement another BroadcastReceiver that listens for RECEIVE_BOOT_COMPLETED, and add logic in your onReceive() to recreate your alarms.
Also, this line is unnecessary:
calendar.setTimeInMillis(System.currentTimeMillis());

This line:
Calendar calendar = Calendar.getInstance();

already gives you a Calendar object set to the exact time you create it.
You should also add the following lines to make sure your alarm fires at exactly 13:56 each day:
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);


text:
Q: Why does Scalaz show up in my project's API docs? Suppose my entire project configuration is this simple build.sbt:
scalaVersion := "2.11.4"

libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.1.0"

And this is my code:
import scalaz.Equal
import scalaz.syntax.equal._

object Foo {
  def whatever[A: Equal](a: A, b: A) = a === b
}

Now when I run sbt doc and open the API docs in the browser, I see the scalaz package in the ScalaDoc root package listing, together with my Foo:
object Foo
package scalaz

Or, in case you don't believe me:

I've noticed this with Scalaz before, and I'm not the only one it happens to (see for example the currently published version of the Argonaut API docs). I'm not sure I've seen it happen with any library other than Scalaz.
If I don't actually use anything from Scalaz in my project code, it doesn't show up. The same thing happens on at least 2.10.4 and 2.11.4.
Why is the scalaz package showing up here and how can I make it stop?

A: I noticed this too. It also happens with the akka.pattern package from Akka as well as for example the upickle package from the upickle project.
Those three packages have two things in common:

*

*They are package objects

*They define at least one type in a mixin trait.

So I did a little experiment with two projects:
Project A:
trait SomeFunctionality {
  class P(val s: String)
}

package object projectA extends SomeFunctionality

Project B (depends on Project A):
package projectB
import projectA._

object B extends App {
  val p = new P("Test")
}

And voila: in the ScalaDoc of Project B appear two packages in the root package:
projectA
projectB

It seems like both criteria above have to be met, since eliminating one solves the issue.
I believe this is a bug in the scala compiler. So I can not help you with avoiding this since the only way would be to change the sources of scalaz in this case. Changing anything in ProjectB except for removing all references to ProjectA didn't help.

Update: It seems like you can instruct the compiler to exclude specific packages from scaladoc.
scaladoc -skip-packages <pack1>:<pack2>:...:<packN> files.scala

So this would be a workaround here


text:
Q: Don't ask me to approve closure of questions I edited The closure review queue can include questions I edited but chose not to vote to closure. This seems pointless: if I edited the question I've read it; if I've edited it but not already voted to close it, I must have already decided the question is worth keeping.

A:
if I edited the question I've read it; if I've edited it but not already voted to close it, I must have already decided the question is worth keeping.

While that's certainly plausible, some folks do edit questions they think should be closed, without then voting to close. Possible reasons:

*

*They want to give the author a bit of time to add some missing information before voting.

*Their edit fixed whatever problems were affecting the question, but then the author edited them back in / rolled back the fixes.

*The question was already closed when they edited, and was later re-opened.

*They don't want their name to appear first in the list of close-voters for some reason.

*They lacked the reputation to vote to close when they made the edit.

*Their computer died immediately after their edit was submitted, and they lost track of the question due to the distraction.

*As above, but involving the temporary death of the editor rather than the computer.

*They meant to click "close" but instead clicked "edit" and were too lazy to go back so made some minor edit instead.

*They were looking for an "on hold" button but couldn't find one, so gave up.

As Manishearth notes, you can still click "Leave Open". Heck, you can even edit it again if you see something you missed.

A: If you've decided the question is worth keeping, then give it a "Leave Open" vote.
Also, it won't always be the case that you edited it but "felt it was worth keeping open". If you were making a formatting edit, you may not have realized the other issues in the first place.


text:
Q: Compiling / testing Haskell without a main function I'm working on an assignment in Haskell. However, the base code I am working with does not have a main function defined, and from the wording of the assignment I believe I am not expected to have to write any code outside of the solution to the problem. However, when I try to compile my code, I receive the error:
The IO function 'main' is not defined in module 'Main'

I assume this is because the function does not have a main function. However, when I try to write my own main function:
main :: IO ()
main = solve easy // easy is an array

I get the error:
Couldn't match expected type 'IO()' with actual type '[Int]'

The solve function's type is declared as follows:
solve :: [Int] -> [Int]

So it takes an array and returns an array. What am I doing wrong in writing my main function? Even when I try changing the declaration of main to things like:
main :: [Int]

or
main :: IO [Int]

I still can't get it to compile.

A: Without writing a proper main with a correct type, as described by @G Philip, you can load your file in ghci by writing ghci file.hs in your terminal, or by invoking :l file.hs inside ghci.

A: Firstly: the function main must have type IO t for some type t. When the program is executed, the computation defined by main is executed, and its result (of type t) is thrown away; see here.
So, in particular, you cannot have the type of main as [Int] and have the compiler not complain.
Depending on whether you want to see the results of solving the easy case or not, you can try one of the following:
If you want to see the results: print them!
main :: IO ()
main = putStrLn $ show (solve easy)

If you are not interested in seeing the results, throw them away:
main :: IO ()
main = let solution = solve easy
       in putStrLn ""

Edit: Note, however, that if you do the latter, then (as @yatima2975 mentions in a comment) the "solve easy" part will not be evaluated.

A: Just to add to the other answers:
you don't need to write a main function and can still compile the file into a lib and the easiest way to do this is just giving a module name (that is not Main):
module MyCode where

solve :: ...

But of course compiling it might not make any sense anymore (as you will not be able to run it - and of course even if you have not specified what to output anyway).
So in this case rather load the file into ghci:
ghci MyFile.hs

and then everytime you changed something in your code you can do :r inside ghci to reload it.
Or even better set up your favorite editor (emacs and vi are quite easy but sublime text and some other works great too) to give you integrated ghci - this explains what you need to do to setup emacs with haskell-mode if you are interested.

A: Consider
main :: IO ()
main = do
    let res = solve easy // easy is an array
    return ()

where return () yields a result of type Unit which conveys with the type signature of main. Note solve easy is bound to res which is not used further.


text:
Q: How to determine whether a point is inside or outside a 3D model computationally I have a .obj and .ply file of a 3D model.
What I want to do is read this 3D model file and see if a list of 3D coordinates are either inside or outside the 3D model space.
For example, if the 3D model is a sphere with radius 1, (0,0,0) would be inside (True) and (2,0,0) would be outside (False). Of course the 3D model I'm using is not as simple as a sphere.
I would like to add some of the methods I considered using.
Since I am using Python, I thought of using PyMesh, as their intersection feature looked promising. However the list of coordinates I have are not mesh files but just vectors, so it didn't seem to be the appropriate function to use.
I also found this method using ray casting. However, how to do this with PyMesh, or any other Python tool is something I need advice on.

A: Cast a ray from the 3D point along X-axis and check how many intersections with outer object you find.
Depending on the intersection number on each axis (even or odd) you can understand if your point is inside or outside.
You may want to repeat on Y and Z axes to improve the result (sometimes your ray is coincident with planar faces and intersection number is not reliable).

A: Converting my comment into an answer for future readers.
You can use a Convex Hull library to check whether a point is inside the hull. Most libraries use signed distance function to determine whether the point is inside. trimesh is one of the libraries that implements this feature.


text:
Q: Create Object or Blob from a specified url I need to have a blob or any other object forms like arraybuffer so I can display a file (like image,video) in the web-app I've been making.(the web-app is built with only Javascript and html5)
The blob/objects will be stored locally inside the browser with IndexedDB or any other possible method, so that anytime when I open the web, I don't have to download the whole image/video from the specified URL,
For example, I need to display certain images/videos from these url:

*

*www.abcde.com/BBC.jpg

*gamedomain/content/orphan.mp4

*www.abc.net/content.png

usually, the image/video will be displayed using img or video tag in HTML5 respectively,
but now I want to have those content stored as blob or arraybuffer,
How can I do that?


text:
Q: Add Event Listener not working I have a problem that i never had before.
I wanna call a function when a mobile device change is orientation, so i'm using "onorientationchange" and to be sure it's triggered, i also use "onresize".
The problem is that the even don't work on the page for a mysterious reason :
if i do
document.body.addEventListener("resize",function(){console.log("here")};

it doesn't work, I so created a custom  version of AddEventListener :
function addNewEvent(elementDOM, evenement, fonction){
        var refEvent = null;
        if(elementDOM)
        {
        elementDOM["on"+evenement] = fonction;
            if (elementDOM.attachEvent)
            {
                refEvent =function() {
                    return fonction.call(elementDOM,window.event);
                };
                elementDOM.attachEvent ('on'+evenement,refEvent);
            }
            else if (elementDOM.addEventListener)
            {
                refEvent = fonction;
                elementDOM.addEventListener (evenement,refEvent,false);
            }
            else
            {
                elementDOM["on"+evenement] = fonction;
            }
        }
        return refEvent;
    },

And even this one don't work...
BUT this works :
document.body.onresize = function(){console.log("here")};

it's a normal webpage, i don't get why it doesn't work.
Can you help? :x

A: resize events fire on the window object, not the body element.
You're listening for it in the wrong place.
window.addEventListener("resize",function(e){console.log("here", e.target)};


text:
Q: CakePHP: Encrypt password in config file I don't want to store my password for my database configuration in plain text in the database.php for revision control reasons.
I want something like this:
public $default = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'root',
    'password' => simpleEncryptFunction('v3RyH4rD3NcRyPtEdPaS$wOrD'),
    'database' => 'sample',
    'prefix' => '',
    //'encoding' => 'utf8',
);

private function simpleEncryptFunction($hardPassword == null) {
   // Some pretty easy decrypt code. Not safe at all but I don't care.
   // It just shouldn't be that easy for people who don't understand code.
}

A: ndm's comment is right, your approach is flawed. Instead do this:

*

*Create a database.default.php and put the default values in it without passwords and commit it.

*Put database.php in your .gitignore, this file should never going to be committed.

*Change your deploy script to automatically copy database.default.php to default.php and replace the password value with whatever is needed

*For development your developers will have to do it manually (or by a script)

The same concept can be applied to bootstrap.php as well. And check this plugin out, we're using it for a project to have multiple environments configured and loaded conditionally.


text:
Q: Reload application in Swift I have function in my app:
func saveDownloadFiles(fileInternetUrl: URL, fileName: String, savedURL: String){
        let cms = ServerConnect()
        cms.downloadedFileFromInternet(fileInternetUrl: fileInternetUrl, directory: savedURL, fileName: fileName ,  completion: { (data) in
            switch data {
            case .succes:
                print("DOWNLOAD: \(savedURL)/\(fileName)")
            case .error(let error):
                //self.errorLoginMessage(txt: "MainView - Error 110: Problem with download images. \(error)", title: "Blad".localized())
                print("")
                break
            }
        })
    }

I would like to reload the application after performing it.
The best solution for me would be to disable and enable the application again. If you can not, maybe you can at least return to splash and then display the main view again?

A: Can you be more clear because there is no possible to enable and disable the application. If you need to Reload all the things with UI just call again the functions which are using inside the viewDidLoad.


text:
Q: Remove (duplicate) failed TestNG result via test listener Similar to the solution posted here TestNG retrying failed tests doesn't output the correct test results, I'm trying to remove a (duplicate) test result using a test listener during onFinish(ITestContext context).
Although the removal of the result with context.getFailedTests().removeResult(result) appears to work fine (the result actually is removed), there seems to be "some other spot" where the results are being pulled from cause the build still fails.
Also note that when I run the sample test from the article above (which has one duplicate failure to be removed and one passed test), I get a difference in "test results" (not cleaned up as expected) vs. "suite results" (duplicate failure removed as expected).
And, where is the reporting pulling the results from to decide whether to fail the build? Or is it just that it's pulling the results before I'm cleaning up the failed tests ... ?
===============================================
    Default test
    Tests run: 3, Failures: 2, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 2, Failures: 1, Skips: 0
===============================================

EDIT: Just to clarify, we're running those tests with maven, and they are ITs, so we run them with the failsafe plugin. The problem is that even though it appears that the tests are removed, mvn verify still fails the build as it considers build failures to be found regardless.
And also if run such a test from Eclipse, even though the tests are removed, failures are still being printed in the log when the suite finishes.
About RetryAnalyzer: I would not consider using RetryAnalyzer good/best practice at all, but if you find yourself in a situation where you need to solve the problem, e.g. you inherited a test suite that is relying on RetryAnalyzer, you may find this useful.

A: Try using this code:
ListenerApadter:
public class MyTestListenerAdapter extends TestListenerAdapter {
    @Override
    public void onTestFailure(ITestResult result) {
        if (result.getMethod().getRetryAnalyzer() != null) {
            MyRetryAnalyzer retryAnalyzer = (MyRetryAnalyzer)result.getMethod().getRetryAnalyzer();

            if(retryAnalyzer.isRetryAvailable()) {
                result.setStatus(ITestResult.SKIP);
            } else {
                result.setStatus(ITestResult.FAILURE);
            }
            Reporter.setCurrentTestResult(result);
        }
    }

   @Overrride
   public void onFinish(ITestContext context) {
     Iterator<ITestResult> failedTestCases =context.getFailedTests().getAllResults().iterator();
    while (failedTestCases.hasNext()) {
        System.out.println("failedTestCases");
        ITestResult failedTestCase = failedTestCases.next();
        ITestNGMethod method = failedTestCase.getMethod();
        if (context.getFailedTests().getResults(method).size() > 1) {
            System.out.println("failed test case remove as dup:" + failedTestCase.getTestClass().toString());
            failedTestCases.remove();
        } else {

            if (context.getPassedTests().getResults(method).size() > 0) {
                System.out.println("failed test case remove as pass retry:" + failedTestCase.getTestClass().toString());
                failedTestCases.remove();
            }
        }
    }
   }
}

RetryAnalizer:
public class MyRetryAnalyzer implements IRetryAnalyzer {
    private static int MAX_RETRY_COUNT = 3;

    AtomicInteger count = new AtomicInteger(MAX_RETRY_COUNT);

    public boolean isRetryAvailable() {
        return (count.intValue() > 0);
    }

    @Override
    public boolean retry(ITestResult result) {
        boolean retry = false;
        if (isRetryAvailable()) {
            System.out.println("Going to retry test case: " + result.getMethod() + ", " + (MAX_RETRY_COUNT - count.intValue() + 1) + " out of " + MAX_RETRY_COUNT);
            retry = true;
            count.decrementAndGet();
        }
        return retry;
    }
}

POM.xml -> Surefire Configuration:
This is where you should configure "overwrite" surefire listener wich has their own counters.
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>2.18.1</version>
  <configuration>
    <suiteXmlFiles><suiteXmlFile>${basedir}/testng.xml</suiteXmlFile></suiteXmlFiles>
 <properties>
   <property>
    <name>listener</name>
    <value>Utils.MyTestListenerAdapter,Utils.MyRetryAnalizer</value>
   </property>
 </properties>

A: I ended up going for a solution that uses a suite listener.
The solution may not fully clean up what TestNG / your tests log to the console, but if you use the TestNG Jenkins plugin, and had a failure first on every test, and then success, the test run ends up to be green, which I guess is the most important thing.
And yes, we run mvn integration-test (not mvn verify) and let the TestNG plugin deal with pass / fail. The solution is quite similar / builds on what was posted here.
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.ISuite;
import org.testng.ISuiteListener;
import org.testng.ISuiteResult;
import org.testng.ITestContext;

/**
 * {@link ISuiteListener} implementation to clean up duplicate test results caused by retrying tests using the
 * {@link RetryAnalyzer}
 */
public class SuiteResultListener implements ISuiteListener {

    private static final Logger LOG = LogManager.getLogger();

    @Override
    public void onStart(ISuite suite) {
    }

    @Override
    public void onFinish(ISuite suite) {
        LOG.info("Cleaning up duplicate test failures in suite '" + suite.getName() + "' ...");
        final Map<String, ISuiteResult> results = suite.getResults();
        int removedFailures = 0;
        for (ISuiteResult result : results.values()) {
            final ITestContext testContext = result.getTestContext();

            removedFailures += TestListenerUtil.cleanUpDuplicateFailures(testContext);
        }

        LOG.info("Removed " + removedFailures + " duplicate test failure(s) from suite '" + suite.getName() + "'");
    }
}

And here's the magic that happens in the TestListenerUtil class:
public static int cleanUpDuplicateFailures(ITestContext testContext) {
    final String testContextName = testContext.getName();
    int removedFailures = 0;

    LOG.info("Cleaning up failures in test context '" + testContextName + "' ...");
    final Set<ITestResult> failedTests = testContext.getFailedTests().getAllResults();
    if (failedTests.isEmpty()) {
        LOG.info("There are no failures in test context '" + testContextName + "'\n");
    } else {
        // collect all id's from passed test
        final Set<Integer> passedTestIds = new HashSet<>();
        final Set<ITestResult> passedTests = testContext.getPassedTests().getAllResults();
        LOG.info("Analyzing " + passedTests.size() + " passed test(s)");
        for (ITestResult result : passedTests) {
            final int testId = TestListenerUtil.getId(result);
            passedTestIds.add(testId);
            LOG.info("  Passed test " + TestListenerUtil.getName(result) + ": #" + testId + " @ "
                    + getStartTime(result));
        }

        // check which failed test results should be removed
        final List<Integer> resultsToBeRemoved = new ArrayList<>();
        final Set<Integer> failedTestIds = new HashSet<>();

        LOG.info("Analyzing " + failedTests.size() + " failed test(s)");
        for (ITestResult result : failedTests) {
            final int testId = TestListenerUtil.getId(result);
            final String name = TestListenerUtil.getName(result);

            // if we saw this test pass or fail before we mark the result for deletion
            if (failedTestIds.contains(testId) || passedTestIds.contains(testId)) {
                LOG.info("  Adding test " + name + " to be removed: #" + testId + " @ " + getStartTime(result));
                resultsToBeRemoved.add(testId);
            } else {
                LOG.info("  Remembering failed test " + name + ": #" + testId + " @ " + getStartTime(result));
                failedTestIds.add(testId);
            }
        }

        // finally delete all duplicate failures (if any)
        final int duplicateFailures = resultsToBeRemoved.size();
        if (duplicateFailures > 0) {
            LOG.info("Cleaning up failed tests (expecting to remove " + resultsToBeRemoved.size()
                    + " result(s)) ...");
            for (ITestResult result : testContext.getFailedTests().getAllResults()) {
                final int testId = TestListenerUtil.getId(result);
                final String info = TestListenerUtil.getName(result) + ": #" + testId + " @ "
                        + getStartTime(result);
                if (resultsToBeRemoved.contains(testId)) {
                    LOG.info("  Removing failed test result " + info);
                    testContext.getFailedTests().removeResult(result);
                    resultsToBeRemoved.remove((Integer) testId);
                    removedFailures++;
                } else {
                    LOG.info("  Not removing failed test result " + info);
                }
            }
        }

        if (removedFailures == duplicateFailures) {
            LOG.info("Removed " + removedFailures + " failed test result(s) in '" + testContextName + "'\n");
        } else {
            LOG.warn("Removed " + removedFailures + " failed test result(s) in '" + testContextName
                    + "' (expected to remove " + duplicateFailures + ")\n");
        }
    }

    return removedFailures;
}

With those two additional utils methods:
public static String getName(ITestResult result) {
    final List<String> parameters = new ArrayList<>();
    if (result.getParameters() != null) {
        for (Object parameter : result.getParameters()) {
            if (parameter instanceof TestResult && ((TestResult) parameter).getStatus() < 0) {
                // TestResult.toString() will explode with status < 0, can't use the toString() method
                parameters.add(parameter.getClass().getName() + "@" + parameter.hashCode());
            } else {
                parameters.add(parameter == null ? "null" : parameter.toString());
            }
        }
    }

    return result.getTestClass().getRealClass().getSimpleName() + "." + result.getMethod().getMethodName() + "("
            + StringUtils.join(parameters, ",") + ")";
}

public static int getId(ITestResult result) {
    final HashCodeBuilder builder = new HashCodeBuilder();
    builder.append(result.getTestClass().getRealClass());
    builder.append(result.getMethod().getMethodName());
    builder.append(result.getParameters());
    return builder.toHashCode();
}

And also, if you're interested how our RetryAnalyzer works, see below.
One thing that is important to understand, is that we're taking the the parameters of the test method into account in both the RetryAnalyzer and the duplicate result clean up. Those are relevant cause we often work with DataProviders.
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;

public class RetryAnalyzer implements IRetryAnalyzer {

    private static final Logger LOG = LogManager.getLogger();

    private static Integer maxRetries;
    private final Map<Integer, Integer> retryCount = new HashMap<>();

    @Override
    public boolean retry(ITestResult result) {
        // only re-try failures
        if (result.getStatus() == ITestResult.FAILURE) {
            final String testName = TestListenerUtil.getName(result);
            final int count = getRetryCount(result);
            final int maxRetriesAllowed = getMaxRetriesAllowed();
            if (count < maxRetriesAllowed) {
                retryCount.put(TestListenerUtil.getId(result), count + 1);
                LOG.info("Retrying test (attempt " + (count + 1) + "/" + maxRetriesAllowed + "): " + testName);
                return true;
            } else {
                LOG.error("Failing test after " + count + " retries: " + testName);
            }
        }

        return false;
    }

    public boolean canRetry(ITestResult result) {
        return result.getStatus() == ITestResult.FAILURE && getRetryCount(result) < getMaxRetriesAllowed();
    }

    private int getRetryCount(ITestResult result) {
        final int testId = TestListenerUtil.getId(result);
        return retryCount.containsKey(testId) ? retryCount.get(testId) : 0;
    }

    public static int getMaxRetriesAllowed() {
        return maxRetries == null ? Config.MAX_TEST_RETRIES : maxRetries;
    }
}

A: You can also try below code
   @AfterTest
public void afterTest(ITestContext context) {
       Set<ITestResult> passedTests = context.getPassedTests().getAllResults();
       passedTests.forEach(i -> {
           if (context.getFailedTests().getAllMethods().contains(i.getMethod())) {
               context.getFailedTests().getAllMethods().remove(i.getMethod());
           }
        });
}


text:
Q: CakePHP find all not setting values to variables. All other find functions working In my controller I have two functions that pull all records from the db with a status = 4.  In one function it works fine.  I copied the find all statement from the working function:
$this->set('completed', $this->Topic->find('all', array('fields' => array(
                    'Topic.creator','Topic.link','Topic.id', 'Topic.topic_name', 'Topic.info', 'Topic.priority', 'Topic.user_id',
                    'Topic.completed','Topic.created', 'Topic.status','User.name','User.id','Topic.category','Topic.tags'),'conditions' => array(
                    'Topic.status' => 4))));

But in the new function the $completed array doesn't seem to exist.  The debug statement is just a blank line.  If I debug the sql log using debug($this->Topic->getDataSource()->getLog()); this is the returned array:
Array
(
[log] => Array
    (
        [0] => Array
            (
                [query] => SELECT `Topic`.`creator`, `Topic`.`link`, `Topic`.`id`, `Topic`.`topic_name`, `Topic`.`info`, `Topic`.`priority`, `Topic`.`user_id`, `Topic`.`completed`, `Topic`.`created`, `Topic`.`status`, `User`.`name`, `User`.`id`, `Topic`.`category`, `Topic`.`tags` FROM `topics` AS `Topic` LEFT JOIN `users` AS `User` ON (`Topic`.`user_id` = `User`.`id`) LEFT JOIN `events` AS `Event` ON (`Event`.`topic_id` = `Topic`.`id`)  WHERE `Topic`.`status` = 4
                [affected] => 9
                [numRows] => 9
                [took] => 0
            )

    )

[count] => 1
[time] => 0
)

The SQL statement in the log works.  If I plug in into mySQL it produces results.  And the affected and numRows field show the correct number of records.  But the produced data isn't being set to variables.  Any ideas would be greatly appreciated.  My boss and I are stumped.  Here are both complete functions:
         public function dashboard(){
            $this->set('completed', $this->Topic->find('all', array('fields' => array(
                    'Topic.creator','Topic.link','Topic.id', 'Topic.topic_name', 'Topic.info', 'Topic.priority', 'Topic.user_id',
                    'Topic.completed','Topic.created', 'Topic.status','User.name','User.id','Topic.category','Topic.tags'),'conditions' => array(
                    'Topic.status' => 4))));
            $this->set('total_inprogress_release', $this->Topic->find('count', array('conditions' => array(
                    'OR' => array('status <>' => 4,'status <>' => 0),
                    'priority' => 4))));
    $this->set('upcoming_events', $this->Topic->Event->find('all'));
            $this->Topic->virtualFields['count'] = 'COUNT(*)';
            $this->set('graph_data', $this->Topic->find('chart', array('fields' => array('status_txt', 'priority_txt', 'count'), 'group' => array('status', 'priority'),
                    'chart' => array(
                            'xaxisTitle' => 'Status',
                            'yaxisLabels' => array('Release', 'Company', 'News'),
                            'xaxisLabels' => array('Open','In Progress','Completed'),
                            'yaxis' => 'Topic.priority_txt',
                            'xaxis' => 'Topic.status_txt',
                            'data' => 'Topic.count'
            ))));
    }

And here's the nonworking function:
        public function completed(){
            $foo = $this->Topic->find('all', array('fields' => array(
                    'Topic.creator','Topic.link','Topic.id', 'Topic.topic_name', 'Topic.info', 'Topic.priority', 'Topic.user_id',
                    'Topic.completed','Topic.created', 'Topic.status','User.name','User.id','Topic.category','Topic.tags'),'conditions' => array(
                    'Topic.status' => 4)));
            debug($foo);
            debug($this->Topic->getDataSource()->getLog());

    }

A: After several hours of tracking the data until we figured out where it was being lost, we found that the problem was some of the data in the database.  It was encoded and it was causing a while statement in the core cake files to reset when it encountered said data.  The solution was to alter Config/database.php as such:
    class DATABASE_CONFIG {
    public $default = array(
            'datasource' => 'Database/Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'login' => 'login',
            'password' => 'Password',
            'database' => 'database',
            'prefix' => '',
            'encoding' => 'utf8',//this line allows the database to read utf8 data.
    );

}

A: I think the relationships may be causing an issue here. Try this in the completed function and pr($foo) the results:
$foo = $this->Topic->find('all', array(
    'fields' => array(
        'Topic.creator',
        'Topic.link',
        'Topic.id',
        'Topic.topic_name',
        'Topic.info',
        'Topic.priority',
        'Topic.user_id',
        'Topic.completed',
        'Topic.created',
        'Topic.status',
        'User.name',
        'User.id',
        'Topic.category',
        'Topic.tags'
    ),
    'conditions' => array(
        'Topic.status' => 4,
    ),
    'joins' => array(
        array(
            'table' => 'users',
            'alias' => 'User',
            'type' => 'LEFT',
            'conditions' => array(
                'Topic.user_id = User.id'
            ),
        ),
    ),
    'recursive' => -1,
));

I suspect you will get the results you are looking for.


text:
Q: How can I display something like "5 was rolled the most often (25 times)" at the bottom of this code? As the question says, I need to display the most common dice roll and its frequency. It's a simulation and analysis question for school. I need the last line printed to read something like "x was rolled the most often (y times)"
from random import randint

print("Dice simulation and analysis program")
results = []
frequencies = [0, 0, 0, 0, 0, 0]

# Loop 100 times
for i in range (100):
    throw_result = randint(1,6) # store a random value between 1 and 6
    results.append(throw_result) # append each value to results

    # Start to build up a list of frequencies for each value thrown
    if throw_result == 1:
        frequencies[0] = frequencies[0] + 1
    elif throw_result == 2:
        frequencies[1] = frequencies[1] + 1
    elif throw_result == 3:
        frequencies[2] = frequencies[2] + 1
    elif throw_result == 4:
        frequencies[3] = frequencies[3] + 1
    elif throw_result == 5:
        frequencies[4] = frequencies[4] + 1
    elif throw_result == 6:
        frequencies[5] = frequencies[5] + 1

print()
# print("Results:", results)
print("Frequences:", frequencies)

print("Dice Frequency")
print("---- ---------")
print("1    ", frequencies[0])
print("2    ", frequencies[1])
print("3    ", frequencies[2])
print("4    ", frequencies[3])
print("5    ", frequencies[4])
print("6    ", frequencies[5])

A: max will give you the highest value in an iterable. We can use index() on the frequencies array to find the index of the highest element. These two together give you the information you need to print your statement.
most_rolls = max(frequencies)
print(f"{frequencies.index(most_rolls) + 1} was rolled the most often ({most_rolls} times)")

A: max_ix = max(range(len(frequencies)), key= lambda x: frequencies[x])
print(f"{max_ix+1} was rolled the most often ({frequencies[max_ix]} times)")

Or easier way, you can use numpy.argmax

A: You should really use
frequencies[i] += 1

instead of creating 6 different if/else statements.
And to print the final frequencies, use a for loop:
for i in range(6):
   print(str(i + 1) + "    ", frequencies[i])


text:
Q: Databricks Connect java.lang.ClassNotFoundException I updated our databricks cluster to DBR 9.1 LTS on Azure Databricks, but a package I use regularly is giving me an error when I try to run it in VS Code with Databricks-connect, where it didn't with the previous cluster. The previous cluster was running on DBR 8.3. I updated the package too to be compatible with the new DBR cluster. The maven coordinates are
com.azure.cosmos.spark:azure-cosmos-spark_3-1_2-12:4.3.0. When I run the following script directly in a Databricks notebook it works, but when I run it with Databricks-connect I get the error below.
# com.azure.cosmos.spark:azure-cosmos-spark_3-1_2-12:4.3.0
from pyspark.sql.types import StringType, StructField, StructType
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
from pyspark.dbutils import DBUtils

spark = SparkSession.builder.appName("local").getOrCreate()
dbutils = DBUtils(spark)

cosmosEndpoint = ######################
cosmosMasterKey = ######################
cosmosDatabaseName = ######################
cosmosContainerName = "test"

cfg = {
    "spark.cosmos.accountEndpoint": cosmosEndpoint,
    "spark.cosmos.accountKey": cosmosMasterKey,
    "spark.cosmos.database": cosmosDatabaseName,
    "spark.cosmos.container": cosmosContainerName,
}
# Configure Catalog Api to be used
spark.conf.set("spark.sql.catalog.cosmosCatalog", "com.azure.cosmos.spark.CosmosCatalog")
spark.conf.set("spark.sql.catalog.cosmosCatalog.spark.cosmos.accountEndpoint", cosmosEndpoint)
spark.conf.set("spark.sql.catalog.cosmosCatalog.spark.cosmos.accountKey", cosmosMasterKey)

df = (
    spark
    .read
    .format("cosmos.oltp")
    .options(**cfg)
    .load()
)
df.show()

The error I get in VS code using Databricks connect is the following:
Exception has occurred: Py4JJavaError
An error occurred while calling o35.load.
: java.lang.ClassNotFoundException: Failed to find data source: cosmos.oltp. Please find packages at http://spark.apache.org/third-party-projects.html
    at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:765)
    at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSourceV2(DataSource.scala:819)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:367)
    at com.databricks.service.SparkServiceRPCHandler$$anon$1.call(SparkServiceRPCHandler.scala:101)
    at com.databricks.service.SparkServiceRPCHandler$$anon$1.call(SparkServiceRPCHandler.scala:80)
    at com.google.common.cache.LocalCache$LocalManualCache$1.load(LocalCache.java:4724)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3522)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2315)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2278)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2193)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3932)
    at com.google.common.cache.LocalCache$LocalManualCache.get(LocalCache.java:4721)
    at com.databricks.service.SparkServiceRPCHandler$.getOrLoadAnonymousRelation(SparkServiceRPCHandler.scala:80)
    at com.databricks.service.SparkServiceRPCHandler.execute0(SparkServiceRPCHandler.scala:715)
    at com.databricks.service.SparkServiceRPCHandler.$anonfun$executeRPC0$1(SparkServiceRPCHandler.scala:478)
    at scala.util.DynamicVariable.withValue(DynamicVariable.scala:62)
    at com.databricks.service.SparkServiceRPCHandler.executeRPC0(SparkServiceRPCHandler.scala:370)
    at com.databricks.service.SparkServiceRPCHandler$$anon$2.call(SparkServiceRPCHandler.scala:321)
    at com.databricks.service.SparkServiceRPCHandler$$anon$2.call(SparkServiceRPCHandler.scala:307)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at com.databricks.service.SparkServiceRPCHandler.$anonfun$executeRPC$1(SparkServiceRPCHandler.scala:357)
    at scala.util.DynamicVariable.withValue(DynamicVariable.scala:62)
    at com.databricks.service.SparkServiceRPCHandler.executeRPC(SparkServiceRPCHandler.scala:334)
    at com.databricks.service.SparkServiceRPCServlet.doPost(SparkServiceRPCServer.scala:153)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:799)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:550)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:190)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:501)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127)
    at org.eclipse.jetty.server.Server.handle(Server.java:516)
    at org.eclipse.jetty.server.HttpChannel.lambda$handle$1(HttpChannel.java:388)
    at org.eclipse.jetty.server.HttpChannel.dispatch(HttpChannel.java:633)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:380)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:277)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:311)
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:105)
    at org.eclipse.jetty.io.ChannelEndPoint$1.run(ChannelEndPoint.java:104)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:338)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:315)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:173)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.produce(EatWhatYouKill.java:137)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:882)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$Runner.run(QueuedThreadPool.java:1036)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: cosmos.oltp.DefaultSource
    at java.lang.ClassLoader.findClass(ClassLoader.java:524)
    at org.apache.spark.util.ParentClassLoader.findClass(ParentClassLoader.java:35)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:419)
    at org.apache.spark.util.ParentClassLoader.loadClass(ParentClassLoader.java:40)
    at org.apache.spark.util.ChildFirstURLClassLoader.loadClass(ChildFirstURLClassLoader.java:48)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:352)
    at org.apache.spark.sql.execution.datasources.DataSource$.$anonfun$lookupDataSource$5(DataSource.scala:739)
    at scala.util.Try$.apply(Try.scala:213)
    at org.apache.spark.sql.execution.datasources.DataSource$.$anonfun$lookupDataSource$4(DataSource.scala:739)
    at scala.util.Failure.orElse(Try.scala:224)
    at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:739)
    ... 46 more

I have added the jar file of the package to the following directory: .venv\lib\site-packages\pyspark\jars

A: Problem seems to have resolved itself as it seems to be working again.


text:
Q: Can I change host address port in coturn? Like this image, I only get local address by using my coturn server. because dynamic ports is closed in my building (firewall) and, I can't ask staffs to open ports(they never allow this ports to open).

I could change the relay ports by using turnserver.conf file(min port, max port). Also, I changed Dynamic ports range by using "/proc/sys/net/ipv4/ip_local_port_range"(add a sentence which is "net.ipv4.ip_local_port_range = 8000 8500" at "/etc/sysctl.conf")
I thought the UDP's dynamic ports are changed by ip_local_port_range. but they didn't work at all
Can I change the Host address port in coturn?
Here is turnserver.conf
# TURN server name and realm
realm=<domain>
server-name<domain>

# Use fingerprint in TURN message
fingerprint

# IPs the TURN server listens to
listening-ip=0.0.0.0

# External IP-Address of the TURN server
external-ip=<ip>

# Main listening port
listening-port=8888

# Further ports that are open for communication
min-port=7000
max-port=7999

# Log file path
log-file=/var/log/turnserver.log

no-udp
# Enable verbose logging
verbose
tls-listening-port=8600

# Specify the user for the TURN authentification
user=<user>:<credential>
cert=/etc/letsencrypt/live/<domain>/cert.pem
pkey=/etc/letsencrypt/live/<domain>/privkey.pem
# Enable long-term credential mechanism
lt-cred-mech

# If running coturn version older than 4.5.2, uncomment these rules and ensure
# that you have listening-ip set to ipv4 addresses only.
# Prevent Loopback bypass https://github.com/coturn/coturn/security/advisories/GHSA-6g6j-r9rf-cm7p
#denied-peer-ip=0.0.0.0-0.255.255.255
#denied-peer-ip=127.0.0.0-127.255.255.255
#denied-peer-ip=::1


text:
Q: header Location isn't transferring I have form in my site example.com/pp.php and that form´s action is pp.php because that script is not some external file, but inside of that page. The problem is I need to put header("Location: http://example.com/pp.php#contactForm");  because after pressing Send button I want to reload page on exact position which is /pp.php#contactForm. But header Location is not working.
        <form action="pp.php" method="post">
        Name:
        <input type="text" name="name" value="<?php if($_POST['name']) {
        echo $_POST['name']; } ?>" />
        Email:
        <input type="text" name="email" value="<?php if($_POST['email'])
        { echo $_POST['email']; } ?>" />
        Message:

        <textarea name="message" rows="20" cols="20"><?php
        if($_POST['message']) { echo $_POST['message']; } ?></textarea>

        <input type="text" name="code">

        <input type="submit" class="submit" name="submit" value="Send
        message" />
        </form>

This is php
<?php
    if (isset($_POST['submit'])) {
    $error = "";

    if (!empty($_POST['name'])) {
    $name = $_POST['name'];
    } else {
    $error .= "You didn't type in your name.
";
    }

    if (!empty($_POST['email'])) {
    $email = $_POST['email'];
      if (!preg_match("/^[a-z0-9]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*
(\.[a-z]{2,3})$/i", $email)){
      $error .= "The e-mail address you entered is not valid.
";
      }
    } else {
    $error .= "You didn't type in an e-mail address.
";
    }

    if (!empty($_POST['message'])) {
    $message = $_POST['message'];
    } else {
    $error .= "You didn't type in a message.
";
    }

    if(($_POST['code']) == $_SESSION['code']) {
    $code = $_POST['code'];
    } else {
    $error .= "The captcha code you entered does not match. Please try
again.
";
    }

    if (empty($error)) {
    $from = 'From: ' . $name . ' <' . $email . '>';
    $to = "mail@gmail.com";
    $subject = "New contact form message";
    $content = $name . " has sent you a message: \n" . $message;
    $success = "
Thank you! Your message has been sent!
";
    mail($to,$subject,$content,$from);
    }
    }
    ?>
        <?php
        if (!empty($error)) {
        echo '
Your message was NOT sent
 The
following error(s) returned:
' . $error . '
';
        } elseif (!empty($success)) {
        echo $success;
        }
        header("Location: http://example.com/pp.php#contactForm");
    ?>

A: You can't redirect with header() after outputting to the DOM:

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

As such, you'll need to remove the echo statements in your lines:
if (!empty($error)) {
  echo '
Your message was NOT sent
 The
following error(s) returned:
' . $error . '
';
} elseif (!empty($success)) {
  echo $success;
}

Before calling:
header("Location: http://example.com/pp.php#contactForm");

A: Try this:
 header('Location: pp.php#contactForm');

And make sure you do not output any html tag through anyway before this line.
like the  echo $success;


text:
Q: scraping different table with same classes with beautifulsoup,python i'm trying to extract,using beautiful soup and python,all the odds from this website
http://www.sportstats.com/soccer/italy/serie-a-2013-2014/sampdoria-napoli-zZAT2c14/#odds/1X2/s3
they are divided in different tables depending on wich type do they are.
Ex:the first table under the div id="betType_1_2" represents odds of type 1X2 of "full time"
I tried to search for all class="odds" but it return also odds from others tables.
Have anyone idea on how to extract and then scrape only one table per time by its "div id"?Then i would be able to search for class="odds" and obtain the data i need.
Thank you all and sorry for my bad english!!

A: You can use CSS selectors to get to the table rows in the desired div:
from bs4 import BeautifulSoup
import requests

url = "http://www.sportstats.com/soccer/italy/serie-a-2013-2014/sampdoria-napoli-zZAT2c14/?block=3"
soup = BeautifulSoup(requests.get(url).content)

id_ = "betType_1_2"
for item in soup.select('div#{id} table.oddsTable tr'.format(id=id_))[1:-1]:
    print [td.text for td in item('td')]

Prints:
[u'bwin', u'3.20', u'3.75', u'2.05']
[u'FortunaWin', u'3.30', u'3.40', u'2.10']
[u'Unibet', u'3.45', u'3.50', u'2.10']
[u'Betclic', u'3.40', u'3.60', u'2.00']
[u'Expekt', u'3.40', u'3.60', u'2.00']
[u'Betsson', u'3.50', u'3.35', u'2.10']
[u'Betsafe', u'3.55', u'3.40', u'2.11']
[u'10Bet', u'3.40', u'3.45', u'2.10']
...


text:
Q: On quotient spaces of affine algebraic groups by conjugate subgroups Let $H$ be a closed, connected subgroup of an affine algebraic group $G$.
Then is it true that for every $x\in G$, the quotient spaces $G/H$ and $G/xHx^{-1}$ are isomorphic as varieties ?
Where I am considering $G/H$ as a variety in the usual sense as described in Humphreys, Linear Algebraic Groups, Chapter IV

A: By the universal property of quotients of algebraic groups, the composition $G \xrightarrow{\operatorname{Int} x} G \rightarrow G/xHx^{-1}$ induces a morphism of varieties $G/H \rightarrow G/xHx^{-1}$.  Similarly you can obtain a morphism $G/xHx^{-1} \rightarrow G/H$ and check that these are inverse to each other.


text:
Q: How can I split a xml document into strings between a certain tag? Say I have the following XML:
<foo>
<spam taste="great"> stuff</spam> <spam taste="moldy"> stuff</spam>
<bar taste="eww"> stuff </bar> <bar> stuff </bar>
<bacon taste="yum"> stuff </bacon><bacon taste="yum"> stuff </bacon><bacon taste="yum"> stuff </bacon>
</foo>

With spam, bar, and bacon being data tags with more tags inside, I want to split the XML into this

*

*<spam taste="great"> stuff</spam> <spam taste="moldy"> stuff</spam>,

*<bar taste="eww"> stuff </bar> <bar> stuff </bar>,

*<bacon taste="yum"> stuff </bacon><bacon taste="yum"> stuff </bacon><bacon taste="yum"> stuff </bacon>,

in order to reorder it for parsing.
The basic structure like this, with the blocks being in any order.
<foo>
block of bar tags
block of spam tags
block of bacon tags
</foo>

A: If you don't know what the names of the tags are at runtime + just want to break up the elements by group, you can perhaps try using itertools.groupby in combination with whatever xml parsing library you want:
import xml.etree.ElementTree as et
import itertools

raw_xml = '''<foo>
<spam taste="great"> stuff</spam> <spam taste="moldy"> stuff</spam>
<bar taste="eww"> stuff </bar> <bar> stuff </bar>
<bacon taste="yum"> stuff </bacon><bacon taste="yum"> stuff </bacon><bacon taste="yum"> stuff </bacon>
<spam taste="Great">stuff2</spam>
</foo>'''

groups = itertools.groupby(et.fromstring(raw_xml), lambda element: element.tag)
groups = [list(group[1]) for group in groups]

print groups

The output would then be:
[[<Element 'spam' at 0x218ecb0>, <Element 'spam' at 0x218ee10>],
 [<Element 'bar' at 0x218ee90>, <Element 'bar' at 0x218eeb0>],
 [<Element 'bacon' at 0x218ef30>, <Element 'bacon' at 0x218ef50>, <Element 'bacon' at 0x218ef90>],
 [<Element 'spam' at 0x218efd0>]]

If you need the actual string value, you can do:
print [[et.tostring(element) for element in group] for group in groups]

...which will get you:
[['<spam taste="great"> stuff</spam> ', '<spam taste="moldy">stuff</spam>\n'],
 ['<bar taste="eww"> stuff </bar> ', '<bar> stuff </bar> \n'],
 ['<bacon taste="yum"> stuff </bacon>', '<bacon taste="yum"> stuff </bacon>', '<bacon taste="yum">stuff </bacon>\n'],
 ['<spam taste="Great">stuff2</spam>\n']]

A: Have you looked at the ElementTree methods?
import xml.etree.ElementTree as ET

document = ET.parse("file.xml")
spams = document.findall("spam")
bars = document.findall("bar")
bacon = 'document.findall("bacon")


text:
Q: openCV java code pass Point object to native code(C++)? I'm currently developing an openCV app on Android. Untill now my app is all written in Java, however there's one function that takes MatOfPoint object as a parameter that I want to implement in native code(C++). From openCV Tutorial 2 I know how to pass Mat object to native code method, but what about objects of other class, like Point and MatOfPoint? Any sample code that shows how to do it?
Thanks.

A: For a point i recomend just passing x and y as doubles.
For MatOfPoints and others:
OpenCV comes with converters that store different kind of stuff in a Mat.
There is the converter on the java side, that is part of the opencv-android-sdk
org.opencv.utils.Converters
There is also a C++ converter i found in the opencv repo, but the header is not included in the opencv-android-sdk, and i couldn't get it working with just adding the header so i copied the converters.h and converters.cpp to my jni folder and corrected the imports to point to the right place (but this might not be necessary).
https://github.com/Itseez/opencv/blob/master/modules/java/generator/src/cpp/converters.cpp
This converters can be used to pass MatOfPoint or List and a lot more to your native code, where you have to convert it again to a c++ type (c++ equivalent of MatOfPoint is std::vector< cv::Point >; equivalent of List is std::vector< std::vector< cv::Point > >)
With this converters you can "convert" a MatOfPoint to a Mat and back using vector_Point_to_Mat or Mat_to_vector_Point (returns a List but with MatOfPoint.fromList you get a MatOfPoint from that)
Here is an example how to pass List to native level and a MatOfPoint back.
Java code:
public class YourJavaWrapper {

    static {
        System.loadLibrary("yourlibrary");
    }

    public static MatOfPoint findMostFencyMatOfPoints(List<MatOfPoint> contours){

        List<Mat> contoursTmp = new ArrayList<Mat>(contours.size());
        Mat inputMat = Converters.vector_vector_Point_to_Mat(contours, contoursTmp);
        Mat outputMat = new Mat();

        findMostFencyMatOfPoints(inputMat.nativeObj, outputMat.nativeObj);

        List<Point> pointsTmp = new ArrayList<Point>();
        Converters.Mat_to_vector_Point(outputMat, pointsTmp);
        MatOfPoint matOfInterest = new MatOfPoint();
        matOfInterest.fromList(pointsTmp);
        outputMat.release();

        return matOfInterest;
    }

    private static native void findMostFencyMatOfPoints(long inputMatAddress, long outPutMatAddress);

}

C++ code:
using namespace std;
using namespace cv;

extern "C" JNIEXPORT void JNICALL Java_org_example_yourpackage_YourJavaWrapper_findMostFencyMatOfPoints(JNIEnv*, jobject, jlong inputMatAddress, jlong outPutMatAddress)
{
    cv::Mat& vectorVectorPointMat = *(cv::Mat*) inputMatAddress;
    std::vector< std::vector< cv::Point > > contours;
    Mat_to_vector_vector_Point(vectorVectorPointMat, contours);
    std::vector<cv::Point> fencyVectorOfPoints = findMostFencyVectorOfPoint(contours);
    cv::Mat& largestSquareMat = *(cv::Mat*) outPutMatAddress;
    vector_Point_to_Mat(fencyVectorOfPoints, outPutMatAddress);
}

in this example findMostFencyVectorOfPoint is your custom native function


text:
Q: PyGame: Нет отклика Помогите я сделал прогу которая открывает мое видео в ascii  графика и при нажатии на s чтоб этот файл сохранялся я проверил путь файлов правильный но в консоль ничего не выводить и на экран тоже
import pygame as pg
from numba import njit
import cv2

@njit(fastmath=True)
def accelerate_conversion(image, width, height, ascii_coeff, step):
    array_of_values = []
    for x in range(0, width, step):
        for y in range(0, height, step):
            char_index = image[x, y] // ascii_coeff
            if char_index:
                array_of_values.append((char_index, (x, y)))
    return array_of_values

class ArtConverter:
    def __init__(self, path=r'D:\PROGRAMMING\Umar\python\pythonProject\directory from other projects at python/dla.mp4', font_size=12):
        pg.init()
        self.path = path
        self.capture = cv2.VideoCapture(path)
        self.image = self.get_image()
        self.RES = self.WIDTH, self.HEIGHT = self.image.shape[0], self.image.shape[1]
        self.surface = pg.display.set_mode(self.RES)
        self.clock = pg.time.Clock()

        self.ASCII_CHARS = ' .",:;!~+-xmo*#W&8@'
        self.ASCII_COEFF = 255 // (len(self.ASCII_CHARS) - 1)

        self.font = pg.font.SysFont('Сourier', font_size, bold=True)
        self.CHAR_STEP = int(font_size * 0.6)
        self.RENDERED_ASCII_CHARS = [self.font.render(char, False, 'white') for char in self.ASCII_CHARS]

        self.rec_fps = self.capture.get(cv2.CAP_PROP_FPS)
        self.record = False
        self.recorder = cv2.VideoWriter(r'D:\PROGRAMMING\Umar\python\pythonProject\directory from other projects at python/dla.mp4', cv2.VideoWriter_fourcc(*'mp4v'), self.rec_fps, self.RES)

    def get_frame(self):
        frame = pg.surfarray.array3d(self.surface)
        return cv2.transpose(frame)

    def record_frame(self):
        if self.record:
            frame = self.get_frame()
            self.recorder.write(frame)
            cv2.imshow('Frame', frame)
            if cv2.waitKey(1) & 0xFF == 27:
                self.record = not self.record
                cv2.destroyAllWindows()

    def draw_converted_image(self):
        self.image = self.get_image()
        array_of_values = accelerate_conversion(self.image, self.WIDTH, self.HEIGHT, self.ASCII_COEFF, self.CHAR_STEP)
        for char_index, pos in array_of_values:
            self.surface.blit(self.RENDERED_ASCII_CHARS[char_index], pos)

    def get_image(self):
        # self.cv2_image = cv2.imread(self.path)
        ret, self.cv2_image = self.capture.read()
        if not ret:
            exit()
        transposed_image = cv2.transpose(self.cv2_image)
        gray_image = cv2.cvtColor(transposed_image, cv2.COLOR_BGR2GRAY)
        return gray_image

    def draw_cv2_image(self):
        resized_cv2_image = cv2.resize(self.cv2_image, (640, 360), interpolation=cv2.INTER_AREA)
        cv2.imshow('img', resized_cv2_image)

    def draw(self):
        self.surface.fill('black')
        self.draw_converted_image()
        # self.draw_cv2_image()

    def save_image(self):
        pygame_image = pg.surfarray.array3d(self.surface)
        cv2_img = cv2.transpose(pygame_image)
        cv2.imwrite(r'D:\PROGRAMMING\Umar\python\pythonProject\directory from other projects at python/conv.mp4', cv2_img)

    def run(self):
        while True:
            for i in pg.event.get():
                if i.type == pg.QUIT:
                    exit()
                elif i.type == pg.KEYDOWN:
                    if i.key == pg.K_s:
                        self.save_image()
                    if i.key == pg.K_r:
                        self.record = not self.record
            self.record_frame()
            self.draw()
            pg.display.set_caption(str(self.clock.get_fps()))
            pg.display.flip()
            self.clock.tick()

if __name__ == '__main__':
    app = ArtConverter()
    app.run()


text:
Q: How to use google protobuf compiler with maven-compiler-plugin I have a simple java project(No spring) and I have a protobuf file test.proto in src/resources folder and I want to generate sources from it. I read in several places that, to use the plugin I need to install it locally first. But in my previous gradle project I didn't need to do anything like this and just a simple config like below works for gradle :
protobuf {
  protoc {
    artifact = 'com.google.protobuf:protoc:3.8.0'
  }

  generateProtoTasks.generatedFilesBaseDir = generatedProtoPath
}

What is similar thing in Maven, if I want to use google provided protoc compiler and generate code without downloading and installing anything on my production machine.

A: To answer my own question so that someone finds it helpful :
google protobuf 3.7.0 :
Maven changes -- Add this to your pom.xml :
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java</artifactId>
    <version>3.7.0</version>
</dependency>
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java-util</artifactId>
    <version>3.7.0</version>
</dependency>
</dependencies>
<build>
    <extensions>
        <extension>
            <groupId>kr.motd.maven</groupId>
            <artifactId>os-maven-plugin</artifactId>
            <version>1.6.0</version>
        </extension>
    </extensions>
    <plugins>
    <plugin>
        <groupId>org.xolstice.maven.plugins</groupId>
        <artifactId>protobuf-maven-plugin</artifactId>
        <version>0.6.1</version>
        <extensions>true</extensions>
        <executions>
            <execution>
                <goals>
                    <goal>compile</goal>
                    <goal>test-compile</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <additionalProtoPathElements>
                <additionalProtoPathElement>${project.basedir}/src/main/resources</additionalProtoPathElement>
            </additionalProtoPathElements>
            <protocArtifact>com.google.protobuf:protoc:3.7.0:exe:${os.detected.classifier}</protocArtifact>
        </configuration>
    </plugin>

This is the java class :
public class ProtobufTrial {
  public static void main(String[] args) throws Exception {
    String jsonString = "";
    MyProto.MyEventMsg.Builder builder = MyProto.MyEventMsg.newBuilder();
    JsonFormat.parser().ignoringUnknownFields().merge(jsonString, builder);
    MyProto.MyEventMsg value = builder.build();

    // This is for printing the proto in string format
    System.out.println(JsonFormat.printer().print(value));
  }
}


text:
Q: Default Values on a Shared Data Set in SQL Reports 2008 I would like to know if it is possible to set the default values of a shared dataset with the results of another dataset.
I am currently creating datasets to allow a user group to run ad hoc sql reporting on a SharePoint intgrated deployment.
I know how to do this in an actual report but I would like to do it in the shared dataset so that users would not then have to configure the parameters in the report when they are creating ad hoc reports.
I can see how do create default parameters if I type in the values, however the values  may change over time so I want to autmotaically pick up any changes from the database by running a query to get the appropriate values.
Has anyone achieved anything similar before or could suggest an alternative way to achieve this?
PS quite new to SQL reports. Thanks in advance