text:
Q: Configuring an app that calculates the product of a series of doubles I am trying to configure an app that calculates the product of a series of doubles that are passed to the method calcProduct. calcProduct will have a variable length arguements and should return the product that is calculated. This is supposed to then be printed with the array's identification.
Here is my code so far:
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class variableLength {
public static double calProduct(double... numbers)
{
    double total = 0.0;

    for (double number : numbers)
        total += number;

    return total / numbers.length;
}

public static void main(String[] args)
{

    NumberFormat myFormat = NumberFormat.getInstance();
    myFormat.setGroupingUsed(true);

    DecimalFormat decimalFormat = new DecimalFormat("#.###");
    decimalFormat.setGroupingUsed(true);
    decimalFormat.setGroupingSize(3);

    double[] array1 = {2.1, 3.2, 4.3};
    double[] array2 = {1, 2, 3, 4, 5};
    double[] array3 = {2.0, 110.12345};
    double[] array4 = {10.0, 12, 13.1, 4, 5.2, 6, 7.3, 8, 9.4, 100};
    double[] array5 = { };

    System.out.println(myFormat.format(array1));
    System.out.println(myFormat.format(array2));
    System.out.println(myFormat.format(array3));
    System.out.println(myFormat.format(array4));
    System.out.println(myFormat.format(array5));

    System.out.println(decimalFormat.format(array1));
    System.out.println(decimalFormat.format(array2));
    System.out.println(decimalFormat.format(array3));
    System.out.println(decimalFormat.format(array4));
    System.out.println(decimalFormat.format(array5));

   System.out.printf("array1 = %.1f\narray2 = %.1f\narray3 = %.1f\narray4 = %.1f\narray5 = %.1f\n\n", array1, array2, array3, array4);

    System.out.println("The average of array1 and array2 is \n" + calProduct(array1, array2));
    System.out.println("The average of array1, array2, and array3 is \n" + calProduct(array1, array2, array3));
    System.out.println("The average of array1, array2, and array3, array4 is \n" + calProduct(array1, array2, array3, array4));
    System.out.println("The average of array1, array2, array3, array4 and array5 is \n" + calProduct(array1, array2, array3, array4, array5));
}

}
I keep getting this error:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    The method calProduct(double...) in the type variableLength is not applicable for the arguments (double[], double[])
    The method calProduct(double...) in the type variableLength is not applicable for the arguments (double[], double[], double[])
    The method calProduct(double...) in the type variableLength is not applicable for the arguments (double[], double[], double[], double[])
    The method calProduct(double...) in the type variableLength is not applicable for the arguments (double[], double[], double[], double[], double[])
at variableLength.main(variableLength.java:52)

What am I doing wrong? How can I achieve a working program?
Thank you in advance!

A: Your error is saying that what you are giving to the function calProduct is not what you declared in the function.
public static double calProduct(double[] numbers)

This way you tell java you will give an array which contains doubles.
Also, it says that you only specified one parameter. This means that java doesn't expect you to hand in multiple arrays.
public static double calProduct(double[] numbers, double[] number 2)

I hope you get the idea. You can also include an array in another array, then you only have to pass one array.
Functions in java Array in java

A: The issue is that your calProduct function is written to take a series of doubles, but when you actually called the function, your pass it a series of arrays of doubles.  Since those types are not compatible, you get the compilation error you described.
If you wanted to edit the calProduct function to take a series of arrays of doubles, you would also want to use two for loops, one to loop through the series of arrays, and one to loop through the numbers in each array.  You would also need to track the count of the how many doubles you have, since it looks like you are actually calculating an average, not just the product.
For example, the rewritten calProduct function might looks like this:
public static double calProduct(double[]... numberArrays) {
    double total = 0.0;
    int count = 0;

    for (double[] numbers : numberArrays) {
        for (double number : numbers) {
            total += number;
            count++;
        }
    }

    return total / count;
}


text: Q: Configuring rsnapshot to backup multiple computers - individual exclusion rules I've got rsnapshot set up to backup two computers on my local network, as well as the server it's running on. How do I specify individual exclude sets for each backup? As it stands, I have individual cronjobs for each computer, each with its own rsnapshot.conf file. This would be fine, but I get three additional copies of hourly.* in my backup, which indicates that there is some redundancy going on in my setup. Do I have to write backup scripts for each one and have the excludes in there instead of in the main .conf file?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use enable_if for class member function with sperate definition I'm trying to implement a template binary tree class (for learning).
I have the following definition:
template <typename T>
class binary_tree final
{
...
public:
template <typename TParam,
          typename = enable_if_t<std::is_constructible<T, remove_reference_t<TParam>>::value>>
    void insert(TParam &&data);

};

And I'm trying to add the implementation for insert at the bottom of the header file:
template<typename T>
template <typename TParam,
          typename = enable_if_t<std::is_constructible<T, remove_reference_t<TParam>>::value>>
void binary_tree<T>::insert(TParam &&data)
{
    binary_tree_ptr &insert_location = data > _data ? _right : _left;
    if (!insert_location)
        insert_location = binary_tree_ptr(new binary_tree(std::forward<TParam>(data)));
    else
        insert_location->insert(std::forward<TParam>(data));
}

This won't compile, with the following error, pointing to the implementation:
cannot add a default template argument to the definition of a member of a class template

If I remove the typename = ... from the implementation, I get the following error:
out-of-line definition of 'insert' does not match any declaration in 'binary_tree<T>'

Removing the typename = ... from the declaration doesn't yield anything better.
What am I missing? Is there A way to do that?
I'm compiling using clang 6.


text:
Q: SQL Server - loop through temp table and calculate multiple values to insert rows into second table I have a temp table, #TEMP1, which pulls back the next treatment date for a patients and the total number of planned treatments in a given date range.  Within the temp table is a value which gives me the minimum number of days between each treatment.
What I need to do is take the next treatment date, determine how many planned treatments there are after the next treatment date and populate a second temp table, #TEMP2, with the planned dates.
For example, in #TEMP1, contains the following data:
patient    next_tx_dt  planned_tx_cnt   min_days_bt   start_range  end_range
PATIENT_1  2/15/2015   4                28            2/1/2015     6/1/2015
PATIENT_2  2/05/2015   9                12            2/1/2015     6/1/2015
PATIENT_3  5/17/2015   1                112           2/1/2015     6/1/2015

I would like to loop through #TEMP1 and for each row, calculate the dates of planned treatment.  So one row could be looped through once (PATIENT_3) or nine times (PATIENT_2) and each loop results in a new row in #TEMP2.
PATIENT_1 would have the following results in #TEMP2 after a successful loop:
pat_id      planned_tx_dt   planned_tx_cnt
PATIENT_1   2/15/2015       1
PATIENT_1   3/15/2015       2
PATIENT_1   4/12/2015       3
PATIENT_1   5/10/2015       4

PATIENT_2 would have 9 rows and PATIENT_3 would only have 1 row in #TEMP2.
Is it possible to do this in SQL Server 2008?  I have done very basic loops before using a row count but this technically isn't looping through a table so I'm not sure how to get this started or if it is even possible (I do not have a whole lot of experience writing advanced SQL code).

A: Make sure you read the link I posted. Meanwhile here is a functional example using the information you posted. I actually have that cteTally as a view in my system so I don't have to ever recreate it. You can adjust the cte portion as needed to ensure you have enough rows.
if OBJECT_ID('tempdb..#temp1') is not null
    drop table #temp1

create table #temp1
(
    patient varchar(50)
    , next_tx_dt date
    , planned_tx_cnt int
    , min_days_bt int
    , start_range date
    , end_range date
)

insert #temp1
select 'PATIENT_1', '2/15/2015', '4', '28', '2/1/2015', '6/1/2015' union all
select 'PATIENT_2', '2/05/2015', '9', '12', '2/1/2015', '6/1/2015' union all
select 'PATIENT_3', '5/17/2015', '1', '112', '2/1/2015', '6/1/2015';

WITH
    E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
    E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
    E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
    cteTally(N) AS
    (
        SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
    )

select *, DATEADD(DAY, (N - 1) * min_days_bt, next_tx_dt)
from #temp1 t1
join cteTally t on t.N <= t1.planned_tx_cnt
--where t1.patient = 'PATIENT_1'


text:
Q: play sound while button is pressed -android i have this code
package com.tct.soundTouch;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;

public class main extends Activity implements OnTouchListener {

    private MediaPlayer mp;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final Button zero = (Button) this.findViewById(R.id.button);
        zero.setOnTouchListener(this);

        mp = MediaPlayer.create(this, R.raw.sound);

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {

        case MotionEvent.ACTION_DOWN:
            mp.setLooping(true);
            mp.start();

        case MotionEvent.ACTION_UP:
            mp.pause();
        }

        return true;
    }

}

and it works but not as i expected. The sound plays but only for each time that i press the button. My idea is. While i press the button the sound plays, when i  stop the action (finger out of the button) music pause.
Any idea please?
thanks

A: This should work (there was something wrong with your switch-cases I think):
@Override
public boolean onTouch(View v, MotionEvent event)
{

    switch (event.getAction())
    {

    case MotionEvent.ACTION_DOWN:
    {
        mediaPlayer.setLooping(true);
        mediaPlayer.start();
    }

    break;
    case MotionEvent.ACTION_UP:
    {
        mediaPlayer.pause();
    }
    break;
}

return true;
}

A: public class MainActivity extends AppCompatActivity {

    Button button;
    MediaPlayer player;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );

        button = findViewById( R.id.Click );

        button.setOnTouchListener( new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getAction()== MotionEvent.ACTION_DOWN) {
                    player= MediaPlayer.create( MainActivity.this,R.raw.horn );

                    player.start();
                }
                else if(event.getAction()==MotionEvent.ACTION_UP){
                    player.stop();
                    player.release();
                }
                return true;

            }
        } );

    }

}


text:
Q: Schedule subroutines in perl I'm parsing a log file, and I'm required to produce JSON file with results for every 1 second, 5, 5 min, 15, 30, 1 hour ..etc
I'm confused about the concept here, it is possible to write one big infinite while loop that include number of subroutines each will perform its parsing based on different time interval.
Here is I have so far, not sure if this is the right approach
#!/usr/bin/perl

use strict;
use warnings;

$ | = 1; # Ensure output appears

my $interval = 1;
my @command = "echo processing ...";

my $count = 0;

while (1) {
    `since access.log | json_convert.pl

    sleep $interval - time % $interval;
    system @command;
}

A: Repeated sleep calls will drift rapidly because they don't take into account the time spent creating the JSON data. I would also be very wary of using system calls to do the data manipulation as it is bound to slow things down, and you may well overrun the one-second response time that you are looking for. Do it all within Perl instead
I recommend you look at the excellent EV module. The periodic event type is what you need
Here's a very short example. Your own callback subroutine should examine the time at which it is called to determine what to do, according to whether it is a multiple of 5 seconds, 60 seconds etc. Alternatively you could set up multiple event loops, one for each interval. The module makes it very straighforward
use strict;
use warnings 'all';
use feature 'say';

use EV;
use Time::Piece 'localtime';

STDOUT->autoflush;

my $one_second = EV::periodic 1, 1, 0, \&callback;

sub callback {
  say "Periodic event at ", localtime(EV::now)->hms;
};

EV::run;

output
Periodic event at 10:27:36
Periodic event at 10:27:37
Periodic event at 10:27:38
Periodic event at 10:27:39
Periodic event at 10:27:40

etc.


text:
Q: Page navigation in ICEFaces I recently started working on JSF in ICEFaces FrameWork(Server # Glassfish).
I have one question.
In my first JSF page i have radio buttons, If i to select  and click on next page, I have to publish those selected values in my second page. If i click on back button , i have to show the selected values in my first page.
How can i achieve this? Please suggest
My First Page(suites.xhtml).
  <?xml version='1.0' encoding='UTF-8' ?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<ui:composition template="/WEB-INF/templates/template.xhtml">
<ui:param name="title" value="Eclipse Template Test Page" />
<ui:param name="companyName" value="Autoexetc" />
<ui:define name="menuItems">
    <ace:menuItem value="Dashboard" url="/dashboard.jsf" icon="ui-icon ui-icon-home"
        styleClass="menuBarItem" />
    <ace:menuItem value="Suites" url="/suites.jsf" styleClass="menuBarItem" />
    <ace:menuItem value="Status" url="/status.jsf" styleClass="menuBarItem" />
    <ace:menuItem value="Report" url="#" styleClass="menuBarItem" />
    <ace:menuItem value="Terminal" url="#" styleClass="menuBarItem" />
</ui:define>

<ui:define name="tabItems">
 Your in Suites Page <h:commandButton value="Back To DashBoard" action="dashboard" />

  1. Hard-coded with "f:selectItem" :
    <h:selectOneRadio value="#{user.favColor1}">
        <f:selectItem itemValue="Red" itemLabel="Color1 - Red" />
        <f:selectItem itemValue="Green" itemLabel="Color1 - Green" />
        <f:selectItem itemValue="Blue" itemLabel="Color1 - Blue" />
    </h:selectOneRadio>

        2. Generated by Map :
    <h:selectOneRadio value="#{user.favColor2}">
        <f:selectItems value="#{user.favColor2Value}" />
    </h:selectOneRadio>

         3. Generated by Object array and iterate with var :
    <h:selectOneRadio value="#{user.favColor3}">
        <f:selectItems value="#{user.favColor3Value}" var="c"
        itemLabel="#{c.colorLabel}" itemValue="#{c.colorValue}" />
    </h:selectOneRadio>

            <h:commandButton value="Submit" action="status" />
    <h:commandButton value="Reset" type="reset" />
</ui:define>

</ui:composition>

And My Result Page (status.Xhtml), which gives my selected values.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<ui:composition template="/WEB-INF/templates/template.xhtml">
<ui:param name="title" value="Eclipse Template Test Page" />
<ui:param name="companyName" value="Autoexetc" />
<ui:define name="menuItems">
    <ace:menuItem value="Dashboard" url="/dashboard.jsf" icon="ui-icon ui-icon-home"
        styleClass="menuBarItem" />
    <ace:menuItem value="Suites" url="/suites.jsf" styleClass="menuBarItem" />
    <ace:menuItem value="Status" url="/status.jsf" styleClass="menuBarItem" />
    <ace:menuItem value="Report" url="#" styleClass="menuBarItem" />
    <ace:menuItem value="Terminal" url="#" styleClass="menuBarItem" />
</ui:define>

<ui:define name="tabItems">
 Your in status Page <h:commandButton value="Back To suites" action="suites" />

user.favColor1 : #{user.favColor1}

user.favColor2 : #{user.favColor2}

user.favColor3 : #{user.favColor3}

</ui:define>

When i click on back button from my result page,  first page will display with selected values, if i re-select any values and submit it, cant able to navigate to my result page.


text:
Q: function that returns an array with all the numbers from 1 to 255 can you help me with this code? I'm new here, I'm still lost how to write code here.
    function get_array(){
    var arr [];
`enter code here`
return arr[];

}

A: const arr = new Array(255).fill(0).map((el, i) => i + 1);


text:
Q: Unity Canvas does not fill screen I have a 2D game set to 1080p pixel size (so each unit equals 1 pixel) and I have added a canvas to my scene. However the canvas fills only about 1/8th of the screen and is also not central either. All the canvas size and position settings are locked so I cant move it or resize it. The canvas itself does reflect the screen (ie if I put text in the top right corner it appears correctly) but the size makes it hard to judge where best to position the elements).
How do I get the canvas to fill my scene?

A: On your canvas, set the Canvas Scaler component's Ui Scale Mode to Scale with Screen Size. Then you can define a Reference Resolution of 1080p, i.e. 1920 x 1080.
EDIT: To see the canvas fit into the camera's size in the scene, change the Canvas component's Render Mode to Screen Space - Camera, and drag the camera from the hierarchy to it.

(check this video)


text:
Q: Is there a reason to why 2 objects with the same parameters are having different behaviours? Basically, I'm new to programming (and to stackoverflow) and trying to learn the basics on p5.js.
I'm one of the guys trying Pong out and diving in how to create different levels of difficulty I discovered that 2 balls who supposedly should have the same radius actually don't (fact that messes up my hitboxes) and using the same constant to change the Y axis'speed results in 2 completely different Y speeds. I'm almost sure I know where the problem is, but I have zero clue on why it happens, in any case I will leave a link for the full thing here.
I made a second ball to make the opponent's paddle follow it's path and I'm pretty sure the problem is either in getting the ball's y position or in how I use it after that, since when I comment those out the thing works how I would like it to.
class Ball {
   constructor(_x, _y, _radius, _xSpeed, _ySpeed, _color){
      this.x = _x;
      this.y = _y;
      this.radius = _radius;
      this.xSpeed = _xSpeed;
      this.ySpeed = _ySpeed;
      this.color = _color;
   }

   //this guy is one of my suspects
   get ballY() {
      return this.y += this.ySpeed;
   }

   show() {
      fill(this.color)
      circle(this.x, this.y, 2 * this.radius);
      fill(255)
   }
   moveY() {
      this.y += this.ySpeed;
   }

//leaving it here for context
class Paddle {
  constructor(_x, _y, _length, _height, _tag) {
    this.x = _x
    this.y = _y
    this.length = _length
    this.height = _height
    this.tag = _tag
  }

  //with this guy also in the list
  get opSpeed() {
    return ball2.ballY - this.y - 45;
  }

  //or maybe here
   move() {
      if(this.tag == "opponent") {
      this.y += this.opSpeed;
     }
   }

I would appreciate anyone who could give some light in the matter, thanks.


text:
Q: Abelian ideal of 8-dimensional nilpotent Lie algebra
Let $$L : [x_1, x_2] = [x_3, x_4] = x_6, [x_1, x_5] = [x_2, x_3] = x_7, [x_1, x_7] = [x_2, x_4] = [x_4, x_5] = [x_6, x_3] = x_8$$ be a nilpotent Lie algebra of dimension $8$. Does  have an abelian ideal? I guess this Lie algebra has no abelian ideal of dimension 5 but I can' t show it.

A: The subspace of basis $(x_2,x_5,x_6,x_7,x_8)$ is clearly an ideal (since it contains the derived subalgebra). Moreover it's abelian (since all the given nonzero brackets involve one of $x_1,x_3,x_4$).


text:
Q: I don't understand Angular data binding at all I've spent several hours trying minor variations of this code, and I don't understand why one works and the other doesn't.
Here's the scenario: I'm trying to present a list of registered users (which I'm getting with a simple database query that returns just a few columns), then when one user's name is clicked on, I'll retrieve more information about that user from the database, and present it in a different view. At the moment, I'm doing this with regular  elements with an ng-click directive that sets a value called currentid. Elsewhere in my code, I use $watch() to send out a new database query whenever currentid changes. That part seems to be working (I see the console.log() output from my watch callback, and the database query is spitting out the right data)... but sometimes currentid changes, and sometimes it doesn't, and I cannot figure out why.

*

*A jsfiddle where it doesn't work: http://jsfiddle.net/aLcRL/11/

*A jsfiddle where it DOES work: http://jsfiddle.net/aLcRL/12/
(Click on the "rmunn" and "admin" links in the table: the "Currrent ID" value below should update. And please pardon the almost total lack of CSS; I'm a coder, not a graphics designer ("Dammit, Jim!"), and it's also very late in my timezone right now so I have no motivation to pretty this up. It's functional, it demonstrates the problem, and I'm going to leave it at that.)
The only difference between these two is that one is binding to currentid, and the other is binding to vars.currentid. Now, I understand why binding to currentid wouldn't work in the case of a parent and a child scope (the child's value would overshadow the parent's value); since I'm coming from a Python background, this makes sense to me (it's similar to how Python's instance namespaces can shadow the namespaces of anything defined on the class). But in this jsfiddle, I'm only using one controller -- aren't all these variables in the same scope?
I've been beating my head against this all day, and the several Stack Overflow answers I've tried to read (like How does data binding work in AngularJS? for example) have just left me even more confused: $apply() and $digest() and scopes, oh my! So if anyone can give me a nice simple beginner's guide to scopes in Angular (or point me to an already-written one that I've missed), I'd be very grateful.
"I've learned Clojure and Haskell, I can learn a simple Javascript framework," I thought. "This'll be easy." Boy, was I wrong. :-)

A: You are running into an issue where ng-repeat creates a child scope.

    {{user.userName}}
    {{user.email}}

If you need to access the parent scope you can use $parent.currentid
{{user.userName}}

You need to use $apply() whenever you modify a value outside of the angular world.  For example using setTimeout() or a jQuery Plugin.  Calling $apply() alerts Angular to reevaluate the scope to see if anything changed and update accordingly.


text:
Q: React : Grab change on input value done by jQuery Not a fan of mixing jQuery with React but I liked a color picker called Farbstastic so I embedded it as a component in my React app. There is an input field as type hidden where the value gets changed when user interact the with color picker. I want to grab the value in React using onChange event.

This is my react code to grab the change:
class Color extends Component {
    render() {
        return (

                Color:

                <input type="hidden" id="color" name="color" value="#123456"  onChange={event => { console.log(event.target.value);} }/>

        )
    }
}

The problem is it does not grab the change on value by jQuery.

A: You use case is called uncontrolled components in react world.
https://reactjs.org/docs/uncontrolled-components.html
So basically you have to use ref to access value of this input in your react class methods.
      <input type="hidden" id="color" name="color" value="#123456"
        ref={(input) => this.colorCodeInput = input}/>

Now in your submit function you can access the value set like
onSubmit() {
  let colorCode = this.colorCodeInput.value.
}


text:
Q: The request entity cannot be empty
I am new to Jax-RS. I am trying to implement a simple GET method using
  jersey. I am getting the correct output for the Collection resource,
  but I am getting "ERROR 400 Bad Request" for instance resource . I
  am stuck at this point. Everything seems to be correct,but I am
  missing something which I am not able to figure out. I have been
  trying it for last 10 days. Any help will be appreciable. Please find
  my code below.I am using POSTMAN rest client which is throwing
  "Unexpected 'T'" as response and ARC is throwing "The request entity
  cannot be empty." and both are Error 400 bad request.

This is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <display-name>MessangerWithoutMaven</display-name>
    <welcome-file-list>

        <welcome-file>index.jsp</welcome-file>

    </welcome-file-list>

    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.manish.jax_rs.Messanger</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>
</web-app>

This is my MessageResource.java :
package com.manish.jax_rs.Messanger.resources;

import java.util.List;

import javax.websocket.server.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.manish.jax_rs.Messanger.model.Message;
import com.manish.jax_rs.Messanger.service.MessageService;

@Path("/messages")
public class MessageResource {

    MessageService messageService = new MessageService();
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Message> getMessages(){

        return messageService.getAllMessages();
    }

    @GET
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Message getMessage(@PathParam("id") int id){

        return messageService.getMessage(id);
    }

}

This is  DaoClass.java:
package com.manish.jax_rs.Messanger.Dao;

import java.util.HashMap;
import java.util.Map;

import com.manish.jax_rs.Messanger.model.Message;

public class DaoClass {

    private static Map<Integer,Message> messages = new HashMap<Integer,Message>();

    public static Map<Integer, Message> getMessages() {
        return messages;
    }
}

This is MessageService.java:
package com.manish.jax_rs.Messanger.service;

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;

    import com.manish.jax_rs.Messanger.Dao.DaoClass;
    import com.manish.jax_rs.Messanger.model.Message;

    public class MessageService {

        private Map<Integer,Message> messages= DaoClass.getMessages();

        Message m1= new Message(1,"Hello John","John");
        Message m2=  new Message(2,"Hello Mathews","Mathews");
        Message m3= new Message(3,"Hello Albert","Albert");

        public MessageService(){
            messages.put(1,m1);
            messages.put(2,m2);
            messages.put(3, m3);
        }
        public List<Message> getAllMessages(){
            return new ArrayList<Message>(messages.values());
        }
        public Message getMessage(int id){
            return messages.get(id);
        }
    }

This is Message.java:
package com.manish.jax_rs.Messanger.model;

import java.util.Date;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Message {

    private int id;
    private String message;
    //private Date created;
    private String author;

    public Message() {

    }
    public Message(int id, String message, String author) {

        this.id = id;
        this.message = message;
        this.author = author;
        //this.created = new Date();
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }

    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
}

[List of jars][1]

[correct output for collection resource "messages" in Postman rest client][2]

[Incorrect output for instance resource /messages/1][3]enter code here

  [1]: https://i.stack.imgur.com/sWfMl.jpg
  [2]: https://i.stack.imgur.com/y5Nnf.jpg
  [3]: https://i.stack.imgur.com/8CwId.jpg

A: Please check your import of PathParam.
Instead of "javax.websocket.server.PathParam;" use "import javax.ws.rs.PathParam;".
This should work fine.

A: You have imported import javax.websocket.server.PathParam; which should be import javax.ws.rs.PathParam;


text:
Q: Min Height for GridLayout Row set to Auto In a GridLayout, I have set a row to 'auto' because the content size is dynamic.  In particular, I have a pulldown menu in the row.  When it opens, the row correctly grows to the height of the pulldown list that appears.  BUT, when the pulldown is closed, it is merely a button that should have the same height as the other rows.  Unfortunately, the row height is a bit too small and causes the overall layout to look bad.
To fix this, I need to set the minimum height of the 'auto' row.  Is this possible?  Can I set a minimum height for a GridLayout row that is set to 'auto' ???

A: You can not set minimum height for a particular grid row, instead you can set minHeight (min-height with CSS) on the Button you are talking about / simply wrap the Button with a ContentView / StackLayout if you like to keep the Button smaller while giving it more space.


text:
Q: Get context attribute value from console I'm reading with dev. tools console with this code $('#basis > td')[1] this code line: € 11,85
With $('#basis > td')[1].textContent i read the content of 	, also € 11,85.
How can i read the value of context? - i want to get 11.84689, but i can't find anywhere, how to fetch context attribute value...

A: I think you can use:
$(document).find('td')[0].getAttribute('context');

or
$('#basis').find('td')[0].getAttribute('context');

A: JQuery has a function to get the attributes of elements
console.log( $('#basis td:first-child').attr('context') );

A: I changed your question a little bit to illustrate on how you can retrieve multiple context values. I take that you were using > in an attempt to retrieve more values. Please try this:

    € 11,85
    € 12,85
    € 13,85
    € 14,85
    € 15,85


text:
Q: UIBarButtonItem triggers action only when pressed for long enough I have a few simple UIBarButtonsItems(no customization other than changing style, color and alpha). Everything was working perfectly fine for some time. But now I need to press BarButton for a long time(4-5 seconds) before the action is triggered. I just moved toolbar around and changed color and alpha after which this started happening.  I don't exactly understand what caused this change of behavior.
I used interface builder to build the view and assigned action to UIBarButtonItems by Ctrl+Dragging.
I tried looking up a lot both on google and so. Most of the questions are about UIBarButtons not responding at all. Still I tried the solution of cleaning build of project and Xcode cache. But nothing changed.
Could someone help me with this?

A: I realized my mistake. I had two events getting triggered in same space in view. First was to reveal toolbar(i.e. increase its alpha) when tapped in particular area of the view and second one was of course button tap event for UIBarButtonItem. When tapped in that area the first event got triggered and eventually when pressed for long it also fired the second event once the toolbar was visible(if toolbar was invisible before).
Sorry to bother you all.


text:
Q: Output list data in one line the problem is that i cannot output all the data in one line, lettergrade(float(mylist[2])) and even a simple string like "hello" is always on the next line
lettergrade is just a simple function that returns a string
print("Student Name\t\tFinal Grade\t\tLetter Grade")
mylist = indata.split(",")
print(mylist[0] + " " + mylist[1] + "\t\t" + mylist[2] + "\t\t" + lettergrade(float(mylist[2])))

mylist looks like
['Johnson', 'Abby', '95.6\n']
['Smith', 'Frank', '91.3\n']
['Carson', 'Jack', '89.1\n']
['Wells', 'Orson', '87.9\n']

Output I get
Student Name            Final Grade             Letter Grade
Johnson Abby            95.6
                A
Smith Frank             91.3
                A
Carson Jack             89.1
                B

Expected output
Student Name            Final Grade             Letter Grade
Johnson Abby            95.6                    A
Smith Frank             91.3                    A
Carson Jack             89.1                    B

A: You should remove the \n from the list :
['Johnson', 'Abby', '95.6']
['Smith', 'Frank', '91.3']
['Carson', 'Jack', '89.1']
['Wells', 'Orson', '87.9']

A: \n stands for a line break, you should remove it:
mylist = indata.replace('\n', '').split(",")


text:
Q: Popup with simultaneous page redirection in PHP I want a PHP page that triggers a popup on pageload, and then redirects to another (3rd party) page while the popup is in the foreground. Is this possible with PHP (and perhaps plain JavaScript).

A: Of course it is possible. You should make simple pop up with javascript but if you want to load a page beneath it the page should open in iframe ( at least that's the most simple way I can think of )


text:
Q: Data change not reflected when INotifyPropertyChanged is not implemented first see the below code which works fine and when we update entity then change is automatically reflected in grid but the moment i comment this INotifyPropertyChanged and all other code related to notify property change then grid is not getting the change.
so i like to know what kind of role is played by INotifyPropertyChanged ?
how INotifyPropertyChanged communicate with grid to show or reflect the chnage?
please help me to understand the communication between grid and INotifyPropertyChanged . thanks
namespace PatternSearch
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void btnBindData_Click(object sender, EventArgs e)
        {
            BindingList<Car> cars = new BindingList<Car>();

            cars.Add(new Car("Ford", "Mustang", 1967));
            cars.Add(new Car("Shelby AC", "Cobra", 1965));
            cars.Add(new Car("Chevrolet", "Corvette Sting Ray", 1965));

            dataGridView1.DataSource = cars;
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (dataGridView1.DataSource != null)
            {
                BindingList<Car> cars = dataGridView1.DataSource as BindingList<Car>;
                cars.Where(d => d.Make == "Ford").First().Make = "My Ford000";
            }
            else
                MessageBox.Show("Grid has no data");
        }
    }

    public class Car : INotifyPropertyChanged
    {
        private string _make;
        private string _model;
        private int _year;

        public event PropertyChangedEventHandler PropertyChanged;

        public Car(string make, string model, int year)
        {
            _make = make;
            _model = model;
            _year = year;
        }

        public string Make
        {
            get { return _make; }
            set
            {
                _make = value;
                this.NotifyPropertyChanged("Make");
            }
        }

        public string Model
        {
            get { return _model; }
            set
            {
                _model = value;
                this.NotifyPropertyChanged("Model");
            }
        }

        public int Year
        {
            get { return _year; }
            set
            {
                _year = value;
                this.NotifyPropertyChanged("Year");
            }
        }

        private void NotifyPropertyChanged(string name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}

here is the code where i comment INotifyPropertyChanged and all its related code
namespace PatternSearch
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void btnBindData_Click(object sender, EventArgs e)
        {
            BindingList<Car> cars = new BindingList<Car>();

            cars.Add(new Car("Ford", "Mustang", 1967));
            cars.Add(new Car("Shelby AC", "Cobra", 1965));
            cars.Add(new Car("Chevrolet", "Corvette Sting Ray", 1965));

            dataGridView1.DataSource = cars;
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (dataGridView1.DataSource != null)
            {
                BindingList<Car> cars = dataGridView1.DataSource as BindingList<Car>;
                cars.Where(d => d.Make == "Ford").First().Make = "My Ford000";
            }
            else
                MessageBox.Show("Grid has no data");
        }
    }

    public class Car //: INotifyPropertyChanged
    {
        private string _make;
        private string _model;
        private int _year;

        //public event PropertyChangedEventHandler PropertyChanged;

        public Car(string make, string model, int year)
        {
            _make = make;
            _model = model;
            _year = year;
        }

        public string Make
        {
            get { return _make; }
            set
            {
                _make = value;
                //this.NotifyPropertyChanged("Make");
            }
        }

        public string Model
        {
            get { return _model; }
            set
            {
                _model = value;
                //this.NotifyPropertyChanged("Model");
            }
        }

        public int Year
        {
            get { return _year; }
            set
            {
                _year = value;
                //this.NotifyPropertyChanged("Year");
            }
        }

        private void NotifyPropertyChanged(string name)
        {
            //if (PropertyChanged != null)
            //    PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}

A: The grid checks if the object implements INotifyPropertyChanged. If it does, it subscribes to the PropertyChanged event (the only member of the interface) to be notified of the name of the properties that have the value changed.
A better NotifyPropertyChanged implementation would be:
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    var handler = PropertyChanged;
    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}

and a property would look like:
public int Year
{
    get { return _year; }
    set
    {
        _year = value;
        OnPropertyChanged();
    }
}

In this way, the code would be more bug proof to property name refactoring.


text:
Q: Unable to access nodes/tags in JSON response in Python Trying to learn Python finally. Having read all the other questions on the topic I have deducted I am an idiot.
I'm making a Python request to an open API like below
import requests
import json

url = 'http://api.turfgame.com/v4/users'
payload = [{"name": "tbone"}]
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

This all goes well and I can print the response
print r.text

However, it's when I want to access certain tags/nodes in the response that I run into a wall. The output is
[{"country":"se","medals":[34,54,13,5,46,28,16,6],"zones":[323,7577,14606],"pointsPerHour":21,"points":21809,"blocktime":17,"taken":2290,"name":"tbone","totalPoints":347388,"rank":30,"id":95195,"place":1931,"uniqueZonesTaken":269,"region":{"name":"Stockholm","id":141}}]

And I've tried to
rj = r.json()
print rj['name']

But that only gives me
Traceback (most recent call last):
File "post.py", line 16, in <module>
print rj['name']
TypeError: list indices must be integers, not str

I cannot get my head around how to access any individual tags/nodes in the JSON response.

A: The answer you got : [{"country":"se",..."region":{"name":"Stockholm","id":141}}]
is a list of JSON objects (notice the [] surrounding the dictionary).
So, to get your object, you have to do :
rj = r.json()
print rj[0]['name']    # the [0] to indicate you take the first element of your list


text:
Q: Quantum physics notation in statistical physics Studying statistical physics, in particular studying paramagnets and ferromagnets, I found some quantum mechanical formulas that I don't understand how to interpret. I don't understand if they are equations between operators, eigenvalues or mean values (or something else that I don't know). Can anyone tell me how to interpret these quantum equations (i write examples of them below)? To be clear, I am not asking for an explanation of physical phenomena but an explanation of the notation, which to me looks like a mix of eigenvalue operators and expectation values together.
Example about paramagnets
magnetic moment of each single ion
$$\vec \mu=g \mu_B \vec J$$
where g is the Landé g-factor
$$g=1+\frac {j(j+1)+s(s+1)-l(l+1)}{2j(j+1)}$$
It follow that, if there is a magnetic field, the interaction energy is
$$H=-\vec \mu \cdot \vec B=-g \mu_B B m_j$$
where the possible values of $m_j$ are $(-j,-j+1,...0,...,j-1,j)$
Example about ferromagnets
Hamiltonian of the system in the presence of $\vec B$
$$H=-g \mu_B \vec B \cdot \sum \vec S_i - J \sum \vec S_i \cdot \vec S_j $$

A: Note: I equate expectation values below to emphasize which constants can be moved outside bra-kets. To get the operator equations from such these expectation equations follow, just mentally delete the bra-kets. Nothing here contradicts any other users' insights, given which operators are mutually diagonalizable with the Hamiltonian.
In this case it would be more helpful to write${}^\dagger$ $$\left\langle\hat{H}\right\rangle=\left\langle-\hat{\vec{\mu}}\cdot\vec{B}\right\rangle=-\mu_BB\langle gm_j\rangle.$$The first set of angle brackets were likely dropped because an eigenstate of the Hamiltonian is assumed. Why someone woud drop the second set will hopefully become clear from the footnote below.
${}^\dagger$ We probably put $\vec{B}$ in "by hand", making it classical rather than quantized, which is why I didn't give it an operator hat. The second expression can be rewritten can then be rewritten as e.g. $-\left\langle\hat{\vec{\mu}}\right\rangle\cdot\vec{B}$. The resulting empirical law, by which the eigenenergy is a dot product, allows us to identify $\vec{\mu}$ with its mean.
Edit to address new ferromagnet example: this should be clarified as$$\left\langle\hat{H}\right\rangle=-\mu_B\vec{B}\cdot\sum_i\left\langle g\hat{\vec{S}}_i\right\rangle-\sum_{ij}\left\langle\hat{J}\hat{\vec{S}}_i\cdot\hat{\vec{S}}_j\right\rangle.$$


text:
Q: Parse error: trailing Garbage when array has >1 element When I'm sending an update object call to Algolia I'm getting the Parse Error trailing garbage.
This only happens when I send multiple elements in an array. For example, if I send:
"Tags": ["Wood", "Sustainable"] I get the error, but if I send: "Tags": ["Wood"] there is no error.
I'm unsure what this error actually means and don't see a lot of info about it online.
Full JSON Object:
{
   "Product Name": "Test 1",
   "Description": "Folk is a mercurial, but modest family of chair, stool and table designed for Allermuir by PearsonLloyd.\n\nFolk is both timeless in its seemingly familiar design, and timely in its modest and ingenious flexibility.\n\nStandard Features\nBeech ply seat with a clear finish\nBeech ply back with a clear finish\nCast Aluminium frame finished in Off-Black powder coat\nSolid Beech legs with a clear finish\nPlastic glides\nStacks up to 4 high\n\nOptional Features\nCast Aluminium frame available in a selection of powder coat finishes\nBeech ply seat, back and solid Beech legs available in a selection of colour washes or stains\nSolid Beech legs available in a selection of colour washes or stains\nOak ply seat, back and solid Oak legs with a clear finish\nSolid Oak legs available in a selection of colour washes\nPlastic glides with felt ",
   "Manufacturer": "Allermuir",
   "Product Subcategory": ["Side Chairs"],
   "Tag": ["Wood", "Sustainable", "Post-Consumer Recycled Content", "SCS Indoor Air Quality Certified", "BIFMA", "Beech", "Aluminum"],
   "Designer": "PearsonLloyd",
   "Lead Time": 6,
   "Certifications": "BS EN 16139:2013-Level 1\n\nANSI/BIFMA X5.1-2017\n\nIndoor Air Quality Certified to SCS-EC10.3-2014 v4.0",
   "List Price - Min": 600,
   "List Price - Max": 1200,
   "Product Category": ["Seating"],
   "SKU": "FLK101"
};


text:
Q: Where was the Marauder's Map while Harry, Hermione, and Ron were out hunting for Horcruxes? What happened to the Marauder's Map during the 7th book when Harry and friends were out hunting Horcruxes?

A: Harry had it
He packs it shortly before the Wedding, when the Trio are preparing their getaway bags (emphasis mine):

Up in the attic room, Ron examined his Deluminator, and Harry filled Hagrid's mokeskin purse, not with gold, but with those items he most prized, apparently worthless though some of them were: the Marauder's Map, the shard of Sirius's enchanted mirror, and R.A.B.'s locket. He pulled the string tight and slipped the purse around his neck
Harry Potter and the Deathly Hallows, Chapter 7: "The Will of Albus Dumbledore"

And he uses it after Ron storms out of the tent, initially to watch for Ron, but eventually to spy on gaze wistfully at Ginny's dot:

Meanwhile Harry had started bringing out the Marauder's map and examining it by wandlight. He was waiting for the moment when Ron's labeled dot would reappear in the corridors of Hogwarts, proving that he had returned to the comfortable castle, protected by his status of pureblood. However, Ron did not appear on the map and after a while Harry found himself taking it out simply to stare at Ginny's name in the girl's dormitory, wondering whether the intensity with which he gazed at it might break into her sleep, that she would somehow know he was thinking about her, hoping that she was all right.
Harry Potter and the Deathly Hallows, Chapter 16: "Godric's Hollow"


text:
Q: Difference in meaning between did you speak to... and have you spoken to...?
Possible Duplicate:
How do the tenses in English correspond temporally to one another?

What's the difference in meaning between "Did you speak to the landlord this morning?" and "Have you spoken to the landlord this morning?"

A: It has been pointed out in a few grammar books that the present perfective describes a past event with present relevance. Whatever that is and whether there is a difference depends on the context.
From Practical English Usage, Swan, 3rd ed.:

The difference between the present perfect and the simple past is not
  always very clear-cut. It often depends on our 'focus': are we
  thinking mostly about the present relevance of a past event, or about
  the past details? In some cases both present perfect and past are
  possible with little difference of meaning.

A nice explanation of present relevance, from Cruse, 2000:

Consider the difference between the following:
(39)    John read the book.
(40)    John has read the book.
Both indicate that John's reading of the book occurred in the past.
  But the first sentence directs our attention into the past, to the
  specific time when the event occurred; the second sentence, on the
  other hand, directs our attention towards John's present state, or at
  least at aspects of it which are attributable to his having read the
  book at some (indeterminate) time in the past. This is the essence of
  the perfect: present relevance of past events.

A: If it is still this morning, then it needs to be the present perfect:

*

*Have you spoken to the landlord this morning?

because this morning is an expression of unfinished time and implies the possibility that you still might speak to the landlord.
If, on the other hand, it is no longer this morning (it is afternoon or evening of the same day), then it has to be the past simple:

*

*Did you speak to the landlord this morning?

because this morning is now an expression of finished time.


text:
Q: Removing inline CSS affects styles defined in stylesheet I'm facing a strange behavior.
I have a script that applies inline CSS to elements from its stylesheet with computedStyle method.
This is a way to copy rich text instead of plain text.
But after the copy, I need to delete the style="" attribute.
When this happens, some style attributes (like color, disappears) while I can see in the inspector that this attribute is still linked to my element by its class.
See there :
https://jsfiddle.net/sxybrcug/ (color disappears but border-color is okay)
Do you know what's happening ?
Thanks

A: It looks like inline styles are being added to your container div as well, but on the button click, only the inline styles on the <p> elements are removed. So p continues to inherit the inline styles of container, specifically, -webkit-text-fill-color, which is set to black, overriding the color property.
If you add
container.setAttribute("style", "");

to your click listener, it removes all the inline styles and the color of the p elements shows as red.


text: Q: Problem with page numbering (double page numbering) In my thesis only this page has two number i want only bottom roman number like other front pages, but i don't know why the arabic number 8 is appeared in upper right , no any other pages in the thesis has that problem.


text:
Q: Computed Column in Mysql I am trying to add a computeed column.
alter table datatest add column amount2 double  as (amount*rate)

but I got error while executing this

A: MySQL doesn't support computed columns prior to MySQL 5.7.  The more recent versions do now support computed columns.
You can use a view instead:
create view v_datatest as
    select t.*, (amount * rate) as amount2
    from datatest;

Notes:

*

*In databases that do support computed columns, the type is not part of the column definition.  It is derived from the expression (you can use cast()/convert() to convert to a particular type).

*It is a bad idea to store monetary amounts using floating point representations.  You should be using decimal/numeric instead.

*If you don't want to use a view, you can add a column to the table (along with the type) and use a trigger to maintain the value.


text:
Q: scraping dynamic webpages with nodesJs I am trying to scrape a website using nodeJs. I am fairly new to web scraping and I am more experienced in javascript. The problem I had is that websites that use dynamic contents likeiframes and ajax calls need to be opened in a browser like environment to load the dynamic content.
how do I proceed to be able to load the dynamic content and get the data it provides using Javascript ?


text:
Q: Jasmine/Angular: Cannot read property 'patchValue' of undefined (component testing) In my unit test, I am testing to see if my service is being called.  I have a function called loadUser(). This function uses a service getData, to retrive all of the users from a url. Then, it loads the userID and that specific user's information (name, lastname, etc) into a form. From here, the user is allowed to edit their credentials. This function uses patchValue to display the data to the correct form field. Now I am only trying to test if my service, getData is called and that is it. When running my test, I receive this error:  TypeError: Cannot read property 'patchValue' of undefined. I would like for my test to say that getData has been called. Here is my test, and below that my function (for brevity, I only posted necessary code). I posted my setup because maybe I am missing something there?
Spec:
    fdescribe('User Component', () => {
    let httpService: HttpService;
    let userComponent: UserComponent
    let fixture: ComponentFixture<UserComponent>
    let debugElement: DebugElement;

beforeEach(async() => {
    TestBed.configureTestingModule({
      declarations: [
        UserComponent,
      ],
      imports: [HttpModule, FormsModule,ReactiveFormsModule],
      providers: [
          HttpService
      ],
  }).compileComponents();
});

beforeEach(() => {
     fixture = TestBed.createComponent(UserComponent);
     userComponent = fixture.componentInstance;
     debugElement = fixture.debugElement;
     httpService = debugElement.injector.get(HttpService);

fit('should have getUsers() call the service GetData()', inject([HttpService], fakeAsync((httpService) => {
    let url = AppConfig.URL_UserById'

    let getDataSpy= spyOn(httpService,'getData').and.returnValue(Observable.of(url));
        userComponent.loadUser();
     expect(getDataSpy).toHaveBeenCalled();
   })))
})

Component:
  loadUser() {
this.httpService.getData(AppConfig.URL_UserById + "?UserID=" + this.userId)
  .catch((error: Response | any) => {
    this.showAlertWindow(this.exceptionMessage);
    console.error(error.message || error);
    return Observable.throw(error.message || error);
  })
  .subscribe((res: any) => {
    this.frmUser.patchValue({

      FirstName: res.FirstName,
      MiddleName: res.MiddleName,
      EmailAddress: res.EmailAddress,
      LastName: res.LastName

    });
    this.setUserAccess(res.UserAccessDetail)

  });

Now, if I comment out the line this.frmUser.patchValue){FirstName...}, the test passes and successfully checks if getData() is called. So I am guessing I need to initiate patchValueor something along those lines. Thank you.

A: Simple solution to the problem. In my ngOnInit component, I create my user form. All I needed to do was do userComponent.ngOnInit() and the test passed.
full code for working test:
fit('should have getUsers() call the service GetData()', inject([HttpService], fakeAsync((httpService) => {

    let url = AppConfig.URL_UserById + "?UserID=" + this.userId

    let getDataSpy= spyOn(httpService, 'getData').and.returnValue(Observable.of(url));

   userComponent.ngOnInit();
   userComponent.loadUser();

        expect(getDataSpy).toHaveBeenCalled();

   })))
})

A: Simply adding it to my
 ngOnInit(): void {
   this.myForm.patchValue({
      username: this.AUTH_USER.username
    })
}

Solved the issue: Keep in mind I have AUTH_USER declared with the initial values of the logged in user.


text:
Q: A characteristic 2 polynomial recursion Let $c(n)$ in $\mathbb{Z}/2\mathbb{Z}[x]$ be defined by the recursion $$c(n+4)=c(n+3)+(x^4+x^3+x^2+x)c(n)+x^n\cdot(x+x^2),$$ and the initial conditions
$$c(0)=0,\quad c(1)=1,\quad c(2)=x,\quad c(3)=x^2.$$
Question: If 4 divides $n$, is $c(n)$ a sum of $c(k)$ with $k$ less than $n$?
Remarks:

*

*I've checked that this holds up to $n=64$.

*The recursion may seem artificial, but it arises in studying the action of the operator $U_3$ on a space of mod $2$ modular forms of level 3. This accounts for the number theory tag.

VARIATION ON A THEME
Now define another sequence $c(n)$ in $\mathbb Z/2\mathbb Z[x]$ by the recursion
$$c(n+6)=c(n+5)+(x^6+x^5+x^2+x)c(n)+x^n\cdot(x+x^2),$$
 and the initial conditions
$$c(0)=0,\quad c(1)=1,\quad c(2)=1,\quad c(3)=x,\quad c(4)=x^2,\quad c(5)=x^4+x^2+x.$$
Question: If $n$ is 0 or 2 mod 6, is $c(n)$ a sum of $c(k)$ with $k$ less than $n$?

*

*I've checked that this holds through n=44.

*This question bears the same relation to mod 2 modular forms of level 5 that my initial question bears to level 3.

TWO VARIATIONS IN CHARACTERISTIC 3
Variation 2a---Let c(n) in Z/3[x] be defined by the recursion
c(n+3)=c(n+2)-(x^3+x^2+x)c(n)+x^n*(x^3-x), and the initial conditions
c(0)=0,  c(1)=x,  c(2)=x.
If (n,3)=1, define d(n) to be c(n)+c(n+1)+c(n+2) or c(n)-c(n+1) according as n is 1 or 2 mod 3.
Question:  If n is 2 mod 9, is d(n) a Z/3-linear combo of d(k) with k less than n?
Variation 2b---Let c*(n) be c(n)-x^n with c(n) as in variation 2a. For n prime to 3 define d*(n) as in variation 2a, but with c(n) replaced by c*(n).
Question: If n is 2 mod 9, is d*(n) a Z/3 linear combo of d*(k) with k less than n?
Remarks: I've verified that these hold for n up through 83, and am confident that a variant of Peter Mueller's technique will allow one to go much further. The questions are related to calculating the kernels of U_2+I and U_2-I on the space of mod 3 modular forms of level 2, just as the earlier questions were related to calculating the kernels of U_3+I and U_5+I on the spaces of mod 2 modular forms of levels 3 and 5 respectively.
FINAL EDIT (12/7/16)

*

*I've found elementary but apparently mysterious answers to the first 2 questions--see my 2 answers. The arguments are similar, and I'll randomly accept the level 3 answer.

*I think I can answer the characteristic 3 questions too. But to avoid accusations of self-abuse I'll refrain. And though I find the question on Jordan blocks very interesting (and similar questions attached to the other recursions should also be interesting), the thread has become long and so I've deleted that question.

A: EDIT (11/25/16)
The earlier version of this answer is sketchy, and as I've put up a complete version on arXiv (1603.03910 [math.NT], "A characteristic 2 recurrence with a Hecke algebra application"), I'm replacing my answer with references to this preprint. The argument, culminating in Theorem 2.10, involves nothing more than algebra in a ring Z/2[r], but would be mysterious to someone without a knowledge of modular forms--see the remark preceding Definition 1.1.
The final sections of the preprint give an application of Theorem 2.10 to the space K consisting of the odd mod 2 modular forms of level Gamma_0 (3) that are
killed by I+U_3. Combining Theorem 2.10 with results from arXiv:1508.07523 [math.NT], "A Hecke algebra attached to mod 2 modular forms of level 3", I show that each formal Hecke operator T_p acting on K is (uniquely) a power series in T_7 and T_13.

A: A stronger property seems to hold: If $n$ fulfills the congruence condition such that $c(n)$ is expected to be a sum of $c(k)$'s with $k<n$, then the following greedy algorithm works (for both questions) up to $n=10000$: Start with $f=c(n)$. For $j$ running from $n-1$ down to $0$ replace $f$ with $f+c(j)$ whenever $f$ and $c(j)$ have the same degree. So the degree of the new $f$ drops in such a step. If we get $f=0$, then we have the requested sum. If we finish in $j=0$ and still $f\ne0$, then the algorithm fails.
A Sage code (for the second question) which checks the cases up to $n=10000$ within a few seconds is
K.<x> = GF(2)[]
l = [K(0), K(1), K(1), x, x^2, x^4+x^2+x]
n = len(l)
while n < 10001:
    f = l[-1] + (x^6+x^5+x^2+x)*l[-6]+x^(n-6)*(x+x^2)
    l.append(f)
    if n%6 in [0,2]:
        print n
        for j in range(n-1,0,-1):
            if f.degree() == l[j].degree():
                f += l[j]
                if f == 0:
                    break
        else:
            print "FAIL"
            break
    n += 1

A: EDIT (12/7/16)
This answer deals with the "VARIATIONS ON A THEME". Again my earlier answer was sketchy, and I'm replacing it by references to my arXiv preprint (1612.01599 [math.NT], "A characteristic 2 recurrence attached to U_5 with a Hecke algebra application"). The entirely elementary (but seemingly mysterious) argument takes place in the few pages between Definition 1.1 and Theorem 2.11 of that note. Looking at the material preceding Definition 1.1 will help in understanding the mysteries.
The rest of the note uses Theorem 2.11 (slightly strengthened) to study the Hecke operators T_p acting on a space, K, consisting of the mod 2 modular forms of level Gamma_0 (5) annihilated by U_5+I. It's shown that each T_p, p>5, is (uniquely) in its action on K a power series with zero constant term in T_3 and T_7.


text:
Q: Java process sleeps after 397 seconds This code records video only ~397 seconds from live stream, after stream terminates. File size ~20 Megabytes. Java and ffmpeg processes are not terminated. Centos 6, Oracle JDK 8. Without java ffmpeg recording is not terminated. What is may be problem? May be any limits for JVM or OS?
public class FFMpegLauncher extends Thread {
    private Process pr;
    public static void main(String[] args) {
        FFMpegLauncher launcher = new FFMpegLauncher();
        Runtime rt = Runtime.getRuntime();
        rt.addShutdownHook(launcher);
        try {
            if(args.length > 0) {
                String cameraUid = args[0];
                String rtspURL = "rtsp://otherhost/" + cameraUid;
                launcher.pr = rt.exec("/usr/local/bin/ffmpeg -i " + rtspURL + " -vcodec copy -r 15 -f flv out.mp4");
                launcher.pr.waitFor();
            } else {
                System.exit(-1);
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }
}


text:
Q: Tone marks above Chinese characters in latex My aim is to put tone marks above Chinese characters in latex.
I have tried \v{好}, but this puts the carron accent (3rd tone) in the space left of the character rather than above it.
I have also found that $\stackrel{\vee}{\textrm{你}}$ works well but cannot find equivelent symbols for the other tones. I have tried --, \diagup and \diagdown, but they look really out of place
The standard unicode symbols for the tones are 02C9, 02CA, 02C7, 02CB and 02D9, but think that these are the same as using \v ect.
Does anyone have any suggestions? Thank-you.
The purpose of this is to have them automatically generated to help people learning chinese. I've written the software for that, so just need to output it in a nice format.
P.S. To use Chinese characters in Latex
\documentclass[12p]{article}
\usepackage{CJKutf8}

\begin{document}
\begin{CJK*}{UTF8}{gbsn}
你
\end{CJK*}
\end{document}

A: I am pretty sure that the symbols are not the same ones as the \v etc. Have you tried just typing those symbols in text? I've never used CJKutf8, but I did use CJK with Big5 encoding, and was able to type even in Ruby/ZhuYin symbols.
What I did was to
\newcommand{\rubychinese}[2]{\begin{tabular*}{3em}{c} {\Large #1} \\ %
   {\tiny #2}\end{tabular*}}

which I used like
\rubychinese{<character goes here>}{<pronunciation guide goes here>}

(In my version the ZhuYin appears below the main word, but you can easily switch the order.) Since there is a Bopomofo block in unicode, perhaps you just need a font supporting it and an input method that allows you to type those symbols?
An example output:

A: I have found a solution for this
$\stackrel{\textrm{\raisebox{-0.5em}[0.25em][-0em]{\={}}}}{\textrm{你}}$
$\stackrel{\textrm{\raisebox{-0.5em}[0.25em][-0em]{\'{}}}}{\textrm{你}}$
$\stackrel{\textrm{\raisebox{-0.5em}[0.25em][-0em]{\v{}}}}{\textrm{你}}$
$\stackrel{\textrm{\raisebox{-0.5em}[0.25em][-0em]{\`{}}}}{\textrm{你}}$
$\stackrel{\textrm{\raisebox{-0.5em}[0.25em][-0em]{\.{}}}}{\textrm{你}}$

for tones 1→4 with a dot above the 5th.
(I mainly updated the question on https://stackoverflow.com/questions/4003524/latex-question-accents-on-characters)


text:
Q: Docker rootless mode setup tool script can't find slirp4netns binary I am trying to set up Docker rootless mode on Ubuntu 18.04, using the dockerd-rootless-setuptool.sh script. But I'm struggling to get the script to find the slirp4netns binary I downloaded (slirp4netns provides user-mode networking for unprivileged network namespaces). On Ubuntu 20 this is installable as a package using apt, but for lower Ubuntu versions a pre-built binary is provided here.
I am running the script (as non-root) with:
dockerd-rootless-setuptool.sh install

But it complains:
Either slirp4netns (>= v0.4.0) or vpnkit needs to be installed

I have downloaded the latest stable binary for slirp4netns (v1.1.12) as per the instructions:
curl -o slirp4netns --fail -L https://github.com/rootless-containers/slirp4netns/releases/download/v1.1.12/slirp4netns-$(uname -m)
chmod +x slirp4netns

I moved the binary (as root) to /usr/local/lib. What am I doing wrong? Do I need to update an environment variable? I don't really want to upgrade my entire OS just to get a single library.
Thanks.

A: It was my own stupidity. As the person says in the comment to my question, all I needed to do was to move the binary to /usr/local/bin. I had assumed /usr/local/lib was on PATH, but it wasn't.


text:
Q: Misunderstanding concept of localStorage I'm using this code published by Sasi Varunan  here
<script type="text/javascript">
        // Broad cast that your're opening a page.
        localStorage.openpages = Date.now();

        var onLocalStorageEvent = function(e){
            if(e.key == "openpages"){
                // Listen if anybody else opening the same page!
                localStorage.page_available = Date.now();
            }
            if(e.key == "page_available"){
                alert("One more page already open");
            }
        };
        window.addEventListener('storage', onLocalStorageEvent, false);
</script>

Code is working like charm - doing exactly what I want - detect if an application it's already open in another tab browser or even in another browser window.
From my understanding:
The very first time when the application is started the followings thinks happen:

*

*App set openpages key with Date.now() value.

*Because of 1. storage event listener start onLocalStorageEvent event.

*Because the openpages key exists, is setting page_available key with Date.now ()

*When the followings apps are started they find page_available key in storage (the second if) the alert is triggered and I can redirect them to an error page.

QUESTION:
If I close all the browser windows and restart the app in a new winwdow everything still works fine.
This is what I don't understand because the page_available key is persistent is still there in the storage (no one deleted) the app should go on the second if and that the alert ... but this is not happening.

A:
The very first time when the application is started the followings thinks happen:

*

*App set openpages key with Date.now() value.

*Because of 1. storage event listener start onLocalStorageEvent event.

*Because the openpages key exists, is setting page_available key with Date.now ()

*When the followings apps are started they find page_available key in storage (the second if) the alert is triggered and I can redirect them to an error page.

The entire idea here is to communicate between the tabs using the storage event that is being triggered every time you access localStorage.
So when the page loads it first access the openpages key to trigger the storage event with e.key == "openpages".
Only after that it registers the event listener. So 2 only happens when you load the page on a second tab. On the second tab the event is triggered and the event listener is registered. Because the storage event is triggered for all the tabs, the event listener of the first tab (which is already registered) is being executed.
Tab 1 is triggered by the storage event with e.key == "openpages" and gets into the first if. There it triggers the storage event by accessing page_available key.
At this point tab 2 event listener reacts to the storage event but this time with e.key == "page_available" and gets into the second if where it shows the alert.
Note that if you don't close the tabs and open more tabs, tab 3 will trigger the storage event for all other tabs and you will have multiple tabs with alerts.

Just for reference:
If you want to trigger the alert on the first tab and not the second one you can achieve it with this code:
// Broadcast that you're opening the page.
localStorage.openpage = Date.now();

var onLocalStorageEvent = function(e) {
  if (e.key == "openpage") {
    alert("One more page already open");
  }
};
window.addEventListener('storage', onLocalStorageEvent);

Read more about localStorage here.
Read more about addEventListener here.

A:
After a restart of the browser window everything still works fine, and
  I don't understand why because the page_available key is still there
  in the storage

This is because localStorage has no expiration date which is opposite of sessionStorage. sessionStorage gets cleared once the browser is closed, but localStorage still remains.
You can still clear the localStorage by clearing the browser cache & cookies
Also this snippet localStorage.openpages = Date.now(); seems to be incorrect.
If you want to set a value in localStorage, do like this
localStorage.setItem('openpages',Date.now());


text:
Q: Why does the shape count in PowerPoint Notes page vary even when they all look empty? In a long presentation, most Notes just say "Click to Add Notes". However, some NotesPages have 0, 1, 2, or 3 shapes. And according to the code below and to the MsoShapeType enum, those shapes are Placeholders. Why is the number of placeholders not consistent?
Sub shapes_in_notes()
    counter = 0
    s = ""
    For Each sli In ActivePresentation.Slides
        counter = counter + 1
        s = counter & ": " & sli.NotesPage.Shapes.Count & " shapes: "
        For Each shi In sli.NotesPage.Shapes
            s = s & shi.Type & ", "
        Next
        Debug.Print s
    Next
End Sub

Typical Output:
1: 2 shapes: 14, 14,
2: 3 shapes: 14, 14, 14,
3: 3 shapes: 14, 14, 14,
4: 3 shapes: 14, 14, 14,
5: 3 shapes: 14, 14, 14,
6: 3 shapes: 14, 14, 14,
7: 3 shapes: 14, 14, 14,
8: 3 shapes: 14, 14, 14,
9: 2 shapes: 14, 14,
10: 3 shapes: 14, 14, 14,
11: 3 shapes: 14, 14, 14,
12: 2 shapes: 14, 14,
13: 3 shapes: 14, 14, 14,
14: 1 shapes: 14,
15: 3 shapes: 14, 14, 14,
16: 2 shapes: 14, 14,
17: 3 shapes: 14, 14, 14,
18: 2 shapes: 14, 14,
19: 0 shapes:
20: 3 shapes: 14, 14, 14,
21: 2 shapes: 14, 14,
...

A: The answer is in the program interface. Open a Notes Page, then choose Insert>Header and Footer. The preview shows the available placeholders. Besides the default slide and text placeholders, there are optional placeholders for Date and Time, Page number, Header and Footer. So you could have as many as 6. On the one page that has no placeholders, the slide and text placeholders may have been deleted by the user.
To distinguish them, use shi.PlaceholderFormat.Type.


text:
Q: If condition to handle template.html with Ionic and angular How can i config specific template.html by if condition in controller.js
if('posts.html') {
    //do something
} else
    if (home.html) {
        ///do somthing else
    }

please i read many article without any luck.

A: I'm not sure if I understand your question correctly. Are you trying to do different things according to different template?
If so, why don't you make each corresponding controller for them?

A: This is how we use in our project
templateUrl: (!isSmallScreen)?"InvoiceDetail/invoice-detail.html":"InvoiceDetail/Invoice-detailMobile.html"


text:
Q: How to Limit (clamp) Y axis Rotation for transform.rotatearound Unity I have a camera that I want to rotate around a point (0,0,0) in all directions, but I want to put a clamp on it so that it can't go too far above or below the point. I have seen this question answered for the left and right directions before but never for the vertical one.
I have tried converting the code from these two questions (that basically say the same thing) to work in the vertical direction, but it bugs out at some points along the rotation, and I can't figure out why.
First Question, Second Question
And this is how I tried to convert it:
//how much we want to rotate by this frame
float rotX = Input.GetAxis("Mouse X") * rotSpeed;
float rotY = Input.GetAxis("Mouse Y") * rotSpeed; //(before clamping)

//find current direction
Vector3 currentDirection = transform.position - Vector3.zero;

//find current angle between basis for clamp & where we are now
float angle = Vector3.Angle(Vector3.forward, currentDirection);

 //finds out if it's up or down
if (Vector3.Cross(Vector3.forward, currentDirection).x < 0) angle = -angle;

 //find out how much you can move without violating limits
 float newAngle = Mathf.Clamp(angle + rotY, yMinLimit, yMaxLimit);

//grabs how much you are allowed to move the angle from the current angle
rotY = newAngle - angle;

//spinning the garden
transform.RotateAround(Vector3.zero, Vector3.up, rotX);
 transform.RotateAround(Vector3.zero, transform.TransformDirection(Vector3.right), -rotY); //vertical rotation

If anyone knows of the correct way to make this work for the Y axis, or a different way to clamp the vertical rotation, I would be super excited to hear it! Ty!

A: I have a class here that do exactly what you want. It rotates a camera around a target and clamps the Y rotation. It uses the left button to rotate and the scroll press button to translate the target.
You can edit it to adjust to your specific needs - you might want to change the target to a Vector3 so you can set it to (0,0,0) without the need of an object. Hope it helps.
using UnityEngine;

public class RotateAroundCamera : MonoBehaviour
{
    Camera cam;
    public bool isControlable;
    private Vector3 screenPoint;
    private Vector3 offset;
    public Transform target;
    public float distance = 5.0f;
    public float xSpeed = 50.0f;
    public float ySpeed = 50.0f;

    public float yMinLimit = -80f;
    public float yMaxLimit = 80f;

    public float distanceMin = .5f;
    public float distanceMax = 15f;

    public float smoothTime = 2f;

    public float rotationYAxis = 0.0f;
    float rotationXAxis = 0.0f;

    float velocityX = 0.0f;
    float velocityY = 0.0f;
    float moveDirection = -1;

    public void SetControllable(bool value)
    {
        isControlable = value;
    }

    // Use this for initialization
    void Start()
    {
        cam = GetComponentInChildren<Camera>();
        Vector3 angles = transform.eulerAngles;
        rotationYAxis = (rotationYAxis == 0) ? angles.y : rotationYAxis;
        rotationXAxis = angles.x;

        Rigidbody rigidbody = GetComponent<Rigidbody>();

        // Make the rigid body not change rotation
        if (rigidbody)
        {
            rigidbody.freezeRotation = true;
        }
    }

    void LateUpdate()
    {
        if (target)
        {
            if (Input.GetMouseButton(1) && isControlable)
            {
                velocityX += xSpeed * Input.GetAxis("Mouse X") * 0.02f;
                velocityY += ySpeed * Input.GetAxis("Mouse Y") * 0.02f;
            }

            if (Input.GetMouseButton(2) && isControlable)
            {
                Vector3 curScreenPoint = new Vector3(moveDirection*Input.mousePosition.x, moveDirection*Input.mousePosition.y, screenPoint.z);

                Vector3 curPosition = cam.ScreenToWorldPoint(curScreenPoint) + offset;
                target.transform.position = curPosition;
            }

            if (Input.GetKeyDown(KeyCode.R) && isControlable)
            {
                target.transform.position = Vector3.zero;
            }

            if (Input.GetKeyDown(KeyCode.T) && isControlable)
            {
                moveDirection *= -1;
            }

            if (isControlable)
            {
                distance -= Input.GetAxis("Mouse ScrollWheel");

                if (distance > distanceMax)
                {
                    distance = distanceMax;
                }
                else if (distance < distanceMin)
                {
                    distance = distanceMin;
                }
            }

            rotationYAxis += velocityX;
            rotationXAxis -= velocityY;

            rotationXAxis = ClampAngle(rotationXAxis, yMinLimit, yMaxLimit);

            Quaternion fromRotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, 0);
            Quaternion toRotation = Quaternion.Euler(rotationXAxis, rotationYAxis, 0);
            Quaternion rotation = toRotation;

            Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
            Vector3 position = rotation * negDistance + target.position;

            transform.rotation = rotation;
            transform.position = position;

            velocityX = Mathf.Lerp(velocityX, 0, Time.deltaTime * smoothTime);
            velocityY = Mathf.Lerp(velocityY, 0, Time.deltaTime * smoothTime);

            screenPoint = cam.WorldToScreenPoint(target.transform.position);
            offset = target.transform.position - cam.ScreenToWorldPoint(new Vector3(moveDirection*Input.mousePosition.x, moveDirection*Input.mousePosition.y, screenPoint.z));
        }

    }

    public static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360F)
            angle += 360F;
        if (angle > 360F)
            angle -= 360F;
        return Mathf.Clamp(angle, min, max);
    }
}


text:
Q: COM-object was released unintendedly I have a helper-class for my unit-tests that share a reference to an COM-object in memory:
public class UnitTestGeometryProvider
{
    public static readonly IGeometry Geometry = Deserialize();
}

The geometry is deserialized from a Xml file which is stored as a resource file and appended to the project. Afterwards it is wrapped into a COM object:
public static IGeometry Deserialize()
{
    return (IGeometry) new XMLSerializerClass().LoadFromString(myXDoc.OuterXml, null, null);
}

Now I have two test-methods that use the geometry stored within this class:
[TestClass()]
public class MyTest
{
    [TestMethod()]
    public void FirstTest()
    {
        var p = UnitTestGeometryProvider.Geometry;
    }

    [TestMethod()]
    public void SecondTest()
    {
        var p = UnitTestGeometryProvider.Geometry;
    }
}

When running the second one I get a COMException:

COM object that has been separated from its underlying RCW cannot be used

I wonder why the reference to the COM-object is released as it is marked static in UnitTestGeometryProvider and I do not explicitly release it. So even if the managed resource to the instance would go out of scope (which is does not at it is static), the underlying COM object should go away only when all my tests finished or more general when the application terminates, or do I miss anything?
I am using ArcObjects and Visual NUnit.

A: Due to the comments by Hans Passant I found the actual problem.
Obviously the Visual-NUnit-Framework decides to create a separate thread for every test. Thus whenever I create a COM-object - be it static or not - this object lives on this single thread and cannot be used in another one. If the thread dies also does the COM-object or to be more precise the reference to it. This leads to the GC kicking in throwing the COM-object away as no more managed references to it exist within that thread.
The solution is pretty straitforward: I changed the static field to instance-members and created an instance-member of type UnitTestGeometryProvider within my test-class. Thus a new provider is generated by every test.
However this solution is quite annoying because the Geometry-property has to be initialized and therefor the Deserialize-method runs for every test instead of only once for all tests.
I don´t know if there is a thread-safe solution to not kill the reference to the COM-object when the first thread that intialized it dies.


text:
Q: Why splice syscall fails when my program runs on Linux but succeeds when it runs in gdb? I try to run a book's sample code. Its function is to accept a line of input and output it to the standard output and operation parameters specified file.
Here is the code:
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>

int main( int argc, char* argv[] )
{
    if ( argc != 2 )
    {
        printf( "usage: %s <file>\n", argv[0] );
        return 1;
    }
    int filefd = open( argv[1], O_CREAT | O_WRONLY | O_TRUNC, 0666 );
    assert( filefd > 0 );

    int pipefd_stdout[2];
        int ret = pipe( pipefd_stdout );
    assert( ret != -1 );

    int pipefd_file[2];
        ret = pipe( pipefd_file );
    assert( ret != -1 );

    //the first splice()
    ret = splice( STDIN_FILENO, NULL, pipefd_stdout[1], NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE );
    assert( ret != -1 );

    ret = tee( pipefd_stdout[0], pipefd_file[1], 32768, SPLICE_F_NONBLOCK );
    assert( ret != -1 );

    //the second splice()
    ret = splice( pipefd_file[0], NULL, filefd, NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE );
    assert( ret != -1 );

    //the third splice()
    ret = splice( pipefd_stdout[0], NULL, STDOUT_FILENO, NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE );
    printf("errno:%d\n",errno);
    assert( ret != -1 );

    close( filefd );
        close( pipefd_stdout[0] );
        close( pipefd_stdout[1] );
        close( pipefd_file[0] );
        close( pipefd_file[1] );
    return 0;
}

After i compiled the code, i ran it and typed "123", it can't output to stdout, the third splice() fails and errno is 22. here is the screenshot of result:
p1
And when i use gdb to run the code, it works normally. Here is the screeshot:
p2
kernel version: 4.19.163-1
gcc version: 10.2.0
gdb version: 10.1
my compile command: g++ test.cpp -g -o LinuxServer
my run command: ./LinuxServer test.txt
my gdb command: gdb LinuxServer
So why the splice syscall fails when my program runs on Linux but succeeds when it runs in gdb?

A: In linux manual splice(2), there is a description of ERRORS: EINVAL The target file is opened in append mode.
The stdout in my terminal is at append mode, that's why the third splice syscall fail.
And to solve this problem, we can add fcntl(STDOUT_FILENO, F_SETFL, fcntl(STDOUT_FILENO, F_GETFL) & ~O_APPEND);before the splice syscall.


text:
Q: PostgreSQL Operator Class for index support of custom operator I'm trying to create an index that will support queries that use my custom operator. This is on PostgreSQL 10.4.
The custom operator
I followed the tips in this SO answer to create an operator that performs "LIKE" style matching on elements in an text ARRAY.
CREATE FUNCTION reverse_like (text, text) returns boolean language sql
as $$ select $2 like $1 $$;

CREATE OPERATOR <~~ ( function =reverse_like, leftarg = text, rightarg=text );

The above operator allows me to do things like
SELECT 'ab%' <~~ ANY('{"abc","def"}');

The schema, index and query
I have a table with web traffic visits called sessions which includes an array column.
CREATE TABLE sessions
(
   session_id    varchar(24) NOT NULL,
   first_seen    timestamp,
   domains       varchar[]
);

To query the domains column to see if a given domain (or partial/ wildcarded domain name) was visited I can do the following:
SELECT count(*)
FROM session_4070ba14_f081_41cb_9ef7_9dd385934da7
WHERE 'www.foo%' <~~ ANY(domains);

I want to speed up the above queries with GIN index. So I created the index as follows:
CREATE INDEX idx_domains ON session USING GIN(domains);

The Question
After running  analyze on the table and a set enable_seqscan = false; I have no luck getting Postgres to employ this index. It's always doing a seqscan. It uses the above index of array operators like @> but not for my custom <~~ operator.
I think its because the GIN index doesn't know how to handle my custom operator - so do I need to create an operator class and then create my index using that? Or do I create a functional index?

A: For trigram support, you can try the parray_gin extension
WHERE domains @@> ARRAY['www.foo%'];

If you just want to do prefix matching (more efficiently than that provided by trigram), I don't think there is any way you can do that without writing some C code to glue the pieces together.  I think you would then work on the array type directly, so wouldn't need the ANY, and so wouldn't benefit from the reverse_like operator at all.

A: You won't be able to index an expression like this at all:
<constant> <operator> ANY(<array column>)
Your only chance would be to define an operator such that your expression looks like:
<array column> <operator> <constant>
But writing a GIN operator class means writing an extension in C, and I don't think you want to go that far.
The easy solution would be to change your data model so that you don't use arrays for things like that.

A: Turns out I over complicated this by thinking about a GIN index. A b-tree index on the whole array works fine and supports the custom <~~ operator.

CREATE INDEX IF NOT EXISTS idx_domains2 ON session(domains );

select count(*)
from session
where 'www.foo%' <~~ ANY(domains);

Finalize Aggregate  (cost=331523.11..331523.12 rows=1 width=8)
  ->  Gather  (cost=331522.90..331523.11 rows=2 width=8)
        Workers Planned: 2
        ->  Partial Aggregate  (cost=330522.90..330522.91 rows=1 width=8)
              ->  Parallel Index Only Scan using idx_domains2 on session  (cost=0.42..330200.52 rows=128952 width=0)
                    Filter: ('www.foo%'::text <~~ ANY ((domains)::text[]))


text:
Q: Socle of socle of module is the socle of the module Let M be any left R-module.
I'm having problems proving that
$$ Soc(Soc(M)) = Soc(M) $$
Where $Soc$ is the socle of the module defined as:
$$ Soc(M) = \sum \{V \ \subseteq  M\  |\text{$V$ is a simple left $R$-module}\}$$

A: I write $SM$ for the soccel of $M$. It is clear that $SSM \subset SM$. Now take $x\in SM$. The element $x$ may be written as a finite linear combination $x=y_1+ ...+y_n$ where each $y_r$ is contained in a simple submodule $V_r$ of $M$. But each $V_r$ is also a simple submodule of $SM$, so in particular $y_r$ is contained in $SSM$. Since $SSM$ is a submodule, it follows that $x$ is contained in it.


text:
Q: Chrome sluggish and not repainting non-webGL when drawing webGL in a tight loop I have a page http://williame.github.com/Mandel_1 that draws an animating webGL scene using requestAnimationFrame.  This is the generally recommended approach.
Occasionally it updates a div-element beside the canvas.
In Firefox, this works well, although the Firefox address bar can be sluggish to focus.
In Chrome, the div often doesn't get repainted despite being updated and the whole of Chrome can become sluggish and unresponsive.  I get reports of this from people on both Linux and Windows.
Additionally, the FPS I compute (by periodically counting how many frames in the previous 3 seconds) does not match the FPS that Chrome's own debug FPS counter shows.  The discrepancy is enough to make me wonder if Chrome is measuring something else?
How can I structure my draw-loop to keep Chrome and other browsers responsive whilst drawing at as good a frame-rate as possible?

A: I'm not sure what's going in in your app but it looks like each time you insert a div you are also compiling and linking 4 shaders and checking for success. Compiling and linking is slow.
Try compiling and linking all your programs at startup.
Or, conversely, if you are 100% sure they will compile and link then don't check the compile and link status in which case their compilation and linking will be 100% async relative to JavaScript.


text:
Q: Functional defined on the space of functions with compact support Let $X=C_c(\mathbb{R})$, the space of functions with compact support, normed with the max norm. Define $\Gamma: X \rightarrow \mathbb{R}$ as: $$ \Gamma f= \int_{- \infty}^{\infty} f(t)dt \>\>\> \forall f \in X$$
Prove $\Gamma$ is not continuous.

A: Let $f$ be a continuous function such that $f(x)\in [0,1]$ for all $x$, $f(t)=1$ if $t\in [-1,1]$ and $f(t)=0$ if $|t|>2$. Then define $f_n(x):=f(nx)/n$. Since $
\int f_n(x)\mathrm dx=\int_\mathbb R f(x)\mathrm d x\gt 0$ and $\lVert f_n\rVert=1/n$, $\Gamma$ is not continuous.


text:
Q: Pandas Resample with apply 10 to 15 min values I know there are several questions to that matter but I haven't find the fitting one (and I haven't find a satisfying solution)
I have a Dataframe with 10 min. avg. data and want to resample it, with a specific formular, to 15 min. avg. data. (Formular: DENA-Netzstudie II)
I tried it with the apply function (df.resample('15T').apply(cal_ten_to_fifteen_min)) ... but I failed because the function doesn't handover the right rows to recalculate 10 to 15 min data.
Here my solution to that matter maybe sombody has a better idea :)
#!/usr/bin/env python3
import pandas as pd

def cal_ten_to_fifteen_min(ten_min_value: list) -> list:
    """Returns an array of 15 min values based on the calculation of DENA Netzstudie II (2010) S. 109

    :param ten_min_value: 1-dim. array of 10 min avg. values
    :return: 1-dim. array of fifteen min. values
    :type ten_min_value: int
    :rtype : float[]
    """

    def index_m(_n: int) -> int:
        """Returns an index for the calculation to transfer 10 min values in 15 min values

        :param _n: index
        :type _n: int
        :rtype : int
        :return: index m for the calculation
        """
        return int(((3 * _n + (_n % 2)) / 2) - 1)

    def weighting_g(_m: int) -> int:
        """Returns a weighting value for the calculation to transfer 10 min values in 15 min values

        :param _m: index
        :type _m: int
        :return: weighting value g for the calculation
        :rtype : int
        """
        return abs((2 * _m % 3) - 1) + 1

    fifteen_min_value = list()
    for n in range(1, int(len(ten_min_value) / 6 * 4) + 1):
        m = index_m(n)
        try:
            fifteen_min_value.append(
                (ten_min_value[m - 1] * weighting_g(m) + ten_min_value[m] * weighting_g(m + 1)) / 3)
        except:
            fifteen_min_value.append("NaN")

    return fifteen_min_value

def recalc_10_to_15_df(frame, columns, r_one_col: bool = False):
    """Recalculates a 10 min. avg. Dataframe to a 15 min. avg. Dataframe

    :param frame: DataFrame with 10 min average values
    :param columns: column names with the average values
    :param r_one_col: if true: return only the column (works only when a string is given as parameter columns)

    :type frame: pd.Dataframe
    :type columns: list[str,] or str
    :type r_one_col: bool

    :return: pd.DataFrame with 15 min. avg. Data
    :rtype: pd.DataFrame()
    """
    frame = frame.copy()

    for id in frame.index:
        if id.minute == 0:
            first = id
            break
    index = pd.date_range(first, frame.last_valid_index(), freq='15T')
    frame = frame[(frame.index >= first)]

    if isinstance(columns, str):
        output = cal_ten_to_fifteen_min(list(frame[columns].values))

        output = pd.DataFrame(output, index[:len(output)], [columns, ])
        if r_one_col or len(frame.columns) == 1:
            return output
        frame.drop(columns, axis=1)

    elif isinstance(columns, list):
        output = list()
        for column in columns:
            output.append(recalc_10_to_15_df(frame, column, True))
            frame.drop(column, axis=1)
        output = pd.concat(output, join='inner', axis=1)

    else:
        raise ValueError

    for column in frame:
        output[column] = list(frame[column].values)[:len(output)]

    return output

index = pd.date_range('2020-01-01 00:00', '2020-01-01 02:00', freq='10T')
values = list(range(1, 14))
column_name = '10_min_avg'
df = pd.DataFrame(values, index, [column_name, ])

avg_15_min = recalc_10_to_15_df(df, column_name)


text:
Q: Framework7 : Navbar hidden when I'm move to anothers views I'm learning Framework7 now, but I'm stuck in this problem. I have created two pages, this is the file
index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=1, minimal-ui">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="theme-color" content="#673ab7">

    <title>Ciptaloka Editor</title>

    <link rel="icon" href="assets/img/favicon.png">
    <link rel="stylesheet" href="assets/css/framework7.material.min.css">
    <link rel="stylesheet" href="assets/css/framework7.material.colors.min.css">
    <link rel="stylesheet" href="assets/css/style.css">

                a

                                menu

                            Custom T-Shirt

                                Done

                            dashboard
                            Produk

                            add_a_photo
                            Image

                            text_fields
                            Text

                            photo_filter
                            Clipart

                                Go home 2

                                Image

                                Text

                                Clipart

index2.html

                    back

            Custom Case

            Success direct page

When I'm click 'go home 2' at index.html, its succesfully direct to index2.html, content is shown, but not with the navbar, its only shown a background, but the text is hidden. This my screenshoot :

Why this is happen? Is I miss something?

A: your navbar is inside your data-page
you switch to index2 and all page change.
let navbar outside -> view-main -> navbar and then the data-page
sorry my bad english.


text:
Q: Standalone SVN Viewer I'm currently using tortoiseSVN to version control my localy programmed files. I don't run an SVN Server since one can use tortoiseSVN directly (look e.g. http://invalidlogic.com/2006/12/06/using-subversion-without-a-subversion-server/), as I don't like the heck about installing the SVN server. Now I have my repository and my real programming files and I'm looking for a standalone application (which I download, install and open) to point to my repository and see a nice version history; just like what the webbased SVN viewers offer.
Thanks!

A: RapidSVN has worked for me:
http://www.rapidsvn.org/

A: TortoiseSVN with it's Repository Browser?!
Just use "file:///" protocol for accessing local repo

A: I like Sventon. It's open source and powerful, but you have to run it inside a Tomcat instance, and must have Java 1.6 Runtime installed.
I use svnserve as my private Subversion server. Svnserve comes with Subversion, and is quick and easy to install. The advantage is that I can share my repository if needed. Plus, the URLs are shorter:
C:> svn checkout "file:///C:/Documents and Settings/dweintraub/svn_repos/trunk"

vs.
C:> svn checkout svn://localhost/trunk


text:
Q: The number of solutions of the equation $1 + \sin x\sin^2 {\frac{x}{2}} =0$ in $[-\pi,\pi]$ is...
The number of solutions of the equation $1 + \sin x\sin^2 {\frac{x}{2}} =0$ in $[-\pi,\pi]$ is...

What I have tried...
Since, $\sin \frac{x}{2} = \sqrt{\frac{1-\cos x}{2}}$,
$$ 1 + \sin x\cdot\frac{1-\cos x}{2} = 0$$
$$2+\sin x \cdot (1-\cos x) = 0$$
From here onwards I am not sure how to continue...
P.S. The answer to this question is $0$ ( which means that the equation has no solution. Please explain how) Thank you!

A: Hint.  Don't try to solve the equation algebraicly.  Instead, the product of your sine terms has to be $-1$.  What are the possible outputs of sin?  How can you get that product to be $-1$?


text:
Q: file sent using form data api to express api is showing undefined in node js I am making a simple express api to upload file.I have used formData api.
But shows undefined to my image in console but image name is logged in console .What I have done wrong and how I can fix this issue. I have tried but nothing happen.
Thanks in advance.
Here is my frontend code
import React, {useState} from 'react'
import axios from 'axios'
const Login=()=>{
    const[image,setImage]=useState();
    const [imageName,setImageName]=useState("")
const send=async(e)=>{
    e.preventDefault()
    const formData=new FormData();
formData.append('file',image);
formData.append('name',imageName)
    try {
        const res=await axios.post('http://localhost:8000/post',formData)
        console.log(res.data)
    }
    catch(err){
        console.log(err)
    }

}
const handleImage=(e)=>{
let image=e.target.files[0]
console.log(image)
setImageName(image.name);
setImage(image)
}
    return(
        <>
        <form method ="post" encType="multipart/form-data">

Login With Google

Login With Facebook

         <input type="file" name="file" onChange={handleImage}/>

        <input  type="submit" onClick={send} value="send "></input>
       </form>
        </>
    )
}
export default Login

backend code
const  express=require('express');
const cors=require('cors');
const app =express( );
const fs=require('fs');
const fileUpload=require('express-fileupload');
const bodyParser = require('body-parser');
app.get('/',(req,res)=>{
    res.send("working")
})
app.use(bodyParser.json())
app.use(fileUpload())
app.use(cors())
app.use(bodyParser.urlencoded({extended:false}))
const dir='upload';
if (fs.existsSync(dir)) {
    console.log(`already exist directory ${dir}`);
}
else{
    fs.mkdirSync(dir)
}
app.post('/post',(req,res)=>{
    console.log(req.body.name)
    console.log(req.body.file)
})
const PORT=process.env.PORT||8000
app.listen(PORT,()=>{
console.log(`server is listening in port number ${PORT}`)
})

A: kindly console req.files instead of req.body.file you will get the object in server
enjoy coding