text:
Q: How do i set and get the different states and inputs from a flatlist with multiple objects ok i got this flatlist contained within a flatlist, and the flatlist from inside, contains dropdowns, inputs, and buttons that i need to capture which data i'm getting from them, and of course save the new data based on what i selected, typed in or clicked, i'm not entirely sure how to do this, this is the code for flatlist
                <FlatList
              extraData = {this.state}
              data = {this.state.dataSource}
              renderItem = {({item, index}) => {
                return (
                  <View style={{marginTop: hp('2%')}}>
                    <TouchableOpacity style={{
                      alignSelf: 'center',
                      width: wp('95.7%'),
                      height: hp('10%'),
                      backgroundColor: "#ffffff",
                    }} onPress={() => this.toggleExpanded()}>
                      <View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-between'}}>
                        <View style={{flexDirection: 'column', justifyContent: 'center'}}>
                          <Text numberOfLines={2} ellipsizeMode="tail" style={{
                            marginLeft: wp('5%'),
                            width: wp('55%'),//wp('38.2%'), //151
                            //height: hp('2%'), //19
                            fontSize: rfv(16),
                            fontWeight: "500",
                            fontStyle: "normal",
                            textAlign: "left",
                            color: "#707070"
                          }}>{item.Title}</Text>
                          <Text style={{
                            marginLeft: wp('5%'),
                            fontSize: rfv(14),
                            fontWeight: "normal",
                            fontStyle: "normal",
                            textAlign: "left",
                            color: "#c4c4c4"
                          }}>{`ID ${item.Id} - ${item.Cliente}`}</Text>
                        {
                          !item.IsFavorite ?
                          <Text style={{
                            marginLeft: wp('5%'),
                            fontSize: rfv(14),
                            fontWeight: "normal",
                            fontStyle: "italic",
                            textAlign: "left",
                            color: "#c4c4c4"
                          }}>No favorito</Text>
                          : null
                        }
                        </View>
                        <View style={{flexDirection: 'column', justifyContent: 'center'}}>
                          <View style={{flexDirection: 'row', marginRight: wp('3.4%')}}>
                            <Text style={{
                              fontSize: rfv(18),
                              fontWeight: "300",
                              fontStyle: "normal",
                              textAlign: "right",
                              color: "#707070"}}>{`${0}h`}</Text>
                            <Image style={{marginTop: hp('1%'), marginLeft: wp('3.7%')}} source={this.state.isCollapsed ? Images.expandible : Images.collapsible}/>
                          </View>
                        </View>
                      </View>
                    </TouchableOpacity>
                    <Collapsible style={{
                      alignSelf: 'center',
                      width: wp('95.7%'),
                      backgroundColor: "#ffffff",}} collapsed={this.state.isCollapsed}>

                    <FlatList
                      //extraData = {this.state}
                      data = {item.ListReportHistoryResponse}//{DataManager.FavoriteList[moment(this.state.selectedDate).format('YYYY-MM-DD')]}
                      renderItem = {({ item, index }) => {
                        return (
                          <View>
                          <View style={{flexDirection: 'row'}}>
                            <Text style={{
                              marginLeft: wp('5%'),
                              fontSize: rfv(14),
                              fontWeight: "normal",
                              fontStyle: "normal",
                              textAlign: "left",
                              color: "#717171"
                            }}>Etapa</Text>
                            <Text style={{
                              marginLeft: wp('42.5%'),
                              fontSize: rfv(14),
                              fontWeight: "normal",
                              fontStyle: "normal",
                              textAlign: "left",
                              color: "#717171"
                            }}>Horas</Text>
                          </View>
                          <View style={{flexDirection: 'row'}}>
                            <ModalDropdown
                              adjustFrame={style => {
                                style.top =(Platform.OS === 'ios' ? style.top : style.top - StatusBar.currentHeight);
                                return style;
                              }}
                              dropdownTextStyle={styles.dropdownTextStyle}
                              dropdownTextHighlightStyle={styles.dropdownTextHighlightStyle}
                              dropdownStyle={styles.dropdownStageStyle}
                              defaultValue={item.Etapa}
                              style={styles.dropStageStyle}
                              textStyle={{
                                padding: 0,
                                margin: 0,
                                fontSize: rfv(16),
                                paddingVertical: hp('1.2%'),
                                fontWeight: 'normal',
                                fontStyle: 'normal',
                                textAlign: 'left',
                                color: item.Etapa /*item.ListReportHistoryResponse[index2].Etapa*/ != 'Selecciona una etapa' ? '#1a1a1a' : '#c4c4c4',
                              }}
                              //onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                              //options={Object.keys(this.state.items)}
                              onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                              options={DataManager.ListEtapa}
                            />
                            <View style={styles.InputContainerHours}>
                              <Text style={styles.InputTextHours}>{item.HorasTrabajadas}</Text>
                            </View>
                            <TouchableOpacity style={{marginTop: hp('0.5%'), marginLeft: wp('5.5%')}} onPress={() => this.props.onSubstract}>
                              <Image source={Images.menos_hora}/>
                            </TouchableOpacity>
                            <TouchableOpacity style={{marginTop: hp('0.5%'), marginLeft: wp('2%')}} onPress={() => this.props.onAdd}>
                              <Image source={Images.mas_hora}/>
                            </TouchableOpacity>
                          </View>
                          <Text style={{
                            fontSize: rfv(14),
                            marginLeft: wp('5%'),
                            fontWeight: "normal",
                            fontStyle: "normal",
                            textAlign: "left",
                            color: "#717171"
                          }}>Observaciones</Text>
                          <Input
                            autoCapitalize="none"
                            maxLength={100}
                            inputContainerStyle={styles.InputContainerComentarioOnBlur}
                            containerStyle={styles.InputComentario}
                            inputStyle={styles.InputTextHoursRInput}
                            placeholderTextColor={'#c4c4c4'}
                            placeholder="(Opcional)"
                            onChangeText={value => this.setState({})}
                          />
                          <TouchableOpacity style={{alignItems: 'flex-end', alignSelf: 'flex-end'}}>
                            <Text style={{
                              marginRight: wp('3.4%'),
                              marginBottom: hp('3%'),
                              fontSize: rfv(14),
                              fontWeight: "normal",
                              fontStyle: "normal",
                              textAlign: "left",
                              color: "#1062cc"
                            }}>Agregar etapa</Text>
                          </TouchableOpacity>
                        </View>
                        )}}/>
                        </Collapsible>
                        </View>
                )
              }}
            />

EDIT: updated with screenshot of the object displayed in flatlist, i still need help getting this to work
<View style={styles.InputContainerHours}>
<Text style={styles.InputTextHours}>{item.HorasTrabajadas}</Text>
</View>
<TouchableOpacity style={{marginTop: hp('0.5%'), marginLeft: wp('5.5%')}} onPress={() => this.props.onSubstract}>
<Image source={Images.menos_hora}/>
</TouchableOpacity>
<TouchableOpacity style={{marginTop: hp('0.5%'), marginLeft: wp('2%')}} onPress={() => this.props.onAdd}>
<Image source={Images.mas_hora}/>
</TouchableOpacity>

the onadd is supposed function that adds to item.HorasTrabajadas, 0.5 in addition to the current value, and the onsubstract is the same but substracts to the current value
and here is the object

edit 2: what if the api contains an object with data saved already, how do i edit that new data?

edit 3: i added a github project with the 3 most important parts of this project, https://github.com/Vasault/HourReg/tree/develop contains 3 files, the most important one HourRegistration.tsx
edit 4: unable to change data that already come from api

A: You can use the index of your array to identify the selected item, and when you have an index of every time you can update the item on every action according to your need.
Let suppose you have 10 items and on every item, you have to update the state you can get the item and index of that row and can update the state easily.
Here is a simple example that can clear your confusion.
 And here is a snack with a working example
https://snack.expo.io/@waheed25/radarada
import React from 'react';
import { SafeAreaView, View, TextInput, FlatList, StyleSheet, Text } from 'react-native';
import Constants from 'expo-constants';

const DATA = [
  {
    id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
    title: 'First Item',
  },
  {
    id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
    title: 'Second Item',
  },
  {
    id: '58694a0f-3da1-471f-bd96-145571e29d72',
    title: 'Third Item',
  },
];

export default class  App extends React.Component {

  state={
    observacionesInput: []
  }
   onTextObservacionesChange = (text, index) => {
    var { observacionesInput } = this.state
    let myArray = observacionesInput
        myArray[index] = text
    this.setState({observacionesInput: myArray });
  }
  toggleExpanded = () => {
    this.setState({ isCollapsed: !this.state.isCollapsed });
  };
  render(){
    console.log('state', this.state)
  return (
    <SafeAreaView>
    <Text>Testing</Text>
      <FlatList
        data={DATA}
        renderItem={({ item, index }) => {
          return(
            <View style={{  marginTop: 20}}>
              <TextInput
               style={{borderColor: 'gray', borderWidth: 1, height: 50,}}
                autoCapitalize="none"
                maxLength={100}
                placeholderTextColor={'#c4c4c4'}
                placeholder="(Opcional)"
                onChangeText={value => this.onTextObservacionesChange(value, index)}
              />
            </View>
          )
        }}
      />
    </SafeAreaView>
  );
  }
}

A: you can make dynamic state by append parentIndex and childIndex to state to uniquely identify of item of child flatlist
you can use onChangeValue for save data into newDataSave object and getDataFromNewSave for get data from newDataSave
Note: you all saving data is saving in newDataSave object. you can console to check it and save into database.
 onChangeValue = (key, value) => {
    this.setState((prevState) => {
      return {
        newDataSave: {
          ...prevState.newDataSave,
          [key]: value,
        },
      };
    });
  };

  getDataFromNewSave = (key) => {
    try {
      return this.state.newDataSave[key];
    } catch (error) {
      return "";
    }
  };

<Input
                            value={this.getDataFromNewSave(
                              `input${parentIndex}${childIndex}`
                            )}
                            autoCapitalize="none"
                            maxLength={100}
                            inputContainerStyle={
                              styles.InputContainerComentarioOnBlur
                            }
                            containerStyle={styles.InputComentario}
                            inputStyle={styles.InputTextHoursRInput}
                            placeholderTextColor={"#c4c4c4"}
                            placeholder="(Opcional)"
                            onChangeText={(value) => {
                              this.onChangeValue(
                                `input${parentIndex}${childIndex}`,
                                value
                              );
                            }}
                          />

Full Code:
import React, { Component } from "react";
import {
  Text,
  StyleSheet,
  View,
  FlatList,
  TouchableOpacity,
  Image,
  TextInput,
} from "react-native";
import {
  widthPercentageToDP as wp,
  heightPercentageToDP as hp,
} from "react-native-responsive-screen";
import Collapsible from "react-native-collapsible";
import ModalDropdown from "react-native-modal-dropdown";

const Input = TextInput;
const rfv = (value) => {
  return value;
};

const DataManager = {
  ListEtapa: ["a", "b", "c"],
};

const Images = {
  collapsed: require("./assets/icons/app-icon.png"),
  expandible: require("./assets/icons/app-icon.png"),
};

export default class App extends Component {
  state = {
    isCollapsed: false,
    dataSource: [
      {
        Id: "1",
        Title: "abc1",
        Cliente: "abc1",
        IsFavorite: false,
        ListReportHistoryResponse: [
          { Etapa: "abc1", HorasTrabajadas: "abcabc1" },
          { Etapa: "cde1", HorasTrabajadas: "cdecde1" },
        ],
      },
      {
        Id: "2",
        Title: "abc2",
        Cliente: "abc2",
        IsFavorite: false,
        ListReportHistoryResponse: [
          { Etapa: "abc2", HorasTrabajadas: "abcabc2" },
          { Etapa: "cde2", HorasTrabajadas: "cdecde2" },
        ],
      },
    ],
    newDataSave: {},
  };

  onChangeValue = (key, value) => {
    this.setState((prevState) => {
      return {
        newDataSave: {
          ...prevState.newDataSave,
          [key]: value,
        },
      };
    });
  };

  getDataFromNewSave = (key) => {
    try {
      return this.state.newDataSave[key];
    } catch (error) {
      return "";
    }
  };

  render() {
    return (
      <View>
        <FlatList
          extraData={this.state}
          data={this.state.dataSource}
          renderItem={({ item, index: parentIndex }) => {
            return (
              <View style={{ marginTop: hp("2%") }}>
                <TouchableOpacity
                  style={{
                    alignSelf: "center",
                    width: wp("95.7%"),
                    height: hp("10%"),
                    backgroundColor: "#ffffff",
                  }}
                  onPress={() => this.toggleExpanded()}
                >
                  <View
                    style={{
                      flex: 1,
                      flexDirection: "row",
                      justifyContent: "space-between",
                    }}
                  >
                    <View
                      style={{
                        flexDirection: "column",
                        justifyContent: "center",
                      }}
                    >
                      <Text
                        numberOfLines={2}
                        ellipsizeMode="tail"
                        style={{
                          marginLeft: wp("5%"),
                          width: wp("55%"), //wp('38.2%'), //151
                          //height: hp('2%'), //19
                          fontSize: rfv(16),
                          fontWeight: "500",
                          fontStyle: "normal",
                          textAlign: "left",
                          color: "#707070",
                        }}
                      >
                        {item.Title}
                      </Text>
                      <Text
                        style={{
                          marginLeft: wp("5%"),
                          fontSize: rfv(14),
                          fontWeight: "normal",
                          fontStyle: "normal",
                          textAlign: "left",
                          color: "#c4c4c4",
                        }}
                      >{`ID ${item.Id} - ${item.Cliente}`}</Text>
                      {!item.IsFavorite ? (
                        <Text
                          style={{
                            marginLeft: wp("5%"),
                            fontSize: rfv(14),
                            fontWeight: "normal",
                            fontStyle: "italic",
                            textAlign: "left",
                            color: "#c4c4c4",
                          }}
                        >
                          No favorito
                        </Text>
                      ) : null}
                    </View>
                    <View
                      style={{
                        flexDirection: "column",
                        justifyContent: "center",
                      }}
                    >
                      <View
                        style={{
                          flexDirection: "row",
                          marginRight: wp("3.4%"),
                        }}
                      >
                        <Text
                          style={{
                            fontSize: rfv(18),
                            fontWeight: "300",
                            fontStyle: "normal",
                            textAlign: "right",
                            color: "#707070",
                          }}
                        >{`${0}h`}</Text>
                        <Image
                          style={{
                            marginTop: hp("1%"),
                            marginLeft: wp("3.7%"),
                          }}
                          source={
                            this.state.isCollapsed
                              ? Images.expandible
                              : Images.collapsible
                          }
                        />
                      </View>
                    </View>
                  </View>
                </TouchableOpacity>
                <Collapsible
                  style={{
                    alignSelf: "center",
                    width: wp("95.7%"),
                    backgroundColor: "#ffffff",
                  }}
                  collapsed={this.state.isCollapsed}
                >
                  <FlatList
                    //extraData = {this.state}
                    data={item.ListReportHistoryResponse} //{DataManager.FavoriteList[moment(this.state.selectedDate).format('YYYY-MM-DD')]}
                    renderItem={({ item, index: childIndex }) => {
                      return (
                        <View>
                          <View style={{ flexDirection: "row" }}>
                            <Text
                              style={{
                                marginLeft: wp("5%"),
                                fontSize: rfv(14),
                                fontWeight: "normal",
                                fontStyle: "normal",
                                textAlign: "left",
                                color: "#717171",
                              }}
                            >
                              Etapa
                            </Text>
                            <Text
                              style={{
                                marginLeft: wp("42.5%"),
                                fontSize: rfv(14),
                                fontWeight: "normal",
                                fontStyle: "normal",
                                textAlign: "left",
                                color: "#717171",
                              }}
                            >
                              Horas
                            </Text>
                          </View>
                          <View style={{ flexDirection: "row" }}>
                            <ModalDropdown
                              adjustFrame={(style) => {
                                style.top =
                                  Platform.OS === "ios"
                                    ? style.top
                                    : style.top - StatusBar.currentHeight;
                                return style;
                              }}
                              dropdownTextStyle={styles.dropdownTextStyle}
                              dropdownTextHighlightStyle={
                                styles.dropdownTextHighlightStyle
                              }
                              dropdownStyle={styles.dropdownStageStyle}
                              defaultValue={this.getDataFromNewSave(
                                `SeleccionClientes${parentIndex}${childIndex}`
                              )}
                              style={styles.dropStageStyle}
                              textStyle={{
                                padding: 0,
                                margin: 0,
                                fontSize: rfv(16),
                                paddingVertical: hp("1.2%"),
                                fontWeight: "normal",
                                fontStyle: "normal",
                                textAlign: "left",
                                color:
                                  item.Etapa /*item.ListReportHistoryResponse[index2].Etapa*/ !=
                                  "Selecciona una etapa"
                                    ? "#1a1a1a"
                                    : "#c4c4c4",
                              }}
                              //onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                              //options={Object.keys(this.state.items)}
                              onSelect={(i, value) =>
                                // this.setState({ SeleccionClientes: value })
                                this.onChangeValue(
                                  `SeleccionClientes${parentIndex}${childIndex}`,
                                  value
                                )
                              }
                              options={DataManager.ListEtapa}
                            />
                            <View style={styles.InputContainerHours}>
                              <Text style={styles.InputTextHours}>
                                {item.HorasTrabajadas}
                              </Text>
                            </View>
                            <TouchableOpacity
                              style={{
                                marginTop: hp("0.5%"),
                                marginLeft: wp("5.5%"),
                              }}
                              onPress={() => this.props.onSubstract}
                            >
                              <Image source={Images.menos_hora} />
                            </TouchableOpacity>
                            <TouchableOpacity
                              style={{
                                marginTop: hp("0.5%"),
                                marginLeft: wp("2%"),
                              }}
                              onPress={() => this.props.onAdd}
                            >
                              <Image source={Images.mas_hora} />
                            </TouchableOpacity>
                          </View>
                          <Text
                            style={{
                              fontSize: rfv(14),
                              marginLeft: wp("5%"),
                              fontWeight: "normal",
                              fontStyle: "normal",
                              textAlign: "left",
                              color: "#717171",
                            }}
                          >
                            Observaciones
                          </Text>
                          <Input
                            value={this.getDataFromNewSave(
                              `input${parentIndex}${childIndex}`
                            )}
                            autoCapitalize="none"
                            maxLength={100}
                            inputContainerStyle={
                              styles.InputContainerComentarioOnBlur
                            }
                            containerStyle={styles.InputComentario}
                            inputStyle={styles.InputTextHoursRInput}
                            placeholderTextColor={"#c4c4c4"}
                            placeholder="(Opcional)"
                            onChangeText={(value) => {
                              this.onChangeValue(
                                `input${parentIndex}${childIndex}`,
                                value
                              );
                            }}
                          />
                          <TouchableOpacity
                            style={{
                              alignItems: "flex-end",
                              alignSelf: "flex-end",
                            }}
                          >
                            <Text
                              style={{
                                marginRight: wp("3.4%"),
                                marginBottom: hp("3%"),
                                fontSize: rfv(14),
                                fontWeight: "normal",
                                fontStyle: "normal",
                                textAlign: "left",
                                color: "#1062cc",
                              }}
                            >
                              Agregar etapa
                            </Text>
                          </TouchableOpacity>
                        </View>
                      );
                    }}
                  />
                </Collapsible>
              </View>
            );
          }}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({});

A: SOLVED, in a much better and easier way
on every input, dropdown, etc. set a function and pass 3 parameters
onChangeText={value => this.onChangeTextObservaciones(parentIndex, childIndex, value)
parentIndex (the one from outside flatlist), childIndex (the one from inside), and the value you're editing (blank or not)
const onChangeTextObservaciones = (indexOutside, indexInside, value) => {
    this.dataList[indexOutside].ListReportHistoryResponse[indexInside].Title = value;
    this.setState({displayDay: this.dataList});
}

change the specific value from the specific element from that object, and change it with the new value, and lastly change the whole new object with the new value.
a friend of mine realize this


text:
Q: Is it possible to intercept calls from one controller to another one in Nestjs? and I'm working in a backend application and I want to reuse some api writed before in other controller but its necesary that when I call a method for example from controller A to Controller B it must be intecepted by a Guard, middleware, etc. I'm using a global guard, that intercept any request call. And I  tried something like the example below but just intercept the first call triggered on controller A but when call to controller B it dosent trigger
@Controller('controller-a')
export class ControllerA {
  @Get()
  methodA(){
    const respFromB = await ControllerB.prototype.methodB({ ..some data.. });
    enter code here
    return '...'
  }
}

@Controller('controller-b')
export class ControllerB {
  @Post()
  methodB(
   @Body() data: any
  ) {
    ... some other code...
    return 'books';
  }
}

// main.ts
const reflector = app.get(Reflector);
const authService = app.get(AuthService);
const prismaClient = app.get(PrismaClient);
app.useGlobalGuards(new MyGlobalGuard(reflector, authService, prismaClient));

// MyGlobalGuard.ts
@Injectable()
export class MyGlobalGuard implements CanActivate {
  public constructor(
    private readonly reflector: Reflector,
    private readonly authService: AuthService,
    private readonly prisma: PrismaClient,
  ) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    ....
    return true;
  }
}

A: As you're the one calling from one controller to another, no it's not possible. You'd need to make an HTTP request from your server to your server to trigger the guards and interceptors again. It's Nest's internal route handler that's in charge of calling these enhancers, so you can't get to them from directly calling the class

redpajama_set_name: RedPajamaStackExchange


text:
Q: Image Library Software I have a need for an Image Library within my organization and I was wondering if anyone knows of any that they could recommend. It will need to be able to integrate with any number of our own solutions (meaning it will have a set of services or APIs that one can use for integration).
Also I would be great if it had: facial recognition, geo-tagging, indexing of colors, people, places, photo content, (meaning it can detect the primary colors used in the photo, read content from the photo, like OCR, tell where the focus of the photo is), search by any of these (i.e. color, geo position, etc).
Basically a cross between, iPhoto (with its facial recognition, geo-tagging, etc) and iStockPhoto (with its color, content, focus placement detection, etc) for an Organization.
As you can imagine I would prefer not to have to build this myself.
Cheers
Anthony

*

*Note: I am more after a commercial piece of software that is an Image Library and does the above,  that allows for integration

A: I have used both DotImage and LeadTools to work with images...  they are the top .NET Imaging libraries out there (that I know of) and provide rich imaging functionality to develop applications.

A: Are you talking about an image processing library or a program for storing images and with some extra features? In the first case, you might take a look at OpenCV.

A: Check similar questions

*

*Fast Cross-Platform C/C++ Image Processing Libraries

*Image processing libraries


text:
Q: Proper way of writing PHP from PHP I am writing an install script where a user will input their database information via <form>.
I want to take those values and ultimately end up with a
<?php
define("WEBSITE_TITLE", "");
define("DATABASE_HOST", "hostnameValue");
define("DATABASE_USER", "usernameValue");
define("DATABASE_PASS", "passwordValue");
define("DATABASE_NAME", "dbNameValue");
?>

config.php already exists and right out of the box all it contains is:
<?php
define("WEBSITE_TITLE", "Data Share | File Manager");

I have it working right now, but it sort of feels like a hack
$file = '../config.php';

$current = file_get_contents($file);
$current .= "\ndefine(\"DATABASE_HOST\", \"" . $request->hostname . "\");\n";
$current .= "define(\"DATABASE_USER\", \"" . $request->username . "\");\n";
$current .= "define(\"DATABASE_PASS\", \"" . $request->password . "\");\n";
$current .= "define(\"DATABASE_NAME\", \"" . $request->dbname . "\");\n";
$current .= "?>";

$save = file_put_contents($file, $current);

The above IS working, but I want to know if their is a better or more proper way of doing this.

A: Here is an adapted version of a function that I had written for handling a similar task.
The key difference to your solution is that this makes use of file locking to prevent data corruption or inconsistencies that may possibly arise with concurrent hits to the config file. This solution is also flexible enough to be applied to different config file types/formats, is robust enough to scale to handling (almost) any number of config options and also handles pre-existing config options in the file.
That said, I do not think this offers any real benefit over your solution for your limited use case though.
<?php
function writeConfig($filePath, array $configs, $clear=false)
{
    // scanf/sprintf format string to parse/print configs
    $configParseFormat = "define('%[^']s', '%[^']s');";
    $configWriteFormat = "define('%s', '%s');\n";

    // Open file for reading/writing
    if ($fp = fopen($filePath, 'c+')) {
        // Get file lock
        if (flock($fp, LOCK_EX)) {

            // Check if current configs should be kept
            if (!$clear) {
                // Read in configs from file and add to new configs array
                while (list($key, $value) = fscanf($fp, $configParseFormat)) {
                    if (!empty(trim($key)) && !array_key_exists($key, $configs)) {
                        $configs[ $key ] = $value;
                    }
                }
            }

            // Clear out file contents
            ftruncate($fp, 0);
            rewind($fp);

            // Start php file
            fwrite($fp, "<?php\n");

            // Loop through all config values
            foreach ($configs as $key => $value) {
                // Write the config line
                fprintf($fp, $configWriteFormat, $key, $value);
            }

            // Flush output and release lock
            fflush($fp);
            flock($fp, LOCK_UN);

            return fclose($fp);
        }

        // Close file
        fclose($fp);
    }

    return false;
}

// E.g use:
writeConfig('config.php', array(
    'DATABASE_HOST' => $request->hostname,
    'DATABASE_PASS' => $request->password,
    'DATABASE_USER' => $request->username,
    'DATABASE_NAME' => $request->dbname
    // WEBSITE_TITLE and any configs already in file will be retained
));

A: There really aren't too many other ways (other than using an array) that might be any better. Using an array might be less "hacky", but better is really interpreted as far as this goes.
$file = '../config.php';
$current = file_get_contents($file);

$define = array("DATABASE_HOST" => "\$request->hostname",
                "DATABASE_USER" => "\$request->username",
                "DATABASE_PASS" => "\$request->password",
                "DATABASE_NAME" => "\$request->dbname");

foreach($define as $key => $value) {
    $current .= "\ndefine(\"".$key."\", \"".$value."\");";
}
$current .= "\n?>";

$save = file_put_contents($file, $current);

A: You can store the configuration in JSON format using json_encode() and
file_put_contents():
$config = array('database' => array('host' => 'example'));
file_put_contents('config.json', json_encode($config));

And then you can create a Config class which loads this file:
class Config
{
    private $config;

    private function load() {
        $string = file_get_contents('config.json');
        $this->config = json_decode($string);
    }

    public function __get($name) {
        // Lazy load configuration file
        if(!isset($this->config)) {
            $this->load();
        }

        return $this->config->$name;
    }
}

Usage is simple, just create an instance of the class and access the object variables:
$config = new Config();
echo $config->database->host; // Outputs 'example'

Later you can make the Config class a singleton to be more performant, add error handling if file can't be loaded, etc.


text:
Q: How to increase the resolution of ggplots in Rmarkdown html files I am trying to knit an Rmarkdown document which contains a rather large ggplot, that I have created using cowplot
This is how one might create such a plot:
library(DOSE)
library(cowplot)
library(enrichplot)
data(geneList)
de <- names(geneList)[abs(geneList) > 2]
edo <- enrichDGN(de)
p1 <- dotplot(edo, showCategory=30) + ggtitle("dotplot for ORA")
p2 <- dotplot(edo, showCategory=30) + ggtitle("dotplot for ORA")
p3 <- dotplot(edo, showCategory=30) + ggtitle("dotplot for ORA")

plot_grid(p1,p2,p3, ncol=3)

I have added the following parameters in the header of the code chunk of my markdown document:
{test echo=F, fig.height=8, fig.width=20, fig.show="hold", fig.align="center"}

When I run the code chunk in Rstudio, the resulting image is clear and perfectly readable.
However, when I try to knit it to an html file, it comes out very blurred and barely readable..
Are there any parameters that I should use that I am missing? Increasing dpi did not help.
It would also be fine, if the image is wider than the text of the markdown document if that increases quality.
Any help is much appreciated!
Cheers!

A: if you know you want to knit to html, then you should be using out.width and out.height using pixels or percentages to specify dimensions. The fig.width and fig.height are used more so for R-generated images. The out.width and out.height can be for both R-generated and HTML. Nice explanation here: https://www.zevross.com/blog/2017/06/19/tips-and-tricks-for-working-with-images-and-figures-in-r-markdown-documents/


text:
Q: Glassfish JavaEE MySQL transaction locked and block all I have trouble with my application developped in JAVA EE 8 and Glassifish... Since a couple of week, Glassfish send transaction to MySQL and sometimes (impossible to reproduce manually or to understand the log to know what's the problem) a transaction stay running and block the full application.
After I have this error :
[2020-11-17T14:55:45.388+0100] [Payara 4.1] [INFO] []
[org.hibernate.event.internal.DefaultLoadEventListener] [tid: _ThreadID=177 _ThreadName=http-thread-pool::http-listener-2(11)] [timeMillis: 1605621345388] [levelValue: 800] [[
HHH000327: Error performing load command : org.hibernate.exception.GenericJDBCException: could not prepare statement]]

[2020-11-17T14:55:45.388+0100] [Payara 4.1] [INFO] [] [org.hibernate.event.internal.DefaultLoadEventListener] [tid: _ThreadID=177 _ThreadName=http-thread-pool::http-listener-2(11)] [timeMillis: 1605621345388] [levelValue: 800] [[
HHH000327: Error performing load command : org.hibernate.exception.GenericJDBCException: could not prepare statement]]

javax.ejb.TransactionRolledbackLocalException: Client's transaction aborted
at com.sun.ejb.containers.EJBContainerTransactionManager.useClientTx(EJBContainerTransactionManager.java:359)
at com.sun.ejb.containers.EJBContainerTransactionManager.preInvokeTx(EJBContainerTransactionManager.java:253)
at com.sun.ejb.containers.BaseContainer.preInvokeTx(BaseContainer.java:4494)
at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1936)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:210)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:90)
at com.sun.proxy.$Proxy404.ajout(Unknown Source)
at ch.BusinessService.TypeReservationPersonneManager.ajout(TypeReservationPersonneManager.java:63)
at sun.reflect.GeneratedMethodAccessor1470.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4756)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:836)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:64)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.GeneratedMethodAccessor63.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:895)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:835)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.GeneratedMethodAccessor65.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:895)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:835)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:374)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4728)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4716)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:90)
at com.sun.proxy.$Proxy275.ajout(Unknown Source)
at service.TypeReservationPersonneFacadeREST.ajoutAbo(TypeReservationPersonneFacadeREST.java:32)
at sun.reflect.GeneratedMethodAccessor1388.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4756)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:836)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:64)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.GeneratedMethodAccessor63.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:895)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:835)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.GeneratedMethodAccessor65.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:895)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:835)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:374)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4728)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4716)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:90)
at com.sun.proxy.$Proxy322.ajoutAbo(Unknown Source)
at service.__EJB31_Generated__TypeReservationPersonneFacadeREST__Intf____Bean__.ajoutAbo(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1388.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1606)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:654)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:593)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:480)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:180)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
at java.lang.Thread.run(Thread.java:748)
]]

[2020-11-17T14:55:45.389+0100] [Payara 4.1] [WARNING] [AS-EJB-00056] [javax.enterprise.ejb.container] [tid: _ThreadID=177 _ThreadName=http-thread-pool::http-listener-2(11)] [timeMillis: 1605621345389] [levelValue: 900] [[
  A system exception occurred during an invocation on EJB TypeReservationPersonneManager, method: public void ch.BusinessService.TypeReservationPersonneManager.ajout(int,int,int,int)]]

and when I do SHOW PROCESSLISTin MySQL, I see that all process are blocked because of the transaction and impossible to go further with the application.
**EDIT : **
I success to reproduce the trouble on the live server and I did SHOW ENGINE INNODB STATUSand this is the result
=====================================
2020-11-17 21:15:31 7f2d3b5e9700 INNODB MONITOR OUTPUT
=====================================
Per second averages calculated from the last 47 seconds
-----------------
BACKGROUND THREAD
-----------------
srv_master_thread loops: 4188 srv_active, 0 srv_shutdown, 3105 srv_idle
srv_master_thread log flush and writes: 7293
----------
SEMAPHORES
----------
OS WAIT ARRAY INFO: reservation count 21306
OS WAIT ARRAY INFO: signal count 121420
Mutex spin waits 531864, rounds 953991, OS waits 11585
RW-shared spins 233875, rounds 1314695, OS waits 6340
RW-excl spins 85836, rounds 717366, OS waits 3022
Spin rounds per wait: 1.79 mutex, 5.62 RW-shared, 8.36 RW-excl
------------
TRANSACTIONS
------------
Trx id counter 744371550
Purge done for trx's n:o < 744371544 undo n:o < 0 state: running but idle
History list length 0
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 744347278, not started
MySQL thread id 13657, OS thread handle 0x7f2d3b508700, query id 2192631 localhost 127.0.0.1 userres
---TRANSACTION 744370010, not started
MySQL thread id 13656, OS thread handle 0x7f2d4d7fe700, query id 2295945 localhost 127.0.0.1 userres
---TRANSACTION 744358938, not started
MySQL thread id 10249, OS thread handle 0x7f2d3b5e9700, query id 2306949 213.55.220.67 userres init
SHOW ENGINE INNODB STATUS
---TRANSACTION 744318375, not started
MySQL thread id 9232, OS thread handle 0x7f2d32959700, query id 2056900 localhost postfix_policyd
---TRANSACTION 744308703, not started
MySQL thread id 2114, OS thread handle 0x7f2d329a4700, query id 2029930 localhost postfix_policyd
---TRANSACTION 744271350, not started
MySQL thread id 1805, OS thread handle 0x7f2d3290e700, query id 1891670 localhost postfix_policyd
---TRANSACTION 744371401, not started
MySQL thread id 15, OS thread handle 0x7f2d53886700, query id 2306184 localhost 127.0.0.1 userres
---TRANSACTION 744297521, not started
MySQL thread id 352, OS thread handle 0x7f2d5391c700, query id 1984473 localhost postfix_policyd
---TRANSACTION 744371549, not started
MySQL thread id 13, OS thread handle 0x7f2d4d7b3700, query id 2306718 localhost 127.0.0.1 userres
---TRANSACTION 743779843, not started
MySQL thread id 1, OS thread handle 0x7f2d53967700, query id 0 Waiting for requests
---TRANSACTION 744370160, ACTIVE 20 sec starting index read
mysql tables in use 2, locked 2
LOCK WAIT 3 lock struct(s), heap size 1184, 2 row lock(s)
MySQL thread id 14084, OS thread handle 0x7f2d3b472700, query id 2296778 localhost MY_DB Sending data
DELETE FROM numeroreservation WHERE numero IN (SELECT numero FROM (SELECT numero FROM numeroreservation ORDER BY numero DESC LIMIT 5, 99999) as x)
Trx #rec lock waits 1 #table lock waits 0
Trx total rec lock wait time 0 SEC
Trx total table lock wait time 0 SEC
------- TRX HAS BEEN WAITING 20 SEC FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 83 page no 3 n bits 776 index `PRIMARY` of table `MY_DB`.`numeroreservation` trx table locks 1 total table locks 4  trx id 744370160 lock mode S locks rec but not gap waiting lock hold time 20 wait time before grant 0
------------------
---TRANSACTION 744369665, ACTIVE 24 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 2 lock struct(s), heap size 1184, 1 row lock(s)
MySQL thread id 14, OS thread handle 0x7f2d4e865700, query id 2294750 localhost 127.0.0.1 userres update
INSERT INTO numeroreservation (numero) VALUES(2410411)
Trx #rec lock waits 1 #table lock waits 0
Trx total rec lock wait time 0 SEC
Trx total table lock wait time 0 SEC
------- TRX HAS BEEN WAITING 24 SEC FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 83 page no 3 n bits 776 index `PRIMARY` of table `MY_DB`.`numeroreservation` trx table locks 1 total table locks 4  trx id 744369665 lock mode S locks rec but not gap waiting lock hold time 24 wait time before grant 0
------------------
---TRANSACTION 744367990, ACTIVE 44 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 2 lock struct(s), heap size 1184, 1 row lock(s)
MySQL thread id 12, OS thread handle 0x7f2d4e8b0700, query id 2280810 localhost 127.0.0.1 userres update
INSERT INTO numeroreservation (numero) VALUES(2410411)
Trx #rec lock waits 4 #table lock waits 0
Trx total rec lock wait time 1 SEC
Trx total table lock wait time 0 SEC
------- TRX HAS BEEN WAITING 44 SEC FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 83 page no 3 n bits 776 index `PRIMARY` of table `MY_DB`.`numeroreservation` trx table locks 1 total table locks 4  trx id 744367990 lock mode S locks rec but not gap waiting lock hold time 44 wait time before grant 0
------------------
---TRANSACTION 744367985, ACTIVE 45 sec
4 lock struct(s), heap size 1184, 1 row lock(s), undo log entries 149
MySQL thread id 11, OS thread handle 0x7f2d5383b700, query id 2306948 localhost 127.0.0.1 userres
Trx #rec lock waits 0 #table lock waits 0
Trx total rec lock wait time 0 SEC
Trx total table lock wait time 0 SEC
--------
FILE I/O
--------
I/O thread 0 state: waiting for completed aio requests (insert buffer thread)
I/O thread 1 state: waiting for completed aio requests (log thread)
I/O thread 2 state: waiting for completed aio requests (read thread)
I/O thread 3 state: waiting for completed aio requests (read thread)
I/O thread 4 state: waiting for completed aio requests (read thread)
I/O thread 5 state: waiting for completed aio requests (read thread)
I/O thread 6 state: waiting for completed aio requests (write thread)
I/O thread 7 state: waiting for completed aio requests (write thread)
I/O thread 8 state: waiting for completed aio requests (write thread)
I/O thread 9 state: waiting for completed aio requests (write thread)
Pending normal aio reads: 0 [0, 0, 0, 0] , aio writes: 0 [0, 0, 0, 0] ,
 ibuf aio reads: 0, log i/o's: 0, sync i/o's: 0
Pending flushes (fsync) log: 0; buffer pool: 0
3492514 OS file reads, 126847 OS file writes, 42386 OS fsyncs
506.41 reads/s, 16384 avg bytes/read, 21.91 writes/s, 8.60 fsyncs/s
-------------------------------------
INSERT BUFFER AND ADAPTIVE HASH INDEX
-------------------------------------
Ibuf: size 1, free list len 2996, seg size 2998, 2503 merges
merged operations:
 insert 5013, delete mark 7772, delete 1996
discarded operations:
 insert 0, delete mark 0, delete 0
32455.37 hash searches/s, 13179.55 non-hash searches/s
---
LOG
---
Log sequence number 88167956003
Log flushed up to   88167956003
Pages flushed up to 88167883665
Last checkpoint at  88167883665
Max checkpoint age    80826164
Checkpoint age target 78300347
Modified age          72338
Checkpoint age        72338
0 pending log writes, 0 pending chkp writes
28468 log i/o's done, 5.23 log i/o's/second
----------------------
BUFFER POOL AND MEMORY
----------------------
Total memory allocated 140574720; in additional pool allocated 0
Total memory allocated by read views 2112
Internal hash tables (constant factor + variable factor)
    Adaptive hash index 13473376    (2213368 + 11260008)
    Page hash           139112 (buffer pool 0 only)
    Dictionary cache    1485776     (554768 + 931008)
    File system         1577960     (812272 + 765688)
    Lock system         341208  (332872 + 8336)
    Recovery system     0   (0 + 0)
Dictionary memory allocated 931008
Buffer pool size        8191
Buffer pool size, bytes 134201344
Free buffers            1024
Database pages          6480
Old database pages      2372
Modified db pages       206
Percent of dirty pages(LRU & free pages): 2.745
Max dirty pages percent: 75.000
Pending reads 0
Pending writes: LRU 0, flush list 0, single page 0
Pages made young 805084, not young 461986343
108.36 youngs/s, 87546.33 non-youngs/s
Pages read 3492228, created 1081, written 92653
506.41 reads/s, 0.19 creates/s, 15.36 writes/s
Buffer pool hit rate 996 / 1000, young-making rate 0 / 1000 not 564 / 1000
Pages read ahead 232.34/s, evicted without access 0.00/s, Random read ahead 0.00/s
LRU len: 6480, unzip_LRU len: 0
I/O sum[13990]:cur[0], unzip sum[0]:cur[0]
--------------
ROW OPERATIONS
--------------
0 queries inside InnoDB, 0 queries in queue
0 read views open inside InnoDB
4 RW transactions active inside InnoDB
0 RO transactions active inside InnoDB
4 out of 1000 descriptors used
Main thread process no. 32076, id 139831933908736, state: sleeping
Number of rows inserted 2389, updated 170325, deleted 853, read 678563355
3.30 inserts/s, 9.64 updates/s, 0.00 deletes/s, 72578.35 reads/s
Number of system rows inserted 0, updated 0, deleted 0, read 0
0.00 inserts/s, 0.00 updates/s, 0.00 deletes/s, 0.00 reads/s
----------------------------
END OF INNODB MONITOR OUTPUT
============================

So this is happening when I add a lot of thing to do in the same place.. But it's never has trouble until a couple of days.. why now this is blocking it ?
My question is :

*

*Why I have it now when my application has 10 years without this problem

*how to solve it ? because this is in production and this is very a big problem yet


text:
Q: Error during WebSocket handshake with user endpoint once Django Channels app is deployed I'm trying to set up a websocket connection at the user level in my django app for receiving notifications. prod is https so need to use wss.
Here is the js:
$( document ).ready(function() {

socket = new WebSocket("wss://" + window.location.host + "/user_id/");
var $notifications = $('.notifications');
var $notificationList = $('.dropdown-menu.notification-list');

$notifications.click(function(){
    $(this).removeClass('newNotification')
});

socket.onmessage = function(e) {

// notification stuff

// Call onopen directly if socket is already open
if (socket.readyState == WebSocket.OPEN) socket.onopen();

}

I've implemented django-channels in settings.py like this:
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "asgi_redis.RedisChannelLayer",
        "CONFIG": {
            "hosts":[ENV_STR("REDIS_URL")]
        },
        "ROUTING": "project.routing.channel_routing",
     },
}

routing.py
from channels.routing import route
from community.consumers import ws_add, ws_disconnect

channel_routing = [
    route("websocket.connect", ws_add),
    route("websocket.disconnect", ws_disconnect),
]

locally, this handshakes just fine.
2017-04-16 16:37:04,108 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive
2017-04-16 16:37:04,109 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive
2017-04-16 16:37:04,109 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive
2017-04-16 16:37:04,110 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive
2017-04-16 16:37:04,111 - INFO - server - HTTP/2 support not enabled (install the http2 and tls Twisted extras)
2017-04-16 16:37:04,112 - INFO - server - Using busy-loop synchronous mode on channel layer
2017-04-16 16:37:04,112 - INFO - server - Listening on endpoint tcp:port=8000:interface=127.0.0.1
[2017/04/16 16:37:22] HTTP GET / 200 [0.55, 127.0.0.1:60129]
[2017/04/16 16:37:23] WebSocket HANDSHAKING /user_id/ [127.0.0.1:60136]
[2017/04/16 16:37:23] WebSocket CONNECT /user_id/ [127.0.0.1:60136]
[2017/04/16 16:37:25] HTTP GET /user/test10 200 [0.47, 127.0.0.1:60129]
[2017/04/16 16:37:25] WebSocket DISCONNECT /user_id/ [127.0.0.1:60136]
[2017/04/16 16:37:26] WebSocket HANDSHAKING /user_id/ [127.0.0.1:60153]
[2017/04/16 16:37:26] WebSocket CONNECT /user_id/ [127.0.0.1:60153]

However, now that the app has been deployed to Heroku, the /_user_id/ endpoint is returning 404, and I'm getting ERR_DISALLOWED_URL_SCHEME when it should be a valid endpoint:
WebSocket connection to 'wss://mydomain.com/user_id/' failed: Error during WebSocket handshake: Unexpected response code: 404.

As I'm continuing to research it seems like this server config can't actually support websockets in prod. Current Procfile:
web: gunicorn project.wsgi:application --log-file -
worker: python manage.py runworker -v2

I spent a few hrs looking at converting the app to asgi and using Daphne, although since the project is python 2.7 that's a difficult conversion (not to mention seems to require a different static file implementation)


text:
Q: Merge release branch to master while excluding CI entries I have a branch, say release-branch with:

*

*Some of the commits from master (since the branch was forked) already merged

*Lots of log spam in the form of maven-release-plugin updates due to Jenkins

I tried git pull --rebase -X theirs upstream release-branch (from a fresh local copy of upstream/master)
With this, a large amount of commits are the Maven release plugin working on POM versioning, which I don't need at all (the plugin has already updated POM files on master anyway).
How can I merge all the changes from branch into master, while excluding those from jenkins (I guess that means skipping all from a particular user or with specified name format)


text:
Q: Node.js MYSQL to run each Queries sequencially after previous one is done? I'm using Javascript MYSQL Library from Node.js and then i have multiple queries to run in loop. But when i run the loop, the loop always reach to end (done) suddenly while the Queries it started are still processing. So how do i keep the loop to wait each Query til done and then continue normally?
My code is:
function startHere() {
    console.log("-- START --");
    for (i=1; i < 6; i++) {
        dbInsert(i);
    }
    console.log("-- END --");
}
function dbInsert(id) {
    connection.query (
        'INSERT INTO table SET data=?',
        [id],
        function selectCb(err, results, fields) {
            if (err) {
                console.log(err.message);
            }
            if (results.length > 0) {
                console.log(id+" RECORDS ADDED!");
            }
        }
    );
}
startHere();

When i run it, it always returns like:
-- START --
-- END --
1 RECORDS ADDED!
2 RECORDS ADDED!
3 RECORDS ADDED!
4 RECORDS ADDED!
5 RECORDS ADDED!

It means, the loop doesn't wait the end of the queries it started.
How can i detect the end-point of the queries and make it work?

A: Your selectCb method is not being called synchronously, so your loop is effectively firing off each call and then returning.
You can either check the docs for a synchronous version of that connection.query method, or you will need to create a callback to print the end message after all your inserts have fired.

A: async should work for you
async.series([
    function(){ ... },
    function(){ ... }
]);

See https://github.com/caolan/async#series


text:
Q: Detect owl carousel drag direction I need your help. I need to detect owl carousel dragging direction.
function startCallback(event) {
    // if drag left do this
    $(".owl-item").css("transform", "rotate(-10deg)");
    //if drag left do this
    $(".owl-item").css("transform", "rotate(10deg)");
}

function endCallback(event) {

}

I need detect drag direction when it start.
Please help.
Thank you.


text:
Q: Proof of continuity of a vector function
Let $f: \mathbb{R}^m \rightarrow \mathbb{R}$. Show that $f(x) = x_i$ where $x_i$ is the $i^{nd}$ component of $x$ regarding the standard basis of $\mathbb{R}^m$ is continuous in 0.

The definition says :

Let $A \subset \mathbb{R}^m$, $f: A \rightarrow \mathbb{R}^p$ and $a \in A$. The function is continuous in a when for all $\epsilon \gt 0$, $\exists \delta \gt 0$ such that for all $x \in A$, $||x - a|| \le \delta$ and $|| f(x) - f(a) || \le \epsilon$.

I know $f(x) = (e_i|x)$.
By Cauchy-Schwarz inequality, we have : $|(e_i|x)| \le ||e_i||.||x||$
We have $||x - 0|| = ||x|| \le \delta$.
So $||f(x) - f(0)|| \le ||e_i||.||x|| - 0 = ||e_i||.||x||$
Now, for every $\epsilon \gt 0$ we can take $\delta = \frac{\epsilon}{||e_i||}$
So $||f(x) - f(0)|| \le ||e_i||.||x|| \le ||e_i||\delta = ||e_i||\frac{\epsilon}{||e_i||} = \epsilon$.
I wonder if it's correct ?


text:
Q: Unordered Linked List (C++) I'm trying to learn Linked List, but I encountered a problem.
below is the code for linkedlist.h file
#ifndef H_LinkedListType
#define H_LinkedListType

#include <iostream>
#include <cassert>

using namespace std;

//Definition of the node

template <class Type>
struct nodeType
{
    Type info;
    nodeType<Type> *link;
};

template <class Type>
class linkedListIterator
{
public:
   linkedListIterator();
     //Default constructor
     //Postcondition: current = nullptr;

   linkedListIterator(nodeType<Type> *ptr);
     //Constructor with a parameter.
     //Postcondition: current = ptr;

   Type operator*();
     //Function to overload the dereferencing operator *.
     //Postcondition: Returns the info contained in the node.

   linkedListIterator<Type> operator++();
     //Overload the pre-increment operator.
     //Postcondition: The iterator is advanced to the next
     //               node.

   bool operator==(const linkedListIterator<Type>& right) const;
     //Overload the equality operator.
     //Postcondition: Returns true if this iterator is equal to
     //               the iterator specified by right,
     //               otherwise it returns the value false.

   bool operator!=(const linkedListIterator<Type>& right) const;
     //Overload the not equal to operator.
     //Postcondition: Returns true if this iterator is not
     //               equal to the iterator specified by
     //               right; otherwise it returns the value
     //               false.

private:
   nodeType<Type> *current; //pointer to point to the current
                            //node in the linked list
};

template <class Type>
linkedListIterator<Type>::linkedListIterator()
{
    current = nullptr;
}

template <class Type>
linkedListIterator<Type>::
                  linkedListIterator(nodeType<Type> *ptr)
{
    current = ptr;
}

template <class Type>
Type linkedListIterator<Type>::operator*()
{
    return current->info;
}

template <class Type>
linkedListIterator<Type> linkedListIterator<Type>::
                                  operator++()
{
    current = current->link;

    return *this;
}

template <class Type>
bool linkedListIterator<Type>::operator==
               (const linkedListIterator<Type>& right) const
{
    return (current == right.current);
}

template <class Type>
bool linkedListIterator<Type>::operator!=
                 (const linkedListIterator<Type>& right) const
{    return (current != right.current);
}

//*****************  class linkedListType   ****************

template <class Type>
class linkedListType
{
public:
    const linkedListType<Type>& operator=
                         (const linkedListType<Type>&);
      //Overload the assignment operator.

    void initializeList();
      //Initialize the list to an empty state.
      //Postcondition: first = nullptr, last = nullptr,
      //               count = 0;

    bool isEmptyList() const;
      //Function to determine whether the list is empty.
      //Postcondition: Returns true if the list is empty,
      //               otherwise it returns false.

    void print() const;
      //Function to output the data contained in each node.
      //Postcondition: none

    int length() const;
      //Function to return the number of nodes in the list.
      //Postcondition: The value of count is returned.

    void destroyList();
      //Function to delete all the nodes from the list.
      //Postcondition: first = nullptr, last = nullptr,
      //               count = 0;

    Type front() const;
      //Function to return the first element of the list.
      //Precondition: The list must exist and must not be
      //              empty.
      //Postcondition: If the list is empty, the program
      //               terminates; otherwise, the first
      //               element of the list is returned.

    Type back() const;
      //Function to return the last element of the list.
      //Precondition: The list must exist and must not be
      //              empty.
      //Postcondition: If the list is empty, the program
      //               terminates; otherwise, the last
      //               element of the list is returned.

    virtual bool search(const Type& searchItem) const = 0;
      //Function to determine whether searchItem is in the list.
      //Postcondition: Returns true if searchItem is in the
      //               list, otherwise the value false is
      //               returned.

    virtual void insertFirst(const Type& newItem) = 0;
      //Function to insert newItem at the beginning of the list.
      //Postcondition: first points to the new list, newItem is
      //               inserted at the beginning of the list,
      //               last points to the last node in the list,
      //               and count is incremented by 1.

    virtual void insertLast(const Type& newItem) = 0;
      //Function to insert newItem at the end of the list.
      //Postcondition: first points to the new list, newItem
      //               is inserted at the end of the list,
      //               last points to the last node in the
      //               list, and count is incremented by 1.

    virtual void deleteNode(const Type& deleteItem) = 0;
      //Function to delete deleteItem from the list.
      //Postcondition: If found, the node containing
      //               deleteItem is deleted from the list.
      //               first points to the first node, last
      //               points to the last node of the updated
      //               list, and count is decremented by 1.

    linkedListIterator<Type> begin();
      //Function to return an iterator at the begining of
      //the linked list.
      //Postcondition: Returns an iterator such that current
      //               is set to first.

    linkedListIterator<Type> end();
      //Function to return an iterator one element past the
      //last element of the linked list.
      //Postcondition: Returns an iterator such that current
      //               is set to nullptr.

    linkedListType();
      //Default constructor
      //Initializes the list to an empty state.
      //Postcondition: first = nullptr, last = nullptr,
      //               count = 0;

    linkedListType(const linkedListType<Type>& otherList);
      //copy constructor

    ~linkedListType();
      //Destructor
      //Deletes all the nodes from the list.
      //Postcondition: The list object is destroyed.

protected:
    int count;   //variable to store the number of
                 //elements in the list
    nodeType<Type> *first; //pointer to the first node of the list
    nodeType<Type> *last;  //pointer to the last node of the list

private:
    void copyList(const linkedListType<Type>& otherList);
      //Function to make a copy of otherList.
      //Postcondition: A copy of otherList is created and
      //               assigned to this list.
};

template <class Type>
bool linkedListType<Type>::isEmptyList() const
{
    return (first == nullptr);
}

template <class Type>
linkedListType<Type>::linkedListType() //default constructor
{
    first = nullptr;
    last = nullptr;
    count = 0;
}

template <class Type>
void linkedListType<Type>::destroyList()
{
    nodeType<Type> *temp;   //pointer to deallocate the memory
                            //occupied by the node
    while (first != nullptr)   //while there are nodes in
    {                          //the list
        temp = first;        //set temp to the current node
        first = first->link; //advance first to the next node
        delete temp;   //deallocate the memory occupied by temp
    }
    last = nullptr; //initialize last to nullptr; first has
               //already been set to nullptr by the while loop
    count = 0;
}

template <class Type>
void linkedListType<Type>::initializeList()
{
    destroyList(); //if the list has any nodes, delete them
}

template <class Type>
void linkedListType<Type>::print() const
{
    nodeType<Type> *current; //pointer to traverse the list

    current = first;    //set current so that it points to
                        //the first node
    while (current != nullptr) //while more data to print
    {
        cout << current->info << " ";
        current = current->link;
    }
}//end print

template <class Type>
int linkedListType<Type>::length() const
{
    return count;
}  //end length

template <class Type>
Type linkedListType<Type>::front() const
{
    assert(first != nullptr);

    return first->info; //return the info of the first node
}//end front

template <class Type>
Type linkedListType<Type>::back() const
{
    assert(last != nullptr);

    return last->info; //return the info of the last node
}//end back

template <class Type>
linkedListIterator<Type> linkedListType<Type>::begin()
{
    linkedListIterator<Type> temp(first);

    return temp;
}

template <class Type>
linkedListIterator<Type> linkedListType<Type>::end()
{
    linkedListIterator<Type> temp(nullptr);

    return temp;
}

template <class Type>
void linkedListType<Type>::copyList
                   (const linkedListType<Type>& otherList)
{
    nodeType<Type> *newNode; //pointer to create a node
    nodeType<Type> *current; //pointer to traverse the list

    if (first != nullptr) //if the list is nonempty, make it empty
       destroyList();

    if (otherList.first == nullptr) //otherList is empty
    {
        first = nullptr;
        last = nullptr;
        count = 0;
    }
    else
    {
        current = otherList.first; //current points to the
                                   //list to be copied
        count = otherList.count;

            //copy the first node
        first = new nodeType<Type>;  //create the node

        first->info = current->info; //copy the info
        first->link = nullptr;        //set the link field of
                                   //the node to nullptr
        last = first;              //make last point to the
                                   //first node
        current = current->link;     //make current point to
                                     //the next node

           //copy the remaining list
        while (current != nullptr)
        {
            newNode = new nodeType<Type>;  //create a node
            newNode->info = current->info; //copy the info
            newNode->link = nullptr;       //set the link of
                                        //newNode to nullptr
            last->link = newNode;  //attach newNode after last
            last = newNode;        //make last point to
                                   //the actual last node
            current = current->link;   //make current point
                                       //to the next node
        }//end while
    }//end else
}//end copyList

template <class Type>
linkedListType<Type>::~linkedListType() //destructor
{
   destroyList();
}//end destructor

template <class Type>
linkedListType<Type>::linkedListType
                      (const linkedListType<Type>& otherList)
{
    first = nullptr;
    copyList(otherList);
}//end copy constructor

         //overload the assignment operator
template <class Type>
const linkedListType<Type>& linkedListType<Type>::operator=
                      (const linkedListType<Type>& otherList)
{
    if (this != &otherList) //avoid self-copy
    {
        copyList(otherList);
    }//end else

     return *this;
}

#endif

Below is the code for the testProgLinkedList.cpp
//This program tests various operation of a linked list
//34 62 21 90 66 53 88 24 10 -999

#include <iostream>                                 //Line 1
#include "unorderedLinkedList.h"                    //Line 2

using namespace std;                                //Line 3

int main()                                          //Line 4
{                                                   //Line 5
    unorderedLinkedList<int> list1, list2;          //Line 6
    int num;                                        //Line 7

    cout << "Line 8: Enter integers ending "
         << "with -999" << endl;                    //Line 8
    cin >> num;                                     //Line 9

    while (num != -999)                             //Line 10
    {                                               //Line 11
        list1.insertLast(num);                      //Line 12
        cin >> num;                                 //Line 13
    }                                               //Line 14

    cout << endl;                                   //Line 15

    cout << "Line 16: list1: ";                     //Line 16
    list1.print();                                  //Line 17
    cout << endl;                                   //Line 18
    cout << "Line 19: Length of list1: "
         << list1.length() << endl;                 //Line 19

    list2 = list1;     //test the assignment operator Line 20

    cout << "Line 21: list2: ";                     //Line 21
    list2.print();                                  //Line 22
    cout << endl;                                   //Line 23
    cout << "Line 24: Length of list2: "
         << list2.length() << endl;                 //Line 24

    cout << "Line 25: Enter the number to be "
         << "deleted: ";                            //Line 25
    cin >> num;                                     //Line 26
    cout << endl;                                   //Line 27

    list2.deleteNode(num);                          //Line 28

    cout << "Line 29: After deleting " << num
         << " list2: " << endl;                     //Line 29
    list2.print();                                  //Line 30
    cout << endl;                                   //Line 31

    cout << "Line 32: Length of list2: "
         << list2.length() << endl;                 //Line 32

    cout << endl << "Line 33: Output list1 "
         << "using an iterator" << endl;            //Line 33

    linkedListIterator<int> it;                     //Line 34

    for (it = list1.begin(); it != list1.end();
                             ++it)                  //Line 35
        cout << *it << " ";                         //Line 36
    cout << endl;                                   //Line 37

    return 0;                                       //Line 38
}                                                   //Line 39

Below is the code for the unorderedLinkList.h file
    #ifndef H_UnorderedLinkedList
    #define H_UnorderedLinkedList

    #include "linkedList.h"

    using namespace std;

    template <class Type>
    class unorderedLinkedList: public linkedListType<Type>
    {
    public:
        bool search(const Type& searchItem) const;
          //Function to determine whether searchItem is in the list.
          //Postcondition: Returns true if searchItem is in the
          //               list, otherwise the value false is
          //               returned.

        void insertFirst(const Type& newItem);
          //Function to insert newItem at the beginning of the list.
          //Postcondition: first points to the new list, newItem is
          //               inserted at the beginning of the list,
          //               last points to the last node in the
          //               list, and count is incremented by 1.

        void insertLast(const Type& newItem);
          //Function to insert newItem at the end of the list.
          //Postcondition: first points to the new list, newItem
          //               is inserted at the end of the list,
          //               last points to the last node in the
          //               list, and count is incremented by 1.

        void deleteNode(const Type& deleteItem);
          //Function to delete deleteItem from the list.
          //Postcondition: If found, the node containing
          //               deleteItem is deleted from the list.
          //               first points to the first node, last
          //               points to the last node of the updated
          //               list, and count is decremented by 1.
    };

    template <class Type>
    bool unorderedLinkedList<Type>::
                       search(const Type& searchItem) const
    {
        nodeType<Type> *current; //pointer to traverse the list
        bool found = false;

        current = first; //set current to point to the first
                         //node in the list

        while (current != nullptr    && !found)    //search the list
            if (current->info == searchItem) //searchItem is found
                found = true;
            else
                current = current->link; //make current point to
                                         //the next node
        return found;
    }//end search

    template <class Type>
    void unorderedLinkedList<Type>::insertFirst(const Type& newItem)
    {
        nodeType<Type> *newNode; //pointer to create the new node

        newNode = new nodeType<Type>; //create the new node

        newNode->info = newItem;    //store the new item in the node
        newNode->link = first;      //insert newNode before first
        first = newNode;            //make first point to the
                                    //actual first node
        count++;                    //increment count

        if (last == nullptr)   //if the list was empty, newNode is also
                            //the last node in the list
            last = newNode;
    }//end insertFirst

    template <class Type>
    void unorderedLinkedList<Type>::insertLast(const Type& newItem)
    {
        nodeType<Type> *newNode; //pointer to create the new node

        newNode = new nodeType<Type>; //create the new node

        newNode->info = newItem;  //store the new item in the node
        newNode->link = nullptr;     //set the link field of newNode
                                  //to nullptr

        if (first == nullptr)  //if the list is empty, newNode is
                            //both the first and last node
        {
            first = newNode;
            last = newNode;
            count++;        //increment count
        }
        else    //the list is not empty, insert newNode after last
        {
            last->link = newNode; //insert newNode after last
            last = newNode; //make last point to the actual
                            //last node in the list
            count++;        //increment count
        }
    }//end insertLast

    template <class Type>
    void unorderedLinkedList<Type>::deleteNode(const Type& deleteItem)
    {
        nodeType<Type> *current; //pointer to traverse the list
        nodeType<Type> *trailCurrent; //pointer just before current
        bool found;

        if (first == nullptr)    //Case 1; the list is empty.
            cout << "Cannot delete from an empty list."
                 << endl;
        else
        {
            if (first->info == deleteItem) //Case 2
            {
                current = first;
                first = first->link;
                count--;
                if (first == nullptr)    //the list has only one node
                    last = nullptr;
                delete current;
            }
            else //search the list for the node with the given info
            {
                found = false;
                trailCurrent = first;  //set trailCurrent to point
                                       //to the first node
                current = first->link; //set current to point to
                                       //the second node

                while (current != nullptr && !found)
                {
                    if (current->info != deleteItem)
                    {
                        trailCurrent = current;
                        current = current-> link;
                    }
                    else
                        found = true;
                }//end while

                if (found) //Case 3; if found, delete the node
                {
                    trailCurrent->link = current->link;
                    count--;

                    if (last == current)   //node to be deleted
                                           //was the last node
                        last = trailCurrent; //update the value
                                             //of last
                    delete current;  //delete the node from the list
                }
                else
                    cout << "The item to be deleted is not in "
                         << "the list." << endl;
            }//end else
        }//end else
    }//end deleteNode

    #endif

But when I compiled the code it showed error messages as seen below:
I don't know how to fix the errors as I am new to coding. Please help me.
Error messages

A: Generally speaking you can ignore all the errors after the first couple. Fix errors one at a time starting with the first.
This line
    current = first; //set current to point to the first
                     //node in the list

generates an error which says that the compiler doesn't know what first is. Now it looks like there is a declaration of first in linkedListType<Type> but the compiler doesn't find it. Why? Well that is complicated, but basically it is because your class is a template and the name is defined in a parent template class. Fortunately there is a simple fix, just add this->
    current = this->first; //set current to point to the first
                           //node in the list

More details here, but be warned it's complicated.


text:
Q: $\lambda < 0 \land \left(A^2+B^2\right) \cos \left(2 \sqrt{\lambda } x\right)+2 A B \sinh \left(2 \sqrt{-\lambda } x\right)\leq 0 \implies A = B = 0$ I was solving an eigenvalue problem and ultimately ended up with having to prove
$$\lambda < 0 \land (A, B) \in \mathbb{R}^2 \land \left(A^2+B^2\right) \cos \left(2 \sqrt{\lambda } x\right)+2 A B \sinh \left(2 \sqrt{-\lambda } x\right)\leq 0 \implies A = B = 0$$
However, I have no clue how to proceed.

A: You have one imaginary argument; I get
$$  \cos it = \cosh t $$
which you need for $\cos 2 \sqrt \lambda x$ since you say $\lambda < 0$
$$ \left(A^2+B^2\right) \cosh \left(2 \sqrt{-\lambda } x\right)+2 A B \sinh \left(2 \sqrt{-\lambda } x\right)\leq 0 $$
Name $t = 2 \sqrt{-\lambda} x$ (which is real)  so that we are looking at
$$ (A^2 + B^2 ) \cosh t + 2AB \sinh t $$
Note that  $$ | \sinh t  | < \cosh t $$ and
$$ \sinh t > - \cosh t $$
$$ (A^2 + B^2 ) \cosh t + 2AB \sinh t \geq (A^2 + B^2 ) \cosh t - 2|AB| \cosh t$$
$$ (A^2 + B^2 ) \cosh t + 2AB \sinh t \geq (|A| - |B| )^2 \cosh t \geq (|A| - |B| )^2$$
See https://en.wikipedia.org/wiki/Hyperbolic_functions#Complex_trigonometric_definitions


text:
Q: why can't get user access token (offline) to manage pages? i'm trying to write a script to post to a page while the admin is offline.
my application has the manage_pages extended permission of the admin user.
here is my code:
require('php-sdk/src/facebook.php');
$facebook = new Facebook(array(
'appId'  => 'MY_APP_ID', // YOUR APP ID
'secret' => 'MY_SECRET', // YOUR API SECRET
'cookie' => true
));

$user_admin_id = 'MY_ADMIN_ID';
$page_id = 'MY_PAGE_ID';

//get the access token to post to my page via the graph api
$accounts = $facebook->api("/" . $user_admin_id  . "/accounts");

foreach ($accounts['data'] as $account)
{
    if ($account['id'] == $page_id)
    {

    //found the access token, now we can break out of the loop
    $page_access_token = $account['access_token'];
    break;
    }
}

but I always get this message:

"Fatal error: Uncaught OAuthException: A user access token is required
  to request this resource. thrown in
  /home/itrade10/public_html/khodiersoftware/php-sdk/src/base_facebook.php
  on line 1033"

A: You forgot to authorize the User, that´s how you get a User Access Token:

https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/

Don´t forget to add the "manage_pages" permission in the scope Parameter. You will also have to use the Function "setExtendedAccessToken" of the PHP SDK to extend the User Token. After that, you will get a Page Access Token that is valid forever with the /me/accounts endpoint.
If you used getLoginUrl already, then there´s something wrong with that code, you may want to add it to the question.
Before getting the accounts (with /me/accounts, not with your id), get the User ID:
$user = $facebook->getUser();

If you got a valid User Token, your ID will be in the $user Variable.

A: maybe this one? https://developers.facebook.com/roadmap/offline-access-removal/  also see Getting long-lived access token with setExtendedAccessToken() returns short lived token

A: The error message is telling you exactly what the problem is... you need to get a user access token to access your page tokens


text:
Q: WARNING: executing transaction with 0 enlisted resource: Bitronix I am getting this warning "executing transaction with 0 enlisted resource" while executing a distributed transaction with Bitronix into two datasources. Can some one help to understand how to enlist resources to global transaction. My code is:
   import java.sql.Connection;
   import java.sql.PreparedStatement;
   import java.sql.SQLException;

   import javax.sql.DataSource;
   import javax.transaction.HeuristicMixedException;
   import javax.transaction.HeuristicRollbackException;
   import javax.transaction.NotSupportedException;
   import javax.transaction.RollbackException;
   import javax.transaction.SystemException;

   import bitronix.tm.BitronixTransactionManager;
   import bitronix.tm.TransactionManagerServices;

   public class TestMain {

     public static void main(String[] args) {

     new TestMain().TestDT();

   }

   private void TestDT(){

     DataSource dataSourceRemote = ConnectionManager.getDatasourceRemote();
     DataSource dataSourceLocal = ConnectionManager.getDatasourceLocal();
     Connection con, conn = null;
     try {

        /*String remoteDS = "remoteDS";
        String localDS = "localDS";
        InitialContext ctxRemote = new InitialContext();
        ctxRemote.bind(remoteDS, dataSourceRemote);*/

        String INSERT_QUERY = "insert emp values (?,?,?,?)";

        /*InitialContext ctxLocal = new InitialContext();
        ctxLocal.bind(localDS, dataSourceLocal);*/
        BitronixTransactionManager btx =         TransactionManagerServices.getTransactionManager();
        //DataSource dsRemote = null;
        //btx.ge
    //UserTransaction us =

        try {

            btx.begin();

            //DataSource dsRemote = (DataSource) ctxRemote.lookup(remoteDS);
            con = dataSourceRemote.getConnection();
            //con.setAutoCommit(false);
            PreparedStatement pstmt = con.prepareStatement(INSERT_QUERY);

            for(int i=1; i<=5; i++){
                pstmt.setInt(1, i);
                pstmt.setString(2, "Sanjay_"+i);
                pstmt.setString(3, "123"+i);
                pstmt.setString(4, "1000"+i);
                pstmt.execute();
            }

            //DataSource dsLocal = (DataSource) ctxLocal.lookup(localDS);
            conn = dataSourceLocal.getConnection();
            //conn.setAutoCommit(false);
            PreparedStatement ps = conn.prepareStatement(INSERT_QUERY);
            for(int i=1; i<=5; i++){
                ps.setInt(1, i);
                ps.setString(2, "Nikhil_"+i);
                ps.setString(3, "123"+i);
                ps.setString(4, "1000"+i);
                ps.execute();
            }

            btx.commit();
            con.close();
            conn.close();

        } catch (NotSupportedException e) {
            e.printStackTrace();
        } catch (SystemException e) {
            e.printStackTrace();
        }catch (SQLException e) {
            try{
                btx.rollback();
            }catch (Exception ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }catch (HeuristicRollbackException e) {
            try{
                btx.rollback();
            }catch (Exception ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }catch (HeuristicMixedException e) {
            try{
                btx.rollback();
            }catch (Exception ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }catch (RollbackException e) {
            try{
                btx.rollback();
            }catch (Exception ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally{
            //try{
                btx.shutdown();
                //con.close();
                //conn.close();
            /*}catch (Exception e) {
                e.printStackTrace();
            }*/
        }

        //btx.getTransaction()
    }catch (Exception e) {

        e.printStackTrace();
    }

}
      }

A: "executing transaction with 0 enlisted resource" simply means that your data-sources are not mapped with Bitronix transaction manager.