text:
Q: creating file paths from 2d lists kdb q Say I have a list of files
`(`fileA`fileB`fileC;`fileX`fileY)

And a list of paths
`:a/b`:c/d

how can I concatenate these so produce
`:a/b/fileA`:a/b/fileB`:a/b/fileC`:c/d/fileX`:c/d/fileX

I would usually use
` sv'paths,'filelist

But in this case since `filelist is 2d and the lengths do not match it produces
`:a/b/fileA/fileB/fileC`:c/d/fileX/fileY

Thankyou

A: You can use a combination of each-both and each-right :
q)raze{` sv/:(x,/:y)}'[(`:a/b`:c/d ) ;(`fileA`fileB`fileC;`fileX`fileY)]
`:a/b/fileA`:a/b/fileB`:a/b/fileC`:c/d/fileX`:c/d/fileY

each-right is appending the files to the dir :
q){` sv/:(x,/:y)}[`:a/b;`fileA`fileB`fileC]
`:a/b/fileA`:a/b/fileB`:a/b/fileC

A: Could also use the built-in .Q.dd
q).Q.dd''[`:a/b`:c/d;(`fileA`fileB`fileC;`fileX`fileY)]
`:a/b/fileA`:a/b/fileB`:a/b/fileC
`:c/d/fileX`:c/d/fileY


text:
Q: How to run Websphere Liberty in debug mode inside docker container? I added this to my Dockerfile and the changes reflect on "docker inspect"
CMD ["/opt/ibm/docker/docker-server", "debug", "defaultServer"]
The server logs indicate that the server has stopped and the ports (http only, not 7777) are unbound), but the java process is still running, thus not letting the container die.
I can go inside the container and start the server with this command and everything works fine
/opt/ibm/docker/docker-server run defaultServer
What am I doing wrong?
Server logs :

A CWWKE0001I: The server defaultServer has been launched.
I CWWKE0002I: The kernel started after 2.253 seconds
I CWWKF0007I: Feature update started.
I CWWKF0008I: Feature update completed in
0.250 seconds.
A CWWKF0036I: The server defaultServer has finished gathering a list of required features.
A CWWKE0036I: The server defaultServer stopped after 2.804 seconds.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java - Wait for Runnable to finish In my app, I have the following code running on a background thread:
MyRunnable myRunnable = new MyRunnable();
runOnUiThread(myRunnable);

synchronized (myRunnable) {
    myRunnable.wait();
}

//rest of my code

And MyRunnable looks like this:
public class MyRunnable implements Runnable {
    public void run() {

        //do some tasks

        synchronized (this) {
            this.notify();
        }
    }
}

I want the background thread to continue after myRunnable has finished executing. I've been told that the above code should take care of that, but there are two things I don't understand:

*

*If the background thread acquires myRunnable's lock, then shouldn't myRunnable block before it's able to call notify() ?

*How do I know that notify() isn't called before wait() ?

A: You could also use JDK's standard RunnableFuture like this:
RunnableFuture<Void> task = new FutureTask<>(runnable, null);
runOnUiThread(task);
try {
    task.get(); // this will block until Runnable completes
} catch (InterruptedException | ExecutionException e) {
    // handle exception
}

A: *

*myRunnable.wait() will release the lock of myRunnable and wait notify

*we always add a check before wait.
//synchronized wait block
while(myRunnable.needWait){
    myRunnable.wait();
}

//synchronized notify block
this.needWait = false;
myRunnable.notify();

A: *

*The lock is released when the wait starts

*That's a possibility, you can avoid it by putting the runOnUiThread within the synchronized block too (so that the runnable can't acquire the lock until the other thread is already waiting)

A: Create an Object called lock. Then after runOnUiThread(myRunnable);, you can call lock.wait(). And when your myRunnable is finish it's job, call lock.notify(). But you must declare MyRunnable as inner class, so they can share the lock object.


text:
Q: File uploading issue in Yii2 I am developing an application in Yii2 framework.
I am uploading an image using code below and which has worked perfect till now. But now I got an error instant. I don't understand what has happened.
Below is the code of controller where upload file and save take place:
// Upload photo of subcategories...
$model->file = UploadedFile::getInstance($model, 'file');
if($model->file) {
    $imageName = rand(1000,100000);
    $model->file->saveAs('uploads/subcategories/'.$imageName.'.'.$model->file->extension);
    $model->sub_category_photo = 'uploads/subcategories/'.$imageName.'.'.$model->file->extension;
}
$model->save();

I got below error:

PHP Warning – yii\base\ErrorException
      finfo_file(C:\xampp\tmp\php9A7B.tmp): failed to open stream: No such file or directory

I also un-comment extension = fileinfo.dll in php.ini file and restart server.

A: I got solutions of this questions.
Call $model->save(); in controller
before
$model->file->saveAs();

Means in above code of my questions changed to below
// Upload photo of subcategories...
$model->file = UploadedFile::getInstance($model, 'file');
if($model->file) {
    $imageName = rand(1000,100000);
    $model->sub_category_photo = 'uploads/subcategories/'.$imageName.'.'.$model->file->extension;
    $model->save();
    $model->file->saveAs('uploads/subcategories/'.$imageName.'.'.$model->file->extension);
} else {
    $model->save();
}

Hope this help someone as it helped me and I found answer from here

A: In views > _form.php
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'image')->fileInput() ?>
<?php ActiveForm::end(); ?>

In controller:
use yii\web\UploadedFile;

In actionCreate():
if ($model->load(Yii::$app->request->post())){
    $model->image = UploadedFile::getInstance($model, 'image');
    if($model->validate() && $model->save()) {
        $model->image->saveAs(dirname(__FILE__).'/../../uploads/'. $model->image);
        $model->save();
    }
}

In actionUpdate():
if ($model->load(Yii::$app->request->post()) ) {
    $model->image = UploadedFile::getInstance($model, 'image');
    if($model->validate() && $model->save()){
        $model->image->saveAs(dirname(__FILE__).'/../../uploads/'.$model->image);
        $model->save();
    }
}

In actionDelete($id):
unlink($_SERVER["DOCUMENT_ROOT"]."/../../uploads/".$model->image);

A: //Model Rule (note skip on empty):
['file', 'file', 'extensions' => 'jpg, jpeg, gif, png', 'mimeTypes' => 'image/jpeg, image/gif, image/png', 'skipOnEmpty' => true],

//save file
$model->file->saveAs();

//set it to null
$model->file = null;

//now it will save ok
$model->save();

I think what happens is once the file is saved, it's cleared out of memory so when the model tries to save it throws an error.


text:
Q: Read UTF-8 encoded text content inside table cell in MS-word file using Apache POI I'm trying to read a table and exact data in a Microsoft Word document (docx file) using apache poi. The file contain UTF-8 encoded characters (Sinhala language). I'm using following code block.
FileInputStream fis = new FileInputStream("path\\to\\file.docx");
XWPFDocument doc = new XWPFDocument(fis);
Iterator<IBodyElement> iter = doc.getBodyElementsIterator();
while (iter.hasNext()) {
    IBodyElement elem = iter.next();
    if (elem instanceof XWPFTable) {
        List<XWPFTableRow> rows = ((XWPFTable) elem).getRows();
        for(XWPFTableRow row :rows){
            List<XWPFTableCell> cells = row.getTableCells();
            for(XWPFTableCell cell : cells){
                PrintStream out = new PrintStream(System.out, true, "UTF-8");
                out.println(cell.getText());
            }
        }
    }
}

But I'm not getting correct UTF-8 characters in the output console.

I have already refer several solutions including following.
How to parse UTF-8 characters in Excel files using POI | I'm trying to read a table in a Word file. So my Cell object doesn't have getStringCellValue() method.
http://www.herongyang.com/Java-Tools/native2ascii-Set-UTF-8-Encoding-in-PrintStream.html | I have already tried this solution and It's not working.
does anyone know how to read UTF-8 encoded characters in a word file using apache poi?

A: I found a solution with setting font for a cell (as a peragraph).
code :
private static final String FILE_NAME = "/tmp/Diskade.docx";

    public static void main(String[] args) throws IOException {

        FileInputStream fis = new FileInputStream(FILE_NAME);
        XWPFDocument doc = new XWPFDocument(fis);

        Iterator<IBodyElement> iter = doc.getBodyElementsIterator();
        while (iter.hasNext()) {
            IBodyElement elem = iter.next();
            if (elem instanceof XWPFTable) {

                List<XWPFTableRow> rows = ((XWPFTable) elem).getRows();
                for(XWPFTableRow row :rows){
                    List<XWPFTableCell> cells = row.getTableCells();

                    for(XWPFTableCell cell : cells){

                        String celltext = cell.getText();
                        XWPFParagraph paragraph = cell.addParagraph();
                        setRun(paragraph.createRun() , "Arial" , 10, "2b5079" , celltext , false, false);
                        System.out.print(cell.getParagraphs().get(0).getParagraphText() + " - ");

                    }
                    System.out.println();
                }
            }
        }
    }

    private static void setRun (XWPFRun run , String fontFamily , int fontSize , String colorRGB , String text , boolean bold , boolean addBreak) {
        run.setFontFamily(fontFamily);
        run.setFontSize(fontSize);
        run.setColor(colorRGB);
        run.setText(text);
        run.setBold(bold);
        if (addBreak) run.addBreak();
    }

EDIT :
Later I noted that, actually adding paragraph is enough. You don't need setRun method or invokin it as setRun(paragraph.createRun() , "Arial" , 10, "2b5079" , celltext , false, false);.

Will see is there anything can be done with encoding. (because, for me once the font is loaded it was working fine without paragraph also)


text:
Q: System of 3 Congruences Trying to solve this system of congruences:
$$n \equiv 4 \quad \text{(mod 19)}$$
$$n \equiv 3 \quad \text{(mod 10)}$$
$$n \equiv 6 \quad \text{(mod 11)}$$
how do I solve this?

A: $$
\begin{eqnarray}
10\cdot11&\equiv&0&\mod10\;,\\
10\cdot11&\equiv&0&\mod11\;,\\
10\cdot11&\equiv&15&\mod19\;.
\end{eqnarray}
$$
Now you just need to solve $15x\equiv4\mod19$, and then $10\cdot11\cdot x$ solves the first congruence without disturbing the other two. Then you can do the same thing for the other two.

A: It's a simple application of Easy CRT (below). With practice, this can be calculated mentally.
$$\!\!\!\!\!\!\!\!\!\rm \begin{eqnarray}\rm n&\equiv&\rm 6\ (mod\ 11) \\
\rm n&\equiv&\rm 4\ (mod\ 19)\end{eqnarray}\!\!\! \iff\!\!  n \equiv 4 + 19\: \bigg[\!\!\frac{6\!-\!4}{19} mod\ 11\bigg]\! \equiv 61\  (mod\ 209)\ \ by\  \frac{2}{19}\equiv \frac{-9}{-3}\equiv 3 \ (mod\ 11)$$

$$\rm\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \begin{eqnarray}\rm n&\equiv&\rm\ 3\ \ (mod\ 10) \\
\rm n&\equiv&\rm 61\: (mod\ 209)\end{eqnarray}\!\!\! \iff\!\!  n \equiv 61 + 209 \bigg[\!\!\frac{3\!-\!61}{209} mod\ 10\bigg]\! \equiv -357\  (mod\ 2090)\ \ by\  \frac{2}{-1}\equiv -2\: (mod\ 10)$$
THEOREM (Easy CRT) $\rm\ \ $ If $\rm\ m,\:n\:$ are coprime integers then $\rm\ n^{-1}\ $ exists $\rm\ (mod\ m)\ \ $ and
$\rm\displaystyle\quad \begin{eqnarray}\rm x&\equiv&\rm\ a\ (mod\ m) \\
\rm x&\equiv&\rm\ b\ (mod\ n)\end{eqnarray}\!\!\! \iff\!  x\: \equiv\: b + n\ \bigg[\frac{a\!-\!b}{n}\ mod\ m\:\bigg]\ \ (mod\ m\:\!n)$
Proof $\rm\ (\Leftarrow)\quad mod\:\ n\!:\:\ x\:\equiv\: b + n\ (\cdots)\equiv b\:,\ $ and $\rm\ mod\ m\!:\ x\equiv b + (a-b)\ n/n\: \equiv\: a\:.$
$\rm\ (\Rightarrow)\ \ $ The solution is unique $\rm\ (mod\ m\:\!n)\ $ since if $\rm\ x',x\ $ are solutions then $\rm\ x'\equiv x\ $ mod $\rm\:m,n\:$ therefore $\rm\ m,n\ |\ x'-x\ \Rightarrow\ m\:\!n\ |\ x'-x\ \ $ since $\rm\ \:m,n\:$ coprime $\rm\:\Rightarrow\ lcm(m,n) = m\:\!n\ \ \ $ QED


text:
Q: Run PHP command line, needs socket_create I have a PHP script that needs to run from command line. One of the function it calls is socket_create.
In php.ini, I have included the following in order to get that function working (see the comment on http://www.php.net/manual/en/sockets.installation.php):
extension=php_sockets.dll

How do I run the script from command line such that it doesn't complain that socket_create is an unknown function? Does PHP CLI actually respect what's in php.ini? I thought it was supposed to, but I do get errors when running it via CLI and no errors when running it via the browser.
UPDATE: by the way, I'm testing this out: https://github.com/nicokaiser/php-websocket. I assume that the server needs to be executed via command line.

A: A different php.ini file may apply when running php on the CLI rather than as a web server module. You appear to be using Windows, so I'm not sure where this file may be, but it could provide a clue;  look for several php.ini files in your disk and see if one of them applies to CLI invocations.


text:
Q: Setting Line Break in High chart legend I am making a Line in highchart where there are between one and two objects and each object has multiple lines associated with it.  My issue is I want my legend to look like this:

Where color represents the object and opacity represents the actual line on the graph.  I couldn't figure out how to get the object labels "Thing one" and "Thing two" in the right place, but I hacked it together by putting the object name in the first series title and got a legend that looks like this:

This isn't the best solution, but I would be ok with it except for the fact that when the chart is resized, the line breaks in arbitrary places:

making it confusing to read.  Is there a way to set the line break so that the different objects are always on different lines if the chart is resized:

Also open to suggestions on better ways to represent this legend.

A: I was able to achieve this by setting the legend itemWidth and width property:
  legend: {
    enabled: true,
    itemWidth: 400,
    width:400,
    align: 'center'
  }


text:
Q: Find the smallest number that has a residue of 3 when divided by 5, and a residue of 4 when divided by 6 or 7 (without using modular arithmetic). I am not too sure how to tackle this without trial and error. I know I can write $n=5a+3=6b+4=7c+4$, however, where do I go next?

A: $6b + 4 \ne 7b +4$.  then number so that $n = 6*(something) + 4$ is probably a different number then then number so that $n = 7*(something) + 4$.
So there are $a,b,c$ so that
$n = 5a + 3 = 6b + 4=7c + 4$
Also you ask for the smallest.  There are infinite positive and infinite negative answers so I'm assuming $n$ is meant to be natural?
$6b = 7c$ so $6|c$ and $7|b$ and there is a $k$ so that $b=7k$ and $6b = 42k = 7c$ and $c = 6k$.
So $n = 5a + 3 = 42k + 4$
So $5a = 42k + 1$.   And $42k + 1 = 40k + 2k +1$ so $5|2k+1$.  Well.... I suppose it is trial and error but if we assume $k$ is non-negative the smallest way to do that is if $2k + 1 =5$ or $k = 2$.
$5a = 42*2 + 1 = 85$ and $a = 17$.
So $n = 5*17 + 3 = 42*2 + 4 = 88$
And indeed $88 \equiv 3 \pmod 5$ and $4\pmod 6$ and $4 \pmod 7$.
And it is the least non-negative as $k=2$ was the least non-negative value.
(Note:  And $88 + 5*6*7m = 88+210m$ including $88-210=-122$ will do.)

A: If $n$ has a remainder of $4$ when divided by $6$ and $7$, then $n-4$ has a reminder of $0$, i.e. $n-4$ is a multiple of $6$ and $7$. The lowest common multiple of $6$ and $7$ is $42$, so $n-4$ is a multiple of $42$.
The smallest positive value of $n$ which leaves a remainder of $4$ when divided by $6$ or $7$ is therefore $0\times 42+4=4$. But this doesn't have the right remainder when divided by $5$. The next is $1\times 42+4=46$, which also doesn't work. The next is $2\times 42 +4=88$. This does give remainder $3$ when divided by $5$, so it is the answer.

A: Alternatively, using the division theorem
For $5*6*7=210$
So for $n$ there is unique $q, r;0\le r < 210$ so that $n = 210q + r$.
But $r$ itself can by divided by $5*6=30$; $5*7=35$ and $6*7=42$ so
$r = 30a + r_1; 0\le r_1< 30$ and as $r <210$, $0\le a < 7$
$r = 35b + r_2; 0 \le r_2< 35$ and $0\le b < 6$
And $r= 42c + r_3; 0\le r_3 < 42$ and $0\le c < 5$.
And so we have three equations for $n$:
$n = 210q +30a + r_1$
$n = 210q +35b + r_2$
$n = 210q +42c + r_3$
Furthermore we can divide $r_1,r_2,r_3$ by $5,6,7$ to get the following six equations.
$n = 210q +30a + 6d + 4$
$n = 210q +30a + 5e + 3$
$n = 210q +35b + 7f + 4$
$n = 210q +35b + 5g + 3$
$n = 210q +42c + 7h + 4$
$n = 210q +42c + 6i + 4$
With the restrictions: $0\le a < 7;0\le b < 6;0\le c < 5;0\le d< 5;0\le e< 6; 0\le f< 5; 0\le g < 7;0\le h< 6;0\le i< 7$.
So we have
$6d+1 = 5e$
$7f+1 = 5g$
$7h = 6i$
But given the restictions these each have only one solution $d=4;e=5; f=2;g=3;h=6;i=7$.
so we have
$30a +28 = 35b + 18 = 42c + 4$.
But $30a + 28 = 35b +18$ means $30a +10=35b$ or $6a+2=7b$
And $35b + 18 = 42 c + 4$ means $35b+14 = 42c$ or $5b+2=6c$.
And $30a + 28 = 42c+4$ means $30a+24=42c$ or $5a+4=7c$.
But given the restrictions these each have only one solution: $a=2;b=2$ and $b=2; c=2$ and $a=2;c=2$.
So $n = 210q + 60 + 28 = 210q + 70 + 18 = 210q + 84 + 4 = 210q + 88$.


text:
Q: Concern Obtaining A Solution To A First Order ODE I'am trying to solve $$\frac{\mathrm{dy} }{\mathrm{d} x}= e^{2x+3y}$$
I use the law of exponent to obtain $$\frac{\mathrm{dy} }{\mathrm{d} x}= e^{2x}e^{3y}$$
I send the $dx$ to the other side and integrate both sides after seperating the variables.$$\int \frac{dy}{e^{3y}} = \int(e^{2x})dx$$
I know the right hand side is equal to $\frac{e^{2x}}{2} + c$.How about the left hand side?

A: Same idea as on the "$x$" side. You are integrating $e^{-3y}dy$, and get $\frac{1}{-3}e^{-3y}$. So we end up with
$$\frac{1}{-3}e^{-3y}=\frac{1}{2}e^{2x}+C.$$
This can be simplified in various ways. In this case, you can get an explicit formula for $y$ in terms of $x$.

A: That is $$\int e^{-3y}dy$$ which is equal to $\frac{1}{-3}e^{-3y}$. Note that $a^b=\frac{1}{a^{-b}}$


text:
Q: Load testing authenticated users I want to do load testing with Visual Studio but i don't get the idea how to setup load testing with authenticated users.
Imagine my scenario. This should be a quite common problem:

*

*a website where you need to authenticate with username and password.
Perform a action that is only allowed for a authenticated user

What i have done so far:

*

*i have already written UI tests with Selenium:
(this is working quite nice)
UPDATE: My Selenium test class: I want to use this code with the load test.This is a data-driven unit test project  as you can see on method TestCase4529
[TestClass]
public class Scenario2
{
    private IWebDriver driver;
    public TestContext TestContext { get; set; }

    [TestInitialize]
    public void SetupTest()
    {
        this.driver = new ChromeDriver();
        this.driver.Manage().Timeouts().ImplicitWait = new TimeSpan(0, 0, 30);
    }

    [TestCleanup]
    public void TeardownTest()
    {
        this.driver.Quit();
    }

    [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\4529.csv", "4529#csv", DataAccessMethod.Sequential), DeploymentItem("4529.csv"), TestMethod]
    public void TestCase4529()
    {
        var userName = TestContext.DataRow["UserName"].ToString();
        var password = TestContext.DataRow["Password"].ToString();

        // UI Test logic
        var loginPage = new LoginPage(this.driver);
        loginPage.FillForm(userName, password);
        loginPage.LoginButton.Click();

        // Some assertions
    }
}

Now when i setup the load test in Visual Studio i am asked how many users should do something:

I am not getting what this number means:

*

*Does it only mean number of simultaneous threads?

*How can i get a connection between a user (defined in the load test) an a authenticated user in my Selenium test?

What i would like to achieve:

*

*Each user defined in the load test should be a authenthenticated user in my selenium UI test.

May somebody give me an idea how to do that or what i am thinking wrong...

A: A Visual Studio load test provides a way of running other tests repeatedly and simultaneously. It works best with Web Performance Tests but it can run unit tests and Coded UI tests.
When a "constant load" of (say) 25 users is selected then 25 test cases chosen from the "test mix" of the load test will be started. Whenever one of those test cases finishes another test will be chosen and started so that there are always 25 test cases being executed. That will continue until the end of the test run, which is normally either a test duration or a number of iterations. (Here "iterations" means number of test cases executed.)
Assuming "Web Performance Tests" are being used then those tests are responsible for providing the user authentication. A common way of doing that is to data drive the test and provide user names and corresponding passwords in that data. See here for more detail.
You question asks whether the "constant load" of 25 users means 25 threads. It means that 25 tests cases will be running at the same time, but it does not use Windows threads.
In response to comments:
I think you are misusing or misunderstanding the terminology of Microsoft's test environments. You may be able to have a Selenium test within the test mix of a load test although I have never done it. The user count and the data source are independent items. The user count is about how many simulated users are running tests at the same time. The data source is used by the test cases. If you have 25 users and one data driven test then that test should be started 25 times and those 25 executions should use the first 25 lines of the data source (assuming a Sequential or Unique access method).

A: To provide user and password you have to check for QueryString Parameters in your recorded webtest and pass data through Data Source see the following images for more detail:

Then pass the recorded webtest into load test as follow:


text:
Q: Use of the custom rules with parameter (vue js - vee validate) I looked the documentation of Vee validate before asking for help here, I have a problem with the use of custom rules with parameter. In fact, the configuration of my rules is fine but I don't find the correct syntax to make it work properly in the component with a parameter.
What should I write in the v-validate features of the concerned field?
Thanks for your help,
Here is my rule:
import { Validator } from 'vee-validate';

Validator.extend('isBigger', (value, [otherValue]) => {
    return value <= otherValue;
}, {
    hasTarget: true
});

I tried this but not working:
<b-form-input ref="bottom"
    name="sampling depth bottom"
    v-validate="{regex: /^-?\d+[.,]?\d{0,10}$/}"
    placeholder="(in cm)"
    v-model="inputSamplingDepthBot"
    ></b-form-input>

<b-form-input
    name="sampling depth top"
    v-validate="{isBigger:'bottom', regex: /^-?\d+[.,]?\d{0,10}$/}"
    placeholder="(in cm)"
    v-model="inputSamplingDepthTop"
    ></b-form-input>

A: No need to wrap the whole thing in curly braces. Try this out:
<b-form-input
    name="sampling depth top"
    v-validate="'isBigger:bottom, regex: /^-?\d+[.,]?\d{0,10}$/'"
    placeholder="(in cm)"
    v-model="inputSamplingDepthTop"
    ></b-form-input>

rule name and parameters should all be passed as a string.
if for some reason you need to pass a variable for the parameter, you can use backticks and interpolate the variables, like this:
<b-form-input
    name="sampling depth top"
    v-validate="`isBigger:${someVariable}, regex: /^-?\d+[.,]?\d{0,10}$/`"
    placeholder="(in cm)"
    v-model="inputSamplingDepthTop"
    ></b-form-input>


text:
Q: Rails4 polymorphic how to use in html page? I used Rails-4.2.8.
Now I had question article comments models, on question has many comments, or one article has many comments, but now how could I submit the comment in question show.html.erb?
Mymodels as follows:
#comment.rb
class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

#question.rb
class Question < ActiveRecord::Base
   has_many :comments, :as => :commentable, :dependent => :destroy
 end

My question show.html.erb as follows:
<% @comment = @question.comments.build  %>
<%= form_for([@comment.commentable,@comment]) do |f| %>
    <%= f.text_area :content,class: "editormd-markdown-textarea" %>
    <%= f.submit "submit", class: "btn btn-primary pull-right" %>
<% end %>

My questions_controller.rb as follows:
def create
   Question.find(params[:question_id]).comments.build
end

My roots.rb as follows
resources :questions do
    resources :comments
  end

But I got this error, could someone give me some suggests that where I had the wrong codes? Thanks so much!
Routing Error
uninitialized constant CommentsController

And also:
Request
Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"/MIczvX+UVpMnKx9K2/7cTmoiM1oDcYZO63RE10mDAlnRMJRukFq/2t24yBqfDIg8D1/Midk3FU1IOaTW4twuA==",
 "comment"=>{"content"=>"adfadfadfadfadfdafadf"},
 "comment-editormd-html-code"=>"
adfadfadfadfadfdafadf
\r\n",
 "commit"=>"Submit",
 "question_id"=>"1"}

A: try following fix
<%= form_for [@comment.commentable,@comment], url: "#{polymorphic_path(commentable)}/comments" do |f| %>


text:
Q: Main window keeps activating after opening a new window in WPF I have a simple Navigator class that keeps instances of my windows and opens them/closes them. When I open a new window from the main window, I need the new window to be on top. Problem is that neither .Focus() nor .Activate() do work. The new window just flashes and then the main window is activated again, even though I never explicitly activate it. The method that I use to open a new window follows:
public Task OpenDetailAsync(int? deploymentScriptID = null)
{
    if (_detailWindow == null)
    {
        var source = new TaskCompletionSource<bool>();
        _detailWindow = new DetailWindow { DataContext = _detailViewModelFactory.Create(deploymentScriptID, this) };
        _detailWindow.Closed += (sender, e) => source.TrySetResult(true);
        _detailWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
        _detailWindow.Show();
        _detailWindow.Activate();
        _detailWindow.Focus();
        return source.Task;
    }
    else
    {
        ShowMessageBox("foreign language you wouldn't understand", "lol");
        return null;
    }
}

So when I inject an instance of my Navigator class to the main window's DataContext and then use it to open a detail window, the detail window is activated, flashes and then the main window is activated again, which I can clearly see when I use the following delegate in the main window:
public ListWindow()
{
    InitializeComponent();
    Activated += ListWindow_Activated;
}

private void ListWindow_Activated(object sender, EventArgs e)
{
    Console.WriteLine(DateTime.Now);
}

Any ideas how to solve this?

A: So I've found out that the problem was completely elsewhere. The detail window is opened from ListView by double clicking on the ListViewItem. I handled the event in main window's UserControl XAML file like this:
<i:Interaction.Triggers>
    <i:EventTrigger EventName="PreviewMouseDoubleClick">
        <i:InvokeCommandAction Command="{Binding OpenDetail}" CommandParameter="{Binding ElementName=ListViewScripts,Path=SelectedItem.DeploymentScriptID}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

It turned out all I needed to do is replace PreviewMouseDoubleClick with MouseDoubleClick.


text:
Q: Subtraction of fractional exponents with different bases I wanna know if $$\left[(x^2+h)^3-(x+h)\right]^{1/2}-[x^3-x]^{1/2}=\left[(x+h)^3-(x+h)-x^3+x\right]^{1/2}.$$

A: Does $a^2 - b^2 = (a-b)^2\;$?
No,  Because $$(a-b)^2 = a^2 -2ab +b^2 \neq a^2 - b^2$$
Alternatively $$a^{1/2} - b^{1/2} = \sqrt a -\sqrt b \neq \sqrt{a-b}$$
Simply take $a = 4, b = 9$.  Then we have $2 - 3 = -1$. Whereas $\sqrt{2-3}$ is undefined in the reals, and which will never be equal to a negative real number.

A: after squaring two times and factorizing we obtain
$$x \left( x-1 \right)  \left( {x}^{10}+{x}^{9}+6\,{x}^{8}h+{x}^{8}+6\,{
x}^{7}h+15\,{x}^{6}{h}^{2}-{x}^{7}+9\,{x}^{5}{h}^{2}+18\,{x}^{4}{h}^{3
}-{x}^{6}-6\,{x}^{5}h-9\,{x}^{4}{h}^{2}+9\,{x}^{2}{h}^{4}-{x}^{5}-6\,{
x}^{4}h-15\,{x}^{3}{h}^{2}-18\,{x}^{2}{h}^{3}-9\,x{h}^{4}-12\,{x}^{3}h
-12\,{x}^{2}{h}^{2}-4\,x{h}^{3}-12\,{x}^{2}h-12\,x{h}^{2}-4\,{h}^{3}+4
\,xh+4\,h \right)
=0$$
and now?


text:
Q: CSS/XHTML Menu - Working in all browsers - IE6 Help i found this menu that's exactly what i want.  It works in all modern browsers and IE 7/8.  I need to find a fix for it to work in IE6.  Any help would be greatly appreciated.
http://lab.returnwt.net/htmlcss/tabmenu/

A: The problem with this menu in IE6 is that it's using selectors like this:
header ul#menu li:hover ul

IE6 only supports :hover on a elements.
Fortunately, there's a really easy fix to make this menu work in IE6.
It's called Whatever:hover

*

*Download the (minified) csshover3.htc file.

*Add this CSS:
body {
    behavior: url("csshover3.htc");
}

Here's a self-contained file that I tested to work with IE6, provided that the csshover3.htc file is in the same folder:
<!DOCTYPE html>

<title>Simple Tabbed Navigation - CSS3</title>

<meta charset="utf-8" />

Home

                Community

Recent Activity

Member Forum

Member List

Member Groups

Pet Help

Pets for Sale

Pet Services


text:
Q: Android Java Webview app: how to open facebook, twitter, linkedin and whatsapp app via my webview app I have a webview app of my website. On my website i have a plugin installed of facebook, twitter, LinkedIn and whatsapp. But if I want to click on facebook or twitter or linkedin or whatsapp via my webview app on one of the pages because i want to share that page/blog, the apps on my mobile will not open.  How can i make sure my webview app will do that.
see the code below
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    WebView webView;
    ProgressBar progressBar;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.webview);
        progressBar = findViewById(R.id.progress);

        webView.setWebChromeClient( new MyWebChromeClient());
        webView.setWebViewClient( new webClient());
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("https://www.hindnc.nl/");
    }

    public class  MyWebChromeClient extends WebChromeClient {
        public void onProgressChanged(WebView view, int newProgress) {
            progressBar.setVisibility(View.VISIBLE);
            progressBar.setProgress(newProgress);
        }
    }

    public class webClient extends WebViewClient {
        public boolean  shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressBar.setVisibility(View.GONE);
        }
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
            progressBar.setVisibility(View.GONE);
        } else  {
            super.onBackPressed();
        }
    }
}


text:
Q: Why this Selection sort code in Cpp, not giving required Output #include<iostream>

using namespace std;
int min_arr(int arr[],int size);
void swap(int *,int *);
int main()
{
    int arr[10]={31,2,55,3,77,12,89,98,43,34},loc;
    int* arr1;
    arr1 = &arr[0];
    for(int i=0;i<10;i++)
    {
        for( int j=i;j<9;j++)
        {
            loc = min_arr(arr1,(10-i));
            swap(&arr[loc],&arr[i]);
            arr1++;
        }
    }

    for(int i =0; i<10;i++)
        cout<<arr[i]<<endl;

    return 0;
}

int min_arr(int arr[],int size)
{
    int k=0;
    int temp=arr[0];
    for(int i=1;i<size;i++)
    {
        if(arr[i]<temp)
        {
            temp=arr[i];
            k=i;
        }
    }

    return k;
}

void swap(int *a, int *b)
{
   int temp;
   temp=*a;
   *a=*b;
   *b=temp;
}

Why this Selection sort code in Cpp, not giving required Output? Kindly find the flaw! I have taken two functions to find min of the sub arrays as we procede. And as i find the min, i return its index and swap the first position of the sub array and minimum valued element!

A: After rearranging the code and adding some debug lines, it's pretty easy to find out what's wrong:

*

*Firstly, the second loop (j loop) is completely pointless

*Secondly loc variable is not 0-based but i-based (as you searched over arr1, which is incremented by the loop), so arr[loc] should be arr[loc+i]

Corrected, smartly indented (that's important to make tour code easily readable) code:
#include<iostream>

#define ARRAY_SIZE 10
using namespace std;
int min_arr(int arr[],int size);
void swap(int *,int *);
int main()
{
    int arr[ARRAY_SIZE]={31,2,55,3,77,12,89,98,43,34},loc;
    int* arr1;
    arr1 = &arr[0];
    for( int i = 0; i < ARRAY_SIZE; i++ )
    {
        //for( int j = i; j<ARRAY_SIZE-1; j++ )
        {
            loc = min_arr(arr1,(ARRAY_SIZE-i));
            // for debug:
            //std::cout << "min found at " << loc << std::endl;
            swap(&arr[loc+i],&arr[i]);

            // for debug:
            //for( int i =0; i<ARRAY_SIZE; i++ )
            //  cout << arr[i] << " ";
            //cout << std::endl;

            arr1++;
        }
    }

    for( int i =0; i<ARRAY_SIZE; i++ )
        cout<<arr[i]<<endl;

    return 0;
}

int min_arr( int arr[], int size )
{
    int k=0;
    int temp=arr[0];
    for( int i=1; i<size; i++ )
    {
        if( arr[i] < temp )
        {
            temp=arr[i];
            k=i;
        }
    }
    return k;
}

void swap(int *a, int *b)
{
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
}

It will output:
2
3
12
31
34
43
55
77
89
98

A: In your version you just go with pointers beyond the area mapped for the array.
First of all, call of the function min_arr. It requires array, not pointer:
loc=min_arr(arr,(10-i));

Second, the function itself. You always start from the beginning of the array, that's why already sorted elements go resorted.
int min_arr(int arr[],int size)
{
int k=10-size;
int temp=arr[k];
for(int i=k+1;i<10;i++)
{
    if(arr[i]<temp)
    {
        temp=arr[i];
        k=i;
    }
    }

   return k;
}

A: for(int i=0;i<10;i++)
  {
    for( int j=i;j<9;j++)  //shouldn't this be j < 10 ?
......


text:
Q: Backpropagation with zero weight initialization Consider the following neural network:

*

*Input layer is 10 neurons

*Layer 1 is a fully connected layer with 10 output neurons

*Layer 2 is a ReLU activation layer

*Layer 3 is a fully connected layer with a single output

*The label is the sign of the output.

Suppose that we have data which is realizable by this architecture, and for which the labels are balanced (have same number of 0's and 1's), while initializing the SGD with the all zeroes weight vectors. Which of the following statement is correct?

*

*SGD is guaranteed to converge on convex problems, hence it will always converge to the correct weights.

*The SGD process will not change the weights at all.

*For some data sets, the SGD process will converge to the correct weights.

*This is a non-convex problem, hence the weight will be changed by SGD, but might converge to a local minimum.

So far, I've managed to eliminate the first answer, I'm left with 3 answers which I consider, however, the last answer seems the most logical to me although I'm not an expert on neural networks and therefore I'm asking here this question.

A: "The SGD process will not change the weights at all."- It will. Why? Check backpropagation formula. There's no reason to not change a weights at all. However, it's better to initialize them with some random values. Why?
Answer's here for this question:
Danger of setting all initial weights to zero in Backpropagation
"For some data sets, the SGD process will converge to the correct weights." - It's true. For some it will but initial weight being 0 don't help. It's said that ann with one hidden layer with non-linear activation can model any function so that's why I believe it's true.
I don't get the last statement.

A: Suppose we are trying to optimize some loss function $\boldsymbol{\epsilon}$ that is parameterized by weights $\boldsymbol{\theta}$. Consider the gradient descent update at time step $(t)$.
$$\boldsymbol{\theta}^{(t+1)} \leftarrow \boldsymbol{\theta}^{(t)} - \alpha \Delta_{\boldsymbol{\theta}}\boldsymbol{\epsilon}$$
where $\alpha$ is the learning rate and $\Delta_{\boldsymbol{\theta}}\boldsymbol{\epsilon}$ is the gradient of the loss function w.r.t. the loss function. Regardless of what value you choose to initalize the weights at, if $\theta_i = \theta_j$ $\forall i,j$, then the gradient signal is identical in all dimensions i.e. $\Delta_{\theta_j}\boldsymbol{\epsilon} = \Delta_{\theta_i}\boldsymbol{\epsilon}$ $\forall i, j$. This means that all the weights will be receiving the same input signal and they will remain equal at all future time steps and therefore no learning can occur.
However, this does not mean that the weights will be unchanged. Indeed, they can change but they will not necessarily lead to a better loss.


text:
Q: Load multiple files into one div via JQuery .load? I'm trying to do this:
$("#Div").click(function(){
  $("#PageContentDiv").load("file.php");
  $("#PageContentDiv").load("another.php");
});

This issue is that the second load function is replacing the first ...

A: Try using $.get() in complete callback of .load() , .append()
$("#Div").click(function() {
  var page = $("#PageContentDiv");
  page.load("file.php", function() {
    $.get("another.php", function(html) {
      page.append(html);
    });
  });
});


text:
Q: Powershell: How to remove all files in Directory except recent ones Have folder which has backups of SQL databases with backup date in the name.
e.g. C:\Backup folder.
Example of backup files:
archive_1_01022022.bak
archive_1_02022022.bak
archive_1_03022022.bak
archive_2_01022022.bak
archive_2_02022022.bak
archive_2_03022022.bak
archive_3_01022022.bak
archive_3_02022022.bak
archive_3_03022022.bak
I need powershell script which removes all files from this directory but keeps recent ones (e.g. for last 5 days), but at the same time I need to keep at least 3 copies of each database (in case there are no backups done for more than last 5 days).
Below script removes all files and keeps recent ones for last 5 days:
$Folder = "C:\Backup"
$CurrentDate = Get-Date
$DateDel = $CurrentDate.AddDays(-5)
Get-ChildItem $Folder | Where-Object { $_.LastWriteTime -lt $DateDel } | Remove-Item

Above is wokring fine, but if there are no recent backups for last 10 days and if I run above code then it will remove all files in C:\Backup. For such cases I need to keep at least 3 backup files of each databases.
If I use below code (for example I have 9 different databases), then it do job:
$Folder = "C:\Backup"
Get-ChildItem $Folder | ? { -not $_.PSIsContainer } |
Sort-Object -Property LastWriteTime -Descending |
Select-Object -Skip 27 |
Remove-Item -Force

But implementation is weird. For example if I have backups of 9 databases, then I need to provide "Select-Object -Skip" with value 27 (9 databases x skip 3 files of each database). In case I have more databases or less, then each time I need to adjust this number. How can I make "Select-Object -Skip 3" static value?

A: In that case, you need to test how many files with a newer or equal date compared to the reference date there are in the folder. If less than 3, sort them by the LastWriteTime property and keep the top 3. If you have enough newer files left, you can delete the old ones:
$Folder  =  "C:\Backup"
$DateDel = (Get-Date).AddDays(-5).Date  # set to midnight

# get a list of all backup files
$allFiles = Get-ChildItem -Path $Folder -Filter 'archive*.bak' -File

# test how many of these are newer than 5 days ago
$latestFiles = @($allFiles | Where-Object { $_.LastWriteTime -ge $DateDel })
if ($latestFiles.Count -lt 3) {
    # if less than three keep the latest 3 files and remove the rest
    $allFiles | Sort-Object LastWriteTime -Descending | Select-Object -Skip 3 | Remove-Item -WhatIf
}
else {
    # there are plenty of newer files, so we can remove the older ones
    $allFiles | Where-Object { $_.LastWriteTime -lt $DateDel } | Remove-Item -WhatIf
}

I have added the -WhatIf safety switch to both Remove-Item cmdlets, so you can first see what would happen before actualy destroying files. Once you are satisfied with what the console shows, remove those -WhatIf switches and run again

If you have 9 databases and the number in the filename after archive_ makes the distinction between those database backup files, just put the above inside a loop and adjust the -Filter:
$Folder  = "C:\Backup"
$DateDel = (Get-Date).AddDays(-5).Date  # set to midnight
# loop through the 9 database files
for ($i = 1; $i -le 9; $i++) {
    # get a list of all backup files per database
    $allFiles = Get-ChildItem -Path $Folder -Filter "archive_$($i)_*.bak" -File

    # test how many of these are newer than 5 days ago
    $latestFiles = @($allFiles | Where-Object { $_.LastWriteTime -ge $DateDel })
    if ($latestFiles.Count -lt 3) {
        # if less than three keep the latest 3 files and remove the rest
        $allFiles | Sort-Object LastWriteTime -Descending | Select-Object -Skip 3 | Remove-Item -WhatIf
    }
    else {
        # there are plenty of newer files, so we can remove the older ones
        $allFiles | Where-Object { $_.LastWriteTime -lt $DateDel } | Remove-Item -WhatIf
    }
}

Ok, so now we know the example names you gave do not bare resemblance with the real names, the code could be as simple as this:
$dbNames = 'archive', 'master', 'documents', 'rb'  # the names used in the backup files each database creates
$Folder  = "C:\Backup"
$DateDel = (Get-Date).AddDays(-5).Date  # set to midnight
# loop through the database files
foreach ($name in $dbNames) {
    # get a list of all backup files per database
    $allFiles = Get-ChildItem -Path $Folder -Filter "$($name)_*.bak" -File

    # test how many of these are newer than 5 days ago
    $latestFiles = @($allFiles | Where-Object { $_.LastWriteTime -ge $DateDel })
    if ($latestFiles.Count -lt 3) {
        # if less than three keep the latest 3 files and remove the rest
        $allFiles | Sort-Object LastWriteTime -Descending | Select-Object -Skip 3 | Remove-Item -WhatIf
    }
    else {
        # there are plenty of newer files, so we can remove the older ones
        $allFiles | Where-Object { $_.LastWriteTime -lt $DateDel } | Remove-Item -WhatIf
    }
}

A: Basing on the assumption that your backups have a name convention of : DBNAME_ddMMyyyy.bak where the date correspond to the backup date, I would do something like below.

$Params = @{
    MinBackupThresold = 1
    MinBackupDays = 5
    SimulateDeletion = $False # Set to true to perform a Remove-Item -WhatIf deletion}

$Folder = "C:\temp\test"
$CurrentDate = Get-Date
$DateDel = $CurrentDate.AddDays($Params.MinBackupDays).Date # set to midnight

$Archives = Foreach ($File in  Get-ChildItem $Folder ) {
    # -13 come from assuming naming convention DBName_8CharBackupDate.ext (eg: Db1_01012022.bak)
    $DbNameEndIndex = $File.Name.Length - 13
    # +1 since our naming convention have an underscore between db name and date.
    $RawDateStr = $File.Name.Substring($DbNameEndIndex + 1 , 8)
    [PSCustomObject]@{
        Path = $FIle.FullName
        LastWriteTime = $File.LastWriteTime
       DBName        = $File.Name.Substring(0, $DbNameEndIndex)
       BackupDate    = [datetime]::ParseExact( $RawDateStr, 'ddMMyyyy', $null)
    }
}

#Here we group archives by their "dbname" so we can make sure to keep a min.  backups for each.
$GroupedArchives = $Archives | Group DBName
Foreach ($Db in $GroupedArchives) {

    if ($Db.Count -gt $Params.MinBackupThresold) {
        $Db.Group | Sort BackupDate | Select-Object -Skip $Params.MinBackupThresold | Where-Object { $_.BackupDate -lt $DateDel } | % { Remove-Item -Path $_.Path -Force -WhatIf:$Params.SimulateDeletion }
    } else {

        # You could include additional checks to verify last backup, alert you if there should be more in there, etc...
    }

}

Note: Using the date extracted from the filename will be more accurate than the lastwritetime, which could be updated for other reasons (Since we have it, might as well use it.)
Note 2 : Added WhatIf in the $params so you can easily switch between actual removal and simulation (Theo's answer gave me the idea of providing that switch) and his .Date to make sure the date was set to midnight instead of  current time of day.


text:
Q: number of ordered pair,s $(a,b,c)$ in $2^a+2^b=c!\;,$ Where $a,b,c$ are non negative integers
number of ordered pair,s $(a,b,c)$ in $2^a+2^b=c!\;,$ Where $a,b,c$ are non negative integers

$\bf{My\; Try::}$ If $a=0,b=0\;,$ Then $c=2$
Similarly for other values of $a$ and $b,$ But i did not understand how can i calculate upper bond of $c$
Help required, Thanks

A: See $$2^x\equiv 1,2,4\pmod 7$$
So if we take equation $\pmod 7$ and if $c\geq 7$ then we get that $c!$ is divisble by 7 because it contains at least one 7 but the sum of $2^a+2^b$ never si divisible by 7 beacuse of $2^x\equiv 1,2,4\pmod 7$ ($2^a+2^b$ can give only ($1,2,3,4,5,6\pmod 7$) so $c\leq 6$.
Then perhaps you can solve it just by case checking like taking c=6, then c=5.


text:
Q: How get PHP single Array Value How I can get only the value "RGE_NOMBRE" for fill an imput text in PHP  from the following array:
object(stdClass)#1367 (1)
{
 ["GetContribuyentesResult"]=> string(161) "{"RGE_RUC":"102318239",**"RGE_NOMBRE"**:"P ARISTIDES HERNANDEZ C POR A","NOMBRE_COMERCIAL":"P ARISTIDES HERNANDEZ","CATEGORIA":"0","REGIMEN_PAGOS":"2","ESTATUS":"2"}"
}

A: Assuming that your response is this:
{"RGE_RUC":"102318239","RGE_NOMBRE":"P ARISTIDES HERNANDEZ C POR A","NOMBRE_COMERCIAL":"P ARISTIDES HERNANDEZ","CATEGORIA":"0","REGIMEN_PAGOS":"2","ESTATUS":"2"}

what you have is a JSON object. To get what you want, decode the JSON and extract your data from the resulting object:
$jsonObject = json_decode($response);
$requiredData = $jsonObject->RGE_NOMBRE; ///  P ARISTIDES HERNANDEZ C POR A

A: While your question is not very clear on how you get the string as a value of stdClass object with key GetContribuyentesResult, I am guess you are inserting the key later.
As per your comments you are doing $data= (array) $response; and your result is a string. Again this is not possible because you are trying to cast an array. Hence I assume $response is the string you are talking about.
This string is a JSON string about which you can read more on this page.
And you can convert a json string to an array with json_decode() in php. This is how you can extract any key from a json string.
$response = '{"RGE_RUC":"102318239","RGE_NOMBRE":"P ARISTIDES HERNANDEZ C POR A","NOMBRE_COMERCIAL":"P ARISTIDES HERNANDEZ","CATEGORIA":"0","REGIMEN_PAGOS":"2","ESTATUS":"2"}';

# decoding to an associative array
$array = json_decode($response, true); ## or json_decode($response) to get an stdClass object
$requiredValue = $array['RGE_NOMBRE']; ## or $requiredValue = $array->RGE_NOMBRE; for stdClass object


text:
Q: How to delete a directory based on date and time The below script will be called from a cronjob and my desire is to remove directories older than 10 mins of the current time.
I'm having trouble with the following in my script:

*

*Trimming \n from the beginning of a variable and not from the end (dumping the $oldDirday variable below to hexdump shows a leading \n

*Adding 600 seconds to the current time

*Getting if test to work properly

This is what I have:
#!/bin/sh

i=1
homeDirData="/home/user"$i"/dirToClean/"

while [ -d $homeDirData ]
do
   echo "Checking user"$i""

   for oldDir in $(find . -type d)
   do
      oldDirDay=$(ls -l $oldDir | awk '{print $7}')
      oldDirTime=$(ls -l $oldDir | awk '{print $8}' | tr -d ':')

      curDay=$(date +%d%t%R | awk '{print $1}')
      curTime=$(date +%d%t%R | awk '{print $2}')

      if [ $oldDirDay -lt $curDay ] && [ $oldDirTime -lt $(($curTime+600)) ]
      then
         find $homeDirData -type f -exec shred -f --remove {} \;
         rm -rf $homeDirData
      else
         echo "Nothing to remove"
      fi

      ((i+1))
   done
done

Error

*

*line 17: [: too many arguments (where the if statement is)

Issue

*

*Nothing is being deleted

A: You can use something like this:
find $homeDirData -type d -mmin +10 -print0 | xargs -0 rmdir


text:
Q: d3 line generator returning null rather than path data string I'm using d3 v4 to create a line graph. My pathGenerator, using d3's line() method, is returning null instead of a path data string (eg "M 100 100 L 300 100 L 200 300 z"), and therefore no lines are being drawn.
When I add in console.log()s to try to determine where the issue occurs, the passed in datum appears correctly as an object with percentLoad and efficiency keys with valid numbers as their values. Console.log()s within the .x() and .y() methods do not seem to be invoked, but I'm not sure why this would be.
const xScale = d3.scaleLinear()
    .domain([10, 100])
    .range([0, chartAreaWidth])

const yScale = d3.scaleLinear()
    .domain([0, 2])
    .range([chartAreaHeight, 0])

const pathGenerator = d3.line()
    .x(d => xScale(d.percentLoad))
    .y(d => yScale(d.efficiency))
    .curve(d3.curveCardinal);

const binGroups = chartGroup.selectAll('.binGroups')
    .data(data.bins)
    .enter().append('g')
    .attr('class', (d,i) => 'binGroups binGroup' + i)

binGroups.selectAll('.percentLoads')
    .data(d => d)
    .enter().append('path')
    .attr('class', (d,i) => 'percentLoads percentLoad' + i)
    .attr('d', d => pathGenerator(d))

A: d3.line generator expects an array of data to generate a line. As mentioned in the docs:

line(data): Generates a line for the given array of data.

In your case, data.bins looks like an array so take a look at a sample curve generated using pathGenerator function from your code and a few sample bins.
Snippet:

var data = {
 bins: [
   { percentLoad: 30, efficiency: 1.4},
   { percentLoad: 60, efficiency: 0.3},
   { percentLoad: 90, efficiency: 1}
  ]
}

const xScale = d3.scaleLinear()
    .domain([10, 100])
    .range([0, 400])

const yScale = d3.scaleLinear()
    .domain([0, 2])
    .range([200, 0])

const pathGenerator = d3.line()
    .x(d => xScale(d.percentLoad))
    .y(d => yScale(d.efficiency))
    .curve(d3.curveCardinal);

const path = d3.select('svg').append('path').style('fill','none').style('stroke', 'steelblue')
    .attr('d', pathGenerator(data.bins));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.0.0/d3.min.js"></script>
<svg width="400" height="200"></svg>

Hope this helps.


text:
Q: How to make a section show all the content? (in a UITableView) I am playing with a piece of code and this is what I have gotten so far. The app gets an XML feed to display job advertisements, and shows them as in the images I attached.
What I am trying to figure out is, how to make the "Description" part display all the information taken from the XML file.
Would the answer be hidden in changing something in this method?
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}

switch(indexPath.section)
{
    case 0:
        cell.text = aBook.title;
        break;
    case 1:
        cell.text = aBook.author;
        break;
    case 2:
        cell.text = aBook.summary;
        break;
}

return cell;

}

A: Try to implement this:
-(CGFloat ) tableView:(UITableView*) tableView heightForRowAtIndexPath:(NSIndexPath*) indexPath
{
If(indexPath.section==2)
{
return 60;
}
}


text:
Q: Crawling error Bing and Google I'm encountering some error while publishing my website.
I've submit my sitemap.xml to Bing and Google using both webmaster tools and both seems have some troubles to crawl my website.
Google doesn't display error message but only 58 pages have been crawled since there is more thant 500 pages submitted by my sitemap.
Furthermore, Bing displays and error while loading my sitemap throught https but is always pending on http.
Could anyone help me to investigate where is my error please ?
Here is my sitemap url :
https://www.unaboria.fr/sitemap.xml
http://www.unaboria.fr/sitemap.xml
My robots.txt is here and allows every robots : http(s)://www.unaboria.fr/robots.txt
Thank you in advance,
Regards,

A: About the Bing Pending status, this will solve it.
After 14 days of pending status, I found this link, to PING Bing with your sitemap. It's a kind of wake-up call for my sitemap. A few hours later, my site was indexed.

*

*Upload your sitemap (but you already did hence the pending status)

*Type in your browser:
http://www.bing.com/webmaster/ping.aspx?siteMap={full url to your sitemap}

You receive a response with something like this:

Thanks for submitting your Sitemap. Join the Bing Webmaster Tools to see your Sitemaps status and more reports on how you are doing on Bing.


text:
Q: Will the original object change if you pass object as parameter to a function inside another file? If you update an object you pass as a parameter will it be updated "upwards", if the method that gets the parameter is in another file? Or will the object you passed down as a parameter have its own context?

A: Yes, that's updated too. In JavaScript you're actually passing objects' references not the objects themselves.

let obj = {
  foo: 'bar'
};

function func(arg) {
  arg.foo = 'hi';
}
func(obj);
console.log(obj.foo); // prints 'hi'


text:
Q: High performance, fast yet Durable databases? Up until recently I was using mongo to try and stem to tide of massive MySQL upgrades to system servers, however, after reading this:
http://www.mikealrogers.com/2010/07/mongodb-performance-durability/
I have halted production of a mongo version of my site until mongo would gain more stability.
Some have suggested I use the _change within couche DB to create a new mongo object which would solve the main issues within mongo db atm but I'm not sure about it.
I have looked into other DB's such as redis and Cassandra but I have since ditched Cassandra as you have to design for your queries and that's just too restricting for my site (bad modulisation). I'm not really looking for joins etc, I'm just looking for the ability to search within a row instead of just the columnfamily id's as it can make programming quite hard when trying to add new functionality. It would be great for a search engine or something but not so good for a real website like facebook in it's entirty (instead of just in its mail search).
I was wondering what experiences people on here have had with trying to get a workable solution to the SQL speed issues. Is there a silver bullet db for it all or is it just a case of gritting your teeth with MySQL or another SQL db if you want reliability?
Maybe a cross between a form of caching and SQL (I noticed facebook uses heavy caching on their wall pages etc...probably why).
Thanks,

A: You haven't really given any idea of the scale of your site which makes a huge difference to what technology/method is appropriate.
At any rate nothing is going to be a magic bullet.  Most of the things you are mentioning are about making large scaling possible rather than avoiding scaling at all.
Even using something like memcached in front of the db needs a slightly different way of thinking to get the full benefit of it.  One of the first things you need to do (and there can be great savings if you haven't already) is to look at and optimise the sort of queries you are making.

A: What is your issue with Mongo exactly?  You will need to make backups anyway.  It now supports replica sets so you are really not tied to a machine failure.
If you are using 25 servers now, you could easily run a replica set of a few servers and not have a single point of failure.
10-30 million rows is really not a lot.  Especially since with a noSQL solution you can probably consolidate a few rows into single records.  If you have 2 million users, it is even possible most of their data will fit into single records.  (4 mb limit is a lot)


text:
Q: asp.NET MVC 3 Composite pattern model binding My application has products and vendors and both of them have similar items in a "has a" relationship...in particular they have a "favorite" so users can bookmark them.
so we have:
public class Product
{
    public int ProductId {get;set;}
    public int Name {get;set;}
    public List<Favorite> Favorites {get;set;}
}

public class Vendor
{
    public int VendorId {get;set;}
    public int Name {get;set;}
    public List<Favorite> Favorites {get;set;}
}

public class Favorite
{
    public int FavoriteId {get;set;}
    public string UserName {get;set;}
}

At first this didn't work, so I added:
    public int? VendorId {get;set;}
    public int? ProductId {get;set;}

Now the issue I'm having is that my Vendor.Favorites and Product.Favorites are always null.
How do I bind these so that I can work with the objects like that? Do I not make it a separate entity?
Thanks!
UPDATE: I should note that I'm using MVC 3 Code-first with POCO.
UPDATE: Solution:
I don't think this is ideal, still working out the kinks with how I want this to work because It will add redundant code for adding favorites and reviews.
public class Product
{
    public int ProductId {get;set;}
    public int Name {get;set;}
    public virtual List<Favorite> Favorites {get;set;}
}

public class Vendor
{
    public int VendorId {get;set;}
    public int Name {get;set;}
    public virtual List<Favorite> Favorites {get;set;}
}

Having the raw nullable int variable in the favorites class makes it work, but if I wanted to use the favorites class with other objects I'll have to modify the favorites properties with a new mapping to the key of the object.  Out of curiosity, when dealing with these classes normally, how do you manage the data storage for these objects?  I'm assuming you deal with it at a DAL?

A: You could use inheritance, make a base class containing only Favorite then derive classes based on that for the other info. This establishes an "is a" relationship
Ex.
public class baseClass
{
 public list<Favorite> Favorites { get; set;}
}
public class Product : base
{
 public int ProductID { get; set; }
 public string Name { get; set; }
}

Then a Product Object would have all 3 properties.

A: I would keep one Property to store the ID's (either VendorID or ProductId) and use another property to tell me what type it is (Vendor or Product)
public class Favorite
{
    public int FavoriteId {get;set;}
    public string UserName {get;set;}
    public int ItemID { set;get;}    //can use a better generic name
    public FavoriteType Type { set;get;}
}

I have an Enum for the Types
public enum FavoriteType
{
    Vendor,
    Product
}

And make sure you are initializing your sub properties before accessing them / applying a method on those so that It won't throw the null reference exception!. You can do it constructor itself
public class Product
{
    public int ProductId {get;set;}
    public int Name {get;set;}
    public List<Favorite> Favorites {get;set;}

  public Product()
  {
      if(Favourites==null)
          Favorites=new List<Favorite>();
  }
}

A: Based on the assumption that you're using EF 4.1:
Your model looks pretty good except I'd change
    public int? VendorId {get;set;}
    public int? ProductId {get;set;}

to
    public virtual Vendor VendorId {get;set;}
    public virtual Product ProductId {get;set;}

Then your FK relationships should be all set. By my understanding of EF, List<Favorite> is meant to establish a relationship and is not actually populated.  You have to populate it yourself, either by calling .Include() on the context or by referencing the actual FK that EF creates in the database, which in your case would be VendorId_FavoriteId or ProductId_FavoriteId


text:
Q: Understanding DI in Scala I have two traits:
trait A {
  def a
}

And:
trait B { this: A =>
  def b
}

Now, I tried to use trait B as this:
def method(bTrait: B) = bTrait.a //error

but it refuses to compile. I thought we could rely on that any implementations of B always extends A. What's wrong? Why doesn't it compile?

A:
I thought we could rely on that any implementations of B always
  extends A

That's not what this: A => means. What it means is: "in order to use B, I require an instance of A to be provided at compile time". This can be done through mixin
Once you understand that, you can do:
def method(bTrait: B with A) = bTrait.a


text:
Q: ox-hugo: All figures and code snippets have the same number (1) When exporting an org file to MD using ox-hugo, all code snippets and figures end up having the same number (1)
Links in the text will also have the same number (1) but in some cases they will have two different numbers even when they are pointing to the same source code. Below is MWE, the org file and the MD after exporting.
    * Summary

    Reference to script 1 ([[code:runscript1]])

    #+caption: Caption 1
    #+name: code:runscript1
    #+begin_src bash
      # Example
      /bin/bash 01-script.sh
    #+end_src
    First part of code snippet [[code:runprog]]

    The second part of snippet [[code:runprog]] shows

    #+caption: Caption 2
    #+name: code:runprog
    #+begin_src bash
      # Example
      /bin/bash 02-script.sh
    #+end_src

    ---
    title: "Test"
    date: 2022-11-25
    lastmod: 2022-12-09T00:05:39-04:00
    draft: false
    menu:
      sidebar:
        weight: 1001
        identifier: "test:weight 34"
        name: "Test"
    author:
      name: Me
      image: /images/author/test2.png
    hero: /images/posts/front/test2.svg
    math: true
    ---

    ## Summary {#summary}

    Reference to script 1 ([1](#code-snippet--code:runscript1))

    ```bash
    # Example
    /bin/bash 01-script.sh
    ```

      Code Snippet 1:
      Caption 1

    First part of code snippet [2](#code-snippet--code:runprog)

    The second part of snippet [1](#code-snippet--code:runprog) shows

    ```bash
    # Example
    /bin/bash 02-script.sh
    ```

      Code Snippet 1:
      Caption 2

*

*A previous version of the same post (from November 25th) did not have such problem so I changed my config file from package.el to straight.el and checked out versions of org and ox-hugo from around that date but the results were the same.

*There is a similar issue posted on ox-hugo github page but so far there has been no response

*Most of the attempts were done on a Debian 11 machine with emacs 27.1 but I have also tried on a Windows 10 machine with emacs 28.2 with the same results
Thanks

A: [Comment converted to answer]
This was apparently a bug in Org 9.6 and it affects more than the ox-hugo backend (maybe every backend). The author of ox-hugo has posted a question on the Org mode mailing list about it. A fix has been been submitted and it has been confirmed. The fix is here and if you use Org mode from the Git repo, you should be able to get the fixed version now.
@KaushalModi (the author of ox-hugo) mentions in a comment above that the fix is now in the Org bugfix branch. I thought this meant that it would be available in the Org mode release on GNU ELPA, but I have not been able to verify that as of yet.


text:
Q: How can I tell the code is running on Google App Engine? When I run google app engine locally, sys.platform reports linux3. It can mean I am running on a linux platform too.
What is the definitive way to tell my code is running in a google app engine environment?

A: One way is to check if the  APPENGINE_RUNTIME environment variable is set
In python would be
import os
if 'APPENGINE_RUNTIME' in os.environ.keys():
    # working in appengine environment

This is a special appengine environment variable that is not set for regular programs.
If you are interested in other environment variables, here is the list
INSTANCE_ID 7ae067a39bdd37e8ab1cf40c711a6dbca84d
wsgi.url_scheme http
wsgi.multiprocess True
wsgi.version (1, 0)
HTTP_USER_AGENT Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36
REMOTE_ADDR 127.0.0.1
HTTP_X_APPENGINE_COUNTRY ZZ
SERVER_PROTOCOL HTTP/1.1
QUERY_STRING
wsgi.run_once False
DATACENTER us1
REQUEST_METHOD GET
SERVER_SOFTWARE Development/2.0
HTTPS off
wsgi.multithread True
SCRIPT_NAME
HTTP_ACCEPT */*
APPLICATION_ID dev~teledap-gae
SERVER_NAME localhost
USER_EMAIL
REQUEST_LOG_ID 5e2e9ae098c4612cfdb1feebacea8dc5cb7e9e989355edfffcb4a30dbca2ecffa69b
wsgi.errors <google.appengine.api.logservice.logservice._LogsStreamBuffer object at 0x7fd47f9308d0>
PATH_INFO /
DEFAULT_VERSION_HOSTNAME localhost:8080
USER_NICKNAME
APPENGINE_RUNTIME python27
CURRENT_VERSION_ID 1.790710791652471334
USER_ID
USER_ORGANIZATION
HTTP_CONTENT_LENGTH 0
HTTP_ACCEPT_LANGUAGE en-US,en;q=0.8,nl;q=0.6,es;q=0.4
HTTP_HOST localhost:8080
CURRENT_MODULE_ID default
TZ UTC
HTTP_COOKIE _ga=GA1.1.2122305447.1428161397; connect.sid=s%3AWErSIaaWXlGMkYqcwwBrikSFU1Xy4EGS.xOv8DCRhhTx2xaKiK4wRJsQh3ol9pG3njPxPexQiRdA
HTTP_CACHE_CONTROL no-cache
AUTH_DOMAIN gmail.com
USER_IS_ADMIN 0
wsgi.input <cStringIO.StringI object at 0x7fd47f92c0b8>
REQUEST_ID_HASH 9B7C4FEB
SERVER_PORT 8080

Some are dependant of where or how they are run, e.g. the HTTP_USER_AGENT or REQUEST_METHOD may vary.
You may also define your own environmental variables if you would rather use those:

You can define variables in app.yaml to make them available to the
  program's os.environ dictionary:
env_variables:
  DJANGO_SETTINGS_MODULE: 'myapp.settings'


text:
Q: issue with iOS fixed position css
Possible Duplicate:
iOS 5 fixed positioning and virtual keyboard

Has anyone come across this before? It only happens when the keyboard is on screen, once the keyboard is hidden again it goes back to normal.
The CSS
div#menu {
    position: fixed;
    bottom: 0;
    width: 100%;
    z-index: 10;
}

The HTML

Account

Read Meter

Info

Logout


text:
Q: Warning: Prop `className` did not match. when using @font-face and styled-components with NextJS
Hi all, I have created a GlobalStyle which I call my fonts using font-face.
import { createGlobalStyle } from 'styled-components';

export const GlobalStyle = createGlobalStyle`
body {
    font-family: 'Roboto', sans-serif;
}
  html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font-family: 'Roboto', sans-serif;
    vertical-align: baseline;
}
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}
@font-face {
  font-family: "Roboto";
  src: url("/fonts/Roboto/Roboto-Regular.ttf");
  font-style: normal;
  font-weight: 400;
  font-display: swap;
}
@font-face {
  font-family: "Roboto";
  src: url("/fonts/Roboto/Roboto-Bold.ttf");
  font-style: bold;
  font-weight: 700;
  font-display: swap;
}
`;

This GlobalStyle is called inside my _app.tsx file. Fonts are located in my public folder.
I never had this error but after I added @font-face this issue started.
What I have tried:
adding this code to .babelrc:
"plugins": [["styled-components", { "ssr": true }]]

Installed babel-preset-next and babel-plugin-styled-components extensions.
Nothing worked.
What I'm doing wrong?
styled-components version: 5.3.0
next: 11.0.1

A: Fixed creating a _document.tsx file in pages folder.
import Document from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static async getInitialProps(ctx: any) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App: any) => (props: any) =>
            sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }
}


text:
Q: Unity streaming WWW issue I'm using WWW Unity class to get songs from S3 Bucket.
The issue is this, when I'm loading one song, the streaming works great, I'm getting a big enough buffer and able to play a song easily with AudioSource Clip.
The problem starts when I try to call the function twich, witch actually means, I have the need to download two songs at the same time. Let me notice that if I try to hold the second function, still I get an error ( The error is a "Red" error, but without any data about the error).
Function:
 private IEnumerator startSongStreaming(int playerIndex,User user)
    {
        string url = user.getCurrentGamePerformacePath ();
        WWW www = new WWW (url);
        AudioSource audioSource = GameObject.FindGameObjectsWithTag ("PlayerResultsAudio")[playerIndex].GetComponent<AudioSource>();
        AudioClip myAudioClip = audioSource.clip;
        Debug.Log (playerIndex +  " :" +  www.progress);
        while (www.progress < .1f) {
            Debug.Log ("Streaming WWW PLAYER INDEX: " + playerIndex + " " + www.progress);
            yield return null;
        }
        myAudioClip = www.audioClip;
        Debug.Log (playerIndex +  " CHECKTHIS:" +  www.progress);
        while (!(myAudioClip.isReadyToPlay)) {
            Debug.Log ("IS READY TO PLAY PLAYER INDEX: " + playerIndex + " " + www.progress);
            yield return null;
        }
        //Debug.Log ("TESTME: " + myAudioClip.isReadyToPlay);
        audioSource.clip = www.GetAudioClip(false, true, AudioType.WAV);
        Button listen = GameObject.FindGameObjectsWithTag ("PlayerResultsListenBtn") [playerIndex].GetComponent<Button> ();
        listen.interactable = true;
    }

I have no issues with the prefabs and getting the GameObjects, it works great with the funciton that function that calls this function.
Anyhow the debug.logs return a good streaming for one of the indexs, and sets streaming to 1 on the other ( like it's finished, but it never really started ).
so I get 0 and streaming ( object will work and play )
and 1 and 1 streaming ( like streaming is completed but an unknowen error and cant play the audio ).
I know it's a head to understand question, Thank ahead.

A: Alright, we have purchased Unity3d Pro version and the problem has been solved, no code errors or changes, simply works :).
So if anyone tackle with this type of problem, contact Unity3d support.


text:
Q: overloaded battery burns appliance I got a 12V car battery. I charged it with a 12 V solar panel until it gets about 17V (the battery was hot, I know that isn't good). Later on, I burned several battery-feed devices. The funny thing was that some of those devices were USB adapters for both 12 AND 24V batteries! What have I missed?
Which maximum voltage you consider safe for this kind of appliances? Do you recommend to reduce the voltage using a minimalistic voltage regulator circuit?
Thank you.
UPDATE: mind you, the main question is why a USB charger prepared for both 12V and 24V is burned by a 17V battery. I did some research and my guess is that is related with voltage droop, maybe the actual voltage for this kind of appliances is higher in the overcharged 12V battery than in the normally charged 24V battery. But I'm unable to get the numbers by myself.

A: According to automotive standards (ISO 16949 for example), a 12V-device should operate between 9 and 16VDC input without any problems. So 17VDC seems a bit excessive for some sensitive devices.
Anyway, a car battery should show 14.5V maximum when fully charged.

A: In addition to the comments given here some more information.
The maximum voltage of a fully charged 12V car battery (lead accid) does not exceed 14.4 V plus or minus a very small tolerance.
However when the charging proces is not stopped by a regulator the proces keeps going on and the battery absorbs the incomming energy by getting hot and boiling of water and some electrolyte vapour.
At the moment that the plates of the battery cells become free from the electrolyte the voltage limitation of 14.4 V is no longer there and the voltage of the battery goes up as long as the charging continues up to the maximum voltage of the charger.
This proces took place in your situation since there was obviously no voltage regulator to stop the charging proces at the moment that the battery has reached the 14.4V maximum.


text:
Q: Python GUI - wm_attributes("-topmost", True) in tkinter do not work with xfreerdp /f I'm writing a lightweight client for xfreerdp in python + tkinter.
At the top of the screen, I've placed a menu with buttons that should appear on top of all programs.
And it works as long as I don't use the /f switch for xfreerdp.
As I understood wm_attributes ("-topmost", True) does not work if another program was launched in full-screen mode.
Is there another way in tkinter to display Toplevel on top of full-screen apps?
Or a way to run xfreerdp inside a tkinter window?
Or a similar method using a different GUI for Python?
from tkinter import *
import subprocess

# ======== MAIN MENU ========
root = Tk()

RootWindowsWidth = 600
RootWindowHeight = 350
#Define display resolution
ScrWdth = root.winfo_screenwidth()
ScrHgth = root.winfo_screenheight()
#Define margine for main menu
RootXLeft = round((ScrWdth/2) - (RootWindowsWidth/2))
RootYTop = round((ScrHgth/2) - (RootWindowHeight/2))
#Main menu settings
root.geometry(str(RootWindowsWidth) + "x" + str(RootWindowHeight) + "+" + str(RootXLeft) + "+" + str(RootYTop))
root['bg'] = '#fafafa'
root.title('MyRDP')
root.wm_attributes('-alpha', 1)

# Global variable for TopBar
TopBarWindowsWidth = 600
TopBarWindowHeight = 20
TopBarXLeft= round((ScrWdth/2) - (TopBarWindowsWidth/2))
TopBarYTop = 0

# ======== TOP MENU ========
global TopBar
TopBar = Toplevel()

TopBar.geometry(str(TopBarWindowsWidth) + "x" + str(TopBarWindowHeight) + "+" + str(TopBarXLeft) + "+" + str(TopBarYTop))
TopBar.wm_attributes('-alpha', 0.85)
TopBar.attributes('-type', 'dock')
TopBar.wm_attributes("-topmost", True)

TopButton01 = Button(TopBar, text='BTN1')
TopButton02 = Button(TopBar, text='BTN2')

TopButton01.grid(row=0,column=0)
TopButton02.grid(row=0,column=2)

# ======== Functions ========
#RDP connect button
def btn_click():
    subprocess.call("gnome-terminal -x xfreerdp /cert-ignore /v:192.168.31.63 /u:user /d:vm2 /p:123 /f", shell=True)

#Exit button
def btn_quit():
    root.quit()

# ======== MAIN MENU CONFIG ========
canvas = Canvas(root, height=350, width=600)
canvas.pack()

frame = Frame(root, bg='green')
frame.place(relx=0.15, rely=0.15, relwidth=0.7, relheight=0.7)

btn = Button(frame, text='RDP', bg='yellow', command=btn_click)
btn.pack()
btn = Button(frame, text='Close', bg='orange', command=btn_quit)
btn.pack()

root.mainloop()

A: So far I'm just use "/floatbar:sticky:off,default:visible,show:fullscreen" and "/multimon" xfreerdp options.That enought for now.


text:
Q: From $\sum_p \frac{\log p}{p^s} = \frac{1}{s-1} + O(1)$ conclude that $\sum_p \frac{1}{p^s} = \log \frac{1}{s-1} + O(1)$ I'm reading a book on analytic number theory. It asks me to prove:

$$ \sum_p \frac{\log p}{p^s} = \frac{1}{s-1} + O(1) \tag{A}$$
  and conclude, via integration, that:
    $$ \sum_p \frac{1}{p^s} = \log \frac{1}{s-1} + O(1) \tag{B}$$

Now, I know how to prove $(A)$ via Abel Summation. However, when it comes to $(B),$ I have the problem that although:
$$\frac{d}{dx} \log(x-1) = \frac{1}{x-1}$$ and
$$\frac{d}{ds} p^{-s} = (-\log p)p^{-s}$$
I have the problem that when I integrate over $O(1)$, I get $\infty$, not $O(1)$.
What am I doing wrong? How do I get from $(A)$ to $(B)$?

A: What if you don't integrate over all of $(s,\infty)$? Say, fix $S$ large enough, and...
$$\int_s^S\sum_{p}\frac{\log p}{p^\sigma}d\sigma=\int_s^S\frac{1}{\sigma-1}+O(1)d\sigma=\log\frac{1}{s-1}+O(1) $$
whereas
$$\int_s^S\sum_{p}\frac{\log p}{p^\sigma}d\sigma=\sum_p\int_s^S\frac{\log p}{p^\sigma}d\sigma=\sum_{p}\left(\frac{1}{p^s}-\frac{1}{p^S}\right)=\sum_p\frac{1}{p^s}~+O(1) $$
for $s<S$ as $s\to1^+$.
(Some uniform convergence stuff needs to be checked so that the interchange is justified.)

A: The first idea I had when you posted in chat was to use infinite Möbius inversion. We have
$$P(s)=\sum_p\frac{1}{p^s}=\sum_{n\ge1}\frac{\mu(n)}{n}\log\zeta(ns), $$
where $P(\cdot)$ is the prime zeta function and $\zeta(\cdot)$ is the Riemann zeta function. (For those who want to check this: write $\zeta$ in the Euler product form and then expand each Euler factor with a series expansion for $\log$ individually; group terms appropriately.) As $s\to1^+$ all of the $n\ge2$ terms are already $O(1)$ (put together), so we need only put $\zeta(s)=\frac{1}{s-1}+O(1)$ inside the first logarithm.
This route requires more work and preliminary information though.

A: Well we know that
$$\zeta(\sigma)= \frac{1}{\sigma-1}$$ when $$ \sigma \to1^+$$ since zeta has a simple pole in $\sigma=1$ with residual one.
Now your function $$\sum_p\frac{\log p}{p^s}$$ can be expressed in terms of the zeta function.
see http://people.math.jussieu.fr/~demarche/enseignements/2011-2012/M1-TDN/MM020-TD6-corrige.pdf (it's the exercise number 7, question g, in french :)).
The tricky part is why could you integrate two functions which are equivalent in the sense that $$\sum_p \frac{\log p}{p^s} ∼ \frac{1}{s-1}$$ ?
Here it is possible since $1/s-1$ is not integrable in a neighborhood of 1.
Why?
here is an sketch of how you could procede.
Let f, g be continuous on R such that f~g and $\int_0^\infty$fdx diverges.
I will write this integral I in what follows and I$x$ when the upper bound is $x$ instead of + $\infty$.
we would like to show that I (f) ~ I (g)
In what follows we have f ~ g at infinity. (I guess you could repeat that proof for an equivalence that holds in another neighborhood)
f ~ g then f (x) = g (x) (1 + h (x)) such that $gh \to0$ when x tends to + infinity (and h tends to $0$ as well).
So you've got  I$x$ (f) / I$x$ (g) = 1 + I$x$ (gh) / I$x$ (g)
then show that | I$x$ (gh) / I$x$ (g) | tends to $0$ in + infinity
since |I$x$ (gh) / I$x$ (g) | = I$a$ (gh) / I$x$ (g) + I$a-x$ (gh) / Ix (g)
 then  | I$x$ (gh) / I$x$ (g) | $ \leq$ I$a$(gh) / I$x$ (g) + sup (h) on [$a$, x]
and since h tends to $0$, you can choose $a$ large enough such that $sup (h) \leq \epsilon / 2$
Once $a$ is chosen, since I$a$ (gh) is a number and I$x$ (g) diverges then there exists $x$ large enough such that I$a$ (gh) / I$x$ (g) $\leq \epsilon / 2$.
Finally, for $x$ large enough everything is inferior to a certain epsilon, and you can conclude.


text:
Q: How to Get the JSON Objects' Name in an JSON Array I need to get the values "channelA" and "channelB", which are the object names.
JSON file:
[
    {
        "channelA": {
            "programmes": [
                {
                    "start_utc": 1522208700,
                    "stop_utc": 1522209600,
                },
                {
                    "start_utc": 1522209600,
                    "stop_utc": 1522210800,
                }
            ]
        }
   },
   {
      "channelB": {
          "programmes": [
               {
                  "start_utc": 1522256700,
                  "stop_utc": 1522260800
               },
               {
                  "start_utc": 152229000,
                  "stop_utc": 1522318900,
               }
           ]
       }
   }
]

I am storing the JSON in a value called epg, and iterating through epg with:
for (var k = 0; k < epg.length; k++) {
    console.log(_epg[k]);
}

I need to compare the name of the object with another variable (channelId):
for (var k = 0; k < _epg.length; k++) {
    if (channelId == epg[k]) {
       console.log(_epg[k]);
    }
}

A: If you just want those names you can simply map over the array and return the first element from the Object.keys array:

const data = [{"channelA":{"programmes":[{"start_utc":1522208700,"stop_utc":1522209600,},{"start_utc":1522209600,"stop_utc":1522210800,}]}},{"channelB":{"programmes":[{"start_utc":1522256700,"stop_utc":1522260800},{"start_utc":152229000,"stop_utc":1522318900,}]}}]

const out = data.map(obj => Object.keys(obj)[0]);
console.log(out);

RESULT
[
  "channelA",
  "channelB"
]

A: Use Object.keys() method for this:

let myArr = [
    {
        "channelA": {
            "programmes": [
                {
                    "start_utc": 1522208700,
                    "stop_utc": 1522209600,
                },
                {
                    "start_utc": 1522209600,
                    "stop_utc": 1522210800,
                }
            ]
        }
   },
   {
      "channelB": {
          "programmes": [
              {
                  "start_utc": 1522256700,
                  "stop_utc": 1522260800
              },
              {
                  "start_utc": 152229000,
                  "stop_utc": 1522318900,
               }
           ]
       }
   }
]

for (let item of myArr) {
  for (let key of Object.keys(item)) {
    if (key == "channelA" || key == "channelB") console.log(key + ": ", item[key])
  }
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

A: Since keys are uniques, you can find the object using the function filter as follow:
I've added two channeldB to illustrate

var array = [    {        "channelA": {            "programmes": [                {                    "start_utc": 1522208700,                    "stop_utc": 1522209600,                },                {                    "start_utc": 1522209600,                    "stop_utc": 1522210800,                }            ]            }   },   {      "channelB": {          "programmes": [               {                  "start_utc": 1522256700,                  "stop_utc": 1522260800                                    },               {                  "start_utc": 152229000,                  "stop_utc": 1522318900,                                    }           ]       }   },   {      "channelB": {          "programmes": [               {                  "start_utc": 15232256700,                  "stop_utc": 1599990800                                    },               {                  "start_utc": 992229000,                  "stop_utc": 1520910900,                                    }           ]       }   }];

var channelId = "channelB";
var found = array.filter((a) => a[channelId]);
console.log(found);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You can use the Object.entries method to get those values.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

A: You can check the key inside each object of the array and compare with the channelId:

var _epg = [
    {
        "channelA": {
            "programmes": [
                {
                    "start_utc": 1522208700,
                    "stop_utc": 1522209600,
                },
                {
                    "start_utc": 1522209600,
                    "stop_utc": 1522210800,
                }
            ]
        }
   },
   {
      "channelB": {
          "programmes": [
              {
                  "start_utc": 1522256700,
                  "stop_utc": 1522260800
              },
              {
                  "start_utc": 152229000,
                  "stop_utc": 1522318900,
               }
           ]
       }
   }
];

var channelId = 'channelB';
for(var k=0; k<_epg.length; k++){
    var key = Object.keys(_epg[k])[0];
    if (channelId == key){
       console.log(_epg[k]);
    }
}

A: You might want to iterate over the json:

var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"}];

for (var i = 0; i < arr.length; i++){
    var obj = arr[i];
    for (var key in obj){
        var attrName = key;
        var attrValue = obj[key];
        console.log(attrName + " " + attrValue)
    }
}

This will produce the following output:

*

*"id 10"

*"class child-of-9"

*"id 11"

*"classd child-of-10"

This might help: https://stackoverflow.com/a/1112609/3504189


text:
Q: MySQL: Syntax error when creating trigger Why my sql syntax is throwing an error?
CREATE TRIGGER info
AFTER INSERT ON inbox
FOR EACH ROW BEGIN if SUBSTRING(new.TextDecoded,1,6)='telkom' then
INSERT INTO outbox ( DestinationNumber, Coding, TextDecoded, CreatorID )VALUES ( new.SenderNumber, 'Default_No_Compression', (SELECT nama from data_dosen WHERE kode = SUBSTRING(new.TextDecoded,8,10)), '1');

else
INSERT INTO outbox (DestinationNumber, Coding, TextDecoded, CreatorID) VALUES (new.SenderNumber, 'Default_No_Compression', 'Maaf format sms Anda salah. Ketik telkom<spasi>kode dosen', '1');

end if;

END$$

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 4

A: You don't have delimiter definition before your trigger. Delimiter informs MySQL which characters will end up your trigger. Without it, MySQL assumes semicolon as default delimiter and fails upon first semicolon in your code. Check out this:
DELIMITER $$
CREATE TRIGGER info
AFTER INSERT ON inbox
FOR EACH ROW BEGIN if SUBSTRING(new.TextDecoded,1,6)='telkom' then
    INSERT INTO outbox ( DestinationNumber, Coding, TextDecoded, CreatorID )VALUES ( new.SenderNumber, 'Default_No_Compression', (SELECT nama from data_dosen WHERE kode = SUBSTRING(new.TextDecoded,8,10)), '1');

else
    INSERT INTO outbox (DestinationNumber, Coding, TextDecoded, CreatorID) VALUES (new.SenderNumber, 'Default_No_Compression', 'Maaf format sms Anda salah. Ketik telkom<spasi>kode dosen', '1');

end if;

END$$
DELIMITER ;


text:
Q: ValueError: Shapes (None, 188, 1) and (None, None, None, None) must have the same rank I am building a CNN-LSTM network and it was working fine until I TimeDistributed the CNN layers. The program is now outputting a ValueError due to a dimension difference that I cannot seem to fix by adjusting the input dimensions. I suspect the error might be due to a difference between the CNN output size and the LSTM expected input, but I flattened the output so I really don't know.
X_train = X_train.reshape(1772, 300, 188, 1)
X_test = X_test.reshape(586, 300, 188, 1)

y_train = np.array(y_train)
y_test = np.array(y_test)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

model = Sequential()
model.add(TimeDistributed(Conv2D(64, kernel_size=(12, 12), activation='relu', input_shape=(1772, 300, 188, 1))))
model.add(TimeDistributed(Conv2D(128, (6, 6), activation='relu')))
model.add(TimeDistributed(MaxPooling2D(pool_size=(4, 4))))
model.add(TimeDistributed(Flatten()))
model.add(LSTM(64))
model.add(Dense(4, activation='softmax'))

A: The problem is that by adding the TimeDistributed wrapped, you need to add a Timestep dimension.
Here you have an input with 4 dim (batch_size, height, width, channels) but your layer :
model.add(TimeDistributed(Conv2D(64, kernel_size=(12, 12), activation='relu', input_shape=(1772, 300, 188, 1))))

is expecting a 5 dim input (batch_size, timestep, height, width, channels).
So you need to add an other dim to your inputs !


text:
Q: How to update single column with multiple entries in MySQL in the same table I have 4 columns in a table which are as
id = Auto Increment Value
user_id = user id from session
short_name = short name for page
status = status of page
Following is the array in the $_POST
Array
(
    [pg_about] => 1
    [pg_tools] => 1
    [pg_in] => 1
    [pg_ex] => 1
    [pg_cats] => 1
    [pg_payee] => 1
    [pg_payment] => 1
    [pg_find] => 1
    [pg_menu] => 1
    [pg_sm] => 1
    [pg_cs] => 1
    [pg_csv] => 1
    [pg_calc] => 1
    [pg_budget] => 1
    [pg_tip] => 1
    [pg_exp_pr] => 1
    [pg_bal] => 1
    [pg_mn_ct_in] => 1
    [pg_mn_ct_ex] => 1
    [pg_mn_sct_in] => 1
    [pg_mn_sct_ex] => 1
    [pg_yr_in] => 1
    [pg_yr_ex] => 1
    [pg_dr_in] => 1
    [pg_dr_ex] => 1
    [pg_ct_in] => 1
    [pg_ct_ex] => 1
    [pg_sct_in] => 1
    [pg_sct_ex] => 1
    [pg_all] => 1
    [pg_all_time] => 1
    [pg_inc_vs_exp] => 1
    [pg_audit] => 1
    [pg_imp] => 1
)

pg_* are stored in the short_name column and the values in the status.
Currently I'm using the following method;
UPDATE tbl_menu2
   SET status = 0
 WHERE user_id = 5
   AND short_name = 'pg_in';

UPDATE tbl_menu2
   SET status = '0'
 WHERE user_id = 5
   AND short_name = 'pg_ex';

...and so on
How can I make it more efficient using single SQL statement.
Note ; user_id will be same for all the 30+ entries.
Update ; I forgot to mention that the status will be different it won't be the same status value is user dependent.

A: if you have a set of value for short_name you could use a IN clause
UPDATE `tbl_menu2`
SET `status` = '0'
WHERE  `user_id` = 5
AND `short_name` IN ( 'pg_in','pg_ex');

A: You can use the same query as following by using in
UPDATE `tbl_menu2` SET `status` = '0' WHERE  `user_id` = 5 AND `short_name` in( 'pg_in','pg_ex','pg_cats',......);

A: I know this is MYSQL question but you can use PHP loop.
foreach ($array as $key => $value) {
    mysql_query("UPDATE tbl_menu2 SET status = $value WHERE user_id = 5  AND short_name = '$key'");
 }


text:
Q: GData Youtube Upload Crashing for iOS I'm trying to use the GData objective c project v1.12.0 to upload a video to youtube. I followed the following guide to get GData linked with my project:
http://mischneider.net/?p=377#comment-1277
It all seems to be linked properly, but I keep getting this error message:

2011-06-23 15:06:30.729[79217:207] * Assertion failure in -GDataServiceBase fetchObjectWithURL:objectClass:objectToPost:ETag:httpMethod:delegate:didFinishSelector:completionHandler:retryInvocationValue:ticket:, /Users/aalesia88/Desktop/VOKAL/Developement/SSB-Youtube/GData/BaseClasses/GDataServiceBase.m:603
  2011-06-23 15:06:30.731[79217:207] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'GDataHTTPUploadFetcher needed'

Here is my methods used in calling the upload procedure:
- (GDataServiceGoogleYouTube *)youTubeService
{
    GDataServiceGoogleYouTube* service = nil;

    if (!service) {
        service = [[GDataServiceGoogleYouTube alloc] init];

        [service setShouldCacheDatedData:YES];
        [service setServiceShouldFollowNextLinks:YES];
        [service setIsServiceRetryEnabled:YES];
    }

    SSBYoutubeCredentials *currentUser = [SSBYoutubeCredentials getCurrentUser];
    NSString *username = currentUser.username;
    NSString *password = currentUser.password;

    if ([username length] > 0 && [password length] > 0) {
        [service setUserCredentialsWithUsername:username
                                       password:password];
    } else {
        // fetch unauthenticated
        [service setUserCredentialsWithUsername:nil
                                       password:nil];
    }

    NSString *devKey = DEVELOPER_KEY;
    [service setYouTubeDeveloperKey:devKey];

    return service;
}

- (void)setUploadTicket:(GDataServiceTicket *)ticket
{
    if (uploadTicket != nil) {
        [uploadTicket release];
    }

    uploadTicket = [ticket retain];
}

- (void)uploadVideoFile
{
    NSString *devKey = DEVELOPER_KEY;

    GDataServiceGoogleYouTube *service = [self youTubeService];
    [service setYouTubeDeveloperKey:devKey];

    SSBYoutubeCredentials *currentUser = [SSBYoutubeCredentials getCurrentUser];
    NSString *username = currentUser.username;

    NSURL *url = [GDataServiceGoogleYouTube youTubeUploadURLForUserID:username];

    // load the file data
    NSString *path;
#if !TARGET_IPHONE_SIMULATOR
    path = self.videoPath;
#else
    path = [[NSBundle mainBundle] pathForResource:@"Movie" ofType:@"m4v"];;
#endif
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSString *filename = [path lastPathComponent];

    // gather all the metadata needed for the mediaGroup
    NSString *titleStr = self.trick;
    GDataMediaTitle *title = [GDataMediaTitle textConstructWithString:titleStr];

    NSString *categoryStr = @"SSB";
    GDataMediaCategory *category = [GDataMediaCategory mediaCategoryWithString:categoryStr];
    [category setScheme:kGDataSchemeYouTubeCategory];

    NSString *descStr = self.description;
    GDataMediaDescription *desc = [GDataMediaDescription textConstructWithString:descStr];

    NSString *keywordsStr = @"SuperShredBros";
    GDataMediaKeywords *keywords = [GDataMediaKeywords keywordsWithString:keywordsStr];

    BOOL isPrivate = NO;

    GDataYouTubeMediaGroup *mediaGroup = [GDataYouTubeMediaGroup mediaGroup];
    [mediaGroup setMediaTitle:title];
    [mediaGroup setMediaDescription:desc];
    [mediaGroup addMediaCategory:category];
    [mediaGroup setMediaKeywords:keywords];
    [mediaGroup setIsPrivate:isPrivate];

    NSString *mimeType = [GDataUtilities MIMETypeForFileAtPath:path
                                               defaultMIMEType:@"video/mp4"];

    // create the upload entry with the mediaGroup and the file
    GDataEntryYouTubeUpload *entry;
    entry = [GDataEntryYouTubeUpload uploadEntryWithMediaGroup:mediaGroup
                                                          data:data
                                                      MIMEType:mimeType
                                                          slug:filename];

    SEL progressSel = @selector(ticket:hasDeliveredByteCount:ofTotalByteCount:);
    [service setServiceUploadProgressSelector:progressSel];

    GDataServiceTicket *ticket;
    ticket = [service fetchEntryByInsertingEntry:entry
                                      forFeedURL:url
                                        delegate:self
                                        didFinishSelector:@selector(uploadTicket:finishedWithEntry:error:)];

    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    [self.navigationController.view addSubview:HUD];
    HUD.delegate = self;
    HUD.mode = MBProgressHUDModeDeterminate;
    HUD.labelText = @"Uploading...";

    [self setUploadTicket:ticket];
}

If anyone has any insight into this problem that would be very helpful.
Thanks,
Anthony

A: The message is from GDataServiceBase.m.  It indicates that the class GTMHTTPUploadFetcher is not linked in to your application.
The class may be missing due to the class file not being linked in the debug or release build target, or due to the preprocessor define GDATA_INCLUDE_YOUTUBE_SERVICE not being set, as described under "Removing Unneeded Code" at http://code.google.com/p/gdata-objectivec-client/wiki/BuildingTheLibrary

A: Yeah, it seemed to be a linking issue. I followed the instructions on that link to compile directly into my code and removed the classes I didn't need such as googledocs. Once I did that, everything built fine and I was able to upload.
Thanks for the help.


text:
Q: Transition Animations between Activities wont be displayed I'm using this to override the transiting animation between two activities. At first it worked properly but now, the animation won't be displayed, though it was a problem with current project so I started a new one and the same thing happens. Is this a thing caused by my device? it is a samsung galaxy S advance with 2.3.6 android. Thank you in advance
this is the code on the activity that is started:
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity2);

}

and this is the first Activty that calls the second, I've just put the override immediately after startActivity and it won't work either.
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button = (Button) findViewById(R.id.button1);

    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(MainActivity.this,Activity2.class);
            startActivity(intent);
            overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);

        }
    });
}

A:
HI , Make sure following step is true for your device :

Settings->Display->Animations and select "All Animations"

A: overridePendingTransition:

Call immediately after one of the flavors of startActivity(Intent) or finish() to specify an explicit transition animation to perform next.

A: You need to keep your overridepending() code after starting a new intent. Also enable all animations in settings otherwise those animations wont be displayed.
overridePendingTransition(android.R.anim.slide_in_left,android.R.anim. slide_in_left);

change the above to
overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_in_left);

why do you keep both animations as one.try different xml