text:
Q: JavaScript React Front-End: Opening one collapse button, all collapse buttons open instead of just the one I am trying to setup a toggle button in react JSX. When I click the Order Details Toggle button I want the toggle to only open for the selected order.
Right now, I am able to do that.  But the other content Cards (react bootstrap Card) open up as well.  The other cards' order details are not shown which is good but their boxes get weirdly elongated.
Please see below:

In my example above, only the Card associated with order id 2 should open.  The other three cards should retain their original size.
Below is my React code on the front-end:
import React from 'react'
import {connect} from 'react-redux'
import {toDollars, getOrders} from '../store/allOrders' // sortOrders
import {updateOrderThunk, fetchSingleOrder} from '../store/singleOrder'
// Status Filter import BeerFilter from './BeerFilter'
import Card from 'react-bootstrap/Card'
import Button from 'react-bootstrap/Button'
import {UncontrolledCollapse, CardBody} from 'reactstrap'

export class AllOrders extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      showForm: false,
      stat: ''
    }
    this.clickHandlerOne = this.clickHandlerOne.bind(this)
    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }

  componentDidMount() {
    try {
      this.props.fetchInitialOrders()
    } catch (error) {
      console.error(error)
    }
  }

  clickHandlerOne() {
    let hidden = this.state.showForm
    this.setState({
      showForm: !hidden
    })
  }

  handleChange(event) {
    //console.log('event.target', event.target)
    this.setState({
      [event.target.name]: event.target.value
    })
  }

  async handleSubmit(orderId) {
    event.preventDefault()

    const updatedOrder = {
      id: orderId,
      status: this.state.stat
    }

    // console.log('UPDATE ORDER', updatedOrder)

    await this.props.updateOrderThunk(updatedOrder)
    this.props.fetchInitialOrders()
  }

  render() {
    const orders = this.props.orders
    // console.log('PROPS', this.props)
    console.log('ORDERS', this.props.orders)

    // const beers = orders.beers || []

    return (

        {/*

          <select onChange={this.handleChange}>
            <option value="">Sort By...</option>
            <option value="priceHighToLow">Price (high to low)</option>
            <option value="priceLowToHigh">Price (low to high)</option>
            <option value="name">Name</option>
          </select>

          <BeerFilter />

 */}

          {orders.map(order => (
            <Card style={{width: '18rem'}} key={order.id}>
              <Card.Body>
                <Card.Title>Order Id: {order.id}</Card.Title>
                <Card.Text>

User: {order.user.username}

Order Status: {order.status}

                            Order Date:{' '}
                            {new Intl.DateTimeFormat('en-GB', {
                              month: 'short',
                              day: '2-digit',
                              year: 'numeric'
                            }).format(new Date(order.createdAt))}

                            {' '}
                            Total Quantity:
                            {order.beers.reduce(function(totalQuantity, beer) {
                              return (
                                beer['beer-orders'].quantity + totalQuantity
                              )
                            }, 0)}

                          {/* */}

                            {' '}
                            Total Price:
                            {toDollars(
                              order.beers.reduce(function(totalPrice, beer) {
                                return (
                                  beer.price * beer['beer-orders'].quantity +
                                  totalPrice
                                )
                              }, 0)
                            )}

                          {/* */}
                          <Button
                            id={`status${order.id}`}
                            onClick={() => {
                              this.clickHandlerOne()
                            }}
                            variant="outline-primary"
                          >
                            Update Status Toggle
                          </Button>
                          <UncontrolledCollapse toggler={`#status${order.id}`}>
                            <form onSubmit={() => this.handleSubmit(order.id)}>

                                  <select
                                    name="stat"
                                    value={
                                      typeof order.status === 'string'
                                        ? this.state.stat
                                        : order.status
                                    }
                                    onChange={this.handleChange}
                                  >
                                    <option value="">
                                      select order status
                                    </option>
                                    <option value="open">open</option>
                                    <option value="processing">
                                      processing
                                    </option>
                                    <option value="cancelled">cancelled</option>
                                  </select>

                                  {/* */}
                                  <button type="submit">Edit</button>

                              {/* delete thunk

                                    <button type="button">Delete</button>

                                */}
                            </form>
                          </UncontrolledCollapse>

 -----------------------------------------

                          <Button
                            variant="info"
                            id={`order${order.id}`}
                            style={{marginBottom: '1rem'}}
                          >
                            Order Details Toggle
                          </Button>
                          <UncontrolledCollapse toggler={`#order${order.id}`}>
                            <Card>
                              <CardBody>

                                    {order.beers.length === 0
                                      ? `${order.user.username} has no orders!`
                                      : order.beers.map(beer => (

 Beer Name: {beer.name}

                                              {' '}
                                              Beer Description:{' '}
                                              {beer.description}{' '}

 Beer IBU: {beer.ibu}

                                              {' '}
                                              Beer Price:{' '}
                                              {toDollars(beer.price)}{' '}

                                              {' '}
                                              --------------------------------

                                        ))}

                              </CardBody>
                            </Card>
                          </UncontrolledCollapse>

                </Card.Text>
              </Card.Body>
            </Card>
          ))}

    )
  }
}

const mapStateToProps = state => {
  return {
    orders: state.allOrders
  }
}

const mapDispatchToProps = dispatch => {
  return {
    loadSingleOrder: id => dispatch(fetchSingleOrder(id)),
    updateOrderThunk: updatedOrder => dispatch(updateOrderThunk(updatedOrder)),
    //getSortedBeers: (sortBy, beers) => dispatch(sortBeers(sortBy, beers)),
    fetchInitialOrders: () => dispatch(getOrders())
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(AllOrders)

How can I fix my code so I can get it to render the toggling appropriately?

A: I think the problem is here:
<Button
  variant="primary"
  id="toggler"
  style={{marginBottom: '1rem'}}
>
  Order Details Toggle
</Button>
<UncontrolledCollapse toggler="#toggler">

ID attribute must be unique (https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id)
A fix:
<Button
  variant="primary"
  id={order.id}
  style={{marginBottom: '1rem'}}
>
  Order Details Toggle
</Button>
<UncontrolledCollapse toggler={`#${order.id}`}>


text:
Q: python - compilation error - cannot import name 'gpio' I am trying out this tutorial here:
http://www.instructables.com/id/Orange-Pi-One-Python-GPIO-basic/?ALLSTEPS
Whenever I execute my .py file, I get the error "cannot import name 'gpio'"
This here is the code I use after installing everything else, stated in the tut:
#import the library
from pyA20.gpio import gpio
from pyA20.gpio import port
from time import sleep

#initialize the gpio module
gpio.init()

#setup the port (same as raspberry pi's gpio.setup() function)
gpio.setcfg(port.PA7, gpio.OUTPUT)

#now we do something (light up the LED)
gpio.output(port.PA7, gpio.HIGH)

#turn off the LED after 2 seconds
sleep(2)
gpio.output(port.PA7, gpio.LOW)

I am pretty new to all of this, so please bear with me.
Thank you very much.

A: got same issue on orange pi Zero... I got the python library from https://pypi.python.org/pypi/pyA10Lime and it worked then :
root@orangepizero:~# wget https://pypi.python.org/packages/e6/52/a6b558fd5c8eb11e5de710271d59881769425e61d3adf6d235836ca877cc/pyA10Lime-0.2.1.tar.gz
root@orangepizero:~# tar -zxf pyA10Lime-0.2.1.tar.gz
root@orangepizero:~# cd pyA10Lime-0.2.1/
root@orangepizero:~/pyA10Lime-0.2.1#
root@orangepizero:~/pyA10Lime-0.2.1# vi setup.py
#
# @line 60, add :
#             elif "sun8i" in processor:
#                 print ("Detected processor: " + print_color(processor) + " (Probably Allwinner H2+/H3)")
#
root@orangepizero:~/pyA10Lime-0.2.1# python setup.py install
root@orangepizero:~/pyA10Lime-0.2.1# python
Python 2.7.9 (default, Aug 13 2016, 17:56:53)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from pyA20.gpio import gpio
>>> from pyA20.gpio import port
>>> gpio.init()
>>> gpio.setcfg(port.PG7, gpio.OUTPUT)
>>> gpio.output(port.PG7, gpio.HIGH)
>>>
>>> gpio.output(port.PG7, gpio.LOW)
>>> exit()

usefull link https://forum.armbian.com/index.php?/topic/3655-guide-orange-pi-zero-gpios/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cyclic dependency error TransferHttpCacheModule, LocalizeRouterModule, TranslateModule I need the following modules for my project:
TranslateModule
LocalizeRouterModule
TransferHttpCacheModule
Somehow this combination of modules is creating a cyclic dependency.
TranslateModule with TransferHttpCacheModule - works
TranslateModule with LocalizeRouterModule - works
But when I import all three it's causing a dependency cyclic.
Cannot instantiate cyclic dependency! ApplicationRef ("[ERROR ->]"): in NgModule AppBrowserModule in ./AppBrowserModule@-1:-1
Check the plnkr for reproduction of the problem: https://plnkr.co/edit/qlUQ866JzTa3JtFgSAIO?p=preview
@NgModule({
imports: [
    HttpClientModule,
    BrowserModule,
    BrowserAnimationsModule,
    TransferHttpCacheModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpTranslationLoaderFactory,
        deps: [HttpClient]
      }
    }),
    LocalizeRouterModule.forRoot([], {
      parser: {
        provide: LocalizeParser,
        useFactory: HttpLoaderFactory,
        deps: [TranslateService, Location, LocalizeRouterSettings]
      }
    }),
    RouterModule.forRoot([])
],
declarations: [
    AppComponent
],
providers: [

],
bootstrap: [AppComponent]
}) export class AppModule { }

A: You do not need to have LocalizeRouterModule under imports since it can be injected to providers which is causing the cyclic depdendency.
Fix it as follows,
@NgModule({
    imports: [
        HttpClientModule,
        BrowserModule,
        BrowserAnimationsModule,
        TransferHttpCacheModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: (createTranslateLoader),
            deps: [HttpClient]
          }
        }),

        RouterModule.forRoot([])
    ],
    declarations: [
        AppComponent,
        LocalizeRouterPipe
    ],
  providers: [TranslateModule  ],
    bootstrap: [AppComponent]
})

PLUNKER
if you need a working repo, look at this as a example


text:
Q: scrollTop() returning position below element I'm using jquery to highlight my navbar when it passes certain points on my page, but there is one part where the nav isn't being highlighted until it passes below the object. The specific offender is the contact portion of the page.
here is the codepen - http://codepen.io/Davez01d/pen/NxMzYy?editors=0010
here is the relevant html -
<hr id="contact-anchor" class="line section-seperator">

css -
.on-section {
  background-color: #2766af !important;
  color: white;
}
.on-section:focus {
  color: white;
}

and javascript -
$(window).scroll(function() {
  var navHeight = $(".navbar").outerHeight();
  var scrollTop = $(window).scrollTop();
  var aboutPoint = $('#about').offset().top;
  var lineMargin = parseInt($('.section-seperator').css('marginTop'));
  var portfolioPoint = $('#portfolio-anchor').offset().top;
  var contactPoint = $('#contact-anchor').offset().top;

  if (scrollTop < aboutPoint)  {
    $('#home-btn').addClass('on-section');
    $('#about-btn').removeClass('on-section');
  } else if (scrollTop > aboutPoint && scrollTop < (portfolioPoint - navHeight)) {
    $('#home-btn').removeClass('on-section');
    $('#about-btn').addClass('on-section');
    $('#portfolio-btn').removeClass('on-section');
  } else if (scrollTop > (portfolioPoint - navHeight) && scrollTop < contactPoint) {
    $('#about-btn').removeClass('on-section');
    $('#portfolio-btn').addClass('on-section');
    $('#contact-btn').removeClass('on-section');
  } else if (scrollTop > (contactPoint - navHeight)) {
    $('#portfolio-btn').removeClass('on-section');
    $('#contact-btn').addClass('on-section');
  }
});

A: Making this change fixes the issue for me, I think you are forgetting that you are treating scrollTop as the scrollTop + navbar height
var scrollTop = $(window).scrollTop() + navHeight;

A: To highlight the about you do this
if (scrollTop > (portfolioPoint - navHeight) && scrollTop < contactPoint)

You have to quit the .navbar height (just how you are doing in the others)
if (scrollTop > (portfolioPoint - navHeight) && scrollTop < (contactPoint - navHeight))

Here you have your codepen working http://codepen.io/anon/pen/XXoLWM?editors=0110

A: Your updated pen is here. There was a problem in the calculation or better conditions when you switch the buttons:
} else if (scrollTop > (portfolioPoint - navHeight) && scrollTop < contactPoint)) {
    // in this condition you stick too long, you forgot the navHeight
} else if (scrollTop > (contactPoint - navHeight)) {
    // therefore you reach this too late
}

In the first condition here you need to add the navheight:
} else if (scrollTop > (portfolioPoint - navHeight) &&
  scrollTop < (contactPoint - navHeight))) {
    // like this it works
} else if (scrollTop > (contactPoint - navHeight)) {
    // and here we go...
}


text:
Q: list of 2D to 3D using dstack I have a list of 2D numpy arrays of length 2000.
I am trying to create a 3D array using dstack.  But it gives me the below error.

return _nx.concatenate([atleast_3d(_m) for _m in tup], 2)
ValueError: all the input array dimensions except for the concatenation axis must match exactly

I manually checked the shapes of the 2D arrays, and all are of shape (3,300).  I am not sure what is wrong.
My code is very simple
   X = list()
   for row in df.itertuples(name=None):
        srow = [ "%s" %x for x in row[2:-1] ]
        exist_words = [word for word in srow if word in model ]
        X.append(model[exist_words])
    return np.dstack(X)


text:
Q: Get json in angular acording to url params I want to get json in angular from mongoDB.
I have server side that sent to my client side json acording to "idstud" and I want that my client side display it to the screen with angular.
this is my server side (controller):
exports.getDataById = function(req,res){
    var idStud1=req.params.id;
    User.find({idstud : idStud1},function(err,user){
            if(err) throw err;
            res.json(user);
        });
}

my server side (index.js):
app.get('/studentsById/:idstud',student.getDataById);

my client side (controller):
var showStudentById = angular.module('showStudentById',[]);
showStudentById.controller('showStudById',
['$scope','$http',function($scope,$http) {
     $http.get("http://localhost:3000/studentsById/:idstud").success(function(data){
        $scope.studentByIdController = data;
        console.log(data);
    });
}]);

my client side html:

 <title>student</title>
 <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
 <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">

All Students By Id

name:{{student.name}}

id:{{student.idstud}}

grade:{{student.grade}}

year:{{student.year}}

coures:{{student.coures}}

--------------------------

.....


text:
Q: Captive portal with android hotspot programmatically configured Is there a way to build on top of a WEP Wifi configuration a Captive portal?
The hotspot is started using this code:
How to programmatically create and read WEP/EAP WiFi configurations in Android?
The idea is to ask a user for a login before actually sharing the data connection.


text:
Q: remove comment from view using AJAX rails I have a directory app that has comments. I add and delete comments with remote: true and I want to fade them out in my view with Jquery.
How do I go about getting a reference to the comment I want to fade out in the view? I can delete the comment just fine, but I don't know how to fade the comment out in my view
Here is my controller:
class CommentsController < ApplicationController
  def create
    business = Business.find(params[:business_id])
    new_comment = business.comments.create
    new_comment.comment = params[:comment_text]
    new_comment.save
    respond_to do |format|
      format.html {redirect_to business}
      format.js
    end
  end

  def destroy
    business = Business.find(params[:business])
    comment = Comment.find(params[:id])
    comment.destroy!
    params[:id] = business.id
    respond_to do |format|
      format.html {redirect_to business_url(id: params[:id])}
      format.js
    end
  end
end

Comments are rendered in my business view like this:

 Reviews

    <% if !@business.comments.empty? %>
      <% @business.comments.each do |comment| %>

          <%= render partial: 'comment', locals: {comment: comment, business: @business} %>

      <% end %>
    <% else %>

 No reviews yet...

    <% end %>
    <%= render partial: 'comments_form' %>

my single comment partial:

    <div class="profile-image" style="background: url('<%= business.profile_image_url(:thumb).to_s %>') no-repeat; background-position:center">

<%= comment.title %>

<%= comment.comment %>

    <%= button_to(business_comment_path(@business.id,comment.id), {method: :delete, remote: true, class:"btn btn-danger delete-comment-button pull-right", params:{id: comment.id, business: business.id}} ) do%>

    <% end %>

the form partial to create a new comment:

      <%= form_tag(business_comments_path(@business), html: { id: "comment-form" }, method: 'post', remote: true) do %>

 Write a Review

        <%= text_area_tag(:comment_text,nil, class: "comment-form-input")%>
        <%= hidden_field_tag 'business_id', params[:id] %>
        <%= submit_tag("Comment", class:"btn btn-primary") %>
      <% end %>

If I have a list of comments, how do I delete a specific comment by clicking on the delete link and also have it removed from my view in a fadeout manner?
I have a destroy.js.erb file that gets called, but I don't know how to get a reference to fade out the specific comment.. not sure if I am explaining myself clearly here

A: You could try something like this:
In your comment partial:
<div id="comment_<%= comment.id %>" class="row single-comment vertical-align">

destroy.js.erb:
$('#comment_<%= @comment.id %>').remove();

A: Knockoutjs can do that The "if" binding

A: First step is to make sure that the thing you want to delete has a unique id, and that this id is easy to generate.  I patched AR::Base with an instance method called dom_id for this, which is like so:
def dom_id
  "#{self.class.name.underscore}-#{self.id}"
end

which means if i'm rendering out a list of Foo objects i can do something like
<%= render :partial => "foos/foo", :collection => @foos %>

and in the partial do this
<li id="<%= foo.dom_id %>">
....

and the id will be something like "foo-123".
Now, in my destroy.js.erb action, after deleting a foo object, i know that it's dom id on the page can be got with @foo.dom_id.  To fade it out and delete it i would then do
page << "$('##{@foo.dom_id}').fadeOut('slow', function(){$(this).remove();});"

A: You can use helper dom_id method (docs):

*

*Change
 to <div id="<%= dom_id comment %>"> or add id attribute to div.single-comment

*In js response do $('#<%= dom_id @comment %>').fadeOut();

Another option is to bind to jQuery event like this:
$('body').on('ajax:success', '.delete-comment-button', function(event) {
  $(event.original_target).closest('.single-comment').fadeOut();
})

Then you can just return status 2XX for the delete request


text:
Q: Error : on a null object reference, SavedInstanceState rotation recyclerview I want to create savedInstanceState that will save/keep data when display is rotating landscape or portrait, but it keep crashing when i try to rotate the display, and showing error "on a null object reference,
Here is some code for my Adapter :
public class ListMovieAdapter extends RecyclerView.Adapter<ListMovieAdapter.CardViewViewHolder> {
Context context;
ArrayList<Movie.ResultsBean> listMovie;
ProgressDialog progressBar;

public ListMovieAdapter(Context context, ArrayList<Movie.ResultsBean> listMovie) {
    this.listMovie = listMovie;
    this.context = context;
    progressBar = new ProgressDialog(this.context);
}

public ArrayList<Movie.ResultsBean> getListMovie() {
    return listMovie;
}

public void setListMovie(ArrayList<Movie.ResultsBean> movieList) {
    this.listMovie = movieList;
    notifyDataSetChanged();
}

and here is some of my Fragment code :
public class MovieFragment extends Fragment {
View v;
private RecyclerView myrecyclerview;
private Parcelable mRecyclerState;
private ListMovieAdapter listMovieAdapter;
private ArrayList<Movie> listMovie = new ArrayList<>();
private MutableLiveData<ArrayList<Movie.ResultsBean>> dataMovies = new MutableLiveData<>();
private ProgressDialog progressBar;
public static String BASE_URL = "https://api.themoviedb.org";
public static String CATEGORY = "upcoming";
public static int PAGE = 1;
public static String API_KEY = "ce7feeb6af94d9372180d04db1bc755d";
public static String LANGUAGE = "en-US";
private static final String SAVEINSTANCE_RECYCLERSTATE = "RecyclerState";
private static final String SAVEINSTANCE_LIST = "movielist";

public MovieFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, @Nullable Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.fragment_movie, viewGroup, false);
    myrecyclerview = v.findViewById(R.id.rv_fragmovie);
    myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
    progressBar = new ProgressDialog(getContext());

    if (savedInstanceState == null) {
        fetchJSON();
}else{
    mRecyclerState = savedInstanceState.getParcelable(SAVEINSTANCE_RECYCLERSTATE);
    listMovieAdapter.setListMovie((ArrayList)savedInstanceState.getParcelableArrayList(SAVEINSTANCE_LIST));
    myrecyclerview.getLayoutManager().onRestoreInstanceState(mRecyclerState);
}
    return v;
}

private void fetchJSON() {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    ApiInterface apiInterface = retrofit.create(ApiInterface.class);
    Call<Movie> call = apiInterface.listOfMovie(CATEGORY, API_KEY, LANGUAGE, PAGE);
    call.enqueue(new Callback<Movie>() {

        @Override
        public void onResponse(Call<Movie> call, Response<Movie> response) {
            Movie results = response.body();
            List<Movie.ResultsBean> listMovie = results.getResults();
            ListMovieAdapter listMovieAdapter = new ListMovieAdapter(getContext(),
                    (ArrayList<Movie.ResultsBean>) listMovie);
            myrecyclerview.setAdapter(listMovieAdapter);

        }

        @Override
        public void onFailure(Call<Movie> call, Throwable t) {
            showDialogLoad(false);
            showDialogFail(true);
        }
    });
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    listMovie = new ArrayList<>();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    mRecyclerState = myrecyclerview.getLayoutManager().onSaveInstanceState();
    outState.putParcelable(SAVEINSTANCE_RECYCLERSTATE,mRecyclerState);
    outState.putParcelableArrayList(SAVEINSTANCE_LIST,(ArrayList<? extends Parcelable>) listMovieAdapter.getListMovie());
    super.onSaveInstanceState(outState);
}

and then some error log :
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList com.ilham.mymoviecatalogue.adapter.ListMovieAdapter.getListMovie()' on a null object reference
    at com.ilham.mymoviecatalogue.fragment.MovieFragment.onSaveInstanceState(MovieFragment.java:106)

A: Create a global variables
private static final String SCROLL_POSITION = "SCROLL_POSITION";
private RecyclerView movieGrid;
private GridLayoutManager layoutManager;
For onSaveInstanceState
@Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putInt(SCROLL_POSITION, ((LinearLayoutManager)movieGrid.getLayoutManager()).findFirstVisibleItemPosition());
        }

Then below that add:
@Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        final int position = savedInstanceState.getInt(SCROLL_POSITION);
        movieGrid.postDelayed(new Runnable() {
            public void run() {
                movieGrid.scrollToPosition(position);
            }
        }, 300);
    }

Note, the last number 300 should be adjusted accordingly, to test if it is returning to the position you were last in instead of resetting your position to the top upon rotation.


text:
Q: Solving Delay PDE I'm trying to numerically solve the following delay PDE:
$$
    \frac{\partial}{\partial t}  f(x,t) = \int_{x+1}^\infty f(y, t) \hspace{0.2em} dy
$$
given the initial conditions
$$
    f(x,0) = 0, \hspace{1em} \lim_{t \to 0} \int_0^\infty x f(x,t) \hspace{0.1em} dx = 1
$$
I tried NDSolve:
pde := D[f[x, t], t] == Integrate[f[y, t], {y, x + 1, Infinity}]
ic = {f[x, 0] == 0, Integrate[x*f[x, 0], {x, 0, Infinity}] == 1}
NDSolve[{pde, ic}, f, {x, 0, 1}, {t, 0, 1}]

but it doesn't support delay PDEs (NDSolve: Delay partial differential equations are not currently supported by NDSolve). I did see some creative answers to other posts with delay PDEs, so I was hoping that there might be a clever workaround in my case too? Thanks.
Note: Just for clarity, the equation that I'm ultimately interested in numerically solving is equation 2 from Krapivsky (1992). There is an analytic solution outlined there, but that fails if I modify the PDE in any way (which I would like to do), so I'd like a numerical solution. I figured that posting that full piecewise equation might be off-putting, hence putting a reduced version above.


text:
Q: Switching between multiple forms in C# I'm developing a C# (compact framework) app which and I need to have 3 forms. I can go from form1 (main) to form2, and from form1 to form3. I also want to be able to switch from form2 to form3. Form3 must be always the same (I need to create it when app starts and close it when app ends).
On form1, on "Go to form 2" button
form2.Show(); form2.BringToFront();

On form1, on "Go to form 3" button
form3.Show(); form3.BringToFront();

On form2, on "Back to form 1"
this.Hide();

On form3, on "Back to form 1"
this.Hide();

But how to switch from form2 to form3 ?
Thank you for any help!

A: I think there's a multi part solution here.

*

*First, if your form3 is a "global" form and should not be re-instantiated, then you should store that off as a static internal variable somewhere for easy reference.

*When form1 opens form2, you should hook into the FormClosed event.

*In form2, when the user clicks the button (or whatever) close the form2.

*In your event handler, for FormClosed, reshow the global form3.

A: Thanks for the all the contributions! I ended up building a flexible solution that can be extended to many forms.
When the app starts I create all the required forms. I have an auxiliary class with a (global) variable that holds the current active form (I've used an int but it could be a string with the form name).
static class GlobalClass
{
    private static int m_currentActiveForm = 1;

    public static int currentActiveForm
    {
        get { return m_currentActiveForm; }
        set { m_currentActiveForm = value; }
    }
}

On form1 I have included a timer that checks every 100ms the var currentActiveForm. When a change is detected the corresponding form is displayed.
private void timer2_Tick(object sender, EventArgs e)
    {

        if (GlobalClass.currentActiveForm != lastActiveForm)
        {
            switch (GlobalClass.currentActiveForm)
            {
                case 1:
                    form2.Hide();
                    form3.Hide();
                    this.BringToFront();
                    break;
                case 2:
                    form2.Show();
                    form2.BringToFront();
                    break;
                case 3:
                    form3.Show();
                    form3.BringToFront();
                    break;
             }
       }
}

Then, on any form, to switch to a new form, I just need to assign a new value to GlobalClass.currentActiveForm which is visible in all forms.

A: On form2, click "Go to form 3" button
form3.Show();

On form3, click "Back to form 2" button
this.Hide();


text:
Q: How to print stack trace of an exception in a velocity template How to print the complete stack trace of the exception using a velocity template
My present template has $exception as template variable, which contains the exception.

A: In velocity this is how i solved this problem.

#foreach ($i in [1..3])
   #if($exception.Cause)
           #set($exception = $exception.Cause)
           #foreach($stack in $exception.getStackTrace())
               $stack.toString()
           #end
    #end
#end

A: In case you want to display the trace on the output you could wrap the evaluate method inside try-catch-finally block. In catch write the stack trace or just the message of the exception to the writer. In the finally section just flush the writer.
Something like this if I remember right:
StringWriter w = new StringWriter();
try {
    Velocity.evaluate( context, w, "mystring", s );
} catch (Exceptions... e)
    w.write(e.getMessage());
} finally {
    w.flush();
}


text:
Q: AutoFixture: how to CreateAnonymous from a System.Type I need to create an object from AutoFixture using nothing more than a System.Type.  However, there doesn't appear to be an overload of CreateAnonymous() that simply takes a type.  They all expect a compile time generic T.  Is there a way to convert a System.Type to T?
Edit with usage details:
I'm using AutoMapper, which has a hook for injecting components to support complex mapping scenarios:
void ConstructServicesUsing(System.Func<Type,object> constructor)

As you can see from the signature, clients can register a Func which AutoMapper invokes anytime it needs an injected service (mostly ValueResolver implementations).
In production builds, this method calls into my StructureMap container to retrieve a component.  However, when unit testing my mapping code, I must provide stub implementations otherwise AutoMapper throws an exception.   Since I'm using AutoFixture + Moq as my automocking container, it seems natural to let AF new up a fully hydrated stub, so I can concentrate on writing unit test code.

A: It's possible, but intentionally hidden, since you should very rarely need to do this:
var specimen = new SpecimenContext(fixture).Resolve(type);

There are tons of extensibility points in AutoFixture that, more often than not, provide a better alternative than a weakly typed Create method. What are you trying to accomplish?

A: You have to use reflection to create the correct MethodInfo and call it. See this answer on how to do that: How to call generic method with a given Type object?


text:
Q: profvis in R causing a fatal error I am currently trying to optimize a fairly lengthy function foo.  The internal function calls are mostly lapply and sapply on xts data.
I am using assertthat and testthat inside of these functions in attempt to debug and verify data being produced and passed.
The function runs outside of profvis perfectly fine, and the result is as expected.  None of my asserts fail nor do any of the tests.
However, when I wrap the identical call of foo in profvis(foo(args)), I am getting:

"R encountered a fatal error.  The session was terminated"

When I run the function with debugging on stepping through line by line, nested call by nested call, the place where it FATALS keeps changing.  This makes me think there is something wrong with my installation, or some idiosyncratic issues with the new builds/packages I'm using.  Or possibly my system.
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252 LC_NUMERIC=C                           LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_3.4.0 tools_3.4.0

UPDATE 1
When I call the function on my linux VM inside of profvis, it doesn't experience the same error as on the windows machine, so I presume it's one of the updates I have deployed in some package over the past weeks.  If anyone else has experienced similar issues and found a resolution, any help is appreciated before I wipe the R windows installation clean.
UPDATE 2
After uninstalling all of the packages associated with R, and only installing the necessary ones, the problem still exists sporadically.  It is able to run once fine, but then fails every successive time with the following errors:

*

*"Error: Unable to establish connection with R session"

*"R encountered a fatal error. The session was terminated"

A: The solution I resorted to was archiving all user installed packages and reinstalling only the ones that foo was dependent on.  I presume some recent package update that I had previously installed was causing namespace issues.  I restarted my machine and it has appeared to clear up the issue.  Will update this thread if the issue resurfaces.


text:
Q: Is it possible to tell sed to perform the subsequent subsitutions if the first one fails? I can pass a variable to sed substitution command as following:
$ myvar=helloworld
$ sed -r "s/$myvar/hellofoo/g; s/foo/bar/g" <(echo helloworld foo)
hellobar bar

But if the variable is empty, it fails:
$ myvar=
$ sed -r "s/$myvar/hellofoo/g; s/foo/bar/g" <(echo helloworld foo)
sed: -e expression #1, char 0: no previous regular expression

Is it possible to just skip the first substitution, and perform the second one? I'd like to have an output similar to this:
$ myvar=
$ sed -r "s/$myvar/hellofoo/g; s/foo/bar/g" <(echo helloworld foo)
helloworld bar

A: Since // reuses the last regular expression, you can prepend your sed program with an innocuous command that uses a regex that won't ever match anything:
$ myvar=
$ sed -r "/$^/ =; s/$myvar/hellofoo/g; s/foo/bar/g" <(echo helloworld foo)
helloworld bar

A: You could switch to awk
awk -v var="$myvar" '(var!=""){gsub(var,"hellofoo")}{gsub("foo","bar")}1' <(echo helloworld foo)


text:
Q: Is it possible to insert a dynamic link into an email using only JavaScript and no HTML? (Using Google Script to sent the email) Need to preface this with an edit, I'm not using Javascript in the actual email. I'm using Javascript in Google Script which I run to send the email.
I don't really know anything about using html/js in emails, but my roommate needed help inserting a dynamic link using JavaScript into his email using Google Sheets (a .gs file), so I found the code to do it, but the problem is the JavaScript still uses HTML for the dynamic link.
What I found was this
var str = "TEXT FOR LINK"
var link = str.link("http://LINKGOESHERE")

Running this works perfectly as it should. However, the rest of his email was entirely JavaScript, so JavaScript used this code to insert the following HTML code:
TEXT FOR LINK

Since we are running this as a .gs file (Google Sheets), I was wondering if there was a way of just inserting the dynamic link without using any HTML at all, or if we simply need to wrap everything in HTML (and if so, how does that work with an email being sent by running a .gs file).
Here is what the .gs file looks like with the main text and info replaced with gibberish:
function sendEmails() {
var str = "TEXT FOR LINK"
var link = str.link("http://LINKGOESHERE")

var senderEmail = 'SOMEONESEMAILADDRESS@email.com';
link.onclick = function() {
    this.href = "mailto:"+senderEmail;
};
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;
  var numRows = sheet.getLastRow()-1;
  var dataRange = sheet.getRange(startRow, 1, numRows, 2);
  var data = dataRange.getValues();

  var sender = 'MyName';
  var body = '\n\nTEXT BLABLABLABLABLA'+link+' TEXTBLABLABLABLA';
  var subject = 'SUBJECT';
  var options = {replyTo: senderEmail , from: senderEmail, name: sender};

  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var emailAddress = row[0];
    var firstName = row[1];
    var message = 'Hi ' + firstName + ',' + body;

    MailApp.sendEmail(emailAddress, subject, message, options);
  }
}

A: You should not use javascript inside your emails. Most email clients do not allow execution of javascript since it is a strong security vulnerability. Some email clients like Outlook for example allowed it, but I am not sure if it still does or not.
Well even if there exists a client that runs javascript, sending emails with javascript is a huge red flag and your emails will be mostly rejected by mail servers.


text:
Q: Use a javascript var in function - order issue I am having issues with the order of my javascript, I'm sure this is very easy:
I want to check what a variable is (using an if statement), and then set it either from another var, or from the value in a txt file
So far I can load the file, and set the var (I can check it in the console) successfully
However the later parts of the script do not wait for the var to be set, so the var is not used, resulting in an error for the var "cleanTradeDate"
My question is, is the below correct or should I be structuring the var differently. How do I make the subsequent code wait/use the "cleanTradeDate" value?
Here is a sample of the code:
var URLTradeDate = document.URL.substring(document.URL.search('tradeDate=') + 10, document.URL.search('tradeDate=') + 22);
var cleanTradeDate;
$(document).ready(function () {
if (URLTradeDate == '') {
    $.get('data/0.max_trade_date.txt', function(maxTradeDate) {
        cleanTradeDate = maxTradeDate.replace(/[\n\r]+/g, '');
    });
} else {
    cleanTradeDate = URLTradeDate;
}

$("#datepicker").datepicker({dateFormat: 'yy-mm-dd'});
$("#datepicker").datepicker('setDate', cleanTradeDate);
});

A: It's not where the variable is declared, but that it's filled asynchronously. You better use promises:
$(document).ready(function () {
    var index = location.search.indexOf('tradeDate=');
    var URLTradeDate = location.search.slice(index + 10, index + 22);
    var promise = (index == -1 || URLTradeDate == '')
      ? $.get('data/0.max_trade_date.txt').then(function(maxTradeDate) {
            return maxTradeDate.replace(/[\n\r]+/g, '');
        });
      : $.when(URLTradeDate);
    promise.then(function(cleanTradeDate) {
        $("#datepicker").datepicker({dateFormat: 'yy-mm-dd'});
        $("#datepicker").datepicker('setDate', cleanTradeDate);
    });
});

A: $.get is asynchronous (meaning the code doesn't wait for it to finish before carrying on), so you'll want something more like:
var URLTradeDate = document.URL.substring(document.URL.search('tradeDate=') + 10, document.URL.search('tradeDate=') + 22);
$(document).ready(function () {
    if (URLTradeDate == '') {
        $.get('data/0.max_trade_date.txt', function(maxTradeDate) {
            setTradeDate(maxTradeDate);
        });
    } else {
        setTradeDate(URLTradeDate);
    }
});

function setTradeDate(tradeDate){
    tradeDate = tradeDate.replace(/[\n\r]+/g, '');
    $("#datepicker").datepicker({dateFormat: 'yy-mm-dd'});
    $("#datepicker").datepicker('setDate', tradeDate);
}

This way once the data is received from the $.get, you call a function 'setTradeDate' that sets the datepicker.
EDIT: moved the formatting of maxTradeDate inside the setTradeDate function and fixed a couple of errors I noticed.


text:
Q: WPF binding works only once I'm developing a C# project in which I've to use WPF and I'm encountering some problems with binding dynamic content to UI.
Briefly, I have this textBlock here declared in a file called NotifyIconResources.xaml:
<TextBlock Name="label_stato" Text="{Binding Source={x:Static Application.Current}, Path=Properties[status]}"/>

It shows the value of a string property, called status, declared in App.xaml.cs:
public partial class App : Application, INotifyPropertyChanged
{
    private MainWindow mw;

    private TaskbarIcon notifyIcon;

    public event PropertyChangedEventHandler PropertyChanged;

    private string _status;
    private string status
    {
        get
        {
            return _status;
        }
        set
        {
            _status = value;
            NotifyPropertyChanged("status");
        }
    }

    /// <summary>
    /// Triggers a GUI update on a property change
    /// </summary>
    /// <param name="propertyName"></param>
    private void NotifyPropertyChanged(string propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        this.Properties["status"] = "Online";

        //create the notifyicon (it's a resource declared in NotifyIconResources.xaml
        ResourceDictionary rd = new ResourceDictionary
        {
            Source = new Uri("/NotifyIconResources.xaml", UriKind.RelativeOrAbsolute)
        };
        notifyIcon = (TaskbarIcon)rd["NotifyIcon"];

        mw = new MainWindow(Environment.GetCommandLineArgs()[1]);
        mw.Show();
    }
}

The value of the property is dynamic, its initial value is showed in the textBlock, but the next modifications of its value don't result in a refresh of the textBlock content.
NotifyIconResources.xaml is declared in App.xaml:
<Application x:Class="FileSharingOnLAN.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:FileSharingOnLAN"
         StartupUri="MainWindow.xaml"
         ShutdownMode="OnExplicitShutdown">
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="NotifyIconResources.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
<Application.MainWindow>
    <NavigationWindow Source="MainWindow.xaml" Visibility="Visible"></NavigationWindow>
</Application.MainWindow>

The NotifyIconResources.xaml file:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:FileSharingOnLAN"
                xmlns:tb="http://www.hardcodet.net/taskbar">

<tb:TaskbarIcon x:Key="NotifyIcon"
                IconSource="/Red.ico"
                ToolTipText="Click for popup, right-click for menu"
                ContextMenu="{StaticResource SysTrayMenu}">
    <tb:TaskbarIcon.TrayPopup>
        <Border
            Background="Black"
            Width="200"
            Height="100">
            <StackPanel>
                <Button
                Content="{Binding ButtonContent}"
                VerticalAlignment="Top"
                Command="{Binding ShowImpostazioniWindowCommand}"/>
                <Border
                    Background="Blue"
                    Width="100"
                    Height="50"
                    VerticalAlignment="Bottom"
                    HorizontalAlignment="Left">
                    <StackPanel>
                        <Label
                            Content="Stato" />
                        <!--<Button
                            Content="{Binding Path="status", Source="{x:Static Application.Current}"}"
                            Command="{Binding StatusClickedCommand}"/>-->
                        <TextBlock Name="label_stato" Text="{Binding Source={x:Static Application.Current}, Path=Properties[status]}"/>
                    </StackPanel>
                </Border>
            </StackPanel>
        </Border>
    </tb:TaskbarIcon.TrayPopup>

    <tb:TaskbarIcon.DataContext>
        <local:NotifyIconViewModel />
    </tb:TaskbarIcon.DataContext>
</tb:TaskbarIcon>

I've tried to fix it by using OnpropertyChanged, like in this: Binding to change the property but it didn't work.
In the same project I use other binding techniques which work and I know how to solve this problem programmatically but I want to understand where my error is, I'm totally stuck with it.

A: You have few things that needs to be changed:
First one is status property it self, make it public:
public string Status
{
    get
    {
        return (string)this.Properties["status"];
    }
    set
    {
        this.Properties["status"] = value;
        NotifyPropertyChanged("Status");
    }
}

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    Status = "Online";
    ...
}

And change your binding to:
<TextBlock Text="{Binding Source={x:Static Application.Current}, Path=Status}" />

Working Example:
<Window x:Class="WpfApplicationTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplicationTest"
        mc:Ignorable="d"
        x:Name="win"
        Title="MainWindow" Height="300" Width="300">
    <Window.Resources>
    </Window.Resources>
    <StackPanel FocusManager.FocusedElement="{Binding ElementName=btnDefault}">
        <TextBox Text="{Binding Source={x:Static Application.Current}, Path=Status}" />
        <TextBlock Text="{Binding Source={x:Static Application.Current}, Path=Status}" />
        <Button>Button 7</Button>
    </StackPanel>
</Window>

A: Found a working solution.
I was changing the value of the property in another cs module like this:
Application.Current.Properties["status"] = "Offline";
This line cannot result in a modification of the property, so I wasn't modifying it. So, thanks to https://stackoverflow.com/a/1609155/10173298, I solved it by substituting that line with:
((App)Application.Current).setOffline();

Where setOffline() is a method I've added to App.xaml.cs:
public void setOffline()
{
    this.Status = "Offline";
}


text:
Q: VR : Player rotated the wrong way in store GUI We are in great need of assistance:
When we move the player from our scene into the VR: Google Store GUI (Desert scene)
No matter how we rotate or reset the position of the player before the desert loads, the message box (with confirm button) ALWAYS spawn behind the player.
This forces the player to always rotate around 180 to interact with the confirm button.
We are out of ideas...
Greatful for any help!
Thanks.


text:
Q: How to use Images Python API correctly to display an avatar with user comments? This is a follow up question to my previous question. I am trying to upload and display an image as an avatar following the sample app here.
This is the code I am using:
In upload.py I have:
from google.appengine.api import images

class Upload(webapp.RequestHandler):
    def get(self):
    self.response.out.write("""
          <form action="/avatar-save" enctype="multipart/form-data" method="post">

Avatar:

<input type="file" name="img"/>

          </form>

      """)

class AvatarSave(webapp.RequestHandler):
    def post(self):
        avatar = images.resize(self.request.get("img"), 32, 32)
        greeting.avatar = db.Blob(avatar)
        greeting.put()
        self.redirect('/')

application = webapp.WSGIApplication(
                                 [('/upload', Upload),
                                  ('/avatar-save', AvatarSave),
                                  ],
                                 debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

My first question is: How do I check that AvatarSave actually saves the image to datastore?
I try to display the image in hw.py:
class MainPage(webapp.RequestHandler):
    def get(self):
    siteUser = users.get_current_user()
    greeting = None
    if siteUser:
        greeting = ("Welcome, %s! (sign out)" %
                    (siteUser.nickname(), users.create_logout_url("/")))
    else:
        greeting = ("Sign in or register" %
                    users.create_login_url("/"))

    self.response.out.write(greeting)

    query = User.all()
    query.order("-userScore")
    results = query.fetch(10)
    self.response.out.write("""

""")
    for result in results:
        self.response.out.write("
")
        self.response.out.write("%s %s " % (result.userName, result.userLatestComment))
        self.response.out.write("
" % result.key())
        self.response.out.write("
")
    self.response.out.write("
")

class Image (webapp.RequestHandler):
    def get(self):
        greeting = db.get(self.request.get("img_id"))
        if greeting.avatar:
            self.response.headers['Content-Type'] = "image/png"
            self.response.out.write(greeting.avatar)
    else:
        self.response.out.write("No image")

application = webapp.WSGIApplication(
                                 [('/', MainPage),
                                  ('/img', Image),
                                  ],
                                 debug=True)

But all I get is the broken image link icon for each line displayed. (I have 8 lines displayed.)
In the Logs I see this:
INFO     2010-12-04 01:03:57,641 dev_appserver.py:3283] "GET / HTTP/1.1" 200 -
INFO     2010-12-04 01:03:57,703 dev_appserver.py:3283] "GET /img?img_id=ag1oZWxsby0xLXdvcmxkcgoLEgRVc2VyGBMM HTTP/1.1" 200 -
INFO     2010-12-04 01:03:57,756 dev_appserver.py:3283] "GET /img?img_id=ag1oZWxsby0xLXdvcmxkcgoLEgRVc2VyGBUM HTTP/1.1" 200 -
INFO     2010-12-04 01:03:58,734 dev_appserver.py:3283] "GET /img?img_id=ag1oZWxsby0xLXdvcmxkcgoLEgRVc2VyGBIM HTTP/1.1" 200 -
INFO     2010-12-04 01:03:58,812 dev_appserver.py:3283] "GET /img?img_id=ag1oZWxsby0xLXdvcmxkcgoLEgRVc2VyGFkM HTTP/1.1" 200 -
INFO     2010-12-04 01:03:58,878 dev_appserver.py:3283] "GET /img?img_id=ag1oZWxsby0xLXdvcmxkcgoLEgRVc2VyGFsM HTTP/1.1" 200 -
INFO     2010-12-04 01:03:58,934 dev_appserver.py:3283] "GET /img?img_id=ag1oZWxsby0xLXdvcmxkcgoLEgRVc2VyGFoM HTTP/1.1" 200 -
INFO     2010-12-04 01:03:58,986 dev_appserver.py:3283] "GET /img?img_id=ag1oZWxsby0xLXdvcmxkcgoLEgRVc2VyGGkM HTTP/1.1" 200 -
INFO     2010-12-04 01:03:59,040 dev_appserver.py:3283] "GET /img?img_id=ag1oZWxsby0xLXdvcmxkcgoLEgRVc2VyGGwM HTTP/1.1" 200 -
INFO     2010-12-04 01:04:00,102 dev_appserver.py:3283] "GET /favicon.ico HTTP/1.1" 200 -

As far as I understand, some images are fetched from the datastore; but I uploaded only 1 image (or I thought I did) but according to the logs the id for each image is different.
Can anyone help me understand what is going on here; and how to fix it? Many thanks for your help.

Update
In response to Ben's answer I updated the code like this:
This is the model I am using:
class User(db.Model):
    userEmail = db.StringProperty()
    ....
    avatar = db.BlobProperty()

and this is new AvatarSave:
class AvatarSave(webapp.RequestHandler):
    def post(self):
        q = User.all()
        q.filter("userEmail =", "az@example.com")
        qTable = q.fetch(1)
        if qTable:
            for row in qTable:
            avatar = images.resize(self.request.get("img"), 32, 32)
            row.avatar = db.Blob(avatar)
            db.put(qTable)
        else:
            self.response.out.write("user not found")

        self.redirect('/')

I believe this now updates the avatar of the user associated with the userEmail "az@example.com". Is this correct?
I updated hw.py to display only this user as well:
query = User.all()
    query.filter("userEmail =", "az@example.com")
    results = query.fetch(1)
    self.response.out.write("""

""")
    for result in results:
        self.response.out.write("
")
        self.response.out.write("%s %s " % (result.userName, result.userLatestComment))
        self.response.out.write("
" % result.key())
        self.response.out.write("
")
    self.response.out.write("
")

But there is still a problem because instead of displaying the image, I get "None" and the image link is broken.
Furthermore, when I look at the Datastore Viewer, I don't see the "avatar" column. But I see that some blob was updated at some point:
Entity Kind: __BlobUploadSession__
Key: ag10ZWxs....
ID: 125
Key Name:
creation: 1291388993.27
state: init
success_path: /upload

Not sure what is going on here and how to fix it. Any suggestion will be welcome.

A: In the log, you're seeing different image IDs because you're requesting up to 10 user objects from the Datastore, and the Datastore query is looking for the users regardless of whether or not they have an image stored (maybe you made 8 User objects in the course of testing).
As to why the avatars aren't saving:
class AvatarSave(webapp.RequestHandler):
    def post(self):
        avatar = images.resize(self.request.get("img"), 32, 32)
        greeting.avatar = db.Blob(avatar)

Unless some code is missing from your example, the "greeting" variable is not set here.  You have to first create a new greeting (by making a new instance of whatever model it uses) or load the appropriate one, then set the avatar to it, then greeting.put()
Update
If your code is indented like:
    qTable = q.fetch(1)
    if qTable:
        for row in qTable:
        avatar = images.resize(self.request.get("img"), 32, 32)
        row.avatar = db.Blob(avatar)
        db.put(qTable)

It will not work.  What you want is probably:
    qTable = q.fetch(1)
    if qTable:
        for row in qTable:
            avatar = images.resize(self.request.get("img"), 32, 32)
            row.avatar = db.Blob(avatar)
        db.put(qTable)

But since you're working with only one object here, it would be simpler to replace your current use of fetch(1) and instead do:
    currentUser = q.get()
    if currentUser is not None:
        avatar = images.resize(self.request.get("img"), 32, 32)
        currentUser.avatar = db.Blob(avatar)
        currentUser.put()


text:
Q: Custom Listview(or Adapter) that allows updating a row instead of adding one. (Android) I have a listview.
Now, i'm using switch-case, where i'm comparing getView() method's position with an id obtained from the server in the form of JSON response.
Suppose the id is myobjectarraylist.get(poisition).getIDForComparison.
Myadapter.java
 ArrayList<MyObject> myobjectarraylist;
        int counter = 0;
     @Override
            public View getView(final int position, View convertView, ViewGroup parent) {

        switch(myobjectarraylist.get(poisition).getIDForComparison){

        case x:

        if (myobjectarraylist.get(position).getIDForComparison) == myobjectarraylist.get(nextposition).getIDForComparison){
        "update the same row by concatenating new text with the exisiting"
        }
        else{
        "insert next row"
        }

        }
    }

So, basically i need to keep collecting the information from my json object in the same row until the myobjectarraylist.get(poisition).getIDForComparison is same for current and next position. if not, i want to allow the addition of a new row.

A: Logic processing should never be done inside the getView Method as it is called multiple random times which leads to inconsistency in the conditionals returning false even though it is a truthy statement.
Assuming that your MyAdapter.java extends BaseAdapter
There are two other methods in the BaseAdapter that can be overridden

*

*BaseAdapter.getViewTypeCount()

*BaseAdapter.getItemViewType(int position)
Your logic should be placed inside getItemViewType(int position), and the corresponding view modifications should be done inside it.
getViewTypeCount() - Returns the number of types of Views that will be created by getView(int, View, ViewGroup). Each type represents a set of views that can be converted in getView(int, View, ViewGroup). If the adapter always returns the same type of View for all items, this method should return 1
Hope this helps


text:
Q: How to Print all the columns in silverlight datagrid Im having 17 columns of datagrid in Silverlight. How can we print all columns in datagrid to print. Since there are more noumber of column, Im enabling Horizantal Scroolbar ,so tht user can scrollto lastcolumn easily.
During printing of silverligt datagrid, i could see contents which are shown in Silverlight Page , anything beyond scroll bar ,those images are cropped and not printed . Any solution for print all columns in datagrid even though beyond the screen width.
One more question, if i have datagrid with horizontal scrollbar enabled, datagrid.actualwidth always give 768 px but not from first column to last column width size
_mahens

A: If you can wait six months for Silverlight 5, then you can completely control the print layout and format it exactly the way you want. Until then I'm not sure if there is anything you can do.

A: You basically have 2 options here.

*

*Shrink your datagrid using Scaling to make the whole grid fit on your page

*Slice the grid into 2 grids (first half of the columns in the first grid, and the other half on the other), then print this as 2 separate pages. Of course you would have to take into account the height of the grid and print additional pages there as well if required.
Difficult? Yes, but achievable :)


text:
Q: adding select all functionality to checkboxes in knockoutjs I'm using checkboxes dynamically generated similar to below code..

      <input type="checkbox" data-bind="checkedValue: itemValue, checked: $root.itemsChecked" />
      <input data-bind="value: itemValue, valueUpdate: 'afterkeydown'" />

I would like to add a button which when pressed would select all checkboxes.
All help is sincerely appreciated.
Thanks

A: You can use another checkbox with a ko.computed to do this, , see in the example this approach:

var checkVm = function(data){
    this.itemValue = ko.observable(data);
};

var viewModel = function() {
  this.items = ko.observableArray([new checkVm("test 1"),new checkVm("test 2")]);
  this.selectedItems = ko.observableArray([]);
  this.selectAllCheck = ko.computed({
      read:function(){
        return this.selectedItems().length == this.items().length;
      },
      write: function(val){
        if(val)
           this.selectedItems(this.items().map(function(item){return item.itemValue();}))
        else
           this.selectedItems.removeAll();
      },
      owner:this
  });
}

ko.applyBindings(new viewModel());

      <input type="checkbox" data-bind="checked: selectAllCheck" />
      Select all

      <input type="checkbox" data-bind="checkedValue: itemValue, checked: $root.selectedItems" />
      <input data-bind="textInput: itemValue" />

 Selected:


text:
Q: How to give "Infinity" as width in Windows 10 for wpf controls I recently updated to Windows 10. I am getting error with controls where width is specified as Infinity.
Below is my code:
 <Grid>
    <StackPanel x:Name="StackPanel1" MaxWidth="500" FlowDirection="RightToLeft" Orientation="Horizontal">
                        <Button ............./>

    </StackPanel>
    <i:Interaction.Triggers>
                        <bases:DataTrigger Binding="{Binding ElementName=control1, Path=Visibility}" Value="Collapsed">
                            <ei:ChangePropertyAction TargetObject="{Binding ElementName=StackPanel1}" PropertyName="MaxWidth" Value="500"/>
                        </bases:DataTrigger>
                        <bases:DataTrigger Binding="{Binding ElementName=control1, Path=Visibility}" Value="Visible">
                            <ei:ChangePropertyAction TargetObject="{Binding ElementName=StackPanel1}" PropertyName="MaxWidth" Value="Infinity"/>
                        </bases:DataTrigger>
      </i:Interaction.Triggers>
</Grid>

It was working fine and still works fine in windows 7/8/8.1, I have upgraded to windows 10 and getting error that "Infinity is not a valid value for Double."
Any Idea?

A: I found one alternative:
 Value="{x:Static system:Double.PositiveInfinity}"

If someone knows anything else please let me know :)


text:
Q: in bash, how to quickly replace a number in a file? my terraform tf file, one line has:
green_nodes_asg_instance_count = 0

I want to replace it with $blue_nodes_asg_instance_count = 3, the result should be:
green_nodes_asg_instance_count = 3

I tried this but does not work:
sed -i 's/\(.*\)green_nodes_asg_instance_count\(.*\)=\(.*\)0/\1green_nodes_asg_instance_count\2=\3\$blue_nodes_asg_instance_count/g' test.tf

A: *

*It's useless to include \(.*\) at the beginning of a pattern just to replace it by itself.

*The same applies for the second and third group. You replace them by themselves

*You also replace green_nodes_asg_instance_count by green_nodes_asg_instance_count. Again not very helpful

If you want to turn
green_nodes_asg_instance_count = 0

into
green_nodes_asg_instance_count = 3

Then change nothing but the 0 with
sed '/green_nodes_asg_instance_count *= *0/s/0/3/' test.tf

*

*/green_nodes_asg_instance_count *= *0/ is an address, which means the following command is executed only on lines that match the regular expression. I added * after the whitespaces to make any number of whitespaces optional

*s/0/3/ substitutes the 0 with your replacement

A: I'd do:
perl -pi -e 's{\bgreen_nodes_asg_instance_count\s*=\s*\K.*}{3}' your-file

To change everything after green_nodes_asg_instance_count<optional-whitespace>=<optional-whitespace> to 3 (and provided that it's not following a word character to avoid replacing it in olive_green_nodes_asg_instance_count = 123 for instance).
That should be more portable than using the non-standard -i extension of sed (with incompatible behaviour between implementations that support it), and means you can use the more advanced PCRE than sed's default BRE.


text:
Q: probability over 3 values with dependency At the exercise, there is no information that B and C are independent, but with logical reasoning, there must be a pendency.
The problem is, I can not create a connection with depency of B and C, is that even possible and if yes, how and I calculate this?
My current approach:
$$
A=rain; B=wet; C=sun \\
$$
Given values:
$$
P(A)=0.44; P(B|A)=0.99, P(B|\bar A)=0.1 \\
P(C|A)=0.05; P(C|\bar A)=0.7
$$
P(B) can be calculated with the law of total probability:
$$
P(B)= P(B|A) \cdot P(A)+P(B|\bar A)\cdot P(\bar A) \\
P(B)= 0.99 \cdot 0.44+0.1\cdot 0.56 \approx 0.49 \\
P(\bar B)= 1-P(B) \approx 0.51 \\
$$
Bayes' theorem:
$$
P(A|B)= \frac {P(B|A)P(A)}{P(B)} \\
= \frac{0.99*0.44}{0.49} \approx 0.89 \\
P(C)= P(C|A) \cdot P(A)+P(C|\bar A) \cdot P(\bar A) \\
P(C)= 0.05 \cdot 0.44+0.7 \cdot 0.56 \approx 0.41 \\
P(\bar B \cap C) = P(\bar B) \cdot P(C)=0.51\cdot 0.41 \approx 0.21 \\
$$
$P(\bar B \cap C)$ can not be calculated as above if depency exist
target:
$$
P(A|\bar B \cap C)=?
$$
I hope someone can help me with that problem, thanks.

A: Assuming this is a Bayesian network problem, events $B,C$ are dependent, but given $A$, are conditionally independent. So you can find $P(A\mid \bar B\cap C)$ as follows:
\begin{eqnarray*}
P(A\mid \bar B\cap C) &=& \dfrac{P(A\cap\bar B\cap C)}{P(\bar B\cap C)} \\
&=& \dfrac{P(A\cap\bar B\cap C)}{P(A\cap\bar B\cap C) + P(\bar A\cap\bar B\cap C)} \\
&& \\
P(A\cap\bar B\cap C) &=& P(\bar B\mid A)P(C\mid A)P(A)\qquad\qquad\text{(using Chain Rule)} \\
&=& 0.01\cdot 0.05\cdot 0.44 \;=\; 0.00022 \\
&& \\
P(\bar A\cap\bar B\cap C) &=& P(\bar B\mid \bar A)P(C\mid \bar A)P(\bar A) \\
&=& 0.9\cdot 0.7\cdot 0.56 \;=\;0.3528 \\
&& \\
\therefore\quad P(A\mid \bar B\cap C) &=& 0.00022 / 0.35302 \approx 0.000623.
\end{eqnarray*}


text:
Q: One FB application to more than one FB Page I want to add a an FB application to more than one FB Page.After the user's authentication , rediraction to my application's url I can't find a way for the application to know the page which the request was made. Thank you in advance for your help

A: You will get the page id in the signed request.
FYI: Signed Request

A: This is pretty easy to do. If you decode the signed_request data POSTed to your page, you can see what page is 'looking' at your app (i.e. which page the app has been installed on).
If you decode the data (e.g. in PHP you can do: print_r( $facebook->getSignedRequest() ); to print the decoded version), you will see something like:
Array
(
    ...
    [page] => Array
        (
            [id] => 1234567890
            [liked] => 1
            [admin] => 1
        )
    [user] => Array
        (
            ...
        )
)

The $response['page']['id'] is the ID of the Page that is looking at your app at that moment. You can store the IDs of the page that have installed your app, and check it with this to determine which content to load up.


text:
Q: Can MAX485 be connected to SN75176 for RS485 communication? In one side I have an SN75176 and the other side is MAX485. Can both be connected for RS485 communication?

A: They are both RS-485 transceivers.
Assumption is that two RS-485 transceivers can be connected together for communication.


text:
Q: Airflow - creating dynamic Tasks from XCOM I'm attempting to generate a set of dynamic tasks from a XCOM variable.  In the XCOM I'm storing a list and I want to use each element of the list to dynamically create a downstream task.
My use case is that I have an upstream operator that checks a sftp server for files and returns a list of file names matching specific criteria.  I want to create dynamic downstream tasks for each of the file names returned.
I've simplified it to the below, and while it works I feel like its not an idiomatic airflow solution.  In my use case, I would write a python function that's called from a python operator that pulls the value from xcom and returns it, instead of using the pusher function.
I understand that while I can create a custom operator that combines both  I don't think creating a throwaway operator is good practice and I'm hoping there's another solution.
from airflow.operators.python_operator import PythonOperator
from airflow.operators.bash_operator import BashOperator
from airflow import DAG
from datetime import datetime, timedelta

default_args = {
    "owner": "test",
    "depends_on_past": False,
    "start_date": datetime(2018, 10, 27),
    "email": ["test@mctest.com"],
    "email_on_failure": False,
    "email_on_retry": False,
    "email_on_success": False,
    "retries": 0,
    "provide_context": True
}

dag = DAG("test",  default_args=default_args, schedule_interval="@daily", catchup=False)

def pusher(**context):
    return ['a', 'b', 'c', 'd', 'e']

pusher_task = PythonOperator(
    task_id='pusher_task',
    dag=dag,
    python_callable=pusher
)

def bash_wrapper(task, **context):
    return BashOperator(
        task_id='dynamic'+task,
        dag=dag,
        bash_command='date'
    )

end = BashOperator(task_id='end', dag=dag, bash_command='echo task has ended')

pusher_task >> [bash_wrapper(task) for task in pusher()] >> end

A: I wouldn't do what you're trying to achieve mainly because:

*

*XCOM value is a state generated in runtime

*DAG structure is something determined in parse time
Even if you use something like the following to get an access to XCOM values generated by some upstream task:
from airflow.models import TaskInstance
from airflow.utils.db import provide_session

dag = DAG(...)

@provide_session
def get_files_list(session):
    execution_date = dag.previous_schedule(datetime.now())

    // Find previous task instance:
    ti = session.query(TaskInstance).filter(
        TaskInstance.dag_id == dag.dag_id,
        TaskInstance.execution_date == execution_date,
        TaskInstance.task_id == upstream_task_id).first()
    if ti:
        files_list = ti.xcom_pull()
        if files_list:
            return files_list
    // Return default state:
    return {...}

files_list = get_files_list()
// Generate tasks based on upstream task state:
task = PythonOperator(
    ...
    xcom_push=True,
    dag=dag)

But this would behave very strangely, because DAG parsing and task execution are not synchronised in a way you wish.
If the main reason you want to do this is parallelising files processing, I'd have some static number of processing tasks (determined by the required parallelism) that read files list from upstream task's XCOM value and operate on a relevant portion of that list.
Another option is parallelising files processing using some framework for distributed computations like Apache Spark.

A: The simplest way I can think of is to use a branch operator.
https://github.com/apache/airflow/blob/master/airflow/example_dags/example_branch_operator.py


text:
Q: NameError wile add config.action_view.embed_authenticity_token_in_remote_forms to true I was working on ajax on my rails app and I got a ActionController::InvalidAuthenticityToken error.
and I read this

config.action_view.embed_authenticity_token_in_remote_forms allows you
  to set the default behavior for authenticity_token in forms with
  remote: true. By default it's set to false, which means that remote
  forms will not include authenticity_token, which is helpful when
  you're fragment-caching the form. Remote forms get the authenticity
  from the meta tag, so embedding is unnecessary unless you support
  browsers without JavaScript. In such case you can either pass
  authenticity_token: true as a form option or set this config setting
  to true.

from RailsGuides
so  I add config.action_view.embed_authenticity_token_in_remote_forms=true to \config\application.rb
and restart rails server ,then an error happened
/Users/haha/railsbridge/railsfun/ruby12weeks/eat/config/application.rb:5:in': undefined local variable or method config' for main:Object (NameError)
Did I put it to wrong place?
this is my github

A: That line or any config line should be inside Application class, that is after line 12 and before line 16 in your github code


text:
Q: Parsley.js Submit form not working when using addAsyncValidator and remote I have a registration form split into blocks that was working perfectly using this code based on one of the examples from the website:
            $('.register-next').on('click', function () {
            var current = $(this).data('currentBlock'),
            next = $(this).data('nextBlock');

            console.log('current block = ' + current);
            console.log('next block = ' + next);
            // only validate going forward. If current group is invalid, do not go further
            // .parsley().validate() returns validation result AND show errors
            if (next > current)
              if (false === $('#form-register').parsley().validate('block' + current))
                return;

                // validation was ok. We can go on next step.
                $('.block' + current)
                  .removeClass('show')
                  .addClass('hidden');

                $('.block' + next)
                  .removeClass('hidden')
                  .addClass('show');
        });

I then wanted to add an additional ajax validation to the last block of the code to make sure that the username was not already taken.  I have the check working but the problems is that the form will now not submit when the validation checks are passed.  Clicking on the submit button just calls the remote function again.
I am assuming that I have to reassign the function of the submit button once all validation checks have been made?
The ID username relates to the input field in the last block of my form.
Thanks
            $('#username').parsley().addAsyncValidator(
          'validateUsername', function (xhr) {
               var UserLogin = $('#username').parsley();

               window.ParsleyUI.removeError(UserLogin,'errorUsername');

               if(xhr.status == '200'){

                    console.log("in 200");
                    return;
               }

               if(xhr.status == '404'){
                    response = $.parseJSON(xhr.responseText);
                    console.log("username exists");
                    window.ParsleyUI.addError(UserLogin,'errorUsername',response.error);
               }
          }, 'inc/check_username.php'
        );

A: I finally got this working.  There is probably a far easier way to do it but this works.
firstly, I made one mistake with my code, I needed to return true if the status was 200
$('#username').parsley().addAsyncValidator(
          'validateUsername', function (xhr) {
               var UserLogin = $('#username').parsley();

               window.ParsleyUI.removeError(UserLogin,'errorUsername');

               if(xhr.status == '200'){

                    return true;
               }

               if(xhr.status == '404'){
                    response = $.parseJSON(xhr.responseText);
                    console.log("username exists");
                    window.ParsleyUI.addError(UserLogin,'errorUsername',response.error);
               }
          }, 'inc/check_username.php'
        );

I then added an additional piece of code to listen for the submit button to be clicked and remove parsley validation from the form before using javascript to submit
$('#new-user-submit').click(function(){

            $('#form-register').parsley().asyncValidate()
                .done(function(){
                    $('#form-register').parsley().destroy();
                    $('#form-register').submit(); });
});

I'm not a big user of javascript so it normally takes me a while to work my way through these things but I thought with parsley being so popular there would be far better support and documentation for it.


text:
Q: Tailscale - Can't connect to LAN of the exit node I have an exit node, that's configured like this:
tailscale up --advertise-exit-node --advertise-routes=192.168.0.0/24
The route shows up on admin page, I've enabled it. I use the client like this:
tailscale up --exit-node=thatnode --exit-node-allow-lan-access
However even though requests to the internet work fine through the exit node (I see its IP on a checker site), when I open 192.168.0.1 I still get my local service.
How do I open exit node's 192.168.0.1?

A: Thanks to the Tailscale support, I've been able to fix this by changing the route to 192.168.0.1/32


text:
Q: Angular 2 Routing from another branch (sub-route) I have segmented my code into different folders such as
/posts
/events
/users

under each folder, there's a list component, a row component, and a detail component. the list will display the row component, when clicked, will load the detail component. using the segmented router feature of Angular 2, they all work, within their own folder/tree.
however, the row components of posts and events, will also load the user row component as well, in hope that when the user click on it, it will lead to the user detail page. but i can't work that out in the RouterConfig.
anybody knows how this should be accomplished? thanx
as requested, bellow is a sniplet
app component
@RouteConfig([
    { path: './posts/...', name: 'Posts', component: PostsComponent },
    { path: './users/...', name: 'Users', component: UsersComponent }
])

post component
@RouteConfig([
    { path: '/', name: 'PostList', component: PostListComponent },
    { path: '/:id', name: 'PostDetail', component: PostDetailComponent }
])

user component
@RouteConfig([
    { path: '/', name: 'UserList', component: UserListComponent },
    { path: '/:id', name: 'UserDetail', component: UserDetailComponent }
])

user list component
import {UserCardComponent} from './userCard.component';

@Component({
    selector: 'my-page',
    template: `
<card *ngFor="#user of userList" [user]="user"></card>
    `,
    directives: [
        userCardComponent
    ],
    providers: [
        UserService
    ]
})

user card component
@Component({
    selector: 'card',
    template: `
<section (click)="onNavigate($event)">{{user.name}}</section>
    `,
})

export class UserCardComponent {
    @Input user;

    constructor(
        private _router: Router,
        private _routeParams: RouteParams) {
    }

    onNavigate($event) {
        this._router.navigate(['UserDetail', {id: this.user.id.toString() }]);
    }
}

post detail component
import {UserCardComponent} from '../users/userCard.component';

@Component({
    selector: 'page',
    template: `
<card [user]="post.user"></card>
`,
    directives: [
        UserCardComponent
    ]

export class PostDetailComponent {
};

So everything shows up okay, but, when PostDetailComponent is displayed, click on the UserCardComponent, I get an error
Component "PostDetailComponent" has no route config.

So, the question is, how do I configure the router so I can go directly from /posts/:id to /users/:id

A: Add a / as prefix to the route name to indicate it's an absolute route
 this._router.navigate(['/User', {id: this.user.id.toString() }]);


text:
Q: Web site web.config error? I don't know what this error means:

it is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.

Can someone tell me what this error means and how to fix it?
EDIT: Also, when I click on the error, it brings me to this line of code in the web.config: <authentication mode="Windows" />

A: As the error is telling you, you need to mark your virtual directory / website as an Application in IIS Manager.


text:
Q: On load jquery not working Hi I have jqgrid which on resize trigger a function so that it resizes according to window size. This function fine but I need that same function to work when the jqgrid loads
so I am calling the function like this
$(window).bind("load", function() {
     $('#' + grid_id).setGridWidth(width, true); //Back to original width
    $('#' + grid_id).setGridWidth($('#' + div_id).width(), true); //Resized to new width as per window
    });

But it is not working.
The same function is called when the window is resized like this
$(window).bind('resize', function () {
            $('#' + grid_id).setGridWidth(width, true); //Back to original width
            $('#' + grid_id).setGridWidth($('#' + div_id).width(), true); //Resized to new width as per window
        }).trigger('resize');

And it works fine. What is wrong am I doing here.

A: You can call setGridWidth method of jqGrid only after the grid is created.
I suppose that you need to do is probably adding the option autowidth: true.
If you want to implement your own custom resizing then you can do it inside of jqGridAfterLoadComplete event. The code could be about the following:
var $grid = $("#grid"),
    resizeGrid = function () {
        var newWidth = $(this).closest(".ui-jqgrid").parent().width();
        $(this).jqGrid("setGridWidth", newWidth, true);
    };

$(window).on("resize", function() {
    resizeGrid.call($grid);
});

$grid.on("jqGridAfterLoadComplete", resizeGrid)
.jqGrid({
    // all jqGrid options
});

See https://jsfiddle.net/OlegKi/ejpn9/153/

A: I allways used "DOMContentLoaded" event and It worked like a charm.
Please Try:
 element.addEventListener("DOMContentLoaded", function(event) {
    //Element loaded
  });


text:
Q: Finding out closest date from today I have defined $today = current system date.
Objective: To find out the value of closest "date" element from today and get the corresponding "price_per_share" value based on below xml. FYI, it does not matter whether the date is in past or in future when calculating the "closest date".
How do I do this?
I was thinking of

*

*Calculating the difference between today and each "date" value

*Then adding "difference" as the child of "details" for each "details" node

*Then sort by the smallest "duration"

*Then extract the first occurrence of "price_per_share" value.

But somehow adding a child does not seem to work for me either.
<test_record>
<details>
    <date>2013-01-16</date>
    <currency>USD</currency>
    <shares>48</shares>
    <price_per_share>20</price_per_share>
</details>
<details>
    <date>2018-05-28</date>
    <currency>USD</currency>
    <shares>49</shares>
    <price_per_share>30</price_per_share>
</details>
<details>
    <date>2018-10-25</date>
    <currency>USD</currency>
    <shares>50</shares>
    <price_per_share>40</price_per_share>
</details>
<details>
    <date>2018-05-02</date>
    <currency>USD</currency>
    <shares>51</shares>
    <price_per_share>60</price_per_share>
</details>

Can't use "map" as I am restricted to use xquery 1.0.

A: The steps you describe sound good, except for the second one. There is no need to append anything as you don't actually want to modify the nodes. In fact, you can't do this with XQuery alone (XQuery Update is another specification which is intended for this). Also, there is no need to use a map here. Your logic sounds like you know procedural programming, but the concept of a functional programming language (XQuery being one) is quite different, so you might want to familiarize yourself with it.
Regarding you question: You first calculate the difference between the date and todays date. As you said it shouldn't matter whether this is in the past or the future, so we have to calculate the absolute value of the duration. To do this we first divide by seconds and thus get the number of seconds for this duration. As we now have a number we can get the absolute value in $abs-diff. We then order by this value, get the first element of the sequence and return price_per_share
let $today := fn:current-date()
return (
  for $detail in //details
  let $diff := xs:date($detail/date) - $today
  let $abs-diff := abs($diff div xs:dayTimeDuration('PT1S'))
  order by $abs-diff
  return $detail
)[1]/price_per_share


text:
Q: php flattening to parent when sub array contains only one element with numeric index I am trying to move child array data to parent, if it contains only one element and parent array key is numeric. I do not want to flatten it completely. I want to keep structure of the array. None of the child arrays should have numeric keys, except the top one.
My input data:
[8] => Array
    (
        [any] => Array
            (
                [0] => Array
                    (
                        [all] => Array
                            (
                                [0] => stdClass Object
                                    (
                                        [f] => test1

                                    )

                                [1] => Array
                                    (
                                        [0] => Array
                                            (
                                                [any] => Array
                                                    (
                                                        [0] => Array
                                                            (
                                                                [all] => Array
                                                                    (
                                                                        [0] => stdClass Object
                                                                            (
                                                                                [f] => test2

                                                                            )

                                                                        [1] => stdClass Object
                                                                            (
                                                                                [f] => test3

                                                                            )

                                                                    )

                                                            )

                                                    )

                                            )

                                    )

                            )

                    )

            )

    )

)
My Desired output :
[8] => Array
                    (
                        [any] => Array
                            (
                                [all] => Array
                                    (
                                        [0] => stdClass Object
                                            (
                                                [f] => test1

                                            )

                                        [any] => Array
                                                    (
                                                        [all] => Array
                                                            (
                                                                [0] => stdClass Object
                                                                    (
                                                                        [f] => test2

                                                                    )

                                                                [1] => stdClass Object
                                                                    (
                                                                        [f] => test3

                                                                    )

                                                            )

                                                    )

                                            )

                                    )

                            )

                    )

I am trying to work with multidimensional arrays.
I tried the following function.
  public function flattenKeyZero(&$arr)    {

        foreach ($arr as $k => &$v) {

            if (is_array($v)) {

                if ( (count($v) == 1 && is_numeric(key($v)) )    ) { // Check count and key if numeric; Check count and parent array contains only all or any
                    $arr[$k] = reset($v);                      // Return child array by reset
                }else {
                    $this->flattenKeyZero($v);
                }

                }
            }

        }

          do {
            $temp = $arr;
            $this->flattenKeyZero($arr);
        }while ($temp != $arr ) ;

I got the following output. Everything looks good except I could not modify it to meet the condition "
None of the child arrays should have numeric keys"
  [8] => Array
                    (
                        [any] => Array
                            (
                                [all] => Array
                                    (
                                        [0] => stdClass Object
                                            (
                                                [f] => test

                                            )

                                        [1] => Array
                                            (
                                                [any] => Array
                                                    (
                                                        [all] => Array
                                                            (
                                                                [0] => stdClass Object
                                                                    (
                                                                        [f] => test

                                                                    )

                                                                [1] => stdClass Object
                                                                    (
                                                                        [f] => test

                                                                    )

                                                            )

                                                    )

                                            )

                                    )

                            )

                    )

            )

I also tried add additional elseif condition,but it doesn't seem to work..
   elseif((is_numeric($k) && (key($v) == 'all' || key($v) == 'any') && count($v) == 1 )){                 // if all or any are under numeric index array , remove numeric index array and move a level up
                    $arr[key($v)] = reset($v);
                }

A: One way is by using reset() after checking for count and if is_numeric
foreach ($arr as $key => $value) {
    if (count($value) == 1 && is_numeric(key($value))) { // Check count and key if numeric
        $arr[$key] = reset($value);                      // Return child array by reset
    }
}

print_r($arr);


text:
Q: Total work zero along the virtual displacement I'm having some trouble understanding virtual work and displacement, especially a particular section of Goldstein. I'll use an example to explain my difficulty, but I realize this might be the product of misunderstanding of virtual displacement.
Consider a pendulum whose length $\ell(t)$ varies as a function of time. It has two degrees of freedom: one along the rod, and one along its angular position; we can describe this system with generalized/polar-plane coordinates $r$ and $\phi$ and thus the constraint is holonomic.
As it swings, both $\phi(t)$ and $\ell(t)$ change and thus the displacement $d\mathbf{r}$ is not perpendicular to the constraint force of the rod. However, the virtual displacement $\delta \mathbf{r}$ points along the direction of angular motion, i.e., perpendicular to the rod at all times. Therefore we can dissect the displacement as
$$ d\mathbf{r} = \delta\mathbf{r} + \Delta\mathbf{r},$$
where $\Delta \mathbf{r}$ is a displacement along the direction of the rod, such that $||\Delta \mathbf{r}|| = \Delta \ell$ in that instant of time ($dt = 0$). We saw this decomposition also in this physics.SE answer on virtual displacement.
Now in Goldstein (section 1.4, p. 17) we have the claim
$$ \sum_{i} \mathbf{F}_i \cdot \delta\mathbf{r}_i = 0,$$
where $\mathbf{F}_i = \mathbf{F}_{a,i} + \mathbf{f}_i$ is the total force, $\mathbf{F}_{a,i}$ is the applied force, and  $\mathbf{f}_i$ is the constraint force.
Thus we could expand our sum for every $i$th particle to see that
$$ \sum_i \left[ \left(\mathbf{F}_{a,i} \cdot \delta\mathbf{r}_i\right) +  \left(\mathbf{f}_i \cdot \delta\mathbf{r}_i\right)\right] = 0.$$
And this is zero by Goldstein's claim that the system in equilibrium. It is easy for me to see that $\mathbf{f}_i \cdot \Delta\mathbf{r}_i$ is nonzero because those vectors are parallel, and likewise that $\mathbf{f}_i \cdot \delta\mathbf{r}_i = 0$ because these vectors are orthogonal.
However, it is not clear to me (at least geometrically) why the other scalar product involving $\mathbf{F}_{a,i}$ is zero. Is this just a glorified statement of energy conservation? How does the original sum (a single term in my example) evaluate to zero for the pendulum?

A: Reading through the section you mention it is clear that Goldstein is using two assumptions to derive your last equation.
(1) The particles are in equilibrium, so that the total force each is zero.  Literally, $\mathbf{F}_i = 0$ for all $i$.  So your second equation is trivially true.
(2) Next, he restricts the derivation to systems for which (his italics) "the net virtual work of forces of constraint is zero."  In other words, $\mathbf{f}_i \cdot \delta\mathbf{r}_i=0$ for all $i$.
As a consequence of these assumptions, you find that the virtual work of the applied forces is also zero, which is mathematically evident from your post.
This isn't a glorified statement of the conservation of energy.  It is a simple mathematical fact that the dot product of a zero vector and any other vector is zero.  You are going at the derivation in the wrong direction where you are trying to derive Godlstein's Equation 1.40 from his equation 1.43, when in fact you need to be working the other way.
Further, your pendulum example is probably not a good example in this case because the bob is not in equilibrium.  If it is oscillating then there is a net force on it.  It isn't clear from your description of the system what is going on, but if you can draw a free body diagram, enumerate the forces and find that $\mathbf{F} \ne 0$, then you are violating the assumptions that go in to the derivation.


text:
Q: Parse error for one row (all the other rows work!) I have set up a function that should update formulas based on the contents of a cell.  The code runs, however, for one row I keep getting a parse error message.  A snippet of the code is below:
ta2020 = ctlSheet.getRange("B19:K19");
efg2020 = ctlSheet.getRange("B20:K20");
decTA2020 = ctlSheet.getRange("B21:K21");
fft502020 = ctlSheet.getRange("B23:K23");

ta2020.setFormula("=countifs(Subject20,$B$1,Ethnicity2020,$b$3,TA_20,B$18");
efg2020.setFormula("=countifs(Subject20,$B$1,Ethnicity2020,$B$3,EFG_20,B$18)");
decTA2020.setFormula("=countifs(Subject20,$B$1,Ethnicity2020,$B$3,DecMock_20,B$18)");
fft502020.setFormula("=countifs(Subject20,$B$1,Ethnicity2020,$b$3,FFT50_20,B$18)");

The offending line is the ta2020.setFormula one.  All the other lines are fine, however, for this one the cell reference does not seem to update as it moves on to the next column so cell c19 should read =countifs(Subject20,$B$1,Ethnicity2020,$b$3,TA_20,C$18, however, it seems to be stuck on =countifs(Subject20,$B$1,Ethnicity2020,$b$3,TA_20,B$18.
Any help would be appreciated.
Thanks

A: You are missing a ) bracket
The correct syntax would be
ta2020.setFormula("=countifs(Subject20,$B$1,Ethnicity2020,$b$3,TA_20,B$18)");