text:
Q: cant find variable props I am trying to show the detail view when user taps on one of the list item. When the user taps on the listitem, I get an error saying Undefined is not an object
evaluating 'this.props.services.ser. Below is the screen shot of the error:

My list item page code is below:
    import React, { Component } from 'react';
import { Text, View, StyleSheet, ListView } from 'react-native';
import { Provider, connect } from 'react-redux';
import { createStore } from 'redux'
import reducers from '../reducers/ServiceReducer';
import ServiceItem from './ServiceItem';
import Icon from 'react-native-vector-icons/EvilIcons';
import ServiceDetail from './ServiceDetail';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: 353,
    flexWrap: 'wrap',
    paddingTop: 20,
    paddingLeft: 20,
  },
});

const store = createStore(reducers);

class AutoCompActivity extends Component {

  renderInitialView() {
    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2,
    });
    this.dataSource = ds.cloneWithRows(this.props.services);

    if (this.props.detailView === true) {
      return (
        <ServiceDetail />
      );
    } else {
      return (
        <ListView
          enableEmptySections={true}
          dataSource={this.dataSource}
          renderRow={(rowData) =>
            <ServiceItem services={rowData} />
          }
        />
      );
    }
  }

  render() {
    return (
      <View style={styles.container}>
        {this.renderInitialView()}
      </View>
    );
  }
}

const mapStateToProps = state => {
  return {

    services: state.services,
    detailView: state.detailView,
  };
};
const ConnectedAutoCompActivity = connect(mapStateToProps)(AutoCompActivity);

const app1 = () => (
  <Provider store={store}>
    <ConnectedAutoCompActivity />
  </Provider>
)

export default app1;

Each item that I display to the user is defined in js class serviceItem.js. Below is the code for serviceItem.js. I put the entire code inside TouchableWithoutFeedback. This is when I am getting an error when user taps on one  of the listItem. I looked at this code several times, but could not figure out where I am doing wrong
  import React from 'react';
import { Text, View, StyleSheet, Image,  TouchableWithoutFeedback } from 'react-native';
import { connect } from 'react-redux';
import { getTheme } from 'react-native-material-kit';
import Icon from 'react-native-vector-icons/EvilIcons';
import * as actions from '../actions';

const theme = getTheme();

const styles = StyleSheet.create({
  card: {
    marginTop: 20,
  },
  title: {
      top: 20,
      left: 80,
      fontSize: 24,
  },
  image: {
      height: 100,
  },
  action: {
      backgroundColor: 'black',
      color: 'white',
  },
  icon: {
      position: 'absolute',
      top: 15,
      left: 0,
      color: 'white',
      backgroundColor: 'rgba(255,255,255,0)',
  },
});

const ServiceItem = (props) => {
    return (

        <TouchableWithoutFeedback
        onPress={() => props.selectServices(props.services)}
    >
        <View style={[theme.cardStyle, styles.card]}>

            <Text >{props.services.ser} </Text>

        </View>
        </TouchableWithoutFeedback>
    );
};

const mapStateToProps = state => {
    return {
        selectServices: state.selectServices,
        services: state.services
     };
  };

export default connect(mapStateToProps, actions)(ServiceItem);

When the user taps on each listitem. I am calling the class ServiceDetail.js. Below is the code for serviceDetail.js class:
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
import React, { Component } from 'react';
import { Text, View, StyleSheet, Image, ScrollView, TouchableOpacity, Linking } from 'react-native';
import { connect } from 'react-redux';
import { getTheme } from 'react-native-material-kit';
import EvilIcon from 'react-native-vector-icons/EvilIcons';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import SimpleIcon from 'react-native-vector-icons/SimpleLineIcons';
import * as actions from '../actions';

const theme = getTheme();

const styles = StyleSheet.create({
  card: {
    marginTop: 10,
    paddingBottom: 20,
    marginBottom: 20,
    borderColor: 'lightgrey',
    borderWidth: 0.5,
  },
  title1: {
      top: 10,
      left: 80,
      fontSize: 24,
  },
  title2: {
      top: 35,
      left: 82,
      fontSize: 18,
  },
  image: {
      flex: 0,
      height: 100,
      width: 333,
      backgroundColor: 'transparent',
      justifyContent: 'center',
      alignItems: 'center',
  },
  closeIcon: {
      position: 'absolute',
      top: 5,
      left: 295,
      color: 'rgba(233,166,154,0.8)',
      backgroundColor: 'rgba(255,255,255,0)',
  },
  icon: {
      position: 'absolute',
      top: 15,
      left: 0,
      color: 'white',
      backgroundColor: 'rgba(255,255,255,0)',
  },
  textArea: {
      flexDirection: 'row',
      paddingLeft: 20,
      paddingTop: 10,
      width: 260,
  },
  textIcons: {
      color: '#26a69a',
  },
  actionArea: {
      paddingTop: 10,
      flexDirection: 'row',
      justifyContent: 'space-around',
      alignItems: 'center',
  },
});
class ServiceDetail extends Component {
    handleClick = (link) => {
        Linking.canOpenURL(link).then(suppported => {
            if (supported) {
                Linking.openURL(link);
            } else {
                console.log('Don\'t know how to open URI: ' + link);
            }
        });
    };
  render() {
    return (
      <ScrollView showsVerticalScrollIndicator={false}>
        <View style={[theme.cardStyle, styles.card]}>
        <Image
            source={require('../images/background.jpg')}
            style={[theme.cardImageStyle, styles.image]}
        />
        <EvilIcon name={'user'} size={100} style={styles.icon}/>
        <SimpleIcon name={'close'} size={30} style={styles.closeIcon}
            onPress={() => this.props.noneSelected()} />
        <Text style={[theme.cardTitleStyle, styles.title1]}>{this.props.services.ser}</Text>

        <Text style={[theme.cardTitleStyle, styles.title2]}>from {this.props.services.Location}</Text>
        <Text style={[theme.cardTitleStyle, styles.title2]}>from {this.props.services.SecondLoc}</Text>
        <View style={styles.textArea}>
           <MaterialIcon name={'phone'} size={40} style={styles.textIcons}/>
           <Text style={theme.cardContentStyle}>{this.props.services.Phone}</Text>
        </View>
        <View style={styles.textArea}>
           <MaterialIcon name={'email'} size={40} style={styles.textIcons}/>
           <Text style={theme.cardContentStyle}>{this.props.services.email}</Text>
        </View>

        <View style={styles.actionArea}>
            <Text>Call</Text>

            <Text>Email</Text>
        </View>
        </View>
      </ScrollView>
    );
  }
}

const mapStateToProps = state => {
  return {
      service: state.serviceSelected,
   };
};

export default connect(mapStateToProps, actions)(ServiceDetail);

My index.js class has the following code under actions folder:
export const selectServices = (serviceId) => {
    return {
        type: 'SELECTED_SERVICE',
        payload: serviceId,
    };
};

export const noneSelected = () => {
    return {
        type: 'NONE_SELECTED',
    };
};

My serviceReducer has the following code:
   import services from './services.json';

const initialState = {
    services,
    detailView: false,
    serviceSelected: null,
};

export default (state = initialState, action) => {
    switch (action.type) {
        case 'SELECTED_SERVICE':
            return {
                ...state,
                detailView: true,
                serviceSelected: action.payload
            }

        case 'NONE_SELECTED':
            return {
                ...state,
                detailView: false,
                serviceSelected: null,
            }

        default:
            return state;
    }
}

I am developing this application on windows machine on android emulator. I know I am missing something. I looked at each and every line, but could not figure out what am I doing wrong. I am new to react native and trying to follow the example to make this app. I tried to debug the application using chrome, but keep getting an error that could not connect to remote debugging.
any help will be highly appreciated.

A: I see you pass props and use it to your const ServiceItem. You need to use mapStateToProps also then pass to your connect at serviceItem.js.
const mapStateToProps = state => {
  return {
      selectServices: state.selectServices,
      services: state.services
   };
};

export default connect(mapStateToProps, actions)(ServiceItem);

Your ServiceDetail.js also should be:
const mapStateToProps = state => {
  return {
      services: state.services
   };
};

export default connect(mapStateToProps, actions)(ServiceDetail);

A: Your ServiceItem component is just a presentational component, in my opinion, it need not to be connected to redux store, instead, pass the data and event hook from parent to ServiceItem component  and that will work just fine. That will solve your props problem as well.
Point made by "DennisFrea" still holds good. i am just suggesting another of achieving the same thing.


text:
Q: Dapr not running in stand alone mode I am pulling my hair out trying to get a basic ASP.NET Core API working with Dapr locally.  I have followed the docs and still no luck.  I'm sure I'm just missing something basic, but I just can't work it out.
These are the steps I have done so far to try and get this working:

*

*Installed Dapr CLI (cli version 0.11.0)

*Executed dapr init --runtime-version 1.0.0-rc.3 (3 docker containers installed and running)

*Navigated to my dotnet project and executed the following command - dapr run --app-id microservicea --app-port 5000 --dapr-http-port 55000 --dapr-grpc-port 55001 -- dotnet run
After executing the dapr run command, the project builds and various Dapr logs appear, however, I also get the following message:
Could not update sidecar metadata for cliPID: PUT http://127.0.0.1:55000/v1.0/metadata/cliPID giving up after 5 attempts
This indicates to me that the sidecar is not running as a process, or just not accessible.
I have no idea what I'm doing wrong.
As a side note, I did notice that if I matched the dapr-http-port to the port in the launchsettings.json, I get the following message - You're up and running! Both Dapr and your app logs will appear here.  But it still doesn't work when I try to call the http://127.0.0.1:5000/v1.0/invoke/microservicea/method/GetSomeData endpoint.
Some help with this would be most appreciated.  If I can't get this basic example working, then I'm going to have to abandon Dapr and look for an alternative to stitch together my microservices.

A: So it turns out the problem was I had the wrong versions of the Dapr CLI and Runtime installed.  At the current time of writing, I made sure I had version 1.0.0-rc.3 of the CLI tool installed, and then installed version 1.0.0-rc.3 of the runtime (dapr init --runtime-version 1.0.0-rc.3).  Once they were installed, everything worked.

A: You are using the same port for dapr-http-port and dapr-grpc-port. there's bound to be a port collision there that might stop the sidecar from running.
Second, you are invoking on the wrong port. you should use http://127.0.0.1:55000/v1.0/invoke/microservicea/method/GetSomeData, or in this case the port you are using from launchsettings.json

redpajama_set_name: RedPajamaStackExchange


text:
Q: Embedding files in Keynote Is there any way to embed files in Keynote presentation? So, that others can click on it and download/open it in their machines.

A: Besides images or other media that can natively be placed into Keynote, for a document or binary file of arbitrary format, you would almost certainly have to post it elsewhere (Dropbox/Google/web page) and embed a URL to the sharing link in your presentation.
Unfortunately, it seems you can't make the URL have the format of file:// instead of http:// You can, however use ftp:// or sftp:// or smb:// !


text:
Q: Is it easier to take the domain from WIX and host the domain under AWS? Or is there another way to do this? Im trying to host a domain purchased through WIX on AWS. The site is ready to go and waiting in the bucket to be hosted under the domain my client bought through WIX. Just wondering if anyone knew how to take it from WIX and host it on AWS. Ive been looking and only found something that takes the CNAMEs made when you create a hosting zone on AWS and you can add them to google CNAMES (it was a tutorial for taking a google domain and routing to AWS) but since the CNAME section on WIX is greyed out I cant go that route.

A: You can get the NS records on Route 53, Go to Wix, Go to the CNAME Records, and have the CNAME point to the NS on Route 53.
Alternatively, you could transfer your domain to AWS, and in Route 53, create a new record set by pressing create record set, set type to NS, set the name to www.[yourdomain].com, and add the wix NS in Value.
The first approach with changing the CNAMES in wix should be easier.


text:
Q: How to nicely align my blocks? Thanks for the vibrant and fantastic community we have here.
I am working on a project in which I need to nicely align all my blocks one below another to not break my design.
I reached a point where I am a little bit stuck and do not really not to to figure this out.
Here is my code :
html

            Popular aisles

                            Browse perishables

                            Browse household

                            Browse pets

                            Browse baby & toddler

Vivamus massa felis, eleifend quis rhoncus id, finibus id velit.

Vivamus massa felis, eleifend quis rhoncus id, finibus id velit.

Vivamus massa felis, eleifend quis rhoncus id, finibus id velit.

and here is css :
.homepage-wrapper {
    max-width: 1043px;
    margin-left: auto;
    margin-right: auto;
}
.homepage-top-category-container-title {
    color: #808080;
    margin-top: 15px;
    padding: 15px 0 15px 0;
    font-weight: bold;
    letter-spacing: -1px;
}
#homepage-top-category-container-title {
    color: ##808080;
    margin-left: 15px;
}
.homepage-top-category-container-list {
    display: flex;
    flex-wrap: wrap;
    width: auto;
    height: auto;
}
.homepage-top-category-container-list > div {
    margin-left: 15px;
    margin-bottom: 15px;
}
.homepage-top-category-container-item {
    display: block;
    float: none;
    width: auto;
    height: auto;
    border: solid 1px #d0d0ce;
    position: relative;
    border-radius: 3px;
}
.homepage-top-category-container-item:hover {
    -webkit-box-shadow: 0px 5px 15px 0px rgba(162, 162, 162, 1);
    -moz-box-shadow: 0px 5px 15px 0px rgba(162, 162, 162, 1);
    box-shadow: 0px 5px 15px 0px rgba(162, 162, 162, 1);
}
#homepage-top-category-container-item-a {
    width: 240px;
    height: 360px;
}
#homepage-top-category-container-item-b {
    width: 240px;
    height: 360px;
}
#homepage-top-category-container-item-c {
    width: 240px;
    height: 360px;
}
#homepage-top-category-container-item-d {
    width: 240px;
    height: 360px;
}
.homepage-top-category-container-item-btn {
    background-color: #cde5d9;
    color: black;
    position: absolute;
    padding: 10px;
    left: 0;
    right: 0;
    bottom: 0;
    border-top: 1px solid #d0d0ce;
    border-bottom: 2px solid #d0d0ce;
}

.homepage-banner-grid{
    width: 100%;
    height: auto;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    }
.homepage-banner-hc-description-items{
    height: 150px;
    background-color: yellow;
    margin-left: 15px;
    }
/*
.homepage-banner-hc-description-items:first-child{
    margin-left:0px;
    }
.homepage-banner-hc-description-items:last-child{
    margin-right:0px;
    }
*/
#homepage-banner-hc-description-item1{
    background-color: pink;
    margin-bottom: 15px;
    margin-left: 15px;
    }
#homepage-banner-hc-description-item2{
    background-color: green;
    margin-bottom: 15px;
    }
#homepage-banner-hc-description-item3{
    background-color: orange;
    margin-bottom: 15px;
    }
.homepage-banner-hc-description-items-icon{
    display: block;
    float: left;
    background-color: red;
    width: auto;
    height: 100%;
    }
.homepage-banner-hc-description-items-text{
    display: flex;
    height: 140px;
    text-align: center;
    }
.homepage-banner-hc-description-items-text span {
    margin-top: auto;
    margin-bottom: auto;
    }

I would greatly appreciate help to align the 4 top-blocks with the 3 bottom-blocks. I would like the whole thing to be nicely aligned so it'll looks professional.
JSfiddle here -->   https://jsfiddle.net/hkz6g5sn/
Thanks.
****************EDIT****************************
it currently looks like this on my screen :

And I want to do this :

A:  Bit of a hack but this will do it, any reason your not using a library to handle the grids? you could solve this with media queries, but it'll take abit of code.
   .homepage-wrapper {
        max-width: 1043px;
        margin-left: auto;
        margin-right: auto;
    }
    .homepage-top-category-container-title {
        color: #808080;
        margin-top: 15px;
        padding: 15px 0 15px 0;
        font-weight: bold;
        letter-spacing: -1px;
    }
    #homepage-top-category-container-title {
        color: ##808080;
        margin-left: 15px;
    }
    .homepage-top-category-container-list {
        display: flex;
        flex-wrap: wrap;
        width: auto;
        height: auto;
    }
    .homepage-top-category-container-list > div {
        margin-left: 15px;
        margin-bottom: 15px;
    }
    .homepage-top-category-container-item {
        display: block;
        float: none;
        width: auto;
        height: auto;
        border: solid 1px #d0d0ce;
        position: relative;
        border-radius: 3px;
    }
    .homepage-top-category-container-item:hover {
        -webkit-box-shadow: 0px 5px 15px 0px rgba(162, 162, 162, 1);
        -moz-box-shadow: 0px 5px 15px 0px rgba(162, 162, 162, 1);
        box-shadow: 0px 5px 15px 0px rgba(162, 162, 162, 1);
    }
    #homepage-top-category-container-item-a {
        width: 240px;
        height: 360px;
    }
    #homepage-top-category-container-item-b {
        width: 240px;
        height: 360px;
    }
    #homepage-top-category-container-item-c {
        width: 240px;
        height: 360px;
    }
    #homepage-top-category-container-item-d {
        width: 240px;
        height: 360px;
    }
    .homepage-top-category-container-item-btn {
        background-color: #cde5d9;
        color: black;
        position: absolute;
        padding: 10px;
        left: 0;
        right: 0;
        bottom: 0;
        border-top: 1px solid #d0d0ce;
        border-bottom: 2px solid #d0d0ce;
    }

    .homepage-banner-grid{
        width: 100%;
        height: auto;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        justify-content: center;
        }

    .homepage-banner-hc-description-items{
        height: 150px;
        background-color: yellow;
        max-width: 328px; // here
        }

      .margin-left {
        margin-left: 15px; // here
      }
    /*
    .homepage-banner-hc-description-items:first-child{
        margin-left:0px;
        }
    .homepage-banner-hc-description-items:last-child{
        margin-right:0px;
        }
    */
    #homepage-banner-hc-description-item1{
        background-color: pink;
        margin-bottom: 15px;
        }
    #homepage-banner-hc-description-item2{
        background-color: green;
        margin-bottom: 15px;
        }
    #homepage-banner-hc-description-item3{
        background-color: orange;
        margin-bottom: 15px;
        }
    .homepage-banner-hc-description-items-icon{
        display: block;
        float: left;
        background-color: red;
        width: auto;
        height: 100%;
        }
    .homepage-banner-hc-description-items-text{
        display: flex;
        height: 140px;
        text-align: center;
        }
    .homepage-banner-hc-description-items-text span {
        margin-top: auto;
        margin-bottom: auto;

}
If you just add .margin-left to second and third item, leaving width at 100%


text:
Q: extract hidden email from webpage using requests and regular expression I want to find the email in this webpage:
https://reachuae.com/livesearch/brand-detail/3910/A-ALICO-LTD-Sharjah
I created this code but no email found:
import requests
import re

url = 'https://reachuae.com/livesearch/brand-detail/3910/A-ALICO-LTD-Sharjah'

headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}
r = requests.get(url, headers=headers)
print(r.status_code)
page_text = r.text
email = re.findall(r'\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b',page_text)
print(email)

return empty list

A: The email is not found in the URL which you have mentioned in the question, but when you click the "(Click here to send enquiry)" another URL is generating at the bottom of page. That URL is containing the mail id. Using the below python code you can extract that Mail id
import requests
from lxml import html

Mail_url = 'https://reachuae.com/livesearch/brand-detail/3910/A-ALICO-LTD-Sharjah'

def mailExtractor():
    mail = Mail_url.split('/')
    innumber = mail[-2]
    Actual_url = 'https://reachuae.com/includes/contact_company.php?id={}&KeepThis=true&'.format(innumber)
    getr = requests.get(Actual_url, headers={"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"})
    sour = html.fromstring(getr.content)
    emails = sour.xpath('//input[@name="mail"]//@value')
    for mail in emails:
        print(mail)

mailExtractor()


text:
Q: Getting a list of entities from a table leads to 500 error - Entity Framework I'm building an SPA on Angular2 (front-end) and back-end web API 2 with OWIN and Identity for authentication and Ninject as a container for DI.
I want to return a list of Managers as json response. And also its related ContactDetail data. They are related as one-to-one in my database. But I'm getting a 500 error as response. Why am I getting this error?

Manager class
   public partial class Manager
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ContactDetail ContactDetail { get; set; }
}

ContactDetail class
    public partial class ContactDetail
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string SecondName { get; set; }
    public string LastName { get; set; }

    public virtual Manager Manager { get; set; }
}

Context
 public partial class LightCRMEntities : DbContext
{
    public LightCRMEntities()
        : base("name=LightCRMEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<ContactDetail> ContactDetails { get; set; }
    public virtual DbSet<Manager> Managers { get; set; }
}

API controller
[Authorize(Roles = "Admin, Moderators")]

public class ManagerAPIController : ApiController
{
    private IManagerRepository _iManagerRepository;

    public ManagerAPIController(IManagerRepository iManagerRepository)
    {
        _iManagerRepository = iManagerRepository;
    }

    [HttpGet]
    [Route("api/AllManagers")]
    public IHttpActionResult GetAllManagers()
    {
        var managers = _iManagerRepository.Managers;
        return Json(managers);
    }
}

Repository:
 public class EFManagerRepository : IManagerRepository
{
    public IEnumerable<Manager> Managers
    {
        get
        {
            using (LightCRMEntities context = new LightCRMEntities())
            {
                return context.Managers.ToList();

            }
        }
    }

}

*

*ContactDetail   '((System.Data.Entity.DynamicProxies.Manager_63305B0F1D8DAA0805603D889C6E3A5114E3050AEE610FE775000D2270697C1F)(new System.Collections.Generic.Mscorlib_CollectionDebugView(managers).Items[0])).ContactDetail' threw an exception of type 'System.ObjectDisposedException'    LightCRM.ContactDetail {System.ObjectDisposedException}

Response:
I'm receiving 500 (Internal server error)

ExceptionMessage
  :
  "Error getting value from 'ContactDetail' on 'System.Data.Entity.DynamicProxies.Manager_63305B0F1D8DAA0805603D889C6E3A5114E3050AEE610FE775000D2270697C1F'."
  ExceptionType
  :
  "Newtonsoft.Json.JsonSerializationException"

Screenshot of a breakpoint:
Though the error does not appear on this point - I can see that one of the related entities ContactDetail - has some problem to be loaded

I hardly understand the meaning of: Configuration.ProxyCreationEnabled = false; but if I add it to the constructor of the Context:
 public partial class LightCRMEntities : DbContext
{
    public LightCRMEntities()
        : base("name=LightCRMEntities")
    {
        Configuration.ProxyCreationEnabled = false;
    }
 // other code
}

Then I get 200 ok and a json object in console:

but it dosn't load the related object - it has a NULL value - ContactDetail
:
null
SQL profiler screenshot for this request:

Screenshot of data in the database:

A: Thanks to @JWeezy, @DavidG and other guys from the comment section of the original post the solution was found:
Modifications needed:
disable lazy loading in the Context
Context
public partial class LightCRMEntities : DbContext
{
    public LightCRMEntities()
        : base("name=LightCRMEntities")
    {
        Configuration.LazyLoadingEnabled = false;
    }
// other code
}

Used eager loading in the repository
public class EFManagerRepository : IManagerRepository
{
    public IEnumerable<Manager> Managers
    {
        get
        {
            using (LightCRMEntities context = new LightCRMEntities())
            {
                return context.Managers.Include("ContactDetail").ToList();

            }
        }
    }
}

In the ContactDetail class added [JsonIgnore] attribute to the
    virtual property
public partial class ContactDetail
{
   //other properties
    [JsonIgnore]
    public virtual Manager Manager { get; set; }
}


text:
Q: What is ParallelStream Queue Behavior? I'm using parallelStream to do some file uploads in parallel, some are large files some are small.  I've noticed that not all workers are being used.
Everything runs fine at first, all threads being used (I set the parallelism option to 16).  Then at a certain point (once it gets to larger files), it only uses one thread
simplified code:
files.parallelStream().forEach((file) -> {
    try (FileInputStream fileInputStream = new FileInputStream(file)) {
                IDocumentStorageAdaptor uploader = null;

                try {
                    logger.debug("Adaptors before taking: " + uploaderPool.size());
                    uploader = uploaderPool.take();
                    logger.debug("Took an adaptor!");
                    logger.debug("Adaptors after taking: " + uploaderPool.size());
                    uploader.addNewFile(file);
                } finally {
                    if (uploader != null) {
                        logger.debug("Adding one back!");
                        uploaderPool.put(uploader);
                        logger.debug("Adaptors after putting: " + uploaderPool.size());
                    }
                }
            } catch (InterruptedException | IOException e) {
                throw new UploadException(e);
            }
});

uploaderPool is a ArrayBlockingQueue.
logs:
[ForkJoinPool.commonPool-worker-8] - Adaptors before taking: 0
[ForkJoinPool.commonPool-worker-15] - Adding one back!
[ForkJoinPool.commonPool-worker-8] - Took an adaptor!
[ForkJoinPool.commonPool-worker-15] - Adaptors after putting: 0
...
...
...
[ForkJoinPool.commonPool-worker-10] - Adding one back!
[ForkJoinPool.commonPool-worker-10] - Adaptors after putting: 16
[ForkJoinPool.commonPool-worker-10] - Adaptors before taking: 16
[ForkJoinPool.commonPool-worker-10] - Took an adaptor!
[ForkJoinPool.commonPool-worker-10] - Adaptors after taking: 15
[ForkJoinPool.commonPool-worker-10] - Adding one back!
[ForkJoinPool.commonPool-worker-10] - Adaptors after putting: 16
[ForkJoinPool.commonPool-worker-10] - Adaptors before taking: 16
[ForkJoinPool.commonPool-worker-10] - Took an adaptor!
[ForkJoinPool.commonPool-worker-10] - Adaptors after taking: 15

It seems like all work (items in the list) is distributed among the 16 threads, and things delegated to one thread will just wait until the thread is free to work rather than using an available thread.  Is there a way to change how parallelStream does its work queueing?  I read forkjoinpool docs and it mentions work-stealing, but only for spawned subtasks.
My other plan was to perhaps randomize the sorting of the list I'm using parallelStream on and maybe that would balance out things.
Thanks!

A: The split-vs-compute heuristics for parallel streams are tuned for data-parallel operations, not for IO-parallel operations.  (In other words, they are tuned to keep the CPUs busy, but not to generate way more tasks than you have CPUs.)  As a result, they are biased towards computation over forking.  There are currently no options for overriding these choices.


text:
Q: Callback on Durandal Modal I have a custom Durandal viewmodel which has the method:
customModalNewMetric.show(someid);

In my CustomModalNewMetric viewmodel, the method looks like this:
CustomModalNewMetric.show = function(someid) {
        return dialog.show(new CustomModalNewMetric(someid));
};

How can I execute some function after the dialog.show function is complete? I want to execute some jQuery after the dialog is shown.

A: Durandal's dialog.show() returns a promise, so all you need to do is the following:
CustomModalNewMetric.show = function(someid) {
    return dialog.show(new CustomModalNewMetric(someid)).then(function(data) {
    //callback function here (called after dialog is closed)
    //also will return any passed data
    });
}

NOTE: When using durandal, make sure you have:

*

*defined all your modules using requirejs

*check for any errors within your console.

EDIT (12/24/2013):
I came across this example, with the source code that illustrates the answer I provided.
Let me know if you have any other questions!

A: To perform subsequent commands after the dialog has opened, it looks as though what you need to do is to add your own dialog context with a compositionComplete method (DialogContext.compositionComplete).
You can add a new context with the dialog.addContext method.
Here I am crudely decorating the default context and adding it as 'myContext' (there are likely to be more elegant ways of doing this):
dialog.addContext('myContext', {

  // Retain the behaviour of the original default context
  parentContext: dialog.getContext(),

  // Nothing but a passthrough to the parent context
  addHost: function(theDialog) {
    this.parentContext.addHost(theDialog);
  },
  removeHost: function(theDialog) {
    this.parentContext.removeHost(theDialog);
  },
  attached: function(view) {
    this.parentContext.attached(view);
  },

  // Here we do something different
  compositionComplete: function(child, parent, context) {
    this.compositionComplete(child, parent, context);
    // Do something now that the modal is open
    console.log('Modal opened');
  }
});

Then when you open the dialog you'll need to pass the context name:
dialog.show(new CustomModalNewMetric(someid), null, 'myContext');


text:
Q: When button clicked get a URL from an API and redirect I am trying to create an HTML button that when clicked:

*

*Selects a random URL from an API

*Redirects to that selected URL

I have tried using an Array but as the list expands it no longer is efficient.
The code I have been using is a simple one:
<script type="text/javascript">
    var urls = [
"/product/245170",
'/product/245166',
'/product/245189',
'/product/245108',
'/product/245041',
'/product/245098',
    ];

    function discoverItems() {
        var url = urls[Math.floor(Math.random()*urls.length)];
        window.location = url; // redirect
    }
</script>

I want it now to search from xyp.com/api/products and ask it to select a random url from there.
Help please!


text:
Q: Make server.R insert HTML code into webpage I want to provide the UI a machine-readable version of my output.  How can I make server.R insert HTML code such as the following into the webpage UI.R dynamically generates?

     Name
     Favorite Color

     Jill
     pink

     Jenny
     purple

A: Ok, this is embarrassing...... Shiny already does what I was asking about...... I was just looking at the HTML code generated when the page loads, but there is more HTML code inserted into the existing HTML later. So there is no problem after all :)


text:
Q: How many multisets can be made using the numbers $1$ through $n$, where each is used at most $3$ times? Note that $n$ is a positive integer.
So we're counting multisets, except with the restriction that no multiset can have more than $3$ copies of the same elements.
The answer is $4^n$, because for each element from $1$ to $n$ you have $4$ choices: don't put that number in the multiset, put it in once, put it in twice, or put it in thrice. There is probably a much better way to explain this, if you care to then please do.
But I'm wondering whether there's a more intuitive way of thinking about this. I feel that my stumbling upon the answer $4^n$ was very much a matter of luck. Maybe it's just me that finds it unintuitive.
One of my favorite things about combinatorics is how there are so many different angles you can approach a single problem at.
TLDR Have you a more intuitive way of thinking of the problem?

A: I would do it exactly the way you suggest.  It seems very intuitive to me, since we all know that there are $2^n$ subsets of a set with $n$ elements, by analogous reasoning.  Here's another way of looking at it, though.  If the elements are $x_1,\dots x_n$ represent the multiset with $k_i$ copies of $x_i$ by the expression $x_1^{k_1}x_2^{k_2}\cdots x_n^{k_n}$.  Then the number of of multisets is the number of terms in the expansion of $$(1+x_1+x_1^2+x_1^3)(1+x_2+x_2^2+x_2^3)\cdots(1+x_n+x_n^2+x_n^3)$$  and there are clearly $4^n$ of these.

A: You can identify every multiset with a number with $n$ digits in base $4$.
You can identify every multiset with an ordered pair of usual sets, call them high and low. If you picked $k$ in the high, that counts for twice, and if you picked it in the low, for once: example for $n=4$: $(\{1,2\},\{2,4\})\mapsto\{1,1,2,2,2,4\}$.
If some other comes to my mind, I'll write it.


text:
Q: Set common legend for multiple categoric plots ggplot 2 I'm creating five plots within a for loop that are stacked columns. There are 10 numbers that are factors on a scale from 0 to 9. Not every plot has each of these factors, but I'd like to have common colors. e.g. all 1's are blue, all 9s are green.
I.e. if I have this list of colors, how do I apply it to the plots.
colLegend <- list('0' = '#A9CCE3',  # light blue
                  '1' = '#A3E4D7',  # light green
                  '2' = '#27AE60',   # DARK GREEN
                  '3' = '#F7DC6F',    # YELLOW
                  '4' = '#F8C471',   # ORANGE
                  '5' = '#D35400',    # RED
                  '6' = '#117864',  # DARK TEAL
                  '7' = '#AF7AC5',   # PURPLE
                  '8' = '#2E4053',    # NAVY
                  '9' = '#616A6B')    # GREY

Current code
## plot stacked percentage of each value

labels <- c('19', '20', '22')

# create tally of each Ellenberg value

j = 1
for (df in ellenCatTab){
  dfName <- names(ellenCatTab)[j]
  j = j + 1

  df = df[,5:31]
  tidy <- df %>%
    gather(key='Quadrat', value='Ellenberg')
  tidy <- na.omit(tidy)
  tally <- tidy %>%
    count(Quadrat, Ellenberg)
  tally$Ellenberg <- as.factor(tally$Ellenberg)
  tally <- as.data.table(tally)
  tally[, c('Q', 'Year') := tstrsplit(tally$Quadrat, "_", fixed=TRUE)][]
  tally$Q <- sub('X', 'Q', tally$Q)

  stacked <- ggplot(tally, aes(fill=Ellenberg, y=n, x=Quadrat)) +
    geom_bar(position='stack', stat='identity') +
    ggtitle(dfName) +
    labs(x='Year', y='Number of Plants') +
    scale_x_discrete(labels=labels) +
    theme_classic() +
    facet_wrap(~ Q, nrow=1, scales='free_x')
  plot(stacked)

  ggsave(plot=stacked,
         file=paste0(dfName, '_stacked.png'),
         limitsize=FALSE,
         width=250, height=200, units='mm')

}

A: Adding this worked:
scale_fill_manual(values = colLegend)


text:
Q: ajax call in a controller : $http is not defined I need a ajax call inside the function but if i use $http i am getting $http is not defined pls suggest me my code is

A: Correctly Passing Params
You should pass parameters to a http request like this
$http.get('http://MyServerIP:ServerPort/APICall', { params: { user_id: $scope._id } })

Also you should make calles like this in a service or a factory to be reused if needed
Add Your Correct Services
you also forgot to add $http in your function, next to $scope
ContactController($scope, $http)

A: You need to inject the $http service to your controller like this :


text:
Q: CFData vs CFString I have a CFMutableDictionaryRef, part of which in debugger is:

"device-id" = <72270000>;

model = <474d4120 39353000>;

"vendor-id" = <86800000>;

Now I can get value of the key model using CFDataRef which returns string like "GMA 950", as compared to the value above.
But I cannot get value of "vendor-id"using same method so I try with CFString, which returns <86800000> instead of a string. So how to retreive correct value of the vendor id (which I already know should return 0x8086 for Intel) ??

A: found it:
have to format the string retreived with CFString as:
NSString *id = [NSString stringWithFormat:@"0x%X",*((UInt32*)CFDataGetBytePtr(cfstr))];


text:
Q: Remove or disable button from layout related with an intent I have an intent:
    Intent myIntent = new Intent(this, MyActivity.class);

There is a layout (with a button) related with MyActivity.
How can I remove or disable the button in myIntent?
TIA

A: I mostly do it like that
Intent intent = new Intent(this, MyActivity.class);
Bundle msges = new Bundle();
msges.putString("disableTheBtn", "yes");
intent.putExtras(msges);
startActivity(intent);

And inside MyActivity class
   public void onCreate(Bundle savedInstanceState) {
        ---------Do some thing , Button and GUI initialization-------
        try{
            String  disableTheBtn = getIntent().getExtras().getString("disableTheBtn"));
           if (disableTheBtn != null && !disableTheBtn.isEmpty(){
              yourBtn.setVisibilty(View.GONE);//hide that button
           }
       }catch(Exception e){
           e.printStack();
       }
   }


text:
Q: Is $\int x\,dx \cdot x=\int x^2 \,dx$ or $\int x\,dx \cdot x=(\int x \, dx)\cdot x$? Is $\int x\,dx \cdot x=\int x^2 \,dx$ or $\int x\, dx \cdot x=(\int x \,dx)\cdot x$?
Edit: My integrals looks like this:
\begin{align}
& \int_0^t e^{-\xi(t-t^\prime)} \, d t^\prime \int_0^t e^{-\xi(t-t^{\prime \prime})} \frac{2 C}{m^2} \delta(t^{\prime}-t^{\prime \prime}) \, dt^{\prime \prime} \\[6pt]
= {} &\int_0^t e^{-\xi(t-t^\prime)} \, d t^\prime\left(e^{-\xi(t-t^\prime)} \frac{2 C}{m^{2}} \Theta(\mathrm{t}-\mathrm{t}^\prime)\right)
\end{align}
And I am not sure if the term in the parenthesis on the last line should be included in the integral.

A: I think it depends always on the context. The $dx$ part does not need to be at the end of the integral, for example, in quantum mechanics you see a lot of integrals written like:
$$\langle \psi| \hat V |\psi \rangle = \frac{1}{2} m \omega^2 |B|^2 \int_{-\infty}^{+\infty}dx x^4 e^{-2 \alpha x^2}$$
and in this case, the integrand is $x^4 e^{-2 \alpha x^2}$. I think that they do this in integrals with large integrands so it's more visible and to make stand out what variable you are integrating over. So if $\int x dx x$ is $\int x^2 dx$ or  $x\cdot \int x dx$ always depends on the context of what you are doing and of what you are working with.


text:
Q: Maze Solving in Python I have tried tirelessly to make a maze solver in python. I have used all my resources such as friends, the internet, and stack. I have adapted my code a lot from stack questions previous to mine, but still can not come to an answer EVEN WHEN COMPLETELY COPYING CODE (which I don't like doing).
The maze/input file (nested list):
    [['*', '*', '*', '*', '*'],
    ['*', ' ', '*', ' ', '*'],
    ['*', ' ', ' ', ' ', '*'],
    ['*', ' ', '*', ' ', 'E'],
    ['*', 'S', '*', '*', '*']]

This function keeps looping over the same points in the maze. My start point "S" is (4,1), with the output:
(4,1)
(4,0)
(3,1)

The above output is from the print statement I used to debug the function. It just prints the above in that order until it hits the recursive limit.Below is my solve function:
already_visited=[]
def solve(x,y):
    global already_visited
    matrix = draw(load())
    print (x,y)

    #base cases
    if matrix[x][y] == "E":
        for row in matrix:
            row = str(row)[1:-1]
            print row
        return True
    if matrix[x][y] == "*":
        return False
    if matrix[x][y] == "x":
        return False

    matrix[x][y] = "x"

    #---------------------
    if (x,y) in already_visited: #check if we have already been here
        return False

    already_visited.append((x,y)) #add position to list
    #---------------------

    # recursive cases (matrix traversal)
    if (x < len(matrix)-1 and solve1(x+1,y)):
        return True
    elif (y > 0 and solve1(x,y-1)):
        return True
    elif (x > 0 and solve1(x-1,y)):
        return True
    elif (y < len(matrix)-1 and solve1(x,y+1)):
        return True
    else:
        return False

All I am entering into the function for x and y are starting indices, S, as seen in the maze posted above. Any help is extremely appreciated!

A: Making the maze is easy.  You make a grid first.
import networkx as nx
import numpy as np

G = nx.Graph()
for i in range(5):
    for j in range(5):
        G.add_node((i,j))
        if i >0:
            G.add_edge((i-1,j),(i,j))
        if j>0:
            G.add_edge((i,j),(i,j-1))

Then you delete the walls leaving the path nodes.
a = np.array([['*', '*', '*', '*', '*'],
       ['*', ' ', '*', ' ', '*'],
       ['*', ' ', ' ', ' ', '*'],
       ['*', ' ', '*', ' ', 'E'],
       ['*', 'S', '*', '*', '*']])

for i in range(5):
    for j in range(5):
        if a[i][j]=='*':
            G.remove_node((i,j))

I'm cheating and putting in the start and end positions.  But then I have NetworkX find the path from start to end.
for point in nx.algorithms.astar_path(G,(4,1),(3,4)):
    print(point)

A: This code here won't work:
if (x < len(matrix)-1 and solve1(x+1,y)):
        return True
    elif (y > 0 and solve1(x,y-1)):
        return True
    elif (x > 0 and solve1(x-1,y)):
        return True
    elif (y < len(matrix)-1 and solve1(x,y+1)):
        return True
    else:
        return False

The Problem lies in the recursion. What your Program does is:

*

*If possible go right

*If not try up

*If not try left

*If not try down

Since you do it recursively, your program will go right till it hits a wall,
then go up till it hits a wall,
then left,
then down.
This makes it very easy to run in circles.
So you have two easy possibilities as far as I can see:

*

*Remember if you have visited a location and always return False in the recursion IF you already have been here

*Run randomly

Number 1 would look like this:
already_visited=[]
def solve1(x,y):
    global already_visited
    matrix = draw(load())
    print (x,y)

    #base cases
    if matrix[x][y] == "E":
        for row in matrix:
            row = str(row)[1:-1]
            print row
        return True
    if matrix[x][y] == "*":
        return False
    if matrix[x][y] == "x":
        return False

    matrix[x][y] = "x"

    #---------------------
    if (x,y) in already_visited: #check if we have already been here
        return False

    already_visited.append((x,y)) #add position to list
    #---------------------

    # recursive cases (matrix traversal)
    if (x < len(matrix)-1 and solve1(x+1,y)):
        return True
    elif (y > 0 and solve1(x,y-1)):
        return True
    elif (x > 0 and solve1(x-1,y)):
        return True
    elif (y < len(matrix)-1 and solve1(x,y+1)):
        return True
    else:
        return False

A: Replacing the start of your function with the correct constraint check makes it work without running into the IndexError. First you need to assure that x is in range of your matrix row count. Then you need to check the same for the column count. Here the value given by len() is the first out of range.
Additionally your reloading the matrix in every call of the solver. You should only operate on one matrix to have persistent changes. For that add it as an argument to the function:
def solve2(matrix,x,y):
    print (x,y)
    if x >= len(matrix) or y >= len(matrix[x]):
        return False
    [...]

Then call it like solve2(draw(load()),4,1) on the first run and replace every recursing call with equivalents of solve2(matrix,x,y-1)). The same works for solve1() as well.


text:
Q: Java Apache POI FINE_DOTS cannot be resolved or is not a field I am trying to reproduce some example code to produce shaded .xmlx cells using this example: http://thinktibits.blogspot.com/2012/12/excel-cell-fill-color-java-poi-example.html
Eclipse is giving me the error "FINE_DOTS cannot be resolved or is not a field".
I don't understand why it doesn't like this as I'm finding quite a few examples involving "XSSFCellStyle.FINE_DOTS".
    import java.io.*;
    import java.sql.*;
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.*;

    import org.apache.poi.hssf.usermodel.*;
    import org.apache.poi.ss.usermodel.*;
    import org.apache.poi.xssf.usermodel.*;
    import org.apache.poi.xssf.usermodel.XSSFCellStyle;

    public class WriteXLSX {

        public WriteXLSX() throws FileNotFoundException, IOException, ParseException {
            /* Create Workbook and Worksheet XLSX Format */
            XSSFWorkbook my_workbook = new XSSFWorkbook();
            XSSFSheet my_sheet = my_workbook.createSheet("Cell Font");
            /* Get access to XSSFCellStyle */
            XSSFCellStyle my_style = my_workbook.createCellStyle();

            /* We will now specify a background cell color */
             my_style.setFillPattern(XSSFCellStyle.FINE_DOTS );
             my_style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
             my_style.setFillBackgroundColor(IndexedColors.RED.getIndex());

            /* Create a row in the sheet */
            Row row = my_sheet.createRow(0);
            /* Create a cell */
            Cell cell = row.createCell(0);
            cell.setCellValue("Cell Fill Color Test");
            /* Attach the style to the cell */
            cell.setCellStyle(my_style);
            /* Write changes to the workbook */
            FileOutputStream out = new FileOutputStream(new File("cell_fill_color.xlsx"));
            my_workbook.write(out);
            out.close();

        }

    }

A: Use FillPatternType.
Try with this:
my_style.setFillPattern(FillPatternType.FINE_DOTS );


text:
Q: How to make the equilibrium double arrow longer? \documentclass{article}

\usepackage{mhchem}

\begin{document}

\ce{H^+ (\textit{aq}) + HCO3^- <=> H2CO3 (\textit{aq}) <=> H2O (\textit{l}) + CO2 (\textit{g})}

\ce{2H2(\textit{g}) + O2(\textit{g}) <=> 2H2O(\textit{l})}

\end{document}

I am new to Latex and doing some chemistry reports and while MS equation editor is a pain, it decently works even by using mixed fractions to get ion charges with subscripts for atoms, but I digress.   I cannot do the double harpoon-like symbol for chemical equilibrium "longer" as I like the arrows to be stretched out more than it is.  Is this even possible?

A: Your original version didn't work for me, hence \expandafter's:
\documentclass{article}

\usepackage{mhchem}

\begin{document}

%\ce{H^+ (\textit{aq}) + HCO3^- <=> H2CO3 (\textit{aq}) <=> H2O (\textit{l}) + CO2 (\textit{g})}

\ce{2H2( \expandafter\textit{g}) + O2( \expandafter\textit{g}) <=> 2H2O( \expandafter\textit{l})}

\ce{2H2( \expandafter\textit{ g}) + O2( \expandafter\textit{g}) <=>[\hspace{1cm}][] 2H2O( \expandafter\textit{l})}

\end{document}

A: First of all, please use mhchem with the version option. You should always read the warnings you get.
Second, why do you try to get the state in italic text? IUPAC recommendation is just normal roman (= upright) text.
You can make the arrows longer by writing some 'space' above them, e.g. \hspace{10ex}.
Are you looking for an option to make all arrows longer by the same value? That is not yet an option available for users, but I could put it on my todo list.
\documentclass{article}
\usepackage[version=3]{mhchem}
\begin{document}
\ce{H^+(aq) + HCO3^- <=>[\hspace{10ex}] H2CO3(aq) <=> H2O(l) + CO2(g)}

\ce{2H2(g) + O2(g) <=> 2H2O(l)}
\end{document}

A: Is this what you require?

Then use the following:
\documentclass[12pt]{article}
\begin{document}
\begin{eqnarray*}
H^+ (aq) + HCO3^- &\Longleftrightarrow& H2CO3 (aq) \Longleftrightarrow     H2O (l) + CO2 (g)\\
2H2(g) + O2(g) &\Longleftrightarrow& 2H2O(l)
\end{eqnarray*}
\end{document}


text:
Q: How can I type hint a variable whose Union type gets narrowed in Python? I have a few helper functions that get passed a type converter and a value. Based on checks that happen later, I decide which helper function to call.
How can I correctly annotate the types to narrow the foo variable's type below so that it can pass a mypy check?
from typing import Type, Union

def do_something(
        typ: Type[Union[float, int]],
        bar: Union[float, int]
) -> Union[float, int]:
    return bar

foo: Type[Union[float, int, str]] = float

assert foo is float or foo is int

do_something(foo, 4.4)

Bonus points if the solution can ensure that typ is a converter to the type of bar!

A: The tool you want here is a TypeVar.
Essentially, a TypeVar let's you say "I don't know quite what type this is (although I may have some ideas), but it'll be the same one throughout its use in this function." (or in some cases throughout its use in a class)
For example, this ensures that each thing you had a Union for gets the same value on any given call to the function.
from typing import Type, TypeVar

# Define a type variable
# and list the things it is allowed to represent
NumberType = TypeVar("NumberType", int, float)

def do_something(
        typ: Type[NumberType],
        bar: NumberType
) -> NumberType:
    return bar

This can be legally called with do_something(float, 2.5) in which case it will return a float, or it can be called with do_something(int, 2) in which case it will return an int. That is, it makes sure that all the things match.
Because you called it a type converter, I suspect that you may not actually want all the types to match. If you need to constrain on more than one Type Variable, you can do so with something more like
from typing import Callable, TypeVar

# Define a type variable
# and list the things it is allowed to represent
NumberTypeIn = TypeVar("NumberTypeIn", int, float)
NumberTypeOut = TypeVar("NumberTypeOut", int, float)

def do_something(
        converter: Callable[[NumberTypeIn], NumberTypeOut],
        bar: NumberTypeIn
) -> NumberTypeOut:
    return type_(bar)

As to the original question of narrowing unions of Type[]s, as you've noticed is doesn't work. Instead you can use issubclass, as in
assert not issubclass(foo, str)

or
assert issubclass(foo, int) or issubclass(foo, float)


text:
Q: Why does shared_ptr::use_count() return a long instead of an unsigned type? shared_ptr observers 20.8.2.2.5 C++14 Final Draft (n4296)

   long use_count() const noexcept;

Returns: the number of shared_ptr objects, *this included, that share ownership with *this, or 0 when *this is empty.
[Note: use_count() is not necessarily efficient. — end note]

A: According to this page
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1450.html

The return type of use_count is signed to avoid pitfalls such as
  p.use_count() > -1 evaluating to false.

with a reference to

John Lakos, Large-Scale C++ Software Design, section 9.2.2, page 637, Addison-Wesley, July 1996, ISBN 0-201-63362-0.

Basically, it looks like a nanny-grade decision, tailored for freshman year software developers.

A: The reason is that the most appropriate type for a counter of this kind is a regular signed integer, even if this counter is never going to get below 0.
Why a counter should be unsigned? The fact that it cannot become negative is not a valid excuse at all given current real meaning of unsigned for the language.
unsigned for C++ doesn't mean an "integer number that cannot be negative". To understand why this definition simply doesn't make sense consider that

*

*The difference of two unsigned is unsigned

*The addition of an unsigned with a signed is unsigned

*An unsigned value is never bigger than -1

None of the above makes any sense if you consider unsigned to mean "non-negative".
Using unsigned for size_t was a mistake (see for example Why is size_t unsigned?), only partially* excusable because in the 16-bit era one extra bit was considered worth the wrong semantics that unsigned types have in C++ for this kind of use.
Unfortunately now the size_t mistake cannot be fixed (because of backward compatibility) but why repeating the same mistake in another unrelated area?
Please note that probably the big mistake made was just the choice of the name unsigned (given its real meaning). If that type would have been named (more appropriately) modulo then probably it would be more evident why using a modulo int for the size of a string doesn't make any sense at all.
The name is irrelevant, what it counts is the semantic and unsigned simply has the wrong semantic for a counter or a size.
(*) I personally don't think it was a good enough reason even back then. If 32767 is not enough for a size now, then 65535 won't be enough really soon. Just a single bit (twice the value) was not, in my opinion, an acceptable price for such a bending of the semantic.
EDIT
I've published a video in which I'm discussing in more details why I think that using and unsigned type for size_t was a design mistake in C++.
Slides can be downloaded from http://raksy.dyndns.org/unsigned.pdf


text:
Q: yii relational complex active record task I'm trying to get used to relational active record but things look too complicated for now.
If it's not difficult please point me in right direction.
I have 4 tables.
Users
userID[pk],userName

Cars
car_id[pk],userID[fk to Users],car_nickname,make_id[fk to Makes],model_id[fk to Models]

Makes
make_id[pk],make_name

Models
model_id[pk],model_name,make_id[fk to Makes]

Now input data is userName,make_name,model_name and task is to get car_nickname from Cars table.
Is this possible using relations or should I do it step by step checking makes,models,users for IDs and then puting all IDs into Cars to get car_nickname ?

A: You can yous only one Model with reliations to all tables. And create one _form.php in the Views, where there will only fields you need.
Some halpfull information. if you save some data into some table and you need saved data id, you caN use $newid = $model->getPrimaryKey(); and assign to new variable , wich will save into other tables.
I think this is short way to solve problem


text:
Q: Count upward in python with variable base I would like to know how to do an equivalent of the range function in python, but with the ability to specify the base number. For example:
countUp(start=0, end=1010, base=2)
countUp(start=0, end=101, base=3)
countUp(start=0, end=22, base=4)

Example output for base 2 counting:
[0, 1, 10, 11, 100, ...]

Is there a function I'm missing that does this? Or what could I do instead?

A: You are apparently confusing numbers with the representation of numbers.
A number does not have a base... it's the number representation that has a base... for example the number represented as "101" in base 2 is the same as the number represented with "5" in base 10.
The range function will count successive numbers, and you can get their representation in any base you like with something like:
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def int2str(x, base):
    if x < 0:
        return "-" + int2str(-x, base)
    return ("" if x < base else int2str(x//base, base)) + digits[x % base]

A: You can not crate integers with special based, but you can create your expected numbers in a specified base in string :
def my_range(start,end,base,step=1):

    def Convert(n,base):
       string = "0123456789ABCDEF"
       if n < base:
          return string[n]
       else:
          return Convert(n//base,base) + string[n%base]
    return (Convert(i,base) for i in range(start,end,step))

Demo:
print list(my_range(4,20,2))
['100', '101', '110', '111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111', '10000', '10001', '10010', '10011']

Note that the passed string string = "0123456789ABCDEF" to function will works till base 16, if want to calculate greater based you can use more letters.

A: You can do it with a custom iterator:
I took the iterater code from here and the base conversion from here
import string
class BaseRange:
    def __init__(self, low, high, base):
        digs = string.digits + string.letters
        self.current = low
        self.high = high
        self.base = base
    def __iter__(self):
        return self
    def next(self):  # Python 3 requires this to be __next__
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.int2base(self.current - 1, self.base)
    def int2base(self, x, base):
        if x < 0: sign = -1
        elif x == 0: return digs[0]
        else: sign = 1
        x *= sign
        digits = []
        while x:
            digits.append(digs[x % base])
            x /= base
        if sign < 0:
            digits.append('-')
            digits.reverse()
        return ''.join(digits)

A Few Example runs produces:
>>> for c in BaseRange(0, 10, 2):
    print(c)

0
1
01
11
001
101
011
111
0001
1001
0101
>>> for c in BaseRange(0, 10, 3):
    print(c)

0
1
2
01
11
21
02
12
22
001
101

A: You could do this with the itertools product function.
from itertools import product

def countUp(start, end, base):
    n_digits = len(end)
    combs = product(*[range(base)] * n_digits)
    while (n := next(combs)) <= end:
        yield n

list(countUp(start=0, end=(2, 0), base=3))
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0)]


text:
Q: Conditions for a diagonal induced metric? Let $M$ be a manifold of dimension $n$ with a (say Lorentzian) metric $g$, that is diagonal in some choice of local coordinates.
Let $S$ be manifold of dimension $k<n$ , embedded in $M$ by some injection $f: S
\rightarrow M$, some collection of local coordinates $C$ that cover it.
What are sufficient conditions on $f$ and $S$ and $C$, such that  the metric on $S$ induced by the pullback of $f$, $f^* g$, is diagonal everywhere with atlas $C$?
Some motivation:
Some canonical examples of embedding manifolds and computing induced metrics are embedding the sphere and the torus in $\mathbb{R}^3$. For both of these examples the induced metric happen to be diagonal. But then one is led to ask - do all surfaces embedded in $\mathbb{R}^3$ have diagonal induced metrics in their usual coordinates? If the answer is no, what's a sufficient condition?


text:
Q: Is there any way to pass checkbox data without using a submit button? I am currently on a Dropbox-like MVC4 project and coding the delete action for files and folders. The thing I am wondering is, can I use my Delete ActionLink (which redirects me to the Delete action), as a submit button? Can I pass the checked checkboxes data through Html.ActionLinks to Controllers?
I have a View like this:
   [@Html.ActionLink("Download", "Download", "File")]
   [@Html.ActionLink("Share", "Share", "File")]
   [@Html.ActionLink("Move", "Move", "File")]
   [@Html.ActionLink("Rename", "Rename", "File")]
   [@Html.ActionLink("Delete","Delete","File")]
   [@Html.ActionLink("Copy", "Copy", "File")]

         @foreach (UserLoginApp.Models.FolderModel dir in Model.FolderList)
            {

                    <input type="checkbox" name="SelectedFolders" value="@dir.Name" />

         @dir.Name

            }

        @foreach (UserLoginApp.Models.FileModel file in Model.FileList)
            {

                    <input type="checkbox" name="SelectedFiles" value="@file.Name" />
                    @if (file.Name.EndsWith(".jpg") || file.Name.EndsWith(".jpeg") || file.Name.EndsWith(".png"))
                        {

                        }
                        else
                        {

                        }
                        @file.Name

            }

A: If you are going to use JS, you can post selected check box ids as list to controller. Here is a simple example,
You have to add a class name for all check box (class="selected-folder"), and a "data-" attribute with value of folder id (data-folderid="@dir.Id").
Like this,

     @foreach (UserLoginApp.Models.FolderModel dir in Model.FolderList)
        {

                <input class="selected-folder" data-folderid="@dir.Id" type="checkbox" name="SelectedFolders" value="@dir.Name" />

               @dir.Name

        }

Now you can get selected check box and folder ids like below,
function deleteFolders()  // call this method as "OnClick" function of "Delete" button
{
   // Create a folder id list
   var folderIds = new Array();

   // Get all selected check box to create a list
   $('.selected-folder:checked').each(function () {
       // Get current selected check box
       var selectedfolder = $(this);

       // Add selected folder ids to list
       folderIds.push(selectedfolder.attr('data-folderid'));
    }
}

and you can POST list of selected folder ids using AJAX POST,
function deleteFolders()
{
   // Create a folder id list
   var folderIds = new Array();

   // Get all selected check box to create a list
   $('.selected-folder:checked').each(function () {
       // Get current selected check box
       var selectedfolder = $(this);

       // Add selected folder ids to list
       folderIds.push(selectedfolder.attr('data-folderid'));
    }

  // Post folder ids to controller
  $.ajax({
     type: "POST",
     url: 'link to controller method',
     cache: false,
     dataType: "json",
     data: folderIds, // Passing list of ids to controller as parameter
     contentType: 'application/json; charset=utf-8',
     success: function (result) {
         // do your success actions
     },
     error: function (error, type, message) {
         // do your failure actions
     },
     async: true,
     processData: false
  });
}

The controller method will accept the list of ids as like this,
public ActionResult DeleteFolders(List<int> folderIds)
{
    // delete selected folders
}

Hope this will help you.


text:
Q: Describe a situation where a training point can be removed without affecting the resulting 1-NN classification for any test point in the input space I have the following question in my textbook:
One of the drawbacks of the nearest-neighbour algorithm is that
we must retain all of the training data. Describe a situation
where a training point can be removed without affecting the
resulting 1-NN classification for any test point in the input space.
One such situation would be if there is only 1 class? Then all of the future test points would be classified as that class.
I can't imagine another situation since from my understanding, for the 1-NN to work, there needs to be at least some datapoints which it would "compare similarity" (measure the distance) with and decide whether it would be some class.
What would other situations look like that aren't what I thought of?

A: If a training point is "surrounded" by other training points of the same class, removing the central point will not change the 1-NN classification anywhere. Imagine a ring of training points with one point inside the ring, and that all of these points are of the same class. Removing the point inside the ring won't change any classifications, since anything that used that point as its nearest neighbor has a second nearest neighbor of the same class. You could also imagine a large, dense cloud of points all sharing the same class - the many points on the interior of the cloud are redundant, and you don't need them all to define the exact same 1-NN class boundaries.
You can evaluate a data point for removal by identifying the neighborhood in which that point is the nearest neighbor. If every possible point in that neighborhood has a second nearest neighbor of the same class, the point can be removed without affecting 1-NN classification. To put it another way, if a point's "nearest neighborhood" is completely overlapped by "second-nearest neighborhoods" of the same class, removing the point will not affect 1-NN classification.


text:
Q: Prestashop PayPal Error I'm trying to add PayPal payments in a Prestashop (v1.7.3) store using the PayPal & Braintree Official Module (v3.11.6), but until now without success.
Installed and configured the module without any problems, but every time i proceed with a payment this error is displayed to the user:

Tested the module in both sandbox and production environments, and the error still persists.
What can be the problem?
UPDATE: After some debugging i found the origin of the problem. The problem is that the module is unable to connect to PayPal's API via cURL with SSL/TLS.
I'm using Prestashop in Windows Server with IIS, and in this environment cURL has to be informed where the certificate authority is located in order to establish a secure connection.
I downloaded the cacert.pem file from curl website, stored it in my server and then, in module files (PPHtmlConfig.php) i added the CA location in the cURL options settings manually:
CURLOPT_CAINFO => 'C:\\(...)\\cacert.pem',

Now i'm able to connect to PayPal's API and successfully make a payment!
I've contacted the module's tech support team and they are analysing this issue.

A: After several contacts with the module tech support, this is their final response to the issue:

We do not know the specialty of your server. This is not a recurring
  error in our module. It happens if the CURL can not find the CA
  certificate. In general, we advise you to ask your server to verify
  that the CA certificate is correctly configured. Otherwise, it is
  necessary to specify the route or curl to find the certificate, for
  example, as you did in your module.
At the moment there is no way to specify this in our module in
  general. So, you should wait for the next update of our Paypal module.

So, if someone comes across the same issue when using a Windows Server environment, specify the complete CA path in the module files (as explained in the question update):

I downloaded the cacert.pem file from curl website, stored it in my
  server and then, in module files (PPHtmlConfig.php) i added the CA
  location in the cURL options settings manually:

CURLOPT_CAINFO => 'C:\\(...)\\cacert.pem',


text:
Q: slot machince not looping numbers I am trying to make a slot machine program that will have the user enter a amount of money and then display 3 words from 5 randomly generated numbers. If 3 of the words match they win 3 times the amount of money entered, if 2 words words match they win 2 times the amount and if 0 match they win nothing. When I run the program and hit yes to play again it just gives me the same match every-time. I am not sure why it is doing this.
here is what I have so far
Console.Write("\n\n");
Console.Write("------------------------------------------------");
Console.WriteLine("\nThis Program simulates a slot machince");
Console.Write("------------------------------------------------");
Console.Write("\n\n");
string answer;
int moneyWon = 0;

Random random = new Random();
int randomWord1 = random.Next(0, 5);
int randomWord2 = random.Next(0, 5);
int randomWord3 = random.Next(0, 5);

do
{
    Console.WriteLine("Enter the amount to depost into the slot machince: ");
    int moneyDeposit = int.Parse(Console.ReadLine());

    if (randomWord1 == 0 && randomWord2 == 0 && randomWord3 == 0)
    {
        Console.WriteLine("Cherries, Cherries, Cherries");
        Console.WriteLine("3 words match. you won 3x");

        moneyWon += moneyDeposit * 3;

    }
    else if (randomWord1 == 1 && randomWord2 == 1 && randomWord3 == 1)
    {
        Console.WriteLine("Oranges, Oranges, Oranges");
        Console.WriteLine("3 words match. you won 3x");

        moneyWon += moneyDeposit * 3;

    }
    else if (randomWord1 == 2 && randomWord2 == 2 && randomWord3 == 2)
    {
        Console.WriteLine("Plums, Plums, Plums");
        Console.WriteLine("3 words match. you won 3x");

        moneyWon += moneyDeposit * 3;

    }
    else if (randomWord1 == 3 && randomWord2 == 3 && randomWord3 == 3)
    {
        Console.WriteLine("Bells, Bells, Bells");
        Console.WriteLine("3 words match. you won 3x");

        moneyWon += moneyDeposit * 3;

    }
    else if (randomWord1 == 4 && randomWord2 == 4 && randomWord3 == 4)
    {
        Console.WriteLine("Melons, Melons, Melons");
        Console.WriteLine("3 words match. you won 3x");

        moneyWon += moneyDeposit * 3;

    }
    else if (randomWord1 == 5 && randomWord2 == 5 && randomWord3 == 5)
    {
        Console.WriteLine("Bars, Bars, Bars");
        Console.WriteLine("3 words match. you won 3x");

        moneyWon += moneyDeposit * 3;

    }
    else if (randomWord1 == 0 && randomWord2 == 1 && randomWord3 == 1)
    {
        Console.WriteLine("Cherries, Oranges, Oranges");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;

    }
    else if (randomWord1 == 1 && randomWord2 == 1 && randomWord3 == 0)
    {
        Console.WriteLine("Oranges, Oranges, Cherries");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 1 && randomWord2 == 0 && randomWord3 == 1)
    {
        Console.WriteLine("Oranges, Cherries, Oranges");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 0 && randomWord2 == 2 && randomWord3 == 2)
    {
        Console.WriteLine("Cherries, Plums, Plums");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 2 && randomWord2 == 2 && randomWord3 == 0)
    {
        Console.WriteLine("Plums, Plums, Cherries");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 2 && randomWord2 == 0 && randomWord3 == 2)
    {
        Console.WriteLine("Plums, Cherries, Plums");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }

    else if (randomWord1 == 3 && randomWord2 == 3 && randomWord3 == 0)
    {
        Console.WriteLine("Bells, Bells, Cherries");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 0 && randomWord2 == 3 && randomWord3 == 3)
    {
        Console.WriteLine("Cherries, Bells, Bells");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 3 && randomWord2 == 0 && randomWord3 == 3)
    {
        Console.WriteLine("Bells, Cherries, Bells");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 3 && randomWord2 == 3 && randomWord3 == 0)
    {
        Console.WriteLine("Bells, Bells, Cherries");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 0 && randomWord2 == 4 && randomWord3 == 4)
    {
        Console.WriteLine("Cherries, Melons, Melons");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 4 && randomWord2 == 4 && randomWord3 == 0)
    {
        Console.WriteLine("Melons, Melons, Cherries");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 4 && randomWord2 == 0 && randomWord3 == 4)
    {
        Console.WriteLine("Melons, Cherries, Melons");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 0 && randomWord2 == 5 && randomWord3 == 5)
    {
        Console.WriteLine("Cherries, Bars, Bars");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 5 && randomWord2 == 5 && randomWord3 == 0)
    {
        Console.WriteLine("Bars, Bars, Cherries");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 5 && randomWord2 == 0 && randomWord3 == 5)
    {
        Console.WriteLine("Bars, Cherries, BarsS");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 1 && randomWord2 == 0 && randomWord3 == 1)
    {
        Console.WriteLine("Oranges, Cherries, Oranges");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 1 && randomWord2 == 1 && randomWord3 == 0)
    {
        Console.WriteLine("Oranges, Oranges, Cherries");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 0 && randomWord2 == 1 && randomWord3 == 1)
    {
        Console.WriteLine("Cherries, Oranges, Cherries");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 1 && randomWord2 == 1 && randomWord3 == 2)
    {
        Console.WriteLine("Oranges, Oranges, Plums");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 1 && randomWord2 == 2 && randomWord3 == 1)
    {
        Console.WriteLine("Oranges, Plums, Oranges");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 2 && randomWord2 == 1 && randomWord3 == 1)
    {
        Console.WriteLine("Plums, Oranges, Oranges");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 1 && randomWord2 == 2 && randomWord3 == 1)
    {
        Console.WriteLine("Oranges, Plums, Oranges");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 1 && randomWord2 == 1 && randomWord3 == 3)
    {
        Console.WriteLine("Oranges, Oranges, Bells");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 1 && randomWord2 == 3 && randomWord3 == 1)
    {
        Console.WriteLine("Oranges, Bells, Oranges");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 3 && randomWord2 == 1 && randomWord3 == 1)
    {
        Console.WriteLine("Bells, Oranges, Oranges");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 1 && randomWord2 == 1 && randomWord3 == 4)
    {
        Console.WriteLine("Oranges, Oranges, Melons");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 1 && randomWord2 == 4 && randomWord3 == 1)
    {
        Console.WriteLine("Oranges, Melons, Oranges");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 4 && randomWord2 == 1 && randomWord3 == 1)
    {
        Console.WriteLine("Melons, Oranges, Oranges");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 1 && randomWord2 == 1 && randomWord3 == 5)
    {
        Console.WriteLine("Oranges, Oranges, Bars");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 1 && randomWord2 == 5 && randomWord3 == 1)
    {
        Console.WriteLine("Oranges, Bells, Oranges");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 5 && randomWord2 == 1 && randomWord3 == 1)
    {
        Console.WriteLine("Bells, Oranges, Oranges");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 2 && randomWord2 == 2 && randomWord3 == 1)
    {
        Console.WriteLine("Plums, Plums, Oranges");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 1 && randomWord2 == 2 && randomWord3 == 2)
    {
        Console.WriteLine("Plums, Plums, Oranges");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 2 && randomWord2 == 1 && randomWord3 == 2)
    {
        Console.WriteLine("Plums, Oranges, Plums");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 2 && randomWord2 == 2 && randomWord3 == 3)
    {
        Console.WriteLine("Plums, Plums, Bells");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 2 && randomWord2 == 3 && randomWord3 == 2)
    {
        Console.WriteLine("Plums, Bells, Plums");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 3 && randomWord2 == 2 && randomWord3 == 2)
    {
        Console.WriteLine("Bells, Plums, Plums");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 2 && randomWord2 == 4 && randomWord3 == 2)
    {
        Console.WriteLine("Plums, Melons, Plums");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 4 && randomWord2 == 2 && randomWord3 == 2)
    {
        Console.WriteLine("Melons, Plums, Plums");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 2 && randomWord2 == 2 && randomWord3 == 4)
    {
        Console.WriteLine("Plums, Plums, Melons");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 5 && randomWord2 == 2 && randomWord3 == 2)
    {
        Console.WriteLine("Bars, Plums, Plums");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 2 && randomWord2 == 2 && randomWord3 == 5)
    {
        Console.WriteLine("Plums, Plums, Bars");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 2 && randomWord2 == 5 && randomWord3 == 2)
    {
        Console.WriteLine("Plums, Bars, Plums");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 3 && randomWord2 == 3 && randomWord3 == 0)
    {
        Console.WriteLine("Bells, Bells, Cherries");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 3 && randomWord2 == 0 && randomWord3 == 3)
    {
        Console.WriteLine("Bells, Cherries, Bells");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 0 && randomWord2 == 3 && randomWord3 == 3)
    {
        Console.WriteLine("Cherries, Bells, Bells");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 1 && randomWord2 == 3 && randomWord3 == 3)
    {
        Console.WriteLine("Oranges, Bells, Bells");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 3 && randomWord2 == 3 && randomWord3 == 1)
    {
        Console.WriteLine("Bells, Bells, Oranges");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 3 && randomWord2 == 1 && randomWord3 == 3)
    {
        Console.WriteLine("Bells, Oranges, Bells");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 1 && randomWord2 == 3 && randomWord3 == 3)
    {
        Console.WriteLine("Cherries, Bells, Bells");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 2 && randomWord2 == 3 && randomWord3 == 3)
    {
        Console.WriteLine("Plums, Bells, Bells");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 3 && randomWord2 == 3 && randomWord3 == 2)
    {
        Console.WriteLine("Bells, Bells, Plums");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
    else if (randomWord1 == 3 && randomWord2 == 2 && randomWord3 == 3)
    {
        Console.WriteLine("Bells, Plums, Bells");
        Console.WriteLine("2 words match, you won 2x");

        moneyWon += moneyDeposit * 2;
    }
      //continue if statements
    else
    {
        Console.WriteLine("No words match.You won 0");
    }

    // Display total deposit, amount won and net gain/losss to the user
    double netGain = moneyWon;
    Console.WriteLine($"Total amount depostited:{moneyDeposit} ");
    Console.WriteLine($"Total amount won:{moneyWon} ");
    Console.WriteLine($"Net gain/loss total:{netGain} ");

    //Ask the user if they want to play again
    Console.WriteLine("Do you want to play again yes/no: ");
    answer = Console.ReadLine();
    if(answer != "Yes" || answer != "yes" || answer != "No" || answer != "no")
    {
        Console.WriteLine("Invalid input try again");
    }

} while (answer == "Yes" || answer == "yes");

A: You are using the same unknown values for each iteration of the loop.
You need to generate the random numbers within the loop:
Random random = new Random();
do
{
   int randomWord1 = random.Next(0, 5);
   int randomWord2 = random.Next(0, 5);
   int randomWord3 = random.Next(0, 5);
   //...


text:
Q: instance based regex in python I was wondering if there is already available a library which does something similar to scrapely
https://github.com/scrapy/scrapely
WHat it does is that you give an example url and then you give the data you want to extract from that html..
url1 = 'http://pypi.python.org/pypi/w3lib/1.1'
data = {'name': 'w3lib 1.1', 'author': 'Scrapy project', 'description': 'Library of web-related functions'}

and then you initiate this rule by simply:
s.train(url1, data)

Now, I can extract the same data from different url...
But is there any library which does the same but for raw text...
For example:
raw_text = "|foo|bar,name = how cool"

And then I want to extract "bar" from this.
I know, I can write a simple regex rules and get done with this.. but is there any library available which solves this as an instance based learning problem..
i.e rather than specifying a regex rule and then passing data over it..
instead I specify an instance and what I would like to extract and it automatically builds rule ?
Hope that I am making some sense.

A: If you like scrapely, you can use it. First, convert the text to something that resembles html, for example by replacing all relevant markers in the text with <br>.  Then do what is done in the Scrapely train method, except fetching the html from a remote location.
If that works well, the scrapely guys will probably like your pull request on Github.

A: Trying to fly under the radar with this answer because you already deleted the post that the actual question was for: creating a nested dictionary/json in python
Well, I solved it to work on my Python and this is what I came up with.
import re
from itertools import chain

d = {'foo': ['a', 'b'], 'foo::bar':['c'], 'foo::bar::baz':['z'], 'foo::baz':['f'], 'bar' :['d'],
'bar::baz': ['d', 'a'], 'boom':[], 'boom::bam::boombam' : ['foo']}

dic = {}
hiers = {}
for k,v in d.items():
    if '::' not in k:
        if not v:
            dic[k] = {'inner_tag':{}}
        else:
            dic[k] = {'sources':v, 'inner_tag':{}}
    if '::' in k:
        hiers[k] =v

it = iter(hiers)
i = next(it)

def reg(i):
    return[m.start() for m in re.finditer('::',i)]

for k,v in dic.items():
    while True:
        try:
            nxt = next(it)
            it = chain([nxt], it)
            curr_len = len(reg(i))
            nxt_len = len(reg(nxt))
        except StopIteration:
            v['inner_tag'][i] = {'sources':hiers[i]}
            break
        if curr_len <= nxt_len and i[:2] == nxt[:2]:
            v['inner_tag'][i] = {'sources':hiers[i], 'inner_tag':{}}
            last = i
            i = next(it)
        elif i[:2] != nxt[:2]:
            v['inner_tag'][i] = {'sources':hiers[i]}
            last = i
            i = next(it)
            break
        else:
            v['inner_tag'][last]['inner_tag'][i] = hiers[i]
            last = i
            i = next(it)
            continue

print(dic)


text:
Q: Computation of the solution of a particular differential equation Let $g(x)=\frac {dx}{dt}$, we want to solve
$$
\frac {\partial n(x,t)}{\partial t}+
\frac {\partial (n(x,t)g(x))}{\partial x}=-\mu(x)n(x,t).
$$
where we can assume all the regularity properties on the functions $g$ and  $\mu$, we search for $n(x,t)>0$ and $x \in \mathbb R$, $t \in (0,\infty)$.
Is it true that
$$
\frac {\partial n(x,t)}{\partial t}+
\frac {\partial n(x,t)}{\partial x}g(x)=-\mu(x)n(x,t)- \frac {\partial g(x)}{\partial x}n(x,t)
$$
hence by the definition of $g$ we have that
$$
\frac {dn(x,t)}{dt} =-\mu(x)n(x,t)- \frac {\partial g(x)}{\partial x}n(x,t)
$$
Hence,  if $n_0(x)= n(0,x)$,
$n(x,t)=n_0(x) \exp(-t (\mu(x)+\frac {\partial g(x)}{\partial x}))$
?
If not why is it not correct?

A: I think you mean that $g$ is given, and you are trying to
analyze the PDE by looking at the behavior of $n$ along
a curve $x(t)$ that satisfies $x'(t) = g(x(t))$.
With that understanding, your last equation ought to be written
$$
 \frac{d}{dt}(n(x(t),t)) = -(\mu(x(t))+g'(x(t)))n(x(t),t).
$$
But the solutions of the ODE $y'(t) = b(t)y(t)$ are of the
form
$$
        y(t) = y(0)\exp(\int_0^t b(s)ds).
$$
So if you can find $x(t)$ and do the integral, the result will
give $n$ along the curve.


text:
Q: How to fix "Unidentified Network" with iSCSI NICs? I have a 2008 R2 server which has NICs on the production LAN and NICs connected to a dedicated iSCSI LAN.
Whilst everything seems to work just fine, the iSCSI NICs show as "Unidentified Network" when I look at the NICs in Control Panel.
Is there a way I can change this?  They aren't unidentified, I know exactly what they are, but there doesn't appear to be a simple way to change this, not that I can see anyway.
Thanks in advance.

A: This link applies to the VirtualBox network adapter, but I think it is related. http://www.brokenwire.net/bw/Various/120/fix-virtualbox-causes-unidentified-network-on-vista-and-windows-7
You need to tell Windows that the iSCSI NIC device is really an endpoint and not a connection to another network. See http://msdn.microsoft.com/en-us/library/ff557037.aspx for more details. The reg key you need to add is *NdisDeviceType. Make sure you check the driver description so you change it on the correct interface!


text:
Q: Why I'm getting segmentation violation error in Go I'm trying to import 2 png image and paste one on top of the other. The output will be jpeg.
When ever I run the code below, I got this error:
image: unknown format
image: unknown format
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x109d7a4]
goroutine 1 [running]:
main.main()

Error is coming whenever I use "Bounds()" method. What do you think is the cause.
code:
func main() {
    imgFile1, err := os.Open("./pics/00/body.png")
    if err != nil {
        fmt.Println(err)
    }
    defer imgFile1.Close()
    imgFile2, err := os.Open("./pics/01/face.png")
    if err != nil {
        fmt.Println(err)
    }
    defer imgFile2.Close()
    img1, _, err := image.Decode(imgFile1)
    if err != nil {
        fmt.Println(err)
    }
    img2, _, err := image.Decode(imgFile2)
    if err != nil {
        fmt.Println(err)
    }
    //new rectangle for the second image
    sp1 := image.Point{0,0}
    sp2 := image.Point{img1.Bounds().Dx(),img1.Bounds().Dy()}
    r2 := image.Rectangle{sp1, sp2}

    //create new image
    rgba := image.NewRGBA(r2)

    //draw the two images into this new image
    draw.Draw(rgba, r2, img1, image.Point{0, 0}, draw.Src)
    draw.Draw(rgba, r2, img2, image.Point{0, 0}, draw.Src)

    //export it
    out, err := os.Create("./output.jpg")
    if err != nil {
        fmt.Println(err)
    }
    defer out.Close()

    var opt jpeg.Options
    opt.Quality = 80

    jpeg.Encode(out, rgba, &opt)
}

A: I'm not sure why Go has two ways to decode like this. If you know the file type, I think it's better to just use the specific package:
package main

import (
   "fmt"
   "image/png"
   "net/http"
)

const ava = "http://gravatar.com/avatar/5ec9c21c8d54825b04def7a41998d18d"

func main() {
   r, err := http.Get(ava)
   if err != nil {
      panic(err)
   }
   defer r.Body.Close()
   i, err := png.Decode(r.Body)
   if err != nil {
      panic(err)
   }
   dx := i.Bounds().Dx()
   fmt.Println(dx)
}

If you insist on using the other method, you will need to add an import (thanks to mkopriva):
import (
   "image"
   _ "image/png"
)

https://godocs.io/image/png#Decode


text:
Q: Retrieving Constants\string values from a separate JS File I am developing an Angular JS application.
I would like to know what is the best practice to include string values in our code.
I am planning to use another JS File which contains all the constant values. I will call this JS file in each and every JS(Controller) to refer the string values.

A: You can define constants in angular like
angular.module('moduleName',[]).constant('constName',string|object|array);

You can inject in directive or controller or wherever you want.
angular.module('moduleName',[]).directive('directiveName', ['constName', function(constName){...});

A: You have several options.
Global value. You can use your constants in form of the javascript object which would be globally accessible across the application. For example, your file could look something like this:
config = {
    host: 'domain',
    port: '1234'
};

Obvious disadvantage is that those values are not really a constants and can be easily changed, so it's error prone.
Angular config module. More reliable and cleaner option is to create a separate module to be used as a dependency for main app module. You would still have separate file for your constants but instead of some global variable this file would hold angular module with constant service. Something like this:
angular.module('app.config', []).constant('config', {
    host: 'domain',
    port: '1234'
});

Then in main application you would configure app like
angular.module('app', ['app.config']).config(function(config) {
    // console.log(config);
});

A: Angular has a built in way of providing constants, e.g:
angular.module('foo', ['ngRoute']) // Your angularjs module

// Decide a name for the bucket of constants, then just declare the
// constants in turn as an object literal:
.constant("HTTP_CONSTANTS", {
    "URL": "http://localhost",
    "PORT": "80"
})

Then you can load it anywhere where you have access too you foo module using dependency injection, i.e.:
angular.module('foo')

.controller('bar', function (HTTP_CONSTANTS) {
    ... // Use HTTP_CONSTANTS.URL or HTTP_CONSTANTS.PORT, for example
})

Here's a good primer on using constants:
http://twofuckingdevelopers.com/2014/06/angularjs-best-practices-001-constants/

A: Here is the sample code;
var app = angular.module('plunker', []);

app.constant('configs', {host:'localhost',port:8080});
app.controller('MainCtrl', function($scope, configs) {
  $scope.name = configs.host;
});

here is demo plunker

A: You can use factory for this purpose and inject this factory where ever you want these constants.
 var app=angular.module('Myapp', []);

    app.factory('ConstantService', function(){
      var constant={temp:'c'};
      var getConstants=function(){
       return constant;
          };
     return{
        constants:getConstants;
      }
    });

    app.controller('MyController',['ConstantService' function (ConstantService){
    var constant= ConstantService.constants;
    }]);


text:
Q: How can I create a dictionary between two columns within a pandas dataframe if each column has more than one value per row? I have a pandas dataframe with columns formatted similarly below:
test_df = pd.DataFrame(
{'A': ['apples|oranges|bananas', 'apples|oranges', 'apples|kiwi'],
 'B': ['store1|store2|store3', 'store1|store2', 'store1|store4']})

A                         B
apples|oranges|bananas    store1|store2|store3
apples|oranges            store1|store2
apples|kiwi               store1|store4

The index of each columns separated by "|" is in order. There is no key for which fruit goes with which store other than the current ordering of items per each row in the dataframe. I would like to create a new column with a dictionary for each row that has the desired output:
A                         B                     C
apples|oranges|bananas    store1|store2|store3  {store1:apples, store2:oranges, store3:bananas}
apples|oranges            store1|store2         {store1:apples, store2:oranges}
apples|kiwi               store1|store4         {store1:apples, store4:kiwi}

First I tried to convert columns A and B to lists and convert them to a dictionary.
test_df.A = test_df.A.str.split('|').tolist()
test_df.B = test_df.B.str.split('|').tolist()

I have tried a few different methods of converting the lists to a dictionary:
test_df['C'] = dict(zip(test_df.A,test_df.B))

Does not work and results in a 'TypeError: 'dict' object is not callable' error.
test_df.groupby('A')['B'].apply(list).to_dict()

Does not work and results in an 'unhashable type: 'list' error, which I assume is because there are multiple values for the dictionary key in 'B'.
Anything I can do to work through this?

A: If you truly need to maintain that organization you can get by with a (slow)  apply where you first split the strings, zip the resulting lists, and make the dict:
test_df['C'] = test_df.apply(lambda r: dict(zip(r.B.split('|'), r.A.split('|'))), axis=1)

                        A                     B                                                               C
0  apples|oranges|bananas  store1|store2|store3  {'store1': 'apples', 'store2': 'oranges', 'store3': 'bananas'}
1          apples|oranges         store1|store2                       {'store1': 'apples', 'store2': 'oranges'}
2             apples|kiwi         store1|store4                          {'store1': 'apples', 'store4': 'kiwi'}

Because dictionaries must have unique keys, if stores in B are ever duplicated on the same line, change dict to tuple that way you can store everything.

However, you can get a similar organization using explode. As this results in a flat way to store all of your data, future manipulations will be much easier and more performant. Because we explode the columns, the index is duplicated and allows you to know which row it came from.
test_df =  pd.concat([test_df[col].str.split('|').explode() for col in test_df.columns], 1)

         A       B
0   apples  store1
0  oranges  store2
0  bananas  store3
1   apples  store1
1  oranges  store2
2   apples  store1
2     kiwi  store4


text:
Q: How to open and minimize running programs in Electron JS? I have a project that simply needs to select two different running programs and handle their windows, opening one in full screen, then minimizing it and doing the same for the second one, in an infinite loop, similarly of what ALT + TAB does, but in an automatic way, so i can monitor these two choosen windows' content without having to alt+tab them. I'm trying to do this on Win10.
I took i look at Electrons shell in both  shell.showItemInFolder and shell.openPath, passing the directories of the two programs i wanted to show and minimize and i wrapped them in a setInterval loop to manage the show/minimize but it didn't help since it only opens the file explorer, not an actual running program.


text:
Q: Go to definition in new tab without changing the view When I do command + click on visual studio or right click and "go to definition", the file containing the definition opens in a new tab and I automatically see this file. So I change the view if the file containing the definition is another file.
Is it possible when I do this command to stay on the same file I was while still opening the other file in another tab?
Thank you for you answer.

A: If you're capable to actually go to the definition you are looking for what is called the "Peek Definition".  VS Code is highly customizable so how you have it configured it could do something different.
What I think you're looking for is Ctrl + Left Mouse Click or Alt + F12.
This should tell you more, VS Code Peek Definition

A: Preferences >> Settings >> Workbench >> Editor >> Enable Preview >> Uncheck/false

A: Double clicking on the tab name also works if you don't want to disable preview feature of editor. Double clicked tab becomes persistent.

A: You can also peek definition with Alt + F12 (be sure to highlight its symbol / invocation first).
This opens the definition in a smaller resizable tab (resizable down to ~4 lines of code) and allows editing if needed.
Example (source):

A: Taken from:
https://code.visualstudio.com/docs/editor/editingevolved#_go-to-definition

If a language supports it, you can go to the definition of a symbol by pressing F12.
If you press Ctrl and hover over a symbol, a preview of the declaration will appear.
Tip: You can jump to the definition with Ctrl+Click or open the definition to the side >with Ctrl+Alt+Click.