text:
Q: Architecture diagram explaining the Ubuntu Cloud Infrastructure with MAAS / Openstack architecture? I'm interested in Ubuntu Cloud Infrastructure with MAAS (based on Openstack from what I understand) but cannot find any architecture diagram which gives an overview of how MAAS works.
The case is Ubuntu Cloud Infrastructure with MAAS.
It requires at least 10 nodes (as described in Installing Ubuntu Cloud Infrastructure) and this "10 MAAS nodes architecture" would typically be a perfect candidate for an architecture diagram!
Wouldn't it be an easy/reality-based way to understand how MAAS works and what it offers?
Looking for docs, I stumbled upon a technical and up-to-date documentation with architecture diagrams(!): Revisiting OpenStack Architecture: Essex Edition

Could we imagine that an architecture diagram and/or description could be provided to easily understand how a minimal 10 nodes Ubuntu Cloud Infrastructure with MAAS installation works?

A: if someone deploys maas+juju for openstack, please run juju status --format=png > architecture.png

A: I am in the process of designing a system to deploy MaaS/Juju/Openstack/juju-jitsu.  The diagram below displays the architecture that I think is necessary for the minimum install as specified by the docs.  I have also been working on a juju overview document found here.

Note 1: I found this thread useful in determining the configuration for the 6 MaaS node architecture.  To get the 10 node based architecture, the diagram can be expanded to have one server per node.
Note 2: For the 6 node architecture, the minimum number of physical computers is 7.
Note 3: For the 10 node architecture, the minimum number of physical computers is: 11.


text:
Q: How can I prevent a re-render error in my functional component? I am new to using React Hooks with stateless components. I usually use stateful components when I have to use state. My present app requires the context API which could only be used in functional Components. I have rewritten most of the code I need to work but one brings an error "Error: Too many re-renders. React limits the number of renders to prevent an infinite loop."
The Component I am trying to convert to a functional one
class pizzas extends Component {
  state ={
    pizzas: [
      {id:1, name: 'Chicken Curry', ingredients: 'Red onions, bell peppers, chicken, pineapple, mozzarella, tomato sauce, curry, chili peppers', price: '3100', image: chickenCurry },
      {id:2, name: 'Pepperoni Fresh', ingredients: 'Pepperoni, mozzarella, green peppers, pizza sauce', price: '2700', image: pepperoniFresh },
      {id:3, name: 'Chicken BBQ', ingredients: 'Chicken, red onions, corn, mozzarella, bbq sauce, tomato sauce', price: '2700', image: chickenBbq },
      {id:4, name: 'Shawarma Pizza', ingredients: 'Mayonnaise & ketchup, spicy chicken, red onions, tomatoes, mozzarella', price: '3100', image: sharwarmaPizza },
      {id:5, name: 'Chicken Suya', ingredients: 'Mayonnaise, spicy sauce, spicy chicken, bell peppers, red onions, suya sauce, tomato sauce, mozzarella, suya spice', price: '2700', image: chickenSuya },
      {id:6, name: 'Pepperoni', ingredients: 'Pepperoni, mozzarella, tomato sauce', price: '2700', image: pepperoni },
      {id:7, name: 'Beef Suya', ingredients: 'Mayonnaise, spicy sauce, spicy meatballs, bell peppers, red onions, mozzarella, suya sauce, tomato sauce, suya spice', price: '2700', image: beefSuya },
      {id:8, name: 'Chicken Supreme', ingredients: 'Spicy sauce, chicken and spicy chicken, mushrooms, bell peppers, olives, red onions, mozzarella, tomato sauce', price: '3100', image: chickenSupreme },
      {id:9, name: 'Sweet Chili Chicken', ingredients: 'Spicy sauce, chicken, chili pepper, mozzarella, sweet chili sauce, tomato sauce', price: '2700', image: chickenCurry },
      {id:10, name: 'Spicy Mixed Pizza', ingredients: 'Spicy sauce, spicy meatballs, spicy chicken, chili pepper, corn, mozzarella, buffalo sauce, tomato sauce', price: '3100', image: spicyMixedPizza },
      {id:11, name: 'Margherita', ingredients: 'Mozarella, tomato sauce', price: '2200', image: margherita },
      {id:12, name: 'Super Meaty', ingredients: 'Chicken, pepperonni, sausages, mozzarella, tomato sauce', price: '3100', image: superMeaty },
      {id:13, name: 'Cheesy Chicken', ingredients: 'Chicken, tomatoes, cheddar, mozzarella, cheese sauce', price: '2700', image: cheesyChicken },
      {id:14, name: 'Cheeseburger Pizza', ingredients: 'Beef, tomatoes, red onions, cheddar, mozzarella, mayonnaise & ketchup, tomato sauce', price: '3100', image: cheeseBurger },
      {id:15, name: 'Meaty Overload', ingredients: 'Spicy sauce, pepperonni, spicy meatballs, chicken, sausages, mozzarella, tomato sauce', price: '3400', image: meatyOverload },
      {id:16, name: 'Meaty BBQ', ingredients: 'Beef, pepperonni, sausages, mozzarella, bbq sauce, tomato sauce', price: '3100', image: meatyBbq },
      {id:17, name: 'Hawaiian', ingredients: 'Chicken, pineapple, mozzarella, sweet chili sauce, tomato sauce', price: '2700', image: hawaiian },
      {id:18, name: 'Veggie Overload', ingredients: 'Mushrooms, bell peppers, corn, olives, red onions, tomatoes, mozzarella, tomato sauce', price: '3100', image: veggieOverload }
    ],
    showModal: false,
    selectedPizza: null,
    orders: []

  }
  toggleModalHandler = (p)=>{
    this.setState({showModal: !this.state.showModal, selectedPizza: p});

  }
  addToOrders = (productName, productIngredients, productPrice, productImage, p)=>{
    this.setState(prevState=>({
      orders: [...prevState.orders, productImage, productName, productIngredients, productPrice]
    }))
  }
  render(){
  const pizza = this.state.pizzas;

  return (
   <Aux>
     { this.state.showModal?
       <Backdrop clicked={this.toggleModalHandler}/>: null}
   { this.state.showModal ?

     <Modal
     clicked={this.toggleModalHandler}
     sendRequest={this.sendingRequestHandler}
     ingredients={this.state.selectedPizza.ingredients}
     price={this.state.selectedPizza.price}
     image={this.state.selectedPizza.image}
     name={this.state.selectedPizza.name}
     key={this.state.pizzas.id}
     addToOrders={this.addToOrders}/>: null}

Pizza

         {pizza.map(p=>{

    return

{p.name}

{p.ingredients}

from ₦{p.price}

           <button onClick={()=>this.toggleModalHandler(p)}>Select</button>

  })}

  </Aux>
  )

}
}
export default pizzas;

What I have done so far
const Pizzas = () => {

  const [showModal, setModal] = useState(false);
  const [selectedPizza, setSelectedPizza] = useState(null)
  const { pizzaproducts } = useContext(ProductsContext)
  const toggleModalHandler = (p) => {
    setModal(true);
    setSelectedPizza(p)
  }
  return (
    <Aux>
      {setModal(true) ?
        <Backdrop clicked={toggleModalHandler} /> : null}
      {setModal(true) ?
        <Modal
          clicked={toggleModalHandler}
          ingredients={selectedPizza.ingredients}
          price={selectedPizza.price}
          image={selectedPizza.image}
          name={selectedPizza.name}
        /> : null}

Pizza

          {pizzaproducts.map(p => {

            return

{p.name}

{p.ingredients}

from ₦{p.price}

                  <button onClick={() => toggleModalHandler(p)}>Select</button>

          })}

    </Aux>
  )
}
export default Pizzas;

How best can I convert this? I am guessing this error is from the togglemodalhandler. I am new to hooks.

A: You shouldn't set state inside the template. This triggers re-render, what again, trigger setting state and next...
Try something like this:
import React, { useState, useContext } from 'react';

const Pizzas = () => {

    const [showModal, setModal] = useState(false);
    const [selectedPizza, setSelectedPizza] = useState(null)
    const { pizzaproducts } = useContext(ProductsContext)
    const toggleModalHandler = (p) => {
        setModal(true);
        setSelectedPizza(p)
    };
    return (
        <Aux>
            {showModal ? <Backdrop clicked={toggleModalHandler} /> : null}

            {showModal ?
                <Modal
                    clicked={toggleModalHandler}
                    ingredients={selectedPizza.ingredients}
                    price={selectedPizza.price}
                    image={selectedPizza.image}
                    name={selectedPizza.name}
                /> : null}

Pizza

                    {pizzaproducts.map(p => {

                        return

{p.name}

{p.ingredients}

from ₦{p.price}

                                    <button onClick={() => toggleModalHandler(p)}>Select</button>

                    })}

        </Aux>
    )
}
export default Pizzas;

A: You are conditionally attempting to render using setModal(true)?, which is incorrect, should be showModal?
useState returns a pair of values: the current state and a function that updates it. This is why we write const [showModal, setModal] = useState(). This is similar to this.state.showModal and this.setState in a class, except you get them in a pair.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dojo: Div Tag Issue We are currently using Dojo to create a mobile map application. We're using Esri for the map service. Everything was working before changing from 3.2 to 3.3. The map works fine but I'm having issues implementing a base map gallery. I've done research for days trying to figure out why my gallery wasn't appearing but I've narrowed down my issue to it actually being the layout of my div tags. On my index.html page I have many div tags for different menu's and what not. I've followed all the div tags to make sure they've all been closed and they have.
So this is what I currently have implemented:

With this code, the gallery doesn't show up, but if I move the closing div tags above the div id="galleryDiv" then it the gallery will show up, but it shows up on every page of the application because there is no ending div tag. Also, we were trying to implement buttons that would move the base map images in the gallery from left to right but they only work in google chrome. I wasn't sure why it would only work in Chrome and not any other browser.
I originally had a scrollable view in it but it wouldn't show up at all so I changed it to just mobile.view and it worked. Throughout the application it interchanges view and scrollable views, but from what I've researched, it should all work regardless.
After all the research I've done, I'm pretty sure it has to do with the parent/child relationship with the div tags but I'm not sure why it would keep my gallery from showing up on one page and why when I closed the div tags it shows up. However, if I close the div tag then the gallery shows up on EVERY page.
I appreciate any and all help, ideas, and comments! So... Any ideas?...

A: So what actually ended up being the problem is that the div tag inherited it's own height at 0px. Once we gave it a height, everything showed up just fine. Now why did it give it's own height 0? No idea. Either way, it works now!


text:
Q: Stop Hover effect of an item using JQUERY I have some div elements and each of them have a hover effect applied by CSS. But I don't always want this hover effect; it should only activate under specific conditions.
Now, how can I disable those hover effects using jQuery when my conditions are satisfied? What is the code for disabling hover?  I don't have access to CSS files.

A: you can do this by using
<script>
$("someDiv").hover(function(event) {
//apply some conditions if yes
  event.preventDefault();
else
return true;
});
</script>

Hope this will work for you....
Thanks

A: Just use the jQuery hover instead of the CSS one.
E.g. instead of such CSS:

#Div1:hover { background-color: yellow; }

Have this jQuery:
$("#Div1").hover(function() {
    $(this).css("background-color", "yellow");
}, function() {
    $(this).css("background-color", "");
});

Same effect, and you control the JS code and can have conditions.
Live test case: http://jsfiddle.net/THXuc/

A: You could apply a different class to the div(s) in question, using jquery .hover(). On mousein, apply the class and on mouseout, remove it.


text:
Q: substraction field type time I'm a beginner php-mysql programmer,, and i have some problem,, 1 of them is ....
i have a table "gangguan83" with field
urut_gangguan int(15) -> primary key.
lv int(10),
trip datetime,
masuk datetime,
current int(10),
ens int(10),
....

how can i query if my statement like this :
ens = (lv * 1,73 * 0,9 * current * (masuk-trip))

please help me.
Thanks very much before.

A: SELECT lv * 1.73 * 0.9 * current * (masuk - trip) AS ens
...


text:
Q: Finding lychrel numbers under 10000, logic seems correct but wrong answer? public static void main(String[] args) {
    String numstr="";
    int lychrel=0;
    int sum=0;
    int iterations=0;

for(int num=10;num<10000;num++){
    sum=num;
    iterations=1;
    numstr=sum+reverse(sum)+"";
    while((isPalyndrom(numstr)==false)&&iterations<50){
        sum=sum+reverse(sum);
        numstr=sum+"";
        iterations++;
    }

if (iterations==50)
    lychrel++;
}
System.out.println(lychrel);
}//End of main

The methods reverse and isPalyndrom are 100% correct , but there's something about sum , when I print it out , some negative large numbers appear which is weird .
The final answer of lychrels that is being printed after the execution is 553 ,which is wrong.


text:
Q: Flutter redux combined state dispatch action and update UI issue I am learning redux. I have the following issues:

*

*My initial state does not seem to be taken into the account

*My actions are dispatched but they are not updating the actual state on the UI

I am trying to understand how things work so please be patient with me. I will be grateful to anyone that can help with this as I tried numerous things and I think I am stuck at this point. Thank you for all your kind help and comments.
main.dart file:
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';

//Actions for redux, these are the things we do
enum FirstActions { Increment, Decrement, Reset }
enum SecondActions { Increment, Decrement, Reset }

//The reducer will take the action and create a state
// TODO: 5. update state values
dynamic firstReducer(dynamic state, dynamic action) {

  print('first ${state}');

  switch (action) {
    case FirstActions.Increment:
      state++;
      break;
    case FirstActions.Decrement:
      state--;
      break;
    case FirstActions.Reset:
      state = 0;
      break;
  }

  print('first ${state}');
  return state;
}

dynamic secondReducer(dynamic state, dynamic action) {
  print('second ${state}');
  switch (action) {
    case SecondActions.Increment:
      state++;
      break;
    case SecondActions.Decrement:
      state--;
      break;
    case SecondActions.Reset:
      state = 0;
      break;
  }

  print('second ${state}');
  return state;
}

// Define your State
class AppState {
  final int firstState = 1;
  final int secondState = 2;

  AppState(firstState, secondState);
}

// Combine state
AppState appStateReducer(AppState state, action) => AppState(
    firstReducer(state.firstState, action),
    secondReducer(state.secondState, action)
);

// App store initialization, passing it to the app
void main() {
  AppState combinedInitialState = AppState(3, 4);
  final store = Store<AppState>(appStateReducer, initialState: combinedInitialState);

  runApp(
    MyApp(
      store: store,
    ),
  );
}

//Stateless because redux is handling the state, but we can mix them
class MyApp extends StatelessWidget {
  MyApp({Key? key, required this.store}) : super(key: key);
  final Store<dynamic> store;

  @override
  Widget build(BuildContext context) {
    return StoreProvider<dynamic>(
        store: store,
        child: MaterialApp(
          title: 'Flutter Redux',
          // Start the app with the "/" named route. In this case, the app starts
          // on the FirstScreen widget.
          initialRoute: '/',
          routes: {
            // When navigating to the "/" route, build the FirstScreen widget.
            '/': (context) => FirstScreen(store: store),
            // When navigating to the "/second" route, build the SecondScreen widget.
            '/second': (context) => SecondScreen(store: store),
          },
        ),
    );
  }
}

// TODO: 4. show results
class FirstScreen extends StatelessWidget {
  final Store<dynamic> store;

  const FirstScreen({
    required this.store,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StoreProvider<dynamic>(
        store: store,
        child: Scaffold(
      appBar: AppBar(
        title: const Text('First Screen'),
      ),
      body: Column(
        children: [
          Center(
            child: ElevatedButton(
              // Within the `FirstScreen` widget
              onPressed: () {
                // Navigate to the second screen using a named route.
                Navigator.pushNamed(context, '/second');
              },
              child: const Text('Go to second screen'),
            ),
          ),
          //Make a connector to get the updates when the store changes
          StoreConnector<dynamic, String>(
            converter: (store) => store.state.firstState.toString(),
            builder: (context, count) {
              return Text(
                  count,
                  style: TextStyle(fontSize: 24.0)
              );
            },
          ),

          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              IconButton(icon: Icon(Icons.add), onPressed: ()=> store.dispatch(FirstActions.Increment)),
              IconButton(icon: Icon(Icons.remove), onPressed: ()=> store.dispatch(FirstActions.Decrement)),
            ],
          ),

          StoreConnector<dynamic, String>(
            converter: (store) => store.state.secondState.toString(),
            builder: (context, count) {
              return Text(
                  count,
                  style: TextStyle(fontSize: 24.0)
              );
            },
          ),

          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              IconButton(icon: Icon(Icons.add), onPressed: ()=> store.dispatch(SecondActions.Increment)),
              IconButton(icon: Icon(Icons.remove), onPressed: ()=> store.dispatch(SecondActions.Decrement)),
            ],
          ),
        ],
      ),
        ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  final Store<dynamic> store;

  const SecondScreen({
    required this.store,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StoreProvider<dynamic>(
        store: store,
        child: Scaffold(
      appBar: AppBar(
        title: const Text('Second Screen'),
      ),
      body: Column(
        children: [
          ElevatedButton(
            // Within the SecondScreen widget
            onPressed: () {
              // Navigate back to the first screen by popping the current route
              // off the stack.
              Navigator.pop(context);
            },
            child: const Text('Go back to first screen'),
          ),
          //Make a connector to get the updates when the store changes
          StoreConnector<dynamic, String>(
            converter: (store) => store.state.toString(),
            builder: (context, count) {
              return Text(
                  count,
                  style: TextStyle(fontSize: 24.0)
              );
            },

          ),

          ElevatedButton(
            onPressed: () {
              print('reset hit');
              store.dispatch(FirstActions.Reset);
            },
            child: const Text('Reset'),
          ),

        ],

      ),
        ),
    );
  }
}

A: The problem was in the AppState class, the values should not have been final but should be constructed like this:
// Define your State
class AppState {
  int firstState = 1;
  int secondState = 2;

  AppState(this.firstState, this.secondState);
}


text:
Q: OpenSSL no crypto directory I followed this tutorial to setup self certified SSL on my server.
but I face a problem when I sign the certificate as follows:
openssl ca -in tempreq.pem -out server_crt.pem

tutorial said you will then be prompted to confirm the information in the exampleserver.cnf but I got error as follows:
140394980766144:error:02001002:system library:fopen:No such file or directory:../crypto/bio/bss_file.c:72:fopen('/root/myCA/index.txt','r')
140394980766144:error:2006D080:BIO routines:BIO_new_file:no such file:../crypto/bio/bss_file.c:79:
root@server:~/myCA# export OPENSSL_CONF=/root/myCA/caconfig.cnf

In fact, my server don't have /crypto directory so I search about "crypto" but I coundn't find about information.
How to countinue this tutorial?


text:
Q: Detect when Touch ID is being touched, no authentication I'm wondering if it's possible to detect when a user's finger is touching the home button on the iPhone 5S/6, without necessarily looking for an authentication. I don't need to verify any kind of biometric data, or even access the secure enclave at all, I just want to use it as another sensor on the phone.
In a similar way to how reachability works as of now on the iPhone, I'd want to just detect a touch on the sensor, not a button press.
Any ideas?

A: There is no public API for this. I looked on UIApplication for a private API, and couldn't find one of those either.


text:
Q: GPResult shows different security groups to Active Directory We have a Windows Server 2012/2016 domain.
when i run a gpresult for a user the section 'The user is a part of the following security groups' are different from the 'member of' tab on the users AD properties.
I have tried gpupdate /force and no change occurs. In fact, there seems to be more security groups shown on GPResult (7 to be exact) versus 'Member Tab' only shows 3. And I'm not counting default groups like Domain Users...etc

A: If you changed the group membership for this user, you have to logoff/logon again and then group membership will be updated.
However, the "MemberOf" tab doesn't display nested groups. If your user is member of Group1, and Group1 is member of Group2, you will not see Group2 in the MemberOf tab, but Group2 will be listed in GPResult.


text:
Q: HTML - Pattern for more words I have an input text and i want to put a pattern to use only characters without numbers for name.
I was trying with this but doesn't work. If i write the name he alert me to type the name.

<form method="post" enctype="multipart/form-data">
Persoana de contact* <input type="text" pattern="[A-Za-z]{3,}" class="form-control" name="contact" required="" oninvalid="this.setCustomValidity('Adaugati va rugam numele persoanei de contact.')" oninput="setCustomValidity('')">
<button type = submit>Send</button>
</form>

A:

<form method="post" enctype="multipart/form-data">
Persoana de contact* <input type="text" pattern="[A-Za-z\s]{3,}" class="form-control" name="contact" required="" oninvalid="this.setCustomValidity('Adaugati va rugam numele persoanei de contact.')" oninput="setCustomValidity('')">
<button type = submit>Send</button>
</form>

Was solved! Thanks to Chris G.
The changes to pattern are "pattern="[A-Za-z\s]{3,}". This will help you to type with space bettwen the words and respect the pattern.


text:
Q: How to use useState to only update specific object from array of objects? I just implemented a like-system functionality into my React application but now I've been struggling to change the state of the specific object instead of the whole array of objects..which is the current behaviour.
{post.likes.some(u => u.user == _id) ? (
  <Button
    variant="link"
    size={`sm`}
    className={`mr-1`}
    onClick={() => {removeLike(post._id) ; setIconColor('success') ; setLikes(post.likes.length) }}
  >
    <i className={`fa fa-heart text-${iconColor} like mr-1`}>{likes}
  </Button>
) : (
  <Button
    variant="link"
    size={`sm`}
    className={`mr-1`}
    onClick={() => {addLike(post._id) ; setIconColor('danger') ; setLikes(post.likes.length) }}
  >
    <i className={`fa fa-heart text-${iconColor} like mr-1`}>{likes}
  </Button>
)}

As mentioned before, this is inside a component which runs throuhg the array of objects.
Right now, this is what I have in my component just before the return statement:
const [iconColor, setIconColor] = useState('');
const [likes, setLikes] = useState(0);

If I run it as-is, it updates the state on every single object instead of the object in which I clicked on. This is my actual problem:
useState() updating muliple objects
UPDATE: I'm using redux-thunk also:
// @desc     Like a post
// @route    PUT /api/v1/posts/:id/like
// @access   Private
// @status   DONE
export const addLike = id => async dispatch => {
  try {
    const res = await axios.put(`/api/v1/posts/${id}/like`);

    return dispatch({
      type: UPDATE_LIKES,
      payload: {
        id,
        likes: res.data
      }
    });
  } catch (err) {
    return dispatch({
      type: POST_ERROR,
      payload: { msg: err.response && err.response.statusText, status: err.response && err.response.status }
    });
  }
};

// @desc     Dislike a post
// @route    PUT /api/v1/posts/:id/dislike
// @access   Private
// @status   DONE
export const removeLike = id => async dispatch => {
  try {
    const res = await axios.put(`/api/v1/posts/${id}/dislike`);

    return dispatch({
      type: UPDATE_LIKES,
      payload: {
        id,
        likes: res.data
      }
    });
  } catch (err) {
    return dispatch({
      type: POST_ERROR,
      payload: { msg: err.response && err.response.statusText, status: err.response && err.response.status }
    });
  }
};

Those function then return a dispatch that connects to my reducer:
case UPDATE_LIKES:
  return {
      ...state,
      likes: state.timeline.map((post) =>
        post._id === payload.id && { [post._id]: payload.likes.length }
      ),
      // like: !state.like,
      // likes: console.log(
      //   state.timeline.map(post =>
      //     post._id === payload.id ? { ...post, likes: payload.likes } : post
      //   )
      // ),
      loading: false
  };

A: You'd need to have an array of variable likes. Currently you're just changing the value of same variable many times. Simply have the like array's index same as your parent array's index. Or even better: store the like count inside the object of the post/card.

A: To only update specific object from array of objects, you can try something like:
let stateObj = {
    one: [],
    two: [],
    three: [],
    // and so on
}

So you can get an specific object or array from this big state like:
stateObj.one

and now you can do what ever you want to do with this and once its values are updated just replace it in the original one.

A: You need to track likes for each post. For that you can use some mapping like { post_id: like_count}
So your state will become:
const [likes, setLikes] = useState({});

And click listener will be:
onClick={() => {addLike(post._id) ; setIconColor('danger') ; setLikes({...likes, [post._id]: post.likes.length}) }}

Displaying like count will be:
<i className={`fa fa-heart text-${iconColor} like mr-1`}>{likes[post._id] || 0}

A: I don't think, you need states for this. As far as I understand from your code, you can achieve the same as below.
{post.likes.some(u => u.user == _id) ? (
  <Button
    variant="link"
    size={`sm`}
    className={`mr-1`}
    onClick={() => {removeLike(post._id)}}
  >
    <i className={`fa fa-heart text-danger like mr-1`}>{post.likes.length}
  </Button>
) : (
  <Button
    variant="link"
    size={`sm`}
    className={`mr-1`}
    onClick={() => {addLike(post._id)}}
  >
    <i className={`fa fa-heart text-success like mr-1`}>{post.likes.length}
  </Button>
)}

and your addLike and removeLike functions should update post which will force re-render your component. And hence it should work as expected.


text:
Q: Имя файла в стримах. new File FileReader reader = new FileReader(new File(r.readLine()));
FileReader reader = new FileReader(r.readLine());

Есть ли разница между объявлениями имен для стримов и что нам дает new File().Или же он сам прописывается , если не написали ?

A: Разницы нет, т.к. если посмотреть на коструктор, где передается строка, то увидим следующее:
public FileReader(String fileName) throws FileNotFoundException {
    super(new FileInputStream(fileName));
}

public FileInputStream(String name) throws FileNotFoundException {
    this(name != null ? new File(name) : null);
}

А вот коструктор, где файл
public FileReader(File file) throws FileNotFoundException {
    super(new FileInputStream(file));
}

Как видим, в обоих случаях вызывается один и тот же конструктор у FileInputStream

A: Судя по всему (например, если r у вас является экземпляром BufferedReader), это разные конструкторы: в первом случае это конструктор
FileReader(File file)

а во втором
FileReader(String fileName)

В обоих случаях создаётся новый FileReader, но в первом конструкторе в качестве параметра указывается файл File, а во втором указывается имя файла как строка.


text:
Q: How to add cookies to a drag and drop div Hello i have added a drop and drop feature to my site See Here and as i am a beginner i don't know anything about adding cookies to a page or a div, i would like to have a save button which will save the position of the div so that when a user returns to a page it will be where they left it, any help will be appreciated,

A: Seems you're using jQuery.
Include jquery.cookie.js. You can now set cookies like $.cookie('position_x', 123) and get them like $.cookie('position_x').
The drag-and-drop library should have some callback that is run when you stop dragging. In that callback, save the x and y position away in separate cookies (to keep things simple).
When the page loads, check for those cookies and use the values to position the element.


text:
Q: Blazor server side behind reverse proxy 404 I have a blazor server-side app hosted on IIS behind a reverse proxy (using ARR).
I have tried everything I can think of, but I keep getting 404 on
_framework/blazor.server.js
My base href is is set to "/subsite/":
<base href="/subsite/" />

and all my src values are relative like this:
<script src="_framework/blazor.server.js"></script>
<script src="_content/BlazorInputFile/inputfile.js"></script>
<script src="animations.js"></script>

Every other script ref loads fine, EVEN the _content data, but not the blazor.server.js.
I tried the old PathBase trick for MVC apps as well with no success:
if (!env.IsDevelopment()) {
    app.Use((context, next) => {
        context.Request.PathBase = new PathString("/subsite");
        return next();
    });
}

Can anyone tell me how to make Blazor realize where to put the blazor.server.js in a reverse proxy scenario?

A: Did you try the UsePathBase ?
app.UsePathBase("/subsite");

Here is my test result

Please check this article for more
https://www.billbogaiv.com/posts/net-core-hosted-on-subdirectories-in-nginx

A: From docs.

Rewrite URLs for correct routing
Routing requests for page components in a Blazor WebAssembly app isn't as straightforward as routing requests in a Blazor Server, hosted app. Consider a Blazor WebAssembly app with two components:

*

*Main.razor – Loads at the root of the app and contains a link to the About component (href="About").

*About.razor – About component.

  When the app's default document is requested using the browser's address
  bar (for example, https://www.contoso.com/):

*

*The browser makes a request.

*The default page is returned, which is usually index.html.

*index.html bootstraps the app.

*Blazor's router loads, and the Razor Main component is rendered.

  In the Main page, selecting the link to the About component works on the client because  the Blazor router stops the browser from making a request on the Internet to www.contoso.com for About and serves the rendered About component itself. All of the requests for internal endpoints within the Blazor WebAssembly app work the same way: Requests don't trigger browser-based requests to server-hosted resources on the Internet. The router handles the requests internally.
If a request is made using the browser's address bar for www.contoso.com/About, the request fails. No such resource exists on the app's Internet host, so a 404 - Not Found response is returned.
Because browsers make requests to Internet-based hosts for client-side pages, web servers and hosting services must rewrite all requests for resources not physically on the server to the index.html page. When index.html is returned, the app's Blazor router takes over and responds with the correct resource.
When deploying to an IIS server, you can use the URL Rewrite Module with the app's published web.config file. For more information, see the IIS section.

Maybe you could try to enable the forward proxy in IIS manager->server node->application request routing cache->proxy->enable.
If you only have one website, you could just add the website to ARR server farm and then it will create the routing rule automatically. It will be convenient to monitor the back-end server with health check.
Is this ARR warning causing my 404?


text:
Q: Помощь в написании запроса VK api android Пишу для учебных целей собственный клиент для ВК. В общем, у меня есть запрос, который выводит список друзей с ВК.
Запрос:
VKRequest vkRequest = VKApi.friends().get(VKParameters.from(VKApiConst.FIELDS, "first_name","order","hints"));

Вместо "first_name", что бы я ни писал, всё равно выводит только имя и фамилию. Помогите сделать так, чтобы выводилась еще ссылка на фото пользователя или само фото (в документации вк вроде пишет что только ссылка). Спасибо!

A: Не знаю что такое ваш VKRequest, но самый обычный HTTP-запрос возвращает ровно то, что требуется:

https://api.vk.com/method/friends.get?count=1&user_id=1&fields=photo_50,photo_100,photo_200_orig

Приходит:
{"response":[
 {
  "uid":2,"first_name":"Александра","last_name":"Владимирова",
  "photo_50":"https:\/\/pp.vk.me\/c837424\/v837424002\/7a58\/EXPtAjVvB3Y.jpg",
  "photo_100":"https:\/\/pp.vk.me\/c837424\/v837424002\/7a57\/LPopmL-2n2M.jpg",
  "photo_200_orig":"https:\/\/pp.vk.me\/c837424\/v837424002\/7a56\/moevLzq_O3k.jpg",
  "hidden":1,"user_id":2
 },
]}

A: Попробуйте делать запрос такого вида
final VKRequest vKRequest = new VKRequest("photos.search", VKParameters.from("start time", 1392005288, "end_time", 1479658261)

Где, соответственно "photos.search" - название метода который вам нужен.
"start time" - параметр передаваемый в метод.
1392005288 - значение данного параметра. Ну и так соответственно далее. Переделайте под себя и посмотрите, должно работать


text: Q: Is there a way to use the requirements.txt file when deploying a Django App with Azure CLI? It seems that the requirements.txt file is automatically recognized and executed when using the github continous integration. Would it be possible to do this with Azure CLI?


text:
Q: Spring Boot Health Check - SQS Consumer Is there a Spring Boot Actuator Health Check endpoint for SQS? I have built a SQS consumer and I want to check if SQS is up and running. I am not using JMSlistener for connecting to SQS but rather using Spring Cloud Libraries.
I implemented the below health check endpoint. This returns the below error when I delete the queue and try to hit the health check endpoint. If there is a connectivity issue or if the SQS service goes down , will I be getting a similar error which will eventually cause the health check endpoint to fail?

com.amazonaws.services.sqs.model.QueueDoesNotExistException: The
  specified queue does not exist for this wsdl version. (Service:
  AmazonSQS; Status Code: 400; Error Code:
  AWS.SimpleQueueService.NonExistentQueue; Request ID:
  cd8e205d-dc43-535e-931f-7332733bd16c)

public class SqsQueueHealthIndicator extends AbstractHealthIndicator {

    private final AmazonSQSAsync amazonSQSAsync;
    private final String queueName;

    public SqsQueueHealthIndicator(AmazonSQSAsync amazonSQSAsync, String queueName) {
        this.amazonSQSAsync = amazonSQSAsync;
        this.queueName = queueName;
    }

    @Override
    protected void doHealthCheck(Health.Builder builder) {
        try {
            amazonSQSAsync.getQueueUrl(queueName);
            builder.up();
        } catch (QueueDoesNotExistException e) {
            e.printStackTrace();
            builder.down(e);
        }
    }

}

Beans
@Bean
SqsQueueHealthIndicator queueHealthIndicator(@Autowired AmazonSQSAsync amazonSQSAsync, @Value("${sqs.queueName}") String queueName) {
    return new SqsQueueHealthIndicator(amazonSQSAsync, queueName);
}

@Bean
SqsQueueHealthIndicator deadLetterQueueHealthIndicator(@Autowired AmazonSQSAsync amazonSQSAsync, @Value("${sqs.dlQueueName}") String deadLetterQueueName) {
    return new SqsQueueHealthIndicator(amazonSQSAsync, deadLetterQueueName);
}

A: You have to write a custom health check like below to check your queue exists or not by calling getQueueUrl using AWS Java SDK lib.
    @Component
public class SQSHealthCheck implements HealthIndicator {
    @Override
    public Health health() {
        int errorCode = check(); // perform some specific health check
        if (errorCode != 0) {
            return Health.down()
              .withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }

    public int check() {
        /**
        your logic to check queue exists or not using by calling getQueueUrl . e.g you will get queue url of a queue named "SampleQueue" like https://sqs.us-east-1.amazonaws.com/12XXX56789XXXX/SampleQueue
        **/
        return 0; // 0 or 1 based on result
    }
    }


text:
Q: Does every increasing, super-linear function $f: \Bbb{N} \rightarrow \Bbb{N}$ with large image take a large set to a small set? Suppose $f: \Bbb{N} \rightarrow \Bbb{N}$ is an increasing function from the natural numbers to themselves which satisfies the following two properties:

*

*$f$ grows super-linearly: $$\lim_{n \to \infty} \frac{n}{f(n)} = 0.$$

*The sum of the reciprocals of the values of $f$ diverges: $$\sum_{n=1}^\infty \frac{1}{f(n)} = \infty.$$
Call a subset $A$ of the integers small if $\sum_{a \in A} \frac{1}{a}$ converges, and large if $\sum_{a \in A} \frac{1}{a}$ diverges. Then the image $f(\Bbb{N}) = \{ f(n) \}_{n \in \Bbb{N}}$ is a large set.
Question: Under the above conditions on $f$, must there be a large set $A$ such that $f(A)$ is a small set? That is, does there exist a set $A \subset \Bbb{N}$ so that $\sum_{a \in A} \frac{1}{a}$ diverges, but $\sum_{a \in A} \frac{1}{f(a)}$ converges?
My intuition is "yes" based on thinking about the example $f(n) = p_n$, the nth prime. For that function, letting $A$ be the set of all primes actually works: $$\sum_{n = 1}^\infty \frac{1}{p_n} \text{ diverges but } \sum_{n = 1}^\infty \frac{1}{f(p_n)} = \sum_{n=1}^\infty \frac{1}{p_{p_n}} \text{ converges, }$$ since $p_n \approx n \log n$, so that we have $p_{p_n} \approx n (\log n)^2$. But there I have an explicit order of magnitude for $f(n)$ that I can use, and I think there should be an argument to show this even without reference to the specific function $f(n)$.

A: Yes. Recursively for every $k\in\Bbb N$, construct subsets $A_k$ of $\Bbb N$ as follows:

*

*Let $N(k)$ be such that $f(n) > k^2 n$ for all $n>N(k)$; without loss of generality we may assume that $N(k)$ is larger than all the integers in $A_1\cup\cdots\cup A_{k-1}$.

*Let $A_k$ be the set of integers between $N(k)$ and $2N(k)$. Then $\sum_{a\in A_k} \frac1a$ is approximately $\log 2$, while $\sum_{a\in A_k} \frac1{f(a)}$ is at most approximately $\frac1{k^2}\log 2$.

Then $A = \bigcup_{k=1}^\infty A_k$ is a set with the desired properties.


text:
Q: Scrollable Div in CSS I am creating a page with a header and footer, and a middle content div that can contain a variable amount of content that should be scrollable for the middle div only. The whole page should fill any viewport/screen size, 100% height and 100% width.
I am using this CSS:
*{margin:0;padding:0}
html, body {height:100%;width:100%;overflow:hidden}
table {height:100%;width:100%;table-layout:static;border-collapse:collapse}
.header {border-bottom:2px solid #000}
.footer {border-top:2px solid #000}
.tdcontent {height:100%}
.content {height:100%; overflow:auto;}

I am using this HTML:

<?php include 'header.htm' ?>

<?php include 'content.htm' ?>

<?php include 'footer.htm' ?>

The above works fine in Chrome. If I insert more content than the screen can show, a vertical scrollbar appears for the middle content div, as expected. But in both IE and Firefox, no scroll bar appears and the content extends beyond the bottom of the page. Any ideas how to fix this problem? I have tried iframes as a cross-browser solution and it works for all of them, but for SEO reasons I do not want to use iframes.
EDIT: the problem seems to be setting height at 100%. Chrome likes it, but IE and FF seem to want fixed height in px only.
EDIT 2: I found an answer on SO at CSS 100% Height, and then Scroll DIV not page

A: overflow:auto;// right and bottom scroll
overflow-y:auto;//only right scroll
overflow-x:auto;//only bottom scroll

UPDATE:
But this is very cool library for this task
https://github.com/noraesae/perfect-scrollbar

A: Try this:
.content {overflow:scroll-y}

My bad, I was really tired when I wrote this ^
It was .content {overflow-y:scroll}


text:
Q: Spring Unit Test and object re-injection In Spring what is the best way to run a bunch of test methods on an object but reset/re-inject the object before each new test method invocation?
I have tried to do in the code below but with my current logic the object gets created and injected only once..
package com.bidtracker;

import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.is;

import com.bidtracker.iface.BidTracker;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class BidTrackerTest {

    @Autowired
    BidTracker tracker;

    @Test
    public void shouldReturnHighestBidAmount1(){

    tracker.bidOnItem("itemB", "user1", 105);
    assertThat(tracker.getHighestBid("itemB").getAmount(),is(Integer.valueOf(105)));
    }

    @Test
    public void shouldReturnHighestBidAmount2(){

    tracker.bidOnItem("itemB", "user1", 39);
    tracker.bidOnItem("itemB", "user1", 50);

    assertThat(tracker.getHighestBid("itemB").getAmount(),is(Integer.valueOf(50)));

    }
}

A: JUnit has the @Before annotation, you can use that to do any initialization before each test.
However, I am curious about your case. Here's from the @Test documentation:

The Test annotation tells JUnit that the public void method to which
  it is attached can be run as a test case. To run the method, JUnit
  first constructs a fresh instance of the class then invokes the
  annotated method. Any exceptions thrown by the test will be reported
  by JUnit as a failure. If no exceptions are thrown, the test is
  assumed to have succeeded.

I'm guessing that the issue is that the bean is a singleton. It actually gets injected again, but if it's been modified you're using the same thing. You can try the @DirtiesContext annotation.

A: The issue here is that Spring test support by default caches the application context and will reuse the cached context if elements of the key match up(context name(s), active profiles etc). To ask Spring to remove the context from the cache you can mark the test with @DirtiesContext annotation (at the method level or test class level).


text:
Q: Creating 10 categorical and 10 continuous random variables and save them as a data frame I would like to create a data frame with 10 categorical and 10 continuous random variables. I can do it using the following loop.
   p_val=rbeta(10,1,1)   #10 probabilities
    n=20
    library(truncnorm)
    mu_val=rtruncnorm(length(p_val),0,Inf, mean = 100, sd=5)#rnorm(length(p))
    d_mat_cat=matrix(NA, nrow = n, ncol = length(p))
    d_mat_cont= matrix(NA, nrow = n, ncol = length(p))
      for ( j in 1:length(p)){
        d_mat_cat[,j]=rbinom(n,1,p[j]) #Binary RV
        d_mat_cont[,j]=rnorm(n,mu_val[j]) #Cont. RV
      }
    d_mat=cbind(d_mat_cat, d_mat_cont)

Any alternative options are appreciated.

A: rbinom is vectorized over prob, and rnorm is vectorized over mean, so you can use this:
cbind(
  matrix(rbinom(n * length(p_val), size = 1, prob = p_val),
         ncol = length(p_val), byrow = TRUE),
  matrix(rnorm(n * length(mu_val), mean = mu_val),
         ncol = length(mu_val), byrow = TRUE)
)

We can be a little clever with rep to make the call much cleaner:
p_val = c(0, 0.5, 1)
mu_val = c(1, 10, 100)
n = 4

##
matrix(
  c(
    rbinom(n * length(p_val), size = 1, prob = rep(c(0, .5, 1), each = n)),
    rnorm(n * length(mu_val), mean = rep(c(1, 10, 100), each = n))
  ),
  nrow = n,
)

#      [,1] [,2] [,3]       [,4]     [,5]     [,6]
# [1,]    0    1    1  1.1962718 9.373595 100.1739
# [2,]    0    0    1 -0.1854631 9.574706 100.0725
# [3,]    0    1    1  3.4873697 9.447363 100.1345
# [4,]    0    1    1  2.8467450 9.700975 101.3178

A: You can try using sapply to run rbinom and rnorm and cbind the data.
cbind(sapply(p_val, rbinom, n = n, size = 1), sapply(mu_val, rnorm, n = n))


text:
Q: I am trying to fill a triangle I am trying to fill a triangle. I tried to do it myself using
g.fillPolygon(Triangle.x1, Triangle.x2, Triangle.x3, Triangle.y1,
         Triangle.y2, Triangle.y3);

but I am getting some errors. Can anyone help me with this?
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Vehicle extends JFrame

 {
    final int WIDTH = 900; int HEIGHT = 650;

public Vehicle()
    {
        //the following code creates the JFrame
        super("Radical Racing");
        setSize(WIDTH,HEIGHT);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);

}
public void paint(Graphics g)
{

    g.setColor(Color.DARK_GRAY);
    g.fillRect(0,0,WIDTH,HEIGHT);

    int x1, y1 ,x2, y2, x3,y3;
    x1 = x2 = x3 = 200;
    y1 = y2 = y3 = 390;

    {
          triangle (g, x1=174, y1, x2=204, y2, x3=189, y3=360);

    }
    g.setColor(Color.green);
    g.fillPolygon(Triangle.x1, Triangle.x2, Triangle.x3, Triangle.y1, Triangle.y2, Triangle.y3);
    triangle(g,x1,y1,x2,y2,x3,y3);
}

void triangle(Graphics g,int x1,int y1,
        int x2, int y2, int x3, int y3){
      g.drawLine (x1, y1, x2, y2);
      g.drawLine (x2, y2, x3, y3);
      g.drawLine (x3, y3, x1, y1);
}

public static void main(String[]args)
    {
        new Vehicle();
    }

}

A: You're welcome and I suggest to use oracle java api sometimes. It's really developers friendly. :)
You don't have any Triangle class with static x1... fields so why Triangle.x1...? :) And why own block to invoke triangle()?
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Vehicle extends JFrame {

    final int WIDTH = 900;
          int HEIGHT = 650;

    public Vehicle() {
        // the following code creates the JFrame
        super("Radical Racing");
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);

    }
    public void paint(Graphics g) {

        g.setColor(Color.DARK_GRAY);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        int x1, y1, x2, y2, x3, y3;
        x1 = x2 = x3 = 200;
        y1 = y2 = y3 = 390;
        triangle(g, x1 = 174, y1, x2 = 204, y2, x3 = 189, y3 = 360);

        g.setColor(Color.green);
        g.fillPolygon(new int[] {x1, x2, x3}, new int[] {y1, y2, y3}, 3);
        triangle(g, x1, y1, x2, y2, x3, y3);
    }

    void triangle(Graphics g, int x1, int y1, int x2, int y2, int x3, int y3) {
        g.drawLine(x1, y1, x2, y2);
        g.drawLine(x2, y2, x3, y3);
        g.drawLine(x3, y3, x1, y1);
    }

    public static void main(String[] args) {
        new Vehicle();
    }

}

A: nvrfrgt answer works and fixes any bugs you have (gave him a +1) but there are some other things you could clean up that are worth keeping in mind (and were too long for a comment).
First off, I think you meant for HEIGHT to be final? Otherwise make it lowercase.
A performance thing that might make a difference later if you are drawing a bunch of racing triangles or something - you are drawing the same triangle twice (never change your x and y values), so one of these is wasted.
triangle (g, x1=174, y1, x2=204, y2, x3=189, y3=360);
...
triangle(g, x1, y1, x2, y2, x3, y3);

How you initialized your x and y values isn't the cleanest either. You set them all to specific numbers, and then turn around and change them in the next line. Why have the initial values? The snippet below makes more sense to me anyway (though that still seems a bit too magic numbery)
int x1 = 174; int x2 = 204; int x3 = 189;
int y1 = 390; int y2 = 390; int y3 = 360;
triangle(g, x1, y1, x2, y2, x3, y3);

If you are going to draw the triangle and fill it in the same color, then drawing the lines might be unnecessary for you (makes 1pixel difference?). If that's the case, you can remove the triangle() call, or replace your triangle implementation with the fill polygon. In the end, something like this is a bit more sleek (still can work on it though):
public class Vehicle extends JFrame {

  final int WIDTH = 900;
  final int HEIGHT = 650; // Made this final

  public Vehicle() {
      // the following code creates the JFrame
      super("Radical Racing");
      setSize(WIDTH, HEIGHT);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setVisible(true);
  }

  public void paint(Graphics g) {

    g.setColor(Color.DARK_GRAY);
    g.fillRect(0, 0, WIDTH, HEIGHT);

    int x1 = 174; int x2 = 204; int x3 = 189;
    int y1 = 390; int y2 = 390; int y3 = 360;
    g.setColor(Color.green);
    // Got rid of redundant drawing
    triangle(g, x1, y1, x2, y2, x3, y3);
  }

  void triangle(Graphics g, int x1, int y1, int x2, int y2, int x3, int y3) {
    // Left both the lines and the fill so you could play with color or something.
    g.drawLine(x1, y1, x2, y2);
    g.drawLine(x2, y2, x3, y3);
    g.drawLine(x3, y3, x1, y1);
    g.fillPolygon(new int[] {x1, x2, x3}, new int[] {y1, y2, y3}, 3);
  }

  public static void main(String[] args) {
    // Want to save this as something so you can move it around later
    Vehicle greenTriangle = new Vehicle();
  }

A: first set color:
g.setColor(R, G, B);

Then fill it:
g.fillTriangle(x1, y1, x2, y2, x3, y3);


text:
Q: http://localhost:3000/api/posts i am getting COULD NOT GET ANY RESPONSE. using POSTMAN     // this is app.js which is the main application file
    var express = require('express');
    var path = require('path');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');

    var api = require('./routes/api');``
    //var users = require('./routes/users');

    var app = express();

    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');

    // uncomment after placing your favicon in /public
    //app.use(favicon(__dirname + '/public/favicon.ico'));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));

  //  app.use('/', routes);
    app.use('/api', api);

    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    });

    // error handlers

    // development error handler
    // will print stacktrace
    if (app.get('env') === 'development') {
        app.use(function(err, req, res, next) {
            res.status(err.status || 500);
            res.render('error', {
                message: err.message,
                error: err
            });
        });
    }

    // production error handler
    // no stacktraces leaked to user
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: {}
        });
    });

    module.exports = app;

and this is api.js which implements the RESTful API.Post is a resource and because of this we will implement a /posts API which will First we'll implement placeholder route handlers for the /posts api within api.js.
var express = require('express');
    var router = express.Router();
//api for all posts
router.route('/posts')

    //create a new post
    .post(function(req, res){

        //TODO create a new post in the database
        res.json({message:"TODO create a new post in the database"});
    })

    .get(function(req, res){

        //TODO get all the posts in the database
        res.json({message:"TODO get all the posts in the database"});
    })

module.exports = router;

i am getting this on postman

A: You should be going to
http://localhost:3000/api/posts
Not
http://localhost:3000/routes/api/posts
..
Edit:
I didn't realize you're trying to call
req.send

Well that is not a method of
req (request)

You're looking for
res (response)

And on top of that you're trying to send a json result, not plain text so use
res.json

Instead of
res.send

A: I don't see you starting the server with app.listen(3000). You merely export the express app.
Or is there a different module that spins up the server?


text:
Q: How to split data into 3 sets (train, validation and test)? I have a pandas dataframe and I wish to divide it to 3 separate sets. I know that using train_test_split from sklearn.cross_validation, one can divide the data in two sets (train and test). However, I couldn't find any solution about splitting the data into three sets. Preferably, I'd like to have the indices of the original data.
I know that a workaround would be to use train_test_split two times and somehow adjust the indices. But is there a more standard / built-in way to split the data into 3 sets instead of 2?

A: However, one approach to dividing the dataset into train, test, cv with 0.6, 0.2, 0.2 would be to use the train_test_split method twice.
from sklearn.model_selection import train_test_split

x, x_test, y, y_test = train_test_split(xtrain,labels,test_size=0.2,train_size=0.8)
x_train, x_cv, y_train, y_cv = train_test_split(x,y,test_size = 0.25,train_size =0.75)

A: Note:
Function was written to handle seeding of randomized set creation.  You should not rely on set splitting that doesn't randomize the sets.
import numpy as np
import pandas as pd

def train_validate_test_split(df, train_percent=.6, validate_percent=.2, seed=None):
    np.random.seed(seed)
    perm = np.random.permutation(df.index)
    m = len(df.index)
    train_end = int(train_percent * m)
    validate_end = int(validate_percent * m) + train_end
    train = df.iloc[perm[:train_end]]
    validate = df.iloc[perm[train_end:validate_end]]
    test = df.iloc[perm[validate_end:]]
    return train, validate, test

Demonstration
np.random.seed([3,1415])
df = pd.DataFrame(np.random.rand(10, 5), columns=list('ABCDE'))
df

train, validate, test = train_validate_test_split(df)

train

validate

test

A: Here is a Python function that splits a Pandas dataframe into train, validation, and test dataframes with stratified sampling. It performs this split by calling scikit-learn's function train_test_split() twice.
import pandas as pd
from sklearn.model_selection import train_test_split

def split_stratified_into_train_val_test(df_input, stratify_colname='y',
                                         frac_train=0.6, frac_val=0.15, frac_test=0.25,
                                         random_state=None):
    '''
    Splits a Pandas dataframe into three subsets (train, val, and test)
    following fractional ratios provided by the user, where each subset is
    stratified by the values in a specific column (that is, each subset has
    the same relative frequency of the values in the column). It performs this
    splitting by running train_test_split() twice.

    Parameters
    ----------
    df_input : Pandas dataframe
        Input dataframe to be split.
    stratify_colname : str
        The name of the column that will be used for stratification. Usually
        this column would be for the label.
    frac_train : float
    frac_val   : float
    frac_test  : float
        The ratios with which the dataframe will be split into train, val, and
        test data. The values should be expressed as float fractions and should
        sum to 1.0.
    random_state : int, None, or RandomStateInstance
        Value to be passed to train_test_split().

    Returns
    -------
    df_train, df_val, df_test :
        Dataframes containing the three splits.
    '''

    if frac_train + frac_val + frac_test != 1.0:
        raise ValueError('fractions %f, %f, %f do not add up to 1.0' % \
                         (frac_train, frac_val, frac_test))

    if stratify_colname not in df_input.columns:
        raise ValueError('%s is not a column in the dataframe' % (stratify_colname))

    X = df_input # Contains all columns.
    y = df_input[[stratify_colname]] # Dataframe of just the column on which to stratify.

    # Split original dataframe into train and temp dataframes.
    df_train, df_temp, y_train, y_temp = train_test_split(X,
                                                          y,
                                                          stratify=y,
                                                          test_size=(1.0 - frac_train),
                                                          random_state=random_state)

    # Split the temp dataframe into val and test dataframes.
    relative_frac_test = frac_test / (frac_val + frac_test)
    df_val, df_test, y_val, y_test = train_test_split(df_temp,
                                                      y_temp,
                                                      stratify=y_temp,
                                                      test_size=relative_frac_test,
                                                      random_state=random_state)

    assert len(df_input) == len(df_train) + len(df_val) + len(df_test)

    return df_train, df_val, df_test

Below is a complete working example.
Consider a dataset that has a label upon which you want to perform the stratification. This label has its own distribution in the original dataset, say 75% foo, 15% bar and 10% baz. Now let's split the dataset into train, validation, and test into subsets using a 60/20/20 ratio, where each split retains the same distribution of the labels. See the illustration below:

Here is the example dataset:
df = pd.DataFrame( { 'A': list(range(0, 100)),
                     'B': list(range(100, 0, -1)),
                     'label': ['foo'] * 75 + ['bar'] * 15 + ['baz'] * 10 } )

df.head()
#    A    B label
# 0  0  100   foo
# 1  1   99   foo
# 2  2   98   foo
# 3  3   97   foo
# 4  4   96   foo

df.shape
# (100, 3)

df.label.value_counts()
# foo    75
# bar    15
# baz    10
# Name: label, dtype: int64

Now, let's call the split_stratified_into_train_val_test() function from above to get train, validation, and test dataframes following a 60/20/20 ratio.
df_train, df_val, df_test = \
    split_stratified_into_train_val_test(df, stratify_colname='label', frac_train=0.60, frac_val=0.20, frac_test=0.20)

The three dataframes df_train, df_val, and df_test contain all the original rows but their sizes will follow the above ratio.
df_train.shape
#(60, 3)

df_val.shape
#(20, 3)

df_test.shape
#(20, 3)

Further, each of the three splits will have the same distribution of the label, namely 75% foo, 15% bar and 10% baz.
df_train.label.value_counts()
# foo    45
# bar     9
# baz     6
# Name: label, dtype: int64

df_val.label.value_counts()
# foo    15
# bar     3
# baz     2
# Name: label, dtype: int64

df_test.label.value_counts()
# foo    15
# bar     3
# baz     2
# Name: label, dtype: int64

A: In the case of supervised learning, you may want to split both X and y (where X is your input and y the ground truth output).
You just have to pay attention to shuffle X and y the same way before splitting.
Here, either X and y are in the same dataframe, so we shuffle them,  separate them and apply the split for each (just like in chosen answer), or X and y are in two different dataframes, so we shuffle X, reorder y the same way as the shuffled X and apply the split to each.
# 1st case: df contains X and y (where y is the "target" column of df)
df_shuffled = df.sample(frac=1)
X_shuffled = df_shuffled.drop("target", axis = 1)
y_shuffled = df_shuffled["target"]

# 2nd case: X and y are two separated dataframes
X_shuffled = X.sample(frac=1)
y_shuffled = y[X_shuffled.index]

# We do the split as in the chosen answer
X_train, X_validation, X_test = np.split(X_shuffled, [int(0.6*len(X)),int(0.8*len(X))])
y_train, y_validation, y_test = np.split(y_shuffled, [int(0.6*len(X)),int(0.8*len(X))])

A: Numpy solution. We will shuffle the whole dataset first (df.sample(frac=1, random_state=42)) and then split our data set into the following parts:

*

*60% - train set,

*20% - validation set,

*20% - test set

In [305]: train, validate, test = \
              np.split(df.sample(frac=1, random_state=42),
                       [int(.6*len(df)), int(.8*len(df))])

In [306]: train
Out[306]:
          A         B         C         D         E
0  0.046919  0.792216  0.206294  0.440346  0.038960
2  0.301010  0.625697  0.604724  0.936968  0.870064
1  0.642237  0.690403  0.813658  0.525379  0.396053
9  0.488484  0.389640  0.599637  0.122919  0.106505
8  0.842717  0.793315  0.554084  0.100361  0.367465
7  0.185214  0.603661  0.217677  0.281780  0.938540

In [307]: validate
Out[307]:
          A         B         C         D         E
5  0.806176  0.008896  0.362878  0.058903  0.026328
6  0.145777  0.485765  0.589272  0.806329  0.703479

In [308]: test
Out[308]:
          A         B         C         D         E
4  0.521640  0.332210  0.370177  0.859169  0.401087
3  0.333348  0.964011  0.083498  0.670386  0.169619

[int(.6*len(df)), int(.8*len(df))] - is an indices_or_sections  array for numpy.split().
Here is a small demo for np.split() usage - let's split 20-elements array into the following parts: 80%, 10%, 10%:
In [45]: a = np.arange(1, 21)

In [46]: a
Out[46]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])

In [47]: np.split(a, [int(.8 * len(a)), int(.9 * len(a))])
Out[47]:
[array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16]),
 array([17, 18]),
 array([19, 20])]

A: It is very convenient to use train_test_split without performing reindexing after dividing to several sets and not writing some additional code. Best answer above does not mention that by separating two times using train_test_split not changing partition sizes won`t give initially intended partition:
x_train, x_remain = train_test_split(x, test_size=(val_size + test_size))

Then the portion of validation and test sets in the x_remain change and could be counted as
new_test_size = np.around(test_size / (val_size + test_size), 2)
# To preserve (new_test_size + new_val_size) = 1.0
new_val_size = 1.0 - new_test_size

x_val, x_test = train_test_split(x_remain, test_size=new_test_size)

In this occasion all initial partitions are saved.

A: def train_val_test_split(X, y, train_size, val_size, test_size):
    X_train_val, X_test, y_train_val, y_test = train_test_split(X, y, test_size = test_size)
    relative_train_size = train_size / (val_size + train_size)
    X_train, X_val, y_train, y_val = train_test_split(X_train_val, y_train_val,
                                                      train_size = relative_train_size, test_size = 1-relative_train_size)
    return X_train, X_val, X_test, y_train, y_val, y_test

Here we split data 2 times with sklearn's train_test_split

A: Considering that df id your original dataframe:
1 - First you split data between Train and Test (10%):
my_test_size = 0.10

X_train_, X_test, y_train_, y_test = train_test_split(
    df.index.values,
    df.label.values,
    test_size=my_test_size,
    random_state=42,
    stratify=df.label.values,
)

2 - Then you split the train set between train and validation (20%):
my_val_size = 0.20

X_train, X_val, y_train, y_val = train_test_split(
    df.loc[X_train_].index.values,
    df.loc[X_train_].label.values,
    test_size=my_val_size,
    random_state=42,
    stratify=df.loc[X_train_].label.values,
)

3 - Then, you slice the original dataframe according to the indices generated in the steps above:
# data_type is not necessary.
df['data_type'] = ['not_set']*df.shape[0]
df.loc[X_train, 'data_type'] = 'train'
df.loc[X_val, 'data_type'] = 'val'
df.loc[X_test, 'data_type'] = 'test'

The result is going to be like this:

Note: This soluctions uses the workaround mentioned in the question.

A: Split the dataset in training and testing set as in the other answers, using
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

Then, if you fit your model, you can add validation_split as a parameter. Then you do not need to create the validation set in advance. For example:
from tensorflow.keras import Model

model = Model(input_layer, out)

[...]

history = model.fit(x=X_train, y=y_train, [...], validation_split = 0.3)

The validation set is meant to serve as a representative on-the-run-testing-set during training of the training set, taken entirely from the training set, be it by k-fold cross-validation (recommended) or by validation_split; then you do not need to create a validation set separately and still you split a dataset into the three sets you are asking for.

A: ANSWER FOR ANY AMOUNT OF SUB-SETS:
def _separate_dataset(patches, label_patches, percentage, shuffle: bool = True):
    """
    :param patches: data patches
    :param label_patches: label patches
    :param percentage: list of percentages for each value, example [0.9, 0.02, 0.08] to get 90% train, 2% val and 8% test.
    :param shuffle: Shuffle dataset before split.
    :return: tuple of two lists of size = len(percentage), one with data x and other with labels y.
    """
    x_test = patches
    y_test = label_patches
    percentage = list(percentage)       # need it to be mutable
    assert sum(percentage) == 1., f"percentage must add to 1, but it adds to sum{percentage} = {sum(percentage)}"
    x = []
    y = []
    for i, per in enumerate(percentage[:-1]):
        x_train, x_test, y_train, y_test = train_test_split(x_test, y_test, test_size=1-per, shuffle=shuffle)
        percentage[i+1:] = [value / (1-percentage[i]) for value in percentage[i+1:]]
        x.append(x_train)
        y.append(y_train)
    x.append(x_test)
    y.append(y_test)
    return x, y

This work for any size of percentage. In your case, you should do percentage = [train_percentage, val_percentage, test_percentage].

A: The easiest way that I could think of is mapping split fractions to array index as follows:
train_set = data[:int((len(data)+1)*train_fraction)]
test_set = data[int((len(data)+1)*train_fraction):int((len(data)+1)*(train_fraction+test_fraction))]
val_set = data[int((len(data)+1)*(train_fraction+test_fraction)):]

where data = random.shuffle(data)


text:
Q: ASP.NET MVC: Adding partial views dynamically and having them reflected in the view model Situation: I have an ASP.NET Razor page that is constructed of partials.
Some of these are in loops iterating over collections that are members of the main page's view model. These iterated partials use the collections' member types as their own view model.
So the main page Razor looks something like this:
@model MyProject.MainViewModel

@*Other stuff...*@

@foreach (Subtype v in Model.SubViewModel)
{
         Html.RenderPartial("MyPartial", v);
}

And the partial looks like this:
@model Subtype

@Html.HiddenFor(t=>t.ParentViewModelID)

@Html.EditorFor(t=>t.Field1)
@Html.EditorFor(t=>t.Field2)

This all works well on initial page load, but I'm wondering how I should handle dynamically adding these partials via AJAX.
Suppose the user presses a button that's ultimately intended to add to one of these view model collections. I can AJAX back to the server, render the appropriate partial there, and return it to the client:
[System.Web.Mvc.HttpGet]
public ActionResult AddSubtype(int mainViewModelId)
{
  var model = new Sub { ParentViewModelID=mainViewModelId};
  return PartialView("MyPartial", model);
}

And then I use a bit of script to stick this into the DOM where it belongs:
 success: (data) => {  $('#subtypeHanger').append(data);},

This seems to work, except for one big part: when I evntually submit my form, I'm not seeing the data associated with this dynamically added partial in my view model.
I have been trying to debug this, but I'm wondering in broad terms whether this is possible- or alternately, how much MVC is supposed to abstract over such things. Obviously I can do things with JavaScript to force this to work. Is there an ASP.NET MVC pattern for this I should emulate, though?

EDIT: I'll mention some things I've tried since I posted this:

*

*Managing the "name" and "id" attributes of the partial views' edit controls manually, so that they end up looking like they do when I nest these controls in the main view instead of a partial (i.e. longer, with more text and an index).

*Using the main view model class for the partials. This makes me move the loops into the partial. The "name" and "id" property look like what I was going for in #1 above, but this design greatly complicates the process of returning the partial from my AJAX calls.

*Using "for" loops instead of "foreach." By itself, this doesn't achieve what I want.
All this said, if #1 or #2 is the best pattern for what I'm doing, perhaps I can make that work.

A: "Situation: I have an ASP.NET Razor page that is constructed of partials."

*

*This is called "Master Details"

*

*check
Master Details CRUD with MVC 5 | The ASP.NET Forums

*

*The trick is naming your Fields
@Html.HiddenFor(t=>t.ParentViewModelID ,new { htmlAttributes = new { @Name = "[" + i + "].ParentViewModelID" } })
@Html.EditorFor(t=>t.Field1 ,new { htmlAttributes = new { @Name = "[" + i + "].Field1" } })
@Html.EditorFor(t=>t.Field2 , new { htmlAttributes = new { @Name = "[" + i + "].Field2" } })

*so it will be
<input type="text" name="[0].Field1" />
<input type="text" name="[0].Field2" />
<input type="text" name="[1].Field1" />
<input type="text" name="[1].Field2" />

*and better(for ASP.NET mvc 5 Model Binding) if you use
public ActionResult Edit(MainViewModel master, List<Subtype> details)

if you provided the Full model i will provide a full working example


text:
Q: POst array and update mysql table with unique id for each update? I have this in firebug:
s:17:"id=12&id=15&id=16";s:19:"qty=15&qty=5&qty=12";s:43:"note=note+one¬e=note+two¬e=note+three";

I have the above as aresult from this:
itemid: $('input.id').serialize(),
qty: $('input.qty').serialize(),
note: $('textarea.note').serialize(),
name: $('input#fname').val(),
phone: $('input#phone').val(),
email:  $('input#email').val()

I have this in my php process file:
$id             = serialize($_POST['itemid']);
$qty            = serialize($_POST['qty']);
$note           = serialize($_POST['note']);

$ids        = explode(',', $id);
$qtys       = explode(',', $qty);
$notes      = explode(',', $note);

$count = count($ids,$qtys,$notes);

for ($i=0; $i < $count; $i++) {
$query = "UPDATE bookings SET qty='{$qtys[$i]}', note='{$notes[$i]}' WHERE id='{$ids[$i]}'";
$result = mysql_query($query) or die(mysql_error());
mysql_close();

Really trying to work out how this is done.What has to happen is that an update would occur for each id from the id= array and the values would change in the fields where qty and notes reside.
Is there a really simple way of doing this?
Thanks in advance
jonny


text:
Q: Failed to load config from https://10.20.1.98/config.js?room=n...', [TypeError: Network request failed i am trying to connect jitsi meet server but i am getting this error
    Failed to load config from https://10.20.1.98/config.js?room=n...', [TypeError: Network request failed]
i install rocket.chat and jitsi in local server and want to connect my android rocket.chat app to local server and its text messaging is working fine but when i click on video/audio call it
alert me timeout exception for 30 sec and return a white blank screen and it gives us belowenter image description here error in emulator?

Failed to load config from https://10.20.1.98/config.js?room=nimsss6x5hxtgma9wa2wgcv5ex4pubmkhz9jgyq6mfthwd62rghj7ku', [TypeError: Network request failed]
2020-02-23 10:39:12.614 7152-7680/chat.rocket.android.dev E/unknown:ReactNative: console.error: "[__filename]", "<>: ", "Failed to load config from https://10.20.1.98/config.js?room=nimsss6x5hxtgma9wa2wgcv5ex4pubmkhz9jgyq6mfthwd62rghj7ku", {}, stack:

we use self signed certificate (invalid certificate) and i can access config.js file in web browser.
rocket.chat version 3.5.0

A: I'm not using rocket.chat but in case you can manipulate your app, this could be one way to make it work:
I see, your have your own internal server and you have to install a root certificate on your phone to connect to your server.
If so, you have to do the following things:
Add android:networkSecurityConfig="@xml/network_security_config" to the application tag in your Android Manifest and create the corresponding file to:
app/src/main/res/xml
This is the Content of the network_security_config.xml file:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <debug-overrides>
        <trust-anchors>
            <certificates src="system" />
            <certificates src="user" />
        </trust-anchors>
    </debug-overrides>
</network-security-config>

So your App knows to use the installed certificate, otherwise it will use the platform Default.
I have to say, this problem appears to many developers, so there could be other solutions, like I found with jitsi-meet.
But this is the way it worked for me.
Hope it helps.


text:
Q: Visual Studio Form Designer Showing List of Controls I know that getting the Form Designer to work is a ticklish business.  Generics, x64, subtle problems with the project's XML...  But perhaps someone can offer advice about my current problem, which is that a component I created that inherits from TabPage, when I try to view it in the designer shows up as a list of its controls, like this:

Thanks in advance.

A: You cannot make a TabPage as root of the designer, while you can do the same for a Panel or other container controls. The limitation is because, TabPage can only be hosted in TabControl, not even in the overlay control of the designer:

TabPage cannot be added to a
'System.Windows.Forms.Design.DesignerFrame+OverlayControl'.  TabPages
can only be added to TabControls.

A control can be shown as root of the designer when the base class of the control has designer of type of DocumentDesigner. Form and UserControl are such controls which means when you create a new Form1:Form or new UserControl1:UserControl, since the base class derived from a designable control, then the class can be edited in the designer as root.
I believe you can handle your requirement by using UserControl, but for learning purpose (or as a workaround) if you want to make a control deriving from Panel designable, you can copy the following code in a code file:
public class MyControl: MyDesignableControl
{
}
[Designer(typeof(DocumentDesigner), typeof(IRootDesigner))]
public class MyDesignableControl : Panel
{

}

Then save it and then double click on it and you can see you can design it like a root control.
Then after you done with the design, change the Panel to TabPage.

Remarks on
DocumentDesigner
This designer is a root designer, meaning that it provides the
root-level design mode view for the associated document when it is
viewed in design mode.
You can associate a designer with a type using a
DesignerAttribute.
For an overview of customizing design time behavior, see Extending
Design-Time
Support.


text: Q: Syntax highlighter for Android application I want to write an android native app where i need to have a syntax highlighting. So does any one know if there is any syntax highlighting library available in java/android, also if it supports some level of customization, like custom color coding.


text:
Q: Cannot read eflags with function call I'm using MSVC 2015.
I was trying to follow an answer provided here and adapted the program to the following:
#include <iostream>
#include <limits>

inline unsigned long long query_intel_x86_eflags(const unsigned long long query_bit_mask)
{
    return __readeflags() & query_bit_mask;
}

int main(int argc,char **argv)
{
    int x = std::numeric_limits<int>::max();
    int y = std::numeric_limits<int>::max();
    int z = x * y;
    //auto g{__readeflags() & 0x801}; // sees overflow and carry flags
    auto g{query_intel_x86_eflags(0x801)}; // doesn't see overflow and carry flags
    std::cout << std::hex << g << '\n';
}

The problem is that the eflags register is reset during the call to query_intel_x86_eflags() prior to the read of the EFL register.
The following assembly is emitted and it contains a sub instruction that resets the EFL register.
inline unsigned long long query_intel_x86_eflags(const unsigned long long query_bit_mask)
{
00007FF6396D1BF0 48 89 4C 24 08       mov         qword ptr [rsp+8],rcx
00007FF6396D1BF5 55                   push        rbp
00007FF6396D1BF6 57                   push        rdi
00007FF6396D1BF7 48 81 EC C8 00 00 00 sub         rsp,0C8h // changes the flags
00007FF6396D1BFE 48 8B EC             mov         rbp,rsp
00007FF6396D1C01 48 8B FC             mov         rdi,rsp
00007FF6396D1C04 B9 32 00 00 00       mov         ecx,32h
00007FF6396D1C09 B8 CC CC CC CC       mov         eax,0CCCCCCCCh
00007FF6396D1C0E F3 AB                rep stos    dword ptr [rdi]
00007FF6396D1C10 48 8B 8C 24 E8 00 00 00 mov         rcx,qword ptr [rsp+0E8h]
    return __readeflags() & query_bit_mask;
00007FF6396D1C18 48 9C                pushfq
00007FF6396D1C1A 58                   pop         rax
00007FF6396D1C1B 48 23 85 E0 00 00 00 and         rax,qword ptr [query_bit_mask]
}

Why does the compiler generate the additional instructions that end up resetting the register?


text:
Q: Show closest result to current date & time (MySQL & PHP) I'm trying to make a query but after hours of trying I can't seem to get it right. What I'm trying to do is showing 1 thing from a database that is closest to the currect date & time and after the current date & time.
my columns look like this:
  date         time
1364399654     15:00
1364684400     16:00
1367272800     12:00

my PHP looks like this:
$timestamp_now = strtotime(date('d-m-Y')); //Creates a timestamp of the currect date
$time_now = date('H:i');
$sql = mysql_query('SELECT * FROM table_name ORDER BY date ASC, time ASC (WHERE date > '.$timestamp_now.') AND (time > "'.$time_now.'") LIMIT 1') or die(mysql_error());
$data = mysql_fetch_array($sql);

However, this doesn't work. Any words of advice?

A: I would ditch using the PHP date/time methods and rely on MySQL giving a query that looks like
SELECT * FROM table_name
WHERE date > CURRENT_DATE
OR (
    date = CURRENT_DATE
    AND
    time > CURRENT_TIME
)
ORDER BY date ASC, time ASC LIMIT 1

The OR makes sure that it gets the correct records else the TIME portion would block i.e. a result at 03:00 from the next day from appearing if the current time was at 06:00
I see you are using timestamp values there so you can always still pass in the PHP date numeric in place of CURRENT_DATE.  This would give a final script of
$timestamp_now = strtotime(date('d-m-Y')); //Creates a timestamp of the currect date
$sql = mysql_query('SELECT * FROM table_name
                    WHERE date > '.$timestamp_now.'
                    OR (
                        date = '.$timestamp_now.'
                        AND
                        time > CURRENT_TIME
                    )
                    ORDER BY date ASC, time ASC LIMIT 1') or die(mysql_error());
$data = mysql_fetch_array($sql);

I would advise considering changing the database if possible to store just as a MySQL DATETIME field, as then you can change this query to simply WHERE datetime > NOW(), but that's entirely up to you.  Just have always found MySQL date handling more logical than PHPs.

A: You should use one more test :

*

*DATE(date) > CURDATE() : if it's tomorrow or later

*DATE(date) = CURDATE() AND time > TIME(NOW()) : it it's today, but later

The full code :
$sql = mysql_query('SELECT *
                    FROM table_name
                    WHERE DATE(date) > CURDATE()
                    OR (DATE(date) = CURDATE() AND time > TIME(NOW()))
                    ORDER BY date ASC, time ASC
                    LIMIT 1'
                  ) or die(mysql_error());
$data = mysql_fetch_array($sql);

Please note you're using timestamp in your date field. Timestamp include date and time, so maybe you'll be able to use this request :
SELECT *
FROM table_name
WHERE date > NOW()
ORDER BY date ASC
LIMIT 1

A: I beleive you need to get the SQL structured with WHERE before ORDER BY
something like
SELECT * FROM table WHERE (date>$now) and (time>$now) ORDER BY date,time LIMIT 1


text:
Q: How to get widgets (QGraphicsProxyWidget) of QGraphicsScene? I am making use of a QGraphicsScene and I am adding regular widgets (QLineEdit, QComboBox, etc.) to it via implicitly created QGraphicsProxyWidget objects:
m_pLineEdit = new QLineEdit("", 0);
m_pProxy = m_pGraphicsScene->addWidget(m_pLineEdit);

I am currently searching for a way to later retrieve those widgets from the scene again for processing, but am not able to find one.
I tried the following approaches already:

*

*Since I cannot pass the graphics scene as parent to the widget constructor, retrieving the widgets via m_pGraphicsScene->findChildren(QLineEdit*) does not work, since there is no direct relation.

*The graphics scene does have a QGraphicsSceneBspTreeIndex child, but that is not part of the official Qt API and therefore relying on it cannot be the way to go.

Bottom-line: How can I get all the QGraphicsProxyWidget objects from a Qt graphics scene? Can this be done in the Qt standard or do I have to subclass QGraphicsScene and try to manage the widgets myself?

A:
Bottom-line: How can I get all the QGraphicsProxyWidget objects from a Qt graphics scene?

Get the list of all the items in the scene via scene->items() , then check if they're of the right class:
// Horrible C++98 code which doesn't even feature algorithms

QList<QGraphicsItem *> items = scene->items();
foreach (QGraphicsItem *item, items) {
    QGraphicsProxyWidget *w;
    if (w = qgraphicsitem_cast<QGraphicsProxyWidget *>(item)) {
        use(w);
    }
}

However, I'd like to stress that you should really keep track of the items you put in the scene. (At least, the ones you're interested in using afterwards). Walking over the scene and retrieving the items like this seems very fragile, and it's a signal of poor code quality and poor design. Note that you have the proxy returned by the addWidget call, just save it somewhere.

A: Just after posting the question I by chance found a solution in the Qt source code. The widget proxies are treated as regular QGraphicsItem internally and can be casted via qgraphicsitem_cast:
QList<QGraphicsItem*> graphicsItemList = m_pGraphicsScene->items();
foreach(QGraphicsItem* pGraphicsItems, graphicsItemList)
{
    QGraphicsProxyWidget* pProxy = qgraphicsitem_cast<QGraphicsProxyWidget*>(pGraphicsItems);
    if(pProxy)
    {
        QLineEdit* pLineEdit = qobject_cast<QLineEdit*>(pProxy->widget());
        if(pLineEdit)
            // do stuff
    }
}

If someone knows a simpler/faster method, I'd be happy to hear about it. Until then I will use the approach outlined above.


text:
Q: Regular Expression in teradata I need to search few patterns from a column using regular expression in Teradata.
One of the example is mentioned below:
SELECT
  REGEXP_SUBSTR(
    REGEXP_SUBSTR('1-2-3','([0-9] *- *[0-9] *- *[0-9])',1, 1, 'i'),
    '([0-9] *- *[0-9] *- *[0-9])',
    1, 1, 'i'
  ) AS Tmp,
  REGEXP_SUBSTR(
    tmp,
    '(^[0-9])',1,1,'i') || '-' || REGEXP_SUBSTR(tmp,'([0-9]$)',
    1, 1, 'i'
  ) AS final_exp
;

In the above expression, I am extracting "1-3" out of a pattern like "1-2-3". Now the patterns can be anything like: 1-2-3-4-5 or 1-2,3 or 1&2-3 or 1-2,3 &4.
Is there any way that I can generalize the search pattern in regular expression like [-,&]* will only search for occurrence of this characters in order, but the characters can be present in any order in the data.
Few examples mentioned below,need is to fetch all the desired result set using a single pattern serch in expression.
Column name           ==>  Result
abc 1-2+3- 4          ==> 1-4
def 10,12 & 13        ==> 10-13
ijk 1,2,3, and 4 lmn  ==> 1-4
abc1-2 & 3 def        ==> 1-3
ikl 11 &12 -13        ==> 11-13
oAy$ 7-8 and 9        ==> 7-9

A: RegExp_Substr(col, '(\d+)',1, 1, 'c') || '-' ||
RegExp_Substr(col, '(\d+)(?!.*\d)',1, 1, 'c')

(\d+)  = first number
(\d+)(?!.*\d) = last number (a number not followed by another number)

There's also no need for those optional parameters, because it's using the defaults anyway:
RegExp_Substr(col, '(\d+)') || '-' ||
RegExp_Substr(col, '(\d+)(?!.*\d)')


text:
Q: How to setup nginx with docker compose I have nginx config and docker compose but I am not able to link them together properly.
default.conf:
worker_processes auto;

events { worker_connections 1024; }

http {

    upstream docker_nginx {
        server nginx:6000;
    }

    server {

         location / {
          proxy_set_header   X-Forwarded-For $remote_addr;
          proxy_pass         http://localhost:4000;
          proxy_set_header Host $host;
        }

        location /jwt/user/ {
          proxy_set_header   X-Forwarded-For $remote_addr;
          pproxy_pass         http://localhost:4000;
          proxy_set_header Host $host;
        }
    }
}

Docker compose:
version: '2'

services:
    reverseproxy:
        image: nginx
        container_name: docker_nginx
        ports:
            - 6000:6000
        volumes:
            - ./services:/default.conf
        restart: always

    jwt:
        build: ./jwt
        image: jwt:1.0
        ports:
            - 4000:4000
        restart: always
        volumes:
            - ./jwt

I want to listen on port 6000 and route request to a service on port 4000. I tried running http://nginx:6000/ and http://localhost:6000/ but I get this:
This site can't be reached. The web page at http://localhost:6000/ might be temporarily down or it may have moved permanently to a new web address.
ERR_UNSAFE_PORT

A: Let me give you my repo, you can check my docker-compose.yml, it uses several services and are proxied using Nginx and are worked together.
On this link you'll find a default.conf file and it contains several Nginx upstream configuration please take a look at how I used docker-compose service references there.
Inside the client/ directory, I also have another Nginx as a web server of a react.js project.
On server/ directory, it has a Node.js API, It connects to Redis and Postgres SQL database also built from docker-compose.yml.
I think this use case can be useful for you and other users!

A: There are few things which are misconfigured.

*

*config file is mapped to wrong location

It should be ./services/default.conf:/etc/nginx/nginx.conf

*You've to explicitly tell nginx (in conf file) to listen to 6000 port or otherwise map your 6000 port to 80 port inside nginx (default for nginx) "6000:80"

*Yes, and as suggested in other answer, instead of proxying to localhost:4000 you have to proxy it to jwt:4000.
For more on nginx in docker see it's doc https://hub.docker.com/_/nginx/

A: Should - ./services:/default.conf be something like - ./default.conf:/etc/nginx/sites-enables/default.conf?
Also try replacing proxy_pass         http://localhost:4000; with proxy_pass         http://jwt:4000; and you probably don't need the upstream section.
The "proxy_pass" is the address of the proxied service from within the network created by docker compose - and each service's domain is the same as its name in docker-compose.yml
I have never used upstream, but if you want to use it, I think you have to put this
upstream docker-jwt {
  server jwt:4000;
}

# and

proxy_pass         http://docker-jwt;

but as I put above, I would skip that and just put http://jwt:4000 as the proxied address.
You also seem to have a typo here: pproxy_pass         http://localhost:4000;
But if you leave the typo, and look at the docker compose logs, you will hopefully see an error from nginx, which means that you successfully mapped the config file


text:
Q: Prove that there is no largest rational number $q$ such that $q^3 < 2$ I know how to prove such things where $q < 2$, but $q^3 < 2$ seems a bit tricky for me. Could someone give me a lead please?

A: I expand on my comment. Let $q>0$ be rational such that $q^3<2$ so that $r=2-q^3>0$. Let $h>0$ be rational and $p=q+h$ and consider $$2-p^3=r-h(3q^2+3qh+h^2)$$ Let $h<1$ so that $$3q^2+3qh+h^2<3q^2+3q+1$$ and if we take $h<r/(3q^2+3q+1)$ ie $h<\min(1,r/(3q^2+3q+1))$ then we can see that $$h(3h^2+3qh+h^2)<r$$ and hence $2-p^3>0$. Thus the proof is complete. The argument works in exactly the same manner if the exponent $3$ is replaced by any positive integer, for example $100$.
The fundamental idea here is the fact that there is no end to supply of small positive rationals. Given any positive rational, there is a smaller one. This fact studied when learning fractions and their manipulation is the key aspect behind the proofs in calculus and strangely it is never emphasized in entire high school curriculum.


text:
Q: Changing screen aspect ratio output on android devices I'm developing an application for an Android set-top box which has HDMI and composite video outputs. The set-top box always outputs a signal that has 16:9 aspect ratio. When the set-top box is connected to a TV with 4:3 aspect ratio, all of the UI elements look squeezed. Can the aspect ratio of the output signal be changed programatically in Android?

A: At the firmware level? Conceivably. That would be the job of the manufacturer of the set-top box.
At the SDK level? No.


text:
Q: Calculate moving average using SQL window functions with leading null's where not enough data is avaliable I want to calculate a moving average using SQL window functions. The following example of a 2 "day" moving average basically works fine, but It also calculates an average if only one data point is available. I rather want the average to be null as long as not enough data is available
create table average(
    nr int,
    value float
);

insert into average values (1, 2), (2, 4), (3, 6), (3, 8), (4, 10);

SELECT
    nr,
    value,
    AVG(value) OVER (ORDER BY nr ROWS BETWEEN 1 PRECEDING AND 0 FOLLOWING)::FLOAT AS "Moving-Average-2"
FROM average;

result:
1   2   2
2   4   3
3   6   5
3   8   7
4   10  9

expected result:
1   2   null
2   4   3
3   6   5
3   8   7
4   10  9

EDIT 1:
Of course the average can be anything not only 2.

A: You could use another window function (COUNT()) to make sure that at least two records are available in the window before doing the computation, like:
SELECT
    nr,
    value,
    CASE WHEN COUNT(*) OVER(ORDER BY nr ROWS BETWEEN 1 PRECEDING AND 0 FOLLOWING) > 1
        THEN AVG(value) OVER (ORDER BY nr ROWS BETWEEN 1 PRECEDING AND 0 FOLLOWING)::FLOAT
        ELSE NULL
    END AS "Moving-Average-2"
FROM average;

Demo on DB Fiddle:
| nr  | value | Moving-Average-2 |
| --- | ----- | ---------------- |
| 1   | 2     |                  |
| 2   | 4     | 3                |
| 3   | 6     | 5                |
| 3   | 8     | 7                |
| 4   | 10    | 9                |

A: Since you happen to form the average only between 1 preceding row and the current one, just using lag()  might be simplest:
select nr, value
     ,(value + lag(value, 1, NULL) OVER (ORDER BY nr)) / 2 AS "Moving-Average-2"
from average;

lag() has an overloaded variant that allows to provide a default value (as 3rd parameter) in case there is no row. Provide NULL and you are there. Or, since NULL is the default default anyway, just:
 ... ,(value + lag(value) OVER (ORDER BY nr)) / 2 AS "Moving-Average-2"

While the underlying table column is of type float, you need no cast to float in this case.
This is assuming the column value is defined NOT NULL (like indicated by your sample data). Else you also get NULL where the previous row has value IS NULL and the current row has a value, while avg() returns the value in this case! (Or this may be what you want anyway, given your question.)

A: This may be a handy place to use a window specification:
select a.*,
       (case when row_number() over w > 1
             then avg(value) over w
        end) as running_average
from average a
window w as (order by nr rows between 1 preceding and current row);

A: i think null is not come in agv first row otherwise below will work by using
BETWEEN 1 PRECEDING AND CURRENT ROW

select nr, value,
       avg(value) OVER (ORDER BY nr ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS "Moving-Average-2"
from average;

BETWEEN 1 PRECEDING AND CURRENT ROW
but you can haddle it by useing case when
select nr, value,
       case when nr=1 then null else
       avg(value) OVER (ORDER BY nr ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) end AS "Moving-Average-2"
from average;

nr  value   Moving-Average-2
1   2
2   4   3
3   6   5
3   8   7
4   10  9

online demo link


text:
Q: Latching space functor in Reedy model strucutre I am new to MO and I hope that this question is suitable for it.
Following Hovey's "Model Categories" ( http://ericmalm.net/ac/projects/symmetric-spectra/hovey--model-cats.pdf  ) to study model structures on functor categories, it seems that something is missing, or better I proved something to proceed further, but I am not really sure about this result.
It seems to me that, considering a model category $\mathscr{C}$ and the simplicial category $\Delta$ and endowing $\mathscr{C}^{\Delta}$ with the Reedy model structure, there is a natural isomorphism $L_n \ l^{\bullet}A \simeq l^{\bullet}A [n]  \ \ \forall A \in \mathscr{C}$.
Let me explain a bit the notation (but everything can be found on pages 124 to 127 in the previous link): by $L_n$ is meant the $n$-th latching space functor ( http://ncatlab.org/nlab/show/Reedy+model+structure) and $l^{\bullet}A$ is the cosimplicial object in $\mathscr{C}$ whose $n$-th "space" is the $n+1$-fold coproduct of $A$, with the obvious cosimplicial structure. Furthermore, it is left adjoint to the evaluation functor $Ev_0 : \mathscr{C}^{\Delta} \to \mathscr{C}$
The abovementioned isomorphism comes out by unraveling definitions and using universal properties of colimits and adjointness, at least for what I have tried.
Could someone confirm this fact, or disprove it (so that I have to find another way to prove the claim I am interested into)?
Thanks in advance, any help will be highly appreciated.


text:
Q: How to change global figure setting? I did
\floatstyle{boxed}
\restylefloat{figure}

so all of my figures are with frames. This works well, but there is a place I do not want frame, how can I change it locally?

A: Once you create a figure, it is set in a box that can move around. However, once set, it stays as is. So, you can temporarily change the style by localizing a change and restyling:

\documentclass{article}
\usepackage{float,graphicx}% http://ctan.org/pkg/{float,graphicx}
\floatstyle{boxed}
\restylefloat{figure}
\begin{document}
\begin{figure}
  \includegraphics[width=\linewidth,height=3\baselineskip]{example-image-a}%
  \caption{This is figure one}
\end{figure}
{\floatstyle{plain}
\restylefloat{figure}
\begin{figure}
  \includegraphics[width=\linewidth,height=3\baselineskip]{example-image-b}%
  \caption{This is figure two}
\end{figure}
}
\begin{figure}
  \includegraphics[width=\linewidth,height=3\baselineskip]{example-image-c}%
  \caption{This is figure three}
\end{figure}

\end{document}

It's best though, for the sake of consistency, to wrap this in your own environment, which also localizes the effect:
\newenvironment{noboxfigure}[1][ht]
  {\floatstyle{plain}\restylefloat{figure}%
   \begin{figure}[#1]
  }{\end{figure}}