text:
Q: Angular: Detect change in nested object I have been looking for a solution here and elsewhere for hours and I cannot believe I haven't found one. So anyway. I have a simple Angular component (using it in Ionic 3):
class Item {
  name = 'New item';
}

@Component({
  selector: 'edit-item',
  template: `<input [(ngModel)]='newItem.name' /><button (click)='save()'>Save</button>`
})
export class EditItem {

  newItem = new Item();

  constructor(private cd: ChangeDetectorRef) {
  }

  save() {
    this.newItem = new Item();
  }

}

When I enter text in the input field, it correctly changes item.name. Now however when I click save, the input field continues to show the text I entered. As I created a new item, I'd rather have it display 'New Item'.
I am aware that the Angular change detection does not deep-compare objects. So I have tried to change the save function to:
save() {
    this.cd.detectChanges();
}

I've also tried to change the component's changeDetection to ChangeDetectionStrategy.OnPush and implement a custom ngOnChanges to fire cd.markForChanges() when the item name has changed.
I have not been successful with any of these approaches. Can you please help me find the correct way to solve this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use ng-show and ng-hide with buttons in AngularJS I have two buttons Start and Stop,when I click the Start button I want the Stop button to show and the Start button to be hidden vice versa when I click the Stop button I want the Start button to be shown and the Stop button to be hidden.Only one button must be shown at any one time.Here is what I tried but it doesn't seem to work.Where am I going wrong?

    <button ng-click="Model.StartEvent()" id="btnEventStart">Start</button>

    <button ng-click="Model.StopEvent()" id="btnStopEvent" class="tooltip">Stop</button>

A: You could do even less
<button ng-click="goEvent();" ng-hide="going">Start</button>
<button ng-click="goEvent();" ng-show="going">Stop</button>

...

$scope.going = false;

$scope.goEvent = function(){
   $scope.going = !$scope.going;
   if($scope.going){
       $scope.go();
   }else{
       $scope.stop();
   }
}

A: you should use same variable for both...
<button ng-click="Model.toggleShow(); Model.StartEvent()" ng-show="Model.showStartEvent">Start</button>

<button ng-click="Model.toggleShow(); Model.StopEvent()" ng-show="!Model.showStartEvent">Stop</button>

Modal.toggleShow = function(){
  Model.showStartEvent = !Model.showStartEvent;
}

also you can call toggle right inside the startevent/stopevent rather than having two function calls on ng-click

A: Html:

<button ng-click="StartEvent($event)"id="btnEventStart">Start</button>
<button ng-click="StopEvent($event)" id="btnStopEvent">Stop</button>

Use single semaphore for hide and show EventRunning
Controller:
{ ...
     $scope.EventRunning = false;
     $scope.StartEvent = function (event) {
            event.preventDefault();
            $scope.EventRunning = true;
            // your code
    }

    $scope.StopEvent = function (event) {
            event.preventDefault();
            $scope.EventRunning = false;
            // your code
    }
... }


text:
Q: xml Error in Android Studio android studio
I just make a new project and it doesn't work.
Look at the link. Some of files like 'colors.xml', there is a problem that the files are made that way.
What can I do?

A: Try to replace your colors.xml with this :
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#ff7c30</color>
    <color name="colorPrimaryDark">#fe5d00</color>
    <color name="colorAccent">#009688</color>
</resources>

When you want to add a color just add :
<color name="yourColor">#YOURCOLOR</color>

And you can use it like this for example :
android:textColor="@color/colorAccent"

A: You must synchronize your project first once you created a new project to add those dependencies that validate the codes including the Layout Files. The synchronize button is at the right top of the Android Studio.

A: I figured it out. We can't use capitals in image files.


text:
Q: div expanding animation max-height doesn't work. always height is 0 I'm trying to make expanding animation on pop-up div element.
I want to show the pop-up div with expanding animation when I just open main page.
But always pop-up div's height is 0. I tried so many ways, but nothing works.
Nowhere not below codes, controlling pop-up layer's height.
    .popupLayer     //I tried setting it's height not to 0, but same.
    {
        position:absolute;

        width:76%;

        left:50%;
        top:0%;
        transform: translate(-50%, -55%);

        display:none;
        background-color:white;
        border-radius: 25px;
        overflow: hidden;
    }

    .expand{
        max-height:86%;
        transition: max-height 2s ease-in;
    }

I'm trying with following code:
window.onload = function(){
    var expandDiv = document.getElementsByClassName('popupLayer')[0];

    expandDiv.style.display='inline';
    expandDiv.style.top = '55%';

    $(expandDiv).addClass('expand');
};

    ... // some elements including popup div..

          ...// popuplayer body

    ...

I reffered following links. Expand div on click with smooth animation, How can I transition height: 0; to height: auto; using CSS? .
Thank you for your helps. :)

A: Don't use max-height, class for animation. Directly set the transition and height in CSS and JS respectively:
Key points:

*

*Set initial height and transition in the CSS rule.

*Increase only height from JS. Adding class does not trigger the CSS animation

JS:
    setTimeout(function() { //setTimeout is to add a delay.
        var expandDiv = document.getElementsByClassName('popupLayer')[0];
        expandDiv.style.display = 'block';
        expandDiv.style.top = '55%';
        setTimeout(function() {
            expandDiv.style.height = '55%'; // This is also for showing the animation.
        }, 1000);
    }, 4000);

CSS:
            .popupLayer {
                 position: absolute;
                 width: 76%;
                 left: 50%;
                 top: 0%;
                 transform: translate(-50%, -55%);
                 outline: 1px solid red;
                 display: none;
                 background-color: white;
                 border-radius: 25px;
                 overflow: hidden;
                 transition: height 4s ease-in;
                 height: 0; // Animation works if you set initial height
             }

Demo: https://jsfiddle.net/lotusgodkk/GCu2D/6016/

A: I hope that can help.
<button id="btn">click</button>

.popupLayer
{
    position:absolute;
    width:76%;
    left:50%;
    top:0%;
    height: 0;
    transform: translate(-50%, -55%);
    background: red;;
    border-radius: 25px;
    overflow: hidden;
    transition: all 1s ease-in;
}

.expand {
    top: 55%;
    height:50%;
}

var popupLayer = document.querySelector('.popupLayer');

document.querySelector('#btn').onclick = _ => {
    popupLayer.classList.add('expand');
}


text:
Q: A given polynomial equation of 5 degree has three equal roots . Given equation is $x^5-10a^3x^2+b^4x+c^5=0$ which has 3 equal roots. What I know is that since its a 5th degree equation therefore it must have 5 roots out (of which 3 are equal).
Aim is to establish the relationship between the constants $a,b$ and $c$.
Options given are:
1) $6a^5+c^5=0$.
2) $b^4=15a^4.$
I have to find which one is correct out of the two, any help?

A: Let $$f(x) = x^5 - 10a^3x^2 + b^4x + c^5 = (x - m)^3g(x)$$ where $m$ is the repeated root, and $g(x)$ is some second-order polynomial.
Then, differentiating and substituting $x = m$,
$$5x^4 - 20a^3x + b^4 = (x - m)^3g'(x) + 3(x - m)^2g(x)$$
$$5m^4 - 20a^3m + b^4 = 0$$
Differentiating another time, and similarly substituting $x = m$,
$$20x^3 - 20a^3  = (x - m)^3g''(x) + 3(x - m)^2g'(x) + 3(x - m)^2g'(x) + 6(x - m)g(x)$$
$$20m^3 - 20a^3 = 0$$
$$m = a$$
Substituting this back into our first result,
$$5a^4 - 20a^3\cdot a + b^4 = 0$$
$$b^4 = 15a^4$$

Note: The fact that $(x - m)$ appears in every term of $f'(x)$ and $f''(x)$ is in fact a usable basis for proving what Gerry Myerson mentioned in the comments - that $f(x), f'(x), f''(x)$ all have a common factor.

A: Let $t$ the triple root and consider the coefficients $r,s$ of the quadratic factor so one has the polynomial $(x-t)^3(x^2+rx+s)$. The equality of corresponding coefficients gives $$r-3t=0$$ $$s-3tr+3t^2=0$$ $$-3ts-t^3+3t^r=-10a^3$$  $$3t^2s-t^3r=b^4$$  $$-t^3s=c^5$$   Solving easily this system we have a parameterization of $a,b,c$ in function of the triple root.
$$a=t$$ $$b=\sqrt[4]{15}\space t$$   $$c=-\sqrt[5]{6}\space t$$
The simplest relationship between $a,b,c$ is $$a=\frac{b}{\sqrt[4]15}=\frac{-c}{\sqrt[5]6}$$

A:
Question : I have to find which one is correct out of the two, any help?

Answer : Actually, both the options are correct. I am giving the explanation.
Let $~f(x) = x^5 – 10a^3x^2 + b^4x + c^5~$.
$$~⇒ f'(x) = 5x^4 – 20a^3x + b^4~~~~ ⇒ f'' (x) = 20x^3 – 20a^3~$$
Since $~x = \alpha~$ be a root that is repeated three times, so
$$f''(\alpha) = 0,~~~~~~ f'(\alpha) = 0,~~~~~~ f(\alpha) = 0$$
$$⇒ 20\alpha^3 – 20a^3=0,~~~~~~ 5a^4 – 20a^3\alpha + b^4 = 0,~~~~~~ \alpha^5 – 10a^3\alpha^2 + b^4\alpha +c^5 = 0$$
$$⇒ \alpha = a,~~~~~~ 5a^4 – 20a^3\alpha + b^4 = 0,~~~~~~ \alpha^5 – 10a^3\alpha^2 + b^4\alpha +c^5 = 0$$
$$⇒ b^4 = 15a^4, ~~~~~~c^5 + ab^4 – 9a^5 = 0\qquad (\text{using the  result}~~\alpha = a )~~~~$$
$$⇒ b^4 = 15a^4, ~~~~~~c^5 + 15a^5 – 9a^5 = 0\qquad (\text{using the  value}~~b^4 = 15a^4)$$
$$⇒ b^4 = 15a^4, ~~~~~~6a^5 + c^5 = 0~.$$


text:
Q: i want to take print of a html page which i m sending the url of the file and need to take the print out without QPrintDialog Is there any other way instead of using QPrintDialog box to print i dont want to show dialog box in qt
QWebEngineView view;
view.setUrl(QUrl(html));

QWebEnginePage *webpage = view.page();
QPrinter printer(QPrinter::HighResolution);

QPrintDialog dialog(&printer, webpage->view());
if (dialog.exec() != QDialog::Accepted)
    return;


text:
Q: Derive the Differential Equation for Laguerre polynomials How can i derive this linear differential equation

$$ xD^2L^{(\alpha)}_n (x)+(1+\alpha -x)DL^{(\alpha)}_n (x)+nL^{(\alpha)}_n (x)=0 $$

from the following recurrence relations

$$\frac{d}{dx}L^{(\alpha)}_n (x)=\frac{1}{x}[ nL^{(\alpha)}_n (x)-(\alpha +n) L^{(\alpha)}_{n-1} (x) ]$$
  $$\frac{d}{dx}L^{(\alpha)}_n (x)=\frac{1}{x}[ (x-\alpha-n-1)L^{(\alpha)}_n (x)+(n+1) L^{(\alpha)}_{n+1} (x) ]$$

My work:
$D[xL^{(\alpha)}_n (x)]=D[ (x-\alpha-n-1)L^{(\alpha)}_n (x)+(n+1) L^{(\alpha)}_{n+1} (x) ]$
$xD^2 L^{(\alpha)}_n (x)+DL^{(\alpha)}_n (x)=(-\alpha -n)L^{(\alpha)}_n (x)+(x-\alpha -n-1) DL^{(\alpha)}_n (x)+(n+1)DL^{(\alpha)}_{n+1} (x)$
$xD^2 L^{(\alpha)}_n (x)+DL^{(\alpha)}_n (x)=(-\alpha -n)L^{(\alpha)}_n (x)+(x-\alpha -n-1) DL^{(\alpha)}_n (x)+\frac{(n+1)}{x}[(n+1)L^{(\alpha)}_{n+1} (x)-(\alpha +n+1)L^{(\alpha)}_n]$
$xD^2 L^{(\alpha)}_n (x)+(1+\alpha -x)DL^{(\alpha)}_n (x)=(-\alpha -n)L^{(\alpha)}_n (x)+(-n-1) DL^{(\alpha)}_n (x)+\frac{(n+1)}{x}[(n+1)L^{(\alpha)}_{n+1} (x)-(\alpha +n+1)L^{(\alpha)}_n]$
$xD^2 L^{(\alpha)}_n (x)+(1+\alpha -x)DL^{(\alpha)}_n (x)+nL^{(\alpha)}_n (x)=-\alpha L^{(\alpha)}_n (x)-(n+1) DL^{(\alpha)}_n (x)+\frac{(n+1)^2}{x}L^{(\alpha)}_{n+1} (x)-\frac{(n+1)(\alpha +n+1)}{x}L^{(\alpha)}_n$
Now $ L.H.S=-\alpha L^{(\alpha)}_n (x)-\frac{(n+1)}{x}[(x-\alpha-n-1)L^{(\alpha)}_n (x)+(n+1) L^{(\alpha)}_{n+1} (x) ]+\frac{(n+1)^2}{x}L^{(\alpha)}_{n+1} (x)-\frac{(n+1)(\alpha +n+1)}{x}L^{(\alpha)}_n$
$ L.H.S=-\alpha L^{(\alpha)}_n (x)-\frac{(n+1)(x-\alpha-n-1)}{x}L^{(\alpha)}_n (x)-\frac{(n+1)(\alpha +n+1)}{x}L^{(\alpha)}_n$
$$ L.H.S = (-\alpha -n-1)L^{(\alpha)}_n$$
But is must be zero
please,some help .

A: By comparison with the page below, the discrepancy comes from the coefficient of term underlined in red.


text:
Q: Searching a Files Content Using Java? I would like to write an application, in java, that allows me to open a file (txt) and using the users input, search for all instances of a particular word or string.
As there are probably more experienced programmers here, i would like some advice about how to go about creating such a tool. How would you go about creating a basic text search tool?
I have been playing around with some java classes such as File, FileOutputStream, FileInputStream, InputStreamReader, OutputStreamReader, FileReader, StreamTokenizer and would like to know  the optimal way to open and search a file using java?
Thanks for any input you may have,
Des.

A: Using a File with a Scanner, and a StringBuilder should give you a good start into that topic.

A: I would recommend using a hash table of some kind. If your data is not changing (is this just a basic search of a static document, or is it like part of a text editor?) then Perfect Hashing is going to give you constant-time lookups. This is VERY fast. If not, maybe try Cuckoo hashing or even just linear probing.
I would read in the file using Scanner or any buffered reader, hash every word as a key to whatever additional data you want (such as line numbers / word indexes of all occurrences), then you can query the hash table super fast.
Edit: Here is a Java implementation of Perfect hashing for Strings: http://blog.tomgibara.com/post/438939809/minimal-perfect-hash-strings

A: What do you want to do with the search results? Is it just to count the number of occurances of a given word or the phrase? What if the user types "line" and the file contains "lines"; should there be a match? Do you have to allow multiple searches on the same file?
Anyways the point is that full-text search is a very involved subject. But there is help ;-). My suggestion for you is to create an in-memory index of the file to be searched using open source Lucene project. It is super fast and has answers to all of the above questions and much more. Here is the code to create that in-memory index. Once you have that index created, you can perform sophisticated searches

A: You can read in the text file to a string and then call the split() method. See documentation. This will return an array of strings. After this you can do a search (ie. Binary search) on the array and continue doing it, removing the word you find and saving the location, until all instances have been found. After that you will have all the locations of the search string in the document.
Here is a wikipedia article on binary search in case you might need it:
http://en.m.wikipedia.org/wiki/Binary_search_algorithm?wasRedirected=true

A: To have speed, I would use the BufferedReader. Something like this :
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(givenFile)));

BufferedReader is the most efficent way of reading a file, IMHO.
There is an existing tool, created by Keith Fenske and named FileSearch, that exists. You can dowload the sources and have a look at it :)


text:
Q: Obtain the value from textbox inside of a DataTemplate (WPF) I´ve just created a datatemplate for a ListBox like that:
 <ListBox Height="150" MinHeight="100" HorizontalAlignment="Left" Name="myListBox"
                 VerticalAlignment="Top" Width="290"
                 ItemsSource="{Binding}" SelectionMode="Multiple" Margin="0,18,0,0">
                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Vertical" >
                                        <StackPanel Orientation="Horizontal">
                                            <CheckBox Name="cbLista" Width="100"  Content="{Binding Path=Nom_estudio}"  IsChecked="{Binding IsChecked, Mode=TwoWay}"
                                                  Checked="cbLista_Checked" />
                                            <TextBox Name="txbCantidad" Width="100" Margin="0,0,0,5" TextChanged="txbCantidad_TextChanged" />
                                        </StackPanel>

                                    </StackPanel>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>

And now I can get every object selected in the checkbox, but how can I obtain the text property for the texbox asociated for every checkbox ?

A: Bind the "Text" property of the TextBox to some property (say MyTextProperty) on your data object. Then when you get the "SelectedItems" list, you just access this property.
ie:
<TextBox Text="{Binding MyTextProperty}" ... />

A: Create on more property in your class which has Nom_estudio and IsChecked properties. Then bind that property to TextBox.Text property
        <StackPanel Orientation="Horizontal">
                <CheckBox Name="cbLista" Width="100"  Content="{Binding Path=Nom_estudio}"  IsChecked="{Binding IsChecked, Mode=TwoWay}"
                                              Checked="cbLista_Checked" />
                 <TextBox Name="txbCantidad" Text="{Binding MYTEXTPROPERTY}" Width="100" Margin="0,0,0,5" TextChanged="txbCantidad_TextChanged" />
                                    </StackPanel>


text:
Q: AWS CloudWatch Dashboard sharing I'm using boto3 (Python SDK for AWS) to create a CloudWatch Dashboard for specific clients. The only thing I cannot find an API for is sharing the dashboard with others via email.  I can do it from the AWS console, but I cannot find any API that will return the shareable link.  I think I can do the permissions with the Cognito and IAM but am stumped on the link and hoping there is an API that does what the console does. Has anyone done this or seen any reference in the API docs?

A: It is not possible using Boto3 as it does not provide API for sharing Dashboard.
Though, you can use console to do this, refer below blog that has much information.
https://aws.amazon.com/blogs/mt/share-your-amazon-cloudwatch-dashboards-with-anyone-using-aws-single-sign-on/


text:
Q: Curvature Formula Proof By Definition Question: Use Definition 3.2 to prove Theorem 3.4.
Definition 3.2 "The signed curvature $k(s)$ of a plane curve $ \alpha: I \rightarrow \mathbb{R^2}, \alpha(u)=(x(u),y(u))$ is defined by $t'(s)=k(s)n(s)$ (where $t(s),n(s)$ are the unit tangent and normal vectors, respectively).
Theorem 3.4 "Let $ \alpha: I \rightarrow \mathbb{R^2}, \alpha(u)=(x(u),y(u))$, be a regular curve (not necessarily parametrised by arc length). Then:
$$k(u)=\frac{x'(u)y''(u)—x''(u)y'(u)}{(x'(u)^2+y'(u)^2)^{\frac{3}{2}}}$$
Below is my attempt. I'm not sure why my denominator has the incorrect index. Clearly, it must be small faux pas but I can't find it. I've looked at other proofs here relating to the curvature (as many as I could, there are a lot) but none seem to be exactly the same as this. I apologise in advance if this is a duplicate.

A: As I said in my last comment, the formula $\mathbf{t}'(s) = k(s)\mathbf{n}(s)$ is valid only for the arc- length parametrization. The correct proof for the arbitrary parameter is done below.
Consider the plane curve $\mathbf{r}(u) = (x(u), y(u))$, where $u$ is an arbitrary parameter, and let $s$ be the arc-length parameter. Then, by the chain rule and as $\mathbf{t}(s) = \mathbf{r}'(s)$,
$$\mathbf{r}'(u) =\mathbf{r}'(s) \dfrac{ds}{du} = \dfrac{ds}{du} \mathbf{t}(s)$$
$$\implies \mathbf{t}(s) = \mathbf{r}'(u) \dfrac{1}{\frac{ds}{du}}$$
$$\implies \mathbf{t}'(s) = k \ \mathbf{n}(s) = \mathbf{r}''(u)\dfrac{1}{\left(\frac{ds}{du}\right)^2} - \mathbf{r}'(u) \dfrac{\frac{d^2s}{du^2}}{\left(\frac{ds}{du}\right)^3}$$
$$\implies k \ \mathbf{n}(s) = \dfrac{1}{\left(\frac{ds}{du}\right)^3}\left(\mathbf{r}''(u) \dfrac{ds}{du} - \mathbf{r}'(u) \dfrac{d^2s}{du^2}\right)$$
Now, $\dfrac{ds}{du} = \sqrt{x'(u)^2 + y'(u)^2} \implies \dfrac{d^2 s}{du^2} = \dfrac{x'(u)x''(u) + y'(u)y''(u)}{\sqrt{x'(u)^2 + y'(u)^2}} = (x'(u)x''(u) + y'(u)y''(u))\dfrac{1}{\frac{ds}{du}}$
Using these in the above equation gives,
$$\implies k \ \mathbf{n}(s) = \dfrac{1}{\left(\frac{ds}{du}\right)^4}\left(\mathbf{r}''(u) \left(\dfrac{ds}{du}\right)^2 - \mathbf{r}'(u) \dfrac{d^2s}{du^2} \dfrac{ds}{du}\right)$$
$$\implies k \ \mathbf{n}(s) = \dfrac{1}{\left(\frac{ds}{du}\right)^4}\left(x''(u)\left(\dfrac{ds}{du}\right)^2 - x'(u)\dfrac{d^2s}{du^2} \dfrac{ds}{du}, y''(u)\left(\dfrac{ds}{du}\right)^2 - y'(u)\dfrac{d^2s}{du^2} \dfrac{ds}{du}\right)$$
$$\implies k \ \mathbf{n}(s) = \dfrac{1}{\left(\frac{ds}{du}\right)^4}\left(x''(u)y'(u)^2 - x'(u)y'(u)y''(u), \ y''(u)x'(u)^2 - x'(u)y'(u)x''(u)\right)$$
$$\implies k \ \mathbf{n}(s) = \dfrac{1}{\left(\frac{ds}{du}\right)^4}\big(y'(u)(x''(u)y'(u) - x'(u)y''(u)), \ x'(u)(y''(u)x'(u) - y'(u)x''(u))\big)$$
Taking the magnitude of both sides,
$$k = \dfrac{1}{\left(\frac{ds}{du}\right)^4}\sqrt{(y'(u))^2(x''(u)y'(u) - x'(u)y''(u))^2 + (x'(u))^2(y''(u)x'(u) - y'(u)x''(u))^2}$$
$$\implies k = \dfrac{1}{\left(\frac{ds}{du}\right)^4} \cdot \dfrac{ds}{du}(x'(u)y''(u) - y'(u)x''(u))$$
$$\implies k = \dfrac{x'(u)y''(u) - y'(u)x''(u)}{\left(\frac{ds}{du}\right)^3} = \dfrac{x'(u)y''(u) - y'(u)x''(u)}{(x'(u)^2 + y'(u)^2)^{\frac{3}{2}}}$$


text:
Q: python tkinter - Make a treeview widget for Directory display with a list of folders so what i want to say is that i want a tkinter treeview widget which shows all files and sub-folders in the directory..
and that too with viewing folders from a list of folders..
I have till now tried that by making a treeview for a single directory but can't make it to view a list of directories

A: You didn't show code so I don't understand what is your problem.
If you have list then use for-loop.

Minimal working code for list with two folders ['test', 'Pobrane']
I use listdir() but you may need os.walk()
import os
import tkinter as tk
from tkinter import ttk

folders = ['test', 'Pobrane']

root = tk.Tk()

tree = ttk.Treeview()
tree.pack(fill='both', expand=True)

for folder in folders:
    tree.insert('', 'end', folder, text=folder)
    for name in os.listdir(folder):
        tree.insert(folder, 'end', name, text=name)

root.mainloop()


text:
Q: Django Dev/Prod Deployment using Mercurial I've a puzzle of a development and production Django setup that I can't figure out a good way to deploy in a simple way. Here's the setup:

*

*/srv/www/projectprod contains my production code, served at www.domain.com

*/srv/www/projectbeta contains my development code, served at www.dev.domain.com

*Prod and Dev are also split into two different virtualenvs, to isolate their various Python packages, just in case.

What I want to do here is to make a bunch of changes in dev, then push to my Mercurial server, and then re-pull those changes in production when stable. But there are a few things making this complicated:

*

*wsgi.py contains the activate_this.py call for the virtualenv, but the path is scoped to either prod or dev, so that needs to be edited before deployment.

*manage.py has a shebang at the top to define the correct python path for the virtualenv. (This is currently #!/srv/ve/.virtualenvs/project-1.2/bin/python so I'm wondering if I can just remove this to simplify things)

*settings.py contains paths to the templates, staticfiles, media root, etc. which are all stored under /srv/www/project[prod|dev]/*
I've looked into Fabric, but I don't see anything in it that would re-write these files for me prior to doing the mercurial push/pull.
Does anyone have any tips for simplifying this, or a way to automate this deployment?

A: *

*Two branches for different environment (with env-specific changes in each, thus - additional merge before deploy)

or

*

*MQ extension, "clean" code in changesets, MQ-patch for every environment on top of single branch (and accuracy with apply|unapply of patches)


text:
Q: Check if this is duplicate I want to check if the username already exists and throw an error message if exist, any tips how can I do it?
I've already tried to search but only found mysql_errno but it won't work for me.
  if ($valid) {
        $pdo = Database::connect();
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //$password = md5($password);
        $sql = "INSERT INTO users (username,password,role) values(?, ?, ?)";
        $q = $pdo->prepare($sql);
        $q->execute(array($username,$password,$role));
        Database::disconnect();
        header("Location: index.php");
    }

sd

A: If you want to check if the username is already used :
SELECT * FROM users WHERE username = :username

If you return one row : you throw your error, else you do your INSERT
So your code should look like this :
if ($valid) {
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql_check = "SELECT * FROM users WHERE username = :username";
    $test = $pdo->prepare($sql_check);
    $test->bindParam(':username', $username);
    $test->execute;

Now here is two solution to check if you have one row :
    if($test->rowCount() > 0) {
        // error
    }

or
    $user = $test->fetch();

    if (!empty($user)) {
        // error
    }

And now if you don't have error, do you insert :
    else {
        //$password = md5($password);
        $sql = "INSERT INTO users (username,password,role) values(?, ?, ?)";
        $q = $pdo->prepare($sql);
        $q->execute(array($username,$password,$role));
        Database::disconnect();
        header("Location: index.php");
    }
}

A: Two solutions:
You could make the username field unique, this way, MYSQL would throw an error if you try to insert a line with an existing username.
$sql = "INSERT INTO users (username,password,role) values(?, ?, ?)";
$q = $pdo->prepare($sql);
$result = $q->execute(array($username,$password,$role));
if(!$result) {
    // print out your error message
}

Otherwise, make a select with the wanted username and see if a row is returned (= already used) or not (=available).
$sql = "SELECT COUNT(*) as count FROM users WHERE username = ?";
$q = $pdo->prepare($sql);
$q->execute(array($username));
$result = $q->fetchAll();
// test result, if 1 > print error, etc

A: SELECT * FROM users WHERE username = $username

If found show error, else insert

A:  <?php
     $getUniqueUsername=$con->query("select * from user where name='$user_name");
     $rowCount=$getUniqueUsername->num_rows;

     if($rowCount) {
          $insertQuery=$con->query("insert into table_name (field_name) Values('".$values."'));
     }
?>


text:
Q: How to securely and efficiently store SSN in a database? My main problem is that I would like to check if someone with the same SSN has multiple accounts with us. Currently all personally identifiable info is encrypted and decryption takes a non-trivial amount of time.
My initial idea was to add a ssn column to the user column in the database. Then I could simply do a query where I get all users with the ssn or user A.
I don't want to store the ssn in plaintext in the database. I was thinking of just salting and hashing it somehow.
My main question is, is this secure (or how secure is it)? What is there a simple way to salt and hash or encrypt and ssn using python?
Edit: The SSN's do not need to be displayed.
This is using a MySQL database.

A: Do not encrypt SSNs, when the attacker gets the DB he will also get the encryption key.
Just using a hash function is not sufficient and just adding a salt does little to improve the security.
Basically handle the SSNs inthe same mannor as passwords.
Instead iIterate over an HMAC with a random salt for about a 100ms duration and save the salt with the hash. Use functions such as PBKDF2 (aka Rfc2898DeriveBytes), password_hash/password_verify, Bcrypt and similar functions. The point is to make the attacker spend a lot of time finding passwords by brute force. Protecting your users is important, please use secure password methods.

A: As per @zaph 's advice. I decided to use PBKDF2. I can then create a BIT column and index that.
My simple hashing looks like
import os
import hashlib

def hash_function(input_str):
    """Run pbkdf2_hmac with a 20byte salt, and 120,000 round on the input."""
    salt = os.urandom(20)
    return hashlib.pbkdf2_hmac('sha256', input_str, salt, 120000)

A: Your question doesn't make it clear if you need to display those SSNs. I'm going to assume you do not. Store the SSN in a SHA2 hash. You can then do a SQL query to search against those hashed values. Store only the last 4 digits encrypted for display.


text:
Q: Trying to deploy our S4 program, we have a fatal error with debug We wrote an application with SF4. It works fine, even on the remote site, in dev mode.
So we try to get prod mode. In .env, we pass the APP_ENV variable to prod, an we have the message :

Fatal error: Uncaught Symfony\Component\DependencyInjection\Exception\InvalidArgumentException: There is no extension able to load the configuration for "debug" (in /home/olymphys/public_html/config/packages/debug.yml). Looked for namespace "debug", found "framework", "sensio_framework_extra", "doctrine_cache", "doctrine", "doctrine_migrations", "security", "swiftmailer", "twig", "monolog", "easy_admin", "vich_uploader", "webpack_encore" in /home/olymphys/public_html/vendor/symfony/dependency-injection/Loader/YamlFileLoader.php:682 Stack trace: #0 /home/olymphys/public_html/vendor/symfony/dependency-injection/Loader/YamlFileLoader.php(652): Symfony\Component\DependencyInjection\Loader\YamlFileLoader->validate(Array, '/home/olymphys/...') #1 /home/olymphys/public_html/vendor/symfony/dependency-injection/Loader/YamlFileLoader.php(119): Symfony\Component\DependencyInjection\Loader\YamlFileLoader->loadFile('/home/olymphys/...') #2 /home/olymphys/public_html/vendor/symfony/config/Loader/FileLoader.php(151): Symfony\Component\D in /home/olymphys/public_html/vendor/symfony/config/Loader/FileLoader.php on line 166

We tried to use dump_destination in symfony/debug-bundle config
and nothing different happen...

A: Whatever you have on packages/debug.yml should not be there for production.
Move it to packages/dev/debug.yml so it's only loaded when APP_ENV is set to dev.


text:
Q: How to insert a translation into a subdocument nested in an array? With a schema like this, where the "items" field contains an array of subdocuments with nested translations :
{
        "_id" : ObjectId("513740415b51ea0803000001"),
        "items" : [
                {
                        "id" : ObjectId("5137407f5b51ea100f000000"),
                        "title" : {
                                "en" : "Yes",
                                "fr" : "Oui",
                                "es" : "Si"
                        }
                },
                {
                        "id" : ObjectId("5137407f5b51ea100f000003"),
                        "title" : {
                                "en" : "No"
                        }
                }

        ],
}

How would you add a translation to a specific item id ?

A: You can use the $ positional operator to update a specific array element of a doc.
For example, to add "de": "nein":
db.test.update(
    {'items.id': ObjectId("5137407f5b51ea100f000003")},
    {$set: {'items.$.title.de': 'nein'}})

The $ in the $set object represents the index of the element in items that the query selection parameter matched.

A: You can do it like that:
db.yourColName.update({"items.id" : "itemId"}, {$set : {"translationField" : "translationValue"}})
Over here in the first part of the query you are searching for the direct item in the array and set a new field + value for it.
The thing is, like you have already noticed, that Mongo doesn't have static schema. So $set will either update already existing field or create a new one. It all depends on the field name you set in the subquery.
To get to the direct document use the $ operator: items.$.title.fr where $ would represent the current object.


text:
Q: Unable to test Sendgrid locally with HTTP Error 403: Forbidden I'm trying to do a basic test with Sendgrid but I keep getting 403 and 401 with my requests.
I'm doing the testing with the localhost development server to simulate a request to my endpoint. My sendgrid key is stored in .env like the rest of my keys as sendgrid_api_key. My API key has full access to sendgrid. I have installed sendgrid==6.9.7
import os
import sendgrid

def sendgrid_welcome_email(request):
    try:

        sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('sendgrid_api_key'))

        response = sg.client.contactdb.lists.get()
        print(response.status_code)
        print(response.body)
        print(response.headers)

    except Exception as ex:
        print("Unexpected error: " + str(ex))
        return "Bad", 500

Error "Unexpected error: HTTP Error 403: Forbidden"

A: So I solved it by using another client endpoint, I think the docs I looked at were old.
import os
from sendgrid import SendGridAPIClient

sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))

data = {
    "contacts": [
        {
            "email": "ryan39@lee-young.com"

        }
    ]
}

response = sg.client.marketing.contacts.put(
    request_body=data
)

print(response.status_code)
print(response.body)
print(response.headers)


text:
Q: Error Grouping in Pivot MySQL with Join Table I have non aggregate rows data in MySQL and I need to create a pivot.
I run my query:
SELECT
  a.id,
  a.kredit_member_no,
  CASE WHEN b.slug='fullname' THEN a.value END as fullname,
  CASE WHEN b.slug='gender' THEN a.value END as gender,
  CASE WHEN b.slug='email' THEN a.value END as email
FROM kredit_data a
LEFT JOIN master_data b ON a.master_id = b.id
WHERE b.slug = 'fullname'
  OR b.slug = 'gender'
  OR b.slug = 'email'
GROUP BY a.kredit_member_no;

But I get this MySQL Error:
SELECT list is not in GROUP
BY clause and contains nonaggregated column 'vortunes_db.a.id' which
is not functionally dependent on columns in GROUP BY clause; this
is incompatible with sql_mode=only_full_group_by

And I remove the GROUP BY i get this result :

How to group them by kredit_member_no ?

A: Even though your data is a string, you'll still want to use an aggregate function on those CASE statements to pivot those rows into columns. Since you have only_full_group_by turned on, you'll also need to either place a.id into the GROUP BY clause or you'll need to remove it that column from the final select list.  I'd suggest changing the query to this:
SELECT
  a.kredit_member_no,
  max(CASE WHEN b.slug='fullname' THEN a.value END) as fullname,
  max(CASE WHEN b.slug='gender' THEN a.value END) as gender,
  max(CASE WHEN b.slug='email' THEN a.value END) as email
FROM kredit_data a
LEFT JOIN master_data b
  ON a.master_id = b.id
  and b.slug IN ('fullname', 'gender', 'email')
GROUP BY a.kredit_member_no;

See SQL Fiddle with Demo
You will also notice that I moved your WHERE clause to the JOIN, this is because you were basically performing an INNER JOIN instead of a LEFT JOIN, which doesn't seem like what you intended.


text:
Q: How to to replace div with a script? Using innerhtml does not work I am trying to replace the contents of a div with a script using innerHTML.
Here is generally what the important parts of my HTML looks like:
    <script> function replace() {
    document.getElementById("area").innerHTML = '<script type="text/javascript" src="SOMELINK"></script>';
    </script>

    <button onclick=replace()> replace </button>
    <div id = "area"> hello </div>

When the button is clicked, I want the div #area to be replaced by the script, such that it shows the contents of the link. I can use innerHTML to replace it with a plaintext, like replace "hello" with "Hello World", but when I include the  tags, nothing shows up at all. If I remove the tags, the rest of the url that goes inside the tags shows up. Any idea on what I might be doing wrong, and how I can use javascript to replace a div with a script object?
edit: I had mistyped the script tag, but now its fixed!

A: Your script tag is malformed, and inserting a script via innerHTML doesn't execute the script. You can create a script element and append it, if you want it to load the source or execute its inner contents.
var area = document.getElementById('area'),
    script = document.createElement('script'); // Create the script
// Set the script source
script.src = 'myAwesomeScript.js';
// Remove the contents of the DIV
area.innerHTML = '';
// But why would you nest a script inside of a DIV, anyway?
area.appendChild(script); // Append it

If you actually want to replace the whole DIV with a script tag:
var area = document.getElementById('area');

// * elem is the element to replace
// * src is the script's source
function replaceWithScript(elem, src) {
    var script = document.createElement('script');
    script.src = src;
    // Insert script after elem
    elem.parentNode.insertBefore(script, elem.nextSibling);
    // Remove elem. Now script has its position, and it looks
    // like it replaced it.
    elem.parentNode.removeChild(elem);
}

replaceWithScript(area, 'myAwesomeScript.js');

Finally, if you want the script to show up as text, then it's just:
document.getElementById('area').innerText = '<script src="farboo.js"></script>';

A: it should work if you provide it with well formed HTML
document.getElementById("area").innerHTML =
  '<script type="text/javascript" src="SOMELINK"></script>';

(you were missing the closing tag)


text:
Q: how to notify user about update available for my application in windows phone marketplace for OS 7.1 Can any one tell me the steps to be followed to notify users that there is an update for my windows phone 7.1 application at market place so that he can go any update it ?

A: if you release an update in the marketplace then the platform will prompt the user automatically. If you want to force an update then the old version will need to poll a service at startup and alert the user that they should go to marketplace and get the new version


text:
Q: Limit number of rows - TSQL - Merge - SQL Server 2008 Hi all i have the following merge sql script which works fine for a relatively small number of rows (up to about 20,000 i've found). However sometimes the data i have in Table B can be up to 100,000 rows and trying to merge this with Table A (which is currently at 60 million rows). This takes quite a while to process, which is understandable as it has to merge 100,000 with 60 million existing records!
I was just wondering if there was a better way to do this. Or is it possible to have some sort of count, so merge 20,000 rows from Table B to Table A. Then delete those merged rows from table B. Then do the next 20,000 rows and so on, until Table B has no rows left?
Script:
MERGE
    Table A AS [target]
USING
    Table B AS [source]
ON
    ([target].recordID = [source].recordID)
WHEN NOT MATCHED BY TARGET
    THEN
        INSERT([recordID],[Field 1]),[Field 2],[Field 3],[Field 4],[Field 5])
        VALUES([source].[recordID],[source].[Field 1],[source].[Field 2],[source].[Field 3],[source].[Field 4],[source].[Field 5]
    );

A: MERGE is overkill for this since all you want is to INSERT missing values.
Try:
INSERT INTO Table_A
([recordID],[Field 1]),[Field 2],[Field 3],[Field 4],[Field 5])
SELECT  B.[recordID],
        B.[Field 1],B.[Field 2],B.[Field 3],B.[Field 4],B.[Field 5]
FROM Table_B as B
WHERE NOT EXISTS (SELECT 1 FROM Table_A A
                  WHERE A.RecordID = B.RecordID)

In my experience MERGE can perform worse for simple operations like this.  I try to reserve it for when you need varying operations depending on conditions, like an UPSERT.

A: You can definitely do (SELECT TOP 20000 * FROM B ORDER BY [some_column]) as [source] in USING and then delete these records after MERGE. So you pseudo-code will look like :
1. Merge top 20000
2. Delete 20000 records from source table
3. Check @@ROWCOUNT. If it's 0, exit; otherwise goto step 1

I'm not sure if it runs any faster than merging all the records at the same time.
Also, are you sure you need MERGE? From what I see in your code INSERT INTO ... SELECT should also work for you.


text:
Q: Why is Hestenes-Powell-Rockafellar penalty function differentiable? They say the penalty function $f:\mathbb{R}^n\rightarrow \mathbb{R}$ given by
$$f(x) = \frac{\rho}{2}\displaystyle \sum_{j=1}^n \left(\max\{0,\mu_j + \rho x_j\}\right)^2$$ is differentiable and even give a formula for the gradient
$$ \nabla f(x) = -\displaystyle \sum_{j=1}^n \max\{0,\mu_j + \rho x_j\}e_j,$$
for the context you can consider $\mu=(\mu_j)$ and $ \rho>0$ as constants. I can kinda see how the derivative would become something like that if the function $\max\{0,\mu_j + \rho x_j\}$ was differentiable, but why is it? There is a maximum. Shoulnd't it be non-differentiable on the places where the scalar functions $0$ and $\mu_j + \rho x_j$ meet?


text:
Q: How to get null object when user detail is not found using postgresql currently I use this code.
SELECT jsonb_agg(user_data) AS contact_info
FROM (
  SELECT jsonb_build_object('user_id', u._id,
                            'name', u.name,
                            'mobile', u.mobile,
                            'profile', CASE WHEN u.profile IS NOT NULL THEN CONCAT ('${process.env.S3_URL}', '', u.profile) ELSE NULL END,
                            'address_list', jsonb_agg(jsonb_build_object('_id', ua._id,
                                                                         'address', address,
                                                                         'lat', lat,
                                                                         'long', long)
                             ORDER BY user_id ASC)) AS user_data
  FROM users u
    LEFT JOIN users_address ua ON ua.user_id = u._id
  WHERE ua.user_id = ${contact_id}
    AND ua.is_deleted = 0
  GROUP BY u._id,
           u.name,
           u.mobile,
           u.profile
) t

Here i use two table > 1. users 2.users_address.   contact_id is nothing but a user id which store in users table. and in users_address i also stored a user_id for referrece so i can easily join that both table using user_id.
current output:
"data": {
        "name": "abhi",
        "mobile": "3256417890",
        "profile": "asda",
        "user_id": 1,
        "address_list": [
            {
                "_id": 3,
                "lat": 23.0031403,
                "long": 72.5337234,
                "address": "India"
            },
            {
                "_id": 5,
                "lat": 23.0031403,
                "long": 72.5337234,
                "address": "India"
            },
            {
                "_id": 7,
                "lat": 23.0031403,
                "long": 72.5337234,
                "address": "India"
            }
        ]
    }

this output is right but whenever i enter contact_id which having null data in users_address table then it throw error.
if no data found then my expected output is :
"data": {
        "name": "abhi",
        "mobile": "3256417890",
        "profile": "asda",
        "user_id": 1,
        "address_list": []
    }

please someone help me to figure out this error. Thank you in adavance.

A: If you want to do a left join on users_address, you should put all related conditions on the users_address table within the LEFT JOIN conditions, instead of in a WHERE:

    LEFT JOIN users_address ua ON ua.user_id = u._id
  WHERE ua.user_id = ${contact_id}
    AND ua.is_deleted = 0

Should be
    LEFT JOIN users_address ua ON (ua.user_id = u._id
  AND ua.user_id = ${contact_id}
    AND ua.is_deleted = 0)

The difference is that the WHERE will apply the conditions on the null cells returned by the LEFT JOIN, so it will remove them.
Also, you don't need the clause

WHERE ua.user_id = ${contact_id}

This is covered by your LEFT JOIN clause already (and it is dangerous to pass raw variables to your SQL string)


text:
Q: Meaning of 2 in's in shell script for loop? What does the 2nd "in" do?  I can't seem to find this kind of example anywhere other than this one right here.
for a in in /home/davidwright/attachments/*/*.tar
do
  echo "extracting $x"
  tar -xvf $x
done

A: Looks like a typo. It means the loop iterates with the string "in" as the first value assigned to a, then proceeds to iterate over the results of the glob. The shell's just not that picky, and every item after the first in is a thing to iterate over in the for loop. Unless there is a file named in that is known to exist, tar will complain when it tries to unpack the non-existent in file.


text:
Q: Two dependent request and recyclerView adapter I have two requests that depend on each other and I want to pass both results to the recyclerView adapter.
Unfortunately, following code does not return data_1 in collect. But when I commented out second collect with data_2 then I see result for data_1.
class MyViewModel(UUID: GUID): ViewModel() {

    private val _data_1: MutableStateFlow<List<Example>> = MutableStateFlow(emptyList())
    val data_1: StateFlow<List<Example>> get() = _data_1.asStateFlow()

    private val _data_2: MutableStateFlow<List<Example_2>> = MutableStateFlow(emptyList())
    val data_2: StateFlow<List<Example_2>> get() = _data_2.asStateFlow()

    init {
        viewModelScope.launch(Dispatchers.IO) {
            _repository.getData(UUID).collect { data_1 ->
            _data_1.value = data_1
            getSecondData(data_1)
        }
    }

    private suspend fun getSecondData(item: List<Example>) {
        val list = mutableListOf<Event>()
            coroutineScope {
                for (item in items) {
                    async(Dispatchers.IO) {
                        _repository.getSecondData(item).collect { it ->
                            list.add(it)
                        }
                    }.await()
                }
                _data_2.value = list
            }
    }
}

Fragment() {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                myViewModel.data_1.collect { data_1 ->
                    myViewModel.data_2.collect { data_2 ->
                        withContext(Dispatchers.Main) {
                            binding.myRecyclerView.adapter = MyListAdapter(data_1, data_2)
                    }
                }
            }
        }
    }
}

I have check with Log.d that data_1 with data_2 returns records. I have tried storing data_1 in private variable in fragment before calling second collect. I have tried joinAll option but together with launch/collect it will never work.
Why is it not working and what should I do to fix it?


text:
Q: openvpn 's netmask and client-to-client mode I had set openvpn 's config as
route 10.8.0.0 255.255.255.0
push "route 10.8.0.0 255.255.255.0"
client-to-client

and set ccd/username as
iroute 10.8.0.0 255.255.255.0

BUT, the client's netmask was 255.255.255.252 yet. and server's ifconfig is:
tun0    Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
        inet addr:10.8.0.1  P-t-P:10.8.0.2  Mask:255.255.255.255
        UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1

I want to set client and server 's mask as 255.255.255.0, for client-to-client communication.

A: OpenVPN (in layer 3/tun mode) creates virtual point-to-point (like you would get with RS232 for example) links between the server and each client. Any traffic between clients goes trough the server (if there is no client-to-client directive, the server just drops those packets).
Check the routing tables of the clients they should say:
10.8.0.0/24 interface tun0
If you use OpenVPN in layer2/tap mode then it creates a virtual ethernet card with the proper IP and netmask.

A: I think it is all a matter of setting the topology parameter to subnet, and then specifying the netmask on the server parameter at the server's config file, like:
server 10.8.0.0 255.255.255.0

Without the topology parameter it seems those changes will not work.
Extracted from here.


text:
Q: Error with Icon class that sows up only on web not with aplet-viewer I have a class that loads a array of icons, my applet uses 2 such arrays, one for images and one for their thumbnails.
I have a animation thread that rotates a set of 6 thumbnails through the array of thumbnails as well as a slider that allows for scrolling through the thumbnails.
When i use applet-viewer the program works fine but if i package the applet and view it on a browser OR if i upload the unpackaged applet onto a website the thumbnails, but NOT the images that use the same class to load does not show up on the screen and the functionality that comes with the thumbnails becomes laggy.
I cant promise that the site wont change but you can try to see the bugs yourself at http://tokweweb.uphero.com/
here is the code for the class that is giving me the problem:
Thank you
    public class IconArray {
    private ImageIcon[] Icons;
    private int Count;
    private String Filepath;

    IconArray(String filepath, int count){
        Count = count;
        Icons = new ImageIcon[Count];
        Filepath = filepath;
    }

    IconArray(String filepath, int count, boolean Autoload){
        Count = count;
        Icons = new ImageIcon[Count];
        Filepath = filepath;
        if(Autoload){
            for(int i = 0; i<Count; i++){
                Icons[i] = new ImageIcon(getClass().getResource(Filepath+i+".jpg"));
            }
        }
    }

    public Icon GetIcon(final int i) throws InterruptedException{
        if(Icons[i]!=null){
          return Icons[i];
          }else{
            Integer temp = new Integer(i);
            Icons[i] = new javax.swing.ImageIcon(getClass().getResource(Filepath+temp.toString()+".jpg"));
            return Icons[i];
        }
    }

    public int GetCount(){
        return Count;
    }

}

A: Your applet appears to consist of a single class file. You probably want to bundle the images with your class in a JAR file, as shown in Using Images in a Swing Applet.


text:
Q: PHP - How do I go from a binary string to a blob in the database? I have a binary string and I am trying to put it into the database. I do this by trying to unpack it to a binary array and then insert it into the database. But once I do that the blob column appears to be empty? I'm really stuck on this problem. $request->recording is the binary string.

Var Dump looks like this, except it's way longer but I cut it off otherwise it would be too long

array(5177) {   2=>   int(0)   2=>
  int(1)   [3]=>   int(0)   [4]=>   int(0)   [5]=>   int(0)   [6]=>
  int(255)   [7]=>   int(255)   [8]=>

Inserting into the database
function insertIntoTable($connection, $tablename, $request)
{
    $stmt = $connection->prepare("INSERT into $tablename(game_name, gamer_tag, meta_data, recording) values (?, ?, ?, ?)");
    $byteArray = unpack('C*', $request->recording);
    var_dump($byteArray);
    $stmt->bind_param("sssb", $request->game_name, $request->gamer_tag, $request->meta_data, $byteArray);

    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error . " \r\n";
    }
}

Base 64 encode results

string(1916)
  "AAEAAAD/////AQAAAAAAAAAMAgAAAEZBc3NlbWJseS1DU2hhcnAsIFZlcnNpb249MC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1udWxsBQEAAAAaUmVjb3JkUmVwbGF5RGF0YS5SZWNvcmRpbmcBAAAACXJlY29yZGVycwOKAVN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbUmVjb3JkUmVwbGF5RGF0YS5SZWNvcmRlckRhdGEsIEFzc2VtYmx5LUNTaGFycCwgVmVyc2lvbj0wLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPW51bGxdXQIAAAAJAwAAAAQDAAAAigFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1JlY29yZFJlcGxheURhdGEuUmVjb3JkZXJEYXRhLCBBc3NlbWJseS1DU2hhcnAsIFZlcnNpb249MC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1udWxsXV0DAAAABl9pdGVtcwVfc2l6ZQhfdmVyc2lvbgQAAB9SZWNvcmRSZXBsYXlEYXRhLlJlY29yZGVyRGF0YVtdAgAAAAgICQQAAAABAAAAAQAAAAcEAAAAAAEAAAAEAAAABB1SZWNvcmRSZXBsYXlEYXRhLlJlY29yZGVyRGF0YQIAAAAJBQAAAA0DBQUAAAAdUmVjb3JkUmVwbGF5RGF0YS5SZWNvcmRlckRhdGECAAAACnJlY29yZGVySUQGZnJhbWVzAAMIhwFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1JlY29yZFJlcGxheURhdGEuRnJhbWVEYXRhLCBBc3NlbWJseS1DU2hhcnAsIFZlcnNpb249MC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1udWxsXV0CAAAAAQAAAAkGAAAABAYAAACHAVN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbUmVjb3JkUmVwbGF5RGF0YS5GcmFtZURhdGEsIEFzc2VtYmx5LUNTaGFycCwgVmVyc2lvbj0wLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPW51bGxdXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBAAAHFJlY29yZFJlcGxheURhdGEuRnJhbWVEYXRhW10CAAAACAgJBwAAAAEAAAABAAAABwcAAAAAAQAAAAQAAAAEGlJlY29yZFJlcGxheURhdGEuRnJhbWVEYXRhAgAAAAkIAAAADQMMCQAAAE1Vbml0eUVuZ2luZS5Db3JlTW9kdWxlLCBWZXJzaW9uPTAuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49bnVsbAUIAAAAGlJlY29yZFJlcGxheURhdGEuRnJhbWVEYXRhBAAAAAZzZWNvbmQIcG9zaXRpb24Icm90YXRpb24Fc2NhbGUABAQECxNVbml0eUVuZ2luZS5WZWN0b3IzCQAAABZVbml0eUVuZ2luZS5RdWF0ZXJuaW9uCQAAABNVbml0eUVuZ2luZS5WZWN0b3IzCQAAAAIAAAAK16M8Bfb///8TVW5pdHlFbmdpbmUuVmVjdG9yMwMAAAABeAF5AXoAAAALCwsJAAAAAAAAAKAcdb8AAAAABfX///8WVW5pdHlFbmdpbmUuUXVhdGVybmlvbgQAAAABeAF5AXoBdwAAAAALCwsLCQAAAAAAAAAAAAAAAAAAAAAAgD8B9P////b///8AAIA/AACAPwAAgD8L"

A: The problem was the bind_param("sssb because it shouldn't be a b but an s at the end. So like bind_param("ssss because i'm inserting a binary string and not a blob.


text:
Q: Fetching the childrens by id from the json tree structure data I am using JS to archive the following functionality.
My json data
data=[{"id":63,"parent":59,"currency":1},{"id":64,"parent":59,"currency":1},
{"id":1,"parent":null,"currency":1},{"id":2,"parent":1,"currency":4},
{"id":4,"parent":3,"currency":4},{"id":3,"parent":2,"currency":2},
{"id":5,"parent":1,"currency":5},{"id":6,"parent":1,"currency":6},
{"id":7,"parent":3,"currency":2},{"id":8,"parent":1,"currency":1},
{"id":57,"parent":56,"currency":1},{"id":58,"parent":1,"currency":1},
{"id":59,"parent":1,"currency":1},{"id":30,"parent":1,"currency":1},
{"id":31,"parent":1,"currency":1},{"id":32,"parent":1,"currency":1},
{"id":33,"parent":1,"currency":1},{"id":34,"parent":1,"currency":1},
{"id":35,"parent":1,"currency":1},{"id":36,"parent":1,"currency":18},
{"id":37,"parent":1,"currency":1},{"id":39,"parent":1,"currency":1},
{"id":41,"parent":6,"currency":6},{"id":42,"parent":1,"currency":1},
{"id":43,"parent":42,"currency":1},{"id":48,"parent":47,"currency":2},
{"id":47,"parent":37,"currency":2},{"id":49,"parent":48,"currency":2},
{"id":52,"parent":1,"currency":16},{"id":9,"parent":1,"currency":9},
{"id":54,"parent":1,"currency":4},{"id":55,"parent":1,"currency":1},
{"id":56,"parent":1,"currency":1},{"id":19,"parent":1,"currency":12},
{"id":21,"parent":1,"currency":1},{"id":12,"parent":1,"currency":1},
{"id":13,"parent":1,"currency":1},{"id":15,"parent":1,"currency":1},
{"id":16,"parent":1,"currency":1},{"id":10,"parent":1,"currency":8},
{"id":11,"parent":1,"currency":4},{"id":66,"parent":1,"currency":1},
{"id":69,"parent":68,"currency":1},{"id":65,"parent":1,"currency":1},
{"id":68,"parent":1,"currency":1},{"id":70,"parent":1,"currency":11}]

What I am trying to archive:

*

*The Js code should fetch all the "ids" of the children and grandchildren of the inputted "id" and form as new json key(children).

*If there is no children found then add their own "id" in children array

if my input is "id" = 59
my resulted json data:
resulteddata = [{"id":59,"currency":1,"children":[59,63,64]}

if my input is "id" = 1
my resulted json data:
resulteddata = [{"id":1,"currency":1,"children":[1,2,3,4,5,6,7,8,9 ...... 70]} // all the children and grand children

Thanks in advance

A: This is a simple function to get what you are looking for. To improve time complexity you can remove sort if that is something you do not need.
const newJson = (id) => {
  const currency = data.find(data => data.id === id).currency;

  const children = getChildren(id)
  return {id, currency, children};
}

const getChildren = (id) => {
  const children = [];
  data.forEach(el => {
    if(el.parent === id){
      children.push(el.id);
    }
  })

  if(!children.includes(id)) children.push(id);

  return children.sort((a, b) => a-b);
}

A:

data = [{"id":63,"parent":59,"currency":1},{"id":64,"parent":59,"currency":1},{"id":1,"parent":null,"currency":1},{"id":2,"parent":1,"currency":4},{"id":4,"parent":3,"currency":4},{"id":3,"parent":2,"currency":2},{"id":5,"parent":1,"currency":5},{"id":6,"parent":1,"currency":6},{"id":7,"parent":3,"currency":2},{"id":8,"parent":1,"currency":1},{"id":57,"parent":56,"currency":1},{"id":58,"parent":1,"currency":1},{"id":59,"parent":1,"currency":1},{"id":30,"parent":1,"currency":1},{"id":31,"parent":1,"currency":1},{"id":32,"parent":1,"currency":1},{"id":33,"parent":1,"currency":1},{"id":34,"parent":1,"currency":1},{"id":35,"parent":1,"currency":1},{"id":36,"parent":1,"currency":18},{"id":37,"parent":1,"currency":1},{"id":39,"parent":1,"currency":1},{"id":41,"parent":6,"currency":6},{"id":42,"parent":1,"currency":1},{"id":43,"parent":42,"currency":1},{"id":48,"parent":47,"currency":2},{"id":47,"parent":37,"currency":2},{"id":49,"parent":48,"currency":2},{"id":52,"parent":1,"currency":16},{"id":9,"parent":1,"currency":9},{"id":54,"parent":1,"currency":4},{"id":55,"parent":1,"currency":1},{"id":56,"parent":1,"currency":1},{"id":19,"parent":1,"currency":12},{"id":21,"parent":1,"currency":1},{"id":12,"parent":1,"currency":1},{"id":13,"parent":1,"currency":1},{"id":15,"parent":1,"currency":1},{"id":16,"parent":1,"currency":1},{"id":10,"parent":1,"currency":8},{"id":11,"parent":1,"currency":4},{"id":66,"parent":1,"currency":1},{"id":69,"parent":68,"currency":1},{"id":65,"parent":1,"currency":1},{"id":68,"parent":1,"currency":1},{"id":70,"parent":1,"currency":11}]

function children(id, data) {
    return data.filter(e => e.parent === id).flatMap(e => [e.id, ...children(e.id, data)])
}

function find(id, data) {
    return {
        ...data.find(e => e.id === id),
        children: children(id, data).sort((a, b) => a === b ? 0 : a > b ? 1 : -1)
    };
}

console.log(find(1, data))


text:
Q: Android 5: button underneath softnavigation bar (Showcaseview legacy) I am using the legacy ShowcaseView for Android. I notice that the Android 5 emulator puts the OK button underneath the softnavigation bar, whereas Android <= KITKAT did not have this behaviour.
See the OK button in the lower right corner here: http://imgur.com/SZtIcHr
I already tried android:fitsSystemWindows="true" but no success. Here is the relevant code in the ShowcaseView.java that I found:
    mEndButton = (Button) LayoutInflater.from(context).inflate(R.layout.showcase_button, null);

(Warning: Avoid passing null as the view root (needed to resolve layout parameters on the inflated layout's root element))
[..]
    if (!mOptions.noButton && mEndButton.getParent() == null) {
        RelativeLayout.LayoutParams lps = (LayoutParams) generateDefaultLayoutParams();
        lps.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        if (getConfigOptions().showcaseId==3)
            lps.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        else
            lps.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        int margin = ((Number) (metricScale * 12)).intValue();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) // TODO: LOLLIPOP workaround
            lps.setMargins(margin, margin, margin, margin*5);
        else
            lps.setMargins(margin, margin, margin, margin);
        lps.height = LayoutParams.WRAP_CONTENT;
        lps.width = LayoutParams.WRAP_CONTENT;
        mEndButton.setLayoutParams(lps);
        mEndButton.setText(buttonText != null ? buttonText : getResources().getString(R.string.positive));
        if (!hasCustomClickListener) mEndButton.setOnClickListener(this);
        addView(mEndButton);

I don't know how to change this or how Android 5 / material design has caused this behaviour. I would be happy for a hint! :)

A: For me works set manually the margin bottom without use the margin returned from the method to obtain int margin.
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

int margin = ((Number) (context.getResources().getDisplayMetrics().density * 12)).intValue();

layoutParams.setMargins(margin, margin, margin, 120);

Hope it works...

The problem has been fixed here...

A: I found very easy fix for this in one of pull requests
Add:
<item name="android:windowDrawsSystemBarBackgrounds">false</item>

to your style/theme in values-v21/styles.xml.
Works well for me, checked on a real device - Nexus 5.


text:
Q: XML with text tags getting prematurely un-encoded when transformed in XSLT 1.0 I'm working on transforming to HTML a multiple choice quiz stored in XML... the answers include html tags:

What is the HTML tag used to create a collection of input fields
  a) <collection>
  b) <lasso>
  c) <fieldset>
  d) No such tag exists

The problem is that while the text is encoded in the XML;
  <multiple_choice>
    <question>

What is the HTML tag used to create a collection of input fields?

    </question>
    <choice value="V1"><collection></choice>
    <choice value="V2"><lasso/>   </choice>
    <choice value="V3"><fieldset></choice>
    <choice value="V4">No such tag exists</choice>
  </multiple_choice>

...by the time it gets rendered it has been unencoded, and the question displays on the screen with a, b, and c as blank, with a fieldset around d:

I found this here on Stack, tinkered it the tiniest bit, and used it:
<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="choice/text()">

    <xsl:variable name="newtext">
        <xsl:call-template name="string-replace">
            <xsl:with-param name="string" select='.' />
            <xsl:with-param name="from" select='"<"' />
            <xsl:with-param name="to" select='"&lt;"' />
        </xsl:call-template>
    </xsl:variable>

    <xsl:value-of select="$newtext"/>
</xsl:template>

Which works SMASHINGLY if I want to change "fieldset" to "monkey" but if I want to change < , I get no change at all.
I tried it with < and with < and neither worked.
Either using this method or any other method, how do I prevent the < and > from decoding before the render?
Update 1
String replace is pretty traditional, but I should have thought to include it:
<xsl:template name="string-replace" >
    <xsl:param name="string" />
    <xsl:param name="from" />
    <xsl:param name="to" />
    <xsl:choose>
        <xsl:when test="contains($string,$from)"> <xsl:value-of select="substring-before($string,$from)"/><xsl:value-of select="$to"/> <xsl:call-template name="string-replace"> <xsl:with-param name="string" select="substring-after($string,$from)"/> <xsl:with-param name="from" select="$from"/> <xsl:with-param name="to" select="$to"/> </xsl:call-template>
        </xsl:when>
        <xsl:otherwise> <xsl:value-of select="$string"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

Update 2
Minor eureka moment... I changed the "from" string to "&lt;" and it was able to find it... which is great, I can change it to "[" easily if I wanted...
However I can't change it to <... or even &amp;amp;amp;lt; ... for whatever reason, the xsl will traverse any number of encodes and return an unencoded less than
Update 3
The actual source I'm recieving at the browser is:

What is the HTML tag used to create a collection of input fields?

<input type="radio" value="V1"/><choice value="V1"><collection></choice>

<input type="radio" value="V2"/><choice value="V2"><lasso></choice>

<input type="radio" value="V3"/><choice value="V3"><fieldset></choice>

<input type="radio" value="V4"/><choice value="V4">No such tag exists</choice>

The source I desire to receiving at the browser is:

What is the HTML tag used to create a collection of input fields?

<input type="radio" value="V1"/><choice value="V1"><collection></choice>

<input type="radio" value="V2"/><choice value="V2"><lasso></choice>

<input type="radio" value="V3"/><choice value="V3"><fieldset></choice>

<input type="radio" value="V4"/><choice value="V4">No such tag exists</choice>

A: Your question is rather confusing. If this is your XML input:
<multiple_choice>
    <question>

What is the HTML tag used to create a collection of input fields?

    </question>
    <choice value="V1"><collection></choice>
    <choice value="V2"><lasso/>   </choice>
    <choice value="V3"><fieldset></choice>
    <choice value="V4">No such tag exists</choice>
</multiple_choice>

why is it necessary to replace anything? Yoi did not post the expected resulting HTML code, but as an example, applying this stylesheet:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" version="1.0" encoding="utf-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="choice">
    <input type="radio" value="{@value}">
        <xsl:value-of select="."/>
    </input>

</xsl:template>

</xsl:stylesheet>

would produce the following result:
<multiple_choice>
   <question>

What is the HTML tag used to create a collection of input fields?

   </question>
   <input type="radio" value="V1"><collection></input>

   <input type="radio" value="V2"><lasso/>   </input>

   <input type="radio" value="V3"><fieldset></input>

   <input type="radio" value="V4">No such tag exists</input>

</multiple_choice>

rendered as:


text:
Q: Code and DB Automation Migration Tool Does someone know of a Code/DB migration tool.  I'm looking for a script-able way of automating code pushes from Dev to Production environments.   The tool should be language/db agnostic so it can work with multiple DB's and development languages.

A: You can take a look at this tools (for deployment):

*

*Capistrano + best practices

*Maven

*Heroku
In case you are talking about binaries, such concept is strongly recommended by the Continuous delivery. Since they consider it as antipattern to promote at the source-code level rather than at the binary level. Use of CI tools to trigger production deployments or you could easily write a simple interface to drive your deploy scripts. Alternatively there are numerous tools available (open source as well as enterprise) which can be used to drive your deployments. Jenkins is quite popular.


text:
Q: Trying to get the key hash of my released key for facebook I'm trying to get a key hash for facebook using my release key but the hash I get which I saved in facebook still gives me a invalid android_key parameter. I can't seem to figure out why.
I entered the right command
C:\Program Files (x86)\Java\jdk\bin>keytool -exportcert -alias my.keystore -
keystore "C:\Users\Gateway\School Work\My stuff\my.keystore" | "C:\Users
\Gateway\Downloads\openssl-0.9.8e_X64\bin\openssl.exe" sha1 -binary | "C:\Users\
Gateway\Downloads\openssl-0.9.8e_X64\bin\openssl.exe" base64
Enter keystore password:
......

and everything worked, but the returned hash still doesn't work.

A: I figured it out, the alias was wrong, so it gave me a wrong hash key.


text:
Q: Unity | AudioSource.mute не работает У меня есть функция (прикручена к нажатию кнопки), которая должна включать/отключать весь звук на сцене (ну и сохранять наличие/отсутствие звука в PlayerPrefs). Она работает абсолютно на рандом, хочет - только работает mute = true, хочет - только mute = false (это меняется при обновлении скрипта). Я никак не могу понять почему.
Функция: (MusicBtn - кнопка звука, нужна только для смены иконки)
// using System.Linq
public void OnOffMusic()
{
    if (PlayerPrefs.GetString("Music") == "off")
    {
        PlayerPrefs.SetString("Music", "on");
        MusicBtn.image.sprite = MusicOn;
    }
    else
    {
        PlayerPrefs.SetString("Music", "off");
        MusicBtn.image.sprite = MusicOff;
    }

    FindObjectsOfType<AudioSource>().All(audio => audio.mute != audio.mute);
}

Кнопка:

!!! Сразу 5 оговорок:

*

*Я могу свободно в редакторе в рантайм поменять значение mute на нужное и всё работает.

*Я пробовал писать mute = false и mute = true явно.

*Я делал отладку и FindObjectsOfType правильно находит все аудио

*Я пробовал использовать ожидание по примерам в интернете (класс Extensions)

*В Start() я проверяю существование в PlayerPrefs "Music"

Extensions:
public static IEnumerator Mute(this AudioSource audioSource)
{
    yield return new WaitForSeconds(0.01f);
    audioSource.mute = true;
}

public static IEnumerator Unmute(this AudioSource audioSource)
{
    yield return new WaitForSeconds(0.01f);
    audioSource.mute = false;
}

Start():
if (PlayerPrefs.HasKey("Music"))
    {
        if (PlayerPrefs.GetString("Music") == "off")
        {
            FindObjectsOfType<AudioSource>().All(audio => audio.mute = true);

            MusicBtn.image.sprite = MusicOn;
        }
    }
    else
    {
        PlayerPrefs.SetString("Music", "on");
    }

Что делать???

A: Вы написали расширяющий метод используя итератор, в качестве возвращаемого значения:
public static IEnumerator Mute(this AudioSource audioSource)
{
    yield return new WaitForSeconds(0.01f);
    audioSource.mute = true;
}

Поэтому при при вызове audioSource.Mute() у вас не запустится корутина, а просто вернётся итератор, который вам самостоятельно придётся "двигать", чтобы поток выполнения кода дошёл до вашего заветного
audioSource.mute = true;

Решением будет заменить audioSource.Mute() на
StartCoroutine(audioSource.Mute());

В принципе, если у вас уже всё так и написано и я несу очевидные вещи, то прошу прислать больше данных.
Так же советую проверить массив FindObjectsOfType<AudioSource>() на наличие в нём элементов.


text:
Q: How to change item in a list with sml? I have a list of tuples, I want to have a function which randomly choose two tuples in this list and then swap this two tuples.
for example, if I have a list as ((0 , 0), (1 , 0), (1 , 1), (1 , 2) ,(2 , 2), (0 , 2)), then, randomly choose two tuples. if (0,0) and (1,0) are chosen, then the return result of this function will be ((1 , 0), (0 , 0), (1 , 1), (1 , 2) ,(2 , 2), (0 , 2)).
I am new to SML, I am struggling in it. there is a psudo-code, I suppose it is not right, anyone can help me with the right one? :
  fun permutation(lst:(int*int) list)=
  let
    val nextInt = Random.randRange (1,List.length(lst))
    val r = Random.rand (1,1)
    val x1 = nextInt r
    val x2 = nextInt r
    val temp = sub(lst,r1)
    update(lst,r1,sub(lst,r2))
    update(lst,r2,temp)
  in
    lst
  end

A: Something simple you can do is make a helper function that takes two indices and a list, and returns the two tuples at those indices.  Something like
fun get_two (i1, i2, xs) =
  let
    fun aux (_, _, [], _, val1, val2) = (val1, val2)
      | aux (i1, i2, x::xs, current_index, val1, val2) =
          if i1 = current_index
          then aux (i1, i2, xs, current_index + 1, SOME x, val2)
          else if i2 = current_index
          then aux (i1, i2, xs, current_index + 1, val1, SOME x)
          else aux (i1, i2, xs, current_index + 1, val1, val2)
  in
    aux (i1, i2, xs, 0, NONE, NONE)
  end

Then write another function that takes in a list, uses this get_two helper function to find two values and their positions in the list, and produces a new list that is the same as the input list, except with these two values switched.


text:
Q: Treatment of categorical variables in rpart I wonder how rpart treats categorical variables. There are several references suggesting that for unordered factors it looks through all combinations. Actually, even the vignette at the end section 6.2 states

(F)or a categorical predictor with m levels, all 2^m−1 different possible
  splits are tested.

However, given my experience with the code, I find it difficult to believe. The vignette shows a supporting evidence that running
rpart(Reliability ~ ., data=car90)

takes a really long, long time. However, in my case, it runs in seconds. Despite having an unordered factor variable with 30 levels.
To demonstrate the issue further, I have created several variables with 52 levels, meaning that 2^51 - 1 ~ 2.2 10^15 splits would need to be checked if all possibilities were explored. This code runs in about a minute, IMHO proving that all combinations are not checked.
NROW = 50000
NVAR = 20

rand_letters = data.frame(replicate(NVAR, as.factor(c(
  letters[sample.int(26, floor(NROW/2), replace = TRUE)],
  LETTERS[sample.int(26, ceiling(NROW/2), replace = TRUE)]))))
rand_letters$target = rbinom(n = NROW, size = 1, prob = 0.1)

system.time({
  tree_letter = rpart(target ~., data = rand_letters, cp = 0.0003)
})
tree_letter

What combinations of categorical variables are ACTUALLY checked in rpart?

A: I know it is an old question but I found this link that might answer some of it.
Bottom line is that rpart seems to be applying a simple algorithm:

*

*First, sort the conditional means, p_i = E(Y|X = x_i)

*Then compute Gini indices based on groups obtained from that ordering.

*Pick the two groups giving the maximum of these Gini indices.

So it should not be nearly as computationally expensive.
However, I personally have a case where I have a single categorical variable, whose categories are US states, and rpart overtimes when trying to use it to produce a classification tree. Creating dummy variables and running rpart with the 51 variables (1 for each state) works fine.