text:
Q: Do multi level grouping and summing using Java Stream API I have a class
public class Person {

    private String name;
    private String country;
    private String city;
    private String pet;
    private int totalCountryToCityCount;
    private int petCount;

    public Person(String name, String country, String city, String pet, int total, int petCount) {
        this.name = name;
        this.country = country;
        this.city = city;
        this.pet = pet;
        this.totalCountryToCityCount = total;
        this.petCount = petCount;
    }

    public String getName() {
        return name;
    }

    public String getCountry() {
        return country;
    }

    public String getCity() {
        return city;
    }

    public String getPet() {
        return pet;
    }

    public int getPetCount() {
        return petCount;
    }

    public int getTotalCountryToCityCount() {
        return totalCountryToCityCount;

    }

}

and Given a list of Person class, I have do aggregations based upon the different properties of the class.
For eg -
Person person1 = new Person("John", "USA", "NYC", "Max", 1, 2);
        Person person2 = new Person("Steve", "UK", "London", "Lucy", 2, 8);
        Person person3 = new Person("Anna", "USA", "NYC", "Max", 4, 32);
        Person person4 = new Person("Mike", "USA", "Chicago", "Duke", 5, 1);
        Person person5 = new Person("Test", "INDIA", "HYD", "Tommy", 4, 32);
        Person person6 = new Person("Test1", "INDIA", "HYD", "Tommy", 4, 65);
        Person person7 = new Person("Tim", "USA", "Chicago", "Duke", 5, 111);
        Person person8 = new Person("Tim", "USA", "Chicago", "Puke", 5, 111);
        Person person9 = new Person("Test1", "INDIA", "DELHI", "Tommy", 4, 65);
List<Person> persons = Arrays
            .asList(person1, person2, person3, person4, person5, person6, person7, person8,
                person9);

Now I need to get a result such that I should get the total "totalCountryToCityCount" based upon the combinations of country and city and I should get total "petCount" based upon combinations of country,city and pet. I am able to get them separately using groupingBy and summingint
private Map<String, Map<String, Integer>> getTotalCountForCountry(List<Person> persons) {
        return persons.stream().collect(groupingBy(Person::getCountry, getCityCount()));
    }

    public Collector<Person, ?, Map<String, Integer>> getCityCount() {
        return groupingBy(Person::getCity, summingInt(Person::getTotal));
    }

    public Map<String, Map<String, Map<String, Integer>>> threeLevelGrouping(List<Person> persons) {
       return  persons
            .stream().collect(
                groupingBy(Person::getCountry, groupByCityAndPetName()
                )
            );
    }

    private Collector<Person, ?, Map<String, Map<String, Integer>>> groupByCityAndPetName() {
        return groupingBy(Person::getCity, groupByPetName());
    }

    private Collector<Person, ?, Map<String, Integer>> groupByPetName() {
        return groupingBy(Person::getPet, summingInt(Person::getPetCount));
    }

which gives the result
{USA={Chicago={Puke=111, Duke=112}, NYC={Max=34}}, UK={London={Lucy=8}}, INDIA={DELHI={Tommy=65}, HYD={Tommy=97}}}
{USA={Chicago=15, NYC=5}, UK={London=2}, INDIA={DELHI=4, HYD=8}}

but the actual result which I want is :-
{USA={Chicago={15,{Puke=111, Duke=112}}, NYC={5,{Max=34} }, UK={London={2, {Lucy=8}}, INDIA={DELHI={4, {Tommy=65}}, , HYD={8,{Tommy=97}}}}

is there a way to achieve the same using Java stream API
I also tried using the code -
 personList.stream().collect(groupingBy(person -> person.getCountry(), collectingAndThen(reducing(
            (a, b) -> new Person(a.getName(), a.getCountry(), a.getCity(), a.getPet(),
                a.getTotal() + b.getTotal(), a.getPetCount() + b.getPetCount())),
            Optional::get)))
            .forEach((country, person) -> System.out.println(country + person));

But was getting the result -
USAPerson{name='John', country='USA', city='NYC'}
UKPerson{name='Steve', country='UK', city='London'}
INDIAPerson{name='Test', country='INDIA', city='HYD'}

with the counts surprisingly removed

A: What you are looking for really is Collectors::teeing, but only available in java-12:
System.out.println(
        persons.stream()
               .collect(Collectors.groupingBy(
                   Person::getCountry,
                   Collectors.groupingBy(
                       Person::getCity,
                       Collectors.teeing(
                           Collectors.summingInt(Person::getTotalCountryToCityCount),
                           Collectors.groupingBy(
                               Person::getPet,
                               Collectors.summingInt(Person::getPetCount)
                           ),
                           SimpleEntry::new
                       )
                   ))));

A back-port for java-8 it is available here.


text:
Q: Can't compile android GoogleAdMobAdsSdk 6.3.1 or 6.4.1 When I update admob sdk to 6.4.1 and try run project I get this error:
[2013-05-15 16:52:32 - Dex Loader] Unable to execute dex: Java heap space
[2013-05-15 16:52:32 - BannerSample] Conversion to Dalvik format failed: Unable to execute dex: Java heap space

I try with my app and with empty admob BannerSample and getting same error.
I update latest android sdk and tools.
I've tried and I've changed eclipse.ini to
-startup
 plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
 --launcher.library

 plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.100.v20110502
 -showsplash

 org.eclipse.platform
 --launcher.XXMaxPermSize
 512m
 --launcher.defaultAction
 openFile
 -vmargs
 -Xms1024m
 -Xmx1024m

But nothing helps, the last version that works is 6.2.1
I have windows 7 64bit 8GB RAM and Eclipse 3.7.2.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Value of uri cannot be cast from double to string im working with Yelp Api and i tried to search for Restaurants but im having a problem with the Restaurant image
im getting the name and rating with no problem but for the image its showing for the first time but when i reload my app it give this error : Value of uri cannot be cast from double to string
here's the code :
const RestaurantItems=(props)=>{
    return(

        <ScrollView>
    <View style={props.theme=='light'?styles.container:styles.darkContainer}>

        {props.restaurantsData.map((item,index)=>(

            <View style={{marginTop:20}} key={index}>
                 <View style={styles.Img}>
              <Image source={{uri:item.image_url}}style={{width:'100%',height:180}} />

        </View>
        <View style={{paddingLeft:10,marginTop:15,flexDirection:"row",justifyContent:'space-between',alignItems:"center"}}>
            <View>
              <Text style={[{fontSize:19,fontWeight:"700"},props.theme=='dark'?{color:'white'}:{color:'black'}]}>{item.name}</Text>
              <Text style={{color:'#717171'}}>35-45 m</Text>
              </View>
              <View style={{marginRight:10,backgroundColor:"#eee",paddingHorizontal:7,borderRadius:30}}>
                  <Text style={{fontSize:19,fontWeight:"500"}}>{item.rating}</Text>
              </View>
        </View>
            </View>
        ))}
        </View>
        </ScrollView>

    )}```

A: item.image should be url string check the value of props.restaurantsData may be one of the index has image_url as number OR try replacing item.image with item.image_url.toString()


text:
Q: I am unable to retrieve a request token using Twitter login library I was attempting to implement the Twitter login library located here: https://github.com/abraham/twitteroauth
I have followed a couple tutorials line by line just to see if I could get it working, but it gives me:

"This page isn't working. MyWebsite.com is unable to handle this request."

After looking through the code and trying some things, I realized the line that is causing it is this one in this picture:
<?php
session_start();
require 'autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;

define('CONSUMER_KEY', 'BlaBlaBlaBla'); // add your app consumer key between single quotes
define('CONSUMER_SECRET', 'BlaBlaBlaBla'); // add your app consumer secret key
between single quotes
define('oAUTH_CALLBACK', 'BlaBlaBlaBla/twitter/callback.php'); // your app callback URL

if (lisset($_SESSION['access_token'])) {
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
    $request_token : $connection->oauth('oauth/request_token', array('oauth_callback' => oAUTH_CALLBACK));
    $_SESSION['oauth_token'] : $request_token['oauth_token'];
    $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
    $url : $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));
    echo $url;
} else {
    $access_token = $_SESSION['access_token'];
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token[
    oauth_token_secret']);
    $user : $connection->get("account/verify_credentials")fl
    echo $user->screen_name;
}
?>

Code image:

If anyone has any experience with this and could help, it would be really helpful.


text:
Q: Validate date range exist in array I have an array of object. Every object have a start_date and and end_date (DATETIME).
I save it with : @arroy_of_objects.each(&:save)
But I can't have two date in the same time. If a start_date is equal and between an another date range, I don't want to save it.
How can I do it with rails ? In a validate in the model or directly in my controller


text:
Q: How to hard code binary data to string I want to test serialized data conversion in my application, currently the object is stored in file and read the binary file and reloading the object.
In my unit test case I want to test this operation. As the file operations are costly I want to hard code the binary file content in the code itself.
How can I do this?
Currently I am trying like this,
std::string FileContent = "\00\00\00\00\00.........";

and it is not working.

A: You're right that a string can contain '\0', but here you're still initializing it from const char*, which, by definition, stops at the first '\0'. I'd recommend you to use uint8_t[] or even uint32_t[] (that is, without passing to std::string), even if the second might have up to 3 bytes of overhead (but it's more compact when in source). That's e.g. how X bitmaps are usually stored.
Another possibility is base64 encoding, which is printable but needs (a relatively quick) decoding.
If you really want to put the const char[] to a std::string, first convert the pointer to const char*, then use the two-iterator constructor of std::string. While it's true that std::string can hold '\0', it's somewhat an antipattern to store binary in a string, thus I'm not giving the exact code, just the hint.

A: The following should do what you need, however probably not recommended as most people wouldn't expect an std::string to contain null bytes.
std::string FileContent { "\x00\x00\x00\x00\x00", 5 };


text:
Q: Add a checkbox to the dropdown list without any Javascript code or with Javascript code How can I add a checkbox to the dropdown list below next to the options? If possible, please advise without using Java Codes.

Other Info

          vERSION

            <select name="version" id="soft" class="text_field">
              <option value="">Select From List</option>
              <option value="4">WordPress 4</option>
              <option value="4.1">WordPress 4.1.*</option>
              <option value="4.2">WordPress 4.2.*</option>
              <option value="4.3">WordPress 4.3.*</option>
              <option value="4.4">WordPress 4.4.*</option>
            </select>

A: After a bit of searching on internet websites that had tutorials about CSS and HTML, I managed to find a code and use it. The code is as follows:

const MultiSelectDropdown = (params) => {
        let config = {
            search: true,
            hideX: false,
            useStyles: true,
            placeholder: 'Select...',
            txtSelected: 'Selected',
            txtAll: 'All',
            txtRemove: 'Remove',
            txtSearch: 'Search...',
            minWidth: '160px',
            maxWidth: '360px',
            maxHeight: '180px',
            borderRadius: 6,
            ...params
        };

        const newElement = (tag, params) => {
            let element = document.createElement(tag);
            if (params) {
                Object.keys(params).forEach((key) => {
                    if (key === 'class') {
                        Array.isArray(params[key])
                            ? params[key].forEach((o) => (o !== '' ? element.classList.add(o) : 0))
                            : params[key] !== ''
                                ? element.classList.add(params[key])
                                : 0;
                    } else if (key === 'style') {
                        Object.keys(params[key]).forEach((value) => {
                            element.style[value] = params[key][value];
                        });
                    } else if (key === 'text') {
                        params[key] === '' ? (element.innerHTML = ' ') : (element.innerText = params[key]);
                    } else {
                        element[key] = params[key];
                    }
                });
            }
            return element;
        };

        document.querySelectorAll('select[multiple]').forEach((multiSelect) => {
            let div = newElement('div', { class: 'multiselect-dropdown' });
            multiSelect.style.display = 'none';
            multiSelect.parentNode.insertBefore(div, multiSelect.nextSibling);
            let dropdownListWrapper = newElement('div', { class: 'multiselect-dropdown-list-wrapper' });
            let dropdownList = newElement('div', { class: 'multiselect-dropdown-list' });
            let search = newElement('input', {
                class: ['multiselect-dropdown-search'].concat([config.searchInput?.class ?? 'form-control']),
                style: {
                    width: '100%',
                    display: config.search ? 'block' : multiSelect.attributes.search?.value === 'true' ? 'block' : 'none'
                },
                placeholder: config.txtSearch
            });
            dropdownListWrapper.appendChild(search);
            div.appendChild(dropdownListWrapper);
            dropdownListWrapper.appendChild(dropdownList);

            multiSelect.loadOptions = () => {
                dropdownList.innerHTML = '';

                if (config.selectAll || multiSelect.attributes['select-all']?.value === 'true') {
                    let optionElementAll = newElement('div', { class: 'multiselect-dropdown-all-selector' });
                    let optionCheckbox = newElement('input', { type: 'checkbox' });
                    optionElementAll.appendChild(optionCheckbox);
                    optionElementAll.appendChild(newElement('label', { text: config.txtAll }));

                    optionElementAll.addEventListener('click', () => {
                        optionElementAll.classList.toggle('checked');
                        optionElementAll.querySelector('input').checked = !optionElementAll.querySelector('input').checked;

                        let ch = optionElementAll.querySelector('input').checked;
                        dropdownList.querySelectorAll(':scope > div:not(.multiselect-dropdown-all-selector)').forEach((i) => {
                            if (i.style.display !== 'none') {
                                i.querySelector('input').checked = ch;
                                i.optEl.selected = ch;
                            }
                        });

                        multiSelect.dispatchEvent(new Event('change'));
                    });
                    optionCheckbox.addEventListener('click', () => {
                        optionCheckbox.checked = !optionCheckbox.checked;
                    });

                    dropdownList.appendChild(optionElementAll);
                }

                Array.from(multiSelect.options).map((option) => {
                    let optionElement = newElement('div', { class: option.selected ? 'checked' : '', srcElement: option });
                    let optionCheckbox = newElement('input', { type: 'checkbox', checked: option.selected });
                    optionElement.appendChild(optionCheckbox);
                    optionElement.appendChild(newElement('label', { text: option.text }));

                    optionElement.addEventListener('click', () => {
                        optionElement.classList.toggle('checked');
                        optionElement.querySelector('input').checked = !optionElement.querySelector('input').checked;
                        optionElement.srcElement.selected = !optionElement.srcElement.selected;
                        multiSelect.dispatchEvent(new Event('change'));
                    });
                    optionCheckbox.addEventListener('click', () => {
                        optionCheckbox.checked = !optionCheckbox.checked;
                    });
                    option.optionElement = optionElement;
                    dropdownList.appendChild(optionElement);
                });
                div.dropdownListWrapper = dropdownListWrapper;

                div.refresh = () => {
                    // For demo purposes, remove
                    let tempSelectedList = document.getElementById('dropdownSelected');

                    div.querySelectorAll('span.optext, span.placeholder').forEach((placeholder) => div.removeChild(placeholder));
                    let selected = Array.from(multiSelect.selectedOptions);
                    if (selected.length > (multiSelect.attributes['max-items']?.value ?? 5)) {
                        div.appendChild(
                            newElement('span', {
                                class: ['optext', 'maxselected'],
                                text: selected.length + ' ' + config.txtSelected
                            })
                        );
                        // For demo purposes, remove
                        tempSelectedList
                            .querySelectorAll('span')
                            .forEach((span, index) => index !== 0 && tempSelectedList.removeChild(span));
                        selected.map((option) => tempSelectedList.appendChild(newElement('span', { text: option.text })));
                    } else {
                        // For demo purposes, remove
                        tempSelectedList
                            .querySelectorAll('span')
                            .forEach((span, index) => index !== 0 && tempSelectedList.removeChild(span));

                        selected.map((option) => {
                            let span = newElement('span', {
                                class: 'optext',
                                text: option.text,
                                srcElement: option
                            });
                            if (!config.hideX) {
                                span.appendChild(
                                    newElement('span', {
                                        class: 'optdel',
                                        text: '',
                                        title: config.txtRemove,
                                        onclick: (e) => {
                                            span.srcElement.optionElement.dispatchEvent(new Event('click'));
                                            div.refresh();
                                            e.stopPropagation();
                                        }
                                    })
                                );
                            }
                            div.appendChild(span);
                            // For demo purposes, remove
                            tempSelectedList.appendChild(newElement('span', { text: option.text }));
                        });
                    }
                    if (multiSelect.selectedOptions?.length === 0) {
                        div.appendChild(
                            newElement('span', {
                                class: 'placeholder',
                                text: multiSelect.attributes?.placeholder?.value ?? config.placeholder
                            })
                        );
                        // For demo purposes, remove
                        tempSelectedList.appendChild(newElement('span', { text: 'n/a' }));
                    }
                };
                div.refresh();
            };
            multiSelect.loadOptions();

            search.addEventListener('input', () => {
                dropdownList.querySelectorAll(':scope div:not(.multiselect-dropdown-all-selector)').forEach((div) => {
                    let innerText = div.querySelector('label').innerText.toLowerCase();
                    div.style.display = innerText.includes(search.value.toLowerCase()) ? 'flex' : 'none';
                });
            });

            div.addEventListener('click', () => {
                div.dropdownListWrapper.style.display = 'block';
                search.focus();
                search.select();
            });

            document.addEventListener('click', (e) => {
                if (!div.contains(e.target)) {
                    dropdownListWrapper.style.display = 'none';
                    div.refresh();
                }
            });
        });

        const createStyles = () => {
            let styles = {
                ':root': {
                    '--color-background': '#ffffff',
                    '--color-border': '#ced4da',
                    '--color-background--option': '#d6dde6',
                    '--color-background--option--hover': '#cbd5e0a1',
                    '--color-text--normal': '#0c0c0c',
                    '--color-text--grey': '#24262c',
                    '--color-text--red': '#cc6666',
                    '--color-text--placeholder': '#ced4da',
                    '--border-radius--base': `${parseInt(config.borderRadius)}px` || '6px',
                    '--border-radius--small': `${parseInt(config.borderRadius) * 0.75}px` || '4px'
                },
                '.multiselect-dropdown': {
                    position: 'relative',
                    display: 'inline-flex',
                    'flex-wrap': 'wrap',
                    padding: '6px 36px 6px 6px',
                    gap: '6px',
                    'border-radius': 'var(--border-radius--base)',
                    border: 'solid 1px var(--color-border)',
                    background: 'var(--color-background)',
                    'background-image':
                        "url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e\")",
                    'background-repeat': 'no-repeat',
                    'background-position': 'right 6px center',
                    'background-size': '16px 12px',
                    'min-width': `${config.minWidth}` ?? '140px',
                    'max-width': `${config.maxWidth}` ?? '360px',
                    cursor: 'pointer'
                },
                'span.optext, span.placeholder': {
                    display: 'inline-flex',
                    'justify-content': 'center',
                    'align-items': 'center',
                    'font-size': '16px',
                    'border-radius': 'var(--border-radius--small)'
                },
                'span.optext': {
                    'background-color': 'var(--color-background--option)',
                    padding: '0 12px 2px 6px',
                    cursor: 'default',
                    '-webkit-user-select': 'none',
                    '-moz-user-select': 'none',
                    '-ms-user-select': 'none',
                    'user-select': 'none'
                },
                'span.optext .optdel': {
                    float: 'right',
                    margin: '0 -6px 1px 6px',
                    'font-size': '12px',
                    cursor: 'pointer',
                    color: 'var(--color-text--grey)'
                },
                'span.optext .optdel:hover': {
                    color: 'var(--color-text--red)'
                },
                'span.placeholder': {
                    color: 'var(--color-border)'
                },
                '.multiselect-dropdown-list-wrapper': {
                    'z-index': 100,
                    'border-radius': 'var(--border-radius--base)',
                    border: 'solid 1px var(--color-border)',
                    display: 'none',
                    margin: '-1px',
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    right: 0,
                    background: 'var(--color-background)'
                },
                '.multiselect-dropdown-search': {
                    padding: '5px 6px 6px 5px',
                    'border-top-left-radius': 'var(--border-radius--base)',
                    'border-top-right-radius': 'var(--border-radius--base)',
                    border: 'solid 1px transparent',
                    'border-bottom': 'solid 1px var(--color-border)',
                    'font-size': 'inherit'
                },
                '.multiselect-dropdown-search::placeholder': {
                    color: 'var(--color-text--placeholder)',
                    'font-size': '16px'
                },
                '.multiselect-dropdown-search:focus, .multiselect-dropdown-search:focus-visible': {
                    outline: 'none'
                },
                '.multiselect-dropdown-list': {
                    'overflow-y': 'auto',
                    'overflow-x': 'hidden',
                    height: '100%',
                    'max-height': `${config.maxHeight}` ?? '160px'
                },
                '.multiselect-dropdown-list::-webkit-scrollbar': {
                    width: '4px'
                },
                '.multiselect-dropdown-list::-webkit-scrollbar-thumb': {
                    'background-color': 'var(--color-background--option)',
                    'border-radius': '1000px'
                },
                '.multiselect-dropdown-list div, .multiselect-dropdown-list div > input, .multiselect-dropdown-list div > label':
                {
                    cursor: 'pointer',
                    'border-radius': 'var(--border-radius--base)'
                },
                '.multiselect-dropdown-list div': {
                    display: 'flex',
                    'align-items': 'center',
                    'justify-content': 'flex-start',
                    'column-gap': '6px',
                    padding: '6px',
                    margin: '6px 4px',
                    transition: '100ms cubic-bezier(0.455, 0.03, 0.515, 0.955)'
                },
                '.multiselect-dropdown-list div:hover': {
                    'background-color': 'var(--color-background--option--hover)'
                },
                '.multiselect-dropdown-list-input': {
                    height: '14px',
                    width: '14px',
                    border: 'solid 1px var(--color-text--grey)',
                    margin: 0
                },
                '.multiselect-dropdown span.maxselected': {
                    width: '100%'
                },
                '.multiselect-dropdown-all-selector': {
                    'border-bottom': 'solid 1px var(--color-border)'
                }
            };
            const style = document.createElement('style');
            style.setAttribute('type', 'text/css');
            style.innerHTML = `${Object.keys(styles)
                .map(
                    (selector) =>
                        `${selector} { ${Object.keys(styles[selector])
                            .map((property) => `${property}: ${styles[selector][property]}`)
                            .join('; ')} }`
                )
                .join('\n')}`;
            document.head.appendChild(style);
        };

        config.useStyles && createStyles();
    };

    window.addEventListener('load', () => {
        MultiSelectDropdown(window.MultiSelectDropdownOptions);
    });
        * {
            box-sizing: border-box;
        }

        html, body, div {
            margin: 0;
            padding: 0;
        }

        body {
            height: 100vh;
            background-color: #fafafa;
            font-size: 16px;
        }

        body, div, span, input, select, p {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        form {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 14px;
        }

        .wrapper {
            display: flex;
            flex-direction: row;
            justify-content: center;
        }

        body > .wrapper {
            flex-direction: column;
        }

        .container {
            width: 50%;
            max-width: 420px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: flex-start;
            margin-top: 14px;
        }

        body > .wrapper > .container {
            width: 100%;
            max-width: unset;
            margin-bottom: 80px;
        }

        #dropdownSelected > span:first-of-type {
            font-weight: bold;
            font-size: 18px;
            margin-bottom: 4px;
        }

Multiselect Dropdown Demo

        Selected

        <select
          multiple
          search='true'
        >
          <option value="Singapore">Singapore</option>
          <option value="Portland">Portland</option>
          <option value="Halifax">Halifax</option>
          <option value="London">London</option>
          <option value="Seattle">Seattle</option>
          <option value="Toronto">Toronto</option>
        </select>


text:
Q: Slicing a range from a pandas dataframe column using loc I tried to extract a value range from a pandas column using loc but I fail with:
df.loc[0.5<df['a']<1.5, ['a']]

What is the correct pandas way to do this?

A: Use Series.between:
df.loc[df['a'].between(0.5, 1.5, inclusive=False), ['a']]

Or chain conditions with & for bitwise AND:
df.loc[(df['a'] > 0.5) & (df['a'] < 1.5), ['a']]

Or DataFrame.query with select a to one column DataFrame:
df[['a']].query("0.5 < a < 1.5")
#alternative
#df.query("0.5 < a < 1.5")[['a']]


text:
Q: Simple calculator in Python - print the answer to the calculation to 2 decimal places This simple calculator program only prints the answer to 1 decimal place. I would like to print the answer to 2 decimal places. How can I add code to print the answer to 2 decimal places please? Here is the code:
# Program make a simple calculator

# This function adds two numbers
def add(x, y):
    return x + y

# This function subtracts two numbers
def subtract(x, y):
    return x - y

# This function multiplies two numbers
def multiply(x, y):
    return x * y

# This function divides two numbers
def divide(x, y):
    return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
    # Take input from the user
    choice = input("Enter choice(1/2/3/4): ")

    # Check if choice is one of the four options
    if choice in ('1', '2', '3', '4'):
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))

        if choice == '1':
            print(num1, "+", num2, "=", add(num1,num2))

        elif choice == '2':
            print(num1, "-", num2, "=", subtract(num1,num2))

        elif choice == '3':
            print(num1, "*", num2, "=", multiply(num1,num2))

        elif choice == '4':
            print(num1, "/", num2, "=", divide(num1,num2))
        break
    else:
        print("Invalid Input")


text:
Q: QGraphicsScene::clear() method crashes only in release mode I inherited my scene from QGraphicsScene. I add many items(QGraphicslineItem, QGraphicsItem, QGraphicsTextItem) on this scene. Whenever i try QGraphicsSceneClear method it crashes on release mode. It works fine on debug mode.
Note: Some items have child items and/or have pointers to other items, so when i delete them i handle them in the destructor (deleting pointers to other items etc). i guess pointers to other items makes it crashing but i do not understand why it crashes only on release mode.
The call stack in release mode is not useful, but it does say access violation on the console.

A: Your problem is some of your items are deleting other items in the same scene. You have no control (well, not directly) on the order of removal of items when calling clear(). Say you have items A, B, and C. C maintains a pointer to both A and B. When clear() is called, A and B may have already been removed and deleted when C's destructor is called.
As for the crash only happening in release mode, the order of removal may depend on the level of compiler optimization. This is really common when dealing with dangling pointer.


text:
Q: Why not run android emulator on ubuntu? I am new in android studio on Ubuntu system.
After created a new project in android studio, I run it on a emulator using x86 image.
 Then a issue "Your CPU does not support required features(VT-x or SVM)" appeared.
To fix the issue I used another emulator using ARM system image.
Then when I run the project, android emulator appeared for just moment and then disappeared.
After that the emulator no appeared.
That is MAIN PROBLEM.
I can't understand that situation.
My ubuntu system run on Virtual Box.
Android studio version is 2.3.1


text:
Q: Move some fileds of array i am working with rest api in php and with use of mysql query ,I am getting following array (1 and 2 are cat_ids),
I just want to move cat_id and cat_image outside of array,I mean i want to show first cat_id with cat_name and inside this i want to get all selfie images with user ids and then second cat_name and cat id and inside this i want to get all selfie images and user id and so on
Here is my code.
foreach($userArr as $k=>$v){
$userCatArr[$v['cat_id']][] = $v; //add node
        unset($userCatArr[$v['cat_id']]['cat_id']); //unset doubles
    }
    $userArr = $userCatArr; unset($userCatArr);
        print_R($userArr);

And i am getting following result
Array
(
    [1] => Array
        (
            [0] => Array
                (
                    [id] => 16
                    [cat_id] => 1
                    [user_id] => 4
                    [cat_image] => abcd.jpg
                    [selfie_image] => abc.jpg
                )

            [1] => Array
                (
                    [id] => 17
                    [cat_id] => 1
                    [user_id] => 4
                    [cat_image] => xyze.jpg
                    [selfie_image] => xyz.jpg
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [id] => 16
                    [cat_id] => 2
                    [user_id] => 4
                    [cat_image] => abcdee.jpg
                    [selfie_image] => abc.jpg
                )
       )

But i want to change result like following array
Array
(
    [cat_id] => 1
    [cat_image] => abc.jpg
        (
            [0] => Array
                (
                    [user_id] => 4
                    [selfie_image] => abc.jpg
                )

            [1] => Array
                (
                    [user_id] => 4
                    [selfie_image] => xyz.jpg
                )

        )

    [cat_id] => 2
    [cat_image] => xyz.jpg
        (
            [0] => Array
                (
                    [user_id] => 4
                    [selfie_image] => abc.jpg
                )
       )


text:
Q: Given a Riemann Integrable function $F(x) = \int_0^x f $ . Prove F is continuous Let $f :\mathbb{R} → \mathbb{R}$ be Riemann integrable on every interval $[a,b]$ and define $F :\mathbb{R} → \mathbb{R}$ by
$F(x) = \int_0^x f$ . Prove that F is continuous.
My thought process behind this proof is that to be Riemann integrable we are assuming f to be bounded, which implies continuity.
Then the fundamental theorem of calculus states: Let $f : [a, b] → \mathbb{R} $ be continuous and define $ F : [a, b] → \mathbb{R}$ by $F(x)= \int_a^x f $. Then $F$ is differentiable.
So as we have f a continuous function we can apply the fundamental theorem of calculus. This gives F is differentiable and differentiable functions are continuous so F is continuous.
Is this correct or have I made wrong assumptions at all?

A: Yes, a Riemann integrable function is bounded over closed intervalls. Now consider
$F(x+h)-F(x)=\int_{x}^{x+h}f(y)dy $
We have $|F(x+h)-F(x)|\leq |h|M$ for some $M$ since on $[x,x+h]$, $f$ is bounded. Clearly $F$ is continuous.


text:
Q: Adding an image to a solution which won't compile and which can be navigated to It often happens that I draw diagrams of how something is designed in my application, for example a tree-like structure in a dialog window with several steps that the user can answer by choosing yes and no.

Is it possible to include this image in my solution but not compile it?
And would it be possible to add a link to the image in my code so that I can simply click on the link, and it would open up the image for me in VS?
This way I wouldn't have to locate it on my disk.
Thank you very much!

A: If you want to add an existing file to your project then right-click on your project in the Solution Explorer and select 'Add > Existing item'.  Set the Build Action to Content and the Copy to output directory to Copy always or Copy if newer.  The file will then be copied to the same folder as the EXE when you build.  You can access such a file at run time using a path like this:
Dim filePath = IO.Path.Combine(Application.StartupPath, "filename.ext")


text:
Q: Compression vs. redundancy: do they cancel each other out? Does it make sense to compress a tarball (or any kind of file, really), e.g., using gzip or bzip2, while at the same time creating redundancy files for it, e.g., a par2 file?
The context is that I am reasoning about how to best backup my personal files.
My #1 priority is to avoid data loss due to bitrot, hence, the par2 files.
Compression would be nice but is not my main concern.
The reason I am doubting the combined application of a compression algorithm and a erasure code algorithm is that the former works by eliminating redundancy (thereby creating smaller files) while the latter works by adding redundancy (thereby adding the capability to perform data recovery operations).
Don't they cancel each other out?
Is this a reasonable assumption or am I missing something here?


text:
Q: Showing that $f$ is a constant function? I am working on the question:

Suppose $f$ is entire, with real and imaginary parts $u$ and $v$ satisfying $u(z) v(z) = 3$ for all $z$.
  Show that $f$ is constant.

I understand that I must show $f'(z) = 0$. The first thing I did here was to set up the Cauchy Riemann Equations: $u_x = v_y$, and $u_y = -v_x$. However, I am not sure how to use $u(z) v(z) = 3$. Clearly I have to take some sort of derivative, but I'm not very familiar with how partial derivatives work. Can I take the partial derivative of both sides of $u(z) v(z) = 3$ and say $u_x (z) v(z) + u(z) v_x(z) = 0$? If yes, how should I proceed afterwards? I have worked under this assumption, but I still didn't get the desired $f'(z) = 0$.

A: If $f(z)$ is entire then so is $f(z)^2$, and if $f=u+iv$ then
$$ f^2=(u+iv)^2=u^2-v^2+2iuv$$
The condition $u(z)v(z)=3$ therefore implies that $f(z)^2$ has a constant imaginary part, so now it's enough to show that an entire function with a constant imaginary part is constant.

A: Note that if $f=u+iv$ and $v=3/u$, then the Cauchy-Riemann Equations reveal that
$$\frac{\partial u}{\partial x}=\frac{\partial v}{\partial y}\implies u_x=-3u_y/u^2 \tag 1$$
and
$$\frac{\partial u}{\partial y}=-\frac{\partial v}{\partial x}\implies u_y=3u_x/u^2 \tag 2$$
Using $(1)$ and $(2)$ together yields
$$u_x^2+u_y^2=0\implies u=\text{constant}$$
Hence $f$ is constant.

A: Consider the function $\displaystyle g(z)=e^{if^2(z)}$. Then , $g$ is an entire function.
Now ,  $\displaystyle |g(z)|=\left|e^{i(u^2-v^2)}\right|.\left|e^{-2uv}\right|=e^{-6}$ , for all $z\in \mathbb C$. So , $g$ is bounded in $\mathbb C$.
So by Liouville's theorem $g$ is constant and hence $f$ is constant.

A: Differentiating partially w.r.t $x$ and $y$ separately, you get $uv_x+vu_x=0$ and $uv_y+vu_y=0$. Use C-R equations to get $-uu_y+vu_x=0$ and $uu_x+vu_y=0$. On solving for $u_x$ you get

$(u^2+v^2)u_x=0\implies u_x=0$ or $u=constant$ as $(u^2+v^2)\ne 0$ unless $u=v=0$


text:
Q: Nested case query Db2 I am trying to create a nested case statement in DB2. It's throwing me an error.
select tmp.claim_number,
       SUM(tmp.LUMP_SUM_E) as LUMP_SUM_E
  from (
select c.claim_number,
       p.amount,
       p.effective_gross_amt,
       --p.lump_sum_e,
       p.released,
       p.to,
       p.payment_option,
       p.sub_benefit_type,
       p.PAYMENT_FIELD,
       CASE WHEN ((EXTRACT(YEAR FROM p.to) < EXTRACT(YEAR FROM p.released))
       THEN
          CASE WHEN (p.to <= '2020-07-01' and p.amount > 0)
          THEN amount ELSE 0
          END
       END AS lump_sum_e
from CLAIMS.claim c inner join claims.payment p on c.id = p.claim_id and c.claim_Number IN (75248)
AND (
      (p.RELEASED >= '2020-07-01' AND p.RELEASED <= '2021-06-30')
   OR
      (p.ATO_RELEASE_DATE >= '2020-07-01' AND p.ATO_RELEASE_DATE <= '2021-06-30')
    )
  ) tmp
GROUP by tmp.claim_number;

it's throwing
1) [Code: -104, SQL State: 42601]  An unexpected token "THEN" was found following "FROM p.released))
".  Expected tokens may include:  ")".. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.22.29
2) [Code: -727, SQL State: 56098]  An error occurred during implicit system action type "2". Information returned for the error includes SQLCODE "-104", SQLSTATE "42601" and message tokens "THEN|FROM p.released))
|)".. SQLCODE=-727, SQLSTATE=56098, DRIVER=4.22.29

Any idea how to write a nested case statement in Db2 please?.
Regards,
R

A: You need to fix your query syntax.
select tmp.claim_number,
       SUM(tmp.LUMP_SUM_E) as LUMP_SUM_E
  from (select c.claim_number,
               p.amount,
               p.effective_gross_amt,
               --p.lump_sum_e,
               p.released,
               p.to,
               p.payment_option,
               p.sub_benefit_type,
               p.PAYMENT_FIELD,
               CASE WHEN (EXTRACT(YEAR FROM p.to) < EXTRACT(YEAR FROM p.released))
                         THEN
                             CASE WHEN (p.to <= '2020-07-01' and p.amount > 0)
                                       THEN amount ELSE 0
                             END
               END AS lump_sum_e
          from CLAIMS.claim c
         inner join claims.payment p on c.id = p.claim_id
                                    and c.claim_Number IN (75248)
                                    AND (
                                         (p.RELEASED >= '2020-07-01'
                                          AND p.RELEASED <= '2021-06-30')
                                         OR
                                         (p.ATO_RELEASE_DATE >= '2020-07-01'
                                          AND p.ATO_RELEASE_DATE <= '2021-06-30')
                                        )
      ) tmp
GROUP by tmp.claim_number;

A: Consider using explicit parenthesis around the inner CASE expression. Also make sure that the ( and ) are in sync. Based on the syntax for the CASE statement it should work.


text:
Q: elisp search-forward with regexp and spec. chars return nil emacs 25.1
I have string:

more complex non Q and A HTML code here.

<th

And if use in emacs regexp-builder with the next regexp: "
"
it's success found text:

OK. But when I use same regexp in elisp by function search-forward nothing found (return nil)
      (setq test-start-point (search-forward "
" nil t))

test-start-point = nil.
Why?

A: search-forward searches exact matches.  In your case, you want to search a regular expression pattern, so you want to use re-search-forward instead.


text:
Q: Stata Mata Programming Conformability Error Hi I need help in Stata's Mata programming language for the following Minimum Working Example.
I am trying to insert sub-matrices of dimension (1x200) (generated by a random normal draw) inside a pointer matrix of dimension 600x1 (V matrix).
mata:
T=600     //number of markets
K_S=1    //number of variables with stochastic coefficients
R=200   //number of random draws
st_matrix("T", T)
//pointers to the market specific random draws:
V=J(T,1,NULL)   //   T by 1  0 matrix

for(t=1;t<=T;t++){
V[t]=(rnormal(K_S,R,0,1)) //dimension K_S x R
}
end

The problem is I am getting a "rnormal():  3200  conformability error"
Could you suggest what I am doing wrong.
Thanks

A: You are trying to assign a K_S x R matrix to a single cell in a column vector. A pointer has to be assigned, well, a pointer:
mata:
T   = 600 // number of markets
K_S = 1   // number of variables with stochastic coefficients
R   = 200 // number of random draws
st_matrix("T", T)

// pointers to the market specific random draws:
V = J(T, 1, NULL)  // T by 1  0 matrix

for(t=1; t<=T; t++){
    V[t]= &(rnormal(K_S, R, 0, 1)) //dimension K_S x R
}
end

In mata the & notation means pointer.


text:
Q: Remove image of UIBarButtonItem programmatically I have a UIBarButtonItem with an image I setup in the storyboard. Later on in the program, I want to change the barButtonItem to have text, and not an image. Here's the code:
self.menuBarButton.setBackgroundImage(nil, forState: .Normal, barMetrics: .Default)
self.menuBarButton.title = "Some Text"

When I run the app, the barButton shows the image, and 3 dots. "...". What can I do to remove the image, and have text instead?

A: Just set the .image-Property nil:
self.menuBarButton.image = nil;


text:
Q: Click on span with padding I have a span with no text, it looks like an image, it has background and padding. But it doesnot execute onclick event. What to do? Do I need obviously change span to everything else?

A: Make sure there's something inside the span, e.g.:

A: As far as i know if you want its background to be visible you need to set width and height for the span. And at least you need to include a space inside span
 & n b s p ;

A: There is no need in spaces or anything, its working great without any changes, that was my bad!


text:
Q: How to apply corner radius to certain corners and add shadow Is there a way to apply rounded corners to certain corners only, and at the same time apply a shadow layer?
I tried doing that using the following extension, but that didn't work for me:
extension UIView {
    func roundCorners(_ corners: UIRectCorner, radius: CGFloat, shadow: Bool = false) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
        if shadow {
            self.layer.shadowColor = UIColor.black.cgColor
            self.layer.shadowOffset = CGSize(width: 0, height: 2)
            self.layer.shadowOpacity = 0.3
            self.layer.shadowRadius = 3.0
        }
    }
}

A: So, I tossed in some code into playground and had a quick playground, based on the example from How to round only specific corners using maskedCorners
let view = UIView(frame: CGRect(x: 100, y: 100, width: 500, height: 500))
view.backgroundColor = UIColor.white
view.layer.cornerRadius = 15
view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMaxYCorner]

view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOffset = CGSize(width: 0, height: 0)
view.layer.shadowOpacity = 1.0
view.layer.shadowRadius = 4
//view.layer.shadowPath = UIBezierPath(rect: view.bounds).cgPath
view.layer.shouldRasterize = false

let outter = UIView(frame: CGRect(x: 0, y: 0, width: 700, height: 700))
outter.backgroundColor = UIColor.red
outter.addSubview(view)

outter

I did some testing:
With no corner radius

With masked corner radius

With reduced shawdowRadius

And just to be sure, increased corner radius


text:
Q: What are the implications of deleting a user account? Most of the websites I've used in the past (including this one) do not offer an option to delete your own account.
I think the main reason is to avoid the orphanage of the items created (or the delete on cascade of those items).
Modern sites (like this one) have a place where those items go when an account is abandoned (in the case of SO it is the user "Community").
What is, in your opinion, the rationale of not providing a "delete my account" feature?
Security? Laziness? Ignorance? Bug? Or feature?
We are designing a small web app, and we are discussing precisely this topic. We can't find too many reasons though for not allowing the user to delete the account.

A: Will it be more work to maintain those abandoned accounts than you would normally have?  Also,  are people that visit your site likely to come back to it after long periods of time?  These are questions your team might want to discuss.
Personally, unless it is going to cause a disruption or slowdown in work, I would keep the accounts.  That way, users won't complain when they visit six months down the road and find they cannot log in.

A: This may not apply to you. But in our system, we deal with patient data. Because of privacy, security and regulatory concerns, we do not delete users. We have extensive audit trails indicating who accessed/entered/changed which pieces of information. We provide a mechanism to disable access, but the audit trails must remain in tact, so the health care facilities can monitor and enforce their privacy policies.

A: I'm pretty sure I've quoted this Udi Dahan article but it's worth posting again here.
The key point is to model the task, not the data.  Do you truly want to nullify the existence of a user (he/she never existed)?

A: This is a pretty broad topic, but some of the ones I've experienced are:

*

*Accounts can be tied to comments, deleting the account screws up the comments

*Accounts can tied to other systems (community server, authorize.net and blackbox web services) and can be hard to delete on those

*Cascade, like you mentioned

*Prevent user stupidity - accidental delete is hard to undo, and even trickier on a subscription site

*Return on investment - try explaining to your boss why you're doing a weeks worth of data integrity testing instead of setting a boolean to false

*Marketing - "We have 85,000 registered users" (see: myspace)

A: I'd say either lack of foresight or "not worth the effort" judgement.

A: As a user, I want to be able to contact a company and request that my account be wiped.


text:
Q: Two statements in small basics arent working together For an assignment in IT we have to create a house using small basics, to get a higher level we are told to make the colours of the windows change colour. I've done this; I've tried to accomplish a higher level by adding moving clouds also, the two different statements aren't working together.
My code is below:
'background
GraphicsWindow.Title= "My House Assessment"
GraphicsWindow.Height= "600"
GraphicsWindow.Width= "1000"
GraphicsWindow.BackgroundColor="#198cFF"
'grass
GraphicsWindow.PenColor= "#2bf90b"
GraphicsWindow.BrushColor= "#2bf90b"
GraphicsWindow.PenColor= "#0000000"
GraphicsWindow.DrawRectangle(0,400,1000,500)
GraphicsWindow.FillRectangle(0,400,1000,500)
'path
GraphicsWindow.BrushColor= "#34000d
GraphicsWindow.PenColor= "#34000d"
GraphicsWindow.DrawTriangle(700,600,300,300,0,1000)
GraphicsWindow.FillTriangle(700,600,300,300,0,1000)
'top floor
GraphicsWindow.BrushColor="#173cf0"
GraphicsWindow.DrawRectangle(100,100,750,200)
GraphicsWindow.FillRectangle(100,100,750,200)
'ground floor
GraphicsWindow.BrushColor="#ffffcc"
GraphicsWindow.DrawRectangle(100,300,750,200)
GraphicsWindow.FillRectangle(100,300,750,200)
'roof
GraphicsWindow.BrushColor="#808080"
GraphicsWindow.DrawTriangle(100,100,425,10,850,100)
GraphicsWindow.FillTriangle(100,100,425,10,850,100)
'door
GraphicsWindow.BrushColor="#000000"
GraphicsWindow.PenColor="#000000"
GraphicsWindow.DrawRectangle(400,350,100,150)
GraphicsWindow.FillRectangle(400,350,100,150)
''number on door
GraphicsWindow.BrushColor="#FFFFFF"
GraphicsWindow.DrawText(450,400,"45")
'doorknob
GraphicsWindow.BrushColor="#FFFFFF"
GraphicsWindow.DrawEllipse(475,420,10,10)
GraphicsWindow.FillEllipse(475,420,10,10)

'windows on floor one
For i= 1 To 5000000
GraphicsWindow.BrushColor= GraphicsWindow.GetRandomColor()
GraphicsWindow.DrawEllipse (200,120,150,150)
GraphicsWindow.FillEllipse(200,120,150,150)
GraphicsWindow.DrawEllipse (600,120,150,150)
GraphicsWindow.FillEllipse(600,120,150,150)
timer.Interval=1000
EndFor
'clouds
Sball = Shapes.AddEllipse(100, 100)
Sball2 = Shapes.AddEllipse(100,100)
Sball3 = Shapes.AddEllipse(100,100)
start:
Shapes.Move(Sball,400,50)
Shapes.Move(Sball2,450,50)
Shapes.Move(Sball3,500,50)
x = 200
Shapes.Animate(Sball,800,50,x)
Shapes.Animate(Sball2,850,50,x)
Shapes.Animate(Sball3,900,50,x)
Program.Delay(500)
If (Shapes.GetLeft(Sball) = x) Then
Shapes.Animate(Sball, 0, 340, 500)
EndIf
If (Shapes.GetLeft(Sball2) = x)Then
Shapes.Animate(Sball, 0, 340, 500)
EndIf

Shapes.Move(Sball,800,50)
Shapes.Move(Sball2,850,50)
Shapes.Move(Sball3,900,50)
x = 200
Shapes.Animate(Sball,400,50,x)
Shapes.Animate(Sball2,450,50,x)
Shapes.Animate(Sball3,500,50,x)
Program.Delay(500)
If (Shapes.GetLeft(Sball) = x) Then
Shapes.Animate(Sball, 0, 340, 500)
EndIf
If (Shapes.GetLeft(Sball2) = x)Then
Shapes.Animate(Sball, 0, 340, 500)
EndIf
If (Shapes.GetLeft(Sball3) = x)Then
Shapes.Animate(Sball, 0, 340, 500)
EndIf
Goto start

A: The first thing I noticed is that you are using Shapes.GetLeft for getting the position of the animated shape. This will not work because Animated shapes will always return the endpoint as their position, even while they are moving.
The second thing is this:
For i= 1 To 5000000
GraphicsWindow.BrushColor= GraphicsWindow.GetRandomColor()
GraphicsWindow.DrawEllipse (200,120,150,150)
GraphicsWindow.FillEllipse(200,120,150,150)
GraphicsWindow.DrawEllipse (600,120,150,150)
GraphicsWindow.FillEllipse(600,120,150,150)
timer.Interval=1000
EndFor

This will not work because timer.Interval=1000 is not a delay. It sets the interval between calling the timer event (you aren't using it here). What you want is Program.Delay(1000).
Also, the For statement is not the way to go. Use a while :D. Once you hit a for loop, the program cannot pass it until it is completed. So that is why the rest of the program isn't working.
Try this program:
GraphicsWindow.BrushColor="#000000"
GraphicsWindow.PenColor="#000000"
GraphicsWindow.DrawRectangle(400,350,100,150)
GraphicsWindow.FillRectangle(400,350,100,150)
''number on door
GraphicsWindow.BrushColor="#FFFFFF"
GraphicsWindow.DrawText(450,400,"45")
'doorknob
GraphicsWindow.BrushColor="#FFFFFF"
GraphicsWindow.DrawEllipse(475,420,10,10)
GraphicsWindow.FillEllipse(475,420,10,10)

Cloud1 = Shapes.AddEllipse(30,30)
Cloud2 = Shapes.AddEllipse(30,30)
Cloud3 = Shapes.AddEllipse(30,30)

xpos = 100

'windows on floor one
While 1 = 1 'This will repeat while the statement is true (1 always = 1)
GraphicsWindow.BrushColor= GraphicsWindow.GetRandomColor()
GraphicsWindow.DrawEllipse (200,120,150,150)
GraphicsWindow.FillEllipse(200,120,150,150)
GraphicsWindow.DrawEllipse (600,120,150,150)
GraphicsWindow.FillEllipse(600,120,150,150)

'Clouds
xpos = - xpos
Shapes.Animate(Cloud1,xpos+300,100,1000)
Shapes.Animate(Cloud2,-xpos+300,150,1000)
Shapes.Animate(Cloud3,xpos+400,100,1000)
Program.Delay(1000)
EndWhile


text:
Q: Pointers : difference between * and (int *) in given context int ar[3][3]={{1,2,3},{4,5,6},{7,8,9}};

statment1:  int k=(int *)((int *)(ar+1)+2);
statment2:  int l=*(*(ar+1)+2);
statement3  int *p = (int *)a +1;

Statement1 does not compile.
Statement2 and Statement3 compiles.
Now, I cannot make out what difference does it make if I put (int *) instead of *, given that the array is of integer type.

A: You are confused about dereference operator * and cast operation (int *), and your very 1st line should have ring a bell:
int k = (int *)bar;

You try to affect an address (pointer to int) in an int variable.
The 2nd is ok because you are using * twice to get a value in your 2-dimension array.
The 3rd is also ok because your container int * p has the right type to get an address (and you dereference just "one dimension".
I hope it is clear enough, anyway you can have a look at this Wikipedia article abour dereference operator.

A: the confusion appears in this line where pointers are used instead of array indexes:
statment1:  int k=(int *)((int *)(ar+1)+2);

It appears the meaning is intended to be ar[1][2] however, that is not what they have. In order to create an equivalent pointer representation of the ar[1][2] index, it would be:
statment1:  int k = *(*(ar + 1) + 2) // equivalent to k = ar[1][2]


text:
Q: Find max in a MongoDB collection using .Net Driver 2 With the 1.10 version of the .NET driver I could do something like this to get the max timestamp in the oplog collection:
this.oplogCollection.AsQueryable<OplogEntry>().Max(o => o.ts);

How can I do that with the new driver 2.0?
The documentation is basically non-existent or not helpful, so I am hoping some insiders can shed some light here.

A: EDIT: Not sure if there is a better way, but this works. I haven't found a way to implement the $max operator easily.
var list = await collection.Aggregate().SortByDescending((a) => a["field"]).FirstAsync();

A: Since MongoDB.Driver 2.0 the best approach is to use FindOptions instance with specified Limit and Sort fields:
var options = new FindOptions<OplogEntry, OplogEntry>
{
    Limit = 1,
    Sort = Builders<OplogEntry>.Sort.Descending(o => o.ts)
};

var max = (await oplogCollection.FindAsync(FilterDefinition<OplogEntry>.Empty, options)).FirstOrDefault();

Sort and Limit params are processed on server side. Therefore such operation is very efficient with only one result item passed to the client.

A: Here's the quickest way to access the last entry in the oplog I have found so far:
this.oplogCollection.Find(new BsonDocument()).Sort(new BsonDocument("$natural", -1)).FirstOrDefaultAsync()

It sorts the oplog in reverse natural order and since the natural order in the oplog is by ascending timestamp, grabbing the last element gives me the max.
This method is very fast and from first experiments it does not seem dependent on the oplog size, since no actual sorting takes place.
The other solutions will decrease in performance with the size of the oplog.

A: You can try this:
var result = await collection.Find(x => true).SortByDescending(d => d.ts).Limit(1).FirstOrDefaultAsync();

BTW $max doesn't give you the biggest value as in Linq or SQL, it specifies the upper exclusive bound of a Find. Documentation here


text:
Q: Programmatically put activity indicator on the login button I'm trying to programmatically place an activity indicator on the login button. At the moment, my button looks like this:

How can I place an activity indicator on the left side of the Login text?
Thanks.

A: Use a UIProgressView and just overlay it on the button. Nothing fancy ;)

A: I'm not sure if there is a specific framework you are trying to use here, but here is a basic fiddle with possibly what you are looking for.
http://jsfiddle.net/mqFQg/


text:
Q: Extending the Magento OnePage checkout class I am adding an additional checkbox field to the Magento checkout for newsletter subscriptions via a new module.
So far I have added the code to my layout file (billing.phtml):

Please untick this box if you do not wish to receive infrequent email updates and newsletters from us. <input type="checkbox" name="billing[is_subscribed]" title="" value="1" id="billing:is_subscribed" class="checkbox" checked="checked" />

I have extended the class (app/code/local/Clientname/Checkout/Model/Type/Onepage.php) - I have extended only the savebilling method:
<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Mage
 * @package     Mage_Checkout
 * @copyright   Copyright (c) 2010 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

/**
 * One page checkout processing model
 */

class Eatyourwords_Checkout_Model_Type_Onepage extends Mage_Checkout_Model_Type_Onepage
{

    public function saveBilling($data, $customerAddressId)
    {
        if (empty($data)) {
            return array('error' => -1, 'message' => $this->_helper->__('Invalid data.'));
        }

        $address = $this->getQuote()->getBillingAddress();

        if (!empty($customerAddressId)) {
            $customerAddress = Mage::getModel('customer/address')->load($customerAddressId);
            if ($customerAddress->getId()) {
                if ($customerAddress->getCustomerId() != $this->getQuote()->getCustomerId()) {
                    return array('error' => 1,
                        'message' => $this->_helper->__('Customer Address is not valid.')
                    );
                }
                $address->importCustomerAddress($customerAddress);
            }
        } else {
            // process billing address and validate form
            /* @var $addressForm Mage_Customer_Model_Form */
            $addressForm    = Mage::getModel('customer/form');
            $addressForm->setFormCode('customer_address_edit')
                ->setEntity($address)
                ->setEntityType('customer_address')
                ->setIsAjaxRequest(Mage::app()->getRequest()->isAjax());
            // emulate request object
            $addressData    = $addressForm->extractData($addressForm->prepareRequest($data));
            $addressErrors  = $addressForm->validateData($addressData);
            if ($addressErrors !== true) {
                return array('error' => 1, 'message' => $addressErrors);
            }
            $addressForm->compactData($addressData);

            if (!empty($data['save_in_address_book'])) {
                $address->setSaveInAddressBook(1);
            }
        }

        // validate billing address
        if (($validateRes = $address->validate()) !== true) {
            return array('error' => 1, 'message' => $validateRes);
        }

        $address->implodeStreetAddress();

        if (true !== ($result = $this->_validateCustomerData($data))) {
            return $result;
        }

        if (!$this->getQuote()->getCustomerId() && self::METHOD_REGISTER == $this->getQuote()->getCheckoutMethod()) {
            if ($this->_customerEmailExists($address->getEmail(), Mage::app()->getWebsite()->getId())) {
                return array('error' => 1, 'message' => $this->_customerEmailExistsMessage);
            }
        }

        if (!$this->getQuote()->isVirtual()) {
            /**
             * Billing address using otions
             */
            $usingCase = isset($data['use_for_shipping']) ? (int)$data['use_for_shipping'] : 0;

            switch($usingCase) {
                case 0:
                    $shipping = $this->getQuote()->getShippingAddress();
                    $shipping->setSameAsBilling(0);
                    break;
                case 1:
                    $billing = clone $address;
                    $billing->unsAddressId()->unsAddressType();
                    $shipping = $this->getQuote()->getShippingAddress();
                    $shippingMethod = $shipping->getShippingMethod();
                    $shipping->addData($billing->getData())
                        ->setSameAsBilling(1)
                        ->setShippingMethod($shippingMethod)
                        ->setCollectShippingRates(true);
                    $this->getCheckout()->setStepData('shipping', 'complete', true);
                    break;
            }
        }

        $this->getQuote()->collectTotals();

        if (isset($data['is_subscribed'])) {
            $status = Mage::getModel('newsletter/subscriber')->subscribe($data['email']);
        }

        $this->getQuote()->save();

        $this->getCheckout()
            ->setStepData('billing', 'allow', true)
            ->setStepData('billing', 'complete', true)
            ->setStepData('shipping', 'allow', true);

        return array();
    }

}

Specifically towards the bottom of the class I have inserted:
if (isset($data['is_subscribed'])) {
            $status = Mage::getModel('newsletter/subscriber')->subscribe($data['email']);
        }

I have added a file to let Magento know about the module (app/etc/modules/Clientname_Checkout.xml):
<?xml version="1.0"?>

<config>
    <modules>
        <Clientname_Checkout>
            <active>true</active>
            <codePool>local</codePool>
        </Clientname_Checkout>
    </modules>
</config>

However I am now stuck on the final step of how I get Magento to recognise and use the alernative save_billing method I have extended.  I think I need to add a file /app/code/local/Clientname/config.xml.
But I don't understand how I set this up so that the new savebilling class is used instead of the original.
Please can somebody help with this final step?
Thanks
Simon

A: This is a textbook example of class overrides in Magento.  As you probably know, Magento uses a form of abstraction to load classes based on the contents of the XML configuration files dotted around the codebase.  This means we can load the model Mage_Checkout_Model_Type_Onepage by calling Mage::getModel('checkout/type_onepage'), with the default configuration.  A pretty cool feature is the ability to modify the mapping of the model reference, checkout/type_onepage to the actual class name.
Directory Structure
So you've done the hard work: editing the template and changing the model method.  Next you need to build a small module to perform the class rewriting.  Based on the name of your class, you're going to need a directory structure of the form:
/app
  /etc
    /modules
      /Eatyourwords_Checkout.xml
  /code
    /local
      /Eatyourwords
        /Checkout
          /etc
            /config.xml
          /Model
            /Type
              /Onepage.php

Performing the rewrite
The rewrite is handled in your module configuration file, config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <eyw_c>
            <version>1.0</version>
        </eyw_c>
    </modules>
    <global>
        <models>
            <eyw_c>Eatyourwords_Checkout_Model</eyw_c>
            <checkout>
                <rewrite>
                    <type_onepage>Eatyourwords_Checkout_Model_Type_Onepage</type_onepage>
                </rewrite>
            </checkout>
        </models>
    </global>
</config>

The stuff in the <modules /> tag group is just some standard bootstrapping for the module.
In the <models /> section we are defining namespace to be used when loading any of our Model classes.  Much like the checkout/type_onepage, we can access any models we have in our /Model directory by appending eyw_c/*.
We then open up the Mage_Checkout model namespace, <checkout />, and perform a rewrite of the checkout/type_onepage class.  Now when Magento attempts to load checkout/type_onepage it will look for our class.  All other checkout/* classes will be unaffected.  The class name for them will be constructed in the normal manner.
Enable the module
Next we need to point Magento to the new module that we've created.  Your attempt was almost correct.  You should call it Eatyourwords_Checkout.xml and place it in /app/etc/modules:
<?xml version="1.0"?>
<config>
    <modules>
        <Eatyourwords_Checkout>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Mage_Checkout />
            </depends>
        </Eatyourwords_Checkout>
    </modules>
</config>

..and that's it done.  Class overridden.


text:
Q: Story about consumerisms and indebting the son I'm searching for a short story I read probably around 20 years ago in a school anthology. It was set in a futuristic setting, where consumerism was rampant. The two protagonists were a door-to-door salesman and its customer.
In this futuristic setting a person could buy things with credit not only by indebting himself but also by indebting the first X years of his son's salary (this even when the son was a child... So you could buy a new TV by exchanging it with the first year of the future salary of your son, to make an example).
The customer was already quite heavily indebted (and clearly already had his house full of things he hadn't ever used, like a pool), and the salesman was trying to persuade the customer to indebt a little of his son's future salaries. If I remember correctly, the customer hadn't still indebted his son, and he was reluctant to do so, but he had already nearly tapped out all of his personal future salary. The salesman used at least two ways to persuade the customer:

*

*he told him that anything he bought would then be used by his son, and a day would become his son's property (at the death of the customer), so it was OK to use the son's future salaries.

*AND, big "secret", he told him that his neighbour had already indebted his yet-to-be-born niece. He told the customer that his company would have to invent new things to sell to this neighbour :-)

A: Cost of Living by Robert Sheckley.
The Avignon Electric finance man comes to call.

"You owe us two hundred and three thousand dollars and twenty-nine
cents, Mr Carrin, as of your last purchase."

...

"Now you know, Mr Carrin , that you won't live long enough to pay us
the full two hundred thousand, don't you?"

...

If you will just sign over your son's earnings for the first thirty
years of his adult life, we can easily arrange credit for you."

Big "secret", he told him that his neighbour had already indebted his yet-to-be-born niece. He told the customer that his company would have to invent new things to sell to this neighbour
No inventions, but they'll "work out something for him" (i.e. finance).

"Do you know Mellon down the block? Well, don't say I said it, but
he's already mortgaged his grandchildren's salary for their full
life-expectancy. And he doesn't have half the goods he's made up his
mind to own. We'll work out something for him."

He told him that anything he bought would then be used by his son, and a day would become his son's property (at the death of the customer), so it was OK to use the son's future salaries.

"And after you're gone, sir, they'll all belong to your son."


text:
Q: Rails Activerecord: How to exclude records with multiple associated records I have the below query with the associations as shown.
The query works when there is only one booking record per bike, but fails when bike has multiple bookings and one or more meet the conditions and others do not. Since the other don't meet the conditions, they cause the associated bike to be returned as a result.
How do I write the query so that a bike is not returned as a query result when at least one of the bookings meets the where.not condition?
class Bike < ActiveRecord::Base
  has_many :bookings
end

class Booking < ActiveRecord::Base
  belongs_to :bike
end

startDate = Date.parse("2018-10-10")
endDate = Date.parse("2018-10-19")

@bikes = Bike.joins(:bookings).where.not("(date_start BETWEEN (?) AND (?)) OR (date_start BETWEEN (?) AND (?)) OR (((?) OR (?)) BETWEEN date_start AND date_end)", startDate, endDate, startDate, endDate, startDate, endDate)

A: You could run the query on Bike with a subquery on Booking:
Bike.where.not(
  id: Booking.select('DISTINCT bike_id').where(...)
)

A: I think you can simplify the condition a bit. I have not considered edge cases but you can do something like this:
Bike.where.not(
    id: Booking.where("start_time < ? and end_time > ?", endDate, startDate
).group(:bike_id))

So basically bookings.start_time should be less then potential endDate while bookings.end_time is bigger than potential startDate. Hence you will get all bookings that are in the range of the potential new booking time range and adding not will select the opposite
I've tested my sample on a simple dataset and it excludes the bikes that are occupied. Please let me know if that works for you

A: You could reverse things, beginning the query with the bookings you want and finding the set of all their unique bikes:
@bikes = Booking.where.not(...).group(:bike_id).includes(:bikes).map{|b| b.bike}


text:
Q: JsonIgnoreProperties not working , Infinite recursion - Kotlin/Spring/ Hello i have 2 tables with relation ManyToMany but i am getting this error after if fetch from the api:
 Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException:

My Classes are ManyToMany as example:
Class A:
  @ManyToMany( fetch = FetchType.LAZY , cascade = [
            CascadeType.PERSIST,
            CascadeType.MERGE
    ])
    @JoinTable(name = "material_formula_material_set",
            joinColumns = [JoinColumn(name = "material_formula_id", referencedColumnName = "id")],
            inverseJoinColumns = [JoinColumn(name = "material_set_id", referencedColumnName = "id")]
    )
    val materialSet: Set<MaterialSet>?,

And Class B:
@ManyToMany(mappedBy = "materialSet")
val materialFormulas: Set<MaterialFormula>?,

I also tried to use  @JsonManagedReference and @JsonBackReference and JsonIgnore to one of them but still not working :\

A: You need to annotate a reference to your parent class in your child class with @JsonIgnore annotation. Since it is many to many relationship it might be  not that obvious to see who is parent and who is the child. But in any case the infinite recursion occurs because class A references B and B in turn references A. So, lets say in B you will need to annotate reference to A with @JsonIgnore and it will solve the problem


text:
Q: How to create an MS Access table with a checkbox field in VBA I want to create a MS Access table dynamically with a checkbox field in VBA. Setting the field property to checkbox works with an existing table:
Set dbs = CurrentDb()
Set tdf = dbs.TableDefs("myTable")
Set fld = tdf.CreateField("myField", dbBoolean)
tdf.Fields.Append fld
fld.Properties.Append fld.CreateProperty("DisplayControl", dbInteger, CInt(acCheckBox))

However, when the table is created dynamically, it does not work.
Set dbs = CurrentDb()
Set tdf = dbs.CreateTableDef("myTable")
Set fld = tdf.CreateField("myField", dbBoolean)
tdf.Fields.Append fld
fld.Properties.Append fld.CreateProperty("DisplayControl", dbInteger, CInt(acCheckBox))
dbs.TableDefs.Append tdf

Does anybody know what is wrong with this code? Or if it is possible at all to set the checkbox property when the table is not yet created.

A: This works for me:
Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field

Set dbs = CurrentDb()
Set tdf = dbs.CreateTableDef("myTable")

Set fld = tdf.CreateField("myField1", dbBoolean)
tdf.Fields.Append fld
dbs.TableDefs.Append tdf
fld.Properties.Append fld.CreateProperty("DisplayControl", dbInteger, acCheckBox)

Set fld = tdf.CreateField("myField2", dbBoolean)
tdf.Fields.Append fld
fld.Properties.Append fld.CreateProperty("DisplayControl", dbInteger, acCheckBox)


text:
Q: Derivative in function form I have a function in mathematica defined as
 b[n_, x_] := x^n/n!/\!\(\*UnderoverscriptBox[\(\[Sum]\), \(k = n\), \(\[Infinity]\)]\*FractionBox[\(x^k\), \(k!\)]\)

which is the same as
$$b(n,x)=\frac{\frac{x^n}{n!}}{e^x-1-x-...-\frac{x^{n-1}}{(n-1)!}}$$
I want to take the derivative of this differential expression with respect to $x$:
$$x^2b''(n,x)+\left[3x^2+(1-3n)x\right]b'(n,x)+\left[2x^2+(1-4n)x+2n^2\right]b(n,x)$$
So i write this into mathematica:
 a[n_, x_] := x^2*D[D[b[n, x], x], x] + (3 x^2 + (1 - 3 n) x)*D[b[n, x], x] + (2 x^2 + (1 - 4 n) x + 2 n^2)*b[n, x]

 D[a[n, x], x]

from here, mathematica spits out the answer, but it gives the answer in terms of
 (1 - 3 n + 6 x) (-((E^(-2 x) x^(-1 + 2 n) Gamma[n])/( n! (Gamma[n] - Gamma[n, x])^2)) + (E^-x n x^(-1 + n) Gamma[n])/(
n! (Gamma[n] - Gamma[n, x])) - (E^-x x^n Gamma[n])/(n! (Gamma[n] - Gamma[n, x]))) + ...

I am hoping someone can help get the output to be in terms of a derivative instead of the gamma function factorization that is being generated when I take the derivative of $a(n,x)$.  For example, the first few terms of the derivative are
$$x^2b'''(n,x)+2xb''(n,x)+\left[3x^2+(1-3n)x\right]b''(n,x)+\left[6x+(1-3n)\right]b'(n,x)+...$$
Is there a way mathematica can do this as an output instead of the long string of factors comprised of the gamma function?

A: The problem is that the definition of b is being substituted (and some of the factorials are being converted to Gamma).  You need to keep b from being evaluated.  Without knowing how you wish to use the result, here is a possibility:
a[n_, x_] :=
 Inactivate[
  x^2*D[D[b[n, x], x], x] + (3 x^2 + (1 - 3 n) x) * D[b[n, x], x] +
    (2 x^2 + (1 - 4 n) x + 2 n^2)*b[n, x],
  b]

D[a[n, x], x]

If you don't like the derivatives of b being displayed as partial derivative, well, it's because you've declared b to the a function of two variable.  Mathematica is just displaying which variable is being differentiated.
Here's a more roundabout way, but keeping your definition of a and avoid the V10 Inactive, which could have been used here instead of HoldForm:
a[n_, x_] :=
 x^2*D[D[b[n, x], x], x] + (3 x^2 + (1 - 3 n) x) * D[b[n, x], x] +
    (2 x^2 + (1 - 4 n) x + 2 n^2)*b[n, x]

Hold[D[a[n, x], x]] /. DownValues[a] /. b -> HoldForm[b] // ReleaseHold

A: This is just an extended comment.
If you use (Full)Simplify there is no long string of terms even with b[n,x] being evaluated.
Clear[a, b]

b[n_, x_] = (x^n/n!)/Sum[x^k/k!, {k, n, Infinity}] //
  FullSimplify

Limit[x^2 D[b[n, x], {x, 2}] +
  (3 x^2 + (1 - 3 n) x) D[b[n, x], x] +
  (2 x^2 + (1 - 4 n) x + 2 n^2) b[n, x], x -> 0]

2*n^2

a[n_, x_] = Piecewise[{
   {2 n^2, x == 0}},
  x^2 D[b[n, x], {x, 2}] +
    (3 x^2 + (1 - 3 n) x) D[b[n, x], x] +
    (2 x^2 + (1 - 4 n) x + 2 n^2) b[n, x] //
   Simplify]

D[a[n, x], x] // FullSimplify


text:
Q: Is it possible to return Fluent children in a GET request? Right now I have the following two classes:
final class Song: MySQLModel {
    var id: Int?
    var lyrics: String
    var artist: String
    var title: String
    var strummingPattern: String

    init(id: Int? = nil, title: String, lyrics: String, artist: String, strummingPattern: String) {

        self.id = id
        self.lyrics = lyrics
        self.title = title
        self.artist = artist
        self.strummingPattern = strummingPattern

    }
}

extension Song {
    var chords: Children<Song, SongChord>{
        return children(\.songID)
    }
}

final class SongChord: MySQLModel {
    var id: Int?
    var songID: Int
    var chord: String
    var position: Int

    init(id: Int? = nil, chord: String, position: Int, songID: Int) {
        self.songID = songID
        self.id = id
        self.chord = chord
        self.position = position
    }
}

extension SongChord {
    var chords: Parent<SongChord, Song>{
        return parent(\.songID)
    }
}

I want to return a list of all Songs with their respective SongChord children. So far I've come up with:
return Song.query(on: req)
            .join(\SongChord.songID, to: \Song.id)
            .alsoDecode(SongChord.self)
            .all()

But this returns an error of "Cannot convert value of type 'EventLoopFuture<[(Song, SongChord)]>' to closure result type '_'". Some people online were suggesting doing a flatmap, but this was still producing an error. Any suggestions on how to retrieve the children would be appreciated.

A: As the error implies you return EventLoopFuture<[(Song, SongChord)]>. If you decode multiple models from your query result, you will receive a Tupel of Song and SongChord for each result row; what you have to do now is:

*

*Create a struct (e.g. SongViewModel) that conforms to Content and has all relevant fields from Song and another var called chords: [SongChords]. Reason is, the original Song model has no array of SongChord but only a Children<Song, SongChord> which you cannot resolve easily

*Map your result from [(Song, SongChord)] to [SongViewModel]. This might be of help for you to transform your Tuple array: https://stackoverflow.com/a/31220067/710350

*return [SongViewModel]


text:
Q: drag and drop of content from the googledocs pdf in the iframe is not working. When I drag and drop the content of the pdf from the googledocs in the iframe is not working in any browser. I hope that as Google docs provides security so its not allowing drag and drop effect from the Google docs pdf. I'm not sure
How to drag the content from the google docs pdf?
Thanks in advance.


text:
Q: Adding labels to cut points with mapply I have data as follows:
library(data.table)
library(Hmisc)
dat <- structure(list(Inc= c(120995, 238097.2, 103993.9, 93801,
255422.769863014, 257038.28739726, 1045388.66465753, 1040685.40328767,
715660.096547945, 484324), value = list(c(0, 15659.7, 78212.8,
419000, 1e+09), c(0, 16136.4, 89658.3, 464800, 1e+09), c(25075,
98208.05, 164627, 276586.59, 1e+09), c(25003.35, 91842, 149675.7,
256661.25, 1e+09), c(25024.7, 54664.75, 123463.2, 258610.05,
1e+09), c(25081, 56070, 120899.15, 282341.03, 1e+09), c(44852.9,
299214, 514994.25, 802947.38, 1e+09), c(36074, 311042.59, 528348.81,
754085.44, 1e+09), c(25540.8, 181958.59, 326804.69, 538702.19,
1e+09), c(28311.2, 175799.41, 316315, 507802.56, 1e+09))), row.names = c(NA,
-10L), class = c("data.table", "data.frame"))

Each row in value column has 5 values. With cut2, I can use those values as cut points as follows:
dat <- setDT(dat)[, cats:= mapply(Hmisc:: cut2, Inc, value, oneval=FALSE)]

The problem is that ?cut2 does not seem to allow using labels. As a result I tried cut, but whatever I do, it says that the labels and the categories do not match up.
dat <- setDT(dat)[, cats := mapply(cut, Inc, breaks=value, labels=c("cat1", "cat2", "cat3", "cat4"))]

Desired output:
          Inc                                                            value cats
 1:  120995.0      0.00000e+00,1.56597e+04,7.82128e+04,4.19000e+05,1.00000e+09 cat3
 2:  238097.2      0.00000e+00,1.61364e+04,8.96583e+04,4.64800e+05,1.00000e+09 cat3
 3:  103993.9 2.507500e+04,9.820805e+04,1.646270e+05,2.765866e+05,1.000000e+09 cat2
 ...
10:  484324.0      28311.2,    175799.4,    316315.0,    507802.6,1000000000.0 cat3

A: Since you already have the intervals in column value (perhaps as a result of a cut() elsewhere) you could use findInterval() as follows:
setDT(dat)[, cats:= paste0('cat', mapply(FUN = findInterval, x = Inc, vec = value))]

(make sure that the breaks in value are ordered)

A: You could use santoku::chop():
setDT(dat)[, cats := mapply(chop, Inc, value,
                       MoreArgs = list(labels = letters[1:4]))]


text:
Q: how to search string inside another string in system verilog? If I want to know if string a is included string qwerty, is there an easy way to do this in system verilog? Like below code in C?
a.strstr("qwerty");

A: currently i do it this way, it works. but i am wondering if there is a better way...
int len = a.len();
for( int i =0; i < len;i++) begin
    if(a.substr(i,i+6-1) =="qwerty")
       $display("found it");
end

A: You can use the svlib library from Verilab that wraps the C functions we know and love in SystemVerilog functions. It provides its own Str class that can tell you if a string contains a certain substring:
Str my_str = Str::create(a);
if my_str.first("qwerty")
  $display("found it");

You can find svlib at this location

A: Based on the answer by awill I coded these two functions:
function int contains(string a, string b);
  // checks if string A contains string B
  int len_a;
  int len_b;
  len_a = a.len();
  len_b = b.len();
  $display("a (%s) len %d -- b (%s) len %d", a, len_a, b, len_b);
  for( int i=0; i<len_a; i++) begin
    if(a.substr(i,i+len_b-1) == b)
         return 1;
  end
  return 0;
endfunction

function int startswith(string a, string b);
  // checks if string A starts-with string B
  int len_b;
  len_b = b.len();
  if(a.substr(0, len_b-1) == b)
    return 1;
  return 0;
endfunction

A:     module test;
      string mainString = "hello world";
      string subString = "rld";

      initial begin
        for (int i=0; i<mainString.len()-subString.len()+1; i++) begin
          if( mainString.substr(i,i+subString.len()-1) == subString ) begin
            $display("\n it Contraints \n");
          end
        end
      end
  endmodule


text:
Q: So strange result of wp_query and have_posts I've tested some piece of simple code, but the result is so so strange.
Test 1:
$featured_posts = new WP_Query( $query_args );
while ($featured_posts->have_posts()) {
    $featured_posts->the_post();
    the_title(); echo '
';
}
echo 'End: "' . $featured_posts->have_posts() . '"'; // have_post() is TRUE, WHY?

Test 2:
$featured_posts = new WP_Query( $query_args );
$have_posts = $featured_posts->have_posts();
while ($have_posts) {
    $featured_posts->the_post();
    the_title(); echo '
';
    $have_posts = $featured_posts->have_posts();
}
echo 'End: "' . $have_posts . '"'; // false -> I think false is right.
echo 'End: "' . $featured_posts->have_posts() . '"'; // but still TRUE, WHY?

Am I missing anything?

A: If we look at have_posts() in source, we can see why this happens:
function have_posts() {
    if ( $this->current_post + 1 < $this->post_count ) {
        return true;
    } elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
        do_action_ref_array('loop_end', array(&$this));
        // Do some cleaning up after the loop
        $this->rewind_posts();
    }

    $this->in_the_loop = false;
    return false;
}

When it reaches the end of the loop, it calls rewind_posts, which resets current_post back to -1, so the next call to have_posts will return true again.
function rewind_posts() {
    $this->current_post = -1;
    if ( $this->post_count > 0 ) {
        $this->post = $this->posts[0];
    }
}


text:
Q: How to add dynamic data to an ExpandableListView? Given static data, how can I add dynamic data using JSON and REST and how will I get data on the server please give me any solution please
http://examples.javacodegeeks.com/android/core/ui/expandablelistview/android-expandablelistview-example/

A: Filling dynamic data to expandable listview is almost similar like static data. Just collect your dynamic data and store it in an ArrayList and load it similarly how you added static data
In order to fetch data from server please follow the steps here
first compile you dependency in build.gradle file
compile 'com.mcxiaoke.volley:library-aar:1.0.0'

Now create a class named Appcontroller which extends Application and add this and import those api which is showing red line
public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;

    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());

        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        int socketTimeOut = 60000;
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeOut, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        req.setRetryPolicy(policy);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }

    public static String getDate() {
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        Date date = new Date();
        String formatedDate = dateFormat.format(date);
        return formatedDate;
    }
}

after that, to get data from server use this methods
add these two in your class level
Response.Listener<String> jsonResponse;
Response.ErrorListener errorListener;

Now, initialize those within onCreate
jsonResponse = new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.d("Response", response);

        //parseData(response); and store in arraylist to show it in expandablelistview

    }
};

errorListener = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError volleyError) {
        Toast.makeText(getApplicationContext(), "Unable to fetch Data from server", Toast.LENGTH_SHORT).show();
        finish();
    }
};
if (ServerConfig.isNetworkOnline(SplashScreen.this)) {
    StringRequest strReq = new StringRequest(Request.Method.POST, "your server link", serverResponse, errorListener) {
    };
    AppController.getInstance().getRequestQueue().add(strReq);
} else {
    Toast.makeText(getApplicationContext(), "Please check your network connection", Toast.LENGTH_SHORT).show();
    finish();
}

if problem let me know and dont forget to add Appcontroller to your
manifest
<application
    android:name=".AppController"..../>


text:
Q: How to preserve an in memory datastructure to later use it in a Unit test In my code, I am occasionally passed various byte arrays and such. Also, they may be managed objects. I would like to preserve those memory structures so that I can write test cases against the concrete examples.
My standard approach is to hit the breakpoint, use the debugger to find the various values and then either new them up or embed a file or something in the unit test assembly as a resource.
Sometimes, this involves writing my own abstraction of the component interaction to make my code depending on something that can be new'ed up.
Is there an easier way? I cannot imagine that this is something new. Let's say that you are given a fire central unit to communicate with. You play around with it to make it produce its datagrams, which you want to create for your unit tests. Also, when you encounter a bug due to some undocumented way that the fire central is composing its composite messages, you want to record and preserve those examples.
Ideally, I would like to be able to record all interaction to my code and then pick and choose various playback scenarios. But just getting the various datagram examples in-memory from the debugger and put it back into a unit test would help me a lot.
Any suggestions?

A: Try with binary serialization.
The above is specifically for the part where you want to save/load the info or some objects holding info that you use to test the interaction with that external system. I prefer to call those tests focused integration tests, to better capture the difference of focus from the unit tests of the rest of your code with other logic you may have.
Try to separate the code that does the specific integration with the external system from the rest of the code in your system. I suggest to put it behind an interface, that you can replace/mock when creating your unit tests for the rest of the system. This way you can have specifically crafted scenarios that test several aspects/logic of your code without hitting the external system - which also means you can run lots of them in seconds.

A: As Freddy Rios hints in his answer, you need some way of persisting the in-memory object so that you can reuse it from your unit tests. The Memento design pattern is a good start, and serialization is the default .NET way of implementing it.
That leaves the question on how to easily capture those objects. Here's an approach that you can try:
Abstract the communication to and from your resource behind an interface. That is always a good design decision.
When you do that, you can use the Decorator design pattern to wrap your real implementation of that interface. This means that you can create a Decorator that simply records (serializes) the interaction, but delegates all calls to an underlying implementation after it has recorded the objects in question.
When you troubleshoot, you can hook your code up to the Memento Decorator and later pick up the files whereever they where written. For production code, you simply skip the Memento Decorator and directly use the real implementation.
If you want to be really fancy, you can even implement the Memento Decorator so that it emits unit test code that mimics the interaction that was recorded, but this is likely to require a fair amount of effort...


text:
Q: Pods are not getting created on one of the agent node in Kubernetes I am using kubernetes cluster with 3 master and 3 agents which is created using Azure container service (ACS).
I have created the 50+ deployments using helm with one pod each and it is working fine. Out of three agents, only two agents are hosting half deployments on it. The third agent doesn't have any pod created on it except system/kubernetes created pods.
Any inputs will be helpful. Thanks in advance.

A: run the kubectl describe node <3rdagent name> command and check Taints is set for NoSchedule
https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/
if not you can label this node and schedule the pod on this with label see its runs on this node.


text:
Q: What is the best convention to define endpoints in Rest APIs? I read an article on the internet which says to avoid rest end points naming with actions that we are trying to deal with ,rather than mentioning the actions use plural form of the entity that we are dealing with for an example if we are using with users then name the end points like api/users so this is really okay for a scenario which  have less end points which means having always different http request types.For an example if we consider the API there is only one type of @Get mapping , other types also same so in a scenario of having multiple end points with the same http request method what is the best way to name those end points?

A: There's are very subtle different between what is RESTful services and what are webservices. From the spring official docs :

*

*Pretty URLs like /employees/3 aren't REST.

*Merely using GET, POST, etc. aren't REST.

*Having all the CRUD operations laid out aren't REST.
The web services which you've referred are known as RPC(Remote Procedure Call)

To get what a flavor of RESTful , Use Spring HATEOS a Spring project aimed at helping you write hypermedia-driven outputs. This tiny library/dependency will give us the constructs to define a RESTful service and then render it in an acceptible format for client consumption. You may more read about Spring HATEOS here
A critical ingredient to any RESTful service is adding links to relevant operations.
Now over to your Question,The REST end points which we get as feature in spring DATA REST and are HATEOS compliance (for CRUD operations) :

*

*GET mapping at http://localhost:8080/users/ to list all entities.

*GET mapping at http://localhost:8080/users/<existing_user_id> to list a single entity

*POST mapping at http://localhost:8080/users/ along with body of JSON/XML to create a
new entity.

*PUT mapping at http://localhost:8080/users/<existing_user_id> to update a particular
id  with updated content in body.

*DELETE mapping at http://localhost:8080/users/<existing_user_id> to delete an entity.
As you have observed by just seeing the url no one can guess what actions will take,
it all depends on HTTP method type.
If you want to read more about REST and HATEOS ( which provide a lot more features
than CRUD such as pagiantion, sorting etc.)
Refer to these official Spring documentation on HATEOS and RESTful services

A: The only naming conventions that is generally followed in naming the APIs is to avoid verbs.
eg. if you want to upsert(insert/update) a user, POST /api/user will be good.
Getting a user -> GET /api/user/{id}
Getting all users -> GET /api/users
If you have any specific requirements, as such, you can mention here.

A: You should check this article about Richardson Maturity Model : https://martinfowler.com/articles/richardsonMaturityModel.html
It contains all information to make well designed RESTful API


text:
Q: XML Parsing using C# from API Response i am getting response from an API like this
<OrbiscomResponse IssuerId="5" ReturnCode="Success" Version="12.2">
    <CreateApprovedPurchaseResponse PurchaseId="87654321" Status="A">
        <CPN AVV="123" Expiry="1407" Id="123456789" PAN="5555444433332222"</CPN>
    </CreateApprovedPurchaseResponse>
</OrbiscomResponse>

I want to save the PurchaseId, AVV, Expiry, PAN into my local database. Kindly let me know how can i retrieve the data related with these values from XML using C#.

A: Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
                "<OrbiscomResponse IssuerId=\"5\" ReturnCode=\"Success\" Version=\"12.2\">" +
                    "<CreateApprovedPurchaseResponse PurchaseId=\"87654321\" Status=\"A\">" +
                        "<CPN AVV=\"123\" Expiry=\"1407\" Id=\"123456789\" PAN=\"5555444433332222\"/>" +
                    "</CreateApprovedPurchaseResponse>" +
                "</OrbiscomResponse>";

            XElement response = XElement.Parse(xml);

            int purchaseId = int.Parse(response.Descendants("CreateApprovedPurchaseResponse").Attributes("PurchaseId").FirstOrDefault().Value);
            int avw = int.Parse(response.Descendants("CPN").FirstOrDefault().Attribute("AVV").Value);
            int expiry = int.Parse(response.Descendants("CPN").Attributes("Expiry").FirstOrDefault().Value);
            string pan = response.Descendants("CPN").Attributes("PAN").FirstOrDefault().Value;
        }
    }
}