text:
Q: this.props.navigation.navigate() is not an object Why is this.props.navigation.navigate() not available in my component? In fact, this.props is completely empty? My setup is that App.js adds StartScreen.js and ListScreen.js to a stackNavigator. ListScreen.js is then used as a component in Startscreen.js and will serve as a stacknavigation...
ListScreen.js
import React, { Component } from "react";
import { ScrollView, View, Text, FlatList, ActivityIndicator } from "react-native";
import { List, ListItem } from 'react-native-elements';

import Styles from 'app/styles/Styles';
import Vars from 'app/vars/Vars';

class ListScreen extends Component {

    /*
    static navigationOptions = {
        title: 'Välkommen',
        headerStyle: Styles.header,
        headerTintColor: Vars.colors.primary,
        headerTitleStyle: Styles.headerTitle,
    };
*/
    constructor(props) {
        super(props);

        console.log(props);

        this.state = {
          loading: true,
          data: [],
          page: 1,
          seed: 1,
          error: null,
          refreshing: false
        };
    }

    componentDidMount() {

        this.fetchItems();
    }

    fetchItems = () => {
        const { page, seed } = this.state;
        const url = 'http://appadmin.test/api/menu/'+this.props.id;

        this.setState({ loading: true });

        fetch(url)
            .then(res => res.json())
            .then(res => {
                this.setState({
                    data: page === 1 ? res : [...this.state.data, ...res],
                    error: res.error || null,
                    loading: false,
                    refreshing: false
                });
            })
            .catch(error => {
                this.setState({ error, loading: false });
            });
    }

    handleRefresh = () => {

        console.log('several handleRefresh?');

        this.setState(
          {
            page: 1,
            seed: this.state.seed + 1,
            refreshing: true
          },
          () => {
            this.fetchItems();
          }
        );
    };

  handleLoadMore = () => {

      console.log('several handleLoadMore?');

    this.setState(
      {
        page: this.state.page + 1
      },
      () => {
        this.fetchItems();
      }
    );
  };

  renderFooter = () => {
    if (!this.state.loading) return null;

    return (
      <View
        style={{
          paddingVertical: 20,
        }}
      >
        <ActivityIndicator animating size="large" />
        <Text style={Styles.textCenter}>
            Laddar innehåll...
        </Text>
      </View>
    );
  };

  renderListItem = ({ item }) => (

      <ListItem
          title = {item.title}
          id = {item.id}
          automaticallyAdjustContentInsets={false}
          item = {item}
          leftIcon={{
              name: item.icon,
              style: Styles.listitemIcon,
              size: 36,
          }}
          onPress = {this.onItemPress}
          style = { Styles.listItem }
          titleStyle = { Styles.listitemTitle }
      />
  )

  onItemPress = (item) => {
    this.props.navigation.navigate('List', {
        id: item.id
    });
  }

    render() {

        return (
            <ScrollView contentContainerStyle={Styles.listContainer}>

                <FlatList
                    automaticallyAdjustContentInsets={false}
                    data = { this.state.data }
                    style={Styles.list}
                    keyExtractor={item => "key_"+item.id}
                    renderItem = { this.renderListItem }
                    ListFooterComponent={this.renderFooter}
                    onRefresh={this.handleRefresh}
                    refreshing={this.state.refreshing}
                    onEndReachedThreshold={50}
                />

            </ScrollView>
        );
    }
}
export default ListScreen;

StartScreen.js
import React, { Component } from "react";
import {
    View,
    ScrollView,
    Text,
    StyleSheet,
    Linking,
    FlatList
} from "react-native";

import Styles from 'app/styles/Styles';
import Vars from 'app/vars/Vars';

import ListScreen from 'app/screens/ListScreen';

import { List, ListItem } from 'react-native-elements';

import Menu from './../../assets/data/navigation.json';

class StartScreen extends Component {

    static navigationOptions = {
        title: 'Välkommen',
        headerStyle: Styles.header,
        headerTintColor: Vars.colors.primary,
        headerTitleStyle: Styles.headerTitle,
    };

    constructor(props) {
        super(props);

        this.state = {
            loading: false,
            data: [],
            page: 1,
            seed: 1,
            error: null,
            refreshing: false,
        };
    }

    componentDidMount() {
        this.fetchList();
    }

    fetchList = () => {
        const { page, seed } = this.state;
        const url = 'http://appadmin.test/api/menu/root';

        this.setState({ loading: true });

        fetch(url)
            .then(response => {
                return response.json();
            })
            .then(json => {

                this.setState({
                    data: json,
                    error: null,
                    loading: false,
                    refreshing: false
                });
            })
            .catch(error => {
                this.setState({ error, loading: false });
            });
    }

    render() {
        return (

                <ScrollView style={Styles.scrollContainer}>
                    <View style={Styles.hero}>
                        <Text style={[Styles.h1, Styles.whiteText]}>
                            Region Halland
                        </Text>

                        <Text style={[Styles.lead, Styles.whiteText]}>
                            Välkommen
                        </Text>
                    </View>
                    <ListScreen id=""/>
                </ScrollView>
        );
    }
}
export default StartScreen;

App.js
import React from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
} from 'react-native';

import initCache from "app/utilities/initCache";

import { AppLoading } from 'expo';

import {
    createBottomTabNavigator,
    createStackNavigator
} from 'react-navigation'

import StartScreen from 'app/screens/StartScreen';
import ListScreen from 'app/screens/ListScreen';
import AboutScreen from 'app/screens/AboutScreen';
import { icon } from 'app/components/Image.js';

import Ionicons from 'react-native-vector-icons/Ionicons'

const StartStack = createStackNavigator({
  Start: {screen: StartScreen, tabBarLabel: 'Hem'},
  List: {screen: ListScreen},
}, {
    navigationOptions : {
        headerTitle:  <Image
           source={ icon }
           style={{ width: 30, height: 30 }} />,
        tabBarLabel: 'hem'
    }
});

const AboutStack = createStackNavigator({
  About: AboutScreen,
});

const Tabs = createBottomTabNavigator({
    StartStack: {screen: StartStack, navigationOptions: { title: 'Hem'}},
    AboutStack: {screen: AboutStack, navigationOptions: { title: 'Om Region Halland'}}
}, {
    navigationOptions: ({ navigation }) => ({
        tabBarIcon: ({ focused, tintColor }) => {
            const { routeName } = navigation.state;
            let iconName;

            if (routeName === 'AboutStack') {
                iconName = `ios-information-circle${focused ? '' : '-outline'}`;
            } else if (routeName === 'StartStack') {
                iconName = `ios-home${focused ? '' : '-outline'}`;
            }

            // You can return any component that you like here! We usually use an
            // icon component from react-native-vector-icons
            return <Ionicons name={iconName} size={24} color={tintColor} />;
      },
    }),
    tabBarOptions: {
      activeTintColor: '#0b457e',
      inactiveTintColor: 'gray',
    },
  })

export default class App extends React.Component {

    state = {
        appIsReady: false,
    };

    componentWillMount() {
        this._loadAssetsAsync();
    }

    async _loadAssetsAsync() {
        try {
            await initCache({
                fonts: [
                    {'scala-sans-regular': require('./assets/fonts/ScalaSans-Regular.ttf')},
                    {'scala-sans-bold': require('./assets/fonts/ScalaSans-Bold.ttf')},
                ]
            });
        } catch (e) {
            console.warn(
                'There was an error caching assets (see: main.js), perhaps due to a ' +
                'network timeout, so we skipped caching. Reload the app to try again.'
            );
            console.log(e.message);
        } finally {
            this.setState({ appIsReady: true });
        }
    }

    render() {
        if (this.state.appIsReady) {
          return (
            <Tabs />
          );
        } else {
          return <AppLoading />;
        }
    }
}

A: const { navigate } = this.props.navigation;
then use it as : navigate('Signup')}


text:
Q: Including png in several layer with ocgx for making a pdf I try to make a pdf with pdflatex, which should contains several pngs images. The special thing is, that there should be for each png one layer (ocgx).
At the end I want to have a pdf file, which all these pngs on one page, which can be activated or not.
But my problem is, that I get for each png a new page.
Further I get for every page the page number and I don't know why, but I did not do that.
Does anybody have a idea?
Thanks.
Here is my code:
\documentclass{article}
\usepackage{ocgx}
\usepackage{graphicx}
\begin{document}

\begin{ocg}{1}{1}{1}
  \includegraphics[scale=0.5]{a.png} \par
\end{ocg}

\begin{ocg}{1}{2}{1}
  \includegraphics[scale=0.5]{b.png} \par
\end{ocg}

\end{document}

A: \documentclass{article}
\usepackage{tikz}
\usepackage{ocgx}
\usepackage{enumerate}
\usepackage{graphicx}
\begin{document}

\begin{enumerate}
\item \setocgs{ocg1 ocg2 ocg3}{ocg1}{ocg2 ocg3}{A-PNG}
\item \setocgs{ocg1 ocg2 ocg3}{ocg2}{ocg1 ocg3}{B-PNG}
\item \setocgs{ocg1 ocg2 ocg3}{ocg3}{ocg1 ocg2}{C-PNG}
\end{enumerate}

\providecommand{\pica}[1]{
\includegraphics[scale=0.125]{#1.png}%
}

\begin{ocg}{OCG 1}{ocg1}{1}
\begin{tikzpicture}
\node[] (p1) {\pica{A}};%
\end{tikzpicture}
\end{ocg}
\begin{ocg}{OCG 2}{ocg2}{0}
\begin{tikzpicture}
\node[] (p1) {\pica{B}};%
\end{tikzpicture}
\end{ocg}
\begin{ocg}{OCG 3}{ocg3}{0}
\begin{tikzpicture}
\node[] (p1) {\pica{C}};%
\end{tikzpicture}
\end{ocg}

\end{document}

You should not activate each figure (which is the last parameter, 0 or 1). Your example both figures are at 1 and then both will be displayed...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to catch an error in Dart in parent class Im trying to make a generic way of catching API errors in my base view model, but its not working as expected.

I want my error to be set in the super BaseModel (line 24 and 26) but somehow it is not triggering those lines of code.
I think it's my limited knowledge of how Dart works. Can anyone point me in the right direction?

A: Looking at code, you want to invoke async operation and catch its errors and set state accordingly. But you are not really waiting for the async operation to over. apiCall just returns Future
One way to get the same affect
Future<T> apiCall<T>(ValueGetter<Future<T>> actualCall) async {
  try {
    setState(ViewState.Busy);
    T result = await actualCall; // Here you are actually waiting for opeation to be over
    return result;
  } on ErrorResponse catch(errorResponse) {
    error = errorResponse;
  } catch (e) {
    error = ErrorResponse.fromMessage('unknown');
  }
  setState(ViewState.Idle);
  return Future.error(error); // Or you can return Future.value(null);
}


text:
Q: ¿Como ejecutar un recyclerview desde un field de firestore como filtro? Tengo una base de datos en Firestore con una colleccion "Padron", la cual va a contener una gran cantidad de documentos.

Como ven en la imagen, estos documentos de la coleccion "padron" tiene un field "CLUB".
De la misma forma los documentos de la collecion "Usuarios", cuentan con el mismo fieldo "CLUB".

Tengo 2 categorias de usuarios, "Admin" y "Client" que ejecutan sus respectivas activitys teniendo en cuenta el "CLUB".
private void loginActivity() {
    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    usersRef.document(uid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document.exists()) {
                    String type = document.getString("CLUB");
                    if(type.equals ("ASV")) {
                        startActivity(new Intent(Login.this, UserAdmin.class));
                    } else if (type != ("ASV")) {
                        startActivity(new Intent(Login.this, UserClient.class));
                    }
                }
            }
        }
    });
}

Mi problema con todo esto es que cuando un usuario "Client" (Solo debe visualizar el recyclerview) ingresa a ver el "Padron", el recyclerview deberia mostrar solo los documentos con el mismo valor "CLUB" que tiene el usuario solicitante y no encuentro como hacer eso.
Adapter:
public class JugadoresMasc_Adapter extends FirestoreRecyclerAdapter<JugadoresMasc, JugadoresMasc_Adapter.ListaHolder> {

public JugadoresMasc_Adapter(@NonNull FirestoreRecyclerOptions<JugadoresMasc> options) {
    super(options);
}

@Override
protected void onBindViewHolder(@NonNull ListaHolder holder, int position, @NonNull JugadoresMasc model) {
    holder.tv_apellido_player.setText(model.getAPELLIDO());
    holder.tv_nombre_player.setText(model.getNOMBRE());
    holder.tv_dni_player.setText(model.getDNI());
    holder.tv_club_player.setText(model.getCLUB());
}

@NonNull
@Override
public ListaHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.lista_jugadores,
            parent, false);
    return new ListaHolder(v);
}

class ListaHolder extends RecyclerView.ViewHolder {
    TextView tv_apellido_player, tv_nombre_player, tv_dni_player, tv_club_player;

    public ListaHolder(@NonNull View itemView) {
        super(itemView);
        tv_apellido_player = itemView.findViewById(R.id.tv_apellido_player);
        tv_nombre_player = itemView.findViewById(R.id.tv_nombre_player);
        tv_dni_player = itemView.findViewById(R.id.tv_dni_player);
        tv_club_player = itemView.findViewById(R.id.tv_club_player);
    }
}

public void deleteItem(int position) {
    getSnapshots().getSnapshot(position).getReference().delete();
}

}
Lista:
public class JugadoresMasc {

private String APELLIDO;
private String NOMBRE;
private String DNI;
private String CLUB;
private String SEXO;

public JugadoresMasc(){

}

public JugadoresMasc(String APELLIDO, String NOMBRE, String SEXO, String DNI, String CLUB){
    this.APELLIDO = APELLIDO;
    this.NOMBRE = NOMBRE;
    this.DNI = DNI;
    this.CLUB = CLUB;
    this.SEXO = SEXO;
}

public String getAPELLIDO() {
    return APELLIDO;
}

public String getNOMBRE() {
    return NOMBRE;
}

public String getDNI() {
    return DNI;
}

public String getCLUB() {
    return CLUB;
}

public String getSEXO() {
    return SEXO;
}

}
Funcion del Recyclerview:
private void PadronMasculinoClient() {
    Query query = jugadoresRef.orderBy("APELLIDO", Query.Direction.ASCENDING);

    FirestoreRecyclerOptions<JugadoresMasc> options = new FirestoreRecyclerOptions.Builder<JugadoresMasc>()
            .setQuery(query, JugadoresMasc.class)
            .build();

    adapter = new JugadoresMasc_Adapter(options);

    RecyclerView recyclerView = findViewById(R.id.recycler_masculino_client);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(adapter);
}

@Override
protected void onStart() {
    super.onStart();
    adapter.startListening();
}

@Override
protected void onStop() {
    super.onStop();
    adapter.stopListening();
}

Todo esto funciona bien, el problema es que nose y no encuentro como hacer ese "Autofiltro" para que el Recycler solo me muestre documentos con de un valor especifico que sea igual al del usuario que lo consulta.

A: Para traer usuarios con el filtro que querés usar para llenar ese RecyclerView, deberias usar las queries compuestas que ofrece Firebase, podes ordenar por apellido y por club, por ejemplo, esta Query te traeria de esa colección todos los usuarios cuyo apellido sea el que vos le pasas y club sea el que vos le pasas.
Query query = jugadoresRef.whereEqualTo("APELLIDO",apellido).whereEqualTo("CLUB",club)

Solo cambiando esto, ahora los documentos que vas a traer de esa colección van a venir filtrados por apellido y club de acuerdo a los parametros que vos le mandes en esa clausula.
Tené en cuenta que cuando uses esto vas a necesitar crear una query compuesta en Firestore, por lo que cuando ejecutes por primera vez este código, tu recyclerview no va a mostrar nada, para eso anda al logcat, y fijate que Firebase te indica que necesitas crear la query compuesta siguiendo un link, clicka ese link y ya se genera esta query en la consola, despues que se genere, solamente ingresa de nuevo a la app y ya deberia tu recyclerview solo mostrarte docmentos que cumplen esta condicion dentro de tu recyclerview
Podés leer mas sobre esto en la documentación
https://firebase.google.com/docs/firestore/query-data/queries?hl=es
O seguír uno de mis videos que explico como crear estas queries
https://www.youtube.com/watch?v=oKTfnF6hVV0


text:
Q: Cookie Gets removed from different subDomain when removing from one My main Domain is 'example.com' when i set cookie in this it will be accessible to both 'h-example.com' and 'k-example.com' But when i remove cookie from 'h-example.com' i don't want to remove it from 'k-example.com' too. But at time of logout when i removing cookie it gets logout from other subDomains too.
At time of Login
res.cookie('cookieToken', token, {maxAge: 24 * 60 * 60 * 1000,httpOnly: true,secure:true,domain:'.example.com');

At time of Logout
res.clearCookie('cookieToken', {path: '/',domain: '.example.com'});

Please let me know if i miss anything.
I tried with setting cookie with diffrent Domain name as per condition. But it gets logout directly.
At time of Login
res.cookie('cookieToken', token, {maxAge: 24 * 60 * 60 * 1000,httpOnly: true,secure:true,domain:'h.example.com');

res.cookie('cookieToken', token, {maxAge: 24 * 60 * 60 * 1000,httpOnly: true,secure:true,domain:'k.example.com');

At time of Logout
res.clearCookie('cookieToken', {path: '/',domain: 'h.example.com'});
res.clearCookie('cookieToken', {path: '/',domain: 'k.example.com'});


text:
Q: My container is being exiting itself while creating , What is the solution to solve this issue? Am trying to build a docker image for my django webapp and upload it to the docker hub . Then pull that image using kubernetes . Am in trouble creating container out of my docker image , Whenever I create my container is exiting itself, Am I doing any mistake while creating a Dockerfile ?
DOCKER FILE :
FROM python:3

ENV PYTHONDONTWRITEBYTECODE=1

ENV PYTHONUNBUFFERED=1

WORKDIR /django-app

COPY requirments.txt /django-app/

RUN pip install -r requirments.txt

ADD . /django-app

COPY . /django-app/

CMD [ "python", "./manage.py runserver 0.0.0.0:8000" ]

REQUIRMENTS FILE(requirments.txt)
Django>=4.0
psycopg2>=2.8

Container exiting:

While I checked my container logs , It shows "python: can't open file '/django-app/./manage.py runserver 0.0.0.0:8000': [Errno 2] No such file or directory"

A: By doing
CMD [ "python", "./manage.py runserver 0.0.0.0:8000" ]

Python will look for a file called ./manage.py runserver 0.0.0.0:8000 which doesn't exist. You need to split the parameters up so it becomes
CMD [ "python", "./manage.py", "runserver", "0.0.0.0:8000" ]

You can also use the simpler syntax of
CMD python ./manage.py runserver 0.0.0.0:8000

if you prefer.

A: There was a problem with the path when starting
CMD [ "python", "/django-app/manage.py", "runserver", "0.0.0.0:8000" ]


text:
Q: Why does the C++ compiler generate a temporary here? The following class is intended to monitor the changing state of another process; its constructor sets up const references to facilitate access to the relevant variables. Here's The ctor code:
template<typename FZYRSRC>
struct MergeableHeight: public FzyQty<FZYRSRC>
{
MergeableHeight(
    const DDBuffer& me, const DDBuffer& neighbor, Orientation ori, bool useV =false)
: iP(me[PEAK_V].index()), iNP(neighbor[PEAK_V].index()),
  facingNeighbor(iP < iNP ? RIGHT_V : LEFT_V),  //vertex pointing to neighbor
  facingMe(iP < iNP ? LEFT_V : RIGHT_V),        //neighbor's vertex pointing to me
  iMyEdge(edgeBar(me,facingNeighbor)), iNeighborEdge(edgeBar(neighbor,facingMe)),
  myEdgeVal(me[facingNeighbor].datum()), neighborEdgeVal(neighbor[facingMe].datum()),
  myPeakVal(me[PEAK_V].datum()), useVolatility(useV),o(ori)
{}

 //member functions etc.
 private:
      virtual MergeableHeight* clone()const {return new MergeableHeight(*this);}
const int &iP, &iNP;
const PeakVertex facingNeighbor, facingMe; //PeakVertex is Enum {LEFT_V,PEAK_V,RIGHT_V}
const int &iMyEdge, &iNeighborEdge;
const double &myEdgeVal, &neighborEdgeVal, &myPeakVal;
const Orientation o;
bool useVolatility;
  };

The class data members of interest are the two const int references iMyEdge and iNeighborEdge, initialized as
  iMyEdge(edgeBar(me,facingNeighbor)), iNeighborEdge(edgeBar(neighbor,facingMe)),

and the 3 const float references myEdgeVal, neighborEdgeVal, myPeakVal, initialized as
  myEdgeVal(me[facingNeighbor].datum()),
  neighborEdgeVal(neighbor[facingMe].datum()),
  myPeakVal(me[PEAK_V].datum()),

In the former case (the ints) the references work as expected. In the floats case, the compiler gives the message
"warning C4413: 'MergeableHeight::myEdgeVal' : reference member is initialized to a temporary that doesn't persist after the constructor exits," and similarly for the other two floats.
The user-defined DDBuffer type encapsulates a vector with a fixed number of DataDescriptors -- another user-defined type. DataDescriptor provides the member function datum(),
const float& datum()const {return _datum;}

while DDBuffer provides the [] operator,
const DatumDescriptor& operator[](int i)const {return buffer.at(i);}
DatumDescriptor& operator[](int i) {return buffer.at(i);} //const & non-const versions

Since everthing returns references, why on earth is a temporary being created here? In particular, the whole point is that the state variables should reflect the actual values in the references passed to the ctor, so I certainly wouldn't want a temporary created even if it was to remain in scope.
What am I missing??

A: datum() returns a const float& and your variable is a const double&. You cannot convert one to the other, hence the temporary.

A: myEdgeVal is a reference to the data stored in me which is passed to the constructor.  As me is itself a const reference, it could be a temporary variable.  If it is, then myEdgeVal would be a reference to something inside an object that's destroyed after the constructor completes.
How do you construct the MergeableHeight object in your code?
Also, as all of those member int/double variables are constant, there is no need to make them references.

A: Sure, me is a ref-to-const, and so is the result of me[facingNeighbor].datum().
However, the latter is a const float& and you're trying to bind it to a const double&, requiring a conversion. This produces a temporary, and it's one that exists only in the scope of the constructor.
Though its lifetime can be extended in higher stack frames (by binding to ref-to-const, as you know) it cannot magically be brought into lower stack frames.

Consider:
int foo();
const int& x = foo(); // valid; the result of foo() may exist as long as x does

But:
const int& foo() {
   return 5;          // not valid; returning reference to local variable
}

int x        = foo();
const int& y = foo(); // same issue.
                      // the `5` simply doesn't exist; its stack frame is gone.


text:
Q: retrieving data from db dynamic doesn't work I have my data in mysql. I am using PDO to pull data with php then using json_encode to convert to js. When i use following scenario, i always get output NaN and if i use static array it works. So I am guessing it's either wrong json format or something with php.
This works if I set values for array smoothly:
codepen: http://codepen.io/pghiran/pen/QEvRjW
Dynamic (pulling data from db and storing in array, doesn't work. My code for doing this:
PHP
$exchangeRates =  array();

$sql = 'SELECT * FROM exchange';

try {
    $stmt = $conn->prepare($sql);
    $stmt->execute();

    for ($i=0; $row=$stmt->fetch();$i++){
        $exchangeRates[] = array($row['rs3'],$row['07'],$row['deadman'],$row['currency']);
    }
}catch(exception $e){
    return $e;
}

var_dump($exchangeRates);

var_dump displays: array(1) { [0]=> array(4) { [0]=> string(3) "0.5" [1]=> string(3) "1.5" [2]=> string(3) "3.5" [3]=> string(1) "$" } }
JS/Jquery:
var amount = $('#amount'),
                    goldtype = $('#goldtype'),
                    exchange= <?php echo json_encode($exchangeRates);?>,
                    price = $('#price');

                    console.log(exchange);

                    goldtype.change(function () {
                        var exchangeIndex = $("select[name='goldtype'] option:selected").index();
                        price.val(amount.val() * exchange[exchangeIndex]);
                    })

console.log(exchange) displays:
[Array[4]]
0
:
Array[4]
0
:
"0.5"
1
:
"1.5"
2
:
"3.5"
3
:
"$"
length
:
4

https://gyazo.com/b167b38d62d9c4b567f31cc35ce00289

A:   $exchangeRates[] = array($row['rs3'],$row['07'],$row['deadman'],$row['currency']);

This was saving in exchangeRates[0] only. I had change this line to:
  $exchangeRate = array($row['rs3'],$row['07'],$row['deadman'],$row['currency']);


text:
Q: CXF interceptor not invoked to read http response I am writing the client for a web service and I want to do two things using interceptor-
1) Log the outgoing XML message and 2) Read the HTTP response, not the SOAP response.
The service side has only a void method and they just acknowledge the receipt of my message through the HTTP response code.
This is what their response looks like:
HTTP/1.1 202 Accepted
Date: Wed, 10 Jul 2013 23:06:36 GMT
Server: Oracle-Application-Server-11g
Content-Length: 0
X-ORACLE-DMS-ECID: 004sJ1KLm7yB_6RjMX^QsA0002X30001U5
X-Powered-By: Servlet/2.5 JSP/2.1
Content-Type:
Content-Language: en
X-F5-ServerSSL-Profile: serverssl_sys_soaorexafun
X-F5-ForwardProxy-Host: 64.181.184.15%819 443

I need the "HTTP/1.1 202 Accepted" response.
My interceptor code is:
package com.cambiahealth.orservice.client;

import org.apache.cxf.binding.soap.interceptor.EndpointSelectionInterceptor;
import org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.log4j.Logger;

public class CoverOregonServiceInterceptor extends AbstractPhaseInterceptor<Message> {

    static Logger logger = Logger.getLogger(CoverOregonServiceInterceptor.class.getName());
    private static Integer responseCode = 0;

    public CoverOregonServiceInterceptor() {
        super(Phase.POST_INVOKE);
        addAfter(ReadHeadersInterceptor.class.getName());
        addAfter(EndpointSelectionInterceptor.class.getName());
    }

    @Override
    public void handleMessage(Message message) throws Fault {
        try{
            responseCode = (Integer) message.get(Message.RESPONSE_CODE);
            logger.info("Response Code is " + responseCode);
        } catch (Exception e){
            logger.error("Failed to read the response code from Soap message", e);
        }
    }

    public Integer getResponseCode(){
        return responseCode;
    }

}

And the code in my client is:
String wsdlUrl = coverOregonServiceUrl + "?wsdl";
CoverOregonServiceInterceptor interceptor = new CoverOregonServiceInterceptor();
CoverOregonServiceInterceptor outInterceptor = new CoverOregonServiceInterceptor();
InboundEnrollmentManagementClient client = new InboundEnrollmentManagementClient(
                    new URL(wsdlUrl));
InboundEnrollManagementPortType port = client.getInboundEnrollManagementPort();
Client cxfClient = ClientProxy.getClient(port);
cxfClient.getInInterceptors().add(interceptor);
cxfClient.getOutFaultInterceptors().add(outInterceptor);
port.statusupdate(request);

However, my interceptor is not getting invoked/triggered at all. I tried various different phases - READ, RECEIVE, PRE_INVOKE, POST_INVOKE, INVOKE, POST_STREAM, SEND. But none of them worked. I tried a similar interceptor to log the XML message before sending the request also. And it's not working there as well. Any suggestions?

A: Figured it out. The service I am calling does not have a return so I cannot use the inbound interceptor chain.
cxfClient.getInInterceptors().add(interceptor);

I used it in the outbound chain and it worked.
cxfClient.getOutInterceptors().add(outInterceptor);


text:
Q: delayed_job in rails docker is not working properly I have shifted my rails application to docker. Everything is working fine except the rails delayed_job. I have use delayed_job to send email. I have started my job through command docker-compose run web rake jobs:work it has started succesfully as shown in the image.

Now when I am trying to send email in console it is showing that the email is initiated as shown in the above image.
Do I have to include any line in my docker-compose.yml or Dockerfile.
My Dockerfile is :
FROM ruby:2.3.6

RUN mkdir -p /railsapp
WORKDIR /railsapp

RUN apt-get update && apt-get install -y nodejs --no-install-recommends
RUN apt-get update && apt-get install -y mysql-client  --no-install-recommends

COPY Gemfile /railsapp/

COPY Gemfile.lock /railsapp/

RUN bundle install

COPY . /railsapp

EXPOSE 3000
CMD ["rails", "server", "-b", "0.0.0.0"]

My docker-compose.yml is :
  version: '3.3'

  services:
    mysql:
      image: mysql
      restart: always
      ports:
        - "3002:3002"
      volumes:
        - /var/lib/mysql
      environment:
        - MYSQL_ROOT_PASSWORD=root
        - MYSQL_DATABASE=dev

    web:
      build: .
      environment:
        - RAILS_ENV=development
      ports:
        - '3000:3000'
      volumes:
        - .:/railsapp
      links:
        - "mysql"
      depends_on:
        - mysql

I am completely new to docker.

A: I am not sure how you have configured your ActionMailer, but if you are using default settings, you are probably sending e-mail via your servers built-in Mail Transfer Agent. In practice, this means that Rails invokes a system command called sendmail which accepts the outgoing e-mail and puts it in a local queue to be picked up by a service/daemon called postfix. Unless you have explicitly enabled it, Postfix is not running inside your Docker container and your e-mails are not going anywhere.
You can see an example of sendmail here: https://help.dreamhost.com/hc/en-us/articles/216687518-How-do-I-use-Sendmail-
You have two options.
1) Enable Postfix inside your Delayed Job container. This involves finding out which OS package to install and which daemon/service to run.
2) Switch to an external SaaS mailing service such as Sendgrid or Mailgun. These services expose REST or SOAP API's which ActionMailer can call directly to ship a particular e-mail. This eliminates the needs to host your own postfix server. In addition, these third party services are specialized in correct delivery, which reduces the risk of your e-mails inadvertedly going into the recipients spam folder. I recommend this approach.


text:
Q: Errors trying to start ZetaSQL planner I'm trying to run a Beam pipeline with SQL transforms, parsed with ZetaSQL. I begin with setting options with
options.setPlannerName("org.apache.beam.sdk.extensions.sql.zetasql.ZetaSQLQueryPlanner");
When I try creating my SqlTransform with any given query, I get
java.util.ServiceConfigurationError: org.apache.beam.repackaged.sql.com.google.zetasql.ClientChannelProvider: Provider org.apache.beam.repackaged.sql.com.google.zetasql.JniChannelProvider could not be instantiated
    at java.util.ServiceLoader.fail (ServiceLoader.java:232)
    at java.util.ServiceLoader.access$100 (ServiceLoader.java:185)
    at java.util.ServiceLoader$LazyIterator.nextService (ServiceLoader.java:384)
    at java.util.ServiceLoader$LazyIterator.next (ServiceLoader.java:404)
    at java.util.ServiceLoader$1.next (ServiceLoader.java:480)
    at org.apache.beam.repackaged.sql.com.google.zetasql.ClientChannelProvider.loadChannel (ClientChannelProvider.java:31)
...
    at org.apache.beam.sdk.extensions.sql.SqlTransform.expand (SqlTransform.java:82)
    at org.apache.beam.sdk.Pipeline.applyInternal (Pipeline.java:539)
    at org.apache.beam.sdk.Pipeline.applyTransform (Pipeline.java:473)
    at org.apache.beam.sdk.values.PCollection.apply (PCollection.java:357)
...

I've added the following relevant dependencies to my POM in maven:
        <dependency>
            <groupId>org.apache.beam</groupId>
            <artifactId>beam-runners-google-cloud-dataflow-java</artifactId>
            <version>2.15.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.beam</groupId>
            <artifactId>beam-sdks-java-extensions-sql</artifactId>
            <version>2.16.0</version>
        </dependency>

Is there something else I'm missing here?

A: Unfortunately the ZetaSQL planner will today not work from a MAC, or older versions of Linux. Please see the comment from Rui in:
ZetaSQL Sample Using Apache beam
Looks like this PR maybe useful here ( I have not dug deeply into this to confirm):
https://github.com/google/zetasql/pull/3
As a workaround could you try on a newer version of linux? Maybe in a container?

A: This is resolved in the latest version of ZetaSQL, which will be used with Beam 2.21. You can also try pulling down a newer version of ZetaSQL (at least 2020.03.2):
    <dependency>
        <groupId>com.google.zetasql</groupId>
        <artifactId>zetasql-jni-channel</artifactId>
        <version>2020.03.2</version>
    </dependency>


text:
Q: Oh-My-Zsh completion not working I reinstalled my computer running macOS Sierra and also reinstalled oh-my-zsh. I copied over my old zshrc, which was working fine (and is still working fine on another computer).
However, every start of the zsh, the following output emerges, before the shell starts up:
    bracketed-paste-magic () {
        # undefined
        builtin autoload -XUz
}
colors () {
        emulate -L zsh
        typeset -Ag color colour
        color=(00 none 01 bold 02 faint 22 normal 03 standout 23 no-standout 04 underline 24 no-underline 05 blink 25 no-blink 07 reverse 27 no-reverse 08 conceal 28 no-conceal 30 black 40 bg-black 31 red 41 bg-red 32 green 42 bg-green 33 yellow 43 bg-yellow 34 blue 44 bg-blue 35 magenta 45 bg-magenta 36 cyan 46 bg-cyan 37 white 47 bg-white 39 default 49 bg-default)
        local k
        for k in ${(k)color}
        do
                color[${color[$k]}]=$k
        done
        for k in ${color[(I)3?]}
        do
                color[fg-${color[$k]}]=$k
        done
        color[grey]=${color[black]}
        color[fg-grey]=${color[grey]}
        color[bg-grey]=${color[bg-black]}
        colour=(${(kv)color})
        local lc=$'\e[' rc=m
        typeset -Hg reset_color bold_color
        reset_color="$lc${color[none]}$rc"
        bold_color="$lc${color[bold]}$rc"
        typeset -AHg fg fg_bold fg_no_bold
        for k in ${(k)color[(I)fg-*]}
        do
                fg[${k#fg-}]="$lc${color[$k]}$rc"
                fg_bold[${k#fg-}]="$lc${color[bold]};${color[$k]}$rc"
                fg_no_bold[${k#fg-}]="$lc${color[normal]};${color[$k]}$rc"
        done
        typeset -AHg bg bg_bold bg_no_bold
        for k in ${(k)color[(I)bg-*]}
        do
                bg[${k#bg-}]="$lc${color[$k]}$rc"
                bg_bold[${k#bg-}]="$lc${color[bold]};${color[$k]}$rc"
                bg_no_bold[${k#bg-}]="$lc${color[normal]};${color[$k]}$rc"
        done
}
compdump () {
        # undefined
        builtin autoload -XUz
}
compinit () {
        emulate -L zsh
        setopt extendedglob
        typeset _i_dumpfile _i_files _i_line _i_done _i_dir _i_autodump=1
        typeset _i_tag _i_file _i_addfiles _i_fail=ask _i_check=yes _i_name
        while [[ $# -gt 0 && $1 = -[dDiuC] ]]
        do
                case "$1" in
                        (-d) _i_autodump=1
                                shift
                                if [[ $# -gt 0 && "$1" != -[dfQC] ]]
                                then
                                        _i_dumpfile="$1"
                                        shift
                                fi ;;
                        (-D) _i_autodump=0
                                shift ;;
                        (-i) _i_fail=ign
                                shift ;;
                        (-u) _i_fail=use
                                shift ;;
                        (-C) _i_check=
                                shift ;;
                esac
        done
        typeset -gHA _comps _services _patcomps _postpatcomps
        typeset -gHA _compautos
        typeset -gHA _lastcomp
        if [[ -n $_i_dumpfile ]]
        then
                typeset -g _comp_dumpfile="$_i_dumpfile"
        else
                typeset -g _comp_dumpfile="${ZDOTDIR:-$HOME}/.zcompdump"
        fi
        typeset -gHa _comp_options
        _comp_options=(bareglobqual extendedglob glob multibyte multifuncdef nullglob rcexpandparam unset NO_allexport NO_aliases NO_cshnullglob NO_cshjunkiequotes NO_errexit NO_globassign NO_globsubst NO_histsubstpattern NO_ignorebraces NO_ignoreclosebraces NO_kshglob NO_ksharrays NO_kshtypeset NO_markdirs NO_octalzeroes NO_posixbuiltins NO_shwordsplit NO_shglob NO_warncreateglobal)
        typeset -gH _comp_setup='local -A _comp_caller_options;
             _comp_caller_options=(${(kv)options[@]});
             setopt localoptions localtraps localpatterns ${_comp_options[@]};
             local IFS=$'\'\ \\t\\r\\n\\0\'';
             builtin enable -p \| \~ \( \? \* \[ \< \^ \# 2>/dev/null;
             exec </dev/null;
             trap - ZERR;
             local -a reply;
             local REPLY'
        typeset -ga compprefuncs comppostfuncs
        compprefuncs=()
        comppostfuncs=()
        : $funcstack
        compdef () {
                local opt autol type func delete eval new i ret=0 cmd svc
                local -a match mbegin mend
                emulate -L zsh
                setopt extendedglob
                if (( ! $# ))
                then
                        print -u2 "$0: I need arguments"
                        return 1
                fi
                while getopts "anpPkKde" opt
                do
                        case "$opt" in
                                (a) autol=yes  ;;
                                (n) new=yes  ;;
                                ([pPkK]) if [[ -n "$type" ]]
                                        then
                                                print -u2 "$0: type already set to $type"
                                                return 1
                                        fi
                                        if [[ "$opt" = p ]]
                                        then
                                                type=pattern
                                        elif [[ "$opt" = P ]]
                                        then
                                                type=postpattern
                                        elif [[ "$opt" = K ]]
                                        then
                                                type=widgetkey
                                        else
                                                type=key
                                        fi ;;
                                (d) delete=yes  ;;
                                (e) eval=yes  ;;
                        esac
                done
                shift OPTIND-1
                if (( ! $# ))
                then
                        print -u2 "$0: I need arguments"
                        return 1
                fi
                if [[ -z "$delete" ]]
                then
                        if [[ -z "$eval" ]] && [[ "$1" = *\=* ]]
                        then
                                while (( $# ))
                                do
                                        if [[ "$1" = *\=* ]]
                                        then
                                                cmd="${1%%\=*}"
                                                svc="${1#*\=}"
                                                func="$_comps[${_services[(r)$svc]:-$svc}]"
                                                [[ -n ${_services[$svc]} ]] && svc=${_services[$svc]}
                                                [[ -z "$func" ]] && func="${${_patcomps[(K)$svc][1]}:-${_postpatcomps[(K)$svc][1]}}"
                                                if [[ -n "$func" ]]
                                                then
                                                        _comps[$cmd]="$func"
                                                        _services[$cmd]="$svc"
                                                else
                                                        print -u2 "$0: unknown command or service: $svc"
                                                        ret=1
                                                fi
                                        else
                                                print -u2 "$0: invalid argument: $1"
                                                ret=1
                                        fi
                                        shift
                                done
                                return ret
                        fi
                        func="$1"
                        [[ -n "$autol" ]] && autoload -Uz "$func"
                        shift
                        case "$type" in
                                (widgetkey) while [[ -n $1 ]]
                                        do
                                                if [[ $# -lt 3 ]]
                                                then
                                                        print -u2 "$0: compdef -K requires <widget> <comp-widget> <key>"
                                                        return 1
                                                fi
                                                [[ $1 = _* ]] || 1="_$1"
                                                [[ $2 = .* ]] || 2=".$2"
                                                [[ $2 = .menu-select ]] && zmodload -i zsh/complist
                                                zle -C "$1" "$2" "$func"
                                                if [[ -n $new ]]
                                                then
                                                        bindkey "$3" | IFS=$' \t' read -A opt
                                                        [[ $opt[-1] = undefined-key ]] && bindkey "$3" "$1"
                                                else
                                                        bindkey "$3" "$1"
                                                fi
                                                shift 3
                                        done ;;
                                (key) if [[ $# -lt 2 ]]
                                        then
                                                print -u2 "$0: missing keys"
                                                return 1
                                        fi
                                        if [[ $1 = .* ]]
                                        then
                                                [[ $1 = .menu-select ]] && zmodload -i zsh/complist
                                                zle -C "$func" "$1" "$func"
                                        else
                                                [[ $1 = menu-select ]] && zmodload -i zsh/complist
                                                zle -C "$func" ".$1" "$func"
                                        fi
                                        shift
                                        for i
                                        do
                                                if [[ -n $new ]]
                                                then
                                                        bindkey "$i" | IFS=$' \t' read -A opt
                                                        [[ $opt[-1] = undefined-key ]] || continue
                                                fi
                                                bindkey "$i" "$func"
                                        done ;;
                                (*) while (( $# ))
                                        do
                                                if [[ "$1" = -N ]]
                                                then
                                                        type=normal
                                                elif [[ "$1" = -p ]]
                                                then
                                                        type=pattern
                                                elif [[ "$1" = -P ]]
                                                then
                                                        type=postpattern
                                                else
                                                        case "$type" in
                                                                (pattern) if [[ $1 = (#b)(*)=(*) ]]
                                                                        then
                                                                                _patcomps[$match[1]]="=$match[2]=$func"
                                                                        else
                                                                                _patcomps[$1]="$func"
                                                                        fi ;;
                                                                (postpattern) if [[ $1 = (#b)(*)=(*) ]]
                                                                        then
                                                                                _postpatcomps[$match[1]]="=$match[2]=$func"
                                                                        else
                                                                                _postpatcomps[$1]="$func"
                                                                        fi ;;
                                                                (*) if [[ "$1" = *\=* ]]
                                                                        then
                                                                                cmd="${1%%\=*}"
                                                                                svc=yes
                                                                        else
                                                                                cmd="$1"
                                                                                svc=
                                                                        fi
                                                                        if [[ -z "$new" || -z "${_comps[$1]}" ]]
                                                                        then
                                                                                _comps[$cmd]="$func"
                                                                                [[ -n "$svc" ]] && _services[$cmd]="${1#*\=}"
                                                                        fi ;;
                                                        esac
                                                fi
                                                shift
                                        done ;;
                        esac
                else
                        case "$type" in
                                (pattern) unset "_patcomps[$^@]" ;;
                                (postpattern) unset "_postpatcomps[$^@]" ;;
                                (key) print -u2 "$0: cannot restore key bindings"
                                        return 1 ;;
                                (*) unset "_comps[$^@]" ;;
                        esac
                fi
        }
        typeset _i_wdirs _i_wfiles
        _i_wdirs=()
        _i_wfiles=()
        autoload -Uz compaudit
        if [[ -n "$_i_check" ]]
        then
                typeset _i_q
                if ! eval compaudit
                then
                        if [[ -n "$_i_q" ]]
                        then
                                if [[ "$_i_fail" = ask ]]
                                then
                                        if ! read -q "?zsh compinit: insecure $_i_q, run compaudit for list.
Ignore insecure $_i_q and continue [y] or abort compinit [n]? "
                                        then
                                                print -u2 "$0: initialization aborted"
                                                unfunction compinit compdef
                                                unset _comp_dumpfile _comp_secure compprefuncs comppostfuncs _comps _patcomps _postpatcomps _compautos _lastcomp
                                                return 1
                                        fi
                                        _i_wfiles=()
                                        _i_wdirs=()
                                else
                                        (( $#_i_wfiles )) && _i_files=("${(@)_i_files:#(${(j:|:)_i_wfiles%.zwc})}")
                                        (( $#_i_wdirs )) && _i_files=("${(@)_i_files:#(${(j:|:)_i_wdirs%.zwc})/*}")
                                fi
                        fi
                        typeset -g _comp_secure=yes
                fi
        fi
        autoload -Uz compdump compinstall
        _i_done=''
        if [[ -f "$_comp_dumpfile" ]]
        then
                if [[ -n "$_i_check" ]]
                then
                        IFS=$' \t' read -rA _i_line < "$_comp_dumpfile"
                        if [[ _i_autodump -eq 1 && $_i_line[2] -eq $#_i_files && $ZSH_VERSION = $_i_line[4] ]]
                        then
                                builtin . "$_comp_dumpfile"
                                _i_done=yes
                        fi
                else
                        builtin . "$_comp_dumpfile"
                        _i_done=yes
                fi
        fi
        if [[ -z "$_i_done" ]]
        then
                typeset -A _i_test
                for _i_dir in $fpath
                do
                        [[ $_i_dir = . ]] && continue
                        (( $_i_wdirs[(I)$_i_dir] )) && continue
                        for _i_file in $_i_dir/^([^_]*|*~|*.zwc)(N)
                        do
                                _i_name="${_i_file:t}"
                                (( $+_i_test[$_i_name] + $_i_wfiles[(I)$_i_file] )) && continue
                                _i_test[$_i_name]=yes
                                IFS=$' \t' read -rA _i_line < $_i_file
                                _i_tag=$_i_line[1]
                                shift _i_line
                                case $_i_tag in
                                        (\#compdef) if [[ $_i_line[1] = -[pPkK](n|) ]]
                                                then
                                                        compdef ${_i_line[1]}na "${_i_name}" "${(@)_i_line[2,-1]}"
                                                else
                                                        compdef -na "${_i_name}" "${_i_line[@]}"
                                                fi ;;
                                        (\#autoload) autoload -Uz "$_i_line[@]" ${_i_name}
                                                [[ "$_i_line" != \ # ]] && _compautos[${_i_name}]="$_i_line"  ;;
                                esac
                        done
                done
                if [[ $_i_autodump = 1 ]]
                then
                        compdump
                fi
        fi
        for _i_line in complete-word delete-char-or-list expand-or-complete expand-or-complete-prefix list-choices menu-complete menu-expand-or-complete reverse-menu-complete
        do
                zle -C $_i_line .$_i_line _main_complete
        done
        zle -la menu-select && zle -C menu-select .menu-select _main_complete
        bindkey '^i' | IFS=$' \t' read -A _i_line
        if [[ ${_i_line[2]} = expand-or-complete ]] && zstyle -a ':completion:' completer _i_line && (( ${_i_line[(i)_expand]} <= ${#_i_line} ))
        then
                bindkey '^i' complete-word
        fi
        unfunction compinit compaudit
        autoload -Uz compinit compaudit
        return 0
}
compinstall () {
        # undefined
        builtin autoload -XUz
}
down-line-or-beginning-search () {
        # undefined
        builtin autoload -XU
}
edit-command-line () {
        # undefined
        builtin autoload -XU
}
is-at-least () {
        emulate -L zsh
        local IFS=".-" min_cnt=0 ver_cnt=0 part min_ver version order
        min_ver=(${=1})
        version=(${=2:-$ZSH_VERSION} 0)
        while (( $min_cnt <= ${#min_ver} ))
        do
                while [[ "$part" != <-> ]]
                do
                        (( ++ver_cnt > ${#version} )) && return 0
                        if [[ ${version[ver_cnt]} = *[0-9][^0-9]* ]]
                        then
                                order=(${version[ver_cnt]} ${min_ver[ver_cnt]})
                                if [[ ${version[ver_cnt]} = <->* ]]
                                then
                                        [[ $order != ${${(On)order}} ]] && return 1
                                else
                                        [[ $order != ${${(O)order}} ]] && return 1
                                fi
                                [[ $order[1] != $order[2] ]] && return 0
                        fi
                        part=${version[ver_cnt]##*[^0-9]}
                done
                while true
                do
                        (( ++min_cnt > ${#min_ver} )) && return 0
                        [[ ${min_ver[min_cnt]} = <-> ]] && break
                done
                (( part > min_ver[min_cnt] )) && return 0
                (( part < min_ver[min_cnt] )) && return 1
                part=''
        done
}
up-line-or-beginning-search () {
        # undefined
        builtin autoload -XU
}
url-quote-magic () {
        # undefined
        builtin autoload -XUz
}

It seems some kind of script is written to stdout, instead of executed. However, I cannot find what the problem is. It might have something to do with completion, as the completion is not working.
Does anyone has any suggestion what the problem might be or  where I should look next?

A: I was facing the same issue.
Re-installing Homebrew fixed the problem.

A: You have to change the default shell to zsh.
chsh -s /bin/zsh


text:
Q: bad format of an array using latex I'm tryning to draw an array with latex, unfortunatly i'm getting a bad print.
Here is what i'm getting:

Here is the part i'm adding to show the array:
   \begin{tabular}{|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|}
  \hline
  N & 1 & 2 &3& 4 &5& 6& 7& 8& 9& 10& 11& 12& 13& 14& 15& 16& 17 \\
  \hline
  Solution & 1& 1& 1& 2& 3& 3& 4& 5& 5& 5& 5& 6& 7& 8& 9& 9& 9 \\
  \hline
\end{tabular}

Can anyone help me to resolve this issue.
Thank you

A: The argument to \begin{tabular} should contain a specification for the columns you want. The standard legal specifiers are

*

*c for a centered column;

*l for a left aligned column;

*r for a right aligned column;

*| for a vertical line between columns (or at either side of the table);

*p for a "paragraph" column, but it should be be followed by a width specification such as p{2cm} (any length specification is valid);

*@ for intercolumn material different from the standard spacing, with the material in braces after @, for instance @{} will remove the intercolumn spacing, @{+} would insert a + instead of the space.

One can use the shorthand
*{<number>}{<specifiers>}

for repeating a group of column specifiers the given number of times. In your case you want eighteen groups of the form c| preceded by a single |, so
\begin{tabular}{ | *{18}{c|} }

which is easier to read than the equivalent
\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}

With your code you get a large number of errors of the form
! LaTeX Error: Illegal character in array arg.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.5 ...lar}{|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|}

These are raised because of a b d e f g h i j k m n o q that are illegal (and LaTeX tries to recover with c instead). There is also
! Missing number, treated as zero.
<to be read again>
                   |
l.7 ...&3& 4 &5& 6& 7& 8& 9& 10& 11& 12& 13& 14& 1
                                                  5& 16& 17 \\
A number should have been here; I inserted `0'.
(If you can't figure out why I needed to see a number,
look up `weird error' in the index to The TeXbook.)

! Illegal unit of measure (pt inserted).
<to be read again>
                   |
l.7 ...&3& 4 &5& 6& 7& 8& 9& 10& 11& 12& 13& 14& 1
                                                  5& 16& 17 \\
Dimensions can be in units of em, ex, in, pt, pc,
cm, mm, dd, cc, nd, nc, bp, or sp; but yours is a new one!
I'll assume that you meant to say pt, for printer's points.
To recover gracefully from this error, it's best to
delete the erroneous units; e.g., type `2' to delete
two letters. (See Chapter 27 of The TeXbook.)

which is due to p being followed by | instead of a length in braces.
There is some output thanks to the error recovery, but it's just what it is. Never disregard errors during typesetting.


text:
Q: How can I get all list of scopes in ActiveRecord 3.x I am using ActiveRecord with Rails 3.
I defined scopes in my model. How can I get the list of all scopes of that model?
Previously I could use Model.scopes
OR
Can I check a scope is defined or not? Something like Model.scope_defined?("scope_name")
Thanks in advance.

A: You can see if a scope is defined or not this way
Model.send(:valid_scope_name?, :scope_name)

it will return true if it does exist and nil if it does not.
If you check the source code of valid_scope_name?, you see that you can just test it using respond_to? and then avoid the logging part.
Model.respond_to?(scope_name, true)


text:
Q: Why return a clone of an object in oop? I recently had to use Slim\Http\Message and Slim\Http\Request to get the users posted data.
I noticed something in the method withBody() where it was returning a clone of the object instead of $this.
This caused me some trouble as I couldn't get my application to work until I assigned $request->withBody(...) to a variable ($request) and then carried on using that new variable in my script.
I have a mock example to explain (see comments in the code);
class Request {
    protected $body;

    public function addBody($body) {
        $clone = clone $this;
        $clone->body = $body;
        return $clone;
    }

    public function getBody() {
        return $this->body;
    }
}

$request = new Request;

// this will return NULL
$request->addBody([
    'name' => 'john',
    'email' => 'john@example.com',
]);

var_dump($request->getBody());

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

// but this will return the "body" that was passed in above.
$request = $request->addBody([
    'name' => 'john',
    'email' => 'john@example.com',
]);

var_dump($request->getBody());

I see what is happening here. But I don't understand why a class would be implemented like this.
What are the benefits? Why restrict a developer in this way?

A: Slim uses the PSR-7 HTTP Messaging Interface standard, which describes itself as follows:
<?php
namespace Psr\Http\Message;

/**
 * HTTP messages consist of requests from a client to a server and responses
 * from a server to a client. This interface defines the methods common to
 * each.
 *
 * Messages are considered immutable; all methods that might change state MUST
 * be implemented such that they retain the internal state of the current
 * message and return an instance that contains the changed state.
 *
 * @see http://www.ietf.org/rfc/rfc7230.txt
 * @see http://www.ietf.org/rfc/rfc7231.txt
 */
interface MessageInterface
{
    //etc
}

"Messages are considered immutable". They are considered Value objects, which must never change state, and if you do want to change state, a new instance is returned.
Here's a link explaining Value Objects http://deviq.com/value-object/
And a little extract from the page I linked:

A Value Object is an immutable type that is distinguishable only by
  the state of its properties. That is, unlike an Entity, which has a
  unique identifier and remains distinct even if its properties are
  otherwise identical, two Value Objects with the exact same properties
  can be considered equal. Value Objects are a pattern first described
  in Evans' Domain-Driven Design book, and further explained in Smith
  and Lerman's Domain-Driven Design Fundamentals course.

Hopefully this will help you understand why!
Finally, have a wee look at the actual PSR-7 Standard here http://www.php-fig.org/psr/psr-7/

A: I would like to ask the same question...
The only benefit I can discover in this design is that you can chain some method calls together like in PSR-7 HttpClients this..
$request = $request
  ->withBody($body)
  ->withHeader('Content-Lenght', strlen($body))
  ->withHeader('Content-Type', 'text/plain')
  ->withHeader('User-Agent', 'xxxx');

But in my opinion that small benefit is not worth to accept all negative effects of this.
E.g. with this Design for each method call a copy of the opject is created.
What means a lot of memory wasting when you have big data objects, or when you have many method calls.


text:
Q: Entity type has no key defined EF6 Here is my code although I already have refined the key attribute but still there is a problem.
public class Contacts
{
    [Key]
    public int ContactId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
}

The error I get is:

Entity Type 'Contacts'  has no key defined. Define the key for this entity type.
  Entity type: EntitySet 'Contacts' is based on type 'Contacts' that has no key defined

A: If you are using EF Code First (not specified in your question), you will need to change the ContactId property name to ContactsId to match the convention of ClassName + Id in order to define the key for your Contacts entity type.
See the MSDN Code First Conventions: http://msdn.microsoft.com/en-us/data/jj679962.aspx

A: I know that this has already been answered in one fashion, but I wanted to post a different approach for those who encounter this.
This error occurred for me even while having [Key] defined above the property I wanted to designate as the Primary Key. The error, occurring during the Update-Database command, was caused by my naming of the migration (through Add-Migration) the same as the entity that I wanted to be added. This is because the Add-Migration command created a partial class which matched the entity name.
For example:
public class Contacts
{
    [Key]
    public int ContactId { get; set; }
    public string Name { get; set; }
}

Didn't work when I executed:
Add-Migration Contacts
Update-Database

because the migration class signature looked like the below, and the body contained no property with the [Key] attribute
public sealed partial class Contacts

To solve this, I deleted the identically-named migration and modified the Add-Migration command:
Add-Migration ContactsTable
Update-Database


text:
Q: Begin root process at boot? I'd like to start a background process as root when my Linux install boots. Can I just add it to a directory or a configuration file?

A: Basically you have two options:

*

*use a cron job with @reboot time specification (see crontab(1) man-page for details)

*start it by the init system. For BSD/SysV init style this means adding a script somewhere to be run in the desired runlevel. For systemd, this involves creating a unit file and requiring it by the desired target.
The first solution is better for things local to one or two machines (since they are more of a configuration thing); the second one is suited for service/daemon like things that are likely to be run on more systems -- and should actually be packaged to make maintenance easier.

A: The easiest way to run a process as root at boot time is to start it from /etc/rc.local. Edit that file and add a line like
/path/to/my/daemon &

However this is not a very good way of starting a daemon. You get no convenient way to control it (check whether it's running, stop it, restart it, etc.).
There are several frameworks to control daemons. They are tied to your init system: Sysvinit, Upstart, Systemd each have their way. Check what is installed on your system (it varies between unix variants, and for Linux, it varies by distribution and by administrator choice).


text:
Q: MySQL: Split longtext column into multiple text columns I have a slight challenge with data that I need to get solved. I have a table where the plain text of emails is stored in a longtext column. It was like this before I started developing in the framework. There are over a million rows already with large emails stored in them.
I need to be able to search for text in that field but it takes ages before any results are returned. This is not ideal because there are hundreds of users using the system and they need the ability to search email content.
I have tried the following simple SQL statement but it takes too long to find records:
select id from emails where description like "%hello world%";
According the the MySQL documentation, full-text indexing can only be used in char, varchar and text fields.
Can anyone suggest an efficient way to search in a longtext column?
or
Are there any SQL methods / commands that can be used to run through the table and splitting the longtext field's content into multiple text columns for full-text indexing?

A:
I have tried the following simple SQL statement but it takes too long
  to find records: select id from emails where description like "%hello
  world%";

Unfortunately mysql cannot use indexes for %something% queries even on varchar fields. In fact it cannot use indexes on '%something' queries either. Indexes can be used only when the wild card occurs at the end of the string.

According the the MySQL documentation, full-text indexing can only be
  used in char, varchar and text fields.

I wish the documentation would be clearer here, this is speaking of TEXT family of fields. That means you can actually create an index on LONGTEXT and MEDIUMTEXT types of fields. Try this:
CREATE TABLE ltxt(bada LONGTEXT);
ALTER TABLE ltxt ADD FULLTEXT INDEX ftxt2(bada);

Yes, you will be pleasently surprised!


text:
Q: get data to viewPager fragment from its fragments I am using viewPager for my custom Tablayout.  I have two fragments, when viewPager activity was created , it should get the data from one of the fragment and have to display it on the tabs as unread count.
but I am getting data at scrolling. how can I over come this issue ?. please help me.

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                PendingPlusPendingForUploadFiles frage = new PendingPlusPendingForUploadFiles();
                System.out.println("====c value===" + frage.count);
            }

            @Override
            public void onPageSelected(int position) {
                //  previousTabPosition = position;
                viewPager.setCurrentItem(position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

A: you can  onResume(); method in the Fragment get it!


text:
Q: How to create a solid DropShadow effect on a translucent background in JavaFX I'm having a strange DropShadow effect when applying it to a node with translucent background color as you can see in this image:

The upper node has a solid background color while the other one has the semi transparent background color. Both of them has the same exact effect, but the second one appeared too blurry. How can I correct this?

EDIT
Here's a working demo:
public class App extends Application {
  public static void main(String[] args) {
    launch(args);
  }

  @Override
  public void start(Stage stage) {
    // The drop shadow effect.
    DropShadow effect = new DropShadow();
    effect.setBlurType(BlurType.GAUSSIAN);
    effect.setColor(Color.rgb(0,0,0, .5));
    effect.setSpread(0);
    effect.setOffsetX(0);
    effect.setOffsetY(7);

    // Node with solid background color.
    Button button1 = new Button("BUTTON");
    VBox.setMargin(button1, new Insets(0, 0, 15, 0));
    button1.setStyle("-fx-background-color: rgb(238,238,238);");
    button1.setEffect(effect);

    // Node with translucent background color.
    Button button2 = new Button("BUTTON");
    VBox.setMargin(button2, new Insets(15, 0, 0, 0));
    button2.setStyle("-fx-background-color: rgba(238,238,238, .5);");
    button2.setEffect(effect);

    VBox root = new VBox(button1, button2);
    root.setStyle("-fx-background-color: white;");
    root.setAlignment(Pos.CENTER);
    root.setPadding(new Insets(15));

    Scene scene = new Scene(root);

    stage.setScene(scene);
    stage.show();
  }
}


text:
Q: Scaling ImageButtons for various screen sizes For my app (runs Android 2.1 and above),
I was wondering how to scale buttons for various screen sizes (virtual emulators in this case) in terms of dpi, because my scaled background images seem to be "unpixelated" perfectly fine... I scaled my button ("GOT IT" as shown below) accordingly with say, an lpdi and a xxhdpi screen, and I get the following results:
For the Nexus 5 virtual emulator (xxhdpi), button supposedly at 150X34 pixels which seems to navigate to the ldpi resource director instead:

Zoomed-in for the QVGA (ldpi), button at 57X13 pixels:

All of that said, do I need to scale down the layout(s) instead considering that I implemented the scale-button images in drawable folders (xhdpi, hdpi, mdpi, and ldpi), called it in a drawable resource file, and then set the drawable resource file as the background image of the ImageButton? Here's the XML of my button btw:
<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:id="@+id/exitBtn"
    android:layout_marginBottom="57dp"
    android:src="@drawable/popup_btn"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:scaleType="centerCrop"
    android:background="@android:color/transparent" />

P.S. Is the scaled-drawable folder, xhdpi, the default location for xxhdpi screens as well? How about for xxxhdpi and above?

A: First you will have to change your Button to take up the whole screen:
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/exitBtn"
android:layout_marginBottom="52dp" <-- You may keep the margin if you like
android:background="@drawable/popup_btn"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />

Next you will have to include different resources for the different densities that you will support: mdpi, xhpdi, xxhdpi, and so on. Please make sure the resolution is appropriate for each one and avoid using the same image, files that are too big will take up memory and processing power, files are too small in resolution will look pixelated.
Edit: More on supporting different devices and screen densities:
http://developer.android.com/guide/practices/screens_support.html

A: for compatible your layouts with different screen sizes you should use dimens under res/ directory for layouts compatibility for example you can define different dimens for different screen sizes see also Providing Resources and Supporting Multiple Screens

A: create display metrics by instantiating it .now from display metrics retrieve the width and height of your whole root view
Once done implement the globallayoutchangelistener in Oncreate of your activity and place your scaling code inside the listener .
Idea is to calculate the device density first and then scale the button according to density in globallayoutchangelistener
Let me know if it works .


text:
Q: error 502 bad gateway when download file angular 11? I work on download zip file from angular 11 .
I face issue when download Large files but small files not have any issue .
Large file i download have size 2.397 kb.
it will take 7 minutes to finish download but after 2 minute give me error 502 bad gateway.
it download file from local pc without any issue but when try to download file from remote server publish give me error 502 bad gateway .
so How to solve this issue and why I get this error ?
e {headers: n, status: 502, statusText: 'Bad Gateway', url: 'https://pn.xxx.com:7072/api/Z2Delivery/ExportNxp', ok: false, …}
error: Blob
size: 1477
type: "text/html"
[[Prototype]]: Blob
headers: n
lazyInit: ƒ ()
lazyUpdate: null
normalizedNames: Map(0) {size: 0}
[[Prototype]]: Object
message: "Http failure response for https://pn.xxx.com:7072/api/Z2Delivery/ExportNxp: 502 Bad Gateway"
name: "HttpErrorResponse"
ok: false
status: 502
statusText: "Bad Gateway"
url: "https://pn.xxx.com:7072/api/Z2Delivery/ExportNxp"
[[Prototype]]: Object
constructor: ƒ e(e)
[[Prototype]]: Object

what i have tried
web api
[Route("ExportNxp")]
        public IActionResult ExportNxp(bool areIdentical)
        {

                if (areIdentical == false)
                {
                    return OK("Not Matched Excel");
                }
                else
                {

                return PhysicalFile(zipPath, "application/zip", Path.GetFileName(zipPath));

                }

        }
service.ts
PostUploadzipNxp(file:any):Observable<any>
{
  formData.append('file', file,file.name);
  return this.http.post('https://pn.xxx.com:7072/api/Z2Delivery/ExportNxp/', formData,{observe: 'response', responseType: 'blob' });
}
component.ts
 this._dataService.PostUploadzipNxp(this.fileToUpload)
     .subscribe(blob => {
       saveAs(blob.body, this.fileToUpload?.name +'.zip');
      });

A: By default, ASP.NET Core request time out is 2 minutes, and you can change it via KeepAliveTimeout in program.cs file
in .net core 6.0
var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel(t =>
{
  t.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(15);
});

in .net core 3.1
 public static void Main(string[] args)
 {
  CreateWebHostBuilder(args).Build().Run();
 }

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
  WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .ConfigureKestrel(o => { o.Limits.KeepAliveTimeout =  TimeSpan.FromMinutes(10); });


text:
Q: AnyLogic Model- Patient Scheduling Project I am currently working on a project to model outpatient appointment scheduling for a local hospital. The goal of this project is to model their current situation and then adjust different factors to reduce the wait time until the next available appointment. We are using AnyLogic to create the model. At this hospital the current system is as follows:

*

*A patient calls and schedules an appointment with one of the hospitals 19 sub-specialties.
         - appointment will either be a first time consultation lasting 1 hour or a follow up appointment lasting 15 minutes.

*Patient waits 1 week-6 months until their appointment date (based on sub-specialty)

*Patient is seen by a doctor and then exits the system
We have approached the problem in two ways, the first was to attach the schedule to the resource pool which consists of the doctors for a single sub specialty. This would allow the schedule to change as the number of doctors change. The second approach was to attach the schedule to the source which consists of the patients entering the system. This better controls the flow of individuals into the system.
We are having difficulties figuring out how to configure the model so that it accurately shows the result of adding more doctors while still allowing the flexibility we need in scheduling different length appointments in multiple sub-specialties.
If anyone has experience with AnyLogic Scheduling, has dealt with a similar problem, or has any advice on how to proceed, I would appreciate the input.
Thanks!

A: If I understand correctly, you want to change the number of resources you have according to a certain schedule...
In the schedule you need to you use integer type and then create your schedule based however you want. In the action you can use "value" as a variable that corresponds to the value of the current schedule value. The action in the schedule is activated everytime the schedule changes... so you can simply do resourcePool.set_capacity(value);
With this you have the flexibility to use different length appointments... You can use one different schedule for each sub-specialty


text:
Q: How to add labels inside and outside to the particular slice using core plot? How to add labels inside and outside to the particular slice using core plot like below image?

A: Use the plot's data labels for the values inside the plot. Add annotations with the other details outside. Core Plot doesn't have any way to draw those connecting lines to the annotations, so you'll have to render those into the annotation content yourself.


text:
Q: Whats the right way to publish an Alpha / Beta Android App? I'm just getting started with writing Android apps.
I have something I want to make available to a few interested testers, but I'm a long way from having an app. ready for the general public.
How do I make it available for testers without putting it on Play?

A: If you have a developer account, you can upload the app for testing, visible only a limited audience. This can be done without publishing the app on Play Appstore for the general public.
Google recommends this for Beta-testing and staged rollouts.

A: You can have a look to this website: http://thebetafamily.com/
On this website, both testers and creators car register. Testers will apply for tests (tests can be paid or not) and app creators can register to present their app and explain what specific parts of the website should be tested: http://thebetafamily.com/features.
I got really good feedbacks from testers there, both functional and technical, even though I did not offer any paid tests for now.
There is also TestFlight: https://testflightapp.com/ but the difference is that you have to gather your own testers team (I did not have a real network of testers to provide ...).


text:
Q: How Can I hide part of my E-mail Address Good Morning Guys! I need to get an e-mail from my database, but I'd like to show it like that:
some*******@hotmail.com
I'd like to show the beginning of my e-mail and then everything after @.
I'm using the following code:
$user_email= "********".substr($linha3['user_email'], -8);

It's working, but sometimes It doesn't appear in a nice way:
********mail.com
May you help me with any solution?

A: $email = $linha3['user_email'];
$email= substr($email, 0, 3).'****'.substr($email, strpos($email, "@"));

A: Use RegEx to always match the e-mail username :
echo preg_replace('/.*@/', '***@', 'some_mail@somewhere.net');


text:
Q: Return CurrentItem from context.Templates.Item JSLink Any ideas on how to return from the Custom Item method when using JSLink (as if it was never called)? I want to do a check in this method and hide the row if the condition fails. I know I can do a PostRender, but then I will have to loop through each row again.
overrideContext.Templates.Item = customItem;

function customItem(context) {
   if(conditionIsNotMet)
      return context.ListData.Row;
   else
      //Hide Row somehow

   //Tried return context.CurrentItem, return null, return "", return context.ListData
}

A: Have you seen this post: Filter out items in list view using jslink
Looks like you could do:
overrideContext.Templates.Item = customItem;

function customItem(context) {
   if(conditionIsNotMet) {
      return RenderItemTemplate(context);
   }
   else {
      return '';  //Hide Row somehow
   }
}

HTH


text:
Q: Why there is no Singleton concept for Action class in Struts2? I was going through differences of Struts1 vs Struts2, and came across this point:

*

*Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action.

*Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues.
Now my question is: in Struts2, why there are no singleton concept for Action class? As I think because, unnecessarily, there is more Object creation for every request.
Please correct me if I am wrong.

A: Object creation is ridiculously fast in Java. Programming thread-safe action classes (and servlets, etc.) is irritating and error-prone.
Like with everything, there's a trade-off.

A: New instance in the sense, its not creating new object but jvm will create instance of that object hence there is no matter that how many request is comming for a particular object...even if the instance is more, the applcation will not hang...


text:
Q: Why my value is not passing into secondViewController I want to pass simple String from oneVC to secondVC. I'm new to iOS.

*

*I declared String nameOfFilm.

*When I'm clicking on CollectionViewItem I'm downloading JSON, taking one value of it(String) and assign it to nameOfFilm. Then I'm starting segue to the secondVC.

*in the PrepareForSegue method with proper identifier I compare the secondVC value to the nameOfFlim.(nextScene.name = nameOfFilm)

In the result, when the secondVC comes in, nextScene.name is empty.enter image description here
JSON i parsed properly. I think it may be mismatch in time and some functions are too fast. What is causing the problem?
var nameOfFilm = String()

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    INDEX_NUMBER_BEFORE = indexPath.row
    let filmID = arrayWithID[INDEX_NUMBER_BEFORE]
    downloadFilm(url: "https://api.themoviedb.org/3/movie/\(filmID)\(key)&append_to_response=videos,images")
    performSegue(withIdentifier: "toTheDetail", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "toTheDetail" {
        let nextScene = segue.destination as! FilmDetailViewController
        nextScene.name = nameOfFilm
    }
}

A: The issue here will be that downloadFilm will be an asynchronous task that occurs in the background and takes some time to make the request and respond with the value that you need.
Your downloadFilm function should accept a callback so that you can wait for the response value and then perform an action based on that response, a typical way of using this would be something like:
downloadFilm(url: "https://api.themoviedb.org/3/movie/\(filmID)\(key)&append_to_response=videos,images") { filmName in
    self.nameOfFilm = filmName
    self.performSegue(withIdentifier: "toTheDetail", sender: self)
}

To do this you would need to update your downloadFilm function, so that its similar to this...
func downloadFilm(url: String, completion: @escaping (_ filmName: String) -> Void) {
   // do work here to setup network request
   let task = URLSession.shared.dataTask(with: request) { data, response, error in
      // parse response and get name
      completion(name)
   }
}

Here is a guide on Swift completion handlers that will help understand the concept.


text:
Q: LCOV reports: 'geninfo: Negative length' I'm analyzing C-Code with LCOV on two systems (windows 7, cygwin, Lcov 1.10). On one system I had never problems, but on the other with the same code I get:
$ lcov --directory CMakeFiles/UnitTest.dir/main --capture --output-file lcov.log
Capturing coverage data from CMakeFiles/UnitTest.dir/main
Found gcov version: 4.8.2
Scanning CMakeFiles/UnitTest.dir/main for .gcda files ...
Found 59 data files in CMakeFiles/UnitTest.dir/main
Processing analyze/analyze.c.gcda
[..]
Processing measure/measur.c.gcda
geninfo: Negative length at /usr/bin/geninfo line 2413.

On both systems the folder and files are the same (via subversion revision control). Maybe there could be a problem with some paths, I guess.
Someone knows what this is about?
Thanks, Led
Addendum: I found out that somethimes it helps to clean the project totally (delete all CMakeFiles and CMakeCache) and rerun the lcov commmand.

A: It seems that this happens if some block, for which the coverage information has been captured before, is no longer present in the object file.
The problem is that the .gcno file will still store the coverage information for such a block.
To solve the problem it is sufficient to just remove the .gcno file and rebuild your unit test.
For example, I have encountered an error like this:
[...]
Processing CMakeFiles/UnitTest.dir/main.cpp.gcda
[...]
Processing CMakeFiles/UnitTest.dir/Math/BoundingBox.cpp.gcda
geninfo: Negative length at /usr/bin/geninfo line 2413.
Processing CMakeFiles/UnitTest.dir/Math/Vectors.cpp.gcda
make[3]: *** [source/CMakeFiles/] Error 255

In this case it was sufficient to delete the "CMakeFiles/UnitTest.dir/Math/Vectors.cpp.gcno" file and then rebuild the "UnitTest" project.


text:
Q: Rails force ssl only on specified controllers I have a ssl certificate which serves https://secure.mydomain.com. I would like to use ssl only on certain controllers and not throughout my entire application. I have looked online and can't seem to find a complete and accurate tutorial on how to enable ssl for specified controllers.
I am aware that I can use the config ssl below but it does not serve me a purpose since it enables ssl site wide
config.force_ssl = true

How can I tell rails to only use ssl on a specific controller rather then my entire application?

A: You can do this with constraints in routes.rb:
resource :account, :constraints => { :protocol => "https", :subdomain => "secure" }

Also, if you have many secure routes, and you want to DRY things up, you can create a scope for your secure routes:
scope :constraints => { :protocol => "https", :subdomain => "secure" } do

  ...[secure routes]...

end


text:
Q: OpenWeatherMap API generates incorrect output I am using the openweathermap.org api, and it provides me incorrect output.
If I hit this url, I get the following output :
"{"coord":{"lon":-121.96,"lat":37.83},"weather":[{"id":721,"main":"Haze","description":"haze","icon":"50n"}],"base":"stations","main":{"temp":281.21,"pressure":1030,"humidity":81,"temp_min":273.15,"temp_max":285.15},"visibility":11265,"wind":{"speed":1.07,"deg":54.0019},"clouds":{"all":1},"dt":1454739836,"sys":{"type":1,"id":409,"message":0.0189,"country":"US","sunrise":1454771247,"sunset":1454809012},"id":5342970,"name":"Diablo","cod":200}"

If I call the same url via php curl or file_get_contents, I get the following output :
"{"coord":{"lon":-121.96,"lat":37.83},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"base":"cmc stations","main":{"temp":275.178,"pressure":1022.49,"humidity":83,"temp_min":275.178,"temp_max":275.178,"sea_level":1043.42,"grnd_level":1022.49},"wind":{"speed":1.07,"deg":356.501},"clouds":{"all":12},"dt":1454738179,"sys":{"message":0.0112,"country":"US","sunrise":1454771247,"sunset":1454809011},"id":5342970,"name":"Diablo","cod":200}"

Why are they different?

A: I don't see the problem. It returns the exact same values for longitude (-121.96), latitude (37.83), city ID (5342970) and city name (Diablo), which clearly indicates that both results represent results from the same location.
The minor differences between both results are probably caused by minor changes in the weather or results being taken from a different server or weather station (which the different values of the base property seem to suggest).
I wouldn't bother about these minor differences. However, I do have another concern (see my note below).

Note :
The behavior of the zip parameter is unreliable. When I open your URL in my browser from my location (in Belgium), I sometimes get the expected results and sometimes get this error :
{"cod":"404","message":"Error: Not found city"}

To avoid this problem, it's better to use one of the following options :

*

*q parameter, with city name and country as values :
http://api.openweathermap.org/data/2.5/weather?appid=35d3153a253e2536f49f02fd8080dfc2&q=Diablo,US

*id parameter, with your city ID as a value :
http://api.openweathermap.org/data/2.5/weather?appid=35d3153a253e2536f49f02fd8080dfc2&id=5342970
(You can download a list of all supported city IDs here)

*lat & lon parameters, with your latitude and longitude as values :
http://api.openweathermap.org/data/2.5/weather?appid=35d3153a253e2536f49f02fd8080dfc2&lat=37.83&lon=-121.96
(You can also find the latitude and longitude of your city in this list of supported cities)
See the API docs for more details.


text:
Q: Char pointer results in bad output i have a problem regarding the output of char ptr. following is the sample code which i am trying to execute..
struct DeviceInfo{

char * name;
int id;

};
void testFunc(DeviceInfo *info){

    char temp[50] = "test input";
    info->name = temp;

}
void main(){

    DeviceInfo deviceInfo;
    testFunc(&deviceInfo);
    std::cout<<"Output is "<<deviceInfo.name;

}

Output i get in the main is some kind of weird one ....
while debugging i find out that when "test.name" is passed on to output stream it not only
gives garbage output but it also changes the "name" value for "deviceInfo" object to that garbage value...
this is kind of test scenario but in actual application this testFunc has to be executed in the same way i.e. constant char string should be assigned name to char ptr.
i tried puting '\0' at the end of char temp like this temp[strlen(temp)] = '\0';
but it still dont work
Any help is appreciated...
Raza

A: This is failing because you are assigning a pointer to an automatic variable to a member of a structure with a different scope (and therefore a different lifetime).  temp is going to get destroyed at the end of testFunc, and further access to it is illegal.

A: temp is a stack-allocated variable, it will get destroyed after testFunc() returns.
So your char* will point to destroyed memory.
This causes undefined behavior.

A: This is why we have a string class.
struct DeviceInfo{
    std::string name;
    int id;
};

void testFunc(DeviceInfo *info){
    info->name = "test_input";
}

int main(){
    DeviceInfo deviceInfo;
    testFunc(&deviceInfo);
    std::cout<<"Output is "<<deviceInfo.name;
}

A: You are storing a pointer to local storage, that disappears when testFunc() goes out of scope.
The proper way for a constant string is:
info->name = "test input";

or for something more dynamic:
info->name = strdup("test input");

You can also opt to not make name into pointer, but instead have char name[50]; in the structure, and then just do:
strcpy(info->name, "test input");

It would also be advisable to use a size-aware version, if you have it:
snprintf(info->name, sizeof info->name, "%s", "test input");

Note that this assumes the array solution, sizeof info->name will not make sense if name is still a pointer.

A: You are assigning a pointer to a temporary array. Once testFunc() returns, your temp array will be destroyed and your info->name pointer will be pointing to random memory.

A: char *temp = "test input";
info->name = (char*)malloc(sizeof(char) * strlen(temp) + 1); // Include room for \0
strcpy(info->name, temp);

instead of:
char temp[50] = "test input";
info->name = temp;

Your char temp[50] is no longer valid after the function returns.


text:
Q: Confusion with scanf() or if() I am not so familiar with C. Therefore, maybe someone will easily find a solution, I will not mind if you share it.
After entering the data in the first scanf() always gives the option else(): "Error".
I was looking for possible options for the problem. I found a lot of things like that,  but nothing that to help me specifically. I think the mistake is in the strcmp(). But I can not say for sure. Will you help?
#include <stdio.h>
#include <string.h>

int main()
{
        float celsius, fahrenheit;
        char tempConvering[10];

        printf("Enter what to convert to what (F to C; C to F): ");
        scanf(" %s", &tempConvering[10]);

        if(strcmp(tempConvering, "F to C") == 0)
        {
            printf("\nEnter temperature in Fahrenheit: ");
            scanf(" %f", &fahrenheit);
            celsius = fahrenheit * 1.8 + 32;
            printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
        }
        else if(strcmp(tempConvering, "C to F") == 0)
        {
            printf("\nEnter temperature in Celsius: ");
            scanf(" %f", &celsius);
            celsius = (fahrenheit - 32) / 1.8;
            printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
        }
        else
        {
            puts("\nError!");
        }
}

A: I believe there's an error with how you're using scanf, specifically, at this point:
scanf(" %s", &tempConvering[10]);
                  ^
                  |
                  +---- here

The second argument to scanf should be the address of the place to store the result. Here, you're saying "place the string that's read in in the memory just after the buffer that I've set up," which isn't probably want you wanted to do. Instead, write this:
scanf(" %s", tempConvering);

This says "place the string inside the buffer named tempConverting." If you're just getting started with C and haven't learned much about pointers and arrays, a good rule of thumb is that if you're reading a string with `scanf, you should just give the name of the array variable where you want to store the string rather than using an ampersand.
Hope this helps!

A: #include <stdio.h>
#include <string.h>

int main()
{
        float celsius, fahrenheit;
        char tempConvering[20];

        printf("what do you want to convert? ");
        scanf("%s", tempConvering);

        if(strcmp(tempConvering, "Fahrenheits") == 0)
        {
            printf("Enter temperature in Fahrenheit: ");
            scanf("%f", &fahrenheit);
            celsius = (fahrenheit - 32) / 1.8;
            printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
        }
        else if(strcmp(tempConvering, "Celsius") == 0)
        {
            printf("Enter temperature in Celsius: ");
            scanf("%f", &celsius);
            fahrenheit = celsius * 9 / 5 + 32;
            printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
        }
        else
        {
            puts("\nError!");
        }
}

This was the answer. I have to thank you for the tips, I will try to remember all the details about the scanf(). However, the problem disappeared only when I changed the desired answer not to "F to C" but to "Fahrenheits". Well, respectively, I changed the question. The program instantly earned. Nevertheless, attempts to do something with the scanf() are unsuccessful, to the extent that the same thing happens with the fgets().
In any case, somehow the problem is solved, thank you all!

A: Don't put extra space while you execute the scanf() function.
This might be an issue sometimes!
This should work fine:
scanf("%s", tempConvering);

By the way, while you take a string as an input, there is no need to use & before the string name.
Someone has already described the details above.


text:
Q: MySQL PHP: When I automatically add users, how to encrypt their passwords Preface: Making a simple ecommerce website. Users are automatically added, when they register, via registration page. I want to automatically encrypt their passwords.
Problem: The MySQL website shows how to use AES_ECRYPT, but it seems like it's for Terminal-type settings where the Admin would manually do this.
I want to add some code to register.php to make it automatically encrypted.
Thanks!

A: As the other answers have stated, you should not encrypt your passwords. They should be hashed.
They should NOT use MD5 or SHA
You SHOULD use bcrypt
Encryption should not be used because you never want to be able to decrypt the values and see the passwords, because hackers could also do the same.
Hashes are like one way encryption, you create a hash, and when logging in, you hash the password they entered on login and compare it against the stored hash.
MD5 and SHA are not suitable for this anymore as computers are faster and faster they can hash dictionary words and common passwords at a rate of 60+ billion per second to try to get your passwords.
This topic has been covered to death on StackOverflow.
See this for how to use bcrypt How do you use bcrypt for hashing passwords in PHP?
And this for an explanation as for why: Secure hash and salt for PHP passwords

A: You are going to want to hash passwords and not encrypt them. An encryption can be undone with the key. The password the user types in is called the plaintext password, the plaintext password should NEVER be written or stored anywhere.
When something is hashed, it is a one way translation, a hash cannot easily be translated back to its plaintext form, so when someone enters their password, you hash it and then compare it with the hashed password stored in the database.
A few hashing algorithms are MD5, SHA1, etc- in PHP, you can use the crypt function to hash a password. I should note that MD5 and SHA1 are not as secure anymore as they are very fast, which means that they can be brute forced fairly quickly (there are also databases where you can reverse engineer the hashes fairly quickly). You should use PHP's crypt function.
tl;dr - Hash passwords, don't encrypt them (for security, especially eCommerce).