Q: How to modify non-configurable, non-writable properties in Javascript? I'm writing a simple EventEmitter is ES5.
The objective is to ensure that all properties on EventEmitter instances are
non-writable and non-configurable."
After 6 hours of racking my brain I still can't figure out how to, increase the listenerCount, for example if the configurable descriptor is set to false.
Here's an example of what I have:
var eventEmitter = function(){
  var listeners = listeners || 0;
  var events = events || {};

  Object.defineProperties(this, {
   listeners: {
    value : 0,
    configurable: false,
    writable: false
  },
  events: {
    value: {},
    configurable : false,
    writable: false
    }
  });
  return this;
};

eventEmmitter.prototype.on = function(ev, cb) {
  if (typeof ev !== 'string') throw new TypeError("Event should be type string", "index.js", 6);
  if (typeof cb !== 'function' || cb === null || cb === undefined) throw new TypeError("callback should be type function", "index.js", 7);

  if (this.events[ev]){
    this.events[ev].push(cb);
  } else {
    this.events[ev] = [cb];
  }

  this.listeners ++;
  return this;
};

A: I would recommend the use of an IIFE (immediatly invoked function expression):
var coolObj=(function(){
var public={};
var nonpublic={};
nonpublic.a=0;
public.getA=function(){nonpublic.a++;return nonpublic.a;};

return public;
})();

Now you can do:
coolObj.getA();//1
coolObj.getA();//2
coolObj.a;//undefined
coolObj.nonpublic;//undefined
coolObj.nonpublic.a;//undefined

I know this is not the answer youve expected, but i think its the easiest way of doing sth like that.

A: You can use a proxy which requires a key in order to define properties:

function createObject() {
  var key = {configurable: true};
  return [new Proxy({}, {
    defineProperty(target, prop, desc) {
      if (desc.value === key) {
        return Reflect.defineProperty(target, prop, key);
      }
    }
  }), key];
}
function func() {
  var [obj, key] = createObject();
  key.value = 0;
  Reflect.defineProperty(obj, "value", {value: key});
  key.value = function() {
    key.value = obj.value + 1;
    Reflect.defineProperty(obj, "value", {value: key});
  };
  Reflect.defineProperty(obj, "increase", {value: key});
  return obj;
}
var obj = func();
console.log(obj.value); // 0
try { obj.value = 123; } catch(err) {}
try { Object.defineProperty(obj, "value", {value: 123}); } catch(err) {}
console.log(obj.value); // 0
obj.increase();
console.log(obj.value); // 1


Q: Image hiding under button android Image view is hiding under the button what changes I can do so that the image view can be above the button view pager also have bottom padding so that button can properly accommodate. The image is showing on the other parts but not above the button.
  <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".McqActivity"
        android:id="@+id/fragment"
        >

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent">

                <ImageView
                android:id="@+id/starFirst"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:src="@drawable/ic_baseline_star_24"
                />

            <com.google.android.material.button.MaterialButton
                android:id="@+id/right"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                 />

        </RelativeLayout>

        <androidx.viewpager2.widget.ViewPager2
            android:id="@+id/questions_view_frag"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.0"
            android:orientation="horizontal"
            android:paddingBottom="20dp"
            android:paddingTop="50dp"
            >

        </androidx.viewpager2.widget.ViewPager2>

    </androidx.constraintlayout.widget.ConstraintLayout>

A: layout_constraintBottom_toBottomOf and other layout_constraint... won't work inside RelativeLayout, these are desired to work with ConstraintLayout as strict parent. if you want to align two Views next to/below/above inside RelativeLayoyut you have to use other attributes, e.g.
android:layout_below="@+id/starFirst"
android:layout_above="@+id/starFirst"
android:layout_toRightOf="@id/starFirst"
android:layout_toLeftOf="@id/starFirst"

note that every attr which starts with layout_ is desired to be read by strict parent, not by View which have such attrs set. every ViewGroup have own set of such
edit: turned out that this is an elevation case/issue (Z axis), so useful attributes are
android:translationZ="100dp"
android:elevation="100dp"


Q: Handling multiple exceptions I have written a class which loads configuration objects of my application and keeps track of them so that I can easily write out changes or reload the whole configuration at once with a single method call. However, each configuration object might potentially throw an exception when doing IO, yet I do not want those errors to cancel the overall process in order to give the other objects still a chance to reload/write. Therefore I collect all exceptions which are thrown while iterating over the objects and store them in a super-exception, which is thrown after the loop, since each exception must still be handled and someone has to be notified of what exactly went wrong. However, that approach looks a bit odd to me. Someone out there with a cleaner solution?
Here is some code of the mentioned class:
public synchronized void store() throws MultipleCauseException
    {
    MultipleCauseException me = new MultipleCauseException("unable to store some resources");
    for(Resource resource : this.resources.values())
        {
        try
            {
            resource.store();
            }
        catch(StoreException e)
            {
            me.addCause(e);
            }
        }
    if(me.hasCauses())
        throw me;
    }

A: If you want to keep the results of the operations, which it seems you do as you purposely carry on, then throwing an exception is the wrong thing to do. Generally you should aim not to disturb anything if you throw an exception.
What I suggest is passing the exceptions, or data derived from them, to an error handling callback as you go along.
public interface StoreExceptionHandler {
    void handle(StoreException exc);
}

public synchronized void store(StoreExceptionHandler excHandler) {
    for (Resource resource : this.resources.values()) {
        try {
            resource.store();
        } catch (StoreException exc) {
            excHandler.handle(exc);
        }
    }
    /* ... return normally ... */
]

A: There are guiding principles in designing what and when exceptions should be thrown, and the two relevant ones for this scenario are:

*

*Throw exceptions appropriate to the abstraction (i.e. the exception translation paradigm)

*Throw exceptions early if possible

The way you translate StoreException to MultipleCauseException seems reasonable to me, although lumping different types of exception into one may not be the best idea. Unfortunately Java doesn't support generic Throwables, so perhaps the only alternative is to create a separate MultipleStoreException subclass instead.
With regards to throwing exceptions as early as possible (which you're NOT doing), I will say that it's okay to bend the rule in certain cases. I feel like the danger of delaying a throw is when exceptional situations nest into a chain reaction unnecessarily. Whenever possible, you want to avoid this and localize the exception to the smallest scope possible.
In your case, if it makes sense to conceptually think of storing of resources as multiple independent tasks, then it may be okay to "batch process" the exception the way you did. In other situations where the tasks has more complicated interdependency relationship, however, lumping it all together will make the task of analyzing the exceptions harder.
In a more abstract sense, in graph theory terms, I think it's okay to merge a node with multiple childless children into one. It's probably not okay to merge a whole big subtree, or even worse, a cyclic graph, into one node.


Q: What is the meaning of Duration in Amazon RDS Backup window What does Duration specify?
Does it mean that the backup will start between 01:00 to 01:30 and keep running until it has completed? Or does it have a different meaning?

A: The duration window indicates the time in which the backup will start. I can start anywhere between the time specified and could last longer than the window.


Q: Uncontrolled input of type text to be controlled warning I'm trying to create a multi step registration form using React and Redux.
The main component is as follows :
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as actionCreators from '../../actions/actionCreators';
import countries from '../../data/countries';

import RegistrationFormStepOne from './registrationFormStepOne';
import RegistrationFormStepTwo from './registrationFormStepTwo';
import RegistrationFormStepThree from './registrationFormStepThree';
import RegistrationFormStepFour from './registrationFormStepFour';

class RegistrationPage extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            user: Object.assign({}, this.props.userData),
            fileNames: {},
            selectedFile: {},
            icons: {
                idCard: 'upload',
                statuten: 'upload',
                blankLetterhead: 'upload',
                companyPhoto: 'upload'
            },
            step: 1,
            errors: {}
        };

        this.setUser = this.setUser.bind(this);
        this.onButtonClick = this.onButtonClick.bind(this);
        this.onButtonPreviousClick = this.onButtonPreviousClick.bind(this);
        this.changeCheckboxState = this.changeCheckboxState.bind(this);
        this.onFileChange = this.onFileChange.bind(this);
        this.routerWillLeave = this.routerWillLeave.bind(this);
    }

    componentDidMount() {
        this.context.router.setRouteLeaveHook(this.props.route, this.routerWillLeave);
    }

    routerWillLeave(nextLocation) {
        if (this.state.step > 1) {
            this.setState({step: this.state.step - 1});
            return false;
        }
    }

    getCountries(){
        return countries;
    }

    setUser(event) {
        const field = event.target.name;
        const value = event.target.value;

        let user = this.state.user;
        user[field] = value;
        this.setState({user: user});

    }

    validation(){
        const user = this.state.user;
        const languageReg = this.props.currentLanguage.default.registrationPage;
        let formIsValid = true;
        let errors = {};

        if(!user.companyName){
            formIsValid = false;
            errors.companyName = languageReg.companyNameEmpty;
        }

        if(!user.btwNumber){
            formIsValid = false;
            errors.btwNumber = languageReg.btwNumberEmpty;
        }

        if(!user.address){
            formIsValid = false;
            errors.address = languageReg.addressEmpty;
        }

        if(!user.country){
            formIsValid = false;
            errors.country = languageReg.countryEmpty;
        }

        if(!user.zipcode){
            formIsValid = false;
            errors.zipcode = languageReg.zipcodeEmpty;
        }

        if(!user.place){
            formIsValid = false;
            errors.place = languageReg.placeEmpty;
        }

        if(!user.firstName){
            formIsValid = false;
            errors.firstName = languageReg.firstnameEmpty;
        }

        this.setState({errors: errors});
        return formIsValid;
    }

    onFileChange(name, event) {
        event.preventDefault();
        let file = event.target.value;

        let filename = file.split('\\').pop(); //We get only the name of the file
        let filenameWithoutExtension = filename.replace(/\.[^/.]+$/, ""); //We get the name of the file without extension

        let user = this.state.user;
        let fileNames = this.state.fileNames;
        let selectedFile = this.state.selectedFile;
        let icons = this.state.icons;

        switch (name.btnName) {
            case "idCard" :
                fileNames[name.btnName] = filenameWithoutExtension;
                //Check if file is selected
                if(file){
                    selectedFile[name.btnName] = "fileSelected";
                    user["idCardFile"] = true;
                    icons["idCard"] = "check";
                }else{
                    selectedFile[name.btnName] = "";
                    user["idCardFile"] = false;
                    icons["idCard"] = "upload";
                }
                break;
            case "statuten" :
                fileNames[name.btnName] = filenameWithoutExtension;

                //Check if file is selected
                if(file){
                    selectedFile[name.btnName] = "fileSelected";
                    user["statutenFile"] = true;
                    icons["statuten"] = "check";
                }else{
                    selectedFile[name.btnName] = "";
                    user["statutenFile"] = false;
                    icons["statuten"] = "upload";
                }
                break;
            case "blankLetterhead" :
                fileNames[name.btnName] = filenameWithoutExtension;

                //Check if file is selected
                if(file){
                    selectedFile[name.btnName] = "fileSelected";
                    user["blankLetterheadFile"] = true;
                    icons["blankLetterhead"] = "check";
                }else{
                    selectedFile[name.btnName] = "";
                    user["blankLetterheadFile"] = false;
                    icons["blankLetterhead"] = "upload";
                }
                break;
            default:
                fileNames[name.btnName] = filenameWithoutExtension;
                //Check if file is selected
                if(file){
                    selectedFile[name.btnName] = "fileSelected";
                    user["companyPhotoFile"] = true;
                    icons["companyPhoto"] = "check";
                }else{
                    selectedFile[name.btnName] = "";
                    user["companyPhotoFile"] = false;
                    icons["companyPhoto"] = "upload";
                }
        }

        this.setState({user: user, fileNames: fileNames, selectedFile: selectedFile, icons: icons});
    }

    changeCheckboxState(event) {
        let chcName = event.target.name;
        let user = this.state.user;

        switch (chcName) {
            case "chcEmailNotificationsYes":
                user["emailNotifications"] = event.target.checked;
                break;
            case "chcEmailNotificationsNo":
                user["emailNotifications"] = !event.target.checked;
                break;
            case "chcTerms":
                if(typeof this.state.user.terms === "undefined"){
                    user["terms"] = false;
                }else{
                    user["terms"] = !this.state.user.terms;
                }

                break;
            case "chcSmsYes":
                user["smsNotifications"] = event.target.checked;
                break;
            default:
                user["smsNotifications"] = !event.target.checked;
        }
        this.setState({user: user});
        this.props.actions.userRegistration(this.state.user);
    }

    onButtonClick(name, event) {
        event.preventDefault();
        this.props.actions.userRegistration(this.state.user);
        switch (name) {
            case "stepFourConfirmation":
                this.setState({step: 1});
                break;
            case "stepTwoNext":
                this.setState({step: 3});
                break;
            case "stepThreeFinish":
                this.setState({step: 4});
                break;
            default:
                if(this.validation()) {
                   this.setState({step: 2});
                }
        }
    }

    onButtonPreviousClick(){
        this.setState({step: this.state.step - 1});
    }

    render() {
        const languageReg = this.props.currentLanguage.default.registrationPage;

        console.log(this.state.user);
        let formStep = '';
        let step = this.state.step;
        switch (step) {
            case 1:
                formStep = (<RegistrationFormStepOne user={this.props.userData}
                                                     onChange={this.setUser}
                                                     onButtonClick={this.onButtonClick}
                                                     countries={this.getCountries(countries)}
                                                     errors={this.state.errors}
                                                     step={step}/>);
                break;
            case 2:
                formStep = (<RegistrationFormStepTwo user={this.props.userData}
                                                     onChange={this.setUser}
                                                     onButtonClick={this.onButtonClick}
                                                     onButtonPreviousClick={this.onButtonPreviousClick}
                                                     errors={this.state.errors}/>);
                break;
            case 3:
                formStep = (<RegistrationFormStepThree user={this.props.userData}
                                                       onFileChange={this.onFileChange}
                                                       onButtonClick={this.onButtonClick}
                                                       onButtonPreviousClick={this.onButtonPreviousClick}
                                                       errors={this.state.errors}
                                                       fileNames={this.state.fileNames}
                                                       icons={this.state.icons}
                                                       fileChosen={this.state.selectedFile}/>);
                break;

            default:
                formStep = (<RegistrationFormStepFour user={this.props.userData}
                                                      onChange={this.setUser}
                                                      onChangeCheckboxState={this.changeCheckboxState}
                                                      onButtonClick={this.onButtonClick}
                                                      onButtonPreviousClick={this.onButtonPreviousClick}
                                                      errors={this.state.errors}/>);
        }

        return (

                                        {React.cloneElement(formStep, {currentLanguage: languageReg})}

        );
    }
}

RegistrationPage.contextTypes = {
    router: PropTypes.object
};

function mapStateToProps(state, ownProps) {
    return {
        userData: state.userRegistrationReducer
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(actionCreators, dispatch)
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(RegistrationPage);

The first step component is as follows
    import React from 'react';
import Button from '../../common/formElements/button';
import RegistrationFormHeader from './registrationFormHeader';
import TextInput from '../../common/formElements/textInput';
import SelectInput from '../../common/formElements/selectInput';

const RegistrationFormStepOne = ({user, onChange, onButtonClick, errors, currentLanguage, countries}) => {

  const language = currentLanguage;

  return (

      <form role="form" action="" method="post" id="contact_form">

          <RegistrationFormHeader activeTab={0} currentLanguage={language}/>

{language.businessInfoConfig}

{language.businessBoxDesc}

              {language.businessDesc}

              <TextInput
                type="text"
                name="companyName"
                label={language.companyNameLabel}
                labelClass="control-label"
                placeholder={language.companyNameLabel}
                className="templateInput"
                id="company"
                onChange={onChange}
                value={user.companyName}
                errors={errors.companyName}
              />

              <TextInput
                type="text"
                name="btwNumber"
                label={language.vatNumberLabel}
                placeholder={language.vatNumberLabel}
                className="templateInput"
                id="btwNumber"
                onChange={onChange}
                value={user.btwNumber}
                errors={errors.btwNumber}
              />

              <TextInput
                type="text"
                name="address"
                label={language.addressLabel}
                placeholder={language.address1Placeholder}
                className="templateInput"
                id="address"
                onChange={onChange}
                value={user.address}
                errors={errors.address}
              />

              <TextInput
                type="text"
                name="address1"
                placeholder={language.address2Placeholder}
                className="templateInput"
                id="address"
                onChange={onChange}
                value={user.address1}
                errors=""
              />

              <TextInput
                type="text"
                name="address2"
                placeholder={language.address3Placeholder}
                className="templateInput"
                id="address"
                onChange={onChange}
                value={user.address2}
                errors=""
              />

              <SelectInput name="country"
                           label={language.selectCountryLabel}
                           onChange={onChange}
                           options={countries}
                           className="templateInput selectField"
                           defaultOption={language.selectCountry}
                           value={user.country}
                           errors={errors.country}
                           />

              <TextInput
                type="text"
                name="zipcode"
                label={language.zipcodeLabel}
                placeholder={language.zipcodeLabel}
                className="templateInput"
                id="zipcode"
                onChange={onChange}
                value={user.zipcode}
                errors={errors.zipcode}
              />

              <TextInput
                type="text"
                name="place"
                label={language.placeLabel}
                placeholder={language.placeLabel}
                className="templateInput"
                id="place"
                onChange={onChange}
                value={user.place}
                errors={errors.place}
              />

            <Button onClick={onButtonClick.bind(this)}
                    name="stepOneNext"
                    value={language.btnNext}
                    icon="arrow-circle-right"
                    style={{margin: '0 auto 60px'}}/>

      </form>

  );
};

export default RegistrationFormStepOne;

I try to add some simple validation and I've added validation function in my main component and then I check on button click if the returned value true or false is. If it's true, than I set step state to a appropriate value. And it works if I validate only the form fields of the first step, but when I try to also validate one or more form fields of the next step (now I'm trying to validate also the first field of the second step)
if(!user.firstName){
        formIsValid = false;
        errors.firstName = languageReg.firstnameEmpty;
    }

I get than
Warning: TextInput is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
Without the validation function works everything perfect.
Any advice?
EDIT
    import React, {propTypes} from 'react';
import _ from 'lodash';

const TextInput = ({errors, style, name, labelClass, label, className, placeholder, id, value, onChange, type}) => {
  let wrapperClass = "form-group";

  if (errors) {
    wrapperClass += " " + "inputHasError";
  }

  return (

      {label}
      <input type={type}
             className={className}
             placeholder={placeholder}
             name={name}
             id={id}
             value={value}
             style={{}}
             onChange={onChange}
      />

{errors}

  );
};

TextInput.propTypes = {
  name: React.PropTypes.string.isRequired,
  label: React.PropTypes.string,
  onChange: React.PropTypes.func.isRequired,
  type: React.PropTypes.string.isRequired,
  id: React.PropTypes.string,
  style: React.PropTypes.object,
  placeholder: React.PropTypes.string,
  className: React.PropTypes.string,
  labelClass: React.PropTypes.string,
  value: React.PropTypes.string,
  errors: React.PropTypes.string
};

export default TextInput;

This is second step component :
import React from 'react';
import Button from '../../common/formElements/button';
import RegistrationFormHeader from './registrationFormHeader';
import TextInput from '../../common/formElements/textInput';

const RegistrationFormStepTwo = ({user, onChange, onButtonClick, onButtonPreviousClick, errors, currentLanguage}) => {
    const language = currentLanguage;

    return (

            <form role="form" action="" method="post" id="contact_form">

                    <RegistrationFormHeader activeTab={1} currentLanguage={language}/>

{language.personalInfoConfig}

{language.personalBoxDesc}

                            {language.personalDesc}

                            <TextInput
                                type="text"
                                name="firstName"
                                label={language.firsnameLabel}
                                placeholder={language.firsnameLabel}
                                className="templateInput"
                                id="name"
                                onChange={onChange}
                                value={user.firstName}
                                errors={errors.firstName}
                            />

                            <TextInput
                                type="text"
                                name="lastName"
                                label={language.lastnameLabel}
                                placeholder={language.lastnameLabel}
                                className="templateInput"
                                id="name"
                                onChange={onChange}
                                value={user.lastName}
                                errors={errors.lastName}
                            />

                            <TextInput
                                type="text"
                                name="phone"
                                label={language.phoneLabel}
                                placeholder={language.phoneLabel}
                                className="templateInput"
                                id="phone"
                                onChange={onChange}
                                value={user.phone}
                                errors={errors.phone}

                            />

                            <TextInput
                                type="text"
                                name="mobilePhone"
                                label={language.mobileLabel}
                                placeholder={language.mobileLabel}
                                className="templateInput"
                                id="phone"
                                style={{}}
                                onChange={onChange}
                                value={user.mobilePhone}
                                errors={errors.mobilePhone}
                            />

                            <TextInput
                                type="text"
                                name="email"
                                id="email"
                                label={language.emailLabel}
                                placeholder={language.emailLabel}
                                className="templateInput"
                                style={{}}
                                onChange={onChange}
                                value={user.email}
                                errors={errors.email}
                            />

                            <TextInput
                                type="text"
                                name="userName"
                                label={language.usernameLabel}
                                placeholder={language.usernameLabel}
                                className="templateInput"
                                id="name"
                                onChange={onChange}
                                value={user.userName}
                                errors={errors.userName}
                            />

                            <TextInput
                                type="password"
                                name="password"
                                label={language.passwordLabel}
                                placeholder={language.passwordLabel}
                                className="templateInput"
                                id="password"
                                onChange={onChange}
                                value={user.password}
                                errors={errors.password}
                            />

                            <TextInput
                                type="password"
                                name="confirmPassword"
                                label={language.passwordConfirmLabel}
                                placeholder={language.passwordConfirmLabel}
                                className="templateInput"
                                id="password"
                                onChange={onChange}
                                value={user.confirmPassword}
                                errors={errors.confirmPassword}
                            />

                        <Button onClick={onButtonPreviousClick}
                                name="btnPrevious"
                                value={language.btnPrevious}
                                icon="arrow-circle-left"
                                style={{marginRight: 10, float: 'right'}}/>

                        <Button onClick={onButtonClick} name="stepTwoNext" value={language.btnNext}
                                icon="arrow-circle-right" style={{marginLeft: 10, float: 'left'}}/>

            </form>

    );
};

export default RegistrationFormStepTwo;

A: This is why the warning exists: When the value is specified as undefined, React has no way of knowing if you intended to render a component with an empty value or if you intended for the component to be uncontrolled. It is a source of bugs.
You could do a null/undefined check, before passing the value to the input.
a source

A: @Kokovin Vladislav is right. To put this in code, you can do this in all your input values:
<TextInput
    // your other code
    value={user.firstName || ''}
/>

That is, if you don't find the value of first name, then give it an empty value.


Q: Interleaving the rows of two different SQL tables, group by one row My Sql query is like this
$view =  mysql_query ("SELECT domain,count(distinct session_id) as
         views FROM `statistik` left join statistik_strippeddomains on
         statistik_strippeddomains.id = statistik.strippeddomain WHERE
         `angebote_id` = '".(int)$_GET['id']."' and strippeddomain!=1
         group by domain having count (distinct session_id) >
         ".(int)($film_daten['angebote_views']/100)."  order
         count(distinct session_id$vladd) desc limit 25");

How can I write its Codeigniter Model I appreciate any Help

A: try this
$this->db->select('statistik.domain,statistik.count(DISTINCT(session_id)) as views');
$this->db->from('statistik');
$this->db->join('statistik_strippeddomains', 'statistik_strippeddomains.id = statistik.strippeddomain', 'left');
$this->db->where('angebote_id',$_GET['id']);
$this->db->where('strippeddomain !=',1);
$this->db->group_by('domain');
$this->db->having('count > '.$film_daten['angebote_views']/100, NULL, FALSE);
$this->db->order_by('count','desc');
$this->db->limit('25');
$query = $this->db->get();

Comment me If you have any query.


Q: Query conditions to insert data from a form What I'm trying to do is:
If the age input in my form = 28, 30, 25 or 21 then I want to auto insert value 8 in the column (VE), else keep it empty. Is this the right way to do that?
if($form_data->action == 'Insert')
        {

            $age=array(28, 30, 25, 21);
            $age_str=implode("','", $age);

                if($form_data->age == $age_str){

                $query="INSERT INTO tbl
                        (VE) VALUE ('8') WHERE id= '".$form_data->id."'
                ";
                    $statement = $connect->prepare($query);
                    $statement->execute();
            }
            $data = array(
                ':date'             =>  $date,
                ':first_name'       =>  $first_name,
                ':last_name'        =>  $last_name,
                ':age'          =>  $age
            );
            $query = "
            INSERT INTO tbl
                (date, first_name, last_name, age) VALUES
                (:date, :first_name, :last_name, :age)
            ";
            $statement = $connect->prepare($query);

            if($statement->execute($data))
            {
                $message = 'Data Inserted';
            }
        }

Also, how do I insert the new row with the row id from the other form data going into tbl?

A: Use php's in_array instead of trying to compare a string. To get the id of the query where you insert the form data, you can return the id of the insert row from your prepared statement.
if ($form_data->action == 'Insert') {

    // assuming $age, $date, $first_name, $last_name
    // already declared prior to this block
    $data = array(
      ':date'             =>  $date,
      ':first_name'       =>  $first_name,
      ':last_name'        =>  $last_name,
      ':age'          =>  $age
    );

    $query = "
      INSERT INTO tbl
        (date, first_name, last_name, age) VALUES
        (:date, :first_name, :last_name, :age)
    ";
    $statement = $connect->prepare($query);

    if ($statement->execute($data)) {
        $message = 'Data Inserted';

        // $id is the last inserted id for (tbl)
        $id = $connect->lastInsertID();

        // NOW you can insert your child row in the other table
        $ages_to_insert = array(28, 30, 25, 21);

        // in_array uses your array...so you don't need
        // if($form_data->age == $age_str){

        if (in_array($form_data->age, $ages_to_insert)) {

            $query="UPDATE tbl SER VE = '8' WHERE id= '".$id."'";
            $statement2 = $connect->prepare($query);
            $statement2->execute();
        }
    }
}


Q: Accessing array value is null Hello I have decoded a json string that I sent to my server and Im trying to get the values from him.
My problem is that I cant get the values from the inner arrays.
This is my code:
<?php

    $post = file_get_contents('php://input');

    $arrayBig = json_decode($post, true);

    foreach ($arrayBig as $array)
    {

    $exercise = $array['exercise'];

    $response["exercise"] = $exercise;
    $response["array"] = $array;

    echo json_encode($response);

    }

?>

When I get the answer from my $response I get this values:
{"exercise":null,"array":[{"exercise":"foo","reps":"foo"}]}

Why is $array['exercise'] null if I can see that is not null in the array
Thanks.

A: Because of the [{...}] you are getting an array in an array when you decode your array key.
So:
$exercise = $array['exercise'];

Should be:
$exercise = $array[0]['exercise'];

See the example here.

A: From looking at the result of $response['array'], it looks like $array is actually this
[['exercise' => 'foo', 'reps' => 'foo']]

that is, an associative array nested within a numeric one. You should probably do some value checking before blindly assigning values but in the interest of brevity...
$exercise = $array[0]['exercise'];


Q: Composer update show this error: VirtualAlloc() failed: [0x00000008] Composer worked find yesterday, but today after I trying install:
composer require --prefer-dist "himiklab/yii2-recaptcha-widget" "*"
While run composer update command it show me error:

VirtualAlloc() failed: [0x00000008] VirtualAlloc() failed:
[0x00000008] PHP Fatal error:  Out of memory (allocated 956301312)
(tried to allocate 201326600 bytes) in
phar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/DependencyResolver/RuleSet.php
on line 84
Fatal error: Out of memory (allocated 956301312) (tried to allocate
201326600 bytes) in
phar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/DependencyResolver/RuleSet.php
on line 84

I try update composer on my other projects, it is worked fine. After some researching I increased memory_limit: 4096M(also -1) in php.ini file. Then I tried to increase virtual memory in Computer->Properties, but still show error.
I try to run next command:
composer update -vvv --profile, result in attached image
Composer error
Any help would be greatly appreciated.

A: You are probably using 32bit PHP. This version cannot allocate enough memory for composer even if you change the memory_limit to -1 (unlimited).
Please use 64 bit PHP with the Composer to get rid of these memory problems.


Q: How do I get the original values of in an Update SQL Trigger I'm not very familiar with triggers so thank you for your patience.
I have a database table with four columns for user text input and just four date columns showing when the user text input was last changed. What I want the trigger to do is to compare the original and new values of the user text input columns and if they are different update the date column with getdate(). I don't know how to do this. The code I wrote can't get the pre-update value of the field so it can't be compared to the post-update value. Does anyone know how to do it?
(Normally I would do this in a stored procedure. However this database table can also be directly edited by an Access database and we can't convert those changes to use the stored procedure. This only leaves us with using a trigger.)

A: In sql server there are two special tables availble in the trigger called inserted and deleted. Same structure as the table on which the trigger is implemented.
inserted has the new versions, deleted the old.


Q: Create Executable progeam of addition in C on linux I am new to Linux. Sorry I am asking very basic question. On windows I have Main.cpp file having code for addition of two number. In Visual studio gives me .exe. But how to do it on Linux. On my Linux machine have gcc compiler no IDE.
What I write in Make file and how to run.
Main.cpp has code like
#include <stido.h>
#include <conio.h>
// Static library file included
//#include "Add.h"
int main()
{
    int a,b,c;

    a = 10;
    b = 20;

    c= a+b;
    //Add function in static lib (.a in case of linux)
    //c= Add(a,b);
    printf("Addition is :%d",c);

    return 0;
}

After that I want use Add function which is in Addition. How to use with above program removing commented in code?

A: For c++ code, the command is usually something like:
g++ Main.cpp -o FileNameToWriteTo

Alternatively, if you just run
g++ Main.cpp

it will output to a default file called a.out.
Either way, you can then run whichever file you created by doing:
./FileNameToWriteTo.out

See this for more details: http://pages.cs.wisc.edu/~beechung/ref/gcc-intro.html


Q: QProgressBar updates as function progress How to initializa the operation of QProgressBar, I already declare her maximum, minimum, range and values.
I want to assimilate the progress of QProgressBar with the "sleep_for" function.
Current code:
void MainPrograma::on_pushCorre_clicked()
{
    QPlainTextEdit *printNaTela = ui->plainTextEdit;
    printNaTela->moveCursor(QTextCursor::End);
    printNaTela->insertPlainText("corrida iniciada\n");

    QProgressBar *progresso = ui->progressBar;
    progresso->setMaximum(100);
    progresso->setMinimum(0);
    progresso->setRange(0, 100);
    progresso->setValue(0);
    progresso->show();

    WORD wEndereco = 53606;
    WORD wValor = 01;
    WORD ifValor = 0;
    EscreveVariavel(wEndereco, wValor);

//How to assimilate QProgressBar to this function:
std::this_thread::sleep_for(std::chrono::milliseconds(15000));
//StackOverFlow help me please

    EscreveVariavel(wEndereco, ifValor);

A: use a QTimer
and in the slot update the value of the progressbar
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    t = new QTimer(this);
    t->setSingleShot(false);
    c = 0;
    connect(t, &QTimer::timeout, [this]()
    {   c++;
        if (c==100) {
            c=0;
        }
        qDebug() << "T...";
        ui->progressBar->setValue(c);
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    t->start(100);
}

A: I'm not sure about your intentions with such sleep: are you simulating long wait? do you have feedback about progress during such process? Is it a blocking task (as in the example) or it will be asynchronous?
As a direct answer (fixed waiting time, blocking) I think it is enough to make a loop with smaller sleeps, like:
EscreveVariavel(wEndereco, wValor);
for (int ii = 0; ii < 100; ++ii) {
   progresso->setValue(ii);
   qApp->processEvents(); // necessary to update the UI
   std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
EscreveVariavel(wEndereco, ifValor);

Note that you may end waiting a bit more time due to thread scheduling and UI refresh.
For an async task you should pass the progress bar to be updated, or some kind of callback that does such update. Keep in mind that UI can only be refreshed from main thread.


Q: Preallocation and Vectorization Speedup I am trying to improve the speed of script I am trying to run.
Here is the code: (my machine = 4 core win 7)
clear y;
n=100;
x=linspace(0,1,n);
% no y pre-allocation using zeros
start_time=tic;

for k=1:n,
    y(k) =  (1-(3/5)*x(k)+(3/20)*x(k)^2 -(x(k)^3/60)) / (1+(2/5)*x(k)-(1/20)*x(k)^2);
end

elapsed_time1 = toc(start_time);
fprintf('Computational time for serialized solution: %f\n',elapsed_time1);

Above code gives 0.013654 elapsed time.
On the other hand, I was tried to use pre-allocation by adding y = zeros(1,n); in the above code where the comment is but the running time is similar around ~0.01. Any ideas why? I was told it would improve by a factor of 2. Am I missing something?
Lastly is there any type of vectorization in Matlab that will allow me to forget about the for loop in the above code?
Thanks,

A: In your code: try with n=10000 and you'll see more of a difference (a factor of almost 10 on my machine).
These things related with allocation are most noticeable when the size of your variable is large. In that case it's more difficult for Matlab to dynamically allocate memory for that variable.

To reduce the number of operations: do it vectorized, and reuse intermediate results to avoid powers:
y = (1 + x.*(-3/5 + x.*(3/20 - x/60))) ./ (1 + x.*(2/5 - x/20));

Benchmarking:
With n=100:
Parag's / venergiac's solution:
>> tic
for count = 1:100
y=(1-(3/5)*x+(3/20)*x.^2 -(x.^3/60))./(1+(2/5)*x-(1/20)*x.^2);
end
toc
Elapsed time is 0.010769 seconds.

My solution:
>> tic
for count = 1:100
y = (1 + x.*(-3/5 + x.*(3/20 - x/60))) ./ (1 + x.*(2/5 - x/20));
end
toc
Elapsed time is 0.006186 seconds.

A: You don't need a for loop. Replace the for loop with the following and MATLAB will handle it.
y=(1-(3/5)*x+(3/20)*x.^2 -(x.^3/60))./(1+(2/5)*x-(1/20)*x.^2);

This may give a computational advantage when vectors become larger in size. Smaller size is the reason why you cannot see the effect of pre-allocation. Read this page for additional tips on how to improve the performance.
Edit: I observed that at larger sizes, n>=10^6, I am getting a constant performance improvement when I try the following:
x=0:1/n:1;

instead of using linspace. At n=10^7, I gain 0.05 seconds (0.03 vs 0.08) by NOT using linspace.

A: try operation element per element (.*, .^)
clear y;
n=50000;
x=linspace(0,1,n);
% no y pre-allocation using zeros
start_time=tic;

for k=1:n,
    y(k) =  (1-(3/5)*x(k)+(3/20)*x(k)^2 -(x(k)^3/60)) / (1+(2/5)*x(k)-(1/20)*x(k)^2);
end

elapsed_time1 = toc(start_time);
fprintf('Computational time for serialized solution: %f\n',elapsed_time1);

start_time=tic;
y =  (1-(3/5)*x+(3/20)*x.^2 -(x.^3/60)) / (1+(2/5)*x-(1/20)*x.^2);

elapsed_time1 = toc(start_time);
fprintf('Computational time for product solution: %f\n',elapsed_time1);

my data

Computational time for serialized solution: 2.578290
Computational time for serialized solution: 0.010060


Q: Scala and Akka HTTP: Request inside a request & issue with threads I am new to learning Scala, Akka Streams and Akka HTTP, so apologies beforehand if the question is too basic.
I want to do an HTTP request inside an HTTP request, just like in the following piece of code:
  implicit val system = ActorSystem("ActorSystem")
  implicit val materializer = ActorMaterializer
  import system.dispatcher

  val requestHandler: Flow[HttpRequest, HttpResponse, _] = Flow[HttpRequest].map {
    case HttpRequest(HttpMethods.GET, Uri.Path("/api"), _, _, _) =>
      val responseFuture = Http().singleRequest(HttpRequest(uri = "http://www.google.com"))
      responseFuture.onComplete {
        case Success(response) =>
          response.discardEntityBytes()
          println(s"The request was successful")
        case Failure(ex) =>
          println(s"The request failed with: $ex")
      }
      //Await.result(responseFuture, 10 seconds)
      println("Reached HttpResponse")
      HttpResponse(
        StatusCodes.OK
      )
  }

  Http().bindAndHandle(requestHandler, "localhost", 8080)

But in the above case the result looks like this, meaning that Reached HttpResponse is reached first before completing the request:
Reached HttpResponse
The request was successful

I tried using Await.result(responseFuture, 10 seconds) (currently commented out) but it made no difference.
What am I missing here? Any help will be greatly appreciated!
Many thanks in advance!

A: map is a function that takes request and produces a response:
HttpRequest => HttpResponse

The challenge is that response is a type of Future. Therefore, you need a function that deals with it. The function that takes HttpRequest and returns Future of HttpResponse.
HttpRequest => Future[HttpResponse]

And voila, mapAsync is exactly what you need:
val requestHandler: Flow[HttpRequest, HttpResponse, _] = Flow[HttpRequest].mapAsync(2) {
  case HttpRequest(HttpMethods.GET, Uri.Path("/api"), _, _, _) =>
    Http().singleRequest(HttpRequest(uri = "http://www.google.com")).map (resp => {
      resp.discardEntityBytes()
      println(s"The request was successful")
      HttpResponse(StatusCodes.OK)
    })
}


Q: Dealing with four digits: memcache sorts 1000 before 150 from least to greatest In app engine I retrieve a list of items stored in memcache:
items = memcache.get("ITEMS")

and sort them by amount and price:
items.sort(key = lambda x:(x.price, x.amount))

Which works most of the time, when the amount is three digits. However, when I have 2 items with 150 and 1000 amounts for the same price, the entry with 1000 goes before other one. How can I fix this?

A: fixed it:
items.sort(key = lambda x:((float)(x.price), (int)(x.amount)))


Q: Do codigniter 3.1.7 support hmvc? I tried but no luck From the very first answer of this
How to implement HMVC in codeigniter 3.0? I tried all steps with codigniter 3.7.1 but no luck. I am still getting 404.
$config['modules_locations'] = array(
    APPPATH.'modules/' => '../modules/',
);

Then I tried putting the above code in application/config/config.php but still 404


Q: Saving time - Compiling c++ and plotting at the same time gnuplot Hi in order to save time whene I execute the code I command this line :
g++ name.cpp && ./a.out

where nome,cpp is the name of the file that contains the code. If I succesively I need to plot some data generated by the exucatable with Gnuplot there is a way to add in the previous line instead of writing:
gnuplot
plot "name2.dat"

?

A: you can:
g++ name.cpp && ./a.out && gnuplot -e "plot 'name2.dat'; pause -1"

gnuplot exits when you hit return (see help pause for more options)
if you want to start an interactive gnuplot session there is a dirty way I implemented.
g++ name.cpp && ./a.out && gnuplot -e "plot 'name2.dat' -

(pay attention to the final minus sign)


Q: How to put a Hyphen in column Total Cost Value in power bi I have a table with blank value, but i want a hyphen "-" to appear when the value is null.
Using an expression similar to this:
var VLGROUP =
(Expression……
RETURN
IF(
ISBLANK(VLGROUP),
BLANK(),
VLGROUP)
Someone know if is possible?
Thanks!!
enter image description here
gur.com/C0u8s.png

A: Try this below option-
Sales for the Group =

var sales =
    CALCULATE(
        SUM(Financialcostcenter[amount]),
        Financialcostcenter[partnercompany]= "BRE",
        Financialcostcenter[2 digits]=71,
        DATESYTD('Datas'[Date])
    )
    +
    CALCULATE(
        SUM(Financialcostcenter[amount]),
        Financialcostcenter[partnercompany]= "GRM",
        Financialcostcenter[2 digits]=71,
        DATESYTD('Datas'[Date])
    )

RETURN IF(sales = BLANK(),"-", -(sales))


Q: Constraints on an embedded subclass - Grails, GORM, Mongo I've been pulling my hair out with this issue for a couple of days.
I have an embedded subclass with several specified constraints. My issue is that these constraints are never enforced,
I'm using grails 2.3.11 and the mongodb plugin 3.0.2.
Here is my setup (Simplified slightly).
Media class
class Media{
ObjectId id;
String name;
Film film;

static mapWith = "mongo"
static embedded = ["film"]
}

Film Class
class Film{
ObjectId id;
String name;

static mapWith = "mongo"
static belongsTo = [media : Media]
static mapping = {
    lazy:false
}
static constraints = {
name(nullable:false) //works as expected. Save fails if name is set to null
}
}

ActionFilm Class
class ActionFilm extends Film{
int score;
String director;

//These constraints are never enforeced. No matter what value I set the fields to the save is always successful
static constraints = {
score(min:50)
director(nullable:true)
}
}

Is this an issue with Mongo and Gorm? Is it possible to have contraints in bth a parent and subclass?
Example code when saving
public boolean saveMedia(){
ActionFilm film = new ActionFilm()
film.setName("TRON");
film.setScore(2)
film.setDirector("Ted")

Media media = new Media()
media.setName("myMedia")
media.setFilm(film)
media.save(flush:true, failOnError:false)  //Saves successfully when it shouldn't as the score is below the minimum constrains

}
Edit
I've played aroubd some more and the issue only persits when I'm saving the Media object with ActionFilm as an embedded object. If I save the ActionFilm object the validation is applied.
 ActionFilm film = new ActionFilm()
    film.setName("TRON");
    film.setScore(2)
    film.setDirector("Ted")
    film.save(flush:true, failOnError:false)  //Doesn't save as the diameter is wrong. Expected behaviour.

So the constraints are applied as expected when I save the ActionFilm object but aren't applied if its an embedded object.

A: I've solved my issue in case anyone else comes across this. It may not be the optimal solution but I haven't found an alternative.
I've added a custom validator to the  Media class that calls validate() on the embedded Film class and adds any errors that arise to the Media objects errors
class Media{
ObjectId id;
String name;
Film film;

static mapWith = "mongo"
static embedded = ["film"]

    static constraints = {
            film(validator : {Film film, def obj, def errors ->
                boolean valid = film.validate()
                if(!valid){
                    film.errors.allErrors.each {FieldError error ->
                        final String field = "film"
                        final String code = "$error.code"
                        errors.rejectValue(field,code,error.arguments,error.defaultMessage )
                    }
                }
                return valid
            }
            )
        }


Q: MySQL -> PHP Array -> Json need output in array plus object format i am trying to fetch data from MySQL and show it in JSON format
This is the partial PHP code
$sql = "SELECT item, cost, veg, spicy_level FROM food1";
$result = $conn->query($sql);

    while($row = $result->fetch_assoc()) {

    echo  json_encode($row),"
";}

?>
i am getting output as
{"item":"dosa","cost":"20","veg":"0","spicy_level":"1"}
{"item":"idli","cost":"20","veg":"0","spicy_level":"2"}

but i need it as
food1:[
{"item":"dosa","cost":"20","veg":"0","spicy_level":"1"},
{"item":"idli","cost":"20","veg":"0","spicy_level":"2"}
]

can anyone please guide me?
i think what i am getting is in object format and i need output in array format i.e. with [ & ].
very new to this json and php.

A: You can incapsulate query results in array and after print it;
$sql = "SELECT item, cost, veg,     spicy_level FROM food1";
$result = $conn->query($sql);
$a = array();
while($row = $result->fetch_assoc()) {
  if($a['food1'] ==null)
     $a['food1'] = array():
  array_push($a['food1'],$row);}

  echo json_encode($a);
?>

A: Your code should be :
$sql = "SELECT item, cost, veg, spicy_level FROM food1";
$result = $conn->query($sql);

$food['food1'] = array();

while($row = $result->fetch_assoc()) {
    $food['food1'][] = $row;
}

echo  json_encode($food);

A: Don't call json_encode each time through the loop. Put all the rows into an array, and then encode that.
$food = array();
while ($row = $result->fetch_assoc()) {
    $food[] = $row;
}
echo json_encode(array('food1' => $food));


Q: Firebase hosting randomly shows "Site Not Found" at custom domain We recently launched our firebase application at https://tnb-widgets.firebaseapp.com/ and https://thenextbid.com/ (the last one being our custom domain). It all works smoothly except for some seemingly random moments in which it shows a page stating "Site Not Found". This already happened multiple times and after a couple of minutes the site seems to be back again.
The last time this happened was at 2:37AM GMT-5 and the last time I deployed a new release to this same firebase hosting project was at 3:45PM the day before. This release also contained 80 files in total, so it cannot possibly be "an empty directory".
Our firebase.json file looks like this:
{
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "hosting": {
    "public": "build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "/api/**",
        "function": "app"
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "storage": {
    "rules": "storage.rules"
  }
}

There's no service workers registered. The "build" folder contains 80 files and most importantly it contains the "index.html" at its root.
Does anyone have similar issues? I would appreciate any idea to solve this! Thanks.


Q: Reduce Time for Checking Out Code in Visual Studio Online I'm trying out VSO and it's taking over 2 minutes to sync with a GitHub repository.  It appears that it's checking out the whole thing on every build.  I made sure that the "clean" box is unchecked but it had no effect.
Any ideas on how to get it to cache the source or is this even possible in VSO?

A: Each build in VSO uses a new VM that is spun up just for your build. Short
of hosting your own Build Server connected your VSO, I don't think it can be avoided.
Unless there are ways to speed up a the process of downloading the code from a git repo, I think you're stuck.


Q: How to skip a line when reading from a file I am reading stuff from a file and this is the format : c stands for circle and the double is the radius, r for rectangle and the double is width and height respectively and t for triangle and the double represents side length:
c 12
c 2
r 3 4
c 2.4
t 2.9
3 c          // wrong format
t 2.9
10 r        // wrong format

I run this code:
ifstream infile(names);
while(infile >> names) {
    if(names.at(0) == 'c') {
        double r;
        infile >> r;
        cout << "radius = " << r << endl;
    } else if(names.at(0) == 'r') {
        double w;
        double h;
        infile >> w;
        infile >> h;
        cout << "width = " << w << ", height = " << h << endl;
    } else if(names.at(0) == 't') {
        double s;
        infile >> s;
        cout << "side = " << s << endl;
    } else {
        continue;
    }
}

infile.close()

And this is the output:
radius = 12
radius = 2
width = 3, height = 4
radius = 2.4
side = 2.9
radius = 0

I was wondering how I can skip the wrong format line. I have tried using geline but still no luck
EDIT: radius, height, width and side have to be > 0

A: The biggest potential problems you are running up against is the fact that you assume a line is valid if it begins with a c, t or r without first validating the remainder of the line matches the format for a circle, triangle or rectangle. While not fatal to this data set, what happens if one of the lines was 'cat' or 'turtle'?
By failing to validate all parts of the line fit the "mold" so to speak, you risk attempting to output values of r, h & w or s that were not read from the file. A simple conditional check of the read to catch the potential failbit or badbit will let you validate you have read what you think you read.
The remainder is basically semantics of whether you use the niceties of C++ like a vector of struct for rectangles and whether you use a string instead of char*, etc. However, there are certain benefits of using a string to read/validate the remainder of each line (or you could check the stream state and use .clear() and .ignore())
Putting those pieces together, you can do something like the following. Note, there are many, many different approaches you can take, this is just one approach,
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

typedef struct {        /* simple typedef for vect of rectangles */
    int width, height;
} rect_t;

int main (int argc, char **argv) {

    vector<double> cir;     /* vector of double for circle radius */
    vector<double> tri;     /* vector of double for triangle side */
    vector<rect_t> rect;    /* vector of rect_t for rectangles */
    string line;            /* string to use a line buffer */

    if (argc < 2) { /* validate at least one argument given */
        cerr << "error: insufficient input.\n"
                "usage: " << argv[0] << " filename\n";
        return 1;
    }

    ifstream f (argv[1]);   /* open file given by first argument */
    if (!f.is_open()) {     /* validate file open for reading */
        cerr << "error: file open failed '" << argv[1] << "'.\n";
        return 1;
    }

    while (getline (f, line)) {     /* read each line into 'line' */
        string shape;               /* string for shape */
        istringstream s (line);     /* stringstream to parse line */
        if (s >> shape) {           /* if shape read */
            if (shape == "c") {     /* is it a "c"? */
                double r;           /* radius */
                string rest;        /* string to read rest of line */
                if (s >> r && !getline (s, rest))  /* radius & nothing else */
                    cir.push_back(r);   /* add radius to cir vector */
                else    /* invalid line for circle, handle error */
                    cerr << "error: invalid radius or unexpected chars.\n";
            }
            else if (shape == "t") {
                double l;           /* side length */
                string rest;        /* string to read rest of line */
                if (s >> l && !getline (s, rest))  /* length & nothing else */
                    tri.push_back(l);   /* add length to tri vector */
                else    /* invalid line for triangle, handle error */
                    cerr << "error: invalid triangle or unexpected chars.\n";
            }
            else if (shape == "r") {    /* is it a rect? */
                rect_t tmp;             /* tmp rect_t */
                if (s >> tmp.width && s >> tmp.height)  /* tmp & nohtin else */
                    rect.push_back(tmp);    /* add to rect vector */
                else    /* invalid line for rect, handle error */
                    cerr << "error: invalid width & height.\n";
            }
            else    /* line neither cir or rect, handle error */
                cerr << "error: unrecognized shape '" << shape << "'.\n";
        }
    }

    cout << "\nthe circles are:\n";     /* output valid circles */
    for (auto& i : cir)
        cout << "  c: " << i << "\n";

    cout << "\nthe triangles are:\n";   /* output valid triangles */
    for (auto& i : tri)
        cout << "  t: " << i << "\n";

    cout << "\nthe rectangles are:\n";  /* output valid rectangles */
    for (auto& i : rect)
        cout << "  r: " << i.width << " x " << i.height << "\n";
}

By storing values for your circles, triangles and rectangles independent of each other, you then have the ability to handle each type of shape as its own collection, e.g.
Example Use/Output
$ ./bin/read_shapes dat/shapes.txt
error: unrecognized shape '3'.
error: unrecognized shape '10'.

the circles are:
  c: 12
  c: 2
  c: 2.4

the triangles are:
  t: 2.9
  t: 2.9

the rectangles are:
  r: 3 x 4

Look things over and let me know if you have further questions. The main takeaway is to insure you validate down to the point you can insure what you have read is either a round-peg to fit in the circle hole, a square-peg to fit in a square hole, etc..

A: The only thing I added was a getline where I put a comment at the "else" of the loop.
while(infile >> names) {
    if(names.at(0) == 'c') {
        double r;
        infile >> r;
        cout << "radius = " << r << endl;
    } else if(names.at(0) == 'r') {
        double w;
        double h;
        infile >> w;
        infile >> h;
        cout << "width = " << w << ", height = " << h << endl;
    } else if(names.at(0) == 't') {
        double s;
        infile >> s;
        cout << "side = " << s << endl;
    } else {
        // discard of the rest of the line using getline()
        getline(infile, names);
        //cout << "discard: " << names << endl;

    }
}

Output:
radius = 12
radius = 2
width = 3, height = 4
radius = 2.4
side = 2.9
side = 2.9


Q: How to filter post by join condition? I have a table called wpps_posts which have this structure:
ID | post_title | post_type
 1      foo         zoacres-property
 2      foo2        zoacres-property
 3      foo3        post

I would like to return all the posts with type zoacres-property and also I want filter them by price. Each price is stored inside the table wp_postmeta:
meta_id | post_id | meta_key | meta_value
  100       2         price       5000
  100       1         price       0

How can I order all the posts by price ASC?
I'm stuck with the following query:
SELECT * FROM wpps_posts p
INNER JOIN wpps_posts wp ON wp.ID = p.ID
WHERE p.post_type = 'zoacres-property'
ORDER BY wp.meta??

EXPECTED RESULT:
ID | post_title | post_type
 1      foo         zoacres-property
 2      foo2        zoacres-propertY

A: SELECT * FROM wpps_posts p
INNER JOIN wp_postmeta wp ON wp.post_ID = p.ID
AND wp.meta_key='price'
WHERE p.post_type = 'zoacres-property'
ORDER BY wp.meta_value asc

A: You could do something like this, depends what other type of meta type records you have.
SELECT * FROM wpps_posts
LEFT JOIN wp_postmeta ON wp_postmeta.post_id = wpps_posts.ID AND wp_postmeta.meta_key = 'price'
WHERE wpps_posts.post_type = 'zoacres-property'
ORDER BY wp_postmeta.meta_value


Q: Convert the existing nested dictionary output in string to a list to iterate over it I have a rest api which provides a list of key value pair's and we need to fetch all the id's from this json output file.
Contents of the json file
{
    "count": 6,
    "results": [
        {
            "key": "roles",
            "id": "1586230"
        },
        {
            "key": "roles",
            "id": "1586951"
        },
        {
            "key": "roles",
            "id": "1586932"
        },
    ],
    "roles": {
        "1586230": {
            "name": "Systems Engineer",
            "deleted_at": null,
            "created_at": "2022-04-22T03:22:24-07:00",
            "updated_at": "2022-04-22T03:22:24-07:00",
            "id": "1586230"
        },
        "1586951": {
            "name": "Engineer- Software",
            "deleted_at": null,
            "created_at": "2022-05-05T01:51:29-07:00",
            "updated_at": "2022-05-05T01:51:29-07:00",
            "id": "1586951"
        },
        "1586932": {
            "name": "Engineer- SW",
            "deleted_at": null,
            "created_at": "2022-05-05T01:38:37-07:00",
            "updated_at": "2022-05-05T01:38:37-07:00",
            "id": "1586932"
        },
    },
    "meta": {
        "count": 6,
        "page_count": 5,
        "page_number": 1,
        "page_size": 20
    }
}

The rest call saves the contents to a file called p1234.json Opened the file in python:
with open ('p1234.json') as file:
    data2 = json.load(file)

for ids in data2['results']:
    res= ids['id']
    print(res)

Similarly
with open ('p1234.json') as file:
    data2 = json.load(file)

for role in data2['roles']:
    res= roles['name']
    print(res)

fails with errors.
How to iterate over a nested array do I can only get the values of names listed in roles array
roles --> 1586230 --> name --> System Engineer

Thank you

A: You have to loop over the items of the dictionary.
for key, value in data2['roles'].items():
    res= value['name']
    print(res)

A: There is nothing wrong with your code, I run it and I didn't get any error.
The problem that I see though is your Json file, some commas shouldn't be there:
{
"count": 6,
"results": [
    {
        "key": "roles",
        "id": "1586230"
    },
    {
        "key": "roles",
        "id": "1586951"
    },
    {
        "key": "roles",
        "id": "1586932"
    } \\ here
],
"roles": {
    "1586230": {
        "name": "Systems Engineer",
        "deleted_at": null,
        "created_at": "2022-04-22T03:22:24-07:00",
        "updated_at": "2022-04-22T03:22:24-07:00",
        "id": "1586230"
    },
    "1586951": {
        "name": "Engineer- Software",
        "deleted_at": null,
        "created_at": "2022-05-05T01:51:29-07:00",
        "updated_at": "2022-05-05T01:51:29-07:00",
        "id": "1586951"
    },
    "1586932": {
        "name": "Engineer- SW",
        "deleted_at": null,
        "created_at": "2022-05-05T01:38:37-07:00",
        "updated_at": "2022-05-05T01:38:37-07:00",
        "id": "1586932"
    } \\ here
},
"meta": {
    "count": 6,
    "page_count": 5,
    "page_number": 1,
    "page_size": 20
}

after that any parsing function will do the job.


Q: how to store Image profile(jpg file) and PDF documents in AWS DynamoDB? I am migrating my Spring MVC services to the AWS API Gateway using Python Lambda with Dynamo Db , I have endpoint where i can store or retrieve the people image and also the reports which is PDF file , can you please suggest me which is the best practice to store the images and pdf files in AWS .
Your help is really appreciated!!

A: Keep in mind, DynamoDB has a 400KB limit on each item.
I would recommend using S3 for images and PDF documents. It also allows you to set up a CDN much more easily, rather than using something like DynamoDB.
You can always link your S3 link to an item in DynamoDB if you need to store data related to the file.

A: AWS DynamoDB has a limit on the row size to be max of 400KB. So, it is not advisable to store the binary content of image/PDF document in a column directly. Instead, you should store the image/PDF in S3 and have the link stored in a column in DynamoDB.
If you were using Java, you could have leveraged the S3Link abstraction that takes care of storing the content in S3 and maintaining the link in DynamoDB column.


Q: Split a column after specific characters I have a field data in mysql db. For example
quot_number
====================
UMAC/ARC/161299/801
UMAC/LAK/151542/1051
UMAC/LAK/150958/00050

Iam expecting an output as below:
801
1051
00050

Actually the last numbers or characters after the last '/' has to be shown in my sql query. Any ways to achieve it?
I tried to add something like this, but not getting expected result:
LEFT(quotation.quot_number, 16) as quot_number4

right(quot_number,((CHAR_LENGTH(quot_number))-(InStr(quot_number,',')))) as quot_number5

A: Use function substring_index.
select
    substring_index(quot_number, '/', -1)
from yourtable


Q: TFS configure variables on Release definition instantiation I have a release definition setup with several tasks. When a developer wants to create a release from this definition, i'd like to give them the option of selecting which features they'd like to release (turn on/off tasks). Ideally this would be via the Create Release dialog using a variable or similar.
Can this be done? Or is the only way to achieve this to create a draft release and enable/disable the tasks on each environment? Believe this is prone to error (toggle task on one environment but forget to on another) and this is not an option as administrator has locked editing of definitions (prevent incorrect setup of production releases).
Understand I can create separate release definitions to cover the options but it seems like a lot of duplication.

A: Unfortunately, this is not supported in TFS currently. The workarounds are just like you mentioned above, to disable and enable those steps or use draft release.
This is a user voice about your request you could vote:
 https://visualstudio.uservoice.com/forums/330519-team-services/suggestions/19165690-select-steps-when-create-release


Q: AWS S3 Internal Server Error: Tyring to upload pdf file on after another I'm trying to generate PDF file using FPDF and PHP and later upload to  AWS-s3 and generate the url. When I executed the below code in my local-machine Using XAMPP it's generating files and uploading it to S3.
But When I deployed in AWS server as an API it's uploading only first file and for other its giving 500 server error
Below is my code that I used in Local Machine
    require '../fpdf/fpdf.php';
    require 'start.php';

    use Aws\Exception\AwsException;

    $location = "bangalore";
    $db     =   getConnection();
    $query   = "SELECT first_name FROM customer_info where location = '$location'";
    $execute = $db->query($query);
    $result  = $execute->fetchAll(PDO::FETCH_ASSOC);

  for($i = 0; $i < $len; $i++) {
 $pdf = new FPDF();
 $pdf->AddPage();

$pdf->SetFont('Arial', 'B', 14);
$txt = "Legal Document of ".$result[$i]['first_name'];
$pdf->Cell(180, 0, $txt, 0, 1, 'C');
$pdf->Line(5, 20, 200, 20);

$docname = $result[$i]['first_name'] . ".pdf";
$filepath = "../file/{$docname}";
$pdf->Output($filepath, 'F');

//s3 client
try {
       $res = $S3->putObject([
        'Bucket' => $config['S3']['bucket'],
        'Key' => "PATH_TO_THE_DOCUMENT/{$docname}",
        'Body' => fopen($filepath, 'rb'),
        'ACL' => 'public-read'
    ]);

    var_dump($res["ObjectURL"]);
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}

}
Output:
   Array ( [0] => Array ( [first_name] => Mohan ) [1] => Array ( [first_name] => Prem ) [2] => Array ( [first_name] => vikash ) [3] => Array ( [first_name] => kaushik ) )

     string(70) "https://streetsmartb2.s3.amazonaws.com/PATH_TO_THE FILE/Mohan.pdf"

 string(72) "https://streetsmartb2.s3.amazonaws.com/PATH_TO_THE FILE/Prem%20.pdf"

API CODE
      //pdf generation another api
      $app->post('/pdfmail', function() use($app){

    //post parameters
    $location = $app->request->post('loc');
    $id       = $app->request->post('id');

   $db = getConnection();
   $query   = "SELECT * FROM customer_info where location = '$location'";
  $execute = $db->query($query);
  $result  = $execute->fetchAll(PDO::FETCH_ASSOC);
  $len = sizeof($result);

  //request array
  $request = array();

  if($result != Null) {
      for($i = 0; $i < $len; $i++) {
          $pdf = new FPDF();
          $pdf->AddPage();

          $pdf->SetFont('Arial', 'B', 14);
          $txt = "Document of Mr." . $result[$i]['first_name'];
          $pdf->Cell(180, 0, $txt, 0, 1, 'C');
          $pdf->Line(5, 20, 200, 20);

          $docname = $result[$i]['first_name'] . ".pdf";
          var_dump($docname);
          $filepath = "../file/{$docname}";
          var_dump($filepath);
          $pdf->Output($filepath, 'F');

          //s3 client
          require '../aws/aws-autoloader.php';

          $config = require('config.php');

          //create s3 instance
          $S3 = S3Client::factory([
              'version' => 'latest',
              'region' => 'REGION',
              'credentials' => array(
                  'key' => $config['S3']['key'],
                  'secret' => $config['S3']['secret']
              )
          ]);

          try {
              $res = $S3->putObject([
                  'Bucket' => $config['S3']['bucket'],
                  'Key' => "PATH_TO_FILE{$docname}",
                  'Body' => fopen($filepath, 'rb'),
                  'ACL' => 'public-read'
              ]);
              var_dump($res["ObjectURL"]);
          } catch (S3Exception $e) {
              echo $e->getMessage() . "\n";
          }

      }
  }

OUTPUT WHEN TESTED IN POSTMAN
    string(10) "vikash.pdf"
    string(18) "../file/vikash.pdf"
   string(71) "https://streetsmartb2.s3.amazonaws.com/PATH_TO_FILE/vikash.pdf"
  string(13) "pradeepan.pdf"
   string(21) "../file/pradeepan.pdf"

After this I'm getting internal server error.

A: Instead of using require_once I've use require...So as the code traversed it was creating AWS Class again and again.
Code
      //s3 client
      require '../aws/aws-autoloader.php'; //use require_once

      $config = require('config.php');

      //create s3 instance
      $S3 = S3Client::factory([
          'version' => 'latest',
          'region' => 'REGION',
          'credentials' => array(
              'key' => $config['S3']['key'],
              'secret' => $config['S3']['secret']
          )
      ]);


Q: Auto-generate @version value in javadoc For the @version tag in javadoc, I use the same value as in BuildConfig.VERSION_NAME. I would like to inject that value, instead of changing every file for each release.
I tried:
* @version {@value BuildConfig#VERSION_NAME}
and
* @version @versionName  (and add -tag versionName:a:"2.2.2")
but none of these works.
I could run sed just before the doc gets generated, but I would rather prefer something 'officially' supported.
Any ideas how to solve this?

A: For the second form, you can put your custom tag at the beginning of a javadoc line.
/**
 * This is a class of Foo<br/>
 *
 * @version
 *
 * @configVersion.
 */

Then use command javadoc -version -tag configVersion.:a:"2.2.2" to generate your javadoc, the custom tag should be handled in this way. Note the last dot(.) character in custom tag name, as the command javadoc suggests

Note: Custom tags that could override future standard tags:  @configVersion. To avoid potential overrides, use at least one period character (.) in custom tag names.


Q: How to retrieve data from MongoDb Atlas and display in an ejs file using mongoose and Nodejs Thanks for the help in advance.
I am trying to retrieve data from my database- myFirstDatabase and collection named as 'shipment' in mongondb. This is a nested schema but I am only interested in the parent data for now. I have this code which retrieves data to the console log. But how can I display or access the data in my orders.ejs file?

Shipment.find({}, function (err, data) {
  if (err) throw err

  console.log(data)
})

MongoDB connected...
[
  {
    _id: new ObjectId("61353311261da54811ee0ca5"),
    name: 'Micky Mouse',
    phone: '5557770000',
    email: 'g@gmail.com',
    address: {
      address: '10 Merrybrook Drive',
      city: 'Herndon',
      state: 'Virginia',
      zip: '21171',
      country: 'United States',
      _id: new ObjectId("61353311261da54811ee0ca6")
    },
    items: {
      car: 'Honda Pilot 2018',
      boxItem: '3 uHaul boxes',
      furniture: 'None',
      electronics: '1 50" Samsung TV',
      bags: '2 black suites cases',
      _id: new ObjectId("61353311261da54811ee0ca7")
    },
    date: 2021-09-05T21:13:53.484Z,
    __v: 0
  }
]

This is the ejs file, a table I am trying to populate the data i get from my mongodb

This is the order table

  <%- include ("./partials/messages"); %>

          #
          Customer
          Address
          City
          State
          Zip
          Phone
          Status

          1

A: server.js
const express = require('express')
const mongoose = require('mongoose')
const Shipment= require('./models/shipment')
const app = express()

mongoose.connect('mongodb://localhost/myFirstDatabase ', {
    useNewUrlParser: true, useUnifiedTopology: true
})

app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended:false }))

app.get('/', async (req,res) => {
    const data= await Shipment.find()
    res.render('index', { data: data})
})

app.listen(process.env.PORT || 5000);

index.ejs
below is part of your ejs file

            #
            Customer
            Address
            City
            State
            Zip
            Phone
            Status

        <% data.forEach((e, index)=> { %>

                <%= index %>
                <%= e.Customer %>
                <%= e.Address %>
                <%= e.City %>
                <%= e.State %>
                <%= e.Zip %>
                <%= e.Phone %>
                <%= e.Status %>

        <% }) %>


Q: node.js app running using forever inaccessible after a while I have a node.js server and a java client communicating using socket.io. I use this api https://github.com/Gottox/socket.io-java-client for the java client. I am using forever module
to run my server.
Everything works well but after some time , my server becomes inaccessible and I need to restart it, Also, most of the times i need to update/edit my node.js server file in order to make my server work again (restarted). Its been two weeks already and im still keep restarting my server :(.
Has anyone run into the same problem ? and solution or advice please.
Thanks


Q: No 'Access-Control-Allow-Origin' header is present on the requested resource. Laravel 5.4 with cors package Hi I was following this tutorial regarding Laravel and VueJs communication.
https://www.youtube.com/watch?v=5hOMkFMxY90&list=PL3ZhWMazGi9IommUd5zQmjyNeF7s1sP7Y&index=8
I have done exactly like it was said in the tutorial. It uses a CORS package https://github.com/barryvdh/laravel-cors/
I have added the service provider middlewares everything as it was told in the tutorial but it just doesnt seem to work.
I have tried it in Laravel 5.4 and Laravel 5.3 as well.
This is my RouetServiceProvider:

            namespace App\Providers;

            use Illuminate\Support\Facades\Route;
            use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

            class RouteServiceProvider extends ServiceProvider
            {
            /**
            * This namespace is applied to your controller routes.
            *
            * In addition, it is set as the URL generator's root namespace.
            *
            * @var string
            */
            protected $namespace = 'App\Http\Controllers';

            /**
            * Define your route model bindings, pattern filters, etc.
            *
            * @return void
            */
            public function boot()
            {
            //

            parent::boot();
            }

            /**
            * Define the routes for the application.
            *
            * @return void
            */
            public function map()
            {
            $this->mapApiRoutes();

            $this->mapWebRoutes();

            //
            }

            /**
            * Define the "web" routes for the application.
            *
            * These routes all receive session state, CSRF protection, etc.
            *
            * @return void
            */
            protected function mapWebRoutes()
            {
            Route::group([
            'middleware' => 'web',
            'namespace' => $this->namespace,
            ], function ($router) {
            require base_path('routes/web.php');
            });
            }

            /**
            * Define the "api" routes for the application.
            *
            * These routes are typically stateless.
            *
            * @return void
            */
            protected function mapApiRoutes()
            {
            Route::group([
            'middleware' => ['api' , 'cors'],
            'namespace' => $this->namespace,
            'prefix' => 'api',
            ], function ($router) {
            require base_path('routes/api.php');
            });
            }
            }

This is my middleware code in kernel
 protected $middleware = [
    \Barryvdh\Cors\HandleCors::class,
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];

I have added its service provider too.
I have seen all the solutions here on stackoverflow but none of them seems to work. I do not need theoretical answer but a practical solution
Thanks


Q: Swift: How to not load AppDelegate during Tests I have an OS X application which on startup loads some data from a server and pushes notifications to the NSUserNotificationCenter.
Now I have the problem that this also happens during my unit tests. I found no way yet to prevent this. Of course I could stub the HTTP loads. But in some cases I want to test the loading and then the notifications get sent anyway.
What I'm trying to do is to make the test runs not load the AppDelegate but a fake one that I'm only using for tests. I found several examples [1] on how to do that with UIApplicationMain, where you can pass a specific AppDelegate class name. The same is not possible with NSApplicationMain [2].
What I've tried is the following:
Removed @NSApplicationMain from AppDelegate.swift, then added a main.swift with the following content:
class FakeAppDelegate: NSObject, NSApplicationDelegate {
}

NSApplication.sharedApplication()
NSApp.delegate = FakeAppDelegate()
NSApplicationMain(Process.argc, Process.unsafeArgv)

This code runs before tests but has no effect at all.
I might have to say: My AppDelegate is almost empty. To handle the MainMenu.xib stuff I made a separate view controller which does the actual loading and notification stuff in awakeFromNib.
[1] http://www.mokacoding.com/blog/prevent-unit-tests-from-loading-app-delegate-in-swift/
[2] https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Miscellaneous/AppKit_Functions/#//apple_ref/c/func/NSApplicationMain

A: Just an update on the previous accept answer, this is my main.swift:
private func isTestRun() -> Bool {
    return NSClassFromString("XCTestCase") != nil
}

if isTestRun() {
    // This skips setting up the app delegate
    NSApplication.shared.run()
} else {
    // For some magical reason, the AppDelegate is setup when
    // initialized this way
    _ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
}

A bit more compact! I'm using Swift 4.1 and XCode 9.4.1

A: After days of trying and failing I found an answer on the Apple forums:

The problem was that my main.swift file was initializing my AppDelegate before NSApplication had been initialized. The Apple documentation makes it clear that lots of other Cocoa classes rely on NSApplication to be up and running when they are initialized. Apparently, NSObject and NSWindow are two of them.

So my final and working code in main.swift looks like this:
private func isTestRun() -> Bool {
    return NSClassFromString("XCTest") != nil
}

private func runApplication(
    application: NSApplication = NSApplication.sharedApplication(),
    delegate: NSObject.Type?   = nil,
    bundle: NSBundle?          = nil,
    nibName: String            = "MainMenu") {

    var topLevelObjects: NSArray?

    // Actual initialization of the delegate is deferred until here:
    application.delegate = delegate?.init() as? NSApplicationDelegate

    guard bundle != nil else {
        application.run()
        return
    }

    if bundle!.loadNibNamed(nibName, owner: application, topLevelObjects: &topLevelObjects ) {
        application.run()
    } else {
        print("An error was encountered while starting the application.")
    }
}

if isTestRun() {
    let mockDelegateClass = NSClassFromString("MockAppDelegate") as? NSObject.Type
    runApplication(delegate: mockDelegateClass)
} else {
    runApplication(delegate: AppDelegate.self, bundle: NSBundle.mainBundle())
}

So the actual problem before was that the Nib was being loaded during tests. This solution prevents this. It just loads the application with a mocked application delegate whenever it detects a test run (By looking for the XCTest class).
I'm sure I will have to tweak this a bit more. Especially when a start with UI Testing. But for the moment it works.


Q: How to use std::transform with a lambda function that takes additional parameters In C++ 11 (or higher) can I use std::transform and a lambda function to transform a vector that also takes other parameters?  For example, how do I pass param to the lambda function below?
std::vector<double> a{ 10.0, 11.0, 12.0 };
std::vector<double> b{ 20.0, 30.0, 40.0 };
std::vector<double> c;
double param = 1.5;
//The desired function is c = (a-b)/param
transform(a.begin(), a.end(), b.begin(), std::back_inserter(c),
          [](double x1, double x2) {return(x1 - x2)/param; });

std::transform wants a function with two input parameters. Do I need to use std::bind?

A: You just need to capture param in your capture list:
transform(a.begin(), a.end(), b.begin(), std::back_inserter(c),
          [param](double x1, double x2) {return(x1 - x2)/param; });

Capturing it by reference also works - and would be correct if param was a big class. But for a double param is fine.

A: This is what the lambda capture is for.  You need to specify & or = or param in the capture block ([]) of the lambda.
std::vector<double> a{ 10.0, 11.0, 12.0 };
std::vector<double> b{ 20.0, 30.0, 40.0 };
std::vector<double> c;
double param = 1.5;
//The desired function is c = (a-b)/param
transform(a.begin(), a.end(), b.begin(), std::back_inserter(c),
          [=](double x1, double x2) {return(x1 - x2)/param; });
//         ^ capture all external variables used in the lambda by value

In the above code we just capture by value since copying a double and having a reference is pretty much the same thing performance wise and we don't need reference semantics.


Q: How can I add an intranet-only endpoint to my IIS hosted WCF service? I have a WCF service hosted in IIS that uses basicHttpBindings. I'm adding a new method to the ServiceContract that will be called from a console app to perform an administrative task. I got to thinking, well wouldn't it be nice if I gave this method its own endpoint. Then I thought and what if that endpoint wasn't even publicly accessible. It would be much better if only a computer on our LAN could access it. It might even be cool if only an AD administrator was authorized to use it, but I don't want to get too elaborate. So I added a new ServiceContract interface that includes my new method. How can I restrict it to LAN access only? Do I need a NetTcpBinding? Networking is not my strong suit and I'm a little confused, conceptually, on how a TCP endpoint could be hosted from IIS. Additionally, when hosting multiple endpoints, does each have to have its own address or can they be at the same address?

A: I am gonna answer some of your questions

*

*there is no binding that would limit access to LAN network though you can use windows authentication to allow users from your network to use the service

*the nettcpbinding is only a tcp connection and you can host it on IIS pof course
check this link for more information hosting nettcp on IIS

*you can have one base address for multiple endpoints , example:
https://localhost:8080/calculator.svc
net.tccp://localhost:8080/calculator.svc