text:
Q: ObservedObject change doesn't redraw SwiftUI View I try to build rather complicated View in SwiftUI. Structure is like this:
struct ContentView<V: SpaceVertexProtocol>: View  where V.Coord.Axis : StyledAxisProtocol{

    @EnvironmentObject var environment: ViewsEnvironments<V>
    @ObservedObject var global: GlobalEnvironment<V>

    var body: some View {
        // It will be HStack, for a while just one view
        SpaceVerticesView(coordinates: $global.coordinates, vertices: $global.vertices)
                .padding(EdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5))
                .environmentObject(environment.spaceVerticesView)
    }
}

public struct SpaceVerticesView<V:SpaceVertexProtocol> : View {
    ...
    @Binding var coordinates : [V.Coord]
    ...
    func updateCoordnates {
       coordinates = ... // yes, this updates view, they're changed by `coordinates[index].at = something`
    }
    public var body: some View {
        ...
        SpotsView(coordinates: $coordinates,....)
        ...
    }

struct SpotsView<V:SpaceVertexProtocol> : View {
    ...
    @Binding var coordinates: [V.Coord]
    var spots: [SpotView<V>] {
         var result: [SpotView<V>] = []
         ...
         //counts and adds views initiated as:
            result.append(SpotView(coordinates: $coordinates,...)
         ...
        return result
    }

    var body: some View {
        return ZStack {
            // makes some SpotView on top
            ForEach(0..<spots.count, id: \.self) { index in
                return self.spots[index]
            }
        }
    }

and two levels more, always coordinates are passed as $coordinates to @Binding variable.
In the deepest view, var body returns Shape
    var body {
       ...
       return spotShape
        .contentShape(spotShape.clickArea).offset(x: 0, y: shift)
        .onTapGesture {
            print ("Tap gesture:",self)
            print (self.coordinates, targetCoordinates)
            self.coordinates = targetCoordinates

I can see coordinates are updated, but view isn't redrawn.
If I click outside of clickArea , SpaceVerticesView.updateCoordinates(...) is fired, coordinates are changed and View is redrawn. Is Shape @Binding invalid? Why no reaction?
When coordinates was part of @EnvironmentObject it was OK.


text:
Q: RealtimeAnalyzer memory I'm trying to write a visualizer for Spotify using the Processing library.
But I have a problem with the audio.RealtimeAnalyzer class.
var analyzer = audio.RealtimeAnalyzer.forPlayer(models.player);
analyzer.addEventListener('audio', function(data){ ... });

If I let this run for an hour Spotify is using more then 1.5GB of memory and eventually crashes. Is there any possibility for dumping or freeing all this unnecessary memory?
Or can I solve this issue with using an other class?

A: Yeah, I first noticed that as well. I posted it as a bug under their github app.
https://github.com/spotify/visualizer-app
Perhaps if you added your input they would see it's really hindering dev work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Access to html tag from inside Web Components I'm learning the firsts concepts of js web components. I pretty nob in these and try to make a simple example. My component is just a button that pretends to change color to a div.
My example work I expected but I noticed that my approach is not too much "component way", if the element that I attempt to change is in my web component to instead outside of it.
This is my html file:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="index.css" />

Yeah Web Components!

      <my-component></my-component>

This is my component .js:
const template = `

    <button class="hi-button">Change</button>

`;

class MyFirstTest extends HTMLElement{
  constructor(){
    super()
    const shadowRoot = this.attachShadow({ mode: 'open' });
    shadowRoot.innerHTML = template;
  }

  changeButtonColor(){
      const box = this.shadowRoot.querySelector(".box");
      if(box.style.background === 'red'){
        box.style.background = 'blue';
      }else{
        box.style.background = 'red';
      }
  }

  connectedCallback(){
      const event = this.shadowRoot.querySelector(".hi-button");
      event.addEventListener('click', () => this.changeButtonColor());
  }

  disabledCallback(){
    const event = this.shadowRoot.querySelector(".button-test");
    event.removeEventListener();
  }

}

customElements.define('my-component', MyFirstTest);

As I said the functionality works fine but I don't want my div to be in my web component but in my html file and mi component be only the button.
For example, my html file would be something like this:
.......

  <link rel="stylesheet" href="index.css" />

Yeah Web Components!

      <my-component></my-component>

.......

Is possible for web components to work in this way?

A: There are some notes about the published code:
CSS & shadowDOM
   .container{
      display: flex;
      flex-direction: column;
      align-items: center;
    }
   .hi-button{
      margin-top: 10px;
    }

This global CSS is never applied to HTML inside the Element shadowDOM.
Note you do not have to use shadowDOM.

*

*Templates

*Custom Elements API

*shadowDOM

are 3 distinct technologies you can use without each other.
To apply the style, declare it inside the shadowDOM:
const template = `

    <button class="hi-button">Change</button>

Templates
It is just a string, you are not using or declaring a <template>
Click event
The click event on the button, by default, bubbles up the DOM.
There is no need to set the handler on the <button> itself, you can set in on any parent.
Garbage Collection
No need to remove Listeners inside/on the Custom Element. The JavaScript Garbage Collection process will do that for you
RemoveListeners are required when you set Listeners on other DOM elements.
eg. When a Component sets a Listener on document
disabledCallback
Does not exist; its called disconnectedCallback()
composed = true
   this.dispatchEvent(new CustomEvent("button-clicked", {
      bubbles: true,
   }));

This only works because the Event is not dispatched from shadowDOM.
But dispatch from inside shadowDOM, or wrap the Element in another Element with shadowDOM and the code will no longer work, because Custom Events, by default, do not 'escape' shadowDOM(s).
For that, you need to use:
   this.dispatchEvent(new CustomEvent("button-clicked", {
      bubbles: true,
      composed: true
   }));

Note: default Events like click do escape shadowDOM by default
Solutions
Without shadowDOM the only code required is:

*

*global CSS now styles the button

customElements.define('my-component', class MyFirstTest extends HTMLElement {
  connectedCallback() {
    this.innerHTML = `<button class="hi-button">Change</button>`;
    this.onclick = (evt) => document.querySelector(".box").classList.toggle("blue");
  }
});

Yeah Web Components!

  <my-component></my-component>

With shadowDOM

*

*There is less need for CSS classes, because all HTML is isolated in the shadowDOM

*<template> can be declared as HTML (so your IDE neatly formats everything inside) Referenced by this.nodeName, so you can re-use code

*super() & attachShadow() are functions setting and returning this scope and this.shadowRoot; so they can be chained

*Custom Events are great; but this code can do with the default click event; the listener checks if the correct button was clicked

*These are just Web Component technical enhancements, loads more functional enhancements possible, all depends on the use case

*Do read ::slotted CSS selector for nested children in shadowDOM slot before you continue with <slot> content
Code could look something like this:

<template id="MY-COMPONENT">

    <button><slot></slot></button>

</template>

  <my-component color="blue">Blue!</my-component>
  <my-component color="gold">Gold!</my-component>
  <my-component color="rebeccapurple">Purple!</my-component>

A: The best way to maintain the independence between components is use events.
Web components dispatch an event that is listened by the parent container. And then, parent do the necessary action.
If you want to talk "directly" between component and parent, the system is pretty coupled and is not a good way. Of course you can, but is not recommended.
You can check this answer which is clearer.
Also, answering your question using events. Is as simple as this:
First, into your component you have to dispatch the event in this way:
this.dispatchEvent(new CustomEvent("button-clicked", {
    bubbles: true,
}));

You can check here the use of this.
Also, the parent will listen using:
document.addEventListener("button-clicked", changeColor);

So, when the button is clicked, the parent will trigger the function changeColor with the logic inside you want.
In this way you are using a Web Component to do actions into parent container but the system is not coupled. Parent can work without child and child can work without parent. Both can be used separately. Of course, the event will not be dispatch or listen but there is no a dependency between components.
Also this is an example how it works.

const template = `

    <button class="hi-button">Change</button>

`;

class MyFirstTest extends HTMLElement{
  constructor(){
    super()
    const shadowRoot = this.attachShadow({ mode: 'open' });
    shadowRoot.innerHTML = template;
  }

  changeButtonColor(){
      //Call parent
      this.dispatchEvent(new CustomEvent("button-clicked", {
            bubbles: true,
        }));
  }

  connectedCallback(){
      const event = this.shadowRoot.querySelector(".hi-button");
      event.addEventListener('click', () => this.changeButtonColor());
  }

  disabledCallback(){
    const event = this.shadowRoot.querySelector(".button-test");
    event.removeEventListener();
  }

}

customElements.define('my-component', MyFirstTest);
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="index.css" />

Yeah Web Components!

      <my-component></my-component>


text:
Q: Using AD service account within SSIS package I have created connection manager within SSIS packages which has windows authentication and by default it is going to use my credentials to connect to a specific db.

I created project parameters that have connectionstring to dev, qa, prod.

and edited connection manager properties to give in expressions to use project parameters and automatically update package to use service account Userid and password.

But, my package has been defaulting to SQL server authentication and is failing when I am trying to connect to database.
Any help is much appreciated and would love to provide any necessary information.

A: If you're using Windows Authentication, make sure your connection string(s) use Integrated Security=SSPI;. Also make sure all your database connections you use in your various tasks are all also set to use Windows Authentication. You may need to use an expression to set their connection strings per environment as well.


text:
Q: Remove a certain word in a file How do I remove just abcd11.gmail.com and *test1: from line 1
and abcd14.gmail.com and *fortest2: from line 2 and abcd19.gmail.com and *asatesteg: from line 2 from below leaving the remaining as is? I have thousands of lines in a file like this:
May 23 03:44:02 abcd11.gmail.com x.x.x.x.x: *test1: May 23 04:46:21.032: #TEST1_ENTRY:4105 THIS is a test1
May 23 03:44:02 abcd14.gmail.com x.x.x.x.x: *fortest2: May 23 04:46:21.032: #TEST2_ENTRY:4105 THIS is a test2
May 23 03:44:02 abcd19.gmail.com x.x.x.x.x: *asatesteg: May 23 04:46:21.032: #TESTEG_ENTRY:4105 THIS is a testeg

A: You can try sed substitution
$ sed -e 's/abcd[0-9]*//g' -e 's/*test[0-9]*://g' file

Where abcd[0-9]* matches every abcd followed by a number, same with *test[0-9]*:

A: A solution using cut:
cat $FILE | cut -d' ' -f4,6 --complement

A: if you need to remove always the same sentence you can try
sed -e 's/abcd[0-9]*//g' -e 's/*test[0-9]*://g' file.ext

this show you the output in the stdout if you want save this output simple add the > to the finel of the instruction or >> to append the content to another file
sed -e 's/abcd[0-9]*//g' -e 's/*test[0-9]*://g' file.ext>new_file.ext
sed -e 's/abcd[0-9]*//g' -e 's/*test[0-9]*://g' file.ext>>new_file.ext

then you can remove the old file and replace whit the new
rm file.ext
mv new_file.ext file.ext


text:
Q: Customized popup in Openlayers I have done point layer overlay with openlayer. Whenever i click any point, its showing me all the data of the table in popup. How to control amount of data in the popup?
Code is:
....
info = new OpenLayers.Control.WMSGetFeatureInfo({
        url: 'http://localhost:8080/geoserver/layername/wms',  // geoserver point layer
        title: 'Identify features by clicking',
        queryVisible: true,
        eventListeners: {
            getfeatureinfo: function(event) {
                map.addPopup(new OpenLayers.Popup.FramedCloud(
                    "ABCD",
                    map.getLonLatFromPixel(event.xy),
                    null,
                    event.text,
                    null,
                    true
                ));
            }
        }
    });
    map.addControl(info);
    info.activate();

Screenshot of current popup is
()
I just want location_name and some html content in popup. How to do that?


text:
Q: Optimize quadratic problem under collinearity boundary condition Summary
Given the optimization problem
$$
\min_{d\in\mathbb{R}^{n\times 2}} \text{trace}\big( d^T Q d+Cd\big)
$$
for some $n\times n$-matrix $Q$ and another matrix $C\in\mathbb{R}^{2\times n}$, I'd like to add the boundary conditions on the collinearity of differences of rows of $d$.
Formally speaking: Let $d=[d_1,\ldots, d_n]^T$ with $d_i\in\mathbb{R}^2$. For given $i, j, k$ I'd like the vectors $d_i-d_k$ and $d_k-d_j$ to be collinear. What is the most efficient way to solve a problem like this?

More elaborated problem
Of course I can modify the original optimization problem to be of the form
$$
\min_{d\in\mathbb{R}^{2n}} d^T \tilde{Q} d + \tilde{c}d
$$
with
$$
\tilde{Q}=\begin{bmatrix} Q & 0 \\ 0 & Q\end{bmatrix},\quad \tilde{c}=[c_1, c_2],
$$
and $c_1, c_2$ the rows of $C$.
This problem may be solved by solving a system of linear equations as it is well known in theory and practice.
My boundary condition furthermore may be formulated as (those are the characterizations I could think of)

*

*$\det(d_i-d_k, d_k-d_j)=0$

*$\frac{\langle d_i-d_k, d_k-d_j\rangle}{\| d_i-d_k\|\cdot \|d_k-d_j\|}=\pm 1$

The most promising is the determinant. Using the correct indices, the determinant may be written as $d^t A d$ with $d\in\mathbb{R}^{2n}$. My first thought was to reformulate my optimization problem like this:
$$
\min_{d\in\mathbb{R}^{2n}} d^T \tilde{Q} d + \tilde{c}d +\mu d^TAd,
$$
which still would be quadratic. However, as it is obvious, $d^TAd$ may be arbitrary small, thus that idea is flawed. Of course, one could do
$$
\min_{d\in\mathbb{R}^{2n}} d^T \tilde{Q} d + \tilde{c}d +\mu (d^TAd)^2.
$$
That one, however, is not even close to quadratic anymore, which catapults the complexity of the problem to a whole new level.
Note, that $n$ is not very big ($n=20$ may be a reasonable guess). However, that problem has to be solved thousands and thousands of times as fast as possible.
My favorite solution would be to get the boundary conditions written as something at most quadratic. If that is not possible, I am looking forward to your ideas on what the most performant optimization algorithm for that particular problem is.
P.S.: There are other boundary conditions of the form $d_i=d_{i+1}$. Those, however, do not really form a problem and probably can be ignored for the matter at hand.

A: So by your collinearity condition, taking any three vectors in the rows of $d$, say $d_i,d_j,d_k$, you can form the equation $c_1 d_i + c_2 d_j + c_3 d_k=0$, with some of the co-efficients not being zero. This amounts to saying that they are linearly dependent. Since you are saying this is true for $i,j,k$. It means that your matrix $d$ is a rank two matrix. Thats all. In terms of column vectors, it means, your first column, should never be a scalar multiple of the second column Now for your optimization problem. You can reformulate it using the $vec$ operator. $vec(d)$ is a $2n\times 1$ vector with its first $n$ elements as the first column of $d$ and the next $n$ elements as next column of $d$. Now use the following identities.
\begin{align}
trace(d^TQd)=vec(d)^T(I\otimes Q)vec(d) \\
trace(Cd)=vec(C^{T})vec(d)
\end{align}
(Please confirm them, am writing them from my memory, but you should get the idea). Defining $c=vec(C^{T})$, $M=(I\otimes Q)$ (kronecker product) and $x=vec(d)$. Thus your problem becomes,
\begin{align}
\min_{x~\epsilon~\mathbb{R}^{2n\times 1}}~x^{T}Mx+c^{T}x
\end{align}
This is a quadratic programming problem. Now the condition you wanted was the columns of $d$ shouldn't be scalar multiples of each other. That will depend on the nature of $M$ and $c$ in here.
EDIT---
If you make your collinearity condition little more explicit, say $d_i-d_k=c(d_k-d_j)$, for some given constant 'c', then this is equivalent to putting some linear equality constraints on the orginal problem. In detail, let $A_1$ be a $1\times n$ vector. You can always find a $A_1$ such that $A_1 d=d_i-d_k$, similarly another $A_2$ such that $A_2 d=d_k-d_j$. Combining both you have the linearity equality constraint $(A_1-cA_2)d=0$. But if you try to make $c$ also a variable, then i am not sure how to proceed.

A: I just solved my own problem.
For the records, here the solution I used, as a rough sketch.
The boundary condition $d_i-d_k=\mu(d_k-d_j)$ may be added without problems for fixed $\mu$. For this $\mu$, the usual quadratic programming approaches allow to find $d_\mu^*$ that solves the optimization problem with respect to those conditions.
Resulting is some one-dimensional optimization problem
$$
 \min_{\mu\in\mathbb{R}} (d_\mu^*)^TQd_\mu^*+cd_\mu^*
$$
The derivatives of this objective function may be computed without to much additional work. Thus, Newtons method may be applied for finding a suitable $\mu$ with only a few iterations.
This is not direct solution, as I would have preferred, but it is fast and has the advantage that the parameter $\mu$ is estimated directly and can be reused for other purposes.


text:
Q: How to get innerHTML content from a loaded element made by .load() Here it is
part.html :

        Hello Mars

full.html :

    $('#inj').load("part.html #header");
    alert(document.getElementById("header").innerHTML); <-- this part is not working

A: if you want to check the loaded content, you need to do it like:
$('#inj').load("part.html #header",function(){
  alert(document.getElementById("header").innerHTML);
});

check http://api.jquery.com/load/

A: the load command is asynchronous you have to wait for the content to load before reading it.
load can have a callback function parameter that is executed when the request completes.
$('#inj').load('part.html', function() {
    alert(document.getElementById('inj').innerHTML);
});

or since you are using jQuery instead of getElementById:
$('#inj').html()


text:
Q: Show only the main frame of the page I would like to print a white page with the frame on the main part of the page:

*

*not the frame of the header

*not the frame of the footer

*not the frame of the footnotes
When I do
\documentclass[a4paper,10pt]{article}

\usepackage[margin=1.5cm, showframe]{geometry}
\pagestyle{empty}

\begin{document}
\
\end{document}

the other frames are printed. See on the left and at the bottom on this screenshot:

Is there a solution to print only the main frame?

A: The showframe option uses a few rules to draw the frame. To stick to geometry only, you need then to redefine the code for showframe:
\documentclass[a4paper,10pt]{article}

\usepackage[margin=1.5cm, showframe]{geometry}

\makeatletter
\renewcommand*{\Gm@vrules@mpi}{%
  \hb@xt@\@tempdima{\llap{\Gm@vrule}\ignorespaces
  \hskip \textwidth\Gm@vrule%\hskip \marginparsep
  % \llap{\Gm@vrule}%
  \hfil
  % \Gm@vrule%
  }}%
\renewcommand*{\Gm@vrules@mpii}{%
  \hb@xt@\@tempdima{\hskip-\marginparwidth\hskip-\marginparsep
  % \llap{\Gm@vrule}%
  \ignorespaces
  \hskip \marginparwidth
  % \rlap{\Gm@vrule}%
  \hskip \marginparsep
  \llap{\Gm@vrule}\hskip\textwidth\rlap{\Gm@vrule}\hss}}%
\renewcommand*{\Gm@pageframes}{%
  \vb@xt@\z@{%
   \ifGm@showcrop
    \vb@xt@\z@{\vskip-1\Gm@truedimen in\vskip\Gm@layoutvoffset%
     \hb@xt@\z@{\hskip-1\Gm@truedimen in\hskip\Gm@layouthoffset%
      \vb@xt@\Gm@layoutheight{%
       \let\protect\relax
       \hb@xt@\Gm@layoutwidth{\Gm@cropmark(-1,1,-3,3)\hfil\Gm@cropmark(1,1,3,3)}%
       \vfil
       \hb@xt@\Gm@layoutwidth{\Gm@cropmark(-1,-1,-3,-3)\hfil\Gm@cropmark(1,-1,3,-3)}}%
     \hss}%
    \vss}%
   \fi%
   \ifGm@showframe
    \if@twoside
     \ifodd\count\z@
       \let\@themargin\oddsidemargin
     \else
       \let\@themargin\evensidemargin
     \fi
    \fi
    \moveright\@themargin%
    \vb@xt@\z@{%
     \vskip\topmargin%\vb@xt@\z@{\vss\Gm@hrule}%
     \vskip\headheight%\vb@xt@\z@{\vss\Gm@hruled}%
     \vskip\headsep\vb@xt@\z@{\vss\Gm@hrule}%
     \@tempdima\textwidth
     \advance\@tempdima by \marginparsep
     \advance\@tempdima by \marginparwidth
     \if@mparswitch
      \ifodd\count\z@
       \Gm@vrules@mpi
      \else
       \Gm@vrules@mpii
      \fi
     \else
      \Gm@vrules@mpi
     \fi
     \vb@xt@\z@{\vss\Gm@hrule}%
     \vskip\footskip%\vb@xt@\z@{\vss\Gm@hruled}%
     \vss}%
    \fi%
  }}%
\makeatother

\pagestyle{empty}

\begin{document}
\
\end{document}

It's a handful of code.
With TikZ, tikzpagenodes, and atbegshi the code gets a tiny bit shorter ;)
\documentclass[a4paper,10pt]{article}

\usepackage[margin=1.5cm]{geometry}

\usepackage{tikzpagenodes}

\usepackage{atbegshi}

\def\drawcode{%
\tikz [remember picture, overlay] \draw
  (current page text area.south west)
  rectangle
  (current page text area.north east);}

\AtBeginDocument{% For the first page
  \drawcode}

\AtBeginShipout{% For the remaining pages
  \drawcode}

\begin{document}
\
\end{document}


text:
Q: VBA Excel - Save as .xlsm followed by save as .pdf location issue I have a template worksheet I use to create daily reports. I am trying to create a macro that uses save as to save and rename the template, then export that newly created xlsm  as pdf. Both files need to be saved in the same location. I can get each to work separately but when I try to combine the two into one macro I run into a runtime error.
This works but saves the PDF to desktop
    Sub SaveRoutine()

    ActiveWorkbook.SaveAs Filename:="U:\Time Study\Timelines\" & Format(Date, "mm.dd.yy") & "- Shift 2" & ".xlsm", FileFormat:=52
    Worksheets("overview").Select
    ActiveSheet.ExportAsFixedFormat _
    Type:=xlTypePDF, _
        Filename:="", _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=True

End Sub

This returns a runtime error after saving as xlms.
    Sub SaveRoutine()

    ActiveWorkbook.SaveAs Filename:="U:\Time Study\Timelines\" & Format(Date, "mm.dd.yy") & "- Shift 2" & ".xlsm", FileFormat:=52

Worksheets("overview").Select
    ActiveSheet.ExportAsFixedFormat _
    Type:=xlTypePDF, _
        Filename:="U:\Time Study\Timelines\", _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=True

End Sub

I am sure its simple and I have tried variations in the Filename:= variable but can't figure it out. Any help would be appreciated.
Thanks


text:
Q: Rails 3.1 asset pipeline and embeddable javascript widgets: Where should the js live? I'm upgrading a rails 2.3.9 application and I have a file named widget.js that lives at /public/javascripts/widget.js.
Users can embed this javascript widget on their own site like so:
<script src='http://example.com/javascripts/widget.js' type='text/javascript'></script>
<script>
  new Widget({user_id: 1234});
</script>

As I understand it, with Rails 3.1 everything under assets/ is fingerprinted in production so widget.js would have a filename like widget-XXXYYYZZZ.js and would change every time the file was changed. This means that it wouldn't be possible to give users this embeddable url for the widget.js file since it'll change.
How can this be accomplished on rails 3.1?

A: You could just leave your script in public/javascripts/widget.js and serve it from /javascripts/widget.js. The asset pipeline is optional, you don't have to use it for everything (or anything for that matter).

A: You can disable fingerprinting by putting
config.assets.digest = false

in config/application.rb or in one of the config/environments/* files.


text:
Q: Помогите исправить ошибку в коде (форма отправки данных на сайте) Файл newform.php загрузил на 000webhost.com
Вот код:
<?php
if (isset($_POST['first_name'])) {$first_name = $_POST['first_name'];}
if (isset($_POST['last_name'])) {$last_name = $_POST['last_name'];}
if (isset($_POST['telephone'])) {$telephone = $_POST['telephone'];}
if (isset($_POST['email'])) {$email = $_POST['email'];}
if (isset($_POST['course'])) {$course = $_POST['course'];
//if (isset($_POST['mess'])) {$mess = $_POST['mess'];}
//if (isset($_POST['select'])) {$mess = $_POST['select'];}

    $to = "моя_почта@gmail.com";
    $headers = "Content-type: text/plain; charset = UTF-8";
    $subject = "Заявка на обучение";
    $message = "first_name: $first_name; \n last_name: $last_name; \n telephone: $phone; \n email: $email; \n course: $course";
    $send = mail ($to, $subject, $message, $headers);
    if ($send == 'true')
    {
    echo "Thank you!
";
    }
    else
    {
    echo "
Ошибка";
    }
}
?>
<form class="form-wrap" method="POST" action="mail.php" onsubmit="return checkForm(this);">

Заявка на обучение

                                <input type="text" class="form-control" name="first_name" placeholder="Имя" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Имя'" >
                                <input type="text" class="form-control" name="last_name" placeholder="Фамилия" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Фамилия'" >
                                <input type="phone" class="form-control" name="telephone" placeholder="Сотовый номер" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Сотовый номер'" >
                                <input type="email" class="form-control" name="email" placeholder="Почтовый адрес" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Почтовый адрес'" >

                                    <select  name="course">
                                        <option datd-display="">Выбрать курс</option>
                                        <option value="1">Подготовка к ЕНТ(10-11класс)</option>
                                        <option value="2">Математика/Логика(НИШ)</option>
                                        <option value="3">Английский язык(НИШ)</option>
                                        <option value="4">Казахский/Русский язык(НИШ)</option>
                                        <option value="5">Математика/Логика(КТЛ)</option>
                                        <option value="6">Английский язык(КТЛ)</option>
                                        <option value="7">Казахский/Русский язык(КТЛ)</option>
                                        <option value="8">Продленка(математика/логика)4класс</option>
                                        <option value="9">Продленка(английский язык)4класс</option>
                                        <option value="10">Продленка(казахский язык)4класс</option>
                                    </select>

                                <button class="primary-btn text-uppercase">Отправить</button>
                            </form>

Ниже код из файла mail.php.
После заполнения полей выдает ошибку:
Parse error: syntax error, unexpected 'Фамилия' (T_STRING), expecting ',' or ')' in /storage/ssd4/925/15155925/public_html/mail.php on line 55
Посмотрел. Вроде в 55 строке все правильно. Где там должна быть "," или ")" никак не пойму.
Помогите исправить ошибку.
<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$telephone = $_POST['telephone'];
$email = $_POST['email'];
$course = $_POST['course'];
$mess = $_POST['mess'];
$select = $_POST['select'];

$first_name = htmlspecialchars($first_name);
$last_name= htmlspecialchars($last_name);
$telephone = htmlspecialchars($telephone);
$email= htmlspecialchars($email);
$course = htmlspecialchars($course);
$mess= htmlspecialchars($mess);
$select = htmlspecialchars($select);

$first_name = urldecode($first_name);
$last_name= urldecode($last_name);
$telephone = urldecode($telephone);
$email= urldecode($email);
$course = urldecode($course);
$mess= urldecode($mess);
$select = urldecode($select);

$first_name = trim($first_name);
$last_name= trim($last_name);
$telephone = trim($telephone);
$email= trim($email);
$course = trim($course);
$mess= trim($mess);
$select = trim($select);

//echo $first_name;
//echo "
";
//echo $last_name;
//echo "
";
//echo $telephone;
//echo "
";
//echo $email;
//echo "
";
//echo $course;
//echo "
";
//echo $mess;
//echo "
";
//echo $select;

if(mail("моя_почта@gmail.com", "Заявка с сайта", "Имя:".$first_name.". "Фамилия:".$last_name.". "Телефон:".$telephone.". "email:".$email.". "Курс:".$course.". "mess:".$mess.". "select:".$select.". E-mail: ".$email ,"From: почта_на_000webhost.com \r\n"))
    {
        echo "сообщение успешно отправлено";
    } else {
        echo "при отправке сообщения возникли ошибки";
        }
?>

Repl.it показывает ту же ошибку:

Вроде все правильно..
В NetBeans где фамилия появилась красная линия. Вставить туда ',' или ')' ?

A: Немного отрефакторил:
$data = [
'Имя'     => 'first_name' ,
'Фамилия' => 'last_name',
'Телефон' => 'telephone',
'email'   => 'email',
'Курс'    => 'course',
'mess'    => 'mess',
'select'  => 'select',
];

$message = array_reduce(array_keys($data), static function (string $prev, $name) use ($data) {
$delim = ': ';
$suffix   = '. ';
$value = trim(urldecode(htmlspecialchars($_POST[$data[$name]] ?? ''))) ?: 'Отсутствует';
return $prev . $name . $delim . $value . $suffix;
}, '');

if (mail("моя_почта@gmail.com", "Заявка с сайта", $message, "From: почта_на_000webhost.com \r\n")) {
echo "сообщение успешно отправлено";
} else {
echo "при отправке сообщения возникли ошибки";
}


text:
Q: How do I verify the hash created by fingerprint2.js using the components array I'm interested in using fingerprint2.js
https://github.com/Valve/fingerprintjs2
I'm storing both the hash and the components array being generated.
Is there a way to take the components and then create the hash?
I realize that the user can spoof his browser data and thereby change the the hash , however I want to ensure that the hash itself is real, and not a spoofed string.
Ie:
Fingerprint2.get(function (components) {
                     console.log(components);
                     Posttoserver(components);
                 });

/* Get hash , components. Post to server, store the data */

What is the function to get the hash? Is it callable separately?
Is there a library or tool that can take a comp array and produce the same hash that the browser generated from the command line?
Like getHash(components)

A: It would appear in version 2.0 hash and component functions have been decoupled
"Fingerprint2 ships with the murmur hash function that you may use to create a hash fingerprint:"
So this means you can rebuild the hash later on for verification very simply . Problem solved


text:
Q: Rearrange dataframe using dcast using a dummy I've like to use dcast function (reshape2 package) for returns a reshape data frame, but doesn't work. In my example:
#Data set
X<-c(804519.4,804519.6,804519.6,804519.4,804519.4,804519.4,804519.6,804519.6,804519.4,804519.4)
Y<-c(7673833,7673833,7673833,7673833,7673833,7673833,7673833,7673833,7673833,7673833)
band<-c("band1","band1","band1","band1","band1","band2","band2","band2","band2","band2")# My original data set are 31 bands
reflec<-c(9.608848,10.504454,8.648237,9.935091,11.282750,9.608848,10.504454,8.648237,9.935091,11.282750)
dummy<-1:10
RES3<-data.frame(X,Y,band,reflec,dummy)
RES3
          X       Y  band    reflec dummy
1  804519.4 7673833 band1  9.608848     1
2  804519.6 7673833 band1 10.504454     2
3  804519.6 7673833 band1  8.648237     3
4  804519.4 7673833 band1  9.935091     4
5  804519.4 7673833 band1 11.282750     5
6  804519.4 7673833 band2  9.608848     6
7  804519.6 7673833 band2 10.504454     7
8  804519.6 7673833 band2  8.648237     8
9  804519.4 7673833 band2  9.935091     9
10 804519.4 7673833 band2 11.282750    10
RES3<-as.data.frame(RES3)
colnames(RES3)<-c("X","Y","band","reflec","dummy")
dcast(RES3, X + Y + dummy ~ band,
         fun.aggregate = length,
         value.var="reflec")

Doesn't work, my output is:
          X       Y dummy band1 band2
1  804519.4 7673833     1     1     0
2  804519.4 7673833     4     1     0
3  804519.4 7673833     5     1     0
4  804519.4 7673833     6     0     1
5  804519.4 7673833     9     0     1
6  804519.4 7673833    10     0     1
7  804519.6 7673833     2     1     0
8  804519.6 7673833     3     1     0
9  804519.6 7673833     7     0     1
10 804519.6 7673833     8     0     1

I expected:
         X       Y    band1    band2
1 804519.4 7673833    9.608848 9.608848
2 804519.6 7673833   10.504454 10.504454
3 804519.6 7673833    8.648237  8.648237
4 804519.4 7673833    9.935091  9.935091
5 804519.4 7673833   11.282750 11.282750

Any member could help me, because my original data set are 31 bands as levels and I've like to convert in columns? Thanks!

A: Like I mentioned, reshape2 has been deprecated in favor of tidyr within the tidyverse packages. In my opinion (and that of the packages' authors), tidyr's spread and gather are a bit more clear than reshape2's cast and melt—no formula notation, cleaner ways to specify values. (Some context for that is here).
Also as I mentioned, you've got a couple extra lines—data.frame will add the column names according to the names of the vectors going into it.
I've updated this answer to match the new data you posted. My original solution worked for your original data, but needs some more steps for your new data, which I'm doing with dplyr functions.
I don't totally get the dummy column at this point, since it's not in your expected output. I'm dropping it with dplyr::select(-dummy). One tricky thing with tidyr::spread is that you need some way to mark rows uniquely—annoying, but also prevents errors in reshaping the data. So I'm grouping by band, then adding row numbers as follows:
library(tidyr)
library(dplyr)

res3 <- data.frame(X, Y, band, reflec, dummy)

res3 %>%
  select(-dummy) %>%
  group_by(band) %>%
  mutate(row = row_number())
#> # A tibble: 10 x 5
#> # Groups:   band [2]
#>          X       Y band  reflec   row
#>      <dbl>   <dbl> <fct>  <dbl> <int>
#>  1 804519. 7673833 band1   9.61     1
#>  2 804520. 7673833 band1  10.5      2
#>  3 804520. 7673833 band1   8.65     3
#>  4 804519. 7673833 band1   9.94     4
#>  5 804519. 7673833 band1  11.3      5
#>  6 804519. 7673833 band2   9.61     1
#>  7 804520. 7673833 band2  10.5      2
#>  8 804520. 7673833 band2   8.65     3
#>  9 804519. 7673833 band2   9.94     4
#> 10 804519. 7673833 band2  11.3      5

That way, row 1 will have a band 1 value and a band 2 value, and so on. Then I call spread with the band as the key to become columns and the reflec values to populate those columns, and finally drop the row number column.
res3 %>%
  select(-dummy) %>%
  group_by(band) %>%
  mutate(row = row_number()) %>%
  spread(key = band, value = reflec) %>%
  select(-row)
#> # A tibble: 5 x 4
#>         X       Y band1 band2
#>     <dbl>   <dbl> <dbl> <dbl>
#> 1 804519. 7673833  9.61  9.61
#> 2 804519. 7673833  9.94  9.94
#> 3 804519. 7673833 11.3  11.3
#> 4 804520. 7673833 10.5  10.5
#> 5 804520. 7673833  8.65  8.65

Created on 2019-01-28 by the reprex package (v0.2.1)

A: The value.var should be a string that specifies the column name.  According to ?dcast

value.var - name of column which stores values

and name of column is character string
By specifying it unquoted, it is searching for the column name from the values
dcast(RES3, X + Y + dummy ~ band,
         fun.aggregate = length,
         value.var="reflec")

A: RES4<-dcast(RES3, ... ~ band,
            value.var="reflec")


text:
Q: Работа скрипта только в активном окне браузера Как заставить данный цикл работать только тогда, когда у пользователя активно окно браузера.
То есть, цикл должен переставать работать, когда окно браузера свёрнуто или когда пользователь перешел на другую вкладку браузера(на другой сайт).

let a = document.querySelector('.opa');

let go = setInterval(function() {
  a.style.height = a.offsetHeight * 1 + 'px';
}, 1000);
.opa {
  padding: 20px;
  background: gray;
}

 Это цикл

A: Попробуйте воспользоваться Page Visibility API. Возможно вам этого будет достаточно. Для этого надо подписаться на ивент visibilitychange.

let a = document.querySelector('.opa');
let interval;

function startDoingSothing() {
  interval = setInterval(function() {
    a.style.height = a.offsetHeight * 1 + 'px';
  }, 1000);
}

startDoingSothing();

function handleVisibilityChange() {
  console.log( document.visibilityState );
  if (document.visibilityState === "hidden") {
    clearInterval(interval);
  } else {
    startDoingSothing();
  }
}

document.addEventListener("visibilitychange", handleVisibilityChange, false);
.opa {
  padding: 20px;
  background: gray;
}

 Это цикл


text:
Q: Why can't I get json from struts 2 action? I want to send ajax post request to my struts action using jquery like this:
$.ajax({
        type: "POST",
        url: "ds/query",
        data :JSON.stringify(data),
        dataType:"json",
        contentType: "application/json; charset=utf-8",
        success : function(d, t, x){
            console.log(x);
        }
    });

my action configuaration:
<package name="ds" namespace="/ds" extends="json-default">
        <action name="query" class="gov.cbrc.gzbanking.action.DataServiceAction" method="query">
            <interceptor-ref name="json">
                <param name="enableSMD">true</param>
            </interceptor-ref>
            <result type="json">
                <param name="noCache">true</param>
                <param name="excludeNullProperties">true</param>
                <param name="root">qRes</param>
            </result>
        </action>
    </package>

my action class :
public class DataServiceAction {

    private QueryRequest qReq;

    private QueryResponse qRes;

    public QueryRequest getQr() {
        return qReq;
    }

    public void setQr(QueryRequest qReq) {
        this.qReq = qReq;
    }

    public QueryResponse getqRes() {
        return qRes;
    }

    public void setqRes(QueryResponse qRes) {
        this.qRes = qRes;
    }

    public String query() throws Exception{
        App.getLogger().debug(qReq.toString());
        String dsClz = SysCodes.getCodeItem("data_service", qReq.getDs()).getConfig1();
        Class<?> dsCls = Class.forName(dsClz);
        if(!DataService.class.isAssignableFrom(dsCls)){
            throw new Exception("specified class does't implement DataService interface.");
        }else{
            DataService ds = (DataService) dsCls.newInstance();
            System.out.println(JsonUtil.toJson(ds.query(qReq)));
            qRes = ds.query(qReq);
        }
        return ActionSupport.SUCCESS;
    }

}

QueryRequest and QueryResponse are just java beans, when I execute my code, Server can read json data and do it's job without error, and I am sure QueryResponse object is popluted with data. but I can't get anything at client side, responseText and responseJson are both null.
why did not struts-json plugin convert my QueryResponse  object into json string automaticaly?
my QueryResponse  class :
public class QueryResponse {

    private int total;

    private List<?> data;

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public List<?> getData() {
        return data;
    }

    public void setData(List<?> data) {
        this.data = data;
    }

}

the actual type of data list contains must be determined at runtime, for example, if data contains list of Role objects:
package gov.cbrc.gzbanking.domain;
public class Role {

    private String id;

    private String name;

    private String remark;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

then expected result is like this:
{
total : "1", data :[{"id":"admin", "name":"admin role"}]
}

A: Because you are using Struts2. Struts2 is used to capitalize property name to resolve a getter method, before a "get" method name could be resolved a property "qRes" capitalized to "QRes" and prefixed with "get". So, the method name will be getQRes.  You can remove root parameter from the result and see if it can be used otherwise, or rename a getter method name as
public QueryResponse getQRes() {
    return qRes;
}

You can also read this question about why generated getters and setters in Eclipse don't work with Struts2 OGNL.

A: I think you are not reading data properly at client side. Try this:
$.ajax({
    type: "POST",
    url: "ds/query",
    data :JSON.stringify(data),
    dataType:"json",
    contentType: "application/json; charset=utf-8",
    success : function(d, t, x){
        console.log(t);
        console.log(d[0].id);
        console.log(d[0].name);
    }
});


text:
Q: Any tips on implementing a Google Maps frame into drupal? i have this very simple google map that I want to be displayed as the first thing you see on my drupal homepage. Any suggestion on how I can get it on there nicely? I've tried using a module called insertFrame and using their shorthand, but it is an old module and I can't seem to get it working... Thanks for any and all advice!
var overlay;
var myCenter=new google.maps.LatLng(##.######, -##.######);
var marker;

USGSOverlay.prototype = new google.maps.OverlayView();

function initialize() {

var myLatLng = new google.maps.LatLng(##.######, -##.######);
var mapOptions = {
zoom: 11,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.MAP
};

var map = new google.maps.Map(document.getElementById('map-canvas'),
  mapOptions);

var swBound = new google.maps.LatLng(##.######, -##.######);
var neBound = new google.maps.LatLng(##.######, -##.######);
var bounds = new google.maps.LatLngBounds(swBound, neBound);

marker=new google.maps.Marker({
position:myLatLng,
animation:google.maps.Animation.BOUNCE
});
marker.setMap(map);

var srcImage = 'https://developers.google.com/maps/documentation/javascript/';

overlay = new USGSOverlay(bounds, srcImage, map);
}

function USGSOverlay(bounds, image, map) {

this.bounds_ = bounds;
this.image_ = image;
this.map_ = map;

this.div_ = null;

this.setMap(map);
}

USGSOverlay.prototype.onAdd = function() {

var div = document.createElement('div');
div.style.border = 'none';
div.style.borderWidth = '0px';
div.style.position = 'absolute';

var img = document.createElement('img');
img.src = this.image_;
img.style.width = '100%';
img.style.height = '100%';
div.appendChild(img);

this.div_ = div;

var panes = this.getPanes();
panes.overlayImage.appendChild(this.div_);
};

USGSOverlay.prototype.draw = function() {

var overlayProjection = this.getProjection();

var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());

var div = this.div_;
div.style.left = sw.x + 'px';
div.style.top = ne.y + 'px';
div.style.width = (ne.x - sw.x) + 'px';
div.style.height = (sw.y - ne.y) + 'px';
};

USGSOverlay.prototype.onRemove = function() {
this.div_.parentNode.removeChild(this.div_);
};

USGSOverlay.prototype.hide = function() {
if (this.div_) {

this.div_.style.visibility = 'hidden';
}
};

USGSOverlay.prototype.show = function() {
if (this.div_) {
this.div_.style.visibility = 'visible';
}
};

USGSOverlay.prototype.toggle = function() {
if (this.div_) {
if (this.div_.style.visibility == 'hidden') {
  this.show();
} else {
  this.hide();
}
}
};
USGSOverlay.prototype.toggleDOM = function() {
if (this.getMap()) {

this.setMap(null);
} else {
this.setMap(this.map_);
}
};

google.maps.event.addDomListener(window, 'load', initialize);

</script>

  <input type="button" value="Toggle visibility" onclick="overlay.toggle();"></input>
  <input type="button" value="Toggle DOM attachment" onclick="overlay.toggleDOM();"></input>

A: In this case I think your code is custom enough that it can go directly into your templates as opposed to in a node or a block or anything like that.
Your page template contains the markup for your page and you can override this to have a specific template just for your home page.
To do this copy your theme's page.tpl.php to page--front.tpl.php (if your theme doesn't have a page.tpl.php you can get it from your theme's base theme or else the drupal core system module)  - then clear your drupal cache so the new template gets picked up.
Then you would add your map canvas div markup in the place you want your map to go.
Then copy all your javascript code into a javascript file and call it something like map.js and put it in your theme (in it's javascript or js directory if your theme has one).
Then you can load your js file for the home page only by using drupal_add_js() in your template_preprocess_html() function of your template.php file of you theme like this:
function THEMENAME_preprocess_html(&$variables) {
  // Add js for the homepage map.
  if (drupal_is_front_page()) {
    drupal_add_js(drupal_get_path('theme', 'THEMENAME') . '/js/map.js');
  }
}

Alternatively you might want to write a custom module that implements a custom block that prints the map div and adds the map js.
There are a number of ways you can add the map so it depends on your requirements as to which is the best option for you.


text:
Q: Friendly URL's with UTF8 characters I'm dealing with creating friendly url's using the title of articles which can be in different languages.
Some languages use characters like 'ä','ü','ö','ß', other characters like cyrillic, accents in spanish words and so on.
The question is that I need to create an URL perfectly understable by browsers and of course google.
Is there any function which manage this?
I'm quite confused in tackling this task.
Anyone can help?

A: Okay do this.
Pass the string as an argument into the inbuilt urlencode("string");
A valid URL is generated

A: At least I could find the solution.
Here is a link of a function that manage this perfectly: https://gist.github.com/sgmurphy/3098978#file-url_slug-php
I hope this help people with the same problem.


text:
Q: Novel: Woman lives her entire life, then finds out it was just practice I read this book sometime between the late 1980s and the early 1990s. The story follows the life of a woman, which starts when she is a newborn in a kind of robotic creche that cares for her, teaches her how to speak, and provides basic elementary school level knowledge. Once she gets to early childhood (maybe 5 years old or so?), she learns that there is a world outside the creche and is allowed to go out into it.
Outside is a futuristic society that I'm not 100% sure was supposed to be Earth, though from the impression I recall it could have been a future Earth with a low population. She finds other people and has various adventures (none of which I can recall), and she eventually reaches old age. She reflects back on her life on her deathbed (I think) and eventually dies.
At that point, she wakes up again and finds herself as an infant in the same robotic creche. The creche explains to her that her previous life was a simulation, and that this is now her real life -- she will be much better prepared for it now that she has had a chance to experience it once and learn from her mistakes. The story ends before describing anything about what she does in her real life.
I think that there may have been a kind of parallel or framing story intermixed with this, which may have been about explorers examining the ruins of a dead civilization on an alien planet (maybe the future of the main character's planet?), but the framing story didn't have as much of an impact, and I'm not sure I'm not conflating something from another story here.
The book was a paperback, probably around 250 to 300 pages or so based on size, having a bluish cover showing a landscape with a gas giant type of planet in the sky and buildings/figures in the foreground. I'd guess a late 1970s publication, but it could have been earlier.
I think that the author had a woman's name. I'm pretty sure that it was NOT a big-name author, unless it was a pen name for one of them. I recall looking for other stories by the same author but not finding any, so this book and author may be pretty obscure.

A: I remembered enough to find this one with some searching on ISFDB. It's From the Legend of Biel (1975) by Mary Staton.
An Amazon review by Doran Jensen mentions the essential plot point that I recall:

Before a child can be "released" into the Thoacdien world they are
given a chance to live a life before they are born, a chance to work
through their fears and limitations so they can be truly themselves
and part of the galaxy spanning civilization to which they will
belong.

I don't have a copy handy to provide quotes, so I'm not sure how much of the rest of it I may have misremembered. The cover isn't quite as I recall -- the "gas giant" was actually a large round building behind the others:

The author only published one other book, in 2007, which I think was after the time that I looked for her other works online.
For anyone interested, it appears that an electronic copy can be "borrowed" from the Internet Archive.


text:
Q: Notice: Undefined index on line XX I am creating a database using php and viewing the tables in html.  Within my coding I scripted an "add/insert" function to insert within the table with a submit button.  When the submit button is selected it takes me to the error message listed above.  I am not sure what I have changed, I ran this code last night (on a different computer) and all worked fine!?!  Anyone have any ideas??
Here is the code for my insert scripts for the TABLE, INSERT info, add.html and insert.php
<?php
$con=mysqli_connect("localhost","root","","Franchise_Call_Log");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Create table
$sql="CREATE TABLE caller_info(caller_id int(11) unsigned auto_increment primary key not null,
Firstname varchar(35) not null, Lastname varchar(35) not null,
Franchise varchar(25) not null)";

// Execute query
if (mysqli_query($con,$sql))
{
echo "Table caller_info created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
?>

<?php
$con=mysqli_connect("localhost","root","","Franchise_Call_Log");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_query($con,"INSERT INTO caller_info (Firstname, Lastname, franchise)
VALUES ('Peter', 'Griffin',Minneapolis)");

mysqli_query($con,"INSERT INTO caller_info (Firstname, Lastname, Franchise)
VALUES ('Maggie', 'DeJesus',Virginia)");

mysqli_close($con);
?>

<html>
<body>

<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Franchise: <input type="text" name="franchise">
<input type="submit">
</form>

</body>
</html>

<?php
$con=mysqli_connect("localhost","root","","Franchise_Call_Log");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="INSERT INTO caller_info (Firstname, Lastname, Franchise)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[franchise]')";

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>

*UPDATE
I was able to fix the issue above by changing the names of my files but now running everything again I am running into this message:
Notice: Undefined index: Firstname in C:\xampp\htdocs\Final Tests\insert.php on line 11
Notice: Undefined index: Lastname in C:\xampp\htdocs\Final Tests\insert.php on line 11
Notice: Undefined index: Franchise in C:\xampp\htdocs\Final Tests\insert.php on line 11
 1 record added
Although its just a notice, when selecting the tables the new record is not there.  There is a disconnect somewhere that I am not catching.  Any thoughts?

A: You use
$sql="INSERT INTO caller_info (Firstname, Lastname, Franchise)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[franchise]')";

But where you refer to the $_POST values ( ex: $_POST[xyz] ), you are not quoting the xyz name. It should be:
$sql="INSERT INTO caller_info (Firstname, Lastname, Franchise)
VALUES
('{$_POST['firstname']}','{$_POST['lastname']}','{$_POST['franchise']}')";

I've added the {}-brackets around the $_POST['xyz'] so php can correctly identify the variable. Ofcourse you are now subject to SQL-injection ( read more at How can I prevent SQL injection in PHP? )

A: If your submitting the form to the same page then leave the action field blank:
<form action="" method="post">

Specify name for submit button:
<input type="submit" name="submit">

and insert the value into database if the submit is set(submit is pressed):
if(isset($_POST['submit'])){

$sql="INSERT INTO caller_info (Firstname, Lastname, Franchise)
      VALUES('".$_POST['firstname']."','".$_POST['lastname']."',
             '".$_POST['franchise']."')";

if (!mysqli_query($con,$sql))
 {
die('Error: ' . mysqli_error($con));
 }
echo "1 record added";
}


text:
Q: Get selected products summery from another table I have a table1 where column names are there

line
product

1
a

2
b

3
d

Another table2 product sales

a
b
c
d

l
s
m
xs

xs
s
xs
m

m
xl
s
l

xs
xl
m
xl

xs
xl
l
s

xs
m
xl
l

m
m
l
l

s
m
m
l

And I want a summery of products from table2 based on selected products in table1. Ay suggestion on this please?
The expected result looks like;

product
sizes
qty

a
l
1

a
xs
4

a
m
2

a
s
1

b
s
2

b
xl
3

b
m
3

d
xs
1

d
m
1

d
l
4

d
xl
1

d
s
1

A: You need to first linearize your sales table, by changing the schema from <a,b,c,d> to <product, sizes> using the UNION ALL as shown in the cte below.
Then you can:

*

*use INNER JOIN to filter your needed products,

*use COUNT to generate your qty field, by aggregating on both product and sizes

WITH cte_sales AS (
    SELECT 'a' AS product, a AS sizes FROM sales
    UNION ALL
    SELECT 'b' AS product, b AS sizes FROM sales
    UNION ALL
    SELECT 'c' AS product, c AS sizes FROM sales
    UNION ALL
    SELECT 'd' AS product, d AS sizes FROM sales
)
SELECT s.product, s.sizes, COUNT(s.sizes) AS qty
FROM       products  p
INNER JOIN cte_sales s
        ON p.product = s.product
GROUP BY s.product, s.sizes
ORDER BY s.product, s.sizes

If you know in advance you want only a, b and c sales, and want to avoid the join, you can also do as follows:
WITH cte_sales AS (
    SELECT 'a' AS product, a AS sizes FROM sales
    UNION ALL
    SELECT 'b' AS product, b AS sizes FROM sales
    UNION ALL
    SELECT 'd' AS product, d AS sizes FROM sales
)
SELECT s.product, s.sizes, COUNT(s.sizes) AS qty
FROM cte_sales s
GROUP BY s.product, s.sizes
ORDER BY s.product, s.sizes

Output:

product
sizes
qty

a
l
1

a
m
2

a
s
1

a
xs
4

b
m
3

b
s
2

b
xl
3

d
l
4

d
m
1

d
s
1

d
xl
1

d
xs
1

Check the demo here.


text:
Q: Uploading a File with Ajax POST, Multipart content and JSON payload There is a REST service, which enables me to upload a file. I have to construct a POST request with the following payload, for example:
Content-Type: multipart/form-data; boundary= ---1234567890
-----1234567890
Content-Disposition: form-data; name="parameters"
Content-Type: application/json

{
"parentID":"FB4CD874EF94CD2CC1B60B72T0000000000100000001"
}
-----1234567890
Content-Disposition: form-data; name="primaryFile"; filename="example.txt"
Content-Type: text/plain

<File Content>
-----1234567890--

Looks simple enough. The first part is a JSON object, that decribes the location on the server, where the file should be saved, the second part is the file itself. (Please note that I am n no position to modify the server.)
After lots of googling, I discovered that I can use FormData object to create this multipart request. Here is my code:
function checkInNewFile(folderId, file)
{
  var response;
  var fd = new FormData();

  var parent = new Blob(['{ "parentID": "' + folderId + '" }"'], { type: "application/json"});
  fd.append("parameters", parent, null);

  fd.append("primaryFile", file);

  var jqXHR =
    $.ajax(
      {
        type: "POST",
        url: someURL,
        async: false,

        data: fd,
        processData: false,
        contentType: false
      }
    );
  jqXHR.done( function (data) { response = data; });
  return response;
}

The generated request is almost the expected one ... the file content is correct, but I am unable to create exactly the first part. Actually the code above produce this first part:
-----1234567890
Content-Disposition: form-data; name="parameters"; filename=""
Content-Type: application/json

{
"parentID":"FB4CD874EF94CD2CC1B60B72T0000000000100000001"
}

As you see, there is an additional filename attribute in the request, and although the actual name is empty, my server does not like the request in this form.
Of course I tried to add a simple text value as the first part:
  var parent = '{ "parentID" : "' +  folderId + '" }';
  fd.append("parameters", parent);

but now the request looks like:
-----1234567890
Content-Disposition: form-data; name="parameters"

{ "parentID":"FB4CD874EF94CD2CC1B60B72T0000000000100000001" }

i.e. the Content-Type is missing, and it is not accepted by the server.
I was trying to add the data as an object, but it did not help at all, either the Content-type or the actual JSON representation, or both were missing.
Reading the FormData documentation, I did not find any other choice. And I do not know enough JavaScript to rewrite FormData from scratch.
Any idea?


text:
Q: Check if a result set has specific values I want to know what is the best way to check if a subquery has a set of values. I came up with the following query but I don't think its efficient.
SELECT * FROM SomeTable
WHERE
(
    2 IN (SELECT OptionId FROM Table2 WHERE Table2_Id = 1) AND
    3 IN (SELECT OptionId FROM Table2 WHERE Table2_Id = 1)
)

I appreciate if anyone can provide me with a better solution.
Thanks

A: I would use EXISTS subqueries:
SELECT * FROM SomeTable
WHERE EXISTS (SELECT * FROM Table2 WHERE Table2_Id = 1 AND OptionId = 2)
AND   EXISTS (SELECT * FROM Table2 WHERE Table2_Id = 1 AND OptionId = 3)

If you have one of the following indexes (Table2_Id,OptionId) or (OptionId,Table2_Id) then you shouldn't have worries about performance.
Edit 1: After reading above comments I think you should JOIN somehow SomeTable with Table2 using a common column thus:
SELECT * FROM SomeTable x
WHERE EXISTS (SELECT * FROM Table2 y WHERE y.Table2_Id = 1 AND y.OptionId = 2 AND x.CommonColumn = y.CommonColumn)
AND   EXISTS (SELECT * FROM Table2 y WHERE y.Table2_Id = 1 AND y.OptionId = 3 AND x.CommonColumn = y.CommonColumn)

If this doesn't solve your problem then you should add more infos.


text:
Q: Getting Value of dynamic form fields using Jquery I have a form dynamically created using Jquery and i am trying to validate the form but every time i try to get the input field value it says "undefined" , My code to get value
var username = $('#username').val();
       console.log(username);

Edited : Below function will add the form field to the div.modal
    function AddUserDialog(){
      var temp = '<input type="text" name="username" id="username" />';
       $('.modal').html(temp);
     }

Thanks

A: $("#form_id").live('submit',function(){
    if($(this).find('#username').val()==''){
        alert('username cant left empty!!');
        return false;
    }
});

Because the form is created by jquery your script can't find it in document and will return undefined..
For such cases we have 3 functions we can use..live,delegate and on..
Read following links for more details..
Live
delegate
on


text:
Q: Averaging the inductor waveforms I am struggling with moving average model of dc-dc converter as below. The image is my modified version from the lecture here (page 18).
My question is written in the image. Can anyone explain that?
  Sorry for the bad writing.

A: How about this:

Notice there is a slight variation in the notation of the result.
Edit for clarification and further point:
From the above equations we get:
\begin{equation}
\ <v_{L}(t) > _{T_{s}} = <v_{g}(t) > _{T_{s}} + <v(t) > _{T_{s}}
\end{equation}
This equation implies that the contents are continous for the whole period.
Now everybody agrees on this, right? We further continue the equation and get:
\begin{equation}
\ <v_{g}(t) > _{T_{s}} = d(t) <v_{g}(t) > _{dT_{s}} + d'(t) <v_{g}(t) > _{d'T_{s}}
\end{equation}
\begin{equation}
\ <v(t) > _{T_{s}} = d(t) <v(t) > _{dT_{s}} + d'(t) <v(t) > _{d'T_{s}}
\end{equation}
but (as can be seen on graph) we assumed this:
\begin{equation}
\ v_{g}(t) = 0 \ (d<t<T_{s})
\\
\ v(t) = 0 \ (0<t<d)
\end{equation}
Thus,
\begin{equation}
\ <v_{g}(t) > _{T_{s}} = d(t) <v_{g}(t) > _{dT_{s}}
\end{equation}
\begin{equation}
\ <v(t) > _{T_{s}} = d'(t) <v(t) > _{d'T_{s}}
\end{equation}
This makes sense because:
\begin{equation}
\ \frac{d(t)}{T_{s}} < 1
\end{equation}
\begin{equation}
\ \frac{d'(t)}{T_{s}} < 1
\end{equation}
The average of those signals taken over a longer time within Ts would drop because they are zero. The maximum average occurs within the zones they are non-zero.
Therefore, what we finally get is:
\begin{equation}
\ <v_{L}(t) > _{T_{s}} = d(t) <v_{g}(t) > _{dT_{s}} + d'(t) <v(t) > _{d'T_{s}}
\end{equation}
Which is not the result found in the slides but I am not sure where I made a mistake in the math... Maybe the slides just have a minor mistake in notation? (It happens)

A: The notation is pretty confusing, but after studying the slides my interpretation is:
d is the fraction of "on" time during the cycle. d' is the fraction of off time during the cycle. Averaged across the cycle, VL will approximately equal input voltage VG for d fraction of the time and will approximately equal output voltage V for d' fraction of the time. So the average voltage will be d*VG + d'*V.
Since everything is a function of time (hopefully slowly changing),  VG and V are replaced by averages over the cycle. And d and d' are replaced by d(t) and d'(t). (This is how the model preserves the low frequency components and removes the high frequency components.) This gives the right hand side of the equation you're looking at. Because these are changing very slightly over a cycle, it's not exact equality but approximate equality so the ≈ symbol is used.
Note that in the integrals, d is used for its differential meaning, while in the other equations d indicates the PWM fraction, which makes things harder to understand. And d' is not the derivative of d but 1-d.
Edit to include some of the comment discussion:
Consider a real-life example such as a power supply where the input voltage Vg(t) is 170V + 60 Hz ripple + 30 kHz switching ripple. You can simplify this by making Vg constant at 170V (which is what chapter 2 does). Or you can make a more realistic simplification by averaging out the ripple and getting Vg(t) = 170V + 60 Hz ripple (which is what chapter 7 does).
One tricky part is that in approximating the integral in the original question, you're assuming that Vg(t) is approximately constant over the switching time period. But after that point in the analysis, you treat the moving averages as functions of t, not constants.

A: I prefer to analyze using the energy storage function E=1/2LI^2 where V1*dt1=V2*dt2 [volt-second] in continuous mode.
Maybe the book explains it better,

I also had a hard time following his notation as well.

A: You are focusing on the math as opposed to realizing why the math must work.
For any switcher operating in continuous mode, the area of the ON cycle must equal the OFF cycle.  The area of the yellow rectangle must equal the orange rectangle for the switcher to be in steady-state mode.

During ON time current comes from the source, but during the OFF time current comes from the inductor forward biasing the diode.  \$I_{MAX}\$ and \$I_{MIN}\$ must meet up or capacitor voltage changes.  It's why switchers require a minimum current.
Wikipedia - Buck converter

A:
From that picture it is important to notice that < v_g(t) > is the dotted line not the one that has a slope. What you are doing is calculating the average of inductor voltage over one switching cycle. So even though the averages change in time, for one specific time period the average notated by < v_g(t) > is constant because it is defined that way.
In other words you messed up notations. In the integral that you made yourself in hand writing you shouldn't have used the over swithcing cycle averages < v_g(tau) > and < v(tau) > but just plain v_g(tau) and v(tau). That is because you don't know the averages for that time period yet but you are only calculating them. They are defined to be the answer of those time integrals. < v_g(t) > for the on time and < v(t) > for the off time.
Also then the interal derived by you only works if calculated from the beginning of the switching cycle but the equation that is on the left side from it works always but of course you knew that and just calculated it from beginning of swithing cycle for convience.

A: Defining:
$$
\begin{align}
d(\tau) &= 1\text{ for } t\leq \tau \leq t+dT_z\\
&= 0 \text{ for } t+dT_s < \tau \leq t+T_s
\end{align}
$$
and
$$
\begin{align}
d'(\tau) &= 0\text{ for } t\leq \tau \leq t+dT_z\\
&= 1 \text{ for } t+dT_s < \tau \leq t+T_s
\end{align}
$$
Then
$$
\begin{align}
\left< v_L(t)\right>_{T_s}&= \frac{1}{T_s}\int_t^{t+T_s}v_L(\tau)d\tau =\\
&= \frac{1}{T_s} \left[1 \times\int_t^{t+dT_s}  v_g(\tau)d\tau +0\times\int_{t+dT_s}^{t+T_s} v_g(\tau)d\tau+\\
+ 0 \times\int_t^{t+dT_s}  v(\tau)d\tau +1\times\int_{t+dT_s}^{t+T_s} v(\tau)d\tau \right]
\end{align}
$$
Appliying the inverse of the distributive property and knowing that
$$
\int_t^{t+dT_s}  x(\tau)d\tau  + \int_{t+dT_s}^{t+T_s}  x(\tau)d\tau =  \int_t^{t+T_s}  x(\tau)d\tau
$$
then,
$$
\begin{align}
\left< v_L(t)\right>_{T_s}&= \frac{1}{T_s}\left[d(\tau)\times\int_t^{t+T_s}v_g(\tau)d\tau+d'(\tau)\int_t^{t+T_s}v(\tau)d\tau  \right]\\
&=d(\tau)\times\frac{1}{T_s}\int_t^{t+T_s}v_g(\tau)d\tau+d'(\tau)\times\frac{1}{T_s}\int_t^{t+T_s}v(\tau)d\tau\\
&= d(\tau)\times\left< v_g(t)\right>_{T_s}+d'(\tau)\times\left< v(t)\right>_{T_s}
\end{align}
$$
thus obtaining the awaited result.


text:
Q: Problems with setting aspect ratio in matplotlib, python 3.6, flattening figure I am trying to format a figure I am making. I have been trying to set the aspect ratio, but whenever I include the aspect ratio call, or use ax.set_aspect(), I end up with a flattened figure.
fig, ax = plt.subplots(1, 1)
plt.rcParams["font.family"] = 'Calibri'

ax.set(xlim=[415, 700], ylim=[0,1.01], aspect=1)

ax.set_xlabel('Wavelength (nm)')
ax.set_ylabel('Normalized Reflectance (a.u.)')

_ = ax.plot(x_lambda[0], y_refl_norm[0], marker='', linestyle='-', color='m')
_ = ax.plot(x_lambda[1], y_refl_norm[1], marker='', linestyle='-', color='b')
_ = ax.plot(x_lambda[2], y_refl_norm[2], marker='', linestyle='-', color='c')
_ = ax.plot(x_lambda[3], y_refl_norm[3], marker='', linestyle='-', color='g')
_ = ax.plot(x_lambda[4], y_refl_norm[4], marker='', linestyle='-', color='y')
_ = ax.plot(x_lambda[5], y_refl_norm[5], marker='', linestyle='-',
color='orange')
_ = ax.plot(x_lambda[6], y_refl_norm[6], marker='', linestyle='-', color='r')

ax.legend(('30 degrees', '35 degrees', '40 degrees', '45 degrees', '50
degrees', '55 degrees', '60 degrees'), loc='lower left', fontsize='x-small',
frameon='True', facecolor='navajowhite', framealpha=0.95)

Without the "aspect=1"
With the "aspect=1"

A: What else would you expect if the range of your x-axis is ~300x larger than the range on the y-axis? With aspect=1 this gives you a figure of which the height is ~300x smaller than the width.
Take this simple example:
import matplotlib.pylab as pl

pl.figure()
pl.subplot(231, aspect=1)
pl.fill_between([0,1],[0,0],[1,1])
pl.xlim(0,10)
pl.ylim(0,10)

pl.subplot(232, aspect=1)
pl.fill_between([0,1],[0,0],[1,1])
pl.xlim(0,10)
pl.ylim(0,5)

pl.subplot(233, aspect=1)
pl.fill_between([0,1],[0,0],[1,1])
pl.xlim(0,10)
pl.ylim(0,1)

pl.subplot(234)
pl.fill_between([0,1],[0,0],[1,1])
pl.xlim(0,10)
pl.ylim(0,10)

pl.subplot(235)
pl.fill_between([0,1],[0,0],[1,1])
pl.xlim(0,10)
pl.ylim(0,5)

pl.subplot(236)
pl.fill_between([0,1],[0,0],[1,1])
pl.xlim(0,10)
pl.ylim(0,1)

When the x-range is equal to the y-range you end up with a square figure in order to keep the aspect ratio of the x-to-y axis equal (black block = square). If the y-range is half the x-range, the height will be half the width, again to keep the aspect ratio equal.
In your case, the only solution is to use an aspect ratio unequal to one, unless you want to make a veeeeeery wide figure in order to keep the y-axis readable.


text:
Q: Creating a link for the test cases in Testlink Is there anyway that I can link the 'testcase A' in testcase B's test description within the same test project in TestLink.
Thanks in adv
Rgds
HH

A: You can use "Relations" section under the "Step actions". There are 5 types of relations. To simply link one test case to another, you can pick "related to" and type ID of related test case.
http://prntscr.com/55xwud


text:
Q: Javascript game, make spaceship shoot on pressdown with interval I am working on my gaming skills (mainly with arrays) to generate enemies and now bullets to take them down. I was able to set-up bullets while testing, but were visible only when I had a key pressed (space bar let's say) and with no interval in between, so the browser was not able to take that many at one point.
Is there any simple way to make the ship fire bullets with interval in between (not to load the browser that much) and maybe upon going to the enemy[i].x / y location to delete an enemy and the bullet can disappear ?
Here is the cleaned as much as possible code I have for now (HTML and JS file. Have some images as well and will provide URL to the game to check it if needed - http://sarahkerrigan.biz/spaceship
<!DOCTYPE html>

    <title>Space Ship</title>

Space Ship

   <canvas id="canvas" width="1000" height="600"></canvas>

And here is the spaceship.js file:
var cvs = document.getElementById("canvas");
var ctx = cvs.getContext("2d");
//-------------------------------

// load images

var player = new Image();
var enemy = new Image();
var bullet = new Image();

player.src = "images/player.png";
enemy.src = "images/enemy.png";
bullet.src = "images/fire.png";
//-------------------------------

// vars
var score = 0;
var pause = 0;

var playerY = 300;
var playerX = 100;

var upPressed = false;
var downPressed = false;
var leftPressed = false;
var rightPressed = false;

// audio
var fire = new Audio();
var hit = new Audio();

fire.src = "sounds/fire.mp3";
hit.src = "sounds/hit.mp3";

//-------------------------------
// on key down
document.addEventListener("keydown", keyDownHandler);

function keyDownHandler(e) {
  if (e.keyCode == 87) {
    upPressed = true;
  }
  if (e.keyCode == 83) {
    downPressed = true;
  }
  if (e.keyCode == 65) {
    leftPressed = true;
  }
  if (e.keyCode == 68) {
    rightPressed = true;
  }
}

// on key up
document.addEventListener("keyup", keyUpHandler);

function keyUpHandler(e) {
  if (e.keyCode == 87) {
    upPressed = false;
  }
  if (e.keyCode == 83) {
    downPressed = false;
  }
  if (e.keyCode == 65) {
    leftPressed = false;
  }
  if (e.keyCode == 68) {
    rightPressed = false;
  }
}

//-------------------------------

function moveUp() {
 if (playerY <= canvas.height - canvas.height){
 }
 else{
  playerY -= 6;
 }
}

function moveDown() {
 if (playerY >= canvas.height - player.height){
 }
 else{
  playerY += 6;
 }
}

function moveLeft() {
 if (playerX <= canvas.width - canvas.width){
 }
 else{
  playerX -= 6;
 }
}

function moveRight() {
 if (playerX >= canvas.width - player.width){
 }
 else{
  playerX += 6;
 }
}

//-------------------------------
// Enemy coordinates

var enemies = [];

enemies[0] = {
  x: cvs.width,
  y: 0
};

//-------------------------------

// reload page

function reLoad() {
  location.reload(); // reload the page
}

//-------------------------------
// draw images

function draw() {

  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  if (upPressed === true) {
    moveUp();
  }
  if (downPressed === true) {
    moveDown();
  }
  if (leftPressed === true) {
    moveLeft();
  }
  if (rightPressed === true) {
    moveRight();
  }

//-------------------------------
  for (var i = 0; i < enemies.length; i++) {

    //draw the enemy
    ctx.drawImage(enemy, enemies[i].x, enemies[i].y);

    // enemy movement speed
    enemies[i].x -= 3;

    if (enemies[i].x == 880) {
      enemies.push({
        x: cvs.width,
        y: Math.floor(Math.random() * enemy.height) * 10 - enemy.height
      });
    }

    // detect collision

    // if enemy hits player
    if (playerX + player.width >= enemies[i].x && playerX <= enemies[i].x + enemy.width && (playerY <= enemies[i].y + enemy.height && playerY + player.height >= enemies[i].y)) {
      pause = 1;
    }
  }
//-------------------------------

  //draw the player
  ctx.drawImage(player, playerX, playerY);

  //draw score
  ctx.fillStyle = "#fff";
  ctx.font = "20px Verdana";
  ctx.fillText("Destroyed ships : " + score + "$", 10, cvs.height - 20);

  function onPause() {
    if (pause >= 1) {
      hit.play();
      ctx.fillStyle = "#df8a62";
      ctx.fillRect(150, 150, 280, 100);

      ctx.fillStyle = "#000";
      ctx.font = "20px Verdana";
      ctx.fillText("You died:", 165, 170);

      document.addEventListener("keydown", reLoad);
    } else if (pause <= 0) {
      requestAnimationFrame(draw);
    }
  }

  onPause();

}

draw();

A: You want to use time intervals instead of listeners.
var myVar = setInterval(timeCycle, 50);
function timeCycle() {
    //all the stuff you currently have listeners for.
}

This way when the time interval happens it will execute your key presses just once.  Then if you want to change your rate of fire you add  something like this:
setInterval(timeCycle, 50);
rateOfFire = 5;
shootCoolDown = 0;
function timeCycle() {
    if (shootPressed === true) {
        if(shootCoolDown === 0){
            shootCoolDown = rateOfFire;
            shoot();
        }
    }
    if (shootCoolDown > 0){
        shootCoolDown --;
    }
}

This way it will shoot once every 5 game cycles (or 4-rounds per second in this case).
There are more fancy things you can do to create a delta-time system to offset lag by changing your sim rate based on the time it takes your timeCycle to execute, but that tends to be much more complex and easy to mess up, so I would not suggest going down that rabbit hole for beginners.
[EDIT]
So, I've seen several questions recently about deltaTime, but don't see any good examples of how to implement it; so, here is a basic example I threw together.  To implement it, just replace the GAME STUFF part with your actual code of what happens in a game cycle, and run all of your time-based values through the delta() function, and it will convert your values from to units per second to units per currentFrame.
My game us under a load of <input type="text" id="lag" value="100000000"> operations per frame.

My speed is = <input type="text" id="speed" value="500"> px per second

I moved px this frame.

FPS:

A: The call to requestAnimationFrame will run the draw function only at a rate supported by the monitor and only if the computer is fast enough. If the code is running slow, it will automatically skip a call to the draw function every now and then. Therefore, the draw function should only contain the rendering code and no logic.
You should first put any code that updates the game's state into another function called update. This function will be called at a consistent-ish rate using setInterval:
function update() {
    // read inputs
    // move objects
    // detect collisions
    // etc.

    // render a new frame only if the browser is done drawing the previous one
    requestAnimationFrame(draw);
}

// run the update function 60 times per second
var updateInterval = setInterval(update, 1000 / 60);

It's always good to store the updateInterval so that we can stop the game from running completely with clearInterval(updateInterval), but you might never need to use it.
Now that you have a somewhat consistent game speed, you can set a cooldown on the shooting like this:
if (fireCooldown > 0) {
  fireCooldown -= 1;
}

if (/* holding the fire key */ && fireCooldown === 0) {
  // create a projectile in front of the player ship
  fireCooldown = 30;
}

You'll need to declare that variable somewhere first with var fireCooldown = 0; somewhere, but it should get you started.
As mentioned by Jake Holzinger in the comments, setInterval isn't 100% accurate and the update function might be called a few milliseconds later than expected. You'd have to check the time between two calls yourself using Date objects or other means if you wanted to time stuff perfectly, but I doubt this is necessary for a simple shooter game.


text:
Q: How to run lynx Automate Browsing Actions in background I am trying to extract some contents from one of my website for my report works.
I am unable to continue session in lynx.
So I am using an automate browser action script to login and print the page to a file and I am using that file to get my report.
But whenever, I run the script, it shows the browser actions in foreground. I dont want this and I would like to mute. i.e I dont want to see the browser action.
I am using the following method to run automate script.
lynx -cmd_log=/tmp/newscript http://example.com

Script:
#!/bin/bash

lynx -cmd_script=/tmp/newscript http://example.com

A: I Found out the answer for this question.
We can modify the line to the given below line to make it silent.
lynx -cmd_script=/tmp/newscript http://example.com > /dev/null
Thank you all.


text:
Q: Unable to get results when passing a string via parameter substitution in gql query I am able to properly pass a string variable to the gqlquery through parameter substitution, here's the code i've tried to use;
user_name = self.request.get('username') #retrieved from UI
p = models.UserDetails.all().filter('user_name = ', user_name).fetch(1)

I don't get any results and the query fails silently. But when I hard code the query like this ,
p = models.UserDetails.all().filter('user_name = ', "peter rice").fetch(1)

I get my expected resultset. I think I am passing the variable user_name in a wrong way, Please help me in getting my piece of code right.

A: Have you tried filter('user_name = ', str(user_name)) ?
I supose you are sure user_name has the expected content.

A: I think I've got it, I tried using this,
p = models.UserDetails.gql('WHERE user_name = :uname', uname = user_name).fetch(1)

and I got the expected resultset. I wonder why other formats have the problem in string substitution.

A: Try logging repr(user_name) to verify that the string is exactly the same as what you're expecting (and that it's not unicode rather than raw). Also try logging the expression user_name == "peter rice". Other than that, I can't see any reason why it would not work - there's literally no way the API can affect this, since it doesn't know where the argument you pass in comes from.


text:
Q: jQuery slideToggle function run only on relevant element I want to run jQuery slideToggle function only on concrete menu element that placed near to any clicked menu-title element.

Menu 1

           1

           2

           3

Menu 2

            1

            2

            3

$('.menu-title').click(function(){
  $('.menu').slideToggle();
});

The issue is when click on one of the title it's working on all ul elements together.
Can you please guide me how to make it work on each ul separate?

A: use siblings method
$(this).siblings('.menu').slideToggle();
note: your html has error, you forgot to close menu class in html -it should be class="menu"-, also your is css wrong, it should be .dropdown .menu  not .dropdown-menu.
code: https://codepen.io/peker-ercan/pen/MPvgYp

A: use siblings function of jQuery
$(this).siblings('.menu').slideToggle();

A: $('.menu-title').click(function(){
  $('.menu').slideToggle();
});
$('.menu').mouseover(function(){
  $('.menu-item').slideToggle();
});

A:     $('.menu-title').click(function(){
       $(this).siblings('.menu').slideToggle();
    })


text:
Q: Npm isn't getting automatically installed on installing node.js While hosting my webapp on heroku I got a message of some bugs in my npm package, my npm package was of version 3 and node.js was of version 8, I wrote thinking that I can update my npm version I tried to update it but the version remained same so I decided to uninstall it and wrote the command "npm uninstall " and than again tried to install npm but in vain ,finally I uninstalled my node.js and reinstalled tha npm will automatically get installed with it, but this too didn't work now I have node of version 10 with no npm which I got to know by checking version of npm which gave me message of "command not found ", now my every try to install npm has failed , may anyone suggest me what I can do to restore my losses and resume my work.

A: I am not sure if you have Linux or Windows. First I would check if the npm folder is in path.
You can follow one of these two to add to path if it is not done yet.

*

*Windows

*Linux
Alternatively you can install node with node version manager (nvm):

*

*nvm linux and mac

*nvm windows


text:
Q: Convergent alternating series problem Find the constant $~c~$  such that                                                          $$4c-4c^2+4c^3-4c^4+...=1 $$
So I took $~4c~$ as a common multiple and got
$$4c(1-c+c^2-c^3+...)=1~. $$
And now:
$$\sum_{k =0}^{\infty}(-1)^k c^k=1/4c$$
But then i didnt know what to do to find c.
P.s. Sorry iam bad with commands

A: You want to have $$ c-c^2+c^3-...=1/4$$
$$\frac {c}{1+c}= 1/4$$
Solve for $c$ and you get $c=1/3$


text:
Q: Creating pages for individual products in Django I have a "Category", "Subcategory" and "Product" model. Rather than having a view for each category, subcategory and product I want to href to templates that will be filled with the righ models.
models.py
class Category(models.Model):
    category_title = models.CharField(max_length=200)
    category_image = models.ImageField(upload_to="category")
    category_description = models.TextField()
    category_slug = models.SlugField(max_length=200, default=1)

    class Meta:
        verbose_name_plural = "Categories"

    def __str__(self):
        return self.category_title

class Subcategory(models.Model):
    subcategory_title = models.CharField(max_length=200)
    subcategory_image = models.ImageField()
    subcategory_category = models.ForeignKey(
        Category, default=1, verbose_name="Category", on_delete=models.SET_DEFAULT)

    class Meta:
        verbose_name_plural = "Subcategories"

    def __str__(self):
        return self.subcategory_title

class Product(models.Model):
    product_title = models.CharField(max_length=200)
    product_image = models.ImageField()
    product_base_price = models.DecimalField(max_digits=12, decimal_places=2)
    product_addons = models.CharField(max_length=200, blank=True)
    product_description = models.TextField()
    product_date_added = models.DateTimeField(default=datetime.now, blank=True)
    product_slug = models.SlugField(max_length=200, default=1)
    product_subcategory = models.ForeignKey(
    Subcategory, default=1, verbose_name="Subcategories", on_delete=models.SET_DEFAULT)
    product_available = models.BooleanField(default=True)

A: To list all products with a link to a specific product
Here is a sample view, url & template for Product model. Please replace myapp with you app's name.
Define a view:
# views.py
from django.views.generic import ListView
from django.shortcuts import render
from .models import Product

class ProductList(ListView):
    model = Product

def productdetail(request,id):
    product = Product.objects.get(id = id)
    return render(request, 'myapp/product.html', {'product': product})

Finally hook that view into your urls:
# urls.py
from django.urls import path
from myapp.views import ProductList, productdetail

urlpatterns = [
    path('products/', ProductList.as_view()),
    path('products/<int:pk>/', productdetail, name='productdetail'),
]

create a template to list products at: /path/to/project/myapp/templates/myapp/products_list.html
{% extends "base.html" %}

{% block content %}

Products

        {% for product in object_list %}

{{ product.product_title }}

        {% endfor %}

{% endblock %}

create a template to show a specific product: /path/to/project/myapp/templates/myapp/product.html::
{% extends "base.html" %}

{% block content %}

Product

    {{product.product_title}}
{% endblock %}

A:     product_created_on = models.DateTimeField(auto_now_add=True)

I have the answer, just use DateTimeField()

A: You used:
product = Product.objects.get(id = id)

change it to :
product = Product.objects.get(id = pk)


text:
Q: Spring post request parameter missing for long strings I have a post method in my Spring controller that takes one request parameter called wkt. Here is my method signature:
@RequestMapping(value="/getNumberOfProperties", method=RequestMethod.POST)
public String getEstimateForNumberOfProperties(@RequestParam("wkt") String wkt) {
    //code
}

In my jQuery, I am calling this method like this.
$.post(webroot + "/project/getNumberOfProperties", {wkt : wktGeomFromServer})

This works great. However, I was getting this error for wkt strings that are too long.
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'wkt' is not present
at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:255) ~[spring-web-4.0.2.RELEASE.jar:4.0.2.RELEASE]
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:95) ~[spring-web-4.0.2.RELEASE.jar:4.0.2.RELEASE]
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:79) ~[spring-web-4.0.2.RELEASE.jar:4.0.2.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:157) ~[spring-web-4.0.2.RELEASE.jar:4.0.2.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:124) ~[spring-web-4.0.2.RELEASE.jar:4.0.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-4.0.2.RELEASE.jar:4.0.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749) ~[spring-webmvc-4.0.2.RELEASE.jar:4.0.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690) ~[spring-webmvc-4.0.2.RELEASE.jar:4.0.2.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) ~[spring-webmvc-4.0.2.RELEASE.jar:4.0.2.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945) [spring-webmvc-4.0.2.RELEASE.jar:4.0.2.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876) [spring-webmvc-4.0.2.RELEASE.jar:4.0.2.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) [spring-webmvc-4.0.2.RELEASE.jar:4.0.2.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863) [spring-webmvc-4.0.2.RELEASE.jar:4.0.2.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647) [servlet-api.jar:?]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) [spring-webmvc-4.0.2.RELEASE.jar:4.0.2.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) [servlet-api.jar:?]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) [catalina.jar:7.0.41]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.41]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-3.2.1.RELEASE.jar:3.2.1.RELEASE]

So how long is too long? After doing some testing, I have discovered that if the length of the string is 1,971,324 or less everything works. Otherwise, I get the above exception. I don't know if this is something with Spring, or tomcat, etc. Also, I have verified with Chrome that wkt parameter is getting sent in all cases, regardless of length. So the Spring error message when it is too long does not make much sense to me. Is 1,971,324 some magic number somewhere?
Any suggestions?

A: Could it be server configuration issue? For example Tomcat has 2MB maximum post request content size by default.


text:
Q: How can I get the serial number of my cameras in C++? I would like to get the serial number of my cameras in C++ (probably using OpenCV library). In fact, I should synchronize two cameras. To do so, I need a way to get the serial number of cameras to see if it is the right one or the left one.
I would be most grateful if someone can give me some advice about that.


text:
Q: How to verify 'Open xdg-open popup' in Chrome via Selenium Webdriver? I am writing a testcase where if a certain link is clicked a "Open xdg-open" Popup is triggered in the chrome browser.
I want to verify in my testcase if an "Open xdg-open" Popup actually appears.
I tried to use the following Code block:
boolean check;
try {
     driver.switchTo().alert();
     check = true;
} catch(NoAlertPresentException e) {
   check = false;
}

However the "Open xdg-open" Popup triggers the NoAlertPresentExcpetion even though it appears in the browser.
Do you have any clue how I can verify the "Open xdg-open" Popup?

A: It does not work because it's not a DOM element you can switch to it. This kind of xdg-open alert happens whenever want to handle a protocol defined by user preferences. It could be any of (afp, Tel, disk, file, hcp, ...)
You can use ChromeOptions in order to exclude these kind of schemes
chrome_options.add_experimental_option( "prefs", {'protocol_handler.excluded_schemes.hcp': false})

You should change the protocol above with whatever protocol is on your side or use this code which exclude list of schemes
driver.execute_script("window.confirm = function(msg) { return true; }")

prefs = {"protocol_handler.excluded_schemes":{"afp":True,"data":True,"disk":True,"disks":True,"file":True,"hcp":True,"intent":True, "itms-appss":True, "itms-apps":True,"itms":True,"market":True,"javascript":True,"mailto":True,"ms-help":True,"news":True,"nntp":True,"shell":True,"sip":True,"snews":False,"vbscript":True,"view-source":True,"vnd":{"ms":{"radio":True}}}}

chrome_options.add_experimental_option("prefs",prefs)


text:
Q: Mongoose $unwind returns empty array I have saw similar but nothing solved by problem. Thats why I am posting the question again. This is my mongoose schema
'use strict';

//Importing packages
const Mongoose    = require('mongoose');

//Declaring schema
const Schema = Mongoose.Schema({
    moduleName  : {type: String, unique: true},
    parentModule: {type: Mongoose.Schema.Types.ObjectId, ref: 'module'},
    status      : {type: Number, default: 0},
    sortOrder   : {type: Number, default: 1},
    createdBy   : {type: Mongoose.Schema.Types.ObjectId, ref: 'admin'},
},
{
    timestamps: true
});

//Exporting packages
module.exports = Mongoose.model('module', Schema);

In my collection, parentModule column again referring same collection.
When i am doing aggregate function with $unwind output data was empty. My collection have one-to-one relationship. So that retrieving parent module have to be object rather than array. That's the reason i used $unwind. But its shows empty. When i remove $unwind it shows the data.
Here my code:
const query = ModuleModel
.aggregate([
    {
        $match: {parentModule: {$ne: null}}
    },
    {
        $project: {
            parentModule: {$cond: [{$eq: }]}
        }
    },
    {
        "$lookup": {
            "from": "modules",
            "localField": "parentModule",
            "foreignField": "_id",
            "as":  "parents"
        }
    },
    {
        "$unwind": {
            path: "$parent",
            preserveNullAndEmptyArrays: true
        }
    },
], function(error, data){
    console.log(data);
    if(error)
    {
        console.log(error);
        return response(error);
    }
    else
    {
        console.log("test");
        return response({data: data});
    }
});

When i remove $unwind my output look like this
{
  "data": [
    {
      "_id": "58b509642fb32d1a1436efdd",
      "updatedAt": "2017-02-28T05:23:48.531Z",
      "createdAt": "2017-02-28T05:23:48.531Z",
      "moduleName": "roles1",
      "parentModule": "58b3d64244307f3e2fddd1e1",
      "sortOrder": 1,
      "status": 0,
      "__v": 0,
      "parents": [
        {
          "_id": "58b3d64244307f3e2fddd1e1",
          "updatedAt": "2017-02-27T07:33:22.396Z",
          "createdAt": "2017-02-27T07:33:22.396Z",
          "moduleName": "roles",
          "parentModule": null,
          "sortOrder": 1,
          "status": 0,
          "__v": 0
        }
      ]
    }
  ]
}

Here my parents column shows as an array, I have seen this link. They change the array of objects into object using $unwind. But i didn't get the output same way. Some the parentModule can be null on the collection.
If anyone know about this help me.


text:
Q: how to read value from awk command? I have result file where I need to read the value of "rx cells " the report file is as given as below:
Content of test.log file is as follows:
    co_result=test.log

    ZyXEL IES-1000> statistics port 12 0 33
    [adsl channel 12-0/33]
    tx packets: 56
    rx packets: 60
    tx rate   : 0
    rx rate   : 0
    tx cells  : 468
    rx cells  : 1707
    errors    : 0
    ZyXEL IES-1000>

I am using the following command to read the rx cells value:
    cells=$(grep -e 'cells' $co_result | cut -d: -f2 | awk '{print $1}'| awk 'NR%2{printf $0"";next;}1')
    echo "Var_value: $cells"

but when I tried to run the above 2 commands in a file. I am getting following output , where the first few characters in echo is not displaying:
       1707value: 530

I am expecting only 1707 in $cells variable but it prints wrongly. I am not understanding the issue . Could you please help to fix it.

A: Your command substitution is unnecessarily complex.
Instead:
cells=$( awk '/rx cells/ { print $NF }' <"$co_result" )
printf 'Var_value: %s\n' "$cells"

$NF will be the last whitespace-delimited field on the line, and this is printed if the line contains the string rx cells.
Also make sure that the input file is a Unix text file and not a DOS text file.  Run dos2unix on the file to convert it to a Unix text file.

Looking at your command:
grep -e 'cells' $co_result | cut -d: -f2 | awk '{print $1}'| awk 'NR%2{printf $0"";next;}1'

First: grep -e 'cells' $co_result would fail if $co_result contained a space or tab or newline, or any other special character (since it's unquoted).
The command outputs
tx cells  : 468
rx cells  : 1707

Then: cut -d: -f2.  This outputs
 468
 1707

Then: awk '{print $1}'. This outputs the same as above, but with the initial spaces removed
Then: awk  'NR%2{printf $0"";next;}1'. This is an obfuscated way of doing paste -d' ' - - and outputs
468 1707

The echo later will output
Var_value: 468 1707

The reason you don't get that is that your input file is a DOS text file and contains carriage returns at the end of each line.  Therefore, the cursor jumps back to the start of the line after printing 468.
Use dos2unix on you input file.
Where you get 530 from, I don't know.

A: You could simply use grep:
 cells=$(grep -F "rx cells" "$co_result" | grep -oE "[0-9]+")

this would extract the number into your variable by:
grep -F "rx cells" $co_result: this is extracting the line that contains rx cells  : 1707
grep -oE "[0-9]+": only output the match of the regexp that matchs only number: 1707
You could also use the more elequant sed group substitution to extract the value like this:
cells=$(sed  -r -n 's/rx cells.*\W([0-9]+)/\1/p' "$co_result")

*

*-r: enable extended regex

*-n: only print explicit line

*'s///p': s for substitute, p to explicitly print the line that match the pattern.

*rx cells.*\W([0-9]+) match rx cells .*\W matches any character until a Non-word character and ([0-9]+) capture in group one or more digits.

*\1 replace output by group one which contains n captured digits.