text:
Q: Como deletar um commit? Fiz alguns commit's errados e não estou conseguindo deletar um em especifico. Todos que foram feitos após eles foram apagados e era o que eu desejava, usei o comando git reset --hard + hash do commit e recebo essa mensagem HEAD is now at 8932874 Criação do readme. Quando tento dar um git push --force recebo a mensagem Everything up-to-date. Como faço para apagar o primeiro commit que fiz?
Esse é meu log e quero apagar commit 8932874. Se alguém puder ajudar eu agradeço.
8932874 (HEAD -> feature/CALONI-65-goiabinha, origin/feature/CALONI-65-goiabinha, master) Criação do readme
a687f69 (origin/master, origin/HEAD) Merged in feature/CALONI-62-GlofosApp (pull request #22)
43282e7 CALONI-62: Correção de erro onde edição de dados deletava o usuário. Motivo: Comando Bind ainda continha atributo IsVisible ao invés de Enabled.

A: Tente reverter o commit
git revert [hash do commit]

Você pode tentar também:
git reset --hard [hash do commit]

A: Você pode tentar o git rebase -i -p HEAD~2
Onde o ~2 é os últimos dois commits.
git log
--para listar os commits.
commit 0a6c84980 (HEAD -> hotfix/1, origin/hotfix/1)
Author: Murilo  <murilo@email.com>
Date:   Thu Aug 12 14:16:03 2021 -0300

  commit original

commit dedde93a7498e
Author: Murilo  <murilo@email.com>
Date:   Fri Aug 6 17:21:20 2021 -0300

    Commit duplicado

Executo o comando de rebase listando os últimos dois commits.
git rebase -i -p HEAD~2
Vai carregar as seguintes informações;
pick dedde93a commit original
pick 0a6c8498 Commit duplicado

# Rebase 72337dee..0a6c8498 onto 72337dee (4 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup <commit> = like "squash", but discard this commit's log message
# x, exec <commit> = run command (the rest of the line) using shell
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
# .       create a merge commit using the original merge commit's
# .       message (or the oneline, if no original merge commit was
# .       specified). Use -c <commit> to reword the commit message.
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.

Marco o commit duplicado como "drop"
pick dedde93a commit original
drop 0a6c8498 Commit duplicado
# Rebase 72337dee..0a6c8498 onto 72337dee (4 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup <commit> = like "squash", but discard this commit's log message
# x, exec <commit> = run command (the rest of the line) using shell
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
# .       create a merge commit using the original merge commit's
# .       message (or the oneline, if no original merge commit was
# .       specified). Use -c <commit> to reword the commit message.
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.

Dou um esc e digito :x para salvar e problema resolvido.
Ele vai executar o rebasing e depois só dá um push -f na branch remota pra forçar as atualizações.


text:
Q: Modern looking interface for diff/meld type program (Mac OSX) I'm using Mac OSX, and I was wondering if there was a good program for comparing two text files for differences? I have meld and the interface looks pretty old. It's just a small cosmetic thing, but is there a better diff comparison program out there for Macs?

A: If you have or download XCode, you can use an app that comes with it called FileMerge.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I increment an IntegerField variable in django? I have a small detail, I have a form and in one of its fields I want to get a number (example 1) and fill out the form. I want to add another product and to increase and exit the consecutive number (that would be 2) and so on successively.
When I run the python manage.py migrate it marks an error in my model.py and I do not know how to fix it.
I want it to come out increased by 1 in the textbox automatically when I upload a new product but I do not know how to do it, can you help me please?
Model.py
class Equipo(models.Model):
    folio  = models.IntegerField()
    marca  = models.CharField(max_length=100)
    modelo  = models.CharField(max_length=100)
    serie  = models.CharField(max_length=100)
    express = models.CharField(max_length=100)
    numem = models.CharField(max_length=100)
    responsable = models.CharField(max_length=100)
    departamento = models.ForeignKey(Departamento)
    puesto = models.CharField(max_length=100)
    descripcion = models.CharField(max_length=100)
    estado = models.ForeignKey(Estado)
    estatus = models.ForeignKey(Estatus)
    hdd = models.CharField(max_length=100)
    procesador = models.CharField(max_length=100)
    ram = models.CharField(max_length=100)
    ubicacion = models.ForeignKey(Ubicacion)
    fechaal = models.CharField(max_length=12, null=True)
    ultman = models.CharField(max_length=12, null=True)
    proxman = models.CharField(max_length=12, null=True)
    status  = models.BooleanField(default=True)

    def __unicode__(self):
        return unicode(self.folio)

    def number():
        folio = Equipo.objects.count() #Here I frame error when I do the migration
        if folio == None:
            return 1
        else:
            return no + 1

    incremcode = models.IntegerField(_('Code'), max_length=5, unique=True, \
    default=number)

view.py
def altaeq_view(request):
    if request.method =='POST':
        form = EquipoForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('#')
    else:
        form = EquipoForm()
        return render_to_response('altaeq.html',{'form':form},context_instance=RequestContext(request))

form.py
class EquipoForm(ModelForm):
    class Meta:
        model = Equipo
        fields = ('folio','marca','modelo','serie','express','numem','responsable','departamento','puesto','descripcion','estado','estatus','hdd','procesador','ram','ubicacion','fechaal','ultman','proxman','status',)
        labels = {
            'folio':('Folio'),
            'marca':('Marca'),
            'modelo':('Modelo'),
            'serie':('Serie'),
            'express':('Express Service Code'),
            'numem':('Numero de Empleado'),
            'responsable':('Responsable'),
            'departamento':('Departamento'),
            'puesto':('Puesto'),
            'descripcion':('Descripcion'),
            'estado':('Estado'),
            'estatus':('Status'),
            'hdd':('Disco Duro'),
            'procesador':('Procesador'),
            'ram':('Memoria Ram'),
            'ubicacion':('Ubicacion'),
            'fechaal':('Fecha de la Alta del Equipo'),
            'ultman':('Ultima Fecha del Mantenimiento'),
            'proxman':('Proxima Facha del Mantenimiento'),
            'status':('Siempre debe de Estar Marcado'),

        }

    def clean_folio(self):
        folio = self.cleaned_data['folio']
        try:
            ee = Equipo.objects.get(folio=folio)
        except Equipo.DoesNotExist:
            return folio
        raise forms.ValidationError('Este Numero de Folio ya Existe')

A: When you run migrations, the model classes aren't directly available. That's because your database and the class might differ (until the migration is ran...).
You can replace your method like this:
def number(self):
    return self.objects.count() + 1

Note:
If if folio == None is not necessary. That cannot happen, count() will return an integer. Also in Python, you can write this: if folio is None.


text:
Q: Figuring out function composition If I know $f(x)$ and $f(g(x))$,
how do I figure out what is $g(x)$?
I can solve already some simple cases, but I'm looking for a general strategy.
Particularly in harder cases when just trying to figure it out is hard.

A: Set $h$ so that $f(g(x))=h(x)$.
To get $g(x)$, $f$ is disturbing. $g$ is composited with $f$ from the left. You need the inverse operation. The inverse operation of composition from the left is the left inverse.
Let $f^{-1}$ denote the left inverse of $f$:
$$g(x)=f^{-1}(h(x))$$
$\ $
Let's presuppose that $f$ and $g$ are functions.
If $f$ is bijective, you can set the inverse function (compositional inverse / inverse) of $f$ for $f^{-1}$.
If $f$ is not bijective, you have to choose suitable partial inverses of $f$ for $f^{-1}$. The equation above can give you $g$ as a piecewise given function then.


text:
Q: Spring data MongoDb throwing error Connection refused Getting following error while connecting to mongodb using Spring Data:
java.io.IOException: couldn't connect to [/127.0.0.1:27017] bc:java.net.ConnectException: Connection refused: connect
at com.mongodb.DBPort._open(DBPort.java:228)
at com.mongodb.DBPort.go(DBPort.java:112)
at com.mongodb.DBPort.call(DBPort.java:79)
at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:218)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:305)
at com.mongodb.DB.getCollectionNames(DB.java:284)
at org.springframework.data.mongodb.core.MongoTemplate$14.doInDB(

Please find my configuration :
@Configuration
public class AppConfig {

public @Bean MongoOperations mongoTemplate(Mongo mongo) {
    MongoTemplate mongoTemplate = new MongoTemplate(mongo, "mydb");
    return mongoTemplate;
}

/*
 * Factory bean that creates the Mongo instance
 */
public @Bean MongoFactoryBean mongo() {
    MongoFactoryBean mongo = new MongoFactoryBean();
    mongo.setHost("10.6.120.180");
    mongo.setPort(27017);
    return mongo;
}

/*
 * Use this post processor to translate any MongoExceptions thrown in @Repository annotated classes
 */
public @Bean PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
    return new PersistenceExceptionTranslationPostProcessor();
}

}
Mongo-context-test.xml
    <mongo:db-factory dbname="mydb"/>
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg ref="mongoDbFactory"/>
</bean>

I am new to Spring Data and MongoDB. Please advice, why am I getting this error?
Thanks in advance.

A: Are you sure that your AppConfig class is being used?
As mentioned in my comment the error you are receiving indicates that your program is attempting to connect to MongoDB on server 127.0.0.1 while the AppConfig class you have posted clearly shows that you want to connect to IP address 10.6.120.180.
This can happen if you are somehow picking up an AppConfig class that contains mongo.setHost("localhost") which is in the example code posted on Github.
Update: Based on OP's comment the class reference for mongoTemplate in Mongo-context-test.xml was pointing to the Spring Framework's default MongoTemplate class.
According to the SpringSource documentation Introduction to MongoTemplate use can use Java to create and register an instance of MongoTemplate OR configure a MongoTemplate using Spring's XML <beans/> schema.
Obviously using the <beans/> schema takes precedence over your implementation in Java.  If you use the  <beans/> schema then you need to use <mongo:mongo host="localhost" port="27017"/> to specify your host and port requirements as noted by the OP in his comment.

A: If you plan to define your own configuration beans, with your custom names, you can exclude Spring's auto-configuration classes by doing:
@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})

OR
@SpringBootApplication(exclude={MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})

Remember: when using EnableAutoConfiguration/SpringBootApplication with exclude list make sure there are no other classes annotated with EnableAutoConfiguration or SpringBootApplication.
Source: How to disable spring-data-mongodb autoconfiguration in spring-boot


text:
Q: Check if value in column in Database I have code to insert element into a Database:
def NewElement(new_user,new_pass):
        querycurs.execute('''INSERT into Database (user,passw) values (?,?)''',(new_user,new_pass))

I want to execute the given statement only when the given value os new_user is not already present in the user column in the table. How can i do so?

A: Ensure that you have a UNIQUE constraint on the user column, either with a table constraint, with a unique index, or with a primary key.
Then replace INSERT with INSERT OR IGNORE.


text:
Q: how to access winform components from another class? i have a form with one button and two labels
and i have a separate class called myCounter
i want the myCounter class to be able to access the labels in the form
through a method called changeColor..
how can make the labels available in this class
the form
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public Color colTurn
        {
            get { return lblp1Turn.BackColor; }
            set { lblp1Turn.BackColor = value; }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }

the class
class myCounter
{
    private readonly Form1 Board;
    public myCounter(Form1 Board)
    {
        this.Board = Board;
    }

    public int turn = 0;

    public void changeColor()
    {

        if (turn == 0)
        {
            turn = 1;
            lbl

           //change color code here
        }
    }
}

A: So it looks like you're passing the whole form into your second class anyway, So I'd do what LightStriker suggested. Make a public accessor for all of your items and then set it in your other class.
public partial class Form1 : Form
    {
        private myCounter _counterClass;
        public Form1()
        {
            InitializeComponent();
        }

        public Label MyLabel1
        {
            get {return mylabel1;}
        }

        public Label MyLabel2
        {
            get {return mylabel2;}
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _counterClass = new myCounter(this);
        }

        protected void ButtonClick(object sender, EventArgs e)
        {
            _counterClass.changeColor();
        }
    }

Then in your second class you have access to your Label.
class myCounter
{
    private readonly Form1 Board;
    public myCounter(Form1 Board)
    {
        this.Board = Board;
    }

    public int turn = 0;

    public void changeColor()
    {

        if (turn == 0)
        {
            turn = 1;
            Board.MyLabel1.BackColor = Color.Red;
            Board.MyLabel2.BackColor = Color.White;
        }
        else
        {
            turn = 0;
            Board.MyLabel2.BackColor = Color.Yellow;
            Board.MyLabel1.BackColor = Color.White;
        }
    }
}

Keep in mind this is code I have written in a wiki markup editor and is untested. This SHOULD work for you though.

A: Create a public method on your form for this.
public partial class Form1 : Form{
    public void SetLabelColor(Color color){
        mylabel.BackColor = color;
    }
    //... Other code
}


text:
Q: How to run function 10 times while it is not true and exit from script I have a function named ping_test for testing if a machine is responding to ping:
function ping_test() {
    ping xxx.xxx.xxx.xxx
    if [[ "$?" == "0" ]]; then
        echo "Machine is online"
        return 0
    else
        echo "Machine is offline"
        return 1
    fi

}

other_function1
other_function2
while ! ping_test; do
ping_test
done
other_function3
other_function4
exit 0

How can I exit the script (not execute functions other_function3 and other_function4) after 10 times of ping failure?

A: Try it 10 times, and break if it succeeds early.
other_function1
other_function2

for ((i=0; i<10; i++)); do
    test && break
done || {
    echo "Pings failed"
    exit 1
}

other_function3
other_function4

The exit status of the for loop itself will tell you if the loop ended naturally (non-zero) or due to a break following a successful test (zero).

A: My ping (macOS) has built-in functionality to support your use case:
ping -c 10 -o xxx.xxx.xxx.xxx

where -c count is for

Stop after sending (and receiving) count ECHO_RESPONSE packets

and -o is

Exit successfully after receiving one reply packet.

This means, your code could look like this:
pingtest() {
    if ping -c 10 -o xxx.xxx.xxx.xxx; then
        echo "Machine is online"
    else
        echo "Machine is offline"
        exit 1
    fi
}

other_function1
other_function2
pingtest
other_function3
other_function4

and the whole retry mechanism is handled by ping itself.
Notice that test isn't the best name for your function: it's usually already a shell built-in and the name of a binary in your $PATH.


text:
Q: How to know control is handled or no inside user-control key-up event I have some UIElements in my UserControl. Some of them might be a multiline textbox some of them might not be. For example:
 <Usercontrol PreviewKeyDown="Wizard_PreviewKeyDown">
    <StackPanel>
      <TextBox/>
      <TextBox AcceptsReturn="True"/>
    </StackPanel>
 <Usercontrol>

Code behind of this control:
 private void Wizard_PreviewKeyDown(object sender, KeyEventArgs e)
 {
     Key key = (e.Key == Key.System ? e.SystemKey : e.Key);
     if (key == Key.Enter)
     {
         UIElement uiElement = (e.OriginalSource as UIElement);
         GoToNext(); //if uiElement is already handled I should not call this method
     }
 }

I should not call my GoToNext() method if uiElement is alredy handled. In this case if I select my first textbox and click Enter it should go to next because this textbox is not a multiline. If I select my second textbox it should not go next because it is a multiline. How can I know is UIElement Handled or not? Can someone help me with this problem?
Thanks!

A: I used KeyDown="Wizard_KeyDown" instead of PreviewKeyDown="Wizard_PreviewKeyDown" and it's working as I wanted.


text:
Q: Destroying div after few seconds mixed with PHP I want to destroy div after few seconds after creating it. At the moment i'm using this
function info ( $s ) {
    return ( $s ? '
'.$s.'
' : false );
}

The problem is that doesn't work at all. I'm not good in JS at all, so I can't fix it by my own.
Thanks for advices and help.

A: It's almost fine.
Your problem is, that your ' : false );
}

So what I did is putting $(function(){ /* ... */ }); around your code.


text:
Q: Where to put main code in Mplab Harmony Framework? When i'm doing code using MCC for example i will put my code the following way:
#include "stdio.h"
#include <xc.h>
#include "mcc_generated_files/mcc.h"

void main(void)
{
    SYSTEM_Initialize();
    printf("Booting loop debugger\r\n");
    LED_GREEN_Toggle();
    loop_debug_initialize();// start debug variables
    loop_initialize();
    while (1)
    {
        loop_debug_manage();
    }
}

My question now is using the Harmony framework i have something like this:
int main ( void )
{
    __XC_UART = 1;  // Code is configured to use UART1
    /* Initialize all MPLAB Harmony modules, including application(s). */
    SYS_Initialize ( NULL );

    while ( true )
    {
        /* Maintain state machines of all polled MPLAB Harmony modules. */
        SYS_Tasks ( );
    }

    /* Execution should not come here during normal operation */

    return ( EXIT_FAILURE );
}

Where shall i put the same code? can i put everything on main? like this:
int main ( void )
{
    __XC_UART = 1;  // Code is configured to use UART1
    /* Initialize all MPLAB Harmony modules, including application(s). */
    SYS_Initialize ( NULL );
    loop_debug_initialize();// start debug variables
    loop_initialize();

    while ( true )
    {
        /* Maintain state machines of all polled MPLAB Harmony modules. */
        SYS_Tasks ( );
        loop_debug_manage();
    }

    /* Execution should not come here during normal operation */

    return ( EXIT_FAILURE );
}

Or this is not ok?
Does it need to go inside void SYS_Tasks ( void )?
It's my first time working with Harmony, so any help is appreciated.

A: I understand that Harmony is supposed to make things simpler. It does this well for configuration -- but it does makes a lot more things confusing especially for newcomers. Your main code can go absolutely anywhere you want and you can just dump the APP_Tasks() function.
HOWEVER --- if you really want to follow the correct Harmony procedure and not kill any Harmony peripherals or "system services", your main code MUST be non blocking finite state machine and must be in APP_Tasks.
You should create the states you require for your application state in APP_STATES enum.
Harmony gives you two states right off the bat that you can use if you want.
The first state is APP_STATE_INIT, you can put things in this switch case for starting your application code.
The last state and only second state it gives you is APP_STATE_SERVICE_TASKS which you put your main running code.
However you should really make your own new states, as your main program probably won't be that simple. For example, this code will go into three states, INIT, AWAIT_ON, AWAIT_OFF. Basically just flipping states based on button presses.
app.h
typedef enum
{
    /* Application's state machine's initial state. */
    APP_STATE_INIT=0,
    APP_STATE_AWAIT_PRESS_ON, // Wait for the on button
    APP_STATE_AWAIT_PRESS_OFF, // Switch off! (back to await press on)

    /* TODO: Define states used by the application state machine. */

} APP_STATES;

App_Tasks()
/* Check the application's current state. */
switch ( appData.state )
{
    /* Application's initial state. */
    case APP_STATE_INIT:
    {
        bool appInitialized = true;

        if (appInitialized)
        {
            // initial LATG state
            LATGbits.LATG0 = 0;

            appData.state = APP_STATE_AWAIT_PRESS_ON;
        }
        break;
    }

    case APP_STATE_AWAIT_PRESS_ON:
    {
        if ( PORTEbits.PORTE0 )
        {
            LATGbits.LATG0 = 1;
            appData.state = APP_STATE_AWAIT_PRESS_OFF;
        }
        break;
    }
    case APP_STATE_AWAIT_PRESS_OFF:
    {
        if ( !PORTEbits.PORTE0 )
        {
            LATGbits.LATG0 = 0;
            appData.state = APP_STATE_AWAIT_PRESS_ON;
        }
        break;
    }

    /* The default state should never be executed. */
    default:
    {
        /* TODO: Handle error in application's state machine. */
        break;
    }
}

There is "heartbeat indicator" example code in MPLAB Harmony Tutorial (Step 7: Develop the Application). I would suggest reading these tutorials before jumping straight in.


text:
Q: Defining Kraus operators with normal distribution I am interested in defining Kraus operators which allow you to define quantum measurements peaked at some basis state. To this end I am considering the Normal Distribution. Consider a finite set of basis states $\{ |x \rangle\}_x$ and a set of quantum measurement operators of the form
$$A_C = \sum_x \sqrt{\mathrm{Pr}(x|C)} |x \rangle \langle x|.$$
I want to prove that $A_C$ defines valid Kraus operators. If I consider the Normal distribution
$$\mathrm{Pr}(x|C) = \frac{1}{\sqrt{2 \pi \sigma^2}}e^{-\frac{(x-C)^2}{2 \sigma^2}}~~~~\text{where } x \in \{-M,-M+1,...,M \}$$
 where $C$ is the mean, $x$ the random variable and $\sigma^2$ the variance, then
$$\int_{-\infty}^\infty \mathrm{Pr}(X=x|C)\,dC  = \frac{1}{\sqrt{2 \pi \sigma^2}}\int_{-\infty}^{\infty}e^{-\frac{(x-C)^2}{2 \sigma^2}}dC = 1.$$
Thus it follows that
$$\int_{C}A_C^{\dagger}A_CdC = \int_{-\infty}^{\infty} \sum_{x}\mathrm{Pr}(x|C) |x \rangle \langle x | dC = \sum_x \bigg[\int_{-\infty}^{\infty}\mathrm{Pr}(x|C)dC\bigg]|x \rangle \langle x | = \sum_x |x \rangle \langle x | = 1 $$
hence we have shown $$\int_{C}A_{C}^{\dagger}A_C dC = 1$$ hence $A_C$ satisfies the conditions necessary for $\{A_C \}_C$ to be Kraus operators.
Question:
Please advise if my working and conclusion that $\{A_c \}_C$ are valid Kraus operators is correct? Also, there are only a finite number of states $\{ |x \rangle \}_{x}$ yet the index $C$ is continuous and unbounded, so for some $C$ (the mean), the peak of $Pr(x|C)$ will be well outside the range of any $|x \rangle$. I don't think that this is a problem, but I'm not sure about this...
Thanks.

A:
Please advise if my working and conclusion that $\{A_c \}_C$ are valid Kraus operators is correct?

Your workings and your conclusion that $\{A_c \}_C$ are valid Kraus operators are correct.

Also, there are only a finite number of states $\{ |x \rangle \}_{x}$ yet the index $C$ is continuous and unbounded, so for some $C$ (the mean), the peak of $Pr(x|C)$ will be well outside the range of any $|x \rangle$. I don't think that this is a problem, but I'm not sure about this...

This is not a problem.
If all the $x$ in your finite set are bounded by some constant $|x|<M$, and you take some $C>M$, then you know that the norm of the corresponding Kraus operator is
\begin{align}
||A_C||^2
& = \mathrm{Tr}(A_C^\dagger A_C)
 = \mathrm{Tr}\mathopen{}\left(\sum_x \mathrm{Pr}(x|C)|x \rangle \langle x|\right)
 = \sum_x \mathrm{Pr}(x|C)
\\ & \leq \sum_x \mathrm{Pr}(M|C)
 = N \, \mathrm{Pr}(M|C)
\end{align}
if you have $N$ measurements, and this is exponentially small in $(C-M)^2/\sigma^2$. In other words, those Kraus operators are exponentially close to zero and they do not meaningfully contribute to anything.

I would like some reassurance about some minor technical aspect of my workings, and some validation of my status as a competent student of physics.

For the sorts of questions you've been asking, we can indeed provide that, but I would suggest that this is not necessarily the best use of your rep or of everyone's time. This kind of interaction is much more fruitful in person, and I would strongly encourage you to find a faculty member (or other such professional) to whom you can ask this kind of thing in person. It is quicker but, more importantly, the personal and interpersonal aspects of that kind of relationship are even more important to developing a healthy relationship with physics.
(Or, more specifically: this is obviously my interpretation, and I apologise if I'm overstepping here. However, please do take a good look at why exactly you're asking this style of question, where you've already solved the problem in full, and whether there are other ways to handle them that give you more in the end.)


text:
Q: tinymce paste HTML tag  when I try to paste in the code editor
He cut my tag. it does not allow it ..
I do not understand, I tried everything.
somebody can help me..

<poll poll-id="'POLL ID'"></poll>

give me >

extended_valid_elements: 'poll[poll-id|defer|language|src|type]',
custom_elements: "*[*]",
valid_elements: "*[*]",

or
extended_valid_elements: "*[*]",
custom_elements: "*[*]",
valid_elements: "*[*]",

lots of other thing;...
nothing works: (

A: Tinymce somehow has a problem with the tag being empty.
Try to put a character inside it and it won't get stripped out.


text:
Q: hibernate JPA c3p0 problem I build j2ee application using spring, hibernage-JPA and c3p0 for connection pool. I have defined dataSource bean:
<bean id="basicDataSource"
      class="com.mchange.v2.c3p0.ComboPooledDataSource"
      destroy-method="close"
      p:driverClass="${jdbc.driverClassName}"
      p:jdbcUrl="${jdbc.url}"
      p:user="${jdbc.username}"
      p:password="${jdbc.password}"
      p:initialPoolSize="5"
      p:minPoolSize="5"
      p:maxPoolSize="10"
      p:idleConnectionTestPeriod="10"
      p:checkoutTimeout="30"
      p:maxStatements="500"
      p:acquireIncrement="0"/>

which I'm using it in entityManager if spring app. context:
<bean id="entityManagerFactory"
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
      p:dataSource-ref="basicDataSource"/>

But this combination does't work. Here is the info log:
2011-08-09 16:56:17,398 [main] INFO  org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5ae80842: startup date [Tue Aug 09 16:56:17 CEST 2011]; root of context hierarchy
2011-08-09 16:56:17,661 [main] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from file [/Users/pierre/Documents/workspace/ideaProjects/tServer/app/target/classes/META-INF/spring/applicationContext-persistence.xml]
2011-08-09 16:56:18,252 [main] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from file [/Users/pierre/Documents/workspace/ideaProjects/tServer/app/target/classes/META-INF/spring/applicationContext.xml]
2011-08-09 16:56:18,357 [main] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from file [/Users/pierre/Documents/workspace/ideaProjects/tServer/app/target/classes/META-INF/spring/basicDataSource.xml]
2011-08-09 16:56:18,698 [main] INFO  org.springframework.beans.factory.config.PropertyPlaceholderConfigurer - Loading properties file from file [/Users/pierre/Documents/workspace/ideaProjects/tServer/app/target/classes/META-INF/spring/database.properties]
2011-08-09 16:56:18,793 [main] INFO  com.mchange.v2.log.MLog - MLog clients using log4j logging.
2011-08-09 16:56:18,986 [main] INFO  com.mchange.v2.c3p0.C3P0Registry - Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]
2011-08-09 16:56:19,074 [main] INFO  org.springframework.context.support.ClassPathXmlApplicationContext - Bean 'basicDataSource' of type [class com.mchange.v2.c3p0.ComboPooledDataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2011-08-09 16:56:19,104 [main] INFO  org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'basicPersistenceUnit'
2011-08-09 16:56:19,295 [main] INFO  org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
2011-08-09 16:56:19,302 [main] INFO  org.hibernate.cfg.Environment - Hibernate 3.6.3.Final
2011-08-09 16:56:19,304 [main] INFO  org.hibernate.cfg.Environment - hibernate.properties not found
2011-08-09 16:56:19,307 [main] INFO  org.hibernate.cfg.Environment - Bytecode provider name : javassist
2011-08-09 16:56:19,310 [main] INFO  org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
2011-08-09 16:56:19,437 [main] INFO  org.hibernate.ejb.Version - Hibernate EntityManager 3.6.3.Final
2011-08-09 16:56:19,466 [main] INFO  org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [
    name: basicPersistenceUnit
    ...]
2011-08-09 16:56:19,720 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: sk.wimc.t.domain.GpsPointEntity
2011-08-09 16:56:19,765 [main] INFO  org.hibernate.cfg.annotations.EntityBinder - Bind entity sk.wimc.t.domain.GpsPointEntity on table gps_point
2011-08-09 16:56:19,824 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: sk.wimc.t.domain.LastTripEntity
2011-08-09 16:56:19,825 [main] INFO  org.hibernate.cfg.annotations.EntityBinder - Bind entity sk.wimc.t.domain.LastTripEntity on table last_trip
2011-08-09 16:56:19,826 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: sk.wimc.t.domain.ObjectEntity
2011-08-09 16:56:19,827 [main] INFO  org.hibernate.cfg.annotations.EntityBinder - Bind entity sk.wimc.t.domain.ObjectEntity on table object
2011-08-09 16:56:19,838 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: sk.wimc.t.domain.TachoEntity
2011-08-09 16:56:19,839 [main] INFO  org.hibernate.cfg.annotations.EntityBinder - Bind entity sk.wimc.t.domain.TachoEntity on table tacho
2011-08-09 16:56:19,843 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: sk.wimc.t.domain.TachoOffsetEntity
2011-08-09 16:56:19,844 [main] INFO  org.hibernate.cfg.annotations.EntityBinder - Bind entity sk.wimc.t.domain.TachoOffsetEntity on table tacho_offset
2011-08-09 16:56:19,845 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: sk.wimc.t.domain.TripEntity
2011-08-09 16:56:19,846 [main] INFO  org.hibernate.cfg.annotations.EntityBinder - Bind entity sk.wimc.t.domain.TripEntity on table trip
2011-08-09 16:56:19,861 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: sk.wimc.t.domain.UnitEntity
2011-08-09 16:56:19,862 [main] INFO  org.hibernate.cfg.annotations.EntityBinder - Bind entity sk.wimc.t.domain.UnitEntity on table unit
2011-08-09 16:56:19,879 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: sk.wimc.t.domain.UnitEventEntity
2011-08-09 16:56:19,879 [main] INFO  org.hibernate.cfg.annotations.EntityBinder - Bind entity sk.wimc.t.domain.UnitEventEntity on table unit_event
2011-08-09 16:56:19,889 [main] INFO  org.hibernate.cfg.Configuration - Hibernate Validator not found: ignoring
2011-08-09 16:56:19,908 [main] INFO  org.hibernate.validator.util.Version - Hibernate Validator 4.2.0.Final
2011-08-09 16:56:20,434 [main] INFO  org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
2011-08-09 16:56:20,480 [main] INFO  org.hibernate.connection.ConnectionProviderFactory - Initializing connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
2011-08-09 16:56:20,483 [main] INFO  org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider - Using provided datasource
2011-08-09 16:56:20,545 [main] INFO  com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource - Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 0, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 30, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge0zo8h1ckgtlr18nmn36|7e94af2f, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge0zo8h1ckgtlr18nmn36|7e94af2f, idleConnectionTestPeriod -> 10, initialPoolSize -> 5, jdbcUrl -> jdbc:mysql://192.168.0.123:3306/sos, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 10, maxStatements -> 500, maxStatementsPerConnection -> 0, minPoolSize -> 5, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
2011-08-09 16:56:20,626 [main] WARN  org.hibernate.cfg.SettingsFactory - Could not obtain connection to query metadata
java.sql.SQLException: An attempt by a client to checkout a Connection has timed out.
    at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:106)
    at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:65)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:527)
    at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:134)
    at org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:68)
    at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:113)
    at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2836)
    at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2832)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:906)
    at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:74)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:225)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:308)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:398)
    at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:275)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.detectPersistenceExceptionTranslators(PersistenceExceptionTranslationInterceptor.java:139)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.<init>(PersistenceExceptionTranslationInterceptor.java:79)
    at org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisor.<init>(PersistenceExceptionTranslationAdvisor.java:70)
    at org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:99)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1439)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1408)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:710)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:410)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at sk.wimc.t.app.Service.main(Service.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: com.mchange.v2.resourcepool.TimeoutException: A client timed out while waiting to acquire a resource from com.mchange.v2.resourcepool.BasicResourcePool@46b29c9d -- timeout at awaitAvailable()
    at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1317)
    at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:557)
    at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:477)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:525)
    ... 42 more
2011-08-09 16:56:20,740 [main] INFO  org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2011-08-09 16:56:20,756 [main] INFO  org.hibernate.engine.jdbc.JdbcSupportLoader - Disabling contextual LOB creation as connection was null
2011-08-09 16:56:20,757 [main] INFO  org.hibernate.transaction.TransactionFactoryFactory - Transaction strategy: org.hibernate.transaction.JDBCTransactionFactory
2011-08-09 16:56:20,758 [main] INFO  org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
2011-08-09 16:56:20,758 [main] INFO  org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
2011-08-09 16:56:20,758 [main] INFO  org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
2011-08-09 16:56:20,759 [main] INFO  org.hibernate.cfg.SettingsFactory - Scrollable result sets: disabled
2011-08-09 16:56:20,759 [main] INFO  org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): disabled
2011-08-09 16:56:20,759 [main] INFO  org.hibernate.cfg.SettingsFactory - Connection release mode: auto
2011-08-09 16:56:20,759 [main] INFO  org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2
2011-08-09 16:56:20,759 [main] INFO  org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
2011-08-09 16:56:20,759 [main] INFO  org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
2011-08-09 16:56:20,759 [main] INFO  org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
2011-08-09 16:56:20,759 [main] INFO  org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
2011-08-09 16:56:20,759 [main] INFO  org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
2011-08-09 16:56:20,761 [main] INFO  org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
2011-08-09 16:56:20,761 [main] INFO  org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
2011-08-09 16:56:20,761 [main] INFO  org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: enabled
2011-08-09 16:56:20,761 [main] INFO  org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
2011-08-09 16:56:20,761 [main] INFO  org.hibernate.cfg.SettingsFactory - Query cache: disabled
2011-08-09 16:56:20,761 [main] INFO  org.hibernate.cfg.SettingsFactory - Cache region factory : net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory
2011-08-09 16:56:20,843 [main] INFO  org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: enabled
2011-08-09 16:56:20,843 [main] INFO  org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
2011-08-09 16:56:20,855 [main] INFO  org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout
2011-08-09 16:56:20,863 [main] INFO  org.hibernate.cfg.SettingsFactory - Statistics: disabled
2011-08-09 16:56:20,864 [main] INFO  org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
2011-08-09 16:56:20,865 [main] INFO  org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
2011-08-09 16:56:20,865 [main] INFO  org.hibernate.cfg.SettingsFactory - Named query checking : enabled
2011-08-09 16:56:20,865 [main] INFO  org.hibernate.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): disabled
2011-08-09 16:56:20,903 [main] INFO  org.hibernate.impl.SessionFactoryImpl - building session factory
2011-08-09 16:56:20,916 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [wrapper_characters_clob] overrides previous : org.hibernate.type.CharacterArrayClobType@642726b2
2011-08-09 16:56:20,916 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [materialized_blob] overrides previous : org.hibernate.type.MaterializedBlobType@465da37c
2011-08-09 16:56:20,916 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [characters_clob] overrides previous : org.hibernate.type.PrimitiveCharacterArrayClobType@2d9845fb
2011-08-09 16:56:20,916 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [clob] overrides previous : org.hibernate.type.ClobType@681a791f
2011-08-09 16:56:20,916 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [java.sql.Clob] overrides previous : org.hibernate.type.ClobType@681a791f
2011-08-09 16:56:20,916 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [blob] overrides previous : org.hibernate.type.BlobType@2206179e
2011-08-09 16:56:20,916 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [java.sql.Blob] overrides previous : org.hibernate.type.BlobType@2206179e
2011-08-09 16:56:20,916 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [materialized_clob] overrides previous : org.hibernate.type.MaterializedClobType@3df89785
2011-08-09 16:56:20,916 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [wrapper_materialized_blob] overrides previous : org.hibernate.type.WrappedMaterializedBlobType@ba3bc8c
2011-08-09 16:56:20,950 [main] WARN  net.sf.ehcache.config.ConfigurationFactory - No configuration found. Configuring ehcache from ehcache-failsafe.xml  found in the classpath: jar:file:/Users/pierre/.m2/repository/net/sf/ehcache/ehcache-core/2.4.2/ehcache-core-2.4.2.jar!/ehcache-failsafe.xml
2011-08-09 16:56:21,681 [main] INFO  org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
2011-08-09 16:56:21,684 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaValidator - Running schema validator
2011-08-09 16:56:21,684 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaValidator - fetching database metadata
2011-08-09 16:56:21,765 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - table found: sos.gps_point
2011-08-09 16:56:21,765 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - columns: [gps_latitude, gps_auth_code, gps_speed, gps_origin, gps_curse, gps_longitude, gps_keyname, gps_panic, country_code, unit_serialno, gps_satellites, gps_timestamp, flag, save_timestamp, gps_bininputs, gps_ip, gps_valid, gps_point_id, gps_altitude]
2011-08-09 16:56:21,769 [main] INFO  org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@36f0b7f8: defining beans
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in file [/Users/pierre/Documents/workspace/ideaProjects/tServer/app/target/classes/META-INF/spring/applicationContext-persistence.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in file [/Users/pierre/Documents/workspace/ideaProjects/tServer/app/target/classes/META-INF/spring/applicationContext-persistence.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: basicPersistenceUnit] Unable to build EntityManagerFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:710)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:410)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at sk.wimc.t.app.Service.main(Service.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in file [/Users/pierre/Documents/workspace/ideaProjects/tServer/app/target/classes/META-INF/spring/applicationContext-persistence.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: basicPersistenceUnit] Unable to build EntityManagerFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:398)
    at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:275)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.detectPersistenceExceptionTranslators(PersistenceExceptionTranslationInterceptor.java:139)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.<init>(PersistenceExceptionTranslationInterceptor.java:79)
    at org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisor.<init>(PersistenceExceptionTranslationAdvisor.java:70)
    at org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:99)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1439)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1408)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    ... 15 more
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: basicPersistenceUnit] Unable to build EntityManagerFactory
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)
    at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:74)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:225)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:308)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
    ... 30 more
Caused by: org.hibernate.HibernateException: Wrong column type in sos.gps_point for column country_code. Found: char, expected: varchar(2)
    at org.hibernate.mapping.Table.validateColumns(Table.java:283)
    at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1316)
    at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:139)
    at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:378)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:906)
    ... 35 more

Process finished with exit code 1

When I configure the dataSource to using dbcp and deploy it to glassfish, then it's work. But dbcp does't work for stand alone j2ee app. So I try to using c3p0, but unsuccessful. Can someone see some error(s) in my config?

A: Ok, I solved this problem it was in type definition in enetity, I add this param: columnDefinition = "char" to column annotation.


text:
Q: How to enable syntax highlight for script tages in .cshtml files? Just started using Visual Studio 2022 and for some reason the syntax highlighting is not working correctly on .cshtml files:
For example
Is there a setting I'm missing or will it only work if I explicitly write some type of Javascript in the HTML tags?


text:
Q: Using sed to replace string matching regex with wildcards I have a string I'm trying manipulate with sed
js/plex.js?hash=f1c2b98&version=2.4.23"

Desired output is
js/plex.js"

This is what I'm currently trying
sed -i s'/js\/plex.js[\?.\+\"]/js\/plex.js"/'

But it is only matching the first ? and returns this output
js/plex.js"hash=f1c2b98&version=2.4.23"

I can't see why this isn't working after a few hours

A: This works
echo 'js/plex.js?hash=f1c2b98&version=2.4.23"' | sed  s:.js?.*:.js:g

With the original Regex:
Firstly I would suggest use a different delimiter (like : in sed when using / in the regex. Secondly, the use of [] means that you are matching the characters inside the brackets (and as such it will not expand the .+ to the end of the line - you could potentially try put the + after the [])

A: perhaps
sed 's#\(js/plex.js?\)[^"]\+".*#\1#g'

..
\# is used as a delimiter

\(js/plex.js?\)[^"]\+".*  #find this pattern and replace everything with your marked pattern \1 found
The marked pattern
In sed you can mark part of a pattern or the whole pattern buy using \( \). .
When part of a pattern is enclosed by brackets () escaped by backslashes..the pattern is marked/stored...
in my example this is my pattern without marking
js/plex.js?[^"]\+".*

but I only want sed to remember js/plex.js? and replace the whole line with only this piece of pattern js/plex.js? ..with sed the first marked pattern is known as \1, the second \2 and so forth
\(js/plex.js?\) ---> is marked as \1

Hence I replace the whole line with \1


text:
Q: Is bundling my JS/TS project anti-pattern? I'm working on a project in Angular 2 using TypeScript and trying to nail-down my workflow.
Yesterday, I saw this video from Guy Bedford about package management. In it, he makes mention of the fact that he considers bundling to be anti-pattern.
I've seen similar mention of moving away from bundling on an angular-university guide.
From what I have read since watching the video, it seems to me that the reason for bundling being anti-pattern is that HTTP2 allows multiple responses per request, sent in parallel. This seems pretty useful since a single request to your server could return the whole angular app in individual files.
Is HTTP2 support now prevalent enough to transition to un-bundled apps? What are the pros and cons?
EDIT #2: tried to make the question more focused

A: Anti-pattern is a strong term. Its also a somewhat fuzzy one: we all have this intuitive sense of what it means, but it is certainly easy to get lost in the weeds of arguing whether questionable practice x is or is not, in fact, an anti-pattern.
So rather than trying to read too much into an off-hand comment during a talk from a library author, I'd like to present the case against bundling. These points should be fairly uncontroversial (if anyone disagrees let me know in the comments and I'll edit).
Important caveat before we start: I bundle. I'm a fan of bundling in general, it makes perfect sense for the work I do, and it generally has been a step forward. It has many positive aspects, my favorite being better closure compiler/rollup compression. But for the rest of this answer I'm only dwelling on potential flaws.

*

*Bundling can lead to trivial cache misses. Any change to any part of your app invalidates the browser cache.

*Bundling can make it harder to leverage a cache of common libraries. If you're using the same version of jquery from the same cdn as everyone else there's a good chance your users will never have to even hit your servers for it.

*Bundling means that you generally are loading all of your JavaScript at once. There are exceptions like webpack code splitting but this complicates your build pipeline versus cating files.

*Bundling means missing out on HTTP/2's ability to handle multiple asset requests in parallel. This may or may not be relevant to your use-case. If you're building an internal asset at FooCorp where everyone is still locked to IE 8 by IT because reasons this argument is uncompelling. Ditto most of your customer base being Chinese for the same reason. For most of the world, HTTP/2 is now widely supported (chrome, firefox, edge, iOS safari). Meaning that you are giving the majority of your users a possibly sub-par experience.


text:
Q: MYSQL/PHP Echo Average of foreign key parameters I'm trying to figure out how to have 2 SQL statements back to back, which creates a table with the info from the first SQL statement, and the last cell be the average of one of the columns from said table.
I can display the info needed to make the table. No problem. It's this:
$sql = "SELECT golfer_name, golfer_handicap, golfer_ghin FROM golfers WHERE trip_name_table_ID = '$userid'";
$result = $mysqli->query($sql);

if ($result->num_rows > 0) {
    while($rowitem = mysqli_fetch_array($result)) {
        echo "
";
        echo "" . $rowitem['golfer_name'] . "	";
        echo "" . $rowitem['golfer_handicap'] . "	";
        echo "" . $rowitem['golfer_ghin'] . "	";
        echo "
";

I can get the first colum to total the number of golfers, no problem:
echo "
";
  echo "Total Golfers: $result->num_rows 	";

Now the trouble is trying to get the average of the handicaps in the last cell of that column. I created a 2nd SQL directly below the 1st one, but changed the variables so that they wouldn't mess with the original table data -- and inside my PHPmyAdmin SQL section, this statement returns exactly what I'm looking for:
$sql2 = "SELECT CAST(AVG(golfer_handicap) AS DECIMAL (3,1)) FROM golfers WHERE trip_name_table_ID = '$userid'";

But for the absolute life of me, I cannot figure out how to echo that single piece of data.

A: You would just do it like you did the first query; keeping your variables different as to not interfere with your loop.
<?php
$sql = "SELECT golfer_name, golfer_handicap, golfer_ghin FROM golfers WHERE trip_name_table_ID = '$userid'";
$result = $mysqli->query($sql);

$sql2 = "SELECT CAST(AVG(golfer_handicap) AS DECIMAL (3,1)) AS handicap FROM golfers WHERE trip_name_table_ID = '$userid'";
$result2 = $mysqli->query($sql2);
$total = mysqli_fetch_array($result2);

if ($result->num_rows > 0) {
    while($rowitem = mysqli_fetch_array($result)) {
        echo "
";
        echo "" . $rowitem['golfer_name'] . "	";
        echo "" . $rowitem['golfer_handicap'] . "	";
        echo "" . $rowitem['golfer_ghin'] . "	";
        echo "
";

Then just call/echo $total["handicap"] wherever you want to display the average.
**I have not tested the code.

A: Solution: Thanks to @Dawson_Irvine, please see how they solved my problem here rather than read through the comments. Enjoy!
<?php
$sql = "SELECT golfer_name, golfer_handicap, golfer_ghin FROM golfers WHERE trip_name_table_ID = '$userid'";
$result = $mysqli->query($sql);

$sql2 = "SELECT CAST(AVG(golfer_handicap) AS DECIMAL (3,1)) AS handicap FROM golfers WHERE trip_name_table_ID = '$userid'";
$result2 = $mysqli->query($sql2);
$total = mysqli_fetch_array($result2);

In the $sql2 query I have made the query return the average as 'handicap' key in the array. Try $average['handicap'] or change AS handicap to AS golfer_handicap
New echo that worked:
echo " Average Handicap: " ."". $average['handicap'] ."	";


text:
Q: iOS Facebook app zoomed icon I have some problems with Facebook sharing. Posted messages look normal via browsers (iOS, PC and Mac versions):

And only FB iOS app shows it wrong:

What could be the reason for this?
UPD:
I tried 200, 600 and 158 pixels images. Result:

My code is:
public LevelUPFeed (int reachedLevel, string pictureURL) //LevelUPFeed : IFeed
{
    _linkDescription = string.Format("Just reached Level {0} ", reachedLevel);
    _picture = pictureURL;
}

public void SendFeed (IFeed feed, Action<bool> callback)
{
    //... callback creating

    FB.Feed (
        feed.ToId, feed.Link,
        feed.LinkName, feed.LinkCaption,
        feed.LinkDescription, feed.Picture,
        feed.MediaSource, feed.ActionName,
        feed.ActionLink, feed.Reference,
        feed.Properties, convertedCallback);
}

feed = new LevelUPFeed (level, pictureUrl);
FBManager.SendFeed (feed, onFeedSent);

feed.LinkName is "Game Name", feed.Link "https://facebook.com", feed.LinkName is "Level Up!". All other strings is string.Empty
Picture links:

*

*600px : http://i.imgur.com/10DdiWc.png

*200px : http://i.imgur.com/0Smpm6s.png

A: There are image specifications in the Open Graph Sharing Best Practices documentation. Use PNG or JPG, 72 dpi, at 600 x 600 pixels for a feed image. The Feed Dialog documentation says 200 x 200, but the Games feed is specifically mentioned in the best practices document.

There are two different image sizes to use for game apps:
Open Graph Stories Images appear in a square format. Image ratios for
  these apps should be 600 x 600 px. Non-open Graph Stories Images
  appear in a rectangular format. You should use a 1.91:1 image ratio,
  such as 600 x 314 px.

If this does not answer your question, could you post your API call code?


text:
Q: windows thread id from managed thread id I know the managed thread id of thread (obtained fr.om a locked object)  I also know that this threadis causing a deadlock. Is it possible to identify the windows thread id? is there any utility available for identifying this.

A: The Threads Window in VS2010 displays both the managed and the native ID.
EDIT in reply to comment: I don't believe the information is available in VS2005/8, but you can get it during debugging by loading SOS through the immediate window.

*

*To load SOS use the .load sos command in the immediate window.

*To get the thread IDs use the !threads SOS command. The ID column holds the managed ID for the thread.


text:
Q: Angular js $resource error when calling query on $resource with path parameter I am trying to hit an ajax call using $resource of angular js to get an array of objects.I am passing an path variable which is an id for the object and when i try to call query on $resource , it shows error given below.resource and controller code is given below.
i am using Spring MVC on backend, for rest controller of spring code is given below.Please give some suggestions, what i am doing wrong here and what is the best practice?
this is the error in console -
TypeError: V is not a function
at https://cdnjs.cloudflare.com/ajax/libs/angular-resource/1.6.1/angular-resource.min.js:13:165
at n (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:7:427)
at C.setUrlParams (https://cdnjs.cloudflare.com/ajax/libs/angular-resource/1.6.1/angular-resource.min.js:13:50)
at Function.l.(anonymous function) [as query] (https://cdnjs.cloudflare.com/ajax/libs/angular-resource/1.6.1/angular-resource.min.js:10:156)
at Object.getSubCategoryIdNameFn [as getSubCategoryIdName] (http://localhost:8080/MyCoupon/resources/js/category/category_service.js:17:71)
at r.$scope.catChanged (http://localhost:8080/MyCoupon/resources/js/coupon/coupon_controller.js:13:19)
at fn (eval at compile (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:213:110), <anonymous>:4:221)
at r.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:133:313)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:252:529
at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:264:447

and here are my service and controller code -
function getSubCategoryIdNameFn(catId){
    var deferred = $q.defer();
    $resource("admin/rest/subcategory-id-name/:catId",{catId:"@catId"}).query({catId:catId})
    .$promise
    .then(function(response){
        deferred.resolve(response);
    },function(error){
        deferred.reject(error);
    });
    return deferred.promise;
}

controller -
$scope.catChanged = function (){
    categoryService.getSubCategoryIdName($scope.coupon.category).then(function(response){
        $scope.subcatList = response;
    },function(error){

    });
}

i am new to angular, so have no idea what the console error saying?
server side controller is in spring -
@RequestMapping(value="subcategory-id-name/{catId}", method=RequestMethod.GET,produces={"application/json"})
public List<SubCategory> getSubCategoryIdAndName(@PathVariable int catId){
    return subCategoryService.getSubCategoryIdName(catId);
}


text:
Q: changing eclipse's java compiler to jdk7 I'm trying to upgrade from jre6 and jdk6 to jre7 and jdk7.
I program using eclipse, i downloaded and installed the jre7 and jdk7 on:
C:\program files\java\
now when I enter eclipse i want to change the used compiler so i go to:
window>preferences>java>compiler
but there appears only 1.3,1.4,1.5 and 1.6
I've also entered:
window>preferences>java>Installed JREs
and added the jre7 version. But the compiler I can't change.
how do I change my eclipse compiler?

A: You need a newer version of Eclipse.  At least 3.7SR1.

A: You need to upgrade to at least Eclipse Indigo SR1, which has been out for over a month. See also Eclipse announces full Java 7 support.
As evidence, here's a screen from my Indigo SR1 preferences:

And here's an example of executabele code snippet using diamond operator and ARM:

A: 3.6 Eclipse version is enough. I`m using the same with JDK1.7

A: Go to Window > Preferences >Java > Installed JREs.
Then click Add... and select Standard VM.
You need to specify the directory of your JRE and give it a name.
When you are done, just check the right JRE in the same window.
By default, the checked JRE is added to the build path of newly created Java projects.
(my Eclipse SDK version is 3.7.0)


text:
Q: DeleteButton bind on ListView SelectedItem Wpf Hiiii Everyone
I'm using WPF with MVVM pattern and that is the reason of my atual problem.
so, let's start the explanation, I have a ListView with some objects inside, on each object i'll use one delete button, so when i click on button, that do not trigger with SelectedItem, but when i click on row, that change the selected and then i can delete using the button.
In that scenario i need to select a row for delete that, but every button can delete any row, and my objective is just need to click on button to trigger the delete entire row.
Here my XAML:
<StackPanel Width="350" Height="480">
    <ListView x:Name="ListView1"
                ItemsSource="{Binding Carrinho}"
                Height="476">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="1" VerticalAlignment="Top"/>
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
            <DataTemplate DataType="VendaItemViewModel">
            <StackPanel Width="310" Orientation="Horizontal"
                        materialDesign:TransitionAssist.DisableTransitions="True">
                <TextBlock Text="{Binding Quantidade}"
                           Foreground="#00b503"
                           Margin="0 40 5 0"
                           FontSize="14"
                           TextWrapping="Wrap"
                           HorizontalAlignment="Left"
                           FontWeight="UltraBold"/>
                <TextBlock Text="{Binding ProdutoViewModel.Descricao}"
                           Foreground="#00b503"
                           Margin="10 40 10 10"
                           FontSize="12"
                           TextWrapping="WrapWithOverflow"
                           Width="170"
                           TextAlignment="Left"
                           FontWeight="Bold"/>
                <TextBlock Text="{Binding ProdutoViewModel.ValorVenda, StringFormat={}R$ {0:F2}}"
                           Foreground="#00b503"
                           Margin="10 40 10 10"
                            FontSize="12"
                           TextWrapping="Wrap"
                           HorizontalAlignment="Right"
                           FontWeight="UltraBold"
                           Height="25"/>
                <Button CommandParameter="{Binding ElementName=ListView1, Path=_selectedDelete}"
                        Command="{ Binding ElementName=ListView1, Path=DataContext.Command}"
                        Background="{x:Null}"
                        BorderBrush="{x:Null}"
                        Margin="0 20 0 0"
                        HorizontalAlignment="Left">
                    <materialDesign:PackIcon Kind="Delete"
                                             Margin="-5,0,0,0"
                                             Foreground="Red"
                                             Width="20" Height="20" />
                </Button>
            </StackPanel>
        </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackPanel>

Earlyer i had an ideia to use ContainerFromElement, but that only can be used without MVVM pattern because should need to write code inside codebehind and i need to do that in my ViewModel.
If someone have any idea or solution I'll apreciate!! thanks!

A: I had a little bit of trouble understanding what you wrote, but I believe you're either wanting to remove a given row when the delete button on that row is clicked, or, only when it is the selected row.
As you didn't provide your model, I created my own called RowData. You should be able to translate my answer to your own circumstance though. I did attempt to keep your variable names.
Binding commands requires routing. So to make this simple, I've provided the CommandHandler. It is short, simple, and reusable. I originally sourced it from yo chauhan, here. It allows you to attach a function/ action, and also supply conditions on whether it can execute.
I've updated your XAML to have a bit of a cleaner structure for MVVM. From my experience, I feel it makes the code clearer, and maintains MVVM.
I've then tied it altogether on the MainWindow, but you can place it anywhere, provided it has the data context. You will notice in the DeleteRow method of MainWindow, there are two sections of code. The first deletes the SelectedRow, which is maintained by MainWindow; it also means, you could have a different row selected, and click any button, and it will remove the highlighted row. The second section removes the given row which has been passed to the parent (meaning, the row which owns the delete button which you pressed).
RowDataModel:
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;

public class RowData : INotifyPropertyChanged
{
    private MainWindow _parent;
    public RowData(MainWindow parent)
    {
        _parent = parent;
    }

    private void NotifyChanged([CallerMemberName] string property = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private decimal _quantidade;

    public decimal Quantidade
    {
        get { return _quantidade; }
        set
        {
            _quantidade = value;
            NotifyChanged(nameof(Quantidade));
        }
    }

    private string _descricao;

    public string Descricao
    {
        get { return _descricao; }
        set
        {
            _descricao = value;
            NotifyChanged(nameof(Descricao));
        }
    }

    private decimal _valorVenda;

    public decimal ValorVenda
    {
        get { return _valorVenda; }
        set
        {
            _valorVenda = value;
            NotifyChanged(nameof(ValorVenda));
        }
    }

    private ICommand _delete;

    public ICommand Delete
    {
        get => _delete ?? (_delete = new CommandHandler(() => DeleteRow(), () => CanDelete()));
    }

    private void DeleteRow()
    {
        if (_parent.DeleteRow(this))
        {
            MessageBox.Show("Deleted!");
        }
        else
        {
            MessageBox.Show("Did not delete.");
        }
    }

    private bool CanDelete()
    {
        return true;
    }
}

CommandHandler:
using System;
using System.Windows.Input;

public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A boolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Connects CanExecuteChanged event
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Force checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

XAML:
<ListView ItemsSource="{Binding Carrinho}" SelectedItem="{Binding SelectedRow}">
    <ListView.View>
        <GridView AllowsColumnReorder="True">
            <GridViewColumn Header="Quantidade" Width="100">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Quantidade}" Foreground="#00b503" Margin="0 40 5 0"
                                    FontSize="14" TextWrapping="Wrap" HorizontalAlignment="Left" FontWeight="UltraBold"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn Header="Descricao" Width="100">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Descricao}" Foreground="#00b503" Margin="10 40 10 10"
                                    FontSize="12" TextWrapping="WrapWithOverflow" Width="170" TextAlignment="Left" FontWeight="Bold"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn Header="ValdorVenda" Width="200">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding ValorVenda, StringFormat=N2}" Foreground="#00b503" Margin="10 40 10 10"
                        FontSize="12" TextWrapping="Wrap" HorizontalAlignment="Right" FontWeight="UltraBold" Height="25"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn Width="100">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <Button Command="{ Binding Delete}" Background="{x:Null}" BorderBrush="{x:Null}"
                                    Margin="0 20 0 0" HorizontalAlignment="Left">
                            <Rectangle Fill="Red" Width="20" Height="20" Margin="10"/>
                        </Button>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

MainWindow:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        Generate();
        InitializeComponent();
        DataContext = this;
    }

    private void Generate()
    {
        Carrinho = new ObservableCollection<RowData>();
        for (int i = 0; i < 100; i++)
        {
            Carrinho.Add(new RowData(this)
            {
                Descricao = "A description",
                Quantidade = 10m + (i * 2.2m),
                ValorVenda = 100m + (i * 1.3m)
            });
        }
        NotifyChanged(nameof(Carrinho));
    }

    private void NotifyChanged([CallerMemberName] string property = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }

    private ObservableCollection<RowData> _carrinho;

    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<RowData> Carrinho
    {
        get { return _carrinho; }
        set
        {
            _carrinho = value;
            NotifyChanged(nameof(Carrinho));
        }
    }

    private RowData _selectedRow;

    public RowData SelectedRow
    {
        get { return _selectedRow; }
        set
        {
            _selectedRow = value;
            NotifyChanged(nameof(SelectedRow));
        }
    }

    public bool DeleteRow(RowData child)
    {
        // Removing Selected Row
        //if (SelectedRow != null)
        //{
        //    var temp = new RowData(this)
        //    {
        //        Descricao = SelectedRow.Descricao,
        //        Quantidade = SelectedRow.Quantidade,
        //        ValorVenda = SelectedRow.ValorVenda
        //    };
        //    Carrinho.Remove(SelectedRow);
        //    SelectedRow = null;

        //    return !Carrinho.Contains(temp);
        //}

        // Removing Row where delete was clicked
        if(child != null)
        {
            Carrinho.Remove(child);

            return !Carrinho.Contains(child);
        }

        return false;
    }
}


text:
Q: How can I check if my script works fine on different python versions I have a python script that I wrote and it's works just fine.
My python version is 3.9.2.
There is a way to check if my script will work without any problems on Python 3.7?
Thank you for the help!
Have a great day


text:
Q: Android Kotlin: unable to save InputStream as file I am building an Android application using Kotlin. In my application, I am trying to save InputStream as a File. But it is not working.
This is the function to save InputStream as File
fun copyStreamToFile(inputStream: InputStream) {
        var outputFile = File("testing-again.png")
        inputStream.use { input ->
            val outputStream = FileOutputStream(outputFile)
            outputStream.use { output ->
                val buffer = ByteArray(4 * 1024) // buffer size
                while (true) {
                    val byteCount = input.read(buffer)
                    if (byteCount < 0) break
                    output.write(buffer, 0, byteCount)
                }
                output.flush()
            }
        }
    }

It is giving me the following error
Process: com.forkthecoop.com22222, PID: 16949
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=546, result=-1, data=Intent { dat=content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/images/media/31/ORIGINAL/NONE/image/jpeg/323542094 flg=0x1 clip={text/uri-list {...}} }} to activity {com.forkthecoop.com22222/com.forkthecoop.com22222.SendOrdinaryMessageActivity}: java.io.FileNotFoundException: testing-again.png: open failed: EROFS (Read-only file system)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5015)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.io.FileNotFoundException: testing-again.png: open failed: EROFS (Read-only file system)
        at libcore.io.IoBridge.open(IoBridge.java:492)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:236)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
        at com.forkthecoop.com22222.PartialMediaUploadPreview.copyStreamToFile(PartialMediaUploadPreview.kt:171)
        at com.forkthecoop.com22222.PartialMediaUploadPreview.handleOnActivityResult(PartialMediaUploadPreview.kt:146)
        at com.forkthecoop.com22222.SendOrdinaryMessageActivity.onActivityResult(SendOrdinaryMessageActivity.kt:208)
        at android.app.Activity.dispatchActivityResult(Activity.java:8310)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5008)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: android.system.ErrnoException: open failed: EROFS (Read-only file system)
        at libcore.io.Linux.open(Native Method)
        at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
        at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
        at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
        at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7542)
        at libcore.io.IoBridge.open(IoBridge.java:478)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:236)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
        at com.forkthecoop.com22222.PartialMediaUploadPreview.copyStreamToFile(PartialMediaUploadPreview.kt:171)
        at com.forkthecoop.com22222.PartialMediaUploadPreview.handleOnActivityResult(PartialMediaUploadPreview.kt:146)
        at com.forkthecoop.com22222.SendOrdinaryMessageActivity.onActivityResult(SendOrdinaryMessageActivity.kt:208)
        at android.app.Activity.dispatchActivityResult(Activity.java:8310)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5008)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2021-03-14 15:56:54.505 518-2903/system_process E/WifiThreadRunner: WifiThreadRunner.call() timed out!
    java.lang.Throwable: Stack trace:
        at com.android.server.wifi.WifiThreadRunner.call(WifiThreadRunner.java:80)
        at com.android.server.wifi.WifiServiceImpl.startScan(WifiServiceImpl.java:497)
        at android.net.wifi.IWifiManager$Stub.onTransact(IWifiManager.java:718)
        at android.os.Binder.execTransactInternal(Binder.java:1159)
        at android.os.Binder.execTransact(Binder.java:1123)

My application has both read and write permissions to the Storage. It is just not working. What is wrong with my code and how can I fix it?

A:
FileNotFoundException: testing-again.png: open failed: EROFS
(Read-only file system)

You cannot save a file in the system folder so you must specify the path and save your image for example i saved the image in the DCIM folder below :
fun copyStreamToFile(inputStream: InputStream) {
    val storeDirectory = this.getExternalFilesDir(Environment.DIRECTORY_DCIM) // DCIM folder
    val outputFile = File(storeDirectory, "testing-again.png")
    inputStream.use { input ->
        val outputStream = FileOutputStream(outputFile)
        outputStream.use { output ->
            val buffer = ByteArray(4 * 1024) // buffer size
            while (true) {
                val byteCount = input.read(buffer)
                if (byteCount < 0) break
                output.write(buffer, 0, byteCount)
            }
            output.flush()
        }
    }
}

You will find your image
in this path : /storage/emulated/0/Android/data/Your_Package_Name/files/DCIM


text:
Q: Is it good to have a Base Activity class? Is it good to have BaseActivity class and that will act as super class for all other activity. I need this to have some common implementations for the activities.
BaseActivity:
public class BaseActivity extends Activity
{
     //All Common implementations goes here
}

Activities
public class HomeActivity extends BaseActivity
{
}

A: I have used this type of BaseActivity for all common method cover.
public abstract class AbstractBaseActivity extends AppCompatActivity{

    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentView());
        ButterKnife.bind(this);
        onViewReady(savedInstanceState, getIntent());
    }

    @CallSuper
    protected void onViewReady(Bundle savedInstanceState, Intent intent) {
        //To be used by child activities
    }

    @Override
    protected void onDestroy() {
        ButterKnife.bind(this);
        super.onDestroy();
    }

    protected void hideKeyboard() {
        try {
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            if (getCurrentFocus() != null)
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
            Log.e("MultiBackStack", "Failed to add fragment to back stack", e);
        }
    }

    public void noInternetConnectionAvailable() {
        showToast(getString(R.string.noNetworkFound));
    }

    protected void showBackArrow() {
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setDisplayHomeAsUpEnabled(true);
            supportActionBar.setDisplayShowHomeEnabled(true);
        }
    }

    public void showProgressDialog(String title, @NonNull String message) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            if (title != null)
                mProgressDialog.setTitle(title);
            mProgressDialog.setIcon(R.mipmap.ic_launcher);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setCancelable(false);
        }
        if (!mProgressDialog.isShowing()) {
            mProgressDialog.setMessage(message);
            mProgressDialog.show();
        }
    }

    public void hideDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    protected void showAlertDialog(String msg) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle(null);
        dialogBuilder.setIcon(R.mipmap.ic_launcher);
        dialogBuilder.setMessage(msg);
        dialogBuilder.setPositiveButton(getString(R.string.dialog_ok_btn), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        dialogBuilder.setCancelable(false);
        dialogBuilder.show();
    }

    protected void showToast(String mToastMsg) {
        Toast.makeText(this, mToastMsg, Toast.LENGTH_LONG).show();
    }

    protected abstract int getContentView();

}

In my every activity.
public class MainActivity extends AbstractBaseActivity
{
      @Override
    protected int getContentView() {
        return R.layout.main_activity;//your layout
    }

    @Override
    protected void onViewReady(Bundle savedInstanceState, Intent intent) {
        super.onViewReady(savedInstanceState, intent);
        //your code
        //get baseclass methods like this
        //showToast("hello");

    }
}

Happy coding :)

A: In this case, I suggest having a base abstract activity, and two concrete inherited subclasses. You define all the common behaviour in the base activity, and have abstract methods for the differences, which you then override in your actual implementations.
For example, for two activities with different layout resources:
public abstract class BaseActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResourceId());
    }
    protected abstract int getLayoutResourceId();
}

public class Activity1 extends BaseActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); // do extra stuff on your resources, using findViewById on your layout_for_activity1
    }
     @Override
    protected int getLayoutResourceId(){
        return R.layout.layout_for_activity1;
    }
}

You can have a lot more abstract methods, for every bit you want specific to your subclasses.
Doing that is, in my opinion, a lot better than having a concrete subclass to a concrete superclass: that can lead to many problems and is usually difficult to debug.
Happy coding. Let me know need more help!!

A: It all depends with your requirement, but for the sake of scalability it has always been handy to have a base class to put all your shared functions. I will hugely suggest to use abstract class just incase you need to define different implementation of shared behaviors, like getting the class name or screen name.


text:
Q: why apache directing request diffirently for chrome? in chrome when I type simply

"http://localhost:81"

request directed to "http://mypersonalweb.com/home"
in mozilla I type

"http://localhost:81"

this time, localhost:81 page open with phpinfo() content.. how I cant find where are these configurations set ?

A: check your httpd.conf file and go to line 'DocumentRoot "C:/xampp/htdocs"'(its for my instance.) Whatever directory writes here there must be a file contains

phpinfo();

function in it. so you need to find this file in httpd.conf file in the line of "DirectoryIndex"
change it whatever you want to begin your application.


text:
Q: Do something if process is terminated If a process is running and for example the user accidentally terminates via the Task Manager or the machine reboots (thus forcefully terminating processes), how can I register such an event that the process will execute some task before completely terminating?
What I've tried unsuccessfully is:
from signal import signal
from signal import SIGTERM

def foo():
    print('hello world')

if __name__ == '__main__':
    signal(SIGTERM, foo)
    while True:
        pass

I'll run this from the command line, then navigate to task manager and end the task but foo is never called.

A: Based on the answer to Can I handle the killing of my windows process through the Task Manager? - it seems like the task manager kills processes using an unmaskable signal (equivalent to Linux's SIGKILL). This means that you cannot catch it.
There are other signals you can catch in Windows, like SIGBREAK, SIGCHLD, CTRL_C_EVENT and CTRL_BREAK_EVENT, but I guess the task manager does not use any of those for terminating a process.


text:
Q: Как получить данные из БД Room с помощью RxJava если с удаленного сервера пришла ошибка Всем привет. Пишу приложение в котором запрашивается погода с удаленного сервера. Для Api запроса использую библиотеку Retrofit   и RxJava. Сейчас мне нужно добавить в приложение БД Room, если при Api запросе получаю ошибку то нужно взять данные из БД и отобразить их пользователю, а если Api запрос прошел успешно то нужно сохранить данные в БД. Подскажите пожалуйста как это реализовать с помошью RxJava?
Интерфейс Dao
@Dao
interface WeatherDataDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertWeatherData(weatherDataEntity: WeatherDataEntity): Single<WeatherDataEntity>

    @Query("SELECT * FROM weather_data WHERE city_name = :cityName AND date = :date ")
    fun getWeatherDataFromDb(cityName: String, date: String): Single<WeatherDataEntity>
}

Так выглядит код репозитория сейчас, мне нужно изменить его добавив туда БД
package com.example.data.implementationRepo

import com.example.data.apiservice.WeatherDataApiService
import com.example.data.mappers.WeatherDataMapper
import com.example.domain.models.WeatherData
import com.example.domain.repositories.WeatherDataRepository
import io.reactivex.rxjava3.core.Single

class WeatherDataRepositoryImpl(
    private val weatherDataApiService: WeatherDataApiService,
    private val mapper: WeatherDataMapper,
    private val weatherDataDao: WeatherDataDao
) : WeatherDataRepository {

    override fun getWeatherData(city: String, days: Int, degreeType: String): Single<WeatherData> =
        weatherDataApiService.getWeatherData(city, days, degreeType)
            .map { mapper.mapWeather(it) }

}

A: Вы можете использовать метод onErrorReturn()
weatherDataApiService.getWeatherData(city, days, degreeType)
        .map { mapper.mapWeather(it) }
        .onErrorResumeNext { getDataFromCache() }

Если у вас уже есть готовое значение(например дефолтное какое-то) вы можете использовать onErrorReturn():
weatherDataApiService.getWeatherData(city, days, degreeType)
        .map { mapper.mapWeather(it) }
        .onErrorReturn { getDataFromCache() }


text:
Q: Using operator/ for directories: good or bad idea? I have a Directory class that stores a string and has a / operator, so that a / b where a is a Directory and b is a std::string will add "/" and b to the string stored in a, like this:
Directory a("/home/joe/foo");
Directory b = a / "bar";

This will have b store the string /home/joe/foo/bar. Is this actually usable, or is it just unnecessary fanciness?

A: Boost Filesystem has overloaded operator/ in a similar fashion.  Before you get too far have you checked out boost filesystem?  http://www.boost.org/doc/libs/1_53_0/libs/filesystem/doc/index.htm

A: It's a bad idea because you are changing the common meaning of the / operator.

A: Overloading operators in this style is... odd. I won't say that its terrible or bad, but you have to keep in mind that in most cases operator/ is more like saying "divide this by that". Now, you're free to overload the operators to whatever you want, but the convention for strings (which can represent directories) is usually that you would overload something like + instead.
When I first come across this code, I get the strange feeling you're trying to divide a directory by something else. And that's just really confusing and not too clear. + might be a better choice, or just using an explicit method name like Append or Combine.

A: I don't think it's a good idea since it doesn't follow common sense.
In book , it offers the rules for operator overloading:
Don't Overload Operators with Built-in Meanings