text:
Q: How to write a session cookie in order to retain session when moving to another page In my website, after users log in and moves to a different page, their session is lost and on going back to the previous page(where their session was created) the page is blank, obviously because session is lost
I have two pages

*

*Account.php (where the session is created after loging in)

        Go to options

    <?php
      //Start of session
      session_start();

      //Setting up databse connection
      require_once 'databaseconnection.php';
      $conn = mysqli_connect($db_hostname, $db_username, $db_password,$db_database);
      if($conn->connect_error){
         die("CONNECTION FAILED:".$conn->connect_error);
      }

      //Getting phone number and pasword provided by user in the login page (Not included in this)
      if (isset($_POST['lpho']) &&
          isset($_POST['lpass'])){
          $lpho   = get_post('lpho');
          $lpass= get_post('lpass');

      //Getting user information from database
       $q="SELECT * FROM members WHERE phone='$lpho'";

       if($q) {
       //If record exists
       $querymember = "SELECT * FROM members WHERE phone='$lpho' ";
       $memberidentity = mysqli_query($conn,$querymember);
       //To get number of rows
       $rowsno = $memberidentity->num_rows;
       //To fetch specific member column from database as an array
       $memberrecords = $memberidentity->fetch_array(MYSQLI_NUM);

       $count=$rowsno;

       if($count>0){
       //$reqpass is user's password from the database which is specific to array no [7]
       $reqpass = $memberrecords[7];
       //If given password matches the required password...
       if($lpass==$reqpass){
         //Session details passed
         /*How do I put these in a cookie then load them on my next page */
         $_SESSION['lpho'] = $lpho;
         $_SESSION['lpass'] = $lpass;
       }
      }
     }
    }
    ?>

*Options.php (where the session dies when user navigates to it)

So my question in summary is how I can make a cookie in Account.php that saves lpho(phone) and lpass(password) then loads it to Options.php when user navigates to it.
<?php
    echo "This is the options page";
?>

A: Using sessions in PHP with cookies relies on sending cookies in the headers of the page. This means that session_start() must occur before any output from the page (as any output causes headers to be sent, and they can only be sent once per page). In your Account.php file the first thing you do is output your
 block, which will cause a headers already sent error when you try to set a cookie using session_start(). Move the session_start() to the beginning of each PHP file and that should resolve this problem. For example, in this file:
<?php
  //Start of session
  session_start();
?>

    Go to options

<?php
  //Setting up databse connection
  require_once 'databaseconnection.php';

Note that storing passwords in plain text is a very bad idea (in your case, both in your database and the session file on the server). You should use PHPs password_hash and password_verify functions to store and check passwords.


text:
Q: Pointing dereference inside a struct error i have a function to create a circular list, i am having issues compiling, not sure if it is syntax, appreciate if someone can help.
    void CreateCircularList(struct node** listRef, struct node** tailRef)

    {
    Push(&*listRef, "String 1");
    *tailRef=*listRef;
    Push(&*listRef, "String 2");
    Push(&*listRef, "String 3");
    Push(&*listRef, "String 4");

    *(tailRef->next)=*listRef;

    }

the compiler flags an error in the last line:

"Member reference base type 'struct node*' is not a structure or
  union"

Any ideas why ?  thanks

A: You probably want
  (*tailRef)->next = *listRef;

as the last assignment.
You cannot write tailRef->next since tailRef is a pointer to a pointer.
I also suggest just coding  Push(listRef, "Some string"); instead of your Push(&*listRef, "Some string"); for readability reasons.

A: I think you need to do it as below
(*tailRef)->next = *listRef;

i.e get the struct node * pointed to by tailref, dereference with -> to get the struct node * that is next and then set it to the element pointed to by listRef

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why won't my Query run? I have quite a few similar querys which do work, i have no clue why this one won't:
As soon as i run it i get:

An unhandled exception of type
  'System.Data.SqlServerCe.SqlCeException' occurred in
  System.Data.SqlServerCe.dll

...on the command.ExecuteNonQuery();
Any obvious misstakes?
public void BorrowMovie(int memberCardNumber)
{
    string connectionString = @"Data Source=|DataDirectory|\VideoStoreDB.sdf";
    SqlCeConnection connection = new SqlCeConnection(connectionString);

    connection.Open();
    SqlCeCommand command = new SqlCeCommand(
        "UPDATE Customer SET NumberBorrowedMovies = NumberBorrowedMovies+1 " +
        "WHERE MemberCardNR = @mcn)", connection);
    command.Parameters.AddWithValue("@mcn", memberCardNumber);
    command.ExecuteNonQuery();
    connection.Close();

    Console.WriteLine("Movie was borrowed!");
    Console.ReadLine();
}

A: You have unbalanced parentheses:
SqlCeCommand command = new SqlCeCommand(
    "UPDATE Customer SET NumberBorrowedMovies = NumberBorrowedMovies+1 " +
    "WHERE MemberCardNR = @mcn", connection);

Also, you should be using using blocks:
public void BorrowMovie(int memberCardNumber)
{
    string connectionString = @"Data Source=|DataDirectory|\VideoStoreDB.sdf";
    using (SqlCeConnection connection = new SqlCeConnection(connectionString))
    {

    connection.Open();
    using (SqlCeCommand command = new SqlCeCommand(
        "UPDATE Customer SET NumberBorrowedMovies = NumberBorrowedMovies+1 " +
        "WHERE MemberCardNR = @mcn)", connection))
    {
    command.Parameters.AddWithValue("@mcn", memberCardNumber);
    command.ExecuteNonQuery();
    // connection.Close(); no longer needed
    } // command
    } // connection
    Console.WriteLine("Movie was borrowed!");
    Console.ReadLine();
}


text:
Q: Gecko/Firefox 33.0 crashes on YouTube IFrame API ytPlayer.seekTo(seconds, allowSeekAhead) I do have serious issues with the youtube api. ytPlayer.seekTo() method crashes under Firefox 33.0 (used through desktop as well as slimerjs). It crashes on both firefox (full-installation) as well as xulrunner. Any ideas what may be the reason for this and how to solve it?
Error: Default Windows Error Promt: XULRunner stopped working The programm was closed in reaseon of an problem. You ll be notified as soon as an solution is available.

Shell Errors (Number in square brakets varii from execution to execution somehow random:
[6064] ###!!! ABORT: Aborting on channel error.: file c:/builds/moz2_slave/rel-m-rel-xr_w32_bld-000000000/build/ipc/glue/MessageChannel.cpp, line 1547
[12464] ###!!! ABORT: Aborting on channel error.: file c:/builds/moz2_slave/rel-m-rel-xr_w32_bld-000000000/build/ipc/glue/MessageChannel.cpp, line 1547

The code
<html>
<head>
    <script src="https://www.youtube.com/iframe_api"></script>
</head>
<body style="margin:0; padding:0">
<script>
var ytPlayer;
var nextPlayerTime = 0
// on api ready
function onYouTubeIframeAPIReady() {
    console.log("youtube iframe api ready");
    ytPlayer = new YT.Player("youTubePlayer", {
        events: {
            onStateChange: function(e) {
                if (e.data == YT.PlayerState.PLAYING) {
                    console.log("youtube playing go to next");
                    ytPlayer.pauseVideo();
                    nextPlayerTime +=10;
                    ytPlayer.seekTo( nextPlayerTime ,true );
                    ytPlayer.playVideo();
                }
            }
        }
    });
}
</script>

<iframe id="youTubePlayer" src="https://www.youtube.com/embed/hKWmFWRVLlU?version=3&vq=hd1080&enablejsapi=1&playerapiid=ytplayer&allowscriptaccess=always&wmode=opaque&autoplay=1" width="100%" height="100%" style="border: 0px;"></iframe>

</body>
</html>


text:
Q: installing twiki on ubuntu I want to install twiki on ubuntu server , http://mysite.com/docs/bin/configure is returning the configure file itself .
I renamed the twiki folder to docs .
How can I configure twiki, and why the file is coming in browser?
Please help .
Thanks

A: Please refer to the following URL for installing twiki on ubuntu and make sure you haven't missed any steps
http://ubuntuforums.org/showthread.php?t=219213
http://www.mactech.com/articles/mactech/Vol.22/22.06/Wiki/index.html

A: Just try apt-get install twiki (i am not sure it will work on sevrver but it worked for me on ubuntu 9.10 desktop edition)


text:
Q: php string two echo statements together this string is breaking my code and I am not sure why. If anyone can help me correct it I would appreciate it.
if ($p == $url) { echo '
'
. $label . '
'; } else { echo '
' . $label . '
'; }

A: htmlspecialchars(urlencode($url)) and htmlspecialchars($label). The rest seems fine.


text:
Q: trouble with Javascript while loop, what am I doing wrong? So I am doing a an exercise in which I have to sort a given string. Each word in the string contains a number in it(written like this 'H3llo'). The number that is in each word of the string should be placed in order according to the number in the new string that is to be returned.
For example if my input is "is2 Thi1s T4est 3a", then my function should return "Thi1s is2 3a T4est".
I almost cracked it but my output is incomplete. Here is my code:
function order(words) {
    var lst = words.split(' ');
    var count = 0;
    var n = count + 1;
    var s_n = n.toString();
    var new_l = [];
    while (count < lst.length) {
        if (lst[count].includes(s_n) === true) {
            new_l.push(lst[count])
        }
        count++
    }
    return new_l.join(' ');
}

When I test it, instead of getting:
console.log(order("is2 Thi1s T4est 3a"));
>>> 'Thi1s is2 3a T4est'

I get this:
console.log(order("is2 Thi1s T4est 3a"));
>>> 'Thi1s'

Can anyone explain to me what I am doing wrong?

A: You will basically need two loops - one for your current counter count i.e. the incremental number and another to iterate over the list of words to match that number. You increase the count only after you have finished iterating over the list.

function order(words) {
  var lst = words.split(' ');
  var count = 0;
  var new_l = [];
  while (count <= lst.length) {
    for (i = 0; i < lst.length; i++) {
      if (lst[i].includes(count)) {
        new_l.push(lst[i])
      }
    }
    count++;
  }
  return new_l.join(' ');
}
console.log(order("is2 Thi1s T4est 3a"));

Notice too that you don't need s_n -- the conversion is implicit, and you don't need === true as this is implicit in the if statement.

A: The main thing you are doing wrong is that you assign s_n to the string '1' before your loop, but you never update it within the loop. At the same time as you update count, you need to update s_n to the string of the next integer.
So you 'fixed' the part where you weren't updating the value of n or s_n within your outer loop, but the code still wont't work because you are now using count both to increment the digit you are looking for (within a word) and to increment the search through the list of words. You need an inner loop (and another variable) to increment the search.


text:
Q: PHP, HTML multiple chexbox valuesc I have got the php, html code.
And I want to post the multiple checkbox values, but this does not work dunno why, I can print count or array, it prints(0), does not matter
the array values is always empty
<form action = 'main.php?w=creatNewTemplate2' method = 'post'>
    <input type = 'text' name = 'templateName' maxlength = '30'/>

    <input type= 'checkbox' name= 'exercises[]' value='A' />A

    <input type= 'checkbox' name= 'exercises[]' value='B' />B

    <input type = 'submit' value = 'Sukurti'/>
</form>

if($w == "creatNewTemplate2")
{
    $d = $_POST['exercises'];
    $ddd = count($d);
    print_r($_POST);
}

A: I think this could work for you:
if($w == "creatNewTemplate2")
{
    $d = $_POST['exercises'];
    $ddd = count($d);

    for ($x = 0; $x < $ddd; $x++) {
        echo $_POST['exercises'][$x].'
';
    }
}

If you use same name you need to loop them

A: This should be work
Or you can change the two checkbox to select multiple

<form action="main.php?w=creatNewTemplate2" method="post">
    <input type="text" name="templateName" maxlength="30"/>

    <select multiple name="exercices[]">
       <option>A</option>
       <option>B</option>
    </select>
    <input type="submit" value="Sukurti"/>
</form>

<?php

if($_GET["w"] == "creatNewTemplate2")
{

  foreach ($_POST["exercises"] as $ex) {
    echo $ex . '
';
  }
}


text:
Q: How to Set ? in routeFile in Angular My Requirement is From Backend I am getting routes as "app/dashboard?dashboard_id={id}"
How can I configure this in Module.ts file?
I tried using below
const routes: Routes = [
  {
    path: "app/dashboard/:dashboard_id",
    component: AddEditComponent,
    canActivate: [AuthGuard],
  },
];

but I am getting errors like routes are not defined.
Can Someone Please Help me on that how can I configure this route as I need to catch this id as queryParams in Component.

A: You can do something like this:
const routes: Routes = [
  {
    path: "app/dashboard",
    component: AddEditComponent,
    canActivate: [AuthGuard],
    children: [
        {
            path: ':dashboard_id'
            component: NewComponentId
        }
    ]
  },
];

and in your NewComponentId you can do something like inside the constructor to catch the id:
this.route.paramMap.pipe(
      map((paramMap) => {
        if (paramMap.get('id') !== 'something') {
          // your code
        }
      }),

A: Required Route param:
{path: 'users/:userId', component: UserComponent}

and get it from param:
constructor(params: RouteParams) {
    var paramId = params.get("id");
}

Optional Route Param:
  { path: '/user', component: UserComponent }

its just define the route part and param pass by query string, to read the queryparam:
this.route.queryParams
      .subscribe(params => {
        console.log(params);
      }
    );

you must process the query string for this route: "app/dashboard?dashboard_id={id}"
Update:
To set the queryparam in routerlink use it this way:
  another dashboard


text:
Q: Arduino and temperature sensor hello i want to do a project using an arduino and a temperature sensor. let a certain temperature value be determined.when this value is exceeded, 1.if the engine temperature value is lower than the set value, 2.start the engine. what kind of scheme and coding should I do for this?
I want to know where to start

A: well here's some steps for you:

*

*Learn Programming (Algorithm, Syntax, etc)

*Learn Basic Arduino

*Learn to Read the Sensor Data

*Modify your code by adding "if" statement so you can achieve what you want

I guess your code would looked like this:
#include <library of the sensor if any>

int sensorPin = the number of the pin being used by the sensor;

void setup(){
    pinMode(sensorPin, INPUT); // a sensor is an input device
    //so we set the pin to be an input pin
}

void loop(){
    float sensor_value;
    sensor_value = algorithm to measure the temp;

    if (sensor_value < set value){
        //code to start the engine
    } else {
        //code to stop the engine
    }
}

I'm assuming that you need a relay to start or terminate the engine. Here's some references that might helps:
https://randomnerdtutorials.com/guide-for-ds18b20-temperature-sensor-with-arduino/
https://arduinogetstarted.com/tutorials/arduino-relay


text:
Q: Get text after certain point using NSString I am getting a url of a file when a user opens one from an NSOpenPanel for example like so:
/Users/Name/Documents/MyFile.png

So I just want this bit:
MyFile.png

However the user could have a file name of any length so how can I say, only get the string after the last forward slash (/)? I just want to get the file name.

A: NSString *fileName = [someStringContainingAPath lastPathComponent];
More general advice: spend a little time reading through the reference pages for NSString and NSString(UIStringDrawing). There are a lot of useful methods in there that you might not otherwise know to look for. In addition to -lastPathComponent demonstrated above, there's -pathComponents, -componentsSeparatedByString:, and many other handy tools.


text:
Q: In Kodein dependency injection, how can you inject instances of Kodein itself into instances? In Kodein, I have modules imported into a parent module, and sometimes the classes need an instance of Kodein so they can do injection themselves later.  The problem is this code:
val parentModule = Kodein {
    import(SomeService.module)
}

Where SomeService.module needs the Kodein instance for later, but Kodein isn't yet created.  Passing it later into the module seems like a bad idea.
In Kodein 3.x I see there is the kodein-conf module that has a global instance, but I want to avoid the global.
How do other modules or classes get the Kodein instance?
Note: this question is intentionally written and answered by the author (Self-Answered Questions), so that the idiomatic answers to commonly asked Kotlin/Kodein topics are present in SO.

A: In Kodein 3.x (and maybe older versions) you have access to a property within the initialization of any module called kodein that you can use in your bindings.
Within your module, the binding would look like:
bind<SomeService>() with singleton { SomeService(kodein) }

For a complete example and using a separation of interfaces vs. implementation, it might look something like this:
interface SomeService {
   // ...
}

class DefaultSomeService(val kodein: Kodein): SomeService {
    companion object {
        val module = Kodein.Module {
            bind<SomeService>() with singleton { DefaultSomeService(kodein) }
        }
    }

    val mapper: ObjectMapper = kodein.instance()
    // ...
}

You can import the module from the parent as you noted and it will receive its own reference to the current Kodein instance.
val kodein = Kodein {
    import(DefaultSomeService.module)
}


text:
Q: Cordova adds 350ms delay on click() events in iOS If I use something like $('button').click(function() { alert('hi'); } and I add the following to my <head>:
<meta name="viewport" content="user-scalable=no, width=device-width">

..and I run it as a normal mobile site on iOS 11, there is no delay (=> expected behaviour).
However, if I run the exact same code in a compiled Cordova hybrid app on iOS, the delay is back! (=> not good)
Do I have to start using fastclick.js or some other workaround again like it's 2013? What about other Cordova developers on here: do you experience the same problem?
PS: It works fine on Android.
PPS: Adding touch-action: manipulation; in CSS doesn't help unfortunately

A: About the fastclick issue, apparently, it's a new bug introduced with iOs 11.3.
Here is the full explanation
And here is a fork which resolves the fastclick issue with iOs 11.3
I'm also looking for a workaround, since fastclick doesn't look to be maintained anymore...

A: We experience the exact same problem.
Using FastClick as a workaround works for most iOS versions, except for the latest iOS release: 11.3.
After a fresh start of a Cordova app, FastClick works as expected but after a while (especially when calling native iOS calls like taking a photo), it shows weird behaviour where your input fields (nested in other divs) do not get selected at all and you have to tap multiple times to select an input field.
I have no clue why the 350ms delay is still active for (Cordova) apps and not for a standard mobile website opened in Safari.
Thanks to the tip from Romain Le Qllc, I replaced fastclick with the fork that he mentioned (https://github.com/lasselaakkonen/fastclick).
This resolves the issues in both iOS 11.3 and 11.4.
Also big thanks to lasselaakkonen.


text:
Q: Perturb a piecewise-linear path to make it $C^\infty$ I'm trying to prove that any two points on a path connected smooth manifold can be joined by a smooth path. It becomes easy if I can prove the following:

Given a curve $\gamma :\mathbb{R} \to \mathbb{R}^n$ that is
  $C^\infty$ at each point except at $t=0$ (and which has nonvanishing first derivative), and given a neighborhood $N$
  of $\gamma(0)$ in $\mathbb{R}^n$, there is a $C^\infty$ curve $\tilde{\gamma}:\mathbb{R} \to \mathbb{R}^n$ that agrees
  with $\gamma$ outside $\gamma^{-1}(N)$ (and has nonvanishing first derivative).

(I assume this is true. If there is some counter-example, we could make the domain of the curve compact if that would help.)
When referring to the fact that you can make a small pertubation of a path to make it smooth, some people have waved hands and said "you do it with bump functions". I am familiar with bump functions, but I don't know how to use one to accomplish this. I was thinking convolution with an approximate identity, but that seems to change the function everywhere, not just on a given neighborhood.
Could someone give me a thorough explanation (or a reference for one)?

A: Here's an argument that should work in $\mathbb{R}^n$ for $n \geq 3$. I guarantee that it is not the most elegant approach.
Assume $\gamma$ contains no segment along a line through the origin. (If $\gamma$ contains one or more such segments, shift it by a translation $\tau$ along a vector not in one of those lines. Then carry out the following procedure, which will only modify $\tau(\gamma)$ only in a small neighborhood of $\tau(\gamma(0))$. Afterwards, shift back by $\tau^{-1}$ to get a smooth arc which agrees with $\gamma$ outside a small neighborhood of $\gamma(0)$.)
Fix $\epsilon>0$ and suppose $b(t)$ is any smooth function $\mathbb{R}\to \mathbb{R}$ that is equal to 1 for $|t| \geq \epsilon$ and whose value and derivatives all vanish at 0. For any vector $v \in \mathbb{R}^n$ we  can consider the path $$\beta(t)=b(t)\gamma(t)+(1-b(t))tv,$$
which is smooth and agrees with $\gamma(t)$ for $|t|\geq \epsilon$. Its  derivative is given by
\begin{align*}
\beta'(t) &=
b'(t) \gamma(t) + b(t) \gamma'(t)+(1-b(t)-b'(t)t)v.
\end{align*}
Our approach will be to find $b$ and $v$ such that $\beta'(t)$ is nonvanishing. First note that the image of $[-\epsilon,\epsilon]$ under the map $t \mapsto b'(t) \gamma(t)+b(t) \gamma'(t)$ is a smoothly immersed arc in $\mathbb{R}^n$. For $n \geq 3$, there are lines through the origin which intersect this arc in at most one point (and only do so if the arc itself passes through the origin). Choosing $v$ to be any nonzero vector in such a line, we see that the only times $t_0$ at which $\beta'$ can possibly vanish are those such that both

*

*$1-b(t_0)-b'(t_0) t_0=0$, and

*$b'(t_0) \gamma(t_0)+b(t_0)\gamma'(t_0)=0$.

To address this issue, we narrow our search to a specific family of candidates for $b(t)$. Define $f: \mathbb{R} \to \mathbb{R}$ by
$$f(t) = \begin{cases} \left(1+\operatorname{Exp}\left(\frac{1}{t^2}+\frac{1}{t^2-1}\right)\right)^{-1} & |t| < 1 \\ 1 & |t| \geq 1.\end{cases}$$
Then for any $\delta$ satisfying $0<\delta<\epsilon$, it is straightforward to verify that the function $b_\delta(t)=f(t/\delta)$ is smooth and satisfies

*

*$b_\delta(t)=1$ for $|t| \geq \delta$ (hence for $|t|\geq \epsilon$),

*$b_\delta(0)=0$ and $\frac{d^k b_\delta(t)}{dt^k}\big|_{t=0}=0$ for all $k$, and

*$1-b_\delta(t)-t b_\delta'(t)=0$ at precisely two points $t=\pm t_\delta$ for some $t_\delta \in (\delta/2,\delta)$ that varies linearly with $\delta$.

It suffices to show that there exists some $\delta$ such that $b_\delta'(t)\gamma(t)+b_\delta(t)\gamma'(t)$ is nonzero for $t=\pm t_\delta$. Suppose not. Since $t_\delta$ varies linearly with $\delta$, we can find a small interval $(t_{\delta^-},t_{\delta^+})$ such that either $b_\delta'(t)\gamma(t)+b_\delta(t)\gamma'(t)$ or $b_\delta'(-t)\gamma(-t)+b_\delta(-t)\gamma'(-t)$ is zero for each $t \in (t_{\delta^-},t_{\delta^+})$. By continuity, there must actually be a subinterval of $(t_{\delta^-},t_{\delta^+})$ on which either (or both) of $b_\delta'(\pm t)\gamma(\pm t)+b_\delta(\pm t)\gamma'(\pm t)$ vanishes. Without loss of generality, suppose it is $b_\delta'(t)\gamma(t)+b_\delta(t)\gamma'(t)$. Then
$$(b_\delta(t) \gamma(t))'=b_\delta'(t)\gamma(t)+b_\delta(t)\gamma'(t)=0$$
on this subinterval, so $b_\delta(t)\gamma(t)$ is constant there. Since $b_\delta(t)$ is a scalar for all $t$, $b(t)\gamma(t)$ can be constant only if $\gamma$ contains a segment of a line passing through the origin. But we ruled this out back in the beginning. Thus we can find a $\delta$ of the desired form.
Finally, let's check the result: The derivative
$$\beta'(t)= \big[b'_\delta(t) \gamma(t)+b_\delta(t) \gamma'(t)\big]+\big[(1-b_\delta(t)-b_\delta'(t) t)v\big]$$
never vanishes because the two bracketed terms are never simultaneously zero and are linearly independent whenever they are both nonzero.

A: Let $U \subset \gamma^{-1}(N)$ be a neighborhood of $0$. Choose a smooth function $b : \mathbb{R} \to \mathbb{R}$ which is equal to $1$ outside $U$ and equal to $0$ in a neighborhood of $0$. Define $$\tilde{\gamma}(t) = b(t) \gamma(t).$$ Then $\tilde{\gamma}$ agrees with $\gamma$ outside of $\gamma^{-1}(N)$ ; it is smooth on $\mathbb{R}$ since it is constant near $t = 0$ and equal to a product of smooth functions for $t \neq 0$.
Edit: If $n \ge 2$, then $\tilde{\gamma}$ can be perturbed to obtain an immersion; see e.g. theorem 2.12 in chapter 2 of Differential Topology by Morris Hirsch. However, if your goal is simply to show that two points in a connected manifold can be joined by an immersed path, there is a more elementary approach.
Let $M$ be a smooth connected manifold and let $x$ and $y$ be two distinct points of $M$. Choose a point $z \in M\setminus\{x,y\}$ such that there exists a coordinate chart containing both $x$ and $z$. Then one can easily find a smooth embedded path $\gamma : [0,1] \to M$ such that $\gamma(0) = x$ and $\gamma(1) = z$. Since $M$ is connected, there exists a diffeomorphism $h : M \to M$ satisfying $h(x) = x$ and $h(z) = y$. Then $h\circ\gamma$ is an embedded path going from $x$ to $y$.
The fact that such an $h$ exists is not trivial, but not difficult to prove either. A reference is the book Differential Topology by Guillemin and Pollack, chapter 3, $\S$6. See also the "Homogeneity lemma" in $\S$4 of Milnor's Topology from the differentiable viewpoint for an alternative proof.


text:
Q: How can my server program read the variables sent using a HTTP 'GET' request method in VB.NET? I have written server code in vb.Net. I want it to read to variables sent by another server's HTTP 'GET' request. For example the first server will send this URL
http://localhost/sms/incoming.php?sender=$originator&receiver=$recipient&msgdata=$messagedata&recvtime=$receivedtime&msgid=$messageid where the values to be used by my server are sender, receiver, msgdata, recvtime  and  msgid I have written my code but it only reads the address sent by the http server and locates for the file in the server's root directory. I want the server to be reading the variables sent by the other server using the HTTP 'GET' request. My code is shown below
' the web server only accepts get requests.
    If Mid(LCase(sbuffer), 1, 3) <> "get" Then
        'if not GET request then close socket and exit
        mySocket.Close()
        Return
    End If

    ' Extract path and filename from request
    sRequest = sbuffer.Substring(0, iStartPos - 1)
    sRequest.Replace("\\", "/")
    If ((sRequest.IndexOf(".") < 1) AndAlso (Not sRequest.EndsWith("/"))) Then
        sRequest = sRequest & "/"
    End If

    iStartPos = sRequest.LastIndexOf("/") + 1

    ' Get the filename
    sRequestedFile = sRequest.Substring(iStartPos)

    ' Get the relative path
    sDirName = sRequest.Substring(sRequest.IndexOf("/"), sRequest.LastIndexOf("/") - 3)

    ' Web server root path
    sLocalDir = sMyWebServerRoot

    ' if no filename specified
    ' look for default file
    If (sRequestedFile.Length = 0) Then
        sRequestedFile = _DefaultPage
        sPhysicalFilePath = sLocalDir & sDirName & sRequestedFile

        ' if no default file and no directory requested
        ' then show welcome page
        If Not File.Exists(sPhysicalFilePath) AndAlso (sDirName = "" OrElse sDirName = "/") Then

            sErrorMessage = sErrorMessage & "

No root directory found. Set up the root directory in the configuration file.
"
            SendHeader(sHttpVersion, "", sErrorMessage.Length, " 404 Not Found")
            SendToBrowser(sErrorMessage)
            mySocket.Close()
            Return
        End If

    End If

A: You can get them from the Context.Request.QueryString object:
mySender = Context.Request.QueryString("sender").ToString

This assumes the code you are running on your server is running under IIS.  I notice the call is to a .PHP page and wonder how you are actually getting the url to the server running the VB code.
If this is simply processing the URL as a string, then the following should handle it for you:
        Dim tempArray As String()
    Dim tempValuePairs As String()
    Dim tempPair As String()
    Dim tempValue As String
    Dim tempString As String

    tempArray = sRequest.Split(CChar("?"))
    If tempArray.Length <> 2 Then
        'url not valid
        Return
    End If
    tempValuePairs = tempArray(1).Split(CChar("&"))

    For Each tempString In tempValuePairs
        tempPair = tempString.Split(CChar("="))
        tempValue = tempPair(1)

        'check for pair name, tempvalue will contain data
        Select Case tempPair(0).ToLower
            Case "sender"
                mySender = tempValue
            Case "receiver"
            Case "msgdata"
            Case "recvtime"
            Case "msgid"
            Case Else
        End Select
    Next


text:
Q: Texlive package list - svn or git I looked into several answers here but didn't quite find an answer to what I was looking for. I have texlive-2021 installed on a OpenSuse. Checking the package tools installed in my /usr/share folder I found that all files are dated by Feb 2020.
To my understanding there is a yearly release for texlive. Where do I find a list which packages were supposed to be included?
More or less the question how to check what was supposed and what is :-/


text:
Q: How to insert a normal distribution into another function? I am struggling with the following problem.
TLDR: I want to merge the uncertainty of the normal distribution into another function.
Imagine a certain significant wave height (Hs) of 2 metres in a sea state. One wants to know the Most Probable Maximum (MPM) of the largest wave that passes by in a certain period of time (3 hours). This is done by the following formula:
f_mpm = ((np.exp(-x**2/(2*m0)) * (1 - np.exp(-x**2/(2*m0)))**(N-1) * N*x) / m0)

$$
f_{mpm} = \frac{e^{-\frac{x^2}{2m_0}} * (1 - e^{-\frac{x^2}{2m_0}})^{N-1}*N*x}{m_0}
$$
Where:
N = 10800 / Tm (3 hours divided by the mean period of the waves)
Tm = 10 s --> N ~= 1000
m0 = (Hs/2)^2
However, let's say that the Hs is not known but normally distributed, as it is a forecast.
f_normal = 1/(sigma*np.sqrt(2*np.pi)) * np.exp(-(x-np.sqrt*(4*m0)**2/(2*sigma**2))

$$
\frac{1}{\sigma\sqrt{2\pi}} * e^{-\frac{\left(x-\sqrt{4*m_0}\right)^2}{2*\sigma^2}}
$$
Is there a way to (analytically) merge the two functions to calculate the MPM based on an uncertainty?
Below I included a graph of the two functions. If the solution was plotted as well, it would result in a flatter and wider yellow line.

A: The distribution of the random variable mpm given $Hs=y$ has density
$$
f_{mpm|Hs}(x|y) = \frac{e^{-\frac{x^2}{2 \left(\frac{y}{2} \right)^2}} * (1 - e^{-\frac{x^2}{2 \left(\frac{y}{2} \right)^2}})^{N-1}*N*x}{\left(\frac{y}{2} \right)^2}
$$
The marginal distribution of the random variable mpm is found by integrating the joint distribution over the variable $y$:
$$
f_{mpm}(x) =\int_{-\infty}^{\infty} \frac{e^{-\frac{x^2}{2 \left(\frac{y}{2} \right)^2}} * (1 - e^{-\frac{x^2}{2 \left(\frac{y}{2} \right)^2}})^{N-1}*N*x}{\left(\frac{y}{2} \right)^2} \frac{1}{\sigma\sqrt{2\pi}} * e^{-\frac{\left(y-\sqrt{4*m_0}\right)^2}{2*\sigma^2}} dy
$$
This integral cannot be found analytically.
I understand that it appears that  $Hs$ is almost always positive since the $\sigma$ is small. However, for the normal distribution, negative values are possible and therefore the normal distribution might not be appropriate. I searched online and cannot find any distributions that are conjugate for the ordinary Rayleigh distribution, let alone the distribution you have here.
I am not sure what your goal is here. Do you have some data and you want to find the maximum likelihood estimates of all the parameters in the joint distribution?


text:
Q: NSInvalidArgumentException: -[__NSCFNumber compare:]: nil argument I am using Flurry Analytics to track my app crashes and I keep running into this one:
NSInvalidArgumentException: -[__NSCFNumber compare:]: nil argument

What method in my app could be causing this?  Not sure which method I am using could throw this.
EDIT:
Here is the full crash report:
NSInvalidArgumentException: -[__NSCFNumber compare:]: nil argument
Msg: Crash! josh@robinruthusa.com (
    0 repziov2         0x000af2c1 repziov2 + 8897
    1 CoreFoundation   0x37450987 __handleUncaughtException + 74
    2 libobjc.A.dylib  0x3622f2d1 _objc_terminate + 128


text:
Q: `nginx_filter_xxx` metrics are missing I have:

*

*activated nginx_module_vts (see config below)

*configured and started nginx_vts_exporter

*configured prometheus to scrape metrics from nginx_vts_exporter
I'm able to see nginx_server_xxx and nginx_upstream_xxx metrics in prometheus graph console. However, I can't see nginx_filter_xxx metrics.
Also, filterZones property is present with full data in response to /status/format/json.
What I'm missing to get nginx_filter_xxx metrics in prometheus?
Below is the config of nginx_module_vts:
http {
  vhost_traffic_status_zone;
  vhost_traffic_status_filter_by_set_key $uri uri::$server_name;
  ...
}

location /status {
  vhost_traffic_status_display;
  vhost_traffic_status_display_format json;
}

Example of /status/format/json output:
{
    "hostName": "ctrl.localdomain",
    ...
    "connections": {
        "active": 4,
        ...
    },
    "sharedZones": {
        "name": "ngx_http_vhost_traffic_status",
        ...
    },
    "serverZones": {
        "nginx-vts.localhost": {
            "requestCounter": 5,
            ...
        },
        "php-fpm.localhost": {
            "requestCounter": 6,
            ...
        },
        ...
        "*": {
            "requestCounter": 18,
            ...
        }
    },
    "filterZones": {
        "uri::nginx-vts.localhost": {
            "/status/format/json": {
                "requestCounter": 5,
                ...
            }
        },
        "uri::php-fpm.localhost": {
            "/status": {
                "requestCounter": 6,
                ...
            }
        },
        ...
    },
    "upstreamZones": {
        "::nogroups": [{
            "server": "127.0.0.1:9000",
            "requestCounter": 6,
            ...
            "inBytes": 624,
        }, {
            "server": "127.0.0.1:49090",
            "requestCounter": 7,
            ...
        }]
    }
}

A: Version 0.6 of nginx_vts_exporter I have used doesn't support filter zones. Version 0.7, released on Nov 10th, 2017, supports it.
Please refer to nginx_filter_xxx metrics are missing in prometheus graph console for more details.


text:
Q: specflow + xunit .. trying to skip testing in .net core I'm trying to skip tests under certain conditions and this is what I'm doing.
    public static void BeforeScenario(ScenarioContext scenarioContext)
    {
        if (scenarioContext == null)
            throw new ArgumentNullException("scenarioContext");
        string title = scenarioContext.ScenarioInfo.Title;
        if (shouldSkipTest(title))
        {
            var unitTestRuntimeProvider = (IUnitTestRuntimeProvider)scenarioContext.GetBindingInstance(typeof(IUnitTestRuntimeProvider));
            unitTestRuntimeProvider.TestIgnore("Ignore in rd");
        }
    }

I'm getting Xunit.SkipException ...  I tried TestInconclusive and TestPending, but they throw similar exceptions. Not sure what the correct way of skipping tests is. Any help would be very appreciated!!

A: Since SpecFlow 3.1 we are using xUnit.SkipableFacts when you are using xUnit.
You are able to use the API of it to skip scenarios.
Like
Skip.IfNot(Environment.IsWindows);

Btw, the BeforeScenario Hook method doesn't need to be static. This is only required for Before/AfterTestRun and Before/AfterFeature hooks.

Full disclosure: I am the community manager and a maintainer of SpecFlow and SpecFlow+


text:
Q: Population-level data with small n's I have population data (not sample data) and I'm looking at incidence over time in the population.  I have small n's (for the incidence and for the overall population).  For example, I have an incidence of 9, occurring in a population of about 40,000. Because I am dealing with small n's, would it be appropriate to use confidence intervals and trend analysis, even though I am not actually working with a sample?

A: If you are really dealing with population data than there is nothing to estimate, since there is no uncertanity. The event happened in the population exactly 9 times.
Check also: Statistical inference when the sample "is" the population and What is the difference between a population and a sample? (as @whuber may be right that you may be misinterpreting your sample as population).


text:
Q: Android : errors to load google map I'm trying to load a map with Google API V2, but i meet few errors that i don't understand..
I've these errors :
Could not find class 'gpr', referenced from method gps.a
Could not find class 'com.google.android.gms.location.internal.ParcelableGeofence',      referenced from method glt.a
Failed to load map. Error contacting Google servers. This is probably an authentication issue (but could be due to network errors).

Here, it's my manifest (a part) :
    <uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

       <uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission  android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="@string/keyAndroid"/>

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

I forgot something ? I checked the SHA1 of my certificate, and there is no error with that.
Thx,

A: There is a difference between Debug and Release keys. You need to generate the specific SHA1 key for the developer console and for your specific use of the app.

DEBUG
When you want to see the map in debug, you will find the debug key here (eclipse)

Or in the folder

~/.android/debug.keystore

In Windows it is

C:\User\YourUser.android\debug.keystore

You need to generate the SHA1 key of that keystore and add it in the Developer Console in your Google Maps API v2 for Android

RELEASE
For release keys you will have to go trough these four steps:
You need to (taken from here Generating Google map Release API Key):

*

*Create your own signing key that you will use for publishing, using Keytool : http://developer.android.com/guide/publishing/app-signing.html#cert

*Get the MD5 fingerprint of your newly generated key : https://developers.google.com/maps/documentation/android/mapkey#getfingerprint

*Submit the signature to this link to get your Google Maps key : https://developers.google.com/android/maps-api-signup?hl=fr

*Export your application with your newly created key, in Eclipse : right click on your projet -> Android Tools -> Export signed application package.
Important thing to notice here, that you need to add the package name at the end of the SHA1 key. Like

AB:CD:EF...:08;com.yourpackage.yourapp

USING THE KEYS
Then when you got those two keys, you will have to update it always when you are either using debug or release. Don't mix them up, write a comment next to the key entry like
<!-- DEBUG KEY: 12345... -->
<!-- RELEASE KEY: 23456... ->


text:
Q: Fetch API Delay I'm attempting to fetch data on my server using the fetch API for the request, but the request is taking FOREVER to process (it does eventually process). I'm using React as my view, and Express is serving up my pages. I've listed my Express and JSX code below. Any insight into why this may be happening (The 'mounted' message is logged immediately as expected, but the fetch API after delays) ?
Express:
app.use('/test',function(){
          console.log('connected');
  })

React.JS:
componentDidMount(){
      console.log('mounted');
      fetch('./test').then(function(response){
          console.log(response);
      }).catch(function(error){
          console.log(error);
      })
  }

A: You have to send  the response in the server side :
app.use('/test',function(request, response){
          console.log('connected');
          response.send(); //!!!!! this line
         //Or:  response.sendStatus(200); to send status code without body

  });

... otherwise the endpoint will not be terminated.


text:
Q: Garbage value in iOS Hi guys I am having a very simple problem.
I have created a class called PreferenceHelper and I have a static function as shown below
+ (int) getInt:(NSString *)key{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSInteger value = [prefs integerForKey:key];
    if ([prefs valueForKey:key] == nil||key==nil) {
        return 0;
    }
    int valInt = (int)value;
    return valInt;
}

I invoke the above code from another block of code from another class as mentioned below
[FBRequestConnection startWithGraphPath:@"me/scores"
                          completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                              if (!error){
                                  int parseScore = [PreferenceHelper getInt:@"highscore"];
                              } else {
                                  NSLog(@"failed");
                              }
                          }];

When I debug towards the getInt function in PreferenceHelper the variable key(NSString *) loses its value and sometimes become nil. Also even if the value returned by the function is 0 , the value received by parseScore is a garbage value. anyone knows the reason?

A: Your function looks a little overwrought. It will probably be more robust (and functionally identical) if it looks something like this:
+ (int) getInt:(NSString *)key
{
    if(!key)
        return 0;

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

    NSInteger value = [prefs integerForKey:key];

    return (int)value;
}


text:
Q: Drupal 8 Url::FromRoute toString() Don't take the braces I would like to recover a road with URL::FromRoute
Except that I have some concerns when I use to toString
$path = Url::fromRoute('my_route_name',['mypParamsId' =>  'MYPARAMSID'])->toString();

In this way I find a road but it's not the right one
I wish I could recover that
$path = Url::fromRoute('my_route_name',['mypParamsId' =>  '{MYPARAMSID}'])->toString();

But when I use the toString it does not work and Drupal cannot access my route and if I remove the String it returns my object to me without error

A: Try this:
$myurl = Url::fromRoute('my_route_name',['mypParamsId' =>  $theValue]);
$link = \Drupal::service('link_generator')->generate('title', $myurl);

Then print $myurl
Because, it implements _toString()
Or
Using Drupal\Core\Link for the 2nd line
$url = Url::fromRoute('myrouteName', array(
          'My_id' => $item->id
    ));

$link= Link::fromTextAndUrl($item->id, $url);


text:
Q: Python/Flask add key to inner dictionary I am trying to construct a dictionary with a list of IDs, which will be used as the response from an API. The dict will be used to generate a JSON response.
I am trying to append a list of IDs that have been affected by the request, but am experiencing an error shown below the code.
I have the following code:
data = {"data" : { "message" : "UPDATED TICKETS SUCCESSFULLY", "status" : 200}}
data['data'].append({"child_ids" : child_sr_ids})

The error that I am getting is: AttributeError: 'dict' object has no attribute 'append'
This seems to contradict other sources that I have read such as this: Appending to list in Python dictionary
I am sure I'm doing something simple wrong but I can't work it out. Would appreciate some direction.
edit: title has been changed to better reflect the correct terminology

A: You're not appending to a list, you're adding a key to the inner dictionary. What you're looking for is:
data['data']['child_ids'] = child_sr_ids

A: data["data"] is not a list. It is a dictionary. There isn't a single list in your code. I think what you want to do here is:
data["data"]["child_ids"] = child_sr_ids

A: simply try the line below or use dict update
data["new key"] = "some new entry"


text:
Q: ob_get function make & to amp; public function parseBlade($string, $param = null)
{
    app(\Illuminate\Contracts\View\Factory::class)
        ->share('errors', app(\Illuminate\Support\MessageBag::class));

    extract(app('view')->getShared(), EXTR_SKIP);
    $__env->incrementRender();

    if ($param) {
        extract($param, EXTR_SKIP);
    }
    unset($param);

    ob_start();
    eval('?>' . app('blade.compiler')->compileString($string));
    $content = ltrim(ob_get_clean());

    $__env->decrementRender();
    $__env->flushStateIfDoneRendering();

    return $content;
}

$text = $template->content;
$data = array(
    'token'=>$param['temporaryOrder']['token'],
    'user'=>$param['isUseImei']);
$url = http_build_query($data,'','&');
$obj->setViewData([
    'text' => $this->parseBlade($text,
    [
        'email' => $email,
        'link' => config('frontend.ec_protocol') . $office->subdomain . config('frontend.ec_url') . '/order/registration?'. $url
    ]),
]);

After calling ob_get_clean(), it changes the & in the link to &. Is there any way to solve this problem?

A: $test = '&';

echo htmlspecialchars(htmlspecialchars($test));

A: When you are passing data to the blade template, {{ $variable }} OR echo inside the view file that will properly encode any characters that should not be placed directly in HTML.
The simplest solution is to disable HTML-encoding: {!! $variable !!}.


text:
Q: How to run windows console application in java code using exec() method? how use Runtime.getRuntime().exec()?
I try:
try {
    String[] callAndArgs = {"path\\program.exe","arg1","arg2","arg3"}
    System.out.println("before");
    Process p = Runtime.getRuntime().exec(callAndArgs)
    System.out.println("in");
    p.waitFor();
    System.out.println("after");
} catch (IOException e) {
            System.out.println("catch io: " + e.getMessage());
        } catch (InterruptedException ie) {
            System.out.println("catch ie: " + ie.getMessage());
        }

And program doesn't work. Output:
before
in
after

hm? help ;p

A: See this (classic) article: http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

A: Maybe this could help too (http://ubuntuforums.org/showthread.php?t=681779),
import java.lang.* ;

 public class MyJavaClass
 {
 public void runCmd(String[] args)
 {
 String cmd = "/home_dir/./my_shell_script.sh" ;
 Runtime run = Runtime.getRuntime() ;
 Process pr = run.exec(cmd) ;
 pr.waitFor() ;
 BufferedReader buf = new BufferedReader( new InputStreamReader( pr.getInputStream() ) ) ;

 while ( ( String line ; line = buf.readLine() ) != null )
 {
 System.out.println(line) ;
 }

 }

 }


text:
Q: How Should I pass a secret variable in the .tf file HI I am trying to create a storage blob container in which the source uri = the SAS key key generated referring to the other storage account. It is working fine but i have to pass the SAS key as secret ( in azure portal)
I tried giving the SAS key directly, it is working but i need to pass the SAS key as secret

A: You can add TF_VAR_sas_token as a pipeline variable with secret type.
When you perform a terraform plan and then terraform apply, please specify the values of the variables using the -var flag.
Please refer to link for more details.

A: Another option is to save your SAS token in Azure Keyvault and link it to variable group. Authorize your pipeline to use the variable group.
Under your variables section: use
variables:
  - group: devgroupname

and use your secret name in script like this.
- task: Bash@3
            displayName: 'Terraform Init'
            env:
              ARM_CLIENT_ID: $(AZURE_CLIENT_ID)
              ARM_CLIENT_SECRET: $(AZURE_CLIENT_SECRET)
              ARM_SUBSCRIPTION_ID: $(AZURE_SUBSCRIPTION_ID)
              ARM_TENANT_ID: $(AZURE_TENANT_ID)
            inputs:
              targetType: inline
              script: |
                terraform init \
                  -backend-config="access_key=$(tf-az-sa-key1)"
              workingDirectory: "$(System.DefaultWorkingDirectory)/$(FILE_PATH)"


text:
Q: Flutter custom widget test with callback function fails I've implemented a custom widget for which I'm trying to create test cases. Below is my custom widget. It has one method which is onObserve. So whenever controller detects some data, it calls onObserve method.
class CustomWidget extends StatefulWidget {
  final ValueChanged<Model>? onObserve;

  const CustomWidget({super.key, required this.onObserve});

  @override
  State<CustomWidget> createState() => _CustomWidgetState();
}
class _CustomWidgetState extends State<CustomWidget> {
  @override
  Widget build(BuildContext context) {
    MyController mController = MyController();

    return Stack(
      children: [
        Center(
          child: SizedBox(
            width: 350,
            height: 350,
            child: MyObserver(
                controller: mController,
                onDetect: (code, args) {
                  if (code.value != null) {
                      //...TODO
                      widget.onObserve!(myObservedData);
                  }
                }),
          ),
        ),
      ],
    );
  }
}

Below is my test case :
testWidgets('on observe', (WidgetTester tester) async {
    var mModel = Model();

    await tester.pumpWidget(MyWrapper(Scaffold(body: CustomWidget(
      onObserve: (value) {
        value.address = '5, ABC-123';
        mModel = value;
      },
    ))));
    await tester.pumpAndSettle();
    expect(find.byType(CustomWidget), findsOneWidget);
    expect(find.byType(MyObserver), findsOneWidget);
    expect(mModel.address, '5, ABC-123');
    await tester.pumpAndSettle();
  });

This test case is failing always because it's not going into onObserve method. What I'm trying to do is setting data in onObserve method and verifying with expect(mModel.address, '5, ABC-123'); which is always failing. Is there anything wrong with above test ?

A: If I understand correctly, onDetect of your MyObserve will only be triggered if something happen
await tester.pumpWidget(MyWrapper(Scaffold(body: CustomWidget(
      onObserve: (value) {
        value.address = '5, ABC-123';
        mModel = value;
      },
    ))));
await tester.pumpAndSettle();

Above section of your code only await for your CustomWidget build done, it doesn't wait for onDetect to be triggered, so code inside onObserve will not be called
I don't know excalty your MyObserve do, so I fake this example, you can follow it:
testWidgets('on observe', (WidgetTester tester) async {
    var mModel;
    await tester.pumpWidget(MyWrapper(
      home: Scaffold(body: CustomWidget(
        onObserve: (value) {
          mModel = value;
        },
      )),
    ));

    // You maybe need to implement code to trigger your MyObserve class here
    final CustomWidgetState customWidgetState = tester.state(find.byType(CustomWidget));
    customWidgetState.triggerOnDetect();

    await tester.pumpAndSettle();
    expect(find.byType(CustomWidget), findsOneWidget);
    expect(mModel, 123);
  });


text:
Q: How can I do bulk inserts into the Common Data Service? I have 1000 records that I need to sync daily from an API. I am currently bulk inserting them into a SQL Database, however I would like to use Dataverse/a Common Data Service database instead.
The Logic App connector seems to do 1 record at a time and the SDK does PUTS and POSTS. How can I either insert 1000 records into the Common Data Service in bulk OR somehow synchronise my SQL DB with the CDS?

A: As far as I know there is no another way to do that without programming. You can extended your Power Automate Flow with Azure Functions to insert these records in a single transaction.
In this link explain how can be do it.
https://learn.microsoft.com/en-us/powerapps/developer/data-platform/webapi/execute-batch-operations-using-web-api#when-to-use-batch-requests
Please let me know wtih anything

A: If you want to regularly ingest data (1000 rows) into Dataverse (CDS), then use Dataflows. The following link to MS Docs describes how to set up scheduled bulk data updates. It is therefore a pull rather than push model.
https://learn.microsoft.com/en-us/powerapps/maker/data-platform/create-and-use-dataflows


text:
Q: Nibble Restriction to 0-9 Hello fellow Programmers,
int main()
int n;
scanf("%d", &n ,);
printf("nibble =  %d%d%d%d", (n/8)%2, (n/4)%2, (n/2)%2 , n%2 );

return 0;}

I´ve build this code so far, the code converts a decimal value into a nibble.
It works but i have questions regarding on how to restrict the input to 0-9,
without using if statemens. Is there any possiblty to do that and if how ?
At the moment the code uses 0 - 15 decimals.And can you please give me an example or explain to me so i can understand it .
Thank you!

A: that is not possible without using conditions
but tell us what your program should do if a decimal >9 is putted in?
scanf("%d", &n ,);
if ((n>=0) && (n<10))
  printf("nibble =  %d%d%d%d", (n/8)%2, (n/4)%2, (n/2)%2 , n%2 );
else
  printf("err: input out of range");


text:
Q: How to deploy ASP.NET Core UserSecrets to production I followed the Safe storage of app secrets during development guide over on the asp.net docs during development but it does not describe how to use it when publishing to another machine for QA, Production, etc.  What I figured it would do was insert them into the appsettings.json during publish but it does not.  I ended up having to place my SendGrid keys and other sensitive information directly into the appsettings.json which really defeats the purpose of the app secrets.
Is using app secrets the best way or is there another way to store API keys and SQL user/passwords in my configs?

A: Don't use app secrets in production. Ever. As the article says DURING DEVELOPMENT.
How you publish secrets in production is up to your production environment. Linux, Windows and Azure all support environment variables - that's where your secrets should go, using whatever UI your hosting provider gives you.
The app settings documentation goes into this in greater detail

A: Why "don't use app secrets in production". Is it encrypted secrets safe? It's very acceptable for app configuration, for example, your mentioned SendGrid for password recovery. Is it configuration secrets at all in server? Why do I prohibited? Just copy compiled from development to production and it works.
Startup.cs
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        var builder = new ConfigurationBuilder().AddUserSecrets<Startup>();
        Konfiguration = builder.Build();
    }

    public IConfiguration Configuration { get; }

    public IConfiguration Konfiguration { get; }

    public void ConfigureServices(IServiceCollection services)
           ....
        services.AddSingleton<IEmailSender, EmailSender>();
        services.Configure<AuthMessageSenderOptions>(Configuration);
        if (Configuration["SendGridKey"] != null)
            return;
        // linux'e secrets.json nenuskaitomas
        services.Configure<AuthMessageSenderOptions>(options => {
            options.SendGridKey = Konfiguration["SendGridKey"];
            options.SendGridUser = Konfiguration["SendGridUser"];
        });
    }

HomeController.cs
    private readonly IOptions<AuthMessageSenderOptions> _optionsAccessor;

    public HomeController(..., IOptions<AuthMessageSenderOptions> optionsAccessor)
    {
        ...
        _optionsAccessor = optionsAccessor;
    }

    public IActionResult Index(...)
    {
        if (_optionsAccessor.Value.SendGridUser != null)
            ModelState.AddModelError("", _optionsAccessor.Value.SendGridUser);
        ....

Go forward with "Enable account confirmation and password recovery"
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/accconfirm?view=aspnetcore-2.1&tabs=visual-studio#configure-email-provider


text:
Q: mySQL tree relationships with complex entities I'm busy putting together a database with a structure as follows:
Table named articles has a 1-to-many relationship with the table named field_groups. field_groups has a 1-to-many relationship with the table named fields, however, field_groups requires a tree structure where each field_group can be a parent or child to another field group.
I'm aware of the nested set model for dealing with hierarchical relationships but I'm not sure that this will work well in this case. Not only would I need to maintain the hierarchy of nodes but also retrieve related data for each node, I can't see away around this without looping through and querying for each separate node(a theoretically infinite number of nodes).
For this reason I'm considering going with mongoDB or similar because I believe it will handle this situation quite elegantly, it's worth mentioning that field_groups will only ever be queried in the context of its parent article. I'm aware of some of the various criticism of mongoDB, so I'm not here to ask for advice on that, what I really want to know before committing to another DB solution is - is there a known way to deal with this sort of situation in mySQL?

A: You need a field_group_id in fields which would be a foreign key to the field_groups table and you need an article_id in the field_groups table which would be a foreign key to the articles table. Also, you need a parent_id in the field_groups table which would be a foreign key to the field_groups table. If you have this structure in the database table you can get your data using queries with joins. You can make things easier by using an ORM above your MySQL. Of course, you can switch to MongoDB, I just wanted to show you that there is a solution to your problem in MySQL.


text:
Q: return type of method with nested promises I am getting error from resharper

Cannot convert type 'IPromise < IPromise < void > >' to type
  'IPromise < void >': Types of property 'then' of types 'IPromise < void >'
  and 'IPromise < IPromise < void > >' are incompatible

but if I compile the project using tsc from command line I am not getting any error. As I understand the nested promises are being handled by angular and the calling method does not have to check for nested then
example code
private somemethod(): ng.IPromise<void> {
        return this.promiseOuter().then(this.promiseInner);
}

private promiseOuter = (): ng.IPromise<void> => { }

private promiseInner = (): ng.IPromise<void> => { }

so what really is return type: is it promise< void> or promise< promise <void>>


text:
Q: Is parallel processing actually possible? I have seen new computers having two processors on same motherboard .
How can two processors on same motherboard function properly because it will be something like two brains (trying) to control one body, How actually they carry out parallel processing, is it actually does it ?

A: There are rules which decide who wins if the two (or more) CPUs/cores want to access the same resource. Usually, one CPU will try to access it later, so it will have to wait. If two CPUs actually want to access the same resource at the exact same time, then the rules will make sure that one wins. Today, the rules have become quite complex to make sure that one CPU can't hog a resource (draining the other one).
Caching is a very complex part of this; every CPU will copy part of the real RAM into its caches. That means if CPU 1 has the address X in its cache and the CPU 2 reads or writes that address, then interesting things can happen. Technologies to solve this are address sniffing (CPU 1 notices which addresses CPU 2 wants to see and sends a signal to tell it that the content of this address isn't valid right now), segmentation of RAM (the CPUs can't actually see most of the RAM, so there are only small overlaps where this problem can actually happen), or a special cache bus where the caches of the CPUs talk to each other ("I just read this address", "I'm writing X into that address").
It's a very complex area and it gets more complex with every day. As far as we can tell, this is the only way to keep Moore's Law up for a few more years.
For more details, see the Wikipedia article.


text:
Q: Jooq transactions: connections are not released to pool, if exception thrown in transaction I'm using HikariCP with Jooq.
The code:
*In Kotlin:
//dataSource is from Hikari
DSL.using(dataSource, sqlDialect).transaction {
     config ->
     //in create it simply calls dsl.insertInto ....
     UserRepo.create(User(name="joe"), DSL.using(config))
     UserRepo.create(User(name="foo"), DSL.using(config))

}

And everything runs ok.
But if I throw in block, the connections are not closed (released) (though the transaction is rolled back).
UPDATE:
I'm new to Java so it was my fault. In test, I used to throw Kotlin's Throwable (not the Exception), which was not correctly handled by Java part of the code.
Everything works as expected with regular Exceptions.

A: As you've noticed, given your question edit, jOOQ internally catches only Exception subtypes, not Throwable subtypes in order to influence the transaction management. In DefaultDSLContext.transactionResult0(), you can see the following code (taken form version 3.9.6, shortened for this question):
try {
    provider.begin(ctx);
    result = transactional.run(ctx.configuration());
    provider.commit(ctx);
}
catch (Exception cause) { // <-- This is the problem
    ctx.cause(cause);
    provider.rollback(ctx);

    if (cause instanceof RuntimeException) {
        throw (RuntimeException) cause;
    }
    else {
        throw new DataAccessException("Rollback caused", cause);
    }
}

As you can see, while there is a distinction between checked and unchecked exceptions there's no distinction between Exception and Throwable.
Rationale, in Java vs Kotlin / Scala
Historically, in Java, no one really creates Throwable subtypes. That type only exists as a common super type for Exception and Error. So, the assumption is that a Throwable is either of the above, and Error types usually shouldn't be caught by any client / library code.
That assumption is invalidated by languages like Kotlin and Scala, which do not inherit this, admittedly a bit weird API design from early Java days. There's no reason why a user-defined exception shouldn't directly extend Throwable. Unfortunately, the status quo means you cannot use throwables, you have to throw exceptions.
Bug
This is certainly a bug in jOOQ and should be fixed:
https://github.com/jOOQ/jOOQ/issues/6608
As it is somewhat backwards-incompatible in terms of behaviour, it will only be fixed in a minor release, i.e. 3.10


text:
Q: jQuery - Loading Thumbnails basically I have thumbnails at the bottom of the page and one large image. I want to be able to hover over the thumbnails and have the source of the thumbnail replace that of the big image so the thumbnail takes its place.
Please someone help!! I need to get this finished asap, is there any other info I should provide?!
This is the code I am using:
jQuery('.image-rollover').hover(function() {
    var src = $(this).attr("src").match(/[^\.]+/);
    jQuery('.replace img').replace("src", src);
});

A: jQuery('.image-rollover').hover(function() {
    jQuery('.replace img').attr("src", this.src);
});

A: This is the general idea of how you might want to set this up:
http://jsfiddle.net/GuSeg/
You want to swap the src of your mainImage with the src of the hovered image which is done by:
$('.thumbnailToHoverOn').hover(function(){
    $("#mainImg").attr("src", $(this).attr("src"));
});


text:
Q: Combinatorial Proofs with Summation on One Side How do I go about approaching the following problem?
$$\sum_{k=1}^n k^2 C(n,k) = n(n+1)2^{n-2}$$
I don't know how to interpret the summation of something combinatorially, especially with a k^2 term. Any help or tips would be greatly appreciated!

A: The combinatorial proof:
Given $n$ people, choose a committee of size $k$, then choose a chairperson and a vice chair person (possibly the same person) ... This the LHS.
Another way ... if the the chair & vice are the same person $n2^{n-1}$ ... & if the are different $n(n-1) 2^{n-2}$ ... add these, this is the RHS.


text:
Q: How to extract the particular string in XML without Parsing in iPhone? I have received the data using NSURLConnection and i got the following strings, which is XML formats of string. Now i want to take the status node of string. I want to take that string without using XML parsing.
 -(void)connectionDidFinishLoading:(NSURLConnection *)connection{

     NSString *urlDataString = [[NSString alloc] initWithData:self.recieveData encoding:NSUTF8StringEncoding];

Return String:
    <?xml version="1.0" encoding="Utf-8"?><blacksheep><status>Success</status></blacksheep>

Output:
  Succeess

PLease help me out.
Thanks.

A: NSString* str = @"<?xml version=\"1.0\" encoding=\"Utf-8\"?><blacksheep><status>Success</status></blacksheep>";
NSString* status = [[[[str componentsSeparatedByString: @"<status>"] objectAtIndex: 1] componentsSeparatedByString: @"</status>"] objectAtIndex: 0];

But be careful: this is short but not very safe method. So you'd better add some additional checks.
Edit: better way is
NSString* status = @"Failed";
NSArray* arr = [str componentsSeparatedByString: @"<status>"];
if( [arr count] > 1 ) {
      status = [[[arr objectAtIndex: 1] componentsSeparatedByString: @"</status>"] objectAtIndex: 0];
}


text:
Q: How to lead onto any statement after reaching a contradiction Background:
Let me cite a part from the book Zero: a dangerous idea (as some don't appear to get why I intently divide by zero).

"Dividing by zero once—just one time—allows you to prove, mathematically, anything at all in the universe. You can prove that 1 + 1 = 42, and from there you can prove that J. Edgar Hoover was a space alien, that William Shakespeare came from Uzbekistan, or even that the sky is polka-dotted. [...] Multiplying by zero collapses the number line. But dividing by zero destroys the entire framework of mathematics."

Proof
Let $a$ and $b$ equal $1$. Then
$$b^2=ab \tag{1}$$
As $a=a$,
$$a^2=a^2 \tag{2}$$
$(2)-(1)$ $\rightarrow$
$$a^2-b^2=a^2-ab \tag{3}$$
Simplify $(3)$,
$$(a-b)(a+b)=a(a-b) \tag{4}$$
Divide by $(a-b)$ and simplify,
$$b=0\tag{5}$$
As $b=1$,
$$0=1\tag{6}$$
Then suppose $0=1 \rightarrow A \land \lnot A$
$$\ldots$$
$$A\equiv B$$
And from here you can prove any statement you want.
("$\ldots$" is signifying missing steps).

I don't know how to logically prove that $0=1 \rightarrow A \land \lnot A$ (the missing steps that "$\ldots$" represents) to get that $A\equiv B$. I know too little math to do such a proof. Can I get help with doing this part of the proof?

A: What the sentence you quoted is saying is two things:

*

*If we allow division by zero then we can always reach a contradiction and the system becomes inconsistent.

*From a contradiction we can prove anything.
A formal system is a set of axioms and rules (of inference) over a language. A proof of $A$ from $\Gamma$ in a formal system (where $A$ is a formula -i.e. sentence- and $\Gamma$ is a set of formulas) is a sequence where the last element of the sequence is $A$ and each element of the sequence is either in $\Gamma$ or an axiom of the system or deduced by rules from previous members of the sequence (see an example of a proof at the end). If it is possible to prove $A$ from $\Gamma$ in the formal system $L$ we write $\Gamma\vdash_L A$ (subscript is dropped when there is no confusion). So we can formalize the second sentence as $A\land \neg A\vdash B$. Note that your formalization of the problem, (i.e. getting from $A\land \neg A$ to $A\equiv B$) is not correct. When you say "Dracula is a flying pig" being a pig and being able to fly are properties that describe Dracula (whether true or not). In First-order logic terms, it can be formalized as  $Flies(Dracula)\land IsaPig(Dracula)$.
How about the first sentence? It is saying that if we add "division by zero rule" to our set of rules (let's call the new logic $L_0$) then we can reach a contradiction i.e. $\vdash_{L_0} A\land \neg A$. Of course for this rule to be applicable, our formal system must be a superset of a system of numbers (i.e. it must include axioms and rules for manipulating numbers, etc.).
So the question is this: If we have a formal system that includes axioms and rules governing numbers, and we add the rule of "division by zero" to our set of rules of inference, can we prove every sentence in the language? The answer is yes if our formal system has commonsense axioms and rules (like modus ponens, substitution with equivalent formulas, ...). As you showed above, using the rule of division by zero we can reach a contradiction. Now I show how to prove every sentence (in the language of the formal system) from a contradiction (i.e. $A\land \neg A\vdash B$):
\begin{align}
&1)\ \neg A \qquad\qquad  \text{premise}\\
&2)\ \neg A\lor B \quad\ \ \ \ \text{apply}\lor \text{rule on 1}\\
&3)\ A\rightarrow B \qquad \ \text{replace 2 by equivalent formula}\\
&4)\ A \qquad\qquad \ \ \text{premise} \\
&5)\ B \qquad\qquad \ \ \text{apply } modus\ ponens\text{ rule on 3, 4 }
\end{align}
This was a purely syntactic approach. A semantic approach is possible as well.

A:
Dividing by zero once—just one time—allows you to prove, mathematically, anything at all in the universe.

That is very wrong.  It is perfectly consistent to assign a value to division by zero, your microprocessor does it and the universe is still going.
What is problematic is to remove that $x \ne 0$ condition from statements involving division, such as:
$$x \ne 0 \implies (ax = b \iff a = b/x)$$
But otherwise you can divide by zero all day long.  You just have to realize you can't infer the things you would normally want to infer from such expressions.


text:
Q: How to set default mime-tipe for any file extension in Tomcat 6? Mime-types are specified in Tomcat's conf/web.xml file.
It's look like this:
<mime-mapping>
   <extension>txt</extension>
   <mime-type>text/plain</mime-type>
</mime-mapping>

Previously I try following:
<mime-mapping>
   <extension>*</extension>
   <mime-type>application/octet-stream</mime-type>
</mime-mapping>

but it doesn't help me.
How to specify default mime-type for any file extension?

A: There's no way. You need to explicitly set them yourself. A servlet filter is a suitable place for this.
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
    response.setContentType("application/octet-stream");
    chain.doFilter(request, response);
}

I however highly question the business need for this. It's only disadvantageous for SEO and the client. If your sole purpose is to pop a Save As dialogue, then you should say that so. There are much better solutions to achieve this than forcing a wrong mime type.


text:
Q: Question about long exact sequences and homology I have a question about Hatcher's chapter on long exact sequences (page 116, right before theorem 2.16). I'll rewrite the bit I don't understand.
Let $X$ be a space and $A$ a subspace. If we take $c\in C_n(X,A)=\frac{C_n(X)}{C_n(A)}$ then $c=j(b)$ for $b\in C_n(X)$ where $j$ is the quotient map $C_n(X)\longrightarrow C_n(X,A)$ because $j$ is onto. Then we take the boundary of $b$ and we get an element $\partial b\in C_{n-1}(X)$.
I'm fine until this point but then it goes on to say that $\partial b \in Ker j$ because $j(\partial b)=\partial (j(b)) = \partial c = 0$ and I don't understand why $\partial c = 0$.
Thanks for any help.

A: It seems you missed that Hatcher says "let $c\in C_n$ be a cycle" (emphasis mine).


text:
Q: Каким образом компании зарабатывают на opensource? Меня всегда интересовал вопрос, каким образом компании зарабатывают на opensource проектах? У меня существует две догадки (к сожалению я в вопросах лицензирования не силен).

*

*Должна существовать лицензия, которая позволяет распространять коммерческое по на базе открытого (например без предоставления исходного кода по требованию). Тогда вполне логично, что на этом можно заработать.

*Можно продавать услуги по обслуживанию открытого по, но тогда непонятно, кто будет готов заплатить за услуги подобного рода? (хотя тут как по мне можно привести пример обслуживания серверов, использующих открытое по)

A: Варианты:

*

*ПО с откодом может быть разделено на базовый функционал и на дополнительный (модули, пакеты и прочее). Дополнительные делают платным, а базовый так и остаётся бесплатным, но ограниченным в возможностях, и для того чтобы эти возможности расширить, клиенты покупают доп. возможности.

*Если, как сказано в вопросе, продукт хотят распространять без предоставления кода, то можно купить такую расширенную лицензию у разработчиков откод проекта.

*Платное консультированию и внедрение ПО.

*Написание и продажа учебных пособий для ПО.

*Реклама в основном ПО, куда же без неё.

*Написание (создание) обучающих уроков или каких-либо других ресурсов (сайтов, видео и т.п), где также можно встретить рекламу.

*Спонсирование, бывает и такое.

*Разновидность ПО: открытое-бесплатное и корпоративное.

*Продажа атрибутики (логотипов, символов): наклейки, игрушки и т.п.


text:
Q: Compile error when using initializer list with designator inside a constructor's member initializer list to initialize an anonymous union type I have encountered a situation in c++ where initializing an anonymous union member variable fails when I use initializer list with designators inside a member initializer list of a class constructor.
Following snippet might make things clearer:
class MyClass {
public:
  MyClass() : my_union({.outer_field = 123}) {}
  union {
    struct {
      int a: 16;
      int b: 16;
    } inner_field;
    int outer_field;
  } my_union;
};

Compiler gives the following error:
test.cpp: In constructor 'MyClass::MyClass()':
test.cpp:6:44: error: no matching function for call to 'MyClass::<anonymous union>::._6(<brace-enclosed initializer list>)'
   MyClass() : my_union({.outer_field = 123}) {}
                                            ^
test.cpp:7:9: note: candidate: MyClass::<anonymous union>::<constructor>()
   union {
         ^
test.cpp:7:9: note:   candidate expects 0 arguments, 1 provided
test.cpp:7:9: note: candidate: constexpr MyClass::<anonymous union>::<constructor>(const MyClass::<anonymous union>&)
test.cpp:7:9: note:   no known conversion for argument 1 from '<brace-enclosed initializer list>' to 'const MyClass::<anonymous union>&'
test.cpp:7:9: note: candidate: constexpr MyClass::<anonymous union>::<constructor>(MyClass::<anonymous union>&&)
test.cpp:7:9: note:   no known conversion for argument 1 from '<brace-enclosed initializer list>' to 'MyClass::<anonymous union>&&'

However, the following code compiles with no problem;
union myunion {
  struct {
    int a: 16;
    int b: 16;
  } inner_field;
  int outer_field;
} my_union;
myunion m = {.outer_field = 123};

I can get around the problem by invoking the implicit constructor of union (as the error message suggests) like:
class MyClass {
public:
  MyClass() : my_union({123}) {}
  union {
    struct {
      int a: 16;
      int b: 16;
    } inner_field;
    int outer_field;
  } my_union;
};

But why does the initializer list with designators don't work within a member initializer list?
The g++ used to compile is version 5.4.0.
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

A: Technically the example you give of compiling is not valid c++, but uses a GCC extension to allow C99 designated intializers. The case in question:
myunion m = {.outer_field = 123};

However, this is not using an initializer list, but uniform initialization.  To get the same result in your code that you had as not compiling, just remove the outer parentheses:
class MyClass {
public:
  MyClass() : my_union{.outer_field = 123} {}
  union {
    struct {
      int a: 16;
      int b: 16;
    } inner_field;
    int outer_field;
  } my_union;
};

Instead of trying to pass an initializer list to the union's constructor, this performs uniform initialization.  Keep in mind that it still is using a GCC extension, and would generate a warning if you passed -pedantic to the compiler.
EDIT:
Also as a warning, when using uniform-initialization, unions always initialize the first member.  Structs will zero initialize any missing values.  So your first example of the constructor that compiles:
MyClass() : my_union({123}) {}

This actually sets inner_field to the active field in the union, then a will be 123 and b will be 0.  Here is an example.  See here for more details about initializing unions.


text:
Q: first and last value is not displaying in chart.js used with django i want to display the employee and salary in a graph, i used chart.js and django. but i cannot display the salary of first and last employee..any suggestion is appreciated.
#views
    if request.method=="GET":
        return render(request, 'upload_pandas.html')
    else:
        file=request.FILES['myfile']
        file_read=pd.read_excel(file)
        column_selection=file_read['Salary']
        salary=[]
        salary=list(column_selection)
        print(salary)
        name=[]
        name=list(file_read['First Name'])
        print(name)
        lis=[salary,name]
        data={
            'salary_data': salary,
            'label_data': name,

        }
        return render(request,'map.html',{'data':data})

#url.py

urlpatterns=[

    path('upload/',views.view_panda),

]

the problem is here, when i print in console it prints all the value but it was not loading in the graph.enter image description here
#map.html

    <title>Chart.js</title>

        <canvas id="genderchart" width="1000"></canvas>

A: I actually can't reproduce your error. Here is what I was doing with generated data (and it gets displayed fine).
const count = 26
for (let x = 0; x < count; x++) {
  sData.salary.push(Math.floor(Math.random()*100)*1000)
  sData.label.push(Math.random().toString(36).substr(2, 5))
}

Can you make an online editor version so we can check it easier?
I would guess the problem are the label strings or the options, but it's hard to guess...
Btw you have some spelling errors, e.g. "desplay", scriptsrc, and suggestedMin is no boolean, it's an int.

A: Actually, i got it right ..the mistake was silly as i got the value with  " " that is
let data={% autoescape off %}
                   "{{ data }}"
                {% endautoescape %};

instead of
let data={% autoescape off %}
                  {{ data }}
         {% endautoescape %};

so , no need of split()
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Chart.js</title>

        <canvas id="genderchart" width="1000"></canvas>


text:
Q: Keras as theano as backend can use the code of Keras as tensorflow backend? Can the code which is written on keras using tensorflow as backend can run on another keras environment were theano is the backend? Is there any computational benefits when running on any of them?

A: To avoid dimensional errors just add
"image_data_format": "channels_last"

in the Keras.Json configuration file at
~\.keras

If there is not such a file you can create it yourself.


text:
Q: If $S$ be any set of intervals I in $\mathbb R$ and $J=\bigcap_{I \in S}I$ show $(\alpha,\beta)\subset J\subset [\alpha,\beta]$ Let $S$ be a set of intervals $I$ in $\mathbb R$ s.t. $\exists I_1,I_2\in S$ where $I_1$ is bounded above and $I_2$ is bounded below.
If $J=\bigcap_{I\in S}I$ then show that $\exists \alpha,\beta \in \mathbb R$ with $\alpha\le \beta$ s.t. $(\alpha,\beta)\subset J \subset [\alpha,\beta]$

A: Let $b$ be the right end-point of $I_1$ and $a$ be the left end-point of $I_2$. Clearly $I_1\cap I_2\subset [a,b]$ if $a\le b$. When $a>b,I_1\cap I_2=\emptyset$. Now $J=\bigcap_{I\in S}I\subset I_1\cap I_2$. Thus $J\subset [a,b]$ if $a\le b$ and $J=\emptyset$ if $a>b$. In any case $J$ is a bounded set in $\mathbb R$.
If $J=\emptyset$ then $(c,c)\subset J\subset [c,c] \,\,\forall c \in \mathbb R$. If $J$ is a singleton set, say $\{x\}$ then $(x,x)\subset J\subset [x,x]$.If $J$ contains more than one element, then $\exists x,y\in J$ s.t. $x<y$.  $J\subset I\,\,\forall I \in S \Rightarrow x,y\in I \,\,\forall I\in S$. Therefore $[x,y]\subset I\,\,\forall I\in S$ Hence $[x,y]\subset \bigcap_{ I\in S}I=J$.
By characterization theorem of intervals,  $J$ is an interval. As $J$ is a bounded interval it has a left end-point,say $\alpha$ and right end-point, say $\beta$ in $\mathbb R$ s.t. $(\alpha,\beta)\subset J\subset [\alpha, \beta]$.


text:
Q: search SQL for possibly duplicated user names using PHP I want to search my database to see if a user that is registering is using a username that is currently in my database. I have registered the same name about 5 times so it SHOULD return false but it returns true.
<?php
function registerUser($userName, $userPassword) {

    $db = new dbinterface();
    $db->connect();

    // check for duplicate data
    $checkduplicates = "SELECT * FROM usersexample WHERE $userName = :userName";
    $myresult = mysql_query($checkduplicates);

    if(mysql_num_rows($myresult) > 0){
        echo $myresult;
        return false;
    }
?>

My table name is usersexample and the field i am searching is userName.
ANY and ALL help is appreciated!
Using mysql_num_rows in examples i get this warning:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource.

A: Use mysql_num_rows() to check the number of rows returned.
Sample:
$myresult = mysql_query($checkduplicates);
$rowcount = mysql_num_rows($myresult);

if($rowcount > 0)
{
    // Account name already in use
}

A: Did you try:
$checkduplicates = "SELECT userName FROM usersexample
                    WHERE LOWER('".$userName."') = LOWER(userName)";
$myresult = mysql_query($checkduplicates)
if (!$myresult) {
    die('Invalid query: ' . mysql_error());
} else  {
    $num_rows = mysql_num_rows($myresult);
    if (!$num_rows) {
        die('Invalid query: ' . mysql_error());
    } else return ($num_rows == 0);
}

Please, sanitize user input to avoid SQL injection.

A: You should try this...
if(mysql_num_rows($myresult) > 0) {
        echo $myresult;
        return false;
    }

It will return false if there is a duplicate username.

A:  $getduplicates = mysql_query("SELECT * FROM table WHERE username = $username");
 $duplicates = mysql_num_rows($getduplicates);

 if($duplicates){
     echo "Uh oh someone already has that username";
 }
 else {
     echo "Everything is allllllll good";
 }

A: Please use prepared statements to avoid sql injection.
As you are using :userName in your SQL it seems you are trying to do this (is your
database class based on PDO by any chance?). The :userName part will be replaced
by your variable $userName when you do the bindValue.
Use count() in the database to count the number of records found,
the database knows best ;-)
$query = $db->prepare("SELECT count(*) AS no_found FROM usersexample WHERE userName = :userName");
$query->bindValue(':userName', $userName, PDO::PARAM_STR);
$query->execute();
$result = $query->fetchObject();

if($result->no_found > 0)
{
    return false;
}

A: I don't know if you are doing something fancy I don't understand, but I would build the query like this:
$checkduplicates = "SELECT * FROM `usersexample` WHERE `userName` = '$userName'";

Or this
$checkduplicates = "SELECT * FROM `usersexample` WHERE `userName` = '".$userName."'";


text:
Q: Show payment method discount rule on magento product page I want to display the discounted price the client can have depending on the payment method he chooses directly on the product page.
Basically, what I need is a way to get the shopping cart rules that apply for payment methods. So then I could use it to build a table of payment methods X discounts like this:
Cash: $90 (10% discount)
CC: $100 (Full price)
Transfer: $100 (Full price)
So far I couldn't find a way to access the shopping cart rules. Any insights?
UPDATE:
For those wondering, I've found a way to get the shopping cart rules. Pretty simple actually:
$model = Mage::getModel('salesrule/rule')
        ->getCollection();

With this information I can loop through the rules and find the ones that apply to payment methods.
$conditions = unserialize($item['conditions_serialized']);

But I realized that this way is too much work and can get complex if rules are complex. I decided to get the rules that I want by ID and get the discount value, since it won't change all the time.
If you know how to make Magento calculate everything for me, like me asking "If a user chose this payment method, besides everything else (user group, catalog discounts, etc) what would be the final price?".

A: $model = Mage::getModel('salesrule/rule')
        ->getCollection();

foreach($model as $item){
    // check, do whatever and get discount
}


text:
Q: Toggle display shows the hidden element for a second I'm trying to show a hidden text on click of a button. But when I load the page, the text shows for a second and then disappears. Why would that happen?

This is temporary

  <button id="showme">Show</button>

$(document).ready(function() {
  $(".temp").hide();
  $("#showme").on("click", function() {
    $(".temp").show();
  });
});

A: Try to understand how the webpage loads. Your jquery is executed when the entire page is rendered with the associated CSS. So the browser displays your text for a second till it executes jquery to hide that text. So your browser needs to know that this text is hidden while parsing the html. You can do this by giving a CSS style to the text.
CSS:
.temp {
  display: none;
}

HTML:

This is temporary

  <button id="showme">Show</button>

JS:
$(document).ready(function() {
  $("#showme").on("click", function() {
    $(".temp").show();
  });
});

A: You should use inline style tag in
 tag like this:

This is temporary

instead of hiding it from jQuery!

$(document).ready(function() {
  $("#showme").on("click", function() {
    $(".temp").show();
  });
});

This is temporary

  <button id="showme">Show</button>


text:
Q: login with outlook successfully but Redirect Url not working after login successfully - react native am working on react native app and using react-native-app-auth library login with outlook,
when i run app on ios device then redirect url working fine.
but when i run app on android device then then login successfully but redirect url not working.
my redirectUrl is : 'urn:ietf:wg:oauth:2.0:oob',
i try this but not work.
manifestPlaceholders = [`enter code here`
appAuthRedirectScheme: 'com.googleusercontent.apps.urn:ietf:wg:oauth:2.0:oob'
]

A: Faced the same issue. Post some reading, came across this . https://github.com/openid/AppAuth-iOS/issues/194 which redirects us to RFC 8252 Section 7.1.
Please change it to a domain under your control as advised. Worked for me!


text:
Q: vuex state Not reset after changing routes I'm using Nuxt js and I have a multi-step form that can be used by the user to apply for jobs.
when the page opens I'm fetching the company's data using async and putting it in the vuex state.
I also use activeStep in vuex to determine the current step .
export const state = () => ({
  companyProfile: "",
  fullname: "",
  Myapplications: "",
  activeStep: 1,
});

going to the next step action :
 goToNextStep({ commit, state }, step) {
    commit("setStep", step);
  },
/// Mutation
 setStep(state, step) {
    state.activeStep = step;
  },

this is working fine when the user uses the form the step works perfectly.
The issue is when the user goes to another page and opens a company apply form, the active step is still the last one from the previous submission
This is how I'm handling the steps on my page :
//activeStep is a computed property

   <Step1 v-if="activeStep === 1" />
        <transition
          name="slide-fade"
          v-if="activeStep=== 2"
          mode="in-out"
        >
          <Step2 />
        </transition>
        <transition
          name="slide-fade"
          mode="out-in"
          v-if="activeStep === 3"
        >
          <Step3 />
        </transition>

I tried resetting the state in vuex beforeMount the components but I'm getting a weird behavior where the transition of the steps isn't working. I have to refresh the entire page to get the correct behavior.
am I missing something here related to vue? or should it be done without vuex ?


text:
Q: Sort an array of objects by property value within another array Today I was asked to add sorting to a datatable in Angular. I have tried to use the built in orderBy filter, but it doesn't look like it can handle jagged data.
I need to be able to sort all the columns in the table, although I am having a problem with finding a way to sort values within the array.
Here is the simplified data I am dealing with:
[
  {
    "id": 1,
    "some_data": {
        "nested_id": 3,
        "nested_array": [
            {
                "id": 10,
                "some_value": "test3",
                "another_value": 1
            },
            {
                "id": 10,
                "some_value": "test2",
                "another_value": 1
            }
        ]
    }
},
{
    "id": 2,
    "some_data": {
        "nested_id": 5,
        "nested_array": [
            {
                "id": 10,
                "some_value": "test1",
                "another_value": 1
            }
        ]
    }
  }
]

Could anybody point me in the right direction how would I write a generic method that is able to sort the following array on any property? I know how to sort it based on "id" and "nested_id", but what about "some_value"?
EDIT:
I tried something similar to this, but that would only work on the outer properties, not the properties within the "nested_array".
The result I am trying to achieve is that when I sort on "some_value", it should display object with "id" of 2 first, then object with "id" of 1 and objects within "nested_array" should also change their order.
function sortBy(prop){
 return function(a,b){
  if( a[prop] > b[prop]){
      return 1;
  }else if( a[prop] < b[prop] ){
      return -1;
  }
  return 0;
 }
}


text:
Q: Como restar valores en diccionarios Python Tengo un controle de deudas que están guardadas por nombre y valores respectivos de cada uno en un diccionario. Quería una ayuda para saberlo como hago las restas de un valor dentro del diccionario.
deudas = dict()
deudas['Nombre de la persona'] = float(input('Digite o valor devedor a  "Fafa":€ valor deuda' ))
print(deudas)

float(input('Ingrese el valor pagado este mes en la deuda':€)

A: Solo modifica el valor del diccionario correspondiente al deudor. Por ejemplo:
deudas = dict()
deudas['Alfonso'] = float(input('Digite o valor devedor a  "Fafa":€ valor deuda: ' ))
print(deudas)
abono = float(input('Ingrese el valor pagado este mes en la deuda: '))
deudas['Alfonso'] = deudas['Alfonso'] - abono
print(deudas)

Resultados:
Deuda input
5000

Abono input:
3000

Output:
2000


text:
Q: How do 32-bit applications make system calls on 64-bit Linux? Some (many? all?) 64-bit1 Linux distros allow running 32-bit applications by shipping parallel collections of 32-bit and 64-bit libraries (including libc). So a 32-bit application can link against 32-bit libs and be run by a 64-bit kernel.
I'd like to know the mechanics of how 32-bit applications make system calls on a 64-bit kernel. I suspect the answer is somewhere in libc and/or the kernel source, but it would be time-consuming for me to dive into the source since I don't know where to look.
And a more important question, is there any performance overhead?2 Logically, a call from a 32-bit app system call will have to translate to 64-bit internal kernel environment. How and where is this accomplished?
1 "32-bit" = IA-32, and "64-bit" = AMD64
2 In your answer make an assumption that it matters :)

A: From the userspace side, the mechanics are identical to making a syscall on a 32 bit native kernel - all the usermode code, including the 32 bit glibc, works the same way.
From the kernel side, the old IA32 entry points from userspace (eg. int 0x80) are set up to call the ia32_syscall assembler routine.  (The transition to kernel space involves the processor loading the kernel's code segment selector, which causes a transition to 64 bit "long" mode).
The ia32_syscall routine then shuffles some of the arguments around to match the x86_64 syscall calling convention:
movl    %edi,%r8d
.if \noebp
.else
movl    %ebp,%r9d
.endif
xchg    %ecx,%esi
movl    %ebx,%edi
movl    %edx,%edx   /* zero extension */

It then uses the IA32 syscall number to make a function call through a table, ia32_sys_call_table.  This essentially matches up the IA32 syscall numbers with the native syscall implementations (syscall numbers differ wildly between IA32 and x86_64).  The first part of this table looks like:
ia32_sys_call_table:
    .quad sys_restart_syscall
    .quad sys_exit
    .quad stub32_fork
    .quad sys_read
    .quad sys_write

For most syscalls, the x86_64 implementation can be now called directly - like exit().  For others, like fork(), a wrapper is provided that correctly implements the expected IA32 semantics (in particular, if sign extension of arguments from 32 bit to 64 bit is required).
As you can see, the overhead in kernel code is minimal - a few trivial modifications to register values, and for a few functions, an extra function call.  I'm not sure if loading a code segment selector that causes a transition from 32 bit mode to 64 bit mode is slower for the processor to execute than one that doesn't - check the processor architecture manuals for that.


text:
Q: How to make proguard obfuscate enum names? First of all I'm far from my development machine.
Let assume I have:
public enum Num {
    ONE,
    TWO
}

And I have following code:
String name = Num.ONE.name();

Will name value stay the same after obfuscation? From the Enum class code it should stay the same after obfuscation since it happens after compilation when the name string will be generated.
Am I right?


text:
Q: Sending message from Application-Server to target application on Android device How to know exactly what URL does the 3rd-party application-server try to access while sending message to a client-device via the GCM-server?
In "SendAllMessagesServlet.java"
(which can be found @ android-sdks\extras\google\gcm\samples\gcm-demo-server\src\com\google\android\gcm\demo\server\SendAllMessagesServlet.java)
.....
// Error 500 ( Connection timed out) at the following line

Result result = sender.send(message, registrationId, 5);
.....

3rd-party app-server - Tomcat v7.0

A: The URL is in the Constants.java file as GCM_SEND_ENDPOINT
in the android\gcm\gcm-server libray
public static final String GCM_SEND_ENDPOINT =
      "https://android.googleapis.com/gcm/send";
The error 500 is due to proxy settings.
Thank You


text:
Q: Error with missing Wallpaper after remove unity from sudo command After I paste these scripts into terminal, my wallpaper became white.
sudo ln -s /etc/xdg/xdg-une/autostart/maximus-autostart.desktop /etc/xdg/autostart/
sudo ln -s /etc/xdg/xdg-une/autostart/netbook-launcher.desktop /etc/xdg/autostart/
sudo ln -s /usr/share/gconf/une/default/20_une-gconf-default /usr/share/gconf/defaults/
sudo ln -s /usr/share/gconf/une/mandatory/20_une-gconf-mandatory /usr/share/gconf/defaults/
sudo update-gconf-defaults

Help me, I dont know what [-s] for ? and how do i get my wallpaper back.
Best Regards from Newbie

A: It's so funny that i solved my own question. LOL
.
So, after long googling i decided to remove mutter with this commands
sudo apt-get remove unity
And everything goes perfectly

A: ln -s will make a symbolic link to a file. To reverse what you have done just delete the links:
sudo rm /etc/xdg/autostart/maximus-autostart.desktop
sudo rm /etc/xdg/autostart/netbook-launcher.desktop
sudo rm /usr/share/gconf/defaults/20_une-gconf-default
sudo rm /usr/share/gconf/defaults/20_une-gconf-mandatory
sudo update-gconf-defaults

That should leave the system in the state that was prior the commands.


text:
Q: Blender Python How to convert a mesh with materials to vertex colors? I have imported objects with meshes, each having over 50 different materials, which display only a unique color, so I want get rid of the materials and use vertex colors.
That means, each vertex of a face that has a particular material assigned will be colored to the materials main color.
But I have issues to convert this. I cant get the faces that a material uses. This is what I have so far:
import bpy
import bmesh

for obj in bpy.context.scene.objects:       #support multiple selection
    if obj.type == 'MESH':                  #color only if mesh exists

        mesh = bpy.context.object.data
        bm = bmesh.new()
        bm.from_mesh(mesh)

        materials = bpy.data.materials      #get current meshs materials

        for index in range(len(materials)):         #get corresponding faces of material

            for face in bm.faces:
                if face.material_index == index: #select face that matches current material
                    face.select = True

                    for L in face.loops:
                        L[bm.loops.layers.color.active] = materials[index].diffuse_color

       # bpy.data.materials = [] #remove all materials from material tab

        bm.to_mesh(mesh) #Assign new mesh from bmesh
        bm.free()

Thanks in advance.