text:
Q: Trace of a Sobolev-Function near the boundary when shrinking tubes Let $\Omega\subset\mathbb{R}^n$ be  a bounded Lipschitz domain,  $\delta>0$ and $x_0\in\partial\Omega$ fixed. Moreover let $Q_\delta(x_0)$ be a cube with sidelength $\delta$ around $x_0$ and define for $s>0$ the set $\Omega_s =  \{x\in\Omega: \mathrm{dist}(x,\partial\Omega)>s\}$. Now I expect/hope that something like
$$
\lim_{s\to0} \,\frac{1}{\mathcal{L}^n(Q_\delta(x_0)\cap(\Omega\setminus\Omega_s)}\int_{Q_\delta(x_0)\cap(\Omega\setminus\Omega_s)}u(y)\, \mathrm{d}y = \frac{1}{\mathcal{H}^{n-1}(Q_\delta(x_0)\cap\partial\Omega)}\int_{Q_\delta(x_0)\cap\partial\Omega}\mathrm{tr}(u)\mathrm{d}\mathcal{H}^{n-1}
$$
should hold for $u\in W^{1,1}(\Omega)$, but at the moment I'm not able to prove it. $\mathcal{L}^n$ and $\mathcal{H}^{n-1}$ denote the Lebesgue and the Hausdorff-measure respectively.  First I want to sketch why I think this should be true:

*

*If I take a smooth function $g\in C^ \infty(\overline{\Omega})\cap W^{1,1}(\Omega)$ one can apply a consequence of the coarea-formula, namely the integration over level sets (e.g. Evans-Gariepy, Measure Theory and Fine Properties of Functions- Theorem 3.11) to get that $g|_{\mathrm{dist}^{-1}(\xi)}$ is $\mathcal{H}^{n-1}$-summable for $\mathcal{L}^1$-a.e. $\xi$ and
$$
\int_{\Omega\setminus\Omega_s} g\,\mathrm{d}x = \int_0^s \int_{\mathrm{dist}^{-1}(\xi)}g(y)\,\mathrm{d}\mathcal{H}^{n-1}(y) \,\mathrm{d}\xi
$$
where we have used that the distance function is 1-Lipschitz with Jakobian equals 1 a.e. (for details I have consulted Theorem 3.14 in the same book). In this situation I can apply Lebesgue-differentiation theorem to get the claimed result (For a smooth function every point is a Lebesgue-Point).

*Now my idea was use a approximation sequence $(u_k)_{k\in\mathbb{N}}$ in $C^ \infty(\overline{\Omega})\cap W^{1,1}(\Omega)$ for $u\in W^{1,1}(\Omega)$. For such a sequence we know by continuity of the trace operator that $\mathrm{tr}(u_k)=u_k|_{\partial\Omega} \to \mathrm{tr}(u)$ in $L^1(\partial\Omega,\mathcal{H}^{n-1})$ as $k\to\infty$. At this point I don't have a idea how to argue, that I can interchange limits (if this is even possible?), more precisely I stop at
$$
\lim_{k\to\infty}\,\lim_{s\to0} \,\frac{1}{\mathcal{L}^n(Q_\delta(x_0)\cap(\Omega\setminus\Omega_s)}\int_{Q_\delta(x_0)\cap(\Omega\setminus\Omega_s)}u_k(y)\, \mathrm{d}y = \frac{1}{\mathcal{H}^{n-1}(Q_\delta(x_0)\cap\partial\Omega)}\int_{Q_\delta(x_0)\cap\partial\Omega}\mathrm{tr}(u)\mathrm{d}\mathcal{H}^{n-1}.
$$

*Another idea: One could conclude as above if we would have better regularity of the map
$$
\xi \mapsto \int_{\mathrm{dist}^{-1}(\xi)}u(y)\,\mathrm{d}\mathcal{H}^{n-1}(y)
$$
I think continuity should be enough (or that 0 is a Lebesgue-point). What can we say about the regularity using e.g. the fact $u\in W^{1,1}(\Omega)$? If the mapping would be $W^{1,1}$ one could use the fact, that we have already absolute continuity.

I'm happy about every comment, idea, reference request (maybe such a question has been already treated in the literature) or even some counterexample. Thanks a lot in advance.


text:
Q: Using a number calculated by a macro as a p{} column width within tabular I'm currently trying to create a tabular that dynamically adjusts to some inserted text. For that, I've written this code:
\documentclass{article}
\def\lengthof#1{%
    \setbox0\hbox{#1}%
    \the\wd0%
}

\begin{document}
\begin{tabular}{p{\lengthof{Some Text}}} Some Text \end{tabular}
\end{document}

For some reason, this doesn't compile correctly (it gives me the "Missing number, treated as zero" and "Illegal unit of measure" error codes). This is quite strange, because the lengthof-macro itself works without a problem. What am I doing wrong? I suspect that this has either something to do with expansion order or modes, but I'm unable to figure it out.
(Please note that I am well aware that there are packages which solve this problem, but I want to understand this without a package to get a better understanding of how TeX works internally.)

A: the p{argument} expands to \hsize=argument, so in your case:
\hsize=\setbox0\hbox{#1}\the\wd0

but this is syntactically wrong, because \setbox is unexpandable TeX primitive and TeX expects a dimen at this point. But, if your macro is intended only for usage in p argument, then you can define it by:
\def\lengthof#1{%
    \hsize
    \setbox0\hbox{#1}%
    \hsize=\wd0
}

Now, the p{\lengthof{abc}} expands to
\hsize=\hsize \setbox0\hbox{#1}\hsize=\wd0

and this is OK and creates desired result.
The same trick can be used in OpTeX.

A: No need to reinvent the wheel:
\documentclass{article}

\usepackage{calc}

\begin{document}
\begin{tabular}{|p{\widthof{Some Text}}|} Some Text \\ some longer text\end{tabular}
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: PhantomJS javascript wait until function complete I have a problem with a PhantomJS script. The script gets a JSON encoded string from a web page and does other things with it. The script:
var address = address;
var amount = 0;

function changeAmount()
{
   var page=require('webpage').create();
   page.open (address, function(){
     //parse json, set amount to something (usually 4)
     amount = 4;
  });
}

changeAmount();
console.log(amount); //prints 0

//Do stuff with amount

phantom.exit(); //amount not changed yet.

How can I check if the changeAmount function is finished before going forward? Timeout is not possible since I don't know the time it takes to process the changeAmount.

A: You can use a callback, like so:
function changeAmount(callback) {
    var page=require('webpage').create();
    page.open (address, function () {
        //parse json, set amount to something (usually 4)
        amount = 4;
        callback();
    });
}

changeAmount(function () {
    // This function runs when callback() (above) is reached
    console.log(amount);

    //Do stuff with amount

    phantom.exit();
});

And if you're not using the amount variable elsewhere, you could eliminate it by passing it as an argument to the callback:
changeAmount(function (amount) {

and then
callback(amount); // or callback(4);

A: page.open() is an inherently asynchronous function. The only reliable way to do this is to use callbacks in the PhantomJS script:
var address = address;

function changeAmount(callback)
{
   var page = require('webpage').create();
   page.open (address, function(){
     //parse json, set amount to something (usually 4)
     var amount = 4;
     callback(amount);
  });
}

You can even go as far as passing amount into that callback to remove the global variable.
After that, you will need to write your script using that callback pattern.
changeAmount(function(amount){
    console.log(amount);

    //Do stuff with amount

    phantom.exit();
});

Furthermore, you probably shouldn't create a new page every time you call changeAmount() (if you do this repeatedly). You can reuse the same page. If you think that creating a new page gives you a fresh environment to work in, then you're mistaken. It is just like a new tab. It will use the same session as all the other pages that you have created.
If you do this often, this will lead to a memory leak, because you're not closing the previously opened pages.


text:
Q: How can I remove slashes from strings? I am trying to do some PHP programming concepts and I am not aware of some in-build functions. So my doubt is:
In PHP, how to remove slashes from strings? Is there any function available in PHP for this??
e.g.
$string="people are using Iphone/'s instead of Android phone/'s";

A: backslashes need escaping
$newstr = "
Hello \ fred
";

echo str_replace('\\','',$newstr);

A: You can do a number of things here, but the two approaches I would choose from are:
Use str_replace():
$string = "people are using Iphone/'s instead of Android phone/'s";
$result = str_replace('/','',$string);
echo $result;
// Output: people are using Iphone's instead of Android phone's

If the slashes are backward slashes (as they probably are), you can use stripslashes():
$string = "people are using Iphone\\'s instead of Android phone\\'s";
$result = stripslashes($string);
echo $result;
// Output: people are using Iphone's instead of Android phone's

A: If it is a quoted string. Use stripslashes

A: you can use function like
 $string = preg_replace ("~/~", "", $string);

A: Heres what I use
function removeSlashes($string = '')
{
    return stripslashes(str_replace('/', '', $string));
}

Test
echo $this->removeSlashes('asdasd/asd/asd//as/d/asdzfdzdzd\\hd\h\d\h\dw');

Output
asdasdasdasdasdasdzfdzdzdhdhdhdw

A: Use varian preg
$string="people are using Iphone/'s instead of Android phone/'s";

echo $string = preg_replace('/\//', '', $string);

body, html, iframe {
  width: 100% ;
  height: 100% ;
  overflow: hidden ;
}

A: I tried this method to remove single forward slashes.
I used str_replace to strip the slashes out. It still did not work for me, I had to go and change all the double quotes in the database to single quotes, update the table, then change it back to double quotes for it to work. Weird.
str_replace('\\', '', $content)

A: You can use stripslashes() function.
<?php
$str = "Is your name O\'reilly?";

// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>


text:
Q: How to draw multiple lines in a line chart drwan using PHP, MySQL and Google Charts tool? I'm using Google Charts tool to draw the line chart. I'm fetching data from MySQL databse and depending upon that data I'm drawing the line chart. I want to draw four such lines representing individual data series. If I draw a single line chart then it's working perfectly but when it comes to more than one lines the issue is coming in. I'm showing my PHP code below:
<?php
  $con=mysql_connect("localhost","root","eywaadmin") or die("Failed to connect with database!!!!");
  mysql_select_db("OCN", $con);
  // The Chart table contains two fields: registration dates and respective no. of registraions on that date

  if($_GET['to_date']!='' && $_GET['from_date']!='' && $_GET['type']!='') {

      list($fd, $fm, $fy) = explode('/', $_GET['from_date']);
      list($td, $tm, $ty) = explode('/', $_GET['to_date']);
    $mk_from_time = mktime (0, 0, 0, $fm, $fd, $fy);
    $mk_to_time   = mktime (0, 0, 0, $tm, $td, $ty);

    $transaction_types = array();
    $transaction_types = explode(',', $_GET['type']);

    if (in_array("all",$transaction_types)) {
      $sth_all  = mysql_query("SELECT transaction_date as TDate, count(*) as cnt FROM user_transaction WHERE transaction_date >= ".$mk_from_time." AND transaction_date <=".$mk_to_time." group by date_format(from_unixtime(transaction_date),'%b %d, %Y'), transaction_status order by transaction_date");
    }

    if(in_array("success",$transaction_types)) {
      $sth_success  = mysql_query("SELECT transaction_date as TDate, count(*) as cnt FROM user_transaction WHERE transaction_date >= ".$mk_from_time." AND transaction_date <=".$mk_to_time." AND transaction_status = 'success' group by date_format(from_unixtime(transaction_date),'%b %d, %Y'), transaction_status order by transaction_date");
    }

    if(in_array("inprocess",$transaction_types)) {
      $sth_inprocess  = mysql_query("SELECT transaction_date as TDate, count(*) as cnt FROM user_transaction WHERE transaction_date >= ".$mk_from_time." AND transaction_date <=".$mk_to_time." AND transaction_status = 'inprocess' group by date_format(from_unixtime(transaction_date),'%b %d, %Y'), transaction_status order by transaction_date");
    }

    if(in_array("cancelled",$transaction_types)) {
      $sth_cancelled  = mysql_query("SELECT transaction_date as TDate, count(*) as cnt FROM user_transaction WHERE transaction_date >= ".$mk_from_time." AND transaction_date <=".$mk_to_time." AND transaction_status = 'cancelled' group by date_format(from_unixtime(transaction_date),'%b %d, %Y'), transaction_status order by transaction_date");
    }
  }

$rows  = array();
//flag is not needed
$flag  = true;
$table = array();
$table['cols'] = array(
// Labels for the chart to represent the column titles
// One column is in "string" format and another one is in "number" format as line chart only required "numbers" for and string will be used for column title
    array('label' => 'Transaction Date', 'type' => 'string'),
    array('label' => 'All Transactions', 'type' => 'number'),
    array('label' => 'Successful Transactions', 'type' => 'number'),
    array('label' => 'Inprocess Transactions', 'type' => 'number'),
    array('label' => 'Cancelled Transactions', 'type' => 'number')
);

if (in_array("all",$transaction_types)) {
  //First Series
  $rows = array();

  while($r =  mysql_fetch_assoc($sth_all)) {
    $temp = array();
    // the following line will be used to draw the Line chart
    $temp[] = array('v' => gmdate("d/m/Y", $r['TDate']));

    // Values of each point
    $temp[] = array('v' => (int) $r['cnt']);

    $rows[] = array('c' => $temp);
  }

  $table['rows'] = $rows;

  $jsonTable = json_encode($table);
  //echo $jsonTable;
}

if(in_array("cancelled",$transaction_types)) {
  //Second Series
  $rows = array();

  while($r =  mysql_fetch_assoc($sth_cancelled)) {
    $temp = array();
    // the following line will be used to draw the Line chart
    $temp[] = array('v' => gmdate("d/m/Y", $r['TDate']));

    // Values of each point
    $temp[] = array('v' => (int) $r['cnt']);

    $rows[] = array('c' => $temp);
  }

  $table['rows'] = $rows;

  $jsonTable1 = json_encode($table);
  //echo $jsonTable1;
}

if(in_array("success",$transaction_types)) {
  //Third Series
  $rows = array();

while($r =  mysql_fetch_assoc($sth_success)) {
    $temp = array();
    // the following line will be used to draw the Line chart
    $temp[] = array('v' => gmdate("d/m/Y", $r['TDate']));

    // Values of each point
    $temp[] = array('v' => (int) $r['cnt']);

    $rows[] = array('c' => $temp);
  }

  $table['rows'] = $rows;

  $jsonTable2 = json_encode($table);
  //echo $jsonTable2;
}

if(in_array("inprocess",$transaction_types)) {
  //Fourth Series
  $rows = array();
  while($r =  mysql_fetch_assoc($sth_inprocess)) {
    $temp = array();
    // the following line will be used to draw the Line chart
    $temp[] = array('v' => gmdate("d/m/Y", $r['TDate']));

    // Values of each point
    $temp[] = array('v' => (int) $r['cnt']);

    $rows[] = array('c' => $temp);
  }
  $table['rows'] = $rows;

  $jsonTable3 = json_encode($table);
  //echo $jsonTable3;
}
?>

The URL I'm hitting to run this page is
http://localhost/registration_chart/transaction_stats.php?to_date=27/6/2013&from_date=1/10/2002&type=all,cancelled,inprocess,success

Can anyone help me out in drawing all the four lines on a line chart? Thanks in Advance. If you want I can provide the screenshot of a single line drawn on the line chart.

A: For one thing, you're referencing data2 and data3, but never setting them.  You have three var data1 statements in a row.
Update: I think that unless there is an undocumented concat method of DataTable that merges in the data from other DataTable instances, you're going to need to either implement such a function yourself or create the merged constructor argument in your php code. I'm not sure why the .concat call isn't raising an error, though. Perhaps the DataTable instance is an array.


text:
Q: MYSQL Trigger recursion avoidance I have a general AFTER UPDATE trigger for my users table to check if a column has changed, and if so, call a stored procedure.
The problem is the stored procedure does some calculations and itself updates a field in users.
How do I avoid the recursion if my stored procedure updates the users table, which invokes the trigger, which again invokes the stored procedure?
Thanks!

A: MySQL doesn't let you disable triggers (without dropping and recreating them), but you have a couple of options:

*

*Don't update the users table from within the procedure.

*Add a field to the users that the procedure would set to a specific value on update. When the trigger sees that value for that field, don't call the procedure.

*Use a global variable to accomplish the above (NOT connection safe - will disable triggers for all connections).


text:
Q: Opencart images not showing after manual import I have the following problem - I am migrating website database from other platform to Opencart.
When I imported the images in oc_product using PHP, they are not showing in the website. The real issue is that if I manually change or type the image path, it works. Maybe it's some cache problem, but I cannot figure out why.
The images are not showing even in the admin panel - attaching picture
Here is also how my database look like - the image path is correct
My Opencart version is 1.5.6.4
Any ideas?

A: obviously, the image path differs for the images, when we import and thus the imagepath has to be taken care before we actually import the data.And after importing then we have to run a sql query to change the imagepath in the database.

A: In the question you mention an import step performed using php.
I'm doing a wild guess but maybe that for whatever reason some unprintable character has been added and is messing up the whole thing.
The easiest way to check if this is the case is to analyze the html produced to verify if there is anything odd in the img tag path.
Another quick check is to export a few rows of data that are currently acting weird and analyze the content with a smart (that show special chars) text editor.


text:
Q: An explicit formula for characteristic polynomial of matrix tensor product Consider two polynomials P and Q and their companion matrices. It seems that char polynomial of tensor product of said matrices would be a polynomial with roots that are all possible pairs product of roots of P,Q.
I guess its coefficients could be expressed through coefficients of P and Q.
But I don't know the explicit formula and I cannot find it. I also failed to find it out myself -- I tried different approaches. Maybe it should be that characteristic polynomial, maybe resultant of some form, but..
I hope this is done by someone already.
I'll try to give an example
$c_0 = a_0^nb_0^m$, or maybe $c_0 = (-1)^{n+m}a_0^nb_0^m$ ($m,n$ are the degrees of $P and Q$.
$c_1 = a_0^{n-1}a_1b_0^{m-1}b_1$, this is one is probably incorrect, but I obviously cannot provide the correct answer if I don't know it yet.
It looks like $c_i$ is a sum of some sort.


text:
Q: Suppress red lines in Eclipse I am getting some red lines (most probably the log) while I am running Eclipse program.
Can anyone tell how can I suppress them. I tried to Google it but could not find the solution.

A: By default if a program writes to stdout using System.out.* methods the output is black in Eclipse. For stderr (System.err.*) Eclipse uses red. Are you saying you don't want to see stuff printed to stderr? I'm not sure this would be a wise idea...
The settings for the console btw are controlled by Window -> Preferences -> Run/Debug -> Console.


text:
Q: Configure the automatic password while taking the Database backup from SQL Server I received one requirement from client,if any take the database backup from SQL Server, backup will by default contains the password.
so No One can restore the database without password.
I suggests the TDE encryption solution but he is not agree with this.
anyone one know, Is there any SQL setting for this?
Thanks
Nirav

A: IDK if there is any built-in option (except TDE). We are using WinRAR for similar purpose :
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
DECLARE @fileName varchar(1000)
DECLARE @pathName varchar(1000)
DECLARE @backupName varchar(1000)
DECLARE @backupFullName varchar(1000)
DECLARE @rarName varchar(1000)
DECLARE @compressCommand varchar(1000)
DECLARE @deleteBakCommand varchar(1000)
DECLARE @deleteRarCommand varchar(1000)
DECLARE @moveCommand varchar(1000)
DECLARE @deleteOldRarCommand varchar(1000)

SET @fileName = 'database' + CONVERT(varchar, DATEPART(weekday,getdate()))
set @pathName = 'D:\folder\'
SET @backupName = @fileName + '.bak'
SET @rarName = @fileName + '.rar'
SET @backupFullName =@pathName + @backupName
SET @compressCommand = 'C:\Progra~1\WinRAR\rar a -m5 -pPASSWORD '+ @pathName + @rarName + ' ' + @pathName+@backupName + '"'
SET @deleteBakCommand = 'del ' +   @pathName + @backupName
SET @deleteRarCommand = 'del ' +   @pathName + @rarName
SET @deleteOldRarCommand = 'del ' +   @pathName + 'TARGET\db\' +  @rarName
set @moveCommand = 'copy /y ' + @pathName+@rarName + ' ' + @pathName + 'TARGET\db\' + @rarName

EXEC master..xp_cmdshell @deleteBakCommand;
EXEC master..xp_cmdshell @deleteRarCommand;
BACKUP DATABASE DBNAME TO DISK = @backupFullName;

EXEC master..xp_cmdshell @deleteOldRarCommand;
EXEC master..xp_cmdshell @compressCommand;
EXEC master..xp_cmdshell @deleteBakCommand;
EXEC master..xp_cmdshell @moveCommand;
EXEC master..xp_cmdshell @deleteRarCommand;

GO
EXEC sp_configure 'xp_cmdshell', 0


text:
Q: Finding if a multidimensional array is within an array Java I have an array of arrays - similar to this:
import java.util.Arrays;

public class test {
    public static void main(String[] args)
    {

        String[][] A = { { "a", "b", "c" }, { "d", "e", "f" }, { "g", "h", "-" } };
        String[][] B = { { "-", "e", "b" }, { "a", "h", "c" }, { "d", "g", "f" } };
        String[][] C = { { "a", "b", "c" }, { "d", "e", "f" }, { "g", "h", "-" } };
        String[][][] myArray = { A, B};

        for (String[][] s : myArray) {
            System.out.println(Arrays.deepToString(s));
            if (Arrays.deepToString(s).equals(Arrays.deepToString(C))) {
                System.out.println("true");
            }
        }
    }
}

I need to check if a value is in the array, however, this is the only method I have found to work and it is very inefficient.
Is there a better way to do this since most built-in methods do not appear to work?
I also tried to use a Set and that had the same issues.

A: This is easy: never convert to strings. Try deepEquals it should do what you want, although you of course first have to dive into your myArray and iterate over the elements.
public static boolean contains(String[][][] set, String[][] obj) {
    for (String[][] elt : set) {
        if (Arrays.deepEquals(elt, obj)) {
            return true;
        }
    }
    return false;
}

This performs the contains function for your test set in about 4.5% of the time.

Java has type erasure when it comes to arrays over objects (including other arrays). As such it may be slightly faster to create deepEquals(String[][], String[][]) yourself where you use Arrays.equals(String[], String[]), as you would not have to check if the objects are arrays of String at runtime, nor would you have to check if there are any arrays nested even deeper.
public static boolean fasterContains(String[][][] set, String[][] obj) {
    for (String[][] elt : set) {
        if (deepEquals(elt, obj)) {
            return true;
        }
    }
    return false;
}

private static boolean deepEquals(String[][] a, String[][] b) {
    int n = a.length;
    if (b.length != n) {
        return false;
      }

     for (int i = 0; i < n; i++) {
        if (!Arrays.equals(a[i], b[i])) {
            return false;
        }
    }
    return true;
}

This performs the contains function for your test set in about 3.5% of the time, while being only slightly more complex than the test above.

As a general hint: computers are not efficient when it comes to Strings (although newer Java versions did address this somewhat). Anyway, never convert to string for any comparison, calculation, concatenation or whatnot. Always compare bytes, integers or objects (i.e. the original data) unless there is really no other way.

If you just have a list of characters then there are two observations:

*

*char[][] should also work;

*or just a String[] of course, where the String consist of the various characters (which you can retrieve using String#charAt(index) and compare using String#equals(other).

With the latter you can bring down the search time to about 2%.

A: Another way would be to store/hash your arrays as StringBuilder and compare it with the StringBuilder formed in the multidimentional array.
StringBuilder is faster for String operations compared to String. Here is the code:
import java.util.Arrays;

public class test {
    public static void main(String[] args)
    {

        String[][] A = { { "a", "b", "c" }, { "d", "e", "f" }, { "g", "h", "-" } };
        String[][] B = { { "-", "e", "b" }, { "a", "h", "c" }, { "d", "g", "f" } };
        String[][] C = { { "a", "b", "c" }, { "d", "e", "f" }, { "g", "h", "-" } };
        String[][][] myArray = { A, B};
        StringBuilder str = new StringBuilder();
        StringBuilder str1 = new StringBuilder();
        for(String[] ss : C){
            for(String s : ss){
                for(char p : s.toCharArray()){
                            str1.append(p);
                        }
            }
        }
        String cc = str1.toString();
        for(String[][] s : myArray){
            for(String[] ss : s){
                for(String sss : ss){
                    for(char p : sss.toCharArray()){
                        str.append(p);
                    }
                    if(str.toString().equals(cc)){
                        System.out.println("true");
                    }
                }
            }
        }

    }
}


text:
Q: Show that $\int^{\infty}_{0}\frac{x^{p - 1}\ln\left(x\right)}{1 + x}\,{\rm d}x=-\pi^{2}\csc\left(p\pi\right)\cot\left(p\pi\right)$.
$$
\mbox{Show that}\quad
\int^{\infty}_{0}{x^{p - 1}\ln\left(x\right) \over 1 + x}
=-\pi^{2}\csc\left(p\pi\right)\cot\left(p\pi\right)
$$

$$
\mbox{I guess I have to use the fact that}\quad
\int^{\infty}_{0}{x^{p - 1} \over 1 + x}
=\pi\csc\left(p\pi\right),\quad\mbox{please give me some idea.}
$$

Thank you.

A: Lest the question remain unanswered:
We have
$$\int_0^\infty \frac{x^{p-1}\ln x}{1+x}\,dx = \int_0^\infty \frac{d}{dp}\frac{x^{p-1}}{1+x}\,dx = \frac{d}{dp} \int_0^\infty \frac{x^{p-1}}{1+x}\,dx$$
for $0 < p < 1$, since the dominated convergence theorem guarantees that differentiation under the integral is legitimate.
And
$$\frac{d}{dp} \frac{\pi}{\sin (p\pi)} = - \frac{\pi^2\cos (p\pi)}{\sin^2 (p\pi)} = -\pi^2\csc (p\pi)\cot (p\pi).$$


text:
Q: Ada: public and private part of specification separated? I learned that there is a public part and a private part in an Ada specification file (*.ads) and only the public part should be considered of the user of the compilation unit (usually a package).
It is actually not usual to separate the public and private part of the specification in different files?
So, finally, the user of such a package knows about the internals of the packages on specification layer but can not use it. Am I right here?
Thanks and cheers,
Wolfgang

A: No, Ada does not allow you to separate the public and private part of a package specification.
The original chief designer of Ada, Jean Ichbiah, did some work on a language, which actually separated the public, private (data structure) and implementation parts of a package, but this didn't become a part of Ada.
Also:

*

*The private part and body of a child package can see the private part of its parent.

*The specification of a private child package can see the private part of its parent.

... so you can't always just ignore the private part of a package specification completely.
A practical example:
When I write unit-tests, I like to put the test suite in a child package of the package I am testing.  That way my test cases are not limited to inspect the public view of the types declared in the package.


text:
Q: Java DAO Generics I am using generics to build a DAO. The database could be any database. The problem is that for each type of class there is a specific class. For example:
public class DAO<T> {

    public void save(T entity) {

     }
}

public class StudentDAO extends DAO<Student> {

}

Just imagine I have 1000 tables or more. Do I need to have 1000 classes like this? Is there a better way to design this?
Edit
I am using MongoDB a NoSQL database with Spring MongoDB. It has Repository concept through Spring but I will still end up with 1000 classes. I cannot use JPA or Hibernate. Any other solution?

A: You can do it. But I'd recommend you to use Generic Dao project. It supports both native Hibernate and JPA API and allows you to create one and only one DAO for all entities you have.

A: You don't have to extend DAO class. I assume DAO constructor has a parameter to detect which entity and which table it should interact with. Something like this:
public DAO(Class<T> type) {
    this.persistentType = type;
}

With such constructor, wherever you need a DAO instance for Student entity you can initialize it like this:
DAO<Student> studentDao = new DAO<Student>(Student.class);

A: Yes there is definitely a better way. What you bumped into is what I call the "DAO-per-entity scalability issue". What you need for that is a reusable Generic DAO implementation e.g. PerfectJPattern
 IGenericDao<Long, Customer> myCustomerDao = HibernateDaoFactory.getInstance().createDao(Customer.class);
 // create a Customer
 Customer myCustomer1 = new Customer(/*name=*/"Pedro");
 myCustomerDao.create(myCustomer1);
 // find all customers whose name is "Juan"
 List<Customer> myMatches = myCustomerDao.findByExample(new Customer(/*name=*/"Juan"));

what just happened here? you don't need to create a new CustomerDao but reuse the generic one. In addition to the basic CRUD, you may even cover 90% of your "finder" needs using the findByExample see IGenericReadOnlyDao.
If the findByExample does not cover all your needs then you have the choice to use the Spring level Generic DAO, example here that offers direct mapping from SQL to your DAO interface and you don't need to provide an implementation.

A: Consider Spring Data , which will generate DAO layer for you.

A: You consider use hibernate + spring


text:
Q: Does pouchdb leave deleted tombstones like couchdb does? I have a hybrid app that generates a lot of tombstones on couchdb.  About 100,000 a month on the server.  Each user should be getting about 4 a day.
Does Pouchdb maintain tombstones? Or do they get compacted or purged?  Or is there a command to do that? Or do I have to drop the database and recreate periodically?
Thanks

A: Pouchdb does keep a tombstone when deleting a document.
Purge is not available yet for PouchDB so the only way to completely deletes documents is by deleting the local database.


text:
Q: Getting all constants within a class in python I have a class which is essentially used to define common constants for other classes.  It looks something like the following:
class CommonNames(object):
    C1 = 'c1'
    C2 = 'c2'
    C3 = 'c3'

And I want to get all of the constant values "pythonically".  If I used CommonNames.__dict__.values() I get those values ('c1', etc.) but I get other things such as:
<attribute '__dict__' of 'CommonNames' objects>,
<attribute '__weakref__' of 'CommonNames' objects>,
None ...

Which I don't want.
I want to be able to grab all the values because this code will be changed later and I want other places to know about those changes.

A: If you're trying to use Martijn example in python3, you should use items() instead of iteritmes(), since it's deprecated
[value for name, value in vars(CommonNames).items() if not name.startswith('_')]

A: You'll have to filter those out explicitly by filtering on names:
[value for name, value in vars(CommonNames).iteritems() if not name.startswith('_')]

This produces a list of values for any name not starting with an underscore:
>>> class CommonNames(object):
...     C1 = 'c1'
...     C2 = 'c2'
...     C3 = 'c3'
...
>>> [value for name, value in vars(CommonNames).iteritems() if not name.startswith('_')]
['c3', 'c2', 'c1']

For enumerations like these, you'd be better of using the enum34 backport of the new enum library added to Python 3.4:
from enum import Enum

class CommonNames(Enum):
    C1 = 'c1'
    C2 = 'c2'
    C3 = 'c3'

values = [e.value for e in CommonNames]


text:
Q: Entity Framework 7 creates an unneeded alternate key I have two simple classes using Entity Framework 7, everything is working fine on all classes, except one case where Entity Framework generates a new alternate key with same name as already existing column.
Invoice.cs
namespace Arinsys.Accounts
{
    [Table(name: "Invoice", Schema = "Arinsys_Accounts")]
    public class Invoice
    {
        public long ID { get; set; }
        public string InvoiceID { get; set; }
        public long? CustomerUID { get; set; }
        public long? EmployeeUID { get; set; }
        public DateTime BillDateTime { get; set; }
        public long Amount { get; set; }
        public long? Discount { get; set; }
        public string DiscountReason { get; set; }
        public string CouponID { get; set; }
        public long Charges { get; set; }
        public string ChargesReason { get; set; }
        public long Tax { get; set; }
        public string TaxType { get; set; }
        public long FinalAmount { get; set; }
        public string Status { get; set; }
        public string Remarks { get; set; }

        [ForeignKey("CustomerUID")]
        public virtual CRM.User Customer { get; set; }
        [ForeignKey("EmployeeUID")]
        public virtual CRM.User BilledBy { get; set; }

        public virtual ICollection<InvoiceItems> Items { get; set; }
        public virtual ICollection<Payments> Payments { get; set; }
    }
}

Generated Invoice table code
CREATE TABLE [Arinsys_Accounts].[Invoice] (
    [ID]             BIGINT         IDENTITY (1, 1) NOT NULL,
    [Amount]         BIGINT         NOT NULL,
    [BillDateTime]   DATETIME2 (7)  NOT NULL,
    [Charges]        BIGINT         NOT NULL,
    [ChargesReason]  NVARCHAR (MAX) NULL,
    [CouponID]       NVARCHAR (MAX) NULL,
    [CustomerUID]    BIGINT         NULL,
    [Discount]       BIGINT         NULL,
    [DiscountReason] NVARCHAR (MAX) NULL,
    [EmployeeUID]    BIGINT         NULL,
    [FinalAmount]    BIGINT         NOT NULL,
    [InvoiceID]      NVARCHAR (MAX) NOT NULL,
    [InvoiceID1]     NVARCHAR (450) NOT NULL,
    [Remarks]        NVARCHAR (MAX) NULL,
    [Status]         NVARCHAR (MAX) NULL,
    [Tax]            BIGINT         NOT NULL,
    [TaxType]        NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_Invoice] PRIMARY KEY CLUSTERED ([ID] ASC),
    CONSTRAINT [AK_Invoice_InvoiceID1] UNIQUE NONCLUSTERED ([InvoiceID1] ASC),
    CONSTRAINT [FK_Invoice_User_CustomerUID] FOREIGN KEY ([CustomerUID]) REFERENCES [Arinsys_CRM].[User] ([ID]),
    CONSTRAINT [FK_Invoice_User_EmployeeUID] FOREIGN KEY ([EmployeeUID]) REFERENCES [Arinsys_CRM].[User] ([ID])
);

InvoiceItems.cs
namespace Arinsys.Accounts
{
    [Table(name: "InvoiceItems",Schema = "Arinsys_Accounts")]
    public class InvoiceItems
    {
        public long ID { get; set; }
        public string InvoiceID { get; set; }
        public string ItemID { get; set; }
        public int Quantity { get; set; }
        public int Price { get; set; }
        public int Discount { get; set; }
        public string Reason { get; set; }
        public int Amount { get; set; }
        public string Remarks { get; set; }

        [ForeignKey("InvoiceID")]
        public virtual Invoice Invoice { get; set; }

    }
}

Generated InvoiceItems table code
CREATE TABLE [Arinsys_Accounts].[InvoiceItems] (
    [ID]        BIGINT         IDENTITY (1, 1) NOT NULL,
    [Amount]    INT            NOT NULL,
    [Discount]  INT            NOT NULL,
    [InvoiceID] NVARCHAR (450) NULL,
    [ItemID]    NVARCHAR (MAX) NULL,
    [Price]     INT            NOT NULL,
    [Quantity]  INT            NOT NULL,
    [Reason]    NVARCHAR (MAX) NULL,
    [Remarks]   NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_InvoiceItems] PRIMARY KEY CLUSTERED ([ID] ASC),
    CONSTRAINT [FK_InvoiceItems_Invoice_InvoiceID] FOREIGN KEY ([InvoiceID]) REFERENCES [Arinsys_Accounts].[Invoice] ([InvoiceID1])
);

Notice the InvoiceID1 column in Invoice Table, it's created automatically, and I don't require it. Since these models are in a library i.e. they are just like templates, actual dbcontext will be in the application and i don't want the end developer to be worried with these things, so fluent API in
OnModelCreating is not an option.
As to the next obvious question, how will we manage the references, the overall structure and interfaces are designed in such a way that it's taken care of. Anyways that discussion will go out of scope of current question.
I agree, i can see the foreign Key set to InvoiceID1 in InvoiceItems Table, but i want it to link to ID column in Invoice Table, If i add an [InverseProperty("ID")] Attribute along with existing [ForeignKey("InvoiceID")] Attribute on Invoice object in InvoiceItems class an error shows up

ArgumentNullException: Value cannot be null. Parameter name: type

At the time of writing Entity Framework is still pretty new and documentation is still not complete, and all answers on Stackoverflow and other places tells the answer as to how to do it i.e. how to create an alternate/unique key, but unfortunately I can't find any which answers how to prevent it.
EDIT: Though this question was a programming mistake on my part as answered by @Jcl but we have received some good answers e.g. @Steve Greene posted about String Length Limit in EF SQL, which might be helpful to future reader, so i am leaving the question as is

A: EF(SQL) can't index strings over 900 bytes (450 unicode) so it creates one for you. Change your model to:
[StringLength(450)]
public string InvoiceID { get; set; }

Or use a similar fluent command to limit it. Entity Framework code first unique column

A: The problem is that you are saying that your InvoiceItem has a reference (Invoice) which has a foreign key (InvoiceID, which is of type string).
However the ID of the Invoice is a long, not a string, so it's making its own string key to comply with your requirements.
My guess: if you change the public string InvoiceID { get; set; } in InvoiceItem to: public long InvoiceID { get; set; } it should stop creating the key, plus, you'll actually get the correct foreign key.


text:
Q: (C++) Need help with database I'm trying to make a database and so far, I've been using strings to store my entries from a text file into an array, but this just isn't working out. Thus, I began thinking of a new way of doing it.
What I want to do:
Lets say I have a text file with the following database...
John Smith   00001 jsmith@email  pw1
Rob  Deniro  00002 rdeniro@email pw2
Al   Pacino  00003 apacino@email pw3
Joe  Pesci   00004  jpesci@email  307  pw4
Joaq Phoenix 00005  jphoe@email   208  pw5
John Madden  00006  jmadden@email 708  pw6
Alright, so basically what I'm stuck at is making this "inheritance" friendly. What's the best way to go about storing each entry?  Individual strings?  I've been thinking that the best way is to store each individual character until a whitespace occurs and then storing it into a string, but I'm not sure how that could be done.

A: As TomWij says, you do ifstream then strtok, but I'd recommend you escape your strings with "", not just spaces, that way you can store "something like this, for example a note about the user", that's how its done with CSV (comma separated values).
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;

void readCSV(std::istream &input, std::vector< std::vector<std::string> > &output)
{
    std::string csvLine;
    // read every line from the stream
    while( std::getline(input, csvLine) )
    {
        std::istringstream csvStream(csvLine);
        std::vector<std::string> csvColumn;
        std::string csvElement;
        // read every element from the line that is seperated by commas
        // and put it into the vector or strings
        while( std::getline(csvStream, csvElement, ',') )
        {
            csvColumn.push_back(csvElement);
        }
        output.push_back(csvColumn);
    }
}

int main()
{
    std::fstream file("file.csv", ios::in);
    if(!file.is_open())
    {
        std::cout << "File not found!\n";
        return 1;
    }
    // typedef to save typing for the following object
    typedef std::vector< std::vector<std::string> > csvVector;
    csvVector csvData;

    readCSV(file, csvData);
    // print out read data to prove reading worked
    for(csvVector::iterator i = csvData.begin(); i != csvData.end(); ++i)
    {
        for(std::vector<std::string>::iterator j = i->begin(); j != i->end(); ++j)
        {
            std::cout << *j << ", ";
        }
        std::cout << "\n";
    }
}

Which brings me to the real solution, why don't you use a CSV library like  CSV module  or better yet, SQLite, SQLite is dead easy to install and use, and its all around better than coding a database by hand, besides it shouldn't take you more than 1 hour to get SQLite into your codebase, since its API is REALLY easy.
#include <stdio.h>
#include <sqlite3.h>

static int callback(void *NotUsed, int argc, char **argv, char **azColName){
  int i;
  for(i=0; i<argc; i++){
    printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
  }
  printf("\n");
  return 0;
}

int main(int argc, char **argv){
  sqlite3 *db;
  char *zErrMsg = 0;
  int rc;

  if( argc!=3 ){
    fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]);
    exit(1);
  }
  rc = sqlite3_open(argv[1], &db);
  if( rc ){
    fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
    sqlite3_close(db);
    exit(1);
  }
  rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg);
  if( rc!=SQLITE_OK ){
    fprintf(stderr, "SQL error: %s\n", zErrMsg);
    sqlite3_free(zErrMsg);
  }
  sqlite3_close(db);
  return 0;
}

A: Usually the term "database" is reserved to the standard notion of a relational database such as MySQL, MS SQL Server, Oracle etc'
So this begs the question why don't you use a standard relational database?
you might want to try looking up TinySQL

A: Read one line at a time with ifstream and then use strtok to split each line, use the whitespace as the delimiter. You should use string except for the numeric values, which you can save as an int or a long if you need to support big values. It's also more wise to store the passwords in an encrypted way if you want security.
You might want to look for another solution to store your data instead of plain text for various reasons: Space, performance, security, ... It might be a good idea to try to use binary database files.

A:  #include<iostream>
 #include<conio.h>
 #include<fstream>
 using namespace std;

int main(int argc, char *argv[])

  {

     char Name[100];

     char FTE[100];
      cout<<"What is the file name?\n";
      cin>>FTE;

   ifstream myfile (FTE);

   while(1)
    {

    myfile.getline(Name, 30, '|');
    cout<<line;
   cin.ignore();

 }
  }

all this does is read all your text entries seperated by the '|' Character. Good for making Flat File Databases in C++ and other using same methods.


text:
Q: Incorrect ASP.NET session data returned intermittently I've been given the task of looking into a problem where the session of a user changes between refreshes of a page. Immediately (not knowing anything about the website) I said that it seems like a load-balancing/web cluster configuration issue. However, I found out later that the website is not load-balanced - It's a single server.
The application has a Basket object which is stored in Session. The user adds items to the basket etc. When on the basket page, if the page is refreshed the items which are in the basket change and sometimes there are none.
The session is not lost, it comes back almost always on the next refresh but then the basket can be empty or have different content on the next refresh. I've seen this behaviour before many times but only on multi-server set-ups.
This is something we have tried to replicate on a developer environment with no success - we simply cannot replicate the problem but on live it happens a lot.
The web application is an ASP.NET WebForms site, running under .NET 4.0 on Windows Server 2008 R2 and IIS 7.5.
Session state mode is InProc and the session timeout is set to 480 minutes.
I've used fiddler to look at the requests and responses and the ASP.NET session ID passed to the server is the same each time. There appears to be no difference between the responses besides the actual HTML returned.
Has anyone got any ideas on what could cause this problem?
Update 1:
I have re-worked some of the logging that a colleague implemented in the basket code. I can now see that the Session ID remains the same, the value of the Session variable also stays the same even though different data is displayed.
Sorry, I should have checked their logging before posting this.
I'm convinced that this is a server issue though, the code works as expected in our testing environment.

A:
"I said that it seems like a load-balancing/web cluster configuration issue. However, I found out later that the website is not load-balanced - It's a single server."

Just because it's a single server doesn't mean there's not load balancing going on.  IIS has within it a feature called a "Web Garden" which splits the web work across more than one process, so that it can be spread across multiple CPUs.
It's like a small "Web Farm" -- hence the name "Web Garden". :)
An effect when using a Web Garden is that it makes InProc session variables stop working correctly, as you may end up in a different worker process on each page request.  InProc (In Process) only works reliably if you always end up in the same Process.
Solution 1:

*

*Ensure IIS isn't set to use a Web Garden.  To do this:

*

*Open IIS manager.

*Determine which App Pool you web app is using.

*Right-click your App Pool and select "Advanced Properties".

*Scroll down and set "Maximum Worker Processes" to 1.

Solution 2:

*

*Use a session state server whose sole task is to manage session states for all worker processes.

*Then change the web app to from InProc to StateServer.

*Check out Configure a State Server to Maintain Session State (IIS 7) to get started on that. :)

Check out this MSDN blog: In-Proc Session State Management
It describes your session state options, and how to troubleshoot InProc session loss.

A: I have not changed the code for a long time.(last change : 20 July 2016)
But I have too same problem in Windows Server 2016. My customer was upgrade windows 2012 R2 to windows 2016. I couldnt solve this problem.
Then I downgrade to old server (windows 2012 r2). My problem was solved. I think it is a bug but i cant be sure
Maybe it will help you.


text:
Q: KinectSensor.KinectSensors.Count does not recognize a connected kinect? I am writing my first Kinect Application with the following user interface.

I am following this tutorial for more context.
The concept of the application consists only to integrate the camera of the Kinect into the desktop application. I think it might be important to note that I have a Kinect for Xbox One and its corresponding adapter using the Kinect SDK and Toolkit Version 1.8
The code for the button event handling is the following is the following
    private void btnStream_Click(object sender, EventArgs e)
    {
        if (btnStream.Text == "Stream")
        {

            if (KinectSensor.KinectSensors.Count > 0)
            {

                ksensor = KinectSensor.KinectSensors[0];
                KinectSensor.KinectSensors.StatusChanged += KinectSensors_StatusChanged;

            }
            ksensor.Start();
            lblConnectionID.Text = ksensor.DeviceConnectionId;

        }
        else
        {
            if (ksensor != null && ksensor.IsRunning)
            {
                ksensor.Stop();
                this.btnStream.Text = "Stream";
                this.pbStream.Image = null;
            }
        }

    }

    private void KinectSensors_StatusChanged(object sender, StatusChangedEventArgs e)
    {
        this.lblStatus.Text = ksensor.Status.ToString();
    }

and I get the following error from Visual Studio

An unhandled exception of type 'System.NullReferenceException' occurred in WindowsFormsApplication1.exe

Additional information: Object reference not set to an instance of an object.
The error is pointing to this line of code:
ksensor.Start();

It is guaranteed that the ksensor variable is declared as follows:
private KinectSensor ksensor;

My question is why is my variable KinectSensor.KinectSensors.Count probably 0 while I am supposed to have 1 as the return value? Does my application not recognize my kinnect?

A:
I think it might be important to note that I have a Kinect for Xbox One and its corresponding adapter using the Kinect SDK and Toolkit Version 1.8

The problem is that Microsoft Kinect SDK 1.8 is not compliant with Kinect for Xbox One (see this link).
You should install Kinect SDK 2.0 instead (download is available at this link). Or if you want to follow that tutorial with Kinect SDK 1.8, you should buy an old Kinect for Xbox 360.


text:
Q: Incorrect date returning when casting from varchar to date When casting from a varchar data type to a date datatype, my query results are altering the day of the original field. For example, the below two queries
     select to_Date('2017-12-15 00:11:10.167664+00', 'YYYY-MM-DD')

     select '2017-12-15 00:11:10.167664+00'::date

return a value of "2017-12-14".  I am querying a vertica database using DataGrip.

A: You can just take the leftmost 10 characters of the string and then convert to date, e.g.:
SELECT TO_DATE(LEFT('2017-12-15 00:11:10.167664+00',10), 'YYYY-MM-DD')


text:
Q: Unity Photon 2 spawning players I am having hard time to spawning players for my game, I followed Blackthornprod tutorial for multiplayer but I can't spawn players just like he do, The errors I get every time I run it is "NullReferenceException: Object reference not set to an instance of an object
PlayerSpawner.Start () (at Assets/PlayerSpawner.cs:18)" and if I move the arrow to change my avatars there's new error that I see and its "DefaultPool failed to load "Player". Make sure it's in a "Resources" folder. Or use a custom IPunPrefabPool.
UnityEngine.Debug:LogError (object)" and "NullReferenceException: Object reference not set to an instance of an object
PlayerSpawner.Start () (at Assets/PlayerSpawner.cs:20)" idk why so here's my code for spawning players in photon 2 unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;

public class PlayerSpawner : MonoBehaviour
{
public GameObject[] playerPrefabs;
public Transform[] spawnPoints;
public PlayerItem _playerItem;

private void Start()
{
    int randomNumber = Random.Range(0, spawnPoints.Length);
    Debug.Log("1");
    Transform spawnPoint = spawnPoints[randomNumber];
    Debug.Log("2");
    GameObject playerToSpawn = playerPrefabs[(int)PhotonNetwork.LocalPlayer.CustomProperties["playerAvatar"]];
    Debug.Log("3");
    PhotonNetwork.Instantiate(playerToSpawn.name, spawnPoint.position, Quaternion.identity);
    Debug.Log("4");
}
}

and here's the other code for players that I want to spawn
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
using Photon.Realtime;

public class PlayerItem : MonoBehaviourPunCallbacks
{

public Text playerName;

public Color highlightColor;
public GameObject leftArrowButton;
public GameObject rightArrowButton;

ExitGames.Client.Photon.Hashtable playerProperties = new ExitGames.Client.Photon.Hashtable();
public Image playerAvatar;
public GameObject[] avatars;

Player player;

private void Start()
{
}

public void SetPlayerInfo(Player _player)
{
    playerName.text = _player.NickName;
    player = _player;
    UpdatePlayerItem(player);
}

public void ApplyLocalChanges()
{
    leftArrowButton.SetActive(true);
    rightArrowButton.SetActive(true);
}

public void OnClickLeftArrow()
{
    if ((int)playerProperties["playerAvatar"] == 0)
    {
        playerProperties["playerAvatar"] = avatars.Length - 1;
    }
    else
    {
        playerProperties["playerAvatar"] = (int)playerProperties["playerAvatar"] - 1;
    }
    PhotonNetwork.SetPlayerCustomProperties(playerProperties);
}

public void OnClickRightArrow()
{
    if ((int)playerProperties["playerAvatar"] == avatars.Length - 1)
    {
        playerProperties["playerAvatar"] = 0;
    }
    else
    {
        playerProperties["playerAvatar"] = (int)playerProperties["playerAvatar"] + 1;
    }
    PhotonNetwork.SetPlayerCustomProperties(playerProperties);
}

public override void OnPlayerPropertiesUpdate(Player targetPlayer, ExitGames.Client.Photon.Hashtable changedProps)
{
    if (player == targetPlayer)
    {
        UpdatePlayerItem(targetPlayer);
    }
}

void UpdatePlayerItem(Player player)
{
    if (player.CustomProperties.ContainsKey("playerAvatar"))
    {
        playerAvatar.sprite = avatars[(int)player.CustomProperties["playerAvatar"]].GetComponent<SpriteRenderer>().sprite;
        playerProperties["playerAvatar"] = (int)player.CustomProperties["playerAvatar"];
    }
    else
    {
        playerProperties["playerAvatar"] = 0;
    }
}
}

also last thing if you ever need this but idk if this is needed or relevant but here's the code that will deliver my player to the next scene where I need it to spawn
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.UI;

public class LobbyManager : MonoBehaviourPunCallbacks
{
public InputField roomInputField;
public GameObject lobbyPanel;
public GameObject roomPanel;
public Text roomName;

public RoomItem roomItemPrefab;
public List<RoomItem> roomItemList = new List<RoomItem>();
public Transform contentObject;

public float timeBetweenUpdates = 1.5f;
float nextUpdateTime;

public List<PlayerItem> playerItemsList = new List<PlayerItem>();
public PlayerItem playerItemPrefab;
public Transform playerItemParent;

public GameObject playButton;

private void Start()
{
    PhotonNetwork.JoinLobby();
}

public void OnClickCreate()
{
    if (roomInputField.text.Length >= 1)
    {
        PhotonNetwork.CreateRoom(roomInputField.text, new RoomOptions() { MaxPlayers = 10, BroadcastPropsChangeToAll = true });
    }
}

public override void OnJoinedRoom()
{
    lobbyPanel.SetActive(false);
    roomPanel.SetActive(true);
    roomName.text = "Room: " + PhotonNetwork.CurrentRoom.Name;
    UpdatePlayerList();
}

public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
    if (Time.time >= nextUpdateTime)
    {
        UpdateRoomList(roomList);
        nextUpdateTime = Time.time + timeBetweenUpdates;
    }
}

void UpdateRoomList(List<RoomInfo> list)
{
    foreach (RoomItem item in roomItemList)
    {
        Destroy(item.gameObject);
    }
    roomItemList.Clear();

    foreach (RoomInfo room in list)
    {
        RoomItem newRoom = Instantiate(roomItemPrefab, contentObject);
        newRoom.SetRoomName(room.Name);
        roomItemList.Add(newRoom);
    }
}

public void JoinRoom(string roomName)
{
    PhotonNetwork.JoinRoom(roomName);
}

public void OnClickLeaveRoom()
{
    PhotonNetwork.LeaveRoom();
}

public override void OnLeftRoom()
{
    lobbyPanel.SetActive(true);
    roomPanel.SetActive(false);
}

public override void OnConnectedToMaster()
{
    PhotonNetwork.JoinLobby();
}

void UpdatePlayerList()
{
    foreach (PlayerItem item in playerItemsList)
    {
        Destroy(item.gameObject);
    }
    playerItemsList.Clear();

    if (PhotonNetwork.CurrentRoom == null)
    {
        return;
    }

    foreach (KeyValuePair<int, Player> player in PhotonNetwork.CurrentRoom.Players)
    {
        PlayerItem newPlayerItem = Instantiate(playerItemPrefab, playerItemParent);
        newPlayerItem.SetPlayerInfo(player.Value);

        if (player.Value == PhotonNetwork.LocalPlayer)
        {
            newPlayerItem.ApplyLocalChanges();
        }

        playerItemsList.Add(newPlayerItem);
    }
}

public override void OnPlayerEnteredRoom(Player newPlayer)
{
    UpdatePlayerList();
}

public override void OnPlayerLeftRoom(Player otherPlayer)
{
    UpdatePlayerList();
}

private void Update()
{
    if (PhotonNetwork.IsMasterClient && PhotonNetwork.CurrentRoom.PlayerCount >= 1)
    {
        playButton.SetActive(true);
    }
    else
    {
        playButton.SetActive(false);
    }
}

public void OnClickPlayButton()
{
    PhotonNetwork.LoadLevel("Game");
}
}

Thank you in advance if you ever decided to help me! I will put you in Credits of my game as payment, Thank youuuuu

A: There are three problems.

*

*Replace MonoBehviour with MonoBehviourPun.

*Add all the prefabs contained in the "PlayerPrefabs" list into a
folder called "Resources". All prefabs that PUN needs to instantiate
must be in a folder with this name, or it will not be able to
instantiate them. The prefabs to be instantiated must also have a
PhotonView component.

*There is no property called "PlayerAvatar". You can create one at the
beginning of the game by assigning it a default value, such as 0. In
the LobbyManager class, modify the start () method.

So it will work.
Good work!


text:
Q: Script throwing an error after starting the service I have written the below code to start the service:
invoke-command -cn $server -Credential $cred -ScriptBlock {
param($svc)
if((get-service $svc).status -ne "running") {
    get-service $svc| start-service
    set-service $svc -StartupType Automatic
    (get-service $svc).waitforstatus('running')
 }
 get-service $svc| select ServiceName
} -ArgumentList $svc

After executing the above script, I am getting below error:
Status         : Running
StartType      : Automatic
ServiceName    : svcname
PSComputerName : host1

+     invoke-command -cn $server -Credential $cred -ScriptBlock {
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service], ServiceCommandException
    + FullyQualifiedErrorId : StartServiceFailed,Microsoft.PowerShell.Commands.StartServiceCommand

I see service is Running successfully so why it is throwing an error even when the service was started correctly?
I am using poweshell 5

A: Continuing from my comments, try:
Invoke-Command -ComputerName $server -Credential $cred -ScriptBlock {
    param($svc)
    $theService = Get-Service -Name $svc
    if($theService.Status -ne 'Running') {
        if ($theService.Status -ne 'Stopped') { $theService | Stop-Service -Force }
        $theService | Set-Service -StartupType Automatic
        ($theService | Start-Service -PassThru).WaitForStatus('Running')
     }
     $theService | Select-Object ServiceName
} -ArgumentList $svc


text:
Q: How to finish current activity and launch a new activity Rx way? I want to do the following but in Rx. The startActivity(intent) is guaranteed to be called since finish() is just an async call queued:
private fun launchNewActivity(){
  ...
  finish()
  startActivity(intent)
}

So in Rx way, I'm doing something like this, where both are packaged in their own observables (requirement):
private fun launchNewActivity(): Observable<Any>{
  ...
  return Observable.concat(
    Observable.just(finish())
    Observable.just(startActivity(intent))
    ...
  )
}

However, I'm worried in the Rx way, the activity could finish before startActivity is called. Would that happen?

A: Actually you are calling it in a wrong order. You should call startActivity() first before calling finish(). Still, encapsulating this process inside an Observable might introduce an unexpected behavior, because startActivity() is supposed to be called on UI thread as it triggers UI animation/transition to another Activity.
What you want to do is to call both startActivity() and finish() inside onNext() or onComplete() callback. But in case you REALLY need to encapsulate it, you can follow these simple steps:
1. Create a method which handles Activity switching
private fun launchNewActivity() {
    startActivity(Intent())
    finish()
}

2. Encapsulate this method in Observable
Observable.fromCallable(this::launchNewActivity)

You will want to put above Observable inside a CompositeDisposable or a DisposableObserver.

A: You can Start Your Next Activity Before Finish this Actvity.
First start your activity startactivity(Intent(this,NextActivity::Class.java)
and after call finish() it work as finish your current activity.
here you can find code:
public fun startNewActivity(){
 startActivity(Intent(this,NewActivity::Class.java))
 finish()
}


text:
Q: Error builder exportar apk for android Hola amigos tengo un código que maneja opencv y numpy con otras librerías resulta que cuando exporto el apk para android, y ejecuto la aplicación en android carga y se cierra de una vez realice el logcat en android y me sale el siguiente error:
07-04 12:12:21.207 10072 10098 I python  : [INFO   ] [Text        ] Provider: sdl2
07-04 12:12:21.283 10072 10098 I python  : [INFO   ] [GL          ] NPOT texture support is available
07-04 12:12:21.434 10072 10098 I python  :  Traceback (most recent call last):
07-04 12:12:21.434 10072 10098 I python  :    File "/home/dev-chavita/Documentos/Alcoholimtro/alcoholimetro/.buildozer/android/app/main.py", line 9, in <module>
07-04 12:12:21.435 10072 10098 I python  :    File "/home/dev-chavita/Documentos/Alcoholimtro/alcoholimetro/.buildozer/android/app/views/camLoad.py", line 8, in <module>
07-04 12:12:21.435 10072 10098 I python  :  ModuleNotFoundError: No module named 'cv2'
07-04 12:12:21.435 10072 10098 I python  : Python for android ended.
07-04 12:12:21.493  1674  2449 W InputDispatcher: channel '391dce6 org.test.myalcoholimetro/org.kivy.android.PythonActivity (server)' ~ Consumer closed input channel or an error occurred.  events=0x9

y tengo la siguiente configacion en .spec
# (list) Application requirements
# comma separated e.g. requirements = sqlite3,kivy
requirements = python3,kivy,kivymd,opencv,numpy,face_recognition

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# (list) Permissions
#android.permissions = INTERNET
android.permissions = CAMERA
android.permission-group = HARDWARE_CONTROLS

# (int) Target Android API, should be as high as possible.
#android.api = 27

No se que pasa por que me generar error de cv2, si exporto desde .spec opencv espero me puedan ayudar amigos.


text:
Q: Why doesn't putchar(1+'0') output 10? Why does putchar outputs '1' for putchar(1+'0') but not '10' but when only a character argument is passed, like putchar('0'), it outputs it.
With putchar(1+'0'), I expected an output of 10.

A: putchar always outputs a single character only, as per the name.
'0' is a single character literal. So it's an integer value that represents the character 0 in your computer's encoding — almost certainly ASCII.
1+'0' then literally means "the character that comes one after 0 in my computer's encoding (which is almost certainly ASCII). Which is the character 1.

A: Unlike languages such as Python, the + operator in C is not used to concatenate strings.
What you actually have here with 1+'0' is that you're adding the value 1 with the character code for the character 0.  The C standard guarantees that the characters for the numerals 0 to 9 have consecutive character encodings, so adding 1 to the character code for 0 gives you the character code for 1, which is what gets printed.

A: Understand that in C, there aren't really chars. They are just integers.
putchar(48); prints "0"
putchar(49); prints "1"
putchar(65); prints "A"
Because 48 is the ascii reprentation of character 0, 49 of 1, 65 of A. That is not even C decision. That is the terminal job. putchar just output the integer it was given as an argument to the output terminal, and it does the job of drawing a nice oval if pushed 48, a nice vertical bar if pushed 49, or a upside down V with a transversal bar if pushed 65 (I described it voluntarily this trivial way to make clear how it is just a drawing convention).
Now, the second thing to understand is that in C, for the same reason (there aren't really chars), there are several ways to write a literal integer. 48 for example can be written
in decimal, 48
in hexadecimal, 0x30
in octal, 060
and in "char" representation, '0'.
'0' is just a way to type 48.
The only reason why you wouldn't type this code
printf("Di Caprio is %d years old\n", '0');
is not because it wouldn't work. It is exactly the same as if you had typed
printf("Di Caprio is %d years old\n", 48);
The reason why you don't do that, is because it is an awful style. A human reader of your code would have hard time to understand it. Normally you don't use '0' to say 48, unless you mean "48 as the ascii code of 0"
(Plus, theoretically, you are not supposed to know that 48 is the ascii code of 0. The whole point of using that notation is to let that decision to the compiler).
So, back to your example, when you said
putchar(1+'0');
it is exactly the same code as if you had
putchar(1+0x30);
or
putchar(1+060);
or
putchar(1+48);
so, in the end
putchar(49);
and, since 49 is the ascii code of 1
putchar('1');

A: '0' is a literal character constant for the digit character 0.  In ASCII/ANSI character sets it has a numeric value 0x30 (or 48 decimal).  If you add 1 to it you get a value 0x31 - the character code for '2', and putchar() interprets the parameter as a single character code and presents the appropriate character to stdout.
If you wanted to output "10" you would need:
putchar('1') ;
putchar('0') ;

A: In C a character in single quotes is a char. But a char in C is also just a number that encodes some ASCII character.
The character '0' corresponds corresponds to number 48. So 48 is it's ASCII code.
So when you add an int 1 with a char '0', the char '0' is converted to an int. So basically 1 + 48, which is 49.
Then you try to call putchar(49) which converts the 49 to it's ASCII character which is '1'.


text:
Q: Does the payload of an Alcubierre drive have to be on board during the preparation phase? I was thinking about the practical aspect of using an Alcubierre drive, assuming one existed.
I'm no expert, but my understanding is that, since the destination has to be in the forward light-cone of the vehicle, there is necessarily a preparation phase.
For example, if you wanted to travel 100 ly in a year, you would set up the drive, point it the right way, let it "warm up" for 99 years, hit the switch, and get to the 100 ly destination in 1 year of subjective time, but the whole process still took 100 years.
Would the payload have to be on board during the 99-year warm-up period in this example? If so would that payload have to be causally disconnected from the region of spacetime which doesn't make the journey? If so doesn't that imply that the destination couldn't receive a FTL response to a message it sent to the vehicle, since the equipment on board wouldn't be able to respond in less time than it takes the drive to warm up?

A: Would the payload have to be on board during the 99-year warm-up period in this example?
No. The payload does not have to have the destination be in the forward light cone (for the external metric).  And the warm up doesn't happen at the launch site, it happens along the region you will traverse, which is why it takes a while.
The best analogy is the train track analogy.  The coordination of laying down the tracks happens at slower than light speeds.  But this advance coordination could be to bring in exotic matter and put it in front of the warp drive as needed, with a just-in-time type service.  Setting up the coordination of when the exotic matter arrives when and where requires all the advance planning.  But you could bring many possible payloads that benefit from the same planning.  So you can plan first, ship later.
Does that imply that the destination couldn't receive a FTL response to a message it sent to the vehicle
The destination can send a message, and the destination could be the one doing the advance planning and find a payload and bring it back at the speed they planned for.  Assuming they have the exotic matter and put it in place.
So, to clarify, the "warm up" could start at the destination.


text:
Q: 555 timer question
R1=500k variable resistance
R2= 10k
when the timer's operation time is 5sec, R1 86.7k
What is the operation time when 4V is applied to 5(red point)?
im student, so I would very appreciate it if you could explain it in detail

A: Solve the first order RC differential equation at pin 5, and you'll arrive at your solution.
4V = 5V * (1-exp(-t/RC))
Where, R = R1+R2
t = RC*ln(5)
t = 7.31 seconds


text:
Q: Google CSE - sorting / filter by meta tags I am working on a Google CSE video search. I am stuck with an issue right now and that issue is, I want to filter/sort results on duration or date basis. I mean to say I want to sort/filter results on meta tags basis.
For example: https://search.google.com/structured-data/testing-tool#url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DlF-jPBnZ098
There is a YouTube video and I have checked it on Google Structured Data Testing Tool and I and found that the each YT video contains the following meta info like:
  <meta itemprop="genre" content="Sports">
  <meta itemprop="duration" content="PT9M35S">
  <meta itemprop="datePublished" content="2016-06-09">

So somehow someway I want to filter my query with these meta tags. I saw this answer on Stack Overflow Google custom search API - sorting / filter which looks very similar to my query but it's not working for me.
I tried these queries and I am getting no result.
q=my+query+more:pagemap:metatags-genre:sports
q=my+query+more:pagemap:metatags-duration:2
q=my+query+more:pagemap:metatags-datapublished:2016-01-09

I also tried it with sort parameter but no success at all
q=my+query&sort=more:pagemap:metatags

I am getting no result at all. Nothing is working, just getting frustated. I dont know what kind of mistake I am doing?
I learned these article on Google but I did not find much help:

*

*https://developers.google.com/custom-search/docs/structured_search?csw=1

*https://webmasters.googleblog.com/2012/05/sorting-and-filtering-results-in-custom.html

*https://developers.google.com/custom-search/docs/structured_data
So if someone know how to do it please help!


text:
Q: Delete rows from UITableView and update array from NSUserDefaults With the tableview I am trying to delete only one record of the list but with my code it deletes all the userDefault data. how do i delete only one record?
cell.buttonPressed = {

            self.recDictionaryId?["\(title)"] = "\(sentence)"

            self.pokemonArray.remove(at: indexPath.row)
            self.tvPokemon.deleteRows(at: [indexPath], with: .automatic)

            let defaults = UserDefaults.standard
            defaults.set(self.pokemonArray, forKey: "UserDefSaveDictionary")

            defaults.synchronize()

            self.tvPokemon.reloadData()

}

I also tried with:
removeObject(forKey: "UserDefSaveDictionary")
but the result is the same

A: override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
    objects.remove(at: indexPath.row)
    self. deleteItem(indexPath.row)
    tableView.deleteRows(at: [indexPath], with: .fade)
}
}

func deleteItem(_ index: Int) {
let userDefaults = UserDefaults.standard
if let data =  userDefaults.data(forKey:"keyName") , var array =  try? JSONDecoder().decode([Model].self, from: data) {
    array.remove(at: index)
    guard let result =  try? JSONEncoder().encode(array) else { return }
    userDefaults.set(result, forKey:"keyName")
}
}

you have to fetch the UserDefaults response array and convert it to a model then it would be much easier, if you want make this better you can try by adding a completion block to deleteItem() function and inside that you can perform real deletion


text:
Q: Notice (8): Undefined index I'm trying to make a cakephp project work on my local computer, after setting up everything the login page works perfectly, after login in I'm getting this error:

and this is the code of line 111:

some help please!
My friends have the same code and it's working for them


text:
Q: Can I call tf.variable_scope without a "with" statement? I want to call tensorflow's python APIs in matlab (see https://www.mathworks.com/help/matlab/matlab_external/call-python-from-matlab.html).
The matlab does not support the "with" statement.
I can not create a tf.variable_scope without a "with" statement.
I have tried the two codes below, but both do not work.
Is there any solution?
Python:
import tensorflow as tf
with tf.variable_scope('123') as vs:
    print(vs.name)  # OK
vs2 = tf.variable_scope('456')
print(vs2.name)  # AttributeError: 'variable_scope' object has no attribute 'name'

Matlab:
vs = py.tensorflow.variable_scope('GRAPH', pyargs('reuse', py.tensorflow.AUTO_REUSE));
vs.name  % No appropriate method, property, or field 'name' for class 'py.tensorflow.python.ops.variable_scope.variable_scope'.

A: You can rewrite the python context like
import tensorflow as tf

with tf.variable_scope('123') as vs:
    print(vs.name)  # OK

vs2_obj = tf.variable_scope('456')
vs2 = vs2_obj.__enter__()
try:
    print(vs2.name)  # OK as well
finally:
    vs2_obj.__exit__(None, None, None)

But I guess there are some site-effects.
Explanation: There is a difference between a context-object vs2_obj and the current context vs2 itself.
This gives the output
123
456

A: Also, I write a tool class to mimic "with" statements in matlab.
helper.py:
class With(object):
    def __init__(self, obj):
        self._obj = obj
        self._p = self._obj.__enter__()

    def __del__(self):
        self._obj.__exit__(None, None, None)

    def get(self):
        return self._p

Matlab:
with_vs = py.helper.With(py.tensorflow.variable_scope('X'));
with_vs.get().name
...
clear with_vs;


text:
Q: can't get div to flush at the top of the page I can't seem to get the right side/column of the page to flush at the top. I've included a picture to show you guys what I mean.
JSFiddle
http://jsfiddle.net/vDUE7/2/
Picture
http://oi57.tinypic.com/3128hew.jpg
Code

  Bengal Tiger

Bengal       Tiger

Bengal       Tiger

Bengal       Tiger

Bengal       Tiger

CSS
  img {
border: 0px;
display: block;
margin: 0 auto;
  }
  header#head {
padding-left: 20px;
position: relative;
border-left: 1px solid #dddddd;
border-right: 1px solid #dddddd;
border-bottom: 1px solid #000;
  }
  .image {
     position: relative;
     cursor: pointer;
     float:left;
  }
  #container {
width: 1055px;
margin: 0 auto;
text-align: left;
background: #fff;
padding: 0;
margin-top:-26px;
  }
  #content {
overflow:hidden;
width:1053px;
height:100%;
border: 1px solid #dddddd;
  }
  #side{
width:312px;
height:100%;
float:left;
margin-top:-10px;
padding-left:10px;
background-color:#f3f3f3;
  }
  .block {
border-top: 1px solid #dddddd;
text-align: center;
background-color:#000;
width:1053px;
height:365px;
position:relative;
font-size:15px;
color: #fff;
  }
  .list{
width:300px;
border-bottom: 1px solid #dddddd;
display: inline-block;
margin-top:10px;
  }
  .middle-column {
width: 730px;
float: left;
border-right: 1px solid #dddddd;
  }
  article.in-column {
text-align: left;
padding: 15px;
border-bottom:1px solid #dddddd;
height:100%;
  }
  article.in-column img{
float:left;
margin-right:15px;
  }
  .list img{
float:left;
margin-right:15px;
border:1px solid #ddd;
margin-bottom:10px;
  }
  .top-column {
float: left;
width:730px;
height:360px;
border-right: 1px solid #000;
border-left: 1px solid #000;
border-bottom: 1px solid #000;
  }

A: Add a style to the side bar of
position:fixed;
top:0;
left:/*width of whatever width the stuff to the left of the side bar has*/

Hope I helped

A: have removed the sidebar from the content div and placed it separately and instead of using float:left i've used display:inline-block. here's the updated fiddle,
http://jsfiddle.net/vDUE7/9/
hope this solves your problem.
HTML

Bengal Tiger

Bengal Tiger

Bengal Tiger

Bengal Tiger

Bengal Tiger

CSS
img {
border: 0px;
display: inline-block;
margin: 0 auto;
}
header#head {
padding-left: 20px;
position: relative;
border-left: 1px solid #dddddd;
border-right: 1px solid #dddddd;
border-bottom: 1px solid #000;
}
.image {
  position: relative;
  cursor: pointer;
  float:left;
}
#container {
width: 1055px;
margin: 0 auto;
text-align: left;
background: #fff;
padding: 0;
margin-top:-26px;
}
#content {
overflow:hidden;

height:100%;
border: 1px solid #dddddd;
}
#side{
width:312px;
height:100%;
display:inline-block;
background-color:#f3f3f3;
}
.block {
border-top: 1px solid #dddddd;
text-align: center;
background-color:#000;
width:1053px;
height:365px;
position:relative;
font-size:15px;
color: #fff;
}
.list{
width:300px;
border-bottom: 1px solid #dddddd;
display: inline-block;
margin-top:10px;
}
.middle-column {
width: 730px;
float: left;
border-right: 1px solid #dddddd;
}
article.in-column {
text-align: left;
padding: 15px;
border-bottom:1px solid #dddddd;
height:100%;
}
article.in-column img{
float:left;
margin-right:15px;
}
.list img{
float:left;
margin-right:15px;
border:1px solid #ddd;
margin-bottom:10px;
}
.top-column {
float: left;
width:730px;
height:360px;
border-right: 1px solid #000;
border-left: 1px solid #000;
border-bottom: 1px solid #000;
}


text:
Q: Pass form data from block to a page view in Drupal I am using the location module and views module for a postcode search, which works fine in a page display using views.
However I want the user to be able to enter their postcode into a block on the homepage and clicking submit my module sends them to the page created in views and the postcode is set as a session S_SESSION['postcode'] before sending to this page, next I want the location page to load but using the session to display the locations automatically.
Any ideas I am using hook_form_submit() and inside that declaring the $form_state as a session and then using $form_state['redirect'] to sent to the views page path.

A: Ok the way to do this, is to create a mini panel and assign the view to that mini panel and then select the submit handler to go to the views page.


text:
Q: Good free software that will join .001 files? Can any one suggest free PC software that will join .001 files and what is the proper extension name of the files if possible?

A: HJ-Split also will use this type of extension on top of what Dan has already mentioned. It is a free file splitter and joiner.

A: In short, use 7-Zip.
How to extract 001 files?

A: Usually those files are part of a split ZIP or RAR file. One of the files in that directory should have the .rar or .zip extension. Use 7-zip, IZArc or WinRAR to open that file, and you will get the contents of the .001 file.

A: Total Commander
File > Combine Files

This function allows to combine
  multiple files to one big file. Total
  Commander can not only combine files
  created with its own function split
  file, but also files created with the
  Unix command split -b. Put the cursor
  on the first partial file and choose
  'combine files'. The file names must
  be numbered in ascending order, or
  have letters in ascending order. Total
  Commander will detect file.001,
  file.002, file.003, but also fileaa,
  fileab, fileac etc.

A: Peazip works nicely for that,never tryed using 7zip for that, but if the How-To Geek says it works, it probably does.


text:
Q: PostgreSQL copy from CSV with missing data values I'm trying to import a CSV file into PostgreSQL using COPY.  It chokes when it hits a row where there are empty values, e.g. the second row below:

JAN-01-2001,1,2,3,4,5
JAN-02-2001,6,7,,,

I've tried this COPY statement, as well as variants using NULL and QUOTE and havent found anything that works.

COPY data FROM 'data.dat'
      USING DELIMITERS ',' CSV;

Any suggestions?  The data file is in a massive 22GB flat file, so I'd like to avoid editing it directly.

A: I would suggest converting your numeric columns to text columns for the purposes of your import. The reason is that an empty string is not a valid numeric value. Change your numeric columns to text columns, import the CSV file, update the empty values to null or 0, and then change the column back to an integer.

A: Your statement is suspicious:
COPY data FROM 'data.dat' USING DELIMITERS ',' CSV;

DELIMITERS was used in versions before 7.3. It is still supported in order not to break old code, but don't use it any more. The proper keyword is DELIMITER. And you don't need to specify , at all as it is the default for FORMAT CSV.
Also, I quote the manual here:

filename
The absolute path name of the input or output file. Windows users might need to use an E'' string and double any backslashes used in the path name.

Bold emphasis mine. Replace 'data.dat' with something like '/path/to/data.dat' on UNIX or E'C:\\path\\to\\data.dat' on Windows.
For versions 7.3+ use:
COPY data FROM '/path/to/data.dat' CSV

For versions 9.0+ use:
COPY data FROM '/path/to/data.dat' (FORMAT CSV)

If you still get this error:

ERROR: invalid input syntax for type numeric:
CONTEXT: COPY data, line 13, column interval_2400:

Then, obviously, the source file does not match the structure of table data. Have a look at your source file, go to line 13 and see what value is there for column interval_2400. Chances are, it's not numeric. In particular, an empty string ('') is not allowed in columns of numeric type.
You can either fix the source file or adapt the table definition:
ALTER TABLE data ALTER COLUMN interval_2400 TYPE text;

Or whatever type is more appropriate. Might be interval, judging from the name. (But text accepts almost any input values.)
Or, better yet, create a modified temporary file, COPY to it, fix offending values, then INSERT into the target table, casting from text. See:

*

*How to ignore errors with psql \copy meta-command

*How to update selected rows with values from a CSV file in Postgres?

A: This is PostgreSQL bug - csv parser ignore last empty item and throw error - "PG::BadCopyFileFormat: ERROR:  missing data for column".
i'm use a stupid hack:
If last item is empty, simple add a one delimiter to end of string:
1,2,3
1,2,,

This add missed last item in row to import data.

A: One additional caveat- Check the line number of the error and make sure it is not a blank row in the CSV file. That will cause postgres to throw the same error about missing values.

A: You can do it this way:
COPY productos FROM 'path/to/csv/productos.csv'
WITH DELIMITER ',' CSV HEADER FORCE NULL max_time, warn_time,
time_displayed, id_departamento ENCODING 'ISO 8859-1';

This parameter FORCE NULL (comma-separated fieldlist) converts empty cells to null values into the fieldlist fields. Note that I also had to specify file encoding to make it work.

A: Anyone coming here with smaller files: here's the easiest fix I've found to this and inconsistent number of delimiters in a csv.

*

*Open your CSV.

*Ctrl + Shift + 8 (selects all data)

*Ctrl + h (opens find replace)

*Leave the find box blank so its looking for strings of 0 length.

*Enter a space in the replace with box.

This will loop through the whole CSV and force it to have the correct column count in delimiters ( , ) even if theres no data in that column.
If you're alright with Excel you can turn this into a macro too, so my macro (Ctrl + g) does this in one go. Creating a Macro


text:
Q: ValueError Message with python the Following program:

X=np.array([[1,-7,8],[6,4,9],[7,8,9]],dtype=np.int8)
Y=np.array([1,-1,1],dtype=np.int8)
w=2
sigma=20

for i in range (len(X)):
    e_i=Y-np.dot(w,X)
    Ls_w=1/len(X)*(np.sum(Y-np.dot(w,X)))**2
    delta_ls=-1/len(X)*np.sum(2*np.dot(X,e_i))
    while delta_ls>sigma:
        if(e_i != 0):
            w+=2*np.dot(e_i,X)
            print(w,e_i)

it gives me this :
if(e_i != 0):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
How to fix it ?


text:
Q: Are all Python objects tracked by the garbage collector? I'm trying to debug a memory leak (see question Memory leak in Python Twisted: where is it?).
When the garbage collector is running, does it have access to all Python objects created by the Python interpreter? If we suppose Python C libraries are not leaking, should RSS memory usage grow linearly with respect to the GC object count? What about sys.getobjects?

A: CPython uses two mechanisms to clean up garbage. One is reference counting, which affects all objects but which can't clean up objects that (directly or indirectly) refer to each other. That's where the actual garbage collector comes in: python has the gc module, which searches for cyclic references in objects it knows about. Only objects that can potentially be part of a reference cycle need to worry about participating in the cyclic gc. So, for example, lists do, but strings do not; strings don't reference any other objects. (In fact, the story is a little more complicated, as there's two ways of participating in cyclic gc, but that isn't really relevant here.)
All Python classes (and instances thereof) automatically get tracked by the cyclic gc. Types defined in C aren't, unless they put in a little effort. All the builtin types that could be part of a cycle do. But this does mean the gc module only knows about the types that play along.
Apart from the collection mechanism there's also the fact that Python has its own aggregating memory allocator (obmalloc), which allocates entire memory arenas and uses the memory for most of the smaller objects it creates. Python now does free these arenas when they're completely empty (for a long time it didn't), but actually emptying an arena is fairly rare: because CPython objects aren't movable, you can't just move some stragglers to another arena.

A: The RSS does not grow linearly with the number of Python objects, because Python objects can vary in size. An int object is usually much smaller than a big list.
I suppose that you mean gc.get_objects when you wrote sys.getobjects. This function gives you a list of all reachable objects. If you suppose a leak, you can iterate this list and try to find objects that should have been freed already. (For instance you might know that all objects of a certain type are to be freed at a certain point.)

A: A Python class designed to be unable to be involved in cycles is not tracked by the GC.
class V(object):
    __slots__ = ()

Instances of V cannot have any attribute. Its size is 16, like the size of object().
sys.getsizeof(V()) and v().sizeof() return the same value: 16.
V isn't useful, but I imagine that other classes derived from base types (e.g. tuple), that only add methods, can be crafted so that reference counting is enough to manage them in memory.


text:
Q: Are Synchronised Data Extensions Quasi Populations? I have not been able to get a consistent position on this and I have asked a number of people from both Salesforce and outside.
Should I expect synchronised data extensions to act as Quasi Populations and if not what is the best design pattern in Data Designer?
My use primary use case is to do with injecting people (who are not already in All Subscribers) into Journeys.
From my experience and re-testing in the last month, I found people (not already in All Subscribers) do not inject unless they are in a Population. I can resolved this by creating a Standard DE, Linked it as a Population, created a Query Automation to populate it and ran it so the person was there: Then they inject. Last months test was with an Email Audience. This now seems to be a Data Extension Entry Event (I have no idea if that means it's behavior has changed).
When I have asked this question before I have had all range of responses including:

*

*Its a Quasi Population you don't need to create a Population

*You need to add the population

*To one example where an architect told me he deletes and the SF native Attributes and builds from scratch.

The downside of having to create an explicit Population is that it can only be populated every hour by an Automation where as data can come across in 15min intervals.
I would be grateful is some experienced Architects would share their Design Patterns and why they have made the choices they have and any know trade offs with the choice.
Thank you.


text:
Q: How to prevent Context leak in AsyncTask used by JobService I need to do some background work which requires a Context in a JobService (I'm using the Firebase JobDispatcher one because we support api 16+) I've read a lot of articles about the JobService and AsyncTasks but I'm unable to find any good articles on how to combine them if you need a Context.
My JobService
import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;

public class AsyncJobService extends JobService {

    @Override
    public boolean onStartJob(JobParameters job) {
        new AsyncWork(this, job).execute();
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters job) {
        return false;
    }
}

My AsyncTask
import android.os.AsyncTask;
import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;

class AsyncWork extends AsyncTask<Void, Void, Void> {

    private JobService jobService;

    private JobParameters job;

    AsyncWork(JobService jobService, JobParameters job) {
        this.jobService = jobService;
        this.job = job;
    }

    @Override
    protected Void doInBackground(Void... voids) {
        // some work that needs context
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        // some work that needs context
        jobService.jobFinished(job, false);
    }
}

This gives a warning that the jobService property in the AsyncWork class is leaking a context object. I understand why this is the case if you pass an Activity or Fragment but this is a JobService which should exist untill I call jobFinished(). Am I doing something wrong or can I ignore the warning?

A: You cannot ignore the warning.  Because AsyncWork holds the reference to the Context, the Context cannot be GCed until the task is complete: the Context memory leaks.  There are two solutions:

*

*Use a context that is long-lived, anyway, the Application context.

*Tie the life of the async task to the life of the context to which it hold a reference: cancel it in onPause

A: To handle leaking you need to use WeakRefernce class with JobService Object
class AsyncWork extends AsyncTask<Void, Void, Void> {

  private WeakReference<JobService> jobServiceWeakReference;
  private JobParameters job;

  AsyncWork(JobService jobService, JobParameters job) {
      this.jobServiceWeakReference = new WeakReference<>(jobService);
      this.job = job;
  }

  @Override
  protected Void doInBackground(Void... voids) {
      // some work that needs context
        return null;
    }

  @Override
  protected void onPostExecute(Void aVoid) {
      super.onPostExecute(aVoid);
      // some work that needs context
      jobServiceWeakReference.get().jobFinished(job, false);
  }
}


text:
Q: Performing calculations on elements, and retrieving index the index of an element in a vector Here I am trying to perform calculations and comparisons on elements in a vector, finding average, lower value, higher value and difference. I am also having issues printing the index of elements in a vector.
#include <iostream>
#include <string>
#include <vector>

enum class OrderBookType{bid, ask};

class OrderBookEntry{
public:
    double price;
    double amount;
    std::string timestamp;
    std::string product;
    OrderBookType orderType;

    double computeAveragePrice(std::vector<OrderBookEntry>& entries);

    OrderBookEntry(double _price,
                   double _amount,
                   std::string _timestamp,
                   std::string _product,
                   OrderBookType _orderType):
    price(_price),
    amount(_amount),
    timestamp(_timestamp),
    product(_product),
    orderType(_orderType) {
    }

//*    Other kinds of functions I hope to implement for this program. */
//    double computeLowPrice(std::vector<OrderBookEntry>& entries);
//    double computeHighPrice(std::vector<OrderBookEntry>& entries);
//    double computePriceSpread(std::vector<OrderBookEntry>& entries);

};

double OrderBookEntry::computeAveragePrice(std::vector<OrderBookEntry> &entries) {
        return 5.5; // Just trying to test a for an output here
}

int main() {
    // Declaring vector entries
    std::vector<OrderBookEntry> entries;

    // Adding entries into entries
    entries.push_back(OrderBookEntry{
        10000,
        0.001,
        "2020/03/17 17:01:24.88492",
        "BTC/USDT",
        OrderBookType::bid
    });
    entries.push_back(OrderBookEntry{
        20000,
        0.002,
        "2020/03/17 17:01:24.88492",
        "BTC/USDT",
        OrderBookType::bid
    });

    // Prints prices of all entries
    for (OrderBookEntry& entry : entries) {
        std::cout << "The price entry " << &entry << " is " << entry.price << std::endl;
    }

    std::cout << "The lower price is " << entries.computeAveragePrice() << std::endl;

    return 0;
}

There are three issues I am having here.
Firstly I am unable to call the computeAveragePrice() function to obtain the value that it is returning–in this case just a value of 5.5 for testing.

The image above is the error message for the line of code below.
std::cout << "The lower price is " << entries.computeAveragePrice() << std::endl;

Secondly, I am getting a weird value printed when I'm trying to print the index of elements in the vector.

The above is the output I got. I was expecting to get the respective indexes of the elements but got this instead. Here's the code that I used to iterate through the vector.
for (OrderBookEntry& entry : entries) {
    std::cout << "The price entry " << &entry << " is " << entry.price << std::endl;
}

Lastly, I could use some reference to any article that teaches me how to perform arithmetic on values within a vector such as averages, comparisons and finding differences.
Thank you in advance!

A: computeAveragePrice is a member function in OrderBookEntry but entries is a std::vector<OrderBookEntry>, not a OrderBookEntry so it doesn't have such a member function.
I suggest that you move computeAveragePrice out of the class OrderBookEntry, which only holds information about one single OrderBookEntry. You could create another class to hold a collection of OrderBookEntry and put it there instead. This class can be a simple wrapper around a std::vector<OrderBookEntry>:
Example:
class OrderBook {   // A class to store a collection of OrderBookEntry:s
public:
    // A function to add an `OrderBookEntry`. You'll have to make this in
    // in the way you want. This is just an example:

    template<class... Args>
    decltype(auto) add(Args&&... args) {
        return entries.emplace_back(std::forward<Args>(args)...);
    }

    double computeAveragePrice() const;              // move it here

    // some member functions that just call the vector's member functions:
    size_t size() const { return entries.size(); }

    OrderBookEntry& operator[](size_t idx) { return entries[idx]; }
    const OrderBookEntry& operator[](size_t idx) const { return entries[idx]; }

    auto cbegin() const { return entries.cbegin(); }
    auto cend() const { return entries.cend(); }
    auto begin() const { return entries.cbegin(); }
    auto end() const { return entries.cend(); }
    auto begin() { return entries.begin(); }
    auto end() { return entries.end(); }

private:
    std::vector<OrderBookEntry> entries;    // put the vector in here
};

double OrderBook::computeAveragePrice() const {
    // you need to #include <numeric> to use the accumulate function:
    if(entries.empty()) return NAN;   // not-a-number
    return std::accumulate(entries.begin(), entries.end(), 0.,
                           [](double tot, const OrderBookEntry& e ) {
                               return tot + e.price;
                           }) / entries.size();
}

With that, your main would look like below:
int main() {
    OrderBook entries;            // use the new collection class

    // Adding entries into entries
    entries.add(                  // using the add() member function
        10000,
        0.001,
        "2020/03/17 17:01:24.88492",
        "BTC/USDT",
        OrderBookType::bid
    );

    entries.add(
        20000,
        0.002,
        "2020/03/17 17:01:24.88492",
        "BTC/USDT",
        OrderBookType::bid
    );

    // Prints prices of all entries
    for (OrderBookEntry& entry : entries) {
        std::cout << "The price entry " << &entry << " is " << entry.price << '\n';
    }

    std::cout << "The average price is " << entries.computeAveragePrice() << '\n';

    return 0;
}

Note though that printing &entry will print the address of the OrderBookEntry. If you want to print something meaningful you need to add an overload for operator<< that takes an OrderBookEntry as input.
Example:
std::ostream& operator<<(std::ostream& os, const OrderBookEntry& e) {
    return os << e.product;
}

You could then print the entry, but not by taking its address:
for (const auto& entry : entries) {
    std::cout << "The price entry " << entry << " is " << entry.price << '\n';
    //                                 ^^^^^
}


text:
Q: ga:landingPagePath without request I'm still struggling with ga:landingPagePath (see ga:searchDestinationPage == ga:landingPagePath?).
Is there anyway to get a session with ga:landingPagePath==/pageA and ga:source==XY without a request to /pageA?utm_source=XY ?
I'm getting such results and I am sure there are no such requests!

A: You can try ga:landingPagePath=~^/pageA$


text:
Q: How to check in Windows if the service is not installed using batch file I'm trying to do a batch program that needs to check if the service is installed before checking if it is running/stopped.
I would just like to ask if there is any way that I can check the ERRORLEVEL of an uninstalled service when the OS is Windows XP.
In my code snippet:
ver | find /I "XP"
if %errorlevel%==0 goto ver_xp
goto ver_nonXP

:ver_xp
echo Windows XP
sc query myService > nul
echo %errorlevel%
if errorlevel ___I goto ServiceOk
if errorlevel ___ goto ServiceError
goto ServiceError

:ver_nonXP
echo Windows is not XP
sc query myService > nul
echo error1_percent %errorlevel%
if %errorlevel%==0 goto ServiceOk
if %errorlevel% NEQ '0' goto ServiceError
goto end

:ServiceError
echo Service is not installed
net helpmsg %errorlevel%
goto end

:ServiceError
rem do some operations here....

I tried to use
if errorlevel 1060 goto ServiceError

It seems that if the service is not installed, the condition above will always be false.
I made the errorlevel ____ because I don't know that the correct condition should be.

A: sc query myService  |find "myService" >nul will do the trick

A: According to this answer this is possible in batch using method you described How does one find out if a Windows service is installed using (preferably) only batch?
Alternatively you could query with powershell:
$serv_status = get-service "myService"
if($serv_status -ne $null)
{
    // do some operations here
}