问:
Morningstar.com login using Python Requests
I am trying to log in to my Morningstar.com premium account using the requests module in python as below. The post command runs through with status 200 but does not actually log me in.

(When I download the balance sheet, I only receive the 5 year (non-premium) version instead of the requested 10 year (premium) version. This indicates that my login script fails, since the 5 year data is available without login. The balance sheet URL works correctly right when logging in manually in the browser.)

Does anybody know how to correctly set up the login script?

It seems very straight forward but I have tried the whole day using different forms of the payload/ headers etc. and can't find the right way... Also, I am confused since I cannot find the Form Data information when inspecting the login page.

```<code>import csv
import requests

urlLogin = 'http://members.morningstar.com/memberservice/login.aspx'
urlBalanceSheet = 'http://financials.morningstar.com/ajax/ReportProcess4CSV.html?&t=XNYS:F&region=usa&culture=en-US&cur=&reportType=bs&period=12&dataType=A&order=desc&columnYear=10&rounding=1&view=raw&r=149906&denominatorView=raw&number=1'

payload = {
    "uEmail": "<userEmail>",
    "uPassword": "<userPW>",
    "remember_me": "on",
    "login": "Sign In"
}

with requests.Session() as s:
    p = s.post(urlLogin, data = payload)
    print(p.status_code)

    download = s.get(urlBalanceSheet)
</code>```

答:
There are few things you can do to automate downloading from morningstar

pip install selenium
http://selenium-python.readthedocs.io/installation.html

install firefox, find out where your profile is here is an resource http://toolsqa.com/selenium-webdriver/custom-firefox-profile/

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time
import requests
from xml.etree import cElementTree as ET
import csv
from selenium.webdriver.common.action_chains import ActionChains

def timeme(method):
    def wrapper(*args, **kw):
        startTime = int(round(time.time() * 1000))
        result = method(*args, **kw)
        endTime = int(round(time.time() * 1000))

        print(endTime - startTime, 'ms')
        return result

    return wrapper

class Driver():
    def __init__(self,profile, diver_path, url):
        self.profile = profile
        self.driver_path = diver_path
        self.url = url

    def start_driver(self):
        user_profile = webdriver.FirefoxProfile(self.profile)
        user_profile.set_preference("browser.helperApps.neverAsk.saveToDisk", 'text/csv')

        driver = webdriver.Firefox(executable_path=self.driver_path, firefox_profile=user_profile)
        driver.get(self.url)

        return driver

    def shutdown(self,driver):

        driver.quit()

@timeme
def login(driver, email = '', password = ''):

    wait_time = 1

    try:

        email_input = WebDriverWait(driver,wait_time).until(
        EC.presence_of_all_elements_located((By.XPATH,'//*[@id="uim-uEmail-input"]')))

        email_input = driver.find_element_by_xpath('//*[@id="uim-uEmail-input"]').send_keys(email)

        time.sleep(5) # wait time to see if you have input remove later
        pwd_input = driver.find_element_by_xpath('//*[@id="uim-uPassword-input"]').send_keys(password)
        time.sleep(5)
        sign_in = driver.find_element_by_xpath('//*[@id="uim-login-submit"]').click()

        title = driver.title
        driver.execute_script("window.open('http://financials.morningstar.com/ajax/ReportProcess4CSV.html?&t=XNYS:F&region=usa&culture=en-US&cur=&reportType=bs&period=12&dataType=A&order=desc&columnYear=10&rounding=1&view=raw&r=149906&denominatorView=raw&number=1','new_window');")
        time.sleep(1)

        return 0
    except Exception as e:

        return None

@timeme
def main():
    # i am using on my mac, if you are using windows change paths accordingly
    Mozilla  = Driver(profile = '/Users/yourname/Library/Application Support/Firefox/Profiles/xxxxxxxxxxxx.default',
           diver_path='/usr/local/bin/geckodriver', # path to firefox driver
           url='https://www.morningstar.com/members/login.html?vurl=')

    driver = Mozilla.start_driver()
    download = login(driver, password='', email='')
    if download ==0:
       time.sleep(10) # let browser to download csv

       Mozilla.shutdown(driver) # shutdown

main()
</code>```

Body:
I am trying to log in to my Morningstar.com premium account using the requests module in python as below. The post command runs through with status 200 but does not actually log me in.

(When I download the balance sheet, I only receive the 5 year (non-premium) version instead of the requested 10 year (premium) version. This indicates that my login script fails, since the 5 year data is available without login. The balance sheet URL works correctly right when logging in manually in the browser.)

Does anybody know how to correctly set up the login script?

It seems very straight forward but I have tried the whole day using different forms of the payload/ headers etc. and can't find the right way... Also, I am confused since I cannot find the Form Data information when inspecting the login page.

import csv
import requests

urlLogin = 'http://members.morningstar.com/memberservice/login.aspx'
urlBalanceSheet = 'http://financials.morningstar.com/ajax/ReportProcess4CSV.html?&t=XNYS:F&region=usa&culture=en-US&cur=&reportType=bs&period=12&dataType=A&order=desc&columnYear=10&rounding=1&view=raw&r=149906&denominatorView=raw&number=1'

payload = {
    "uEmail": "<userEmail>",
    "uPassword": "<userPW>",
    "remember_me": "on",
    "login": "Sign In"
}

with requests.Session() as s:
    p = s.post(urlLogin, data = payload)
    print(p.status_code)

    download = s.get(urlBalanceSheet)

Body:
There are few things you can do to automate downloading from morningstar

pip install selenium
http://selenium-python.readthedocs.io/installation.html

install firefox, find out where your profile is here is an resource http://toolsqa.com/selenium-webdriver/custom-firefox-profile/

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time
import requests
from xml.etree import cElementTree as ET
import csv
from selenium.webdriver.common.action_chains import ActionChains

def timeme(method):
    def wrapper(*args, **kw):
        startTime = int(round(time.time() * 1000))
        result = method(*args, **kw)
        endTime = int(round(time.time() * 1000))

        print(endTime - startTime, 'ms')
        return result

    return wrapper

class Driver():
    def __init__(self,profile, diver_path, url):
        self.profile = profile
        self.driver_path = diver_path
        self.url = url

    def start_driver(self):
        user_profile = webdriver.FirefoxProfile(self.profile)
        user_profile.set_preference("browser.helperApps.neverAsk.saveToDisk", 'text/csv')

        driver = webdriver.Firefox(executable_path=self.driver_path, firefox_profile=user_profile)
        driver.get(self.url)

        return driver

    def shutdown(self,driver):

        driver.quit()

@timeme
def login(driver, email = '', password = ''):

    wait_time = 1

    try:

        email_input = WebDriverWait(driver,wait_time).until(
        EC.presence_of_all_elements_located((By.XPATH,'//*[@id="uim-uEmail-input"]')))

        email_input = driver.find_element_by_xpath('//*[@id="uim-uEmail-input"]').send_keys(email)

        time.sleep(5) # wait time to see if you have input remove later
        pwd_input = driver.find_element_by_xpath('//*[@id="uim-uPassword-input"]').send_keys(password)
        time.sleep(5)
        sign_in = driver.find_element_by_xpath('//*[@id="uim-login-submit"]').click()

        title = driver.title
        driver.execute_script("window.open('http://financials.morningstar.com/ajax/ReportProcess4CSV.html?&t=XNYS:F&region=usa&culture=en-US&cur=&reportType=bs&period=12&dataType=A&order=desc&columnYear=10&rounding=1&view=raw&r=149906&denominatorView=raw&number=1','new_window');")
        time.sleep(1)

        return 0
    except Exception as e:

        return None

@timeme
def main():
    # i am using on my mac, if you are using windows change paths accordingly
    Mozilla  = Driver(profile = '/Users/yourname/Library/Application Support/Firefox/Profiles/xxxxxxxxxxxx.default',
           diver_path='/usr/local/bin/geckodriver', # path to firefox driver
           url='https://www.morningstar.com/members/login.html?vurl=')

    driver = Mozilla.start_driver()
    download = login(driver, password='', email='')
    if download ==0:
       time.sleep(10) # let browser to download csv

       Mozilla.shutdown(driver) # shutdown

main()


来源: stackexchange

问:
Mixing fPIC and non-fPIC object modules
Environment: Ubuntu 16.04

In my experiment, I ran the following commands:

```<code>gcc -c 1.c
gcc -c -fPIC 2.c
gcc -shared 1.o 2.o -o libmyxxx.so
</code>```

The functions that I need to expose are all defined in 2.c via extern "C" declarations. These functions internally call other functions that are defined in 1.c.

Note that I did not apply -fPIC to 1.c. Still everything seems to compile/link fine without any warnings.

Can we conclude that -fPIC must be applied only to those source files that expose external functions?

In the larger picture, I have a bunch of archive (.a) files that may not have been compiled with -fPIC flag. I need to create a custom shared library that would link with these archive files. If my assumption is valid, I am thinking it would be okay to link with these archive files. Appreciate your thoughts. Regards.

答:
If there is an object file in the executable, that is compiled without -fPIC flag, there will be pages of program text that have position dependent memory references. These pages won't be able to be relocated to suitable virtual memory addresses at run time (which is mostly the purpose of shared objects). When you build your code on some other machine or link the .so to some other code, these position dependent memory references will come and bight you.

-fPIC is required to generate position independent code for:

global variables

static variables

external variables

string constants

taking addresses of the function

Also, you might get away without any warning or error when compiling/linking an object file without -fPIC on Linux/x86-32; but it is impossible to do that on some architectures.

ContentLicense: CC BY-SA 3.0

Title: Mixing fPIC and non-fPIC object modules

Body:
Environment: Ubuntu 16.04

In my experiment, I ran the following commands:

gcc -c 1.c
gcc -c -fPIC 2.c
gcc -shared 1.o 2.o -o libmyxxx.so

The functions that I need to expose are all defined in 2.c via extern "C" declarations. These functions internally call other functions that are defined in 1.c.

Note that I did not apply -fPIC to 1.c. Still everything seems to compile/link fine without any warnings.

Can we conclude that -fPIC must be applied only to those source files that expose external functions?

In the larger picture, I have a bunch of archive (.a) files that may not have been compiled with -fPIC flag. I need to create a custom shared library that would link with these archive files. If my assumption is valid, I am thinking it would be okay to link with these archive files. Appreciate your thoughts. Regards.

ContentLicense: CC BY-SA 4.0


问:
Is it possible to use NGen with ClickOnce deployment?
Is it possible to use NGen with ClickOnce deployment?</p>

答: No, you can not. See http://social.msdn.microsoft.com/Forums/en-US/clr/thread/a41b62c5-bdee-4bd5-9811-15a35c4a4add/. You need to create a regular installer file for that.</p>

OwnerDisplayName: Branko

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rich B


问:
How to change inline code appearance with custom css in RMarkdown
I can  change code appearance with custom css for code chunks (font family Arial in my example)

```<code>code.r{ /* Code block */
     font-family: arial;
}
</code>```

How can I do this for inline  code?

答:
Unevaluated inline code is contained inside a code element with no class:

```<code>`round(pi, 3)`
</code>```

leads to

```<code><code>round(pi, 3)</code>
</code>```

Therefore using the CSS selector code {} is sufficient.

Body:
I can  change code appearance with custom css for code chunks (font family Arial in my example)

code.r{ /* Code block */
     font-family: arial;
}

How can I do this for inline  code?

Body:
Unevaluated inline code is contained inside a code element with no class:

`round(pi, 3)`

leads to

<code>round(pi, 3)</code>

Therefore using the CSS selector code {} is sufficient.


问:
Why are my points not being plotted?
I am currently creating a graph that that analyzes the correlation of absorption and concentration (Beer's law). While creating the graph, I've ran into a few problems, and I am now stuck. My plots are not showing up within my graph. Is it due to placement error? If possible, I would like to leave the ticks, labels, and title in the same (or similar format). Sorry in advance for the sloppiness, trying to get the function down before I make it pretty. But anyways, here is the code:</p>

```<code>#importing matplotlib to create a graph
import matplotlib.pyplot as plt

#ploting out the points while labeling the graph
plt.plot([1.95E-06, 9.75E-06, 1.95E-05, 9.75E-05, 1.95E-04, 9.75E-04, 1.95E-
03],[0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.xticks([1, 2, 3, 4, 5, 6, 7], [str('1.95E-03'), str('9.75E-04'),
str('1.95E-04'), str('9.75E-05'),str('1.95E-05'), str('9.75E-06'),
str('1.95E-06')])
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.show()
</code>```

答:
Your xticks are completely out of the range where your data lives. Remove the line which sets the xticks and your plot is fine

```<code>import matplotlib.pyplot as plt

plt.plot([1.95E-06, 9.75E-06, 1.95E-05, 9.75E-05, 1.95E-04, 9.75E-04, 1.95E-03],
         [0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.show()
</code>```

If you want to use your custom ticks, you need to set them in the data range, i.e. somewhere between 0 and 0.002 and not between 1 and 7.

Title: Why are my points not being plotted?

Body:
I am currently creating a graph that that analyzes the correlation of absorption and concentration (Beer's law). While creating the graph, I've ran into a few problems, and I am now stuck. My plots are not showing up within my graph. Is it due to placement error? If possible, I would like to leave the ticks, labels, and title in the same (or similar format). Sorry in advance for the sloppiness, trying to get the function down before I make it pretty. But anyways, here is the code:

#importing matplotlib to create a graph
import matplotlib.pyplot as plt

#ploting out the points while labeling the graph
plt.plot([1.95E-06, 9.75E-06, 1.95E-05, 9.75E-05, 1.95E-04, 9.75E-04, 1.95E-
03],[0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.xticks([1, 2, 3, 4, 5, 6, 7], [str('1.95E-03'), str('9.75E-04'),
str('1.95E-04'), str('9.75E-05'),str('1.95E-05'), str('9.75E-06'),
str('1.95E-06')])
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.show()

Body:
Your xticks are completely out of the range where your data lives. Remove the line which sets the xticks and your plot is fine

import matplotlib.pyplot as plt

plt.plot([1.95E-06, 9.75E-06, 1.95E-05, 9.75E-05, 1.95E-04, 9.75E-04, 1.95E-03],
         [0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.show()

If you want to use your custom ticks, you need to set them in the data range, i.e. somewhere between 0 and 0.002 and not between 1 and 7.


问:
tableview max width constraint
I'm trying to set a max width on a tableview inside the default tableview controller in the storyboard. I'm not able to just set a <= width constraint for some reason it's greyed out in xcode.

I would just create a custom tableview inside my view but I've configured somethings that won't work that way with scroll without some work.

I'm trying to restrict the width for a scrolling feed with images so the ipad version isn't full screen. Just max say like 700 or something, any idea how to do that?

Standard xcode tableview controller

custom table view in view controller

This kind of worked, but it jumps into place and shows black bars on the side.

```<code>override func viewDidAppear(_ animated: Bool) {
    let bounds = UIScreen.main.bounds
    if bounds.width > 414 {
        tableView.frame.size.width = CGFloat(600)
        tableView.center.x = bounds.size.width / 2
    }
}
</code>```

答:
You can't alter the frame of the UITableView of a UITableViewController because it is the root view of the controller.  If you want a UITableView to not take up the full width then you should create a UIViewController and add the UITableView to that.  If you do that the UIViewController will have its own UIView which is the root.

You say you are trying to set up your app so that it doesn't occupy the full screen on an iPad just 700 wide.  Unfortunately you can't do that you apps main window always takes up the entire display so even if you have a root view that was transparent you won't see the main iOS interface through it as your main window will block it (I think it would be black).

Title: tableview max width constraint

Body:
I'm trying to set a max width on a tableview inside the default tableview controller in the storyboard. I'm not able to just set a <= width constraint for some reason it's greyed out in xcode.

I would just create a custom tableview inside my view but I've configured somethings that won't work that way with scroll without some work.

I'm trying to restrict the width for a scrolling feed with images so the ipad version isn't full screen. Just max say like 700 or something, any idea how to do that?

Standard xcode tableview controller

custom table view in view controller

This kind of worked, but it jumps into place and shows black bars on the side.

override func viewDidAppear(_ animated: Bool) {
    let bounds = UIScreen.main.bounds
    if bounds.width > 414 {
        tableView.frame.size.width = CGFloat(600)
        tableView.center.x = bounds.size.width / 2
    }
}


问:
Unexpected Token in JSX (React Component)
I am sorry if this is the wrong place to ask something like this, but I cannot find this error for the life of me. I even slept on it and tried for another couple hours this morning.

This is my error:

```<code>ERROR in ./src/components/results_instructor_view/weekly_report_results_instructor.js
Module build failed: SyntaxError: C:/Users/Temple/Source/Workspaces/LMS/TechAcademyLMS/TechAcademyLMS/Scripts/React-Redux-App/src/components/results_instructor_view/weekly_report_results_instructor.js: Unexpected token, expected , (139:4)

  137 |
  138 |
> 139 |                 } else {
      |                   ^
  140 |
  141 |                         return (<h6>No weekly reports yet</h6>);
  142 |                 }

 @ ./src/containers/main_display_container.js 85:40-121
 @ ./src/components/app.js
 @ ./src/routes.js
 @ ./src/Index.js
</code>```

This is my code:

```<code>// libraries
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

// Loader
import Loader from '../../components/loader/loader';

//actions
import { resultsInstructorViewAction } from '../../actions/Results/results_instructor_view_action';

class WeeklyReportResult extends Component {

    componentDidMount() {
        // getting the user info from the props/params
        const userInfo = this.props.match.params.value.split(',');
        // url for the getWeeklyReport
        const url = `/SPA/getWeeklyReport?Id=${userInfo[1]}`;

        this.props.resultsInstructorViewAction(url);
    }

    componentDidUpdate(prevProps, prevState) {

        // set loaded to true
        if (this.state.Loaded === false) {

            this.setState({ Loaded: true });
        }

    }

    render() {

        // checking to see if the data exists
        if (this.props.resultsInstructorView > [0]) {
            const renderList = this.props.resultsInstructorView.map((item, i) => {
                return (
                    // Key for error in console due to mapping
                    <div key={i}>
                        <hr className="style-two" />
                        <h4>Date Submitted: </h4><p>{item.Date}</p>
                        <h5>Course Position: </h5><p>{item.CoursePosition}</p>
                        <h5>Need Help: </h5><p>{item.NeedHelp}</p>
                        <h5>Materials and Supplies Needed: </h5><p>{item.MaterialsAndSupplies}</p>
                        <h5>Meetups: </h5><p>{item.Meetups}</p>
                        <h5>Positive Experiences: </h5><p>{item.Positives}</p>
                        <h5>Complaints: </h5><p>{item.Complaints}</p>
                        <h5>Hours Studied: </h5><p>{item.HoursStudied}</p>
                        <h5>Job Search: </h5><p>{item.JobSearch}</p>
                        <h5>Referral: </h5><p>{item.Referral}</p>
                        <h5>Miscellaneous: </h5><p>{item.Miscellaneous}</p>

                    <button type="button" className="btn btn-info btn-lg" onClick={this.toggleModal} id={item.DailyReportId}>
                                Give Feedback
                    </button>
                    </div>
            );
        });
    }

                    // building the already responded daily reports
const renderAllList = this.props.resultsInstructorView.map((item, i) => {
    if (item.Feedbacks.length > 0) {

        return (

            <Panel key={i} header={item.Date} eventKey={i} bsStyle="primary" className="text-center">
                <hr className="style-two" />
                <div className="text-left">
                    <h6><strong>Date Submitted :</strong> {item.Date}</h6>
                    <h6><strong>Course Position : </strong>{item.CoursePosition}</h6>
                    <h6><strong>Need Help : </strong>{item.NeedHelp}</h6>
                    <h6><strong>Materials and Supplies :</strong> {item.MaterialsAndSupplies}</h6>
                    <h6><strong>Positives : </strong>{item.Positives}</h6>
                    <h6><strong>Complaints :</strong> {item.Complaints}</h6>
                    <h6><strong>Hours Studied :</strong> {item.HoursStudied}</h6>
                    <h6><strong>Job Search :</strong> {item.JobSearch}</h6>
                    <h6><strong>Referral :</strong> {item.Referral}</h6>
                    <h6><strong>Miscellaneous :</strong> {item.Miscellaneous}</h6>
                    <h6><strong>Instructor Feedback : </strong><mark>{item.Feedbacks[0].Content}</mark></h6>
                </div>

            </Panel>
        );
}

            return (
                <div className="container text-center">

                    <div className="row">
                        <h1>Weekly Reports</h1>
                        <h3>Student Name: </h3><h5>{this.props.match.params.value.split(',')[2]}</h5>

                    </div>

                    <div className="col-sm-12 text-left">

                        {renderList}

                        <hr className="style-two" />
                            <h2 className="text-center">Past Reports</h2>

                            <Accordion>
                                {renderAllList}
                            </Accordion>
                            <FeedbackModal
                                show={this.state.isOpen}
                                toggleModal={this.toggleModal}
                                name={this.props.match.params.value.split(',')[0]}
                                id={this.props.match.params.value.split(',')[1]}
                                weeklyReportId={this.state.tempId}

                            />

                    </div>

                </div>

            );

        } else {

            return (<h6>No weekly reports yet</h6>);
        }

    }
    }

function mapStateToProps(state) {
    return { resultsInstructorView: state.ResultsInstructorView };
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        resultsInstructorViewAction
    }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(WeeklyReportResult);
</code>```

答:
Honestly, it seems like you're missing a closing bracket for your map function.  Proper code indentation is helpful to find errors like this.

If that's truly the way you want it though, then this is what the error is pointing out. You currently have a code that looks a bit like this:

```<code>  if (item.Feedbacks.length > 0) {
    return (<Panel>...</Panel>)
  }

  return (<div className="container text-center">...</div>)

  else {
    return (<h6>...</h6>)
  }
</code>```

That middle return statement makes the else statement unreachable.

You would need to edit with something like an else if for that middle return statement or place the else clause above the middle return statement.

Though this is a little broader than your question, it might actually solve it. It looks like those other statements shouldn't be in your map function at all.

Body:
I am sorry if this is the wrong place to ask something like this, but I cannot find this error for the life of me. I even slept on it and tried for another couple hours this morning.

This is my error:

ERROR in ./src/components/results_instructor_view/weekly_report_results_instructor.js
Module build failed: SyntaxError: C:/Users/Temple/Source/Workspaces/LMS/TechAcademyLMS/TechAcademyLMS/Scripts/React-Redux-App/src/components/results_instructor_view/weekly_report_results_instructor.js: Unexpected token, expected , (139:4)

  137 |
  138 |
> 139 |                 } else {
      |                   ^
  140 |
  141 |                         return (
No weekly reports yet
);
  142 |                 }

 @ ./src/containers/main_display_container.js 85:40-121
 @ ./src/components/app.js
 @ ./src/routes.js
 @ ./src/Index.js

This is my code:

// libraries
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

// Loader
import Loader from '../../components/loader/loader';

//actions
import { resultsInstructorViewAction } from '../../actions/Results/results_instructor_view_action';

class WeeklyReportResult extends Component {

    componentDidMount() {
        // getting the user info from the props/params
        const userInfo = this.props.match.params.value.split(',');
        // url for the getWeeklyReport
        const url = `/SPA/getWeeklyReport?Id=${userInfo[1]}`;

        this.props.resultsInstructorViewAction(url);
    }

    componentDidUpdate(prevProps, prevState) {

        // set loaded to true
        if (this.state.Loaded === false) {

            this.setState({ Loaded: true });
        }

    }

    render() {

        // checking to see if the data exists
        if (this.props.resultsInstructorView > [0]) {
            const renderList = this.props.resultsInstructorView.map((item, i) => {
                return (
                    // Key for error in console due to mapping

Date Submitted:

{item.Date}

Course Position:

{item.CoursePosition}

Need Help:

{item.NeedHelp}

Materials and Supplies Needed:

{item.MaterialsAndSupplies}

Meetups:

{item.Meetups}

Positive Experiences:

{item.Positives}

Complaints:

{item.Complaints}

Hours Studied:

{item.HoursStudied}

Job Search:

{item.JobSearch}

Referral:

{item.Referral}

Miscellaneous:

{item.Miscellaneous}

                    <button type="button" className="btn btn-info btn-lg" onClick={this.toggleModal} id={item.DailyReportId}>
                                Give Feedback
                    </button>

            );
        });
    }

                    // building the already responded daily reports
const renderAllList = this.props.resultsInstructorView.map((item, i) => {
    if (item.Feedbacks.length > 0) {

        return (

            <Panel key={i} header={item.Date} eventKey={i} bsStyle="primary" className="text-center">

Date Submitted : {item.Date}

Course Position : {item.CoursePosition}

Need Help : {item.NeedHelp}

Materials and Supplies : {item.MaterialsAndSupplies}

Positives : {item.Positives}

Complaints : {item.Complaints}

Hours Studied : {item.HoursStudied}

Job Search : {item.JobSearch}

Referral : {item.Referral}

Miscellaneous : {item.Miscellaneous}

Instructor Feedback : {item.Feedbacks[0].Content}

            </Panel>
        );
}

            return (

Weekly Reports

Student Name:

{this.props.match.params.value.split(',')[2]}

                        {renderList}

Past Reports

                            <Accordion>
                                {renderAllList}
                            </Accordion>
                            <FeedbackModal
                                show={this.state.isOpen}
                                toggleModal={this.toggleModal}
                                name={this.props.match.params.value.split(',')[0]}
                                id={this.props.match.params.value.split(',')[1]}
                                weeklyReportId={this.state.tempId}

                            />

            );

        } else {

            return (
No weekly reports yet
);
        }

    }
    }

function mapStateToProps(state) {
    return { resultsInstructorView: state.ResultsInstructorView };
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        resultsInstructorViewAction
    }, dispatch);
}

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

Body:
Honestly, it seems like you're missing a closing bracket for your map function.  Proper code indentation is helpful to find errors like this.

If that's truly the way you want it though, then this is what the error is pointing out. You currently have a code that looks a bit like this:

  if (item.Feedbacks.length > 0) {
    return (<Panel>...</Panel>)
  }

  return (<div className="container text-center">...</div>)

  else {
    return (<h6>...</h6>)
  }

That middle return statement makes the else statement unreachable.

You would need to edit with something like an else if for that middle return statement or place the else clause above the middle return statement.

Though this is a little broader than your question, it might actually solve it. It looks like those other statements shouldn't be in your map function at all.


问:
Find unique rows in numpy.array
I need to find unique rows in a numpy.array.

For example:

```<code>>>> a # I have
array([[1, 1, 1, 0, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [1, 1, 1, 0, 0, 0],
       [1, 1, 1, 1, 1, 0]])
>>> new_a # I want to get to
array([[1, 1, 1, 0, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [1, 1, 1, 1, 1, 0]])
</code>```

I know that i can create a set and loop over the array, but I am looking for an efficient pure numpy solution. I believe that there is a way to set data type to void and then I could just use numpy.unique, but I couldn't figure out how to make it work.

答:
We can actually turn m x n numeric numpy array into m x 1 numpy string array, please try using the following function, it provides count, inverse_idx and etc, just like numpy.unique:

```<code>import numpy as np

def uniqueRow(a):
    #This function turn m x n numpy array into m x 1 numpy array storing
    #string, and so the np.unique can be used

    #Input: an m x n numpy array (a)
    #Output unique m' x n numpy array (unique), inverse_indx, and counts

    s = np.chararray((a.shape[0],1))
    s[:] = '-'

    b = (a).astype(np.str)

    s2 = np.expand_dims(b[:,0],axis=1) + s + np.expand_dims(b[:,1],axis=1)

    n = a.shape[1] - 2

    for i in range(0,n):
         s2 = s2 + s + np.expand_dims(b[:,i+2],axis=1)

    s3, idx, inv_, c = np.unique(s2,return_index = True,  return_inverse = True, return_counts = True)

    return a[idx], inv_, c
</code>```

Example:

```<code>A = np.array([[ 3.17   9.502  3.291],
  [ 9.984  2.773  6.852],
  [ 1.172  8.885  4.258],
  [ 9.73   7.518  3.227],
  [ 8.113  9.563  9.117],
  [ 9.984  2.773  6.852],
  [ 9.73   7.518  3.227]])

B, inv_, c = uniqueRow(A)

Results:

B:
[[ 1.172  8.885  4.258]
[ 3.17   9.502  3.291]
[ 8.113  9.563  9.117]
[ 9.73   7.518  3.227]
[ 9.984  2.773  6.852]]

inv_:
[3 4 1 0 2 4 0]

c:
[2 1 1 1 2]
</code>```

Title: Find unique rows in numpy.array

Body:
I need to find unique rows in a numpy.array.

For example:

>>> a # I have
array([[1, 1, 1, 0, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [1, 1, 1, 0, 0, 0],
       [1, 1, 1, 1, 1, 0]])
>>> new_a # I want to get to
array([[1, 1, 1, 0, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [1, 1, 1, 1, 1, 0]])

I know that i can create a set and loop over the array, but I am looking for an efficient pure numpy solution. I believe that there is a way to set data type to void and then I could just use numpy.unique, but I couldn't figure out how to make it work.

Body:
We can actually turn m x n numeric numpy array into m x 1 numpy string array, please try using the following function, it provides count, inverse_idx and etc, just like numpy.unique:

import numpy as np

def uniqueRow(a):
    #This function turn m x n numpy array into m x 1 numpy array storing
    #string, and so the np.unique can be used

    #Input: an m x n numpy array (a)
    #Output unique m' x n numpy array (unique), inverse_indx, and counts

    s = np.chararray((a.shape[0],1))
    s[:] = '-'

    b = (a).astype(np.str)

    s2 = np.expand_dims(b[:,0],axis=1) + s + np.expand_dims(b[:,1],axis=1)

    n = a.shape[1] - 2

    for i in range(0,n):
         s2 = s2 + s + np.expand_dims(b[:,i+2],axis=1)

    s3, idx, inv_, c = np.unique(s2,return_index = True,  return_inverse = True, return_counts = True)

    return a[idx], inv_, c

Example:

A = np.array([[ 3.17   9.502  3.291],
  [ 9.984  2.773  6.852],
  [ 1.172  8.885  4.258],
  [ 9.73   7.518  3.227],
  [ 8.113  9.563  9.117],
  [ 9.984  2.773  6.852],
  [ 9.73   7.518  3.227]])

B, inv_, c = uniqueRow(A)

Results:

B:
[[ 1.172  8.885  4.258]
[ 3.17   9.502  3.291]
[ 8.113  9.563  9.117]
[ 9.73   7.518  3.227]
[ 9.984  2.773  6.852]]

inv_:
[3 4 1 0 2 4 0]

c:
[2 1 1 1 2]


问:
Coding in Emacs shell?
I am  using shell in my emacs version 22.2.1 (debian stable repos) and it has some kind of broken coding. For example, if I run `ls' command, output is

```<code>[0m[01;34margouml-0.30.2[0m
</code>```

not "argouml-0.30.2" as normal. I have tried commands C-x RET p utf-8 and so others but without any effect. I have properly generated utf-8 locales and everywhere else in emacs coding works perfect. Does anybody knows what may be wrong with it?

答: Your terminal type in the shell is set incorrectly; those escapes are for colors, but the emacs shell doesn't support them.  Try M-x term instead for better support.

Title: Coding in Emacs shell?

Body:
I am  using shell in my emacs version 22.2.1 (debian stable repos) and it has some kind of broken coding. For example, if I run `ls' command, output is

[0m[01;34margouml-0.30.2[0m

not "argouml-0.30.2" as normal. I have tried commands C-x RET p utf-8 and so others but without any effect. I have properly generated utf-8 locales and everywhere else in emacs coding works perfect. Does anybody knows what may be wrong with it?


问:
What is the IntentFilter that do my app be recognized like having audio to share?
What is the IntentFilter that I have to use in order to my app be recognized as like having audio to share? WhatsApp do not list my app anyway...

Like this:

I already tried:

```<code><intent-filter>
                <action android:name="android.intent.action.SEND" />
                <data android:mimeType="audio/*" />
</intent-filter>

<intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <data android:mimeType="audio/*" />
</intent-filter>
</code>```

and too

```<code><activity
        android:name=".activities.MyActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.PICK" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="audio/*" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.GET_CONTENT" />
        <category android:name="android.intent.category.OPENABLE" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="audio/*" />
    </intent-filter>
</activity>
</code>```

But nothing seems to work...

Anyone knows?

Thx

答:
Add this in manifest:-

```<code><intent-filter . . . >

<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />

<action android:name="com.example.project.SHOW_CURRENT" />
<action android:name="com.example.project.SHOW_RECENT" />
<action android:name="com.example.project.SHOW_PENDING" />

<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="audio/*" />
. . .
</intent-filter>
</code>```

Combine all <intent-filter . . . >
I hope this should work, besides you can follow this guide Guide link

Body:
What is the IntentFilter that I have to use in order to my app be recognized as like having audio to share? WhatsApp do not list my app anyway...

Like this:

I already tried:

<intent-filter>
                <action android:name="android.intent.action.SEND" />
                <data android:mimeType="audio/*" />
</intent-filter>

<intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <data android:mimeType="audio/*" />
</intent-filter>

and too

<activity
        android:name=".activities.MyActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.PICK" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="audio/*" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.GET_CONTENT" />
        <category android:name="android.intent.category.OPENABLE" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="audio/*" />
    </intent-filter>
</activity>

But nothing seems to work...

Anyone knows?

Thx

Body:
Add this in manifest:-

<intent-filter . . . >

<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />

<action android:name="com.example.project.SHOW_CURRENT" />
<action android:name="com.example.project.SHOW_RECENT" />
<action android:name="com.example.project.SHOW_PENDING" />

<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="audio/*" />
. . .
</intent-filter>

Combine all <intent-filter . . . >
I hope this should work, besides you can follow this guide Guide link


答: The first argument to plt.xticks should be x-coords (not tick indexes).

Title: Why are my points not being plotted?


问:
Not understandable content loadtxt csv from excel
1) given below txt file:

2) import straight into array:

```<code>from numpy import loadtxt

def TestImport():
    HeadersPath = 'C:/mypath/Headers_20170602.txt'
    Header = loadtxt(HeadersPath,dtype=str,delimiter="/t" )

    print Header

TestImport()
</code>```

3) gives me the following output:

```<code>%run "C:/mypath/TestCSVImport.py"
['\xff\xfe1\x00\t\x002\x00\t\x003\x00\t\x004' '' '']
</code>```

Why don't I see 1,2,3,4?

答:
Consider using Pandas module:

```<code>import pandas as pd

arr = pd.read_csv(r'/path/to/file.csv', sep='\t', header=None).values
</code>```

or:

```<code>arr = pd.read_csv(r'/path/to/file.csv', sep='\t', header=None, encoding='utf-16').values
</code>```

Body:
1) given below txt file:

2) import straight into array:

from numpy import loadtxt

def TestImport():
    HeadersPath = 'C:/mypath/Headers_20170602.txt'
    Header = loadtxt(HeadersPath,dtype=str,delimiter="/t" )

    print Header

TestImport()

3) gives me the following output:

%run "C:/mypath/TestCSVImport.py"
['\xff\xfe1\x00\t\x002\x00\t\x003\x00\t\x004' '' '']

Why don't I see 1,2,3,4?

Body:
Consider using Pandas module:

import pandas as pd

arr = pd.read_csv(r'/path/to/file.csv', sep='\t', header=None).values

or:

arr = pd.read_csv(r'/path/to/file.csv', sep='\t', header=None, encoding='utf-16').values


问:
How to thru char into TextBox?
I have some TextBox on focus ( cursor is blinking on him ).
Now, from other usercontrol ( that contain buttons ) i want to send event that will insert char into the TextBox when pressing any of the buttons that are on the usercontrol.

This need to be without lose the focus from the TextBox ... ( blinking cursor on the TextBox )

How can i do it ?
( i try to raise key down event - but its does not work )

答: Make your buttons to be not focusable (Focusable = false).</p>

Title: How to thru char into TextBox?


问:
How do i show an attribute of an object, rather than the object itself, in an accessor field in django-tables2?
I have a table of Compounds with a name field, which is linked to another table called Names.

When I render a table with django-tables2, it's showing up just fine except for the fact that it doesn't say aspirin in the name column, it says Name object.

models.py:

```<code>class Compound(models.Model):

    drug_id = models.AutoField(primary_key=True)

    drug_name = models.ForeignKey(Name, db_column='drug_name', null=True, on_delete=models.PROTECT)
    # for flagging problematic data
    flag_id = models.ForeignKey(Flag, db_column='flag_id', null=True, on_delete=models.PROTECT)
    # is a cocktail
    is_combination = models.BooleanField()

    class Meta:
        db_table = 'compounds'
</code>```

tables.py:

```<code>import django_tables2 as tables
from .models import Compound

class FimTable(tables.Table):

    drug_name = tables.Column(accessor='name.name')

    class Meta:
        model = Compound
        attrs = {'class': 'paleblue table table-condensed table-vertical-center'}
        fields = ('drug_id', 'drug_name')
        sequence = ('drug_id', 'drug_name')
        order_by = ('drug_id')
</code>```

views.py:

```<code>@csrf_protect
@login_required  # redirects to login page if user.is_active is false
def render_fim_table(request):

    table = FimTable(Compound.objects.all())

    table.paginate(page=request.GET.get('page', 1), per_page=20)

    response = render(request, 'fim_table.html', {'table': table})
    return response
</code>```

Result:

答:
You just need to define the __str__ method on the Name object.

```<code>class Name(models.Model):
    ...

    def __str__(self):
        return self.name
</code>```

Body:
I have a table of Compounds with a name field, which is linked to another table called Names.

When I render a table with django-tables2, it's showing up just fine except for the fact that it doesn't say aspirin in the name column, it says Name object.

models.py:

class Compound(models.Model):

    drug_id = models.AutoField(primary_key=True)

    drug_name = models.ForeignKey(Name, db_column='drug_name', null=True, on_delete=models.PROTECT)
    # for flagging problematic data
    flag_id = models.ForeignKey(Flag, db_column='flag_id', null=True, on_delete=models.PROTECT)
    # is a cocktail
    is_combination = models.BooleanField()

    class Meta:
        db_table = 'compounds'

tables.py:

import django_tables2 as tables
from .models import Compound

class FimTable(tables.Table):

    drug_name = tables.Column(accessor='name.name')

    class Meta:
        model = Compound
        attrs = {'class': 'paleblue table table-condensed table-vertical-center'}
        fields = ('drug_id', 'drug_name')
        sequence = ('drug_id', 'drug_name')
        order_by = ('drug_id')

views.py:

@csrf_protect
@login_required  # redirects to login page if user.is_active is false
def render_fim_table(request):

    table = FimTable(Compound.objects.all())

    table.paginate(page=request.GET.get('page', 1), per_page=20)

    response = render(request, 'fim_table.html', {'table': table})
    return response

Result:

Body:
You just need to define the __str__ method on the Name object.

class Name(models.Model):
    ...

    def __str__(self):
        return self.name


问:
Can't submit form without reloading page
I build a link shortener,just for fun!
Everything works, but everytime I create a link and submit the form, the page reloads! I wanted to prevent that with onclick="return false;"but it didnt work.

```<code><input class="submit" type="submit" value="Create!"  />

$('#contactForm').submit(function () {
    sendContactForm();
    return false;
});
</code>```

But nothing works, the file is just stuck and doesn't do anything! What am I doing from ? This is the problem page https://viid.su
PHP

```<code>   require("db_config.php");
       $uid = 1;
      $flink = $_POST['url'];
      if(!preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $flink)) {
        $html = "Error: invalid URL";
      } else {

        $db = mysqli_connect($host, $username, $password);
        $conn = new mysqli($host, $username, $password, $database);

          $id = substr(md5(time().$flink), 0, 5);
          if($conn->query("INSERT INTO `".$database."`.`link` (`id`, `flink`,`adonly`,`userid`) VALUES ('".$id."', '".$flink."','true','".$uid."');")) {
            $html = 'Your short URL is <a class="test" href="https://viid.su/'.$id.'">https://viid.su/'.$id.'</a>';
          } else {
            $html = "Error: cannot find database";
          }
        mysqli_close($db);
      }
</code>```

答: you need to use event object as parameter in function callback and call event.preventDefault()</p>

Body:
I build a link shortener,just for fun!
Everything works, but everytime I create a link and submit the form, the page reloads! I wanted to prevent that with onclick="return false;"but it didnt work.

<input class="submit" type="submit" value="Create!"  />

$('#contactForm').submit(function () {
    sendContactForm();
    return false;
});

But nothing works, the file is just stuck and doesn't do anything! What am I doing from ? This is the problem page https://viid.su
PHP

   require("db_config.php");
       $uid = 1;
      $flink = $_POST['url'];
      if(!preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $flink)) {
        $html = "Error: invalid URL";
      } else {

        $db = mysqli_connect($host, $username, $password);
        $conn = new mysqli($host, $username, $password, $database);

          $id = substr(md5(time().$flink), 0, 5);
          if($conn->query("INSERT INTO `".$database."`.`link` (`id`, `flink`,`adonly`,`userid`) VALUES ('".$id."', '".$flink."','true','".$uid."');")) {
            $html = 'Your short URL is https://viid.su/'.$id.'';
          } else {
            $html = "Error: cannot find database";
          }
        mysqli_close($db);
      }


问:
Express js find: unexpected result
Using Express Js with MongoDB, my query is:

```<code>assoc.Associations.find({
    $and: [
        { idUser: 'me' },
        { $or: [{ stato: '1' }, {$and: [ { idClub: 'myclub' }, { stato: '0' } ] } ] }
        ]
}, function (err, result) {
    if (err) {
        return res.status(500).json({
            message: 'Error,
            error: err
        })
    }
})
</code>```

i have just one document in my collection and satisfy my requirement:

```<code>_id : "58459db823b86410e801ac27"
idUser : "me"
idClub : "myclub"
stato : "0"
</code>```

My goal is to perform this condition:

```<code>idUser = 'me' AND (stato = '1' OR (idClub = 'myclub' and stato = '0'))
</code>```

What's wrong in my find?
Thanks

答:
Try this query:</p>

```<code>assoc.Associations.find({

        $or: [
          { stato: '1', idUser: 'me' },
          { stato: '0', idClub: 'myclub', idUser: 'me' },
        ]

})
</code>```

Title: Express js find: unexpected result

Body:
Using Express Js with MongoDB, my query is:

assoc.Associations.find({
    $and: [
        { idUser: 'me' },
        { $or: [{ stato: '1' }, {$and: [ { idClub: 'myclub' }, { stato: '0' } ] } ] }
        ]
}, function (err, result) {
    if (err) {
        return res.status(500).json({
            message: 'Error,
            error: err
        })
    }
})

i have just one document in my collection and satisfy my requirement:

_id : "58459db823b86410e801ac27"
idUser : "me"
idClub : "myclub"
stato : "0"

My goal is to perform this condition:

idUser = 'me' AND (stato = '1' OR (idClub = 'myclub' and stato = '0'))

What's wrong in my find?
Thanks

Body:
Try this query:

assoc.Associations.find({

        $or: [
          { stato: '1', idUser: 'me' },
          { stato: '0', idClub: 'myclub', idUser: 'me' },
        ]

})


问:
Determine whether an image is PNG despite .BMP extension
I want to check if images in a directory are of type png but with extension .bmp. The following determines whether it is a .bmp extension

```<code> string x = Path.GetExtension(file);
</code>```

From this we establish that its extension is .bmp. Now the problem comes in checking if it is in a png format. I am stuck on this part.

The reason why I am doing this is because I want to have my images transparent and .bmp images don't work so well with that.
Thank you!

答:
We can check the file extension with this </p>

```<code> Byte[] imageBase64 = ....

 var encodedFile = Encoding.ASCII.GetString(imageBase64);
 return encodedFile.ToLower().StartsWith("?png", StringComparison.InvariantCultureIgnoreCase);
</code>```

Body:
I want to check if images in a directory are of type png but with extension .bmp. The following determines whether it is a .bmp extension

 string x = Path.GetExtension(file);

From this we establish that its extension is .bmp. Now the problem comes in checking if it is in a png format. I am stuck on this part.

The reason why I am doing this is because I want to have my images transparent and .bmp images don't work so well with that.
Thank you!

Body:
We can check the file extension with this

 Byte[] imageBase64 = ....

 var encodedFile = Encoding.ASCII.GetString(imageBase64);
 return encodedFile.ToLower().StartsWith("?png", StringComparison.InvariantCultureIgnoreCase);


问:
IndoorAtlas : How many times is sufficient/necessary for mapping coverage in the same path?
I have a question and problem in mapping data coverage - How many times is sufficient or necessary for mapping coverage in the same path ?
for example, if I have 2 waypoint distance by 10m. assume A and B. Is it necessary to repeat collecting data in the same path as A->B ,B->A in many time.
Mapping coverage, this depend on times of collecting path ?

Thank you in advance for your kind support

答: No, It is not necessary as long as you are satisfied with the positioning accuracy.</p>


问:
Change default value for default property that can still be overridden in interface builder / storyboard
Lets suppose i want to create a custom ui class that is marked as IBDesignable so i can use it in storyboards, is it possible to override the default value of a default property but still allow for it to be overridden in the storyboard?

For example, if i wanted to create a custom UILabel, can I override it's default backgroundColor to red so that every time i add it to a view in storyboard it will have a red background color by default (instead of the default white it usually has), but if i change the color to anything else in storyboard it will keep that new color.

I know i can add a specific IBInspectable property as a proxy for the backgroundColor, but that's not optimal since that would just leave me with 2 properties on my object that control the same thing (the backgroundColor).

So does anyone know of a way to do this?

答:
You can do this using the appearance proxy. It's specifically designed to provide custom defaults for custom subclasses.

The call to the appearance proxy must me done before the storyboard is loaded. One way of doing that is to use the initialize class method.

```<code>class MyCustomLabel: UILabel
{
    override class func initialize() {
        if (self === MyCustomLabel.self) {
            MyCustomLabel.appearance().backgroundColor = .red
        }
    }
}
</code>```

Not all properties can participate in the appearance proxy. Those that can are tagged with the UI_APPEARANCE_SELECTOR macro in the Objective-C header. One way to display the Objective-C header of a class is to command-click on the class name inside a comment (this is probably a bug actually...)

```<code>// Copy this comment in you code an click on this: UIView
</code>```

In order to render this default color in Interface builder, you can use the prepareForInterfaceBuilder method like so :

```<code>override func prepareForInterfaceBuilder() {
    super.prepareForInterfaceBuilder()
    if (self.backgroundColor == nil) {
        self.backgroundColor = .red
    }
}
</code>```

Note that although it will correctly render the background, the color dropdown menu will still show the "default" color.

Body:
You can do this using the appearance proxy. It's specifically designed to provide custom defaults for custom subclasses.

The call to the appearance proxy must me done before the storyboard is loaded. One way of doing that is to use the initialize class method.

class MyCustomLabel: UILabel
{
    override class func initialize() {
        if (self === MyCustomLabel.self) {
            MyCustomLabel.appearance().backgroundColor = .red
        }
    }
}

Not all properties can participate in the appearance proxy. Those that can are tagged with the UI_APPEARANCE_SELECTOR macro in the Objective-C header. One way to display the Objective-C header of a class is to command-click on the class name inside a comment (this is probably a bug actually...)

// Copy this comment in you code an click on this: UIView

In order to render this default color in Interface builder, you can use the prepareForInterfaceBuilder method like so :

override func prepareForInterfaceBuilder() {
    super.prepareForInterfaceBuilder()
    if (self.backgroundColor == nil) {
        self.backgroundColor = .red
    }
}

Note that although it will correctly render the background, the color dropdown menu will still show the "default" color.


问:
Python: Multiprocessing Does Not Complete Jobs
I'm using python 2.7 with multiprocessing::Pool to run a job in parallel

I've simplified the example below, but here's the main gist of it.

It will create a file for each person in my dict using the apply_async() function. However when I check to see if the file was created properly, I notice that sometimes the file was not created.

Now I'm thinking I've done something wrong in how I used multiprocessing::Pool

Any advice?

```<code>import os
from multiprocessing import Pool

def outputFile(person):
    ofh=open(person+'.txt','w')
    ofh.write('test\n')
    ofh.close()

pool = Pool(processes=4)
for person in person_dict:
    pool.apply_async(outputFile,args(person))
pool.close()
pool.join()
for person in person_dict:
    print os.path.isfile(person+'.txt')
</code>```

```<code>True
True
False
True
</code>```

答:
If you do not catch exceptions in sub-processes and print them yourself, you will not see them. The following program produces no output:

```<code>import os
from multiprocessing import Pool

def outputFile(person):
    raise Exception("An exception")

pool = Pool(processes=4)
for person in range(100):
    pool.apply_async(outputFile, args=(person,))
pool.close()
pool.join()
</code>```

You need to catch all exceptions and manually print the traceback:

```<code>import os
from multiprocessing import Pool, Lock
import traceback

print_lock = Lock()

def outputFile(person):
    try:
        raise Exception("An exception")
    except:
        with print_lock:
            print "%s: An exception occurred" % person
            print traceback.format_exc()

pool = Pool(processes=4)
for person in range(100):
    args = (person, print_lock)
    pool.apply_async(outputFile, args=(person,))
pool.close()
pool.join()
</code>```

Output

```<code>0: An exception occurred
Traceback (most recent call last):
  File "person.py", line 9, in outputFile
    raise Exception("An exception")
Exception: An exception

1: An exception occurred
Traceback (most recent call last):
  File "person.py", line 9, in outputFile
    raise Exception("An exception")
Exception: An exception

...

99: An exception occurred
Traceback (most recent call last):
  File "person.py", line 9, in outputFile
    raise Exception("An exception")
Exception: An exception
</code>```

Note: The print_lock is used to keep the output from being interleaved.

Body:
I'm using python 2.7 with multiprocessing::Pool to run a job in parallel

I've simplified the example below, but here's the main gist of it.

It will create a file for each person in my dict using the apply_async() function. However when I check to see if the file was created properly, I notice that sometimes the file was not created.

Now I'm thinking I've done something wrong in how I used multiprocessing::Pool

Any advice?

import os
from multiprocessing import Pool

def outputFile(person):
    ofh=open(person+'.txt','w')
    ofh.write('test\n')
    ofh.close()

pool = Pool(processes=4)
for person in person_dict:
    pool.apply_async(outputFile,args(person))
pool.close()
pool.join()
for person in person_dict:
    print os.path.isfile(person+'.txt')

True
True
False
True

Body:
If you do not catch exceptions in sub-processes and print them yourself, you will not see them. The following program produces no output:

import os
from multiprocessing import Pool

def outputFile(person):
    raise Exception("An exception")

pool = Pool(processes=4)
for person in range(100):
    pool.apply_async(outputFile, args=(person,))
pool.close()
pool.join()

You need to catch all exceptions and manually print the traceback:

import os
from multiprocessing import Pool, Lock
import traceback

print_lock = Lock()

def outputFile(person):
    try:
        raise Exception("An exception")
    except:
        with print_lock:
            print "%s: An exception occurred" % person
            print traceback.format_exc()

pool = Pool(processes=4)
for person in range(100):
    args = (person, print_lock)
    pool.apply_async(outputFile, args=(person,))
pool.close()
pool.join()

Output

0: An exception occurred
Traceback (most recent call last):
  File "person.py", line 9, in outputFile
    raise Exception("An exception")
Exception: An exception

1: An exception occurred
Traceback (most recent call last):
  File "person.py", line 9, in outputFile
    raise Exception("An exception")
Exception: An exception

...

99: An exception occurred
Traceback (most recent call last):
  File "person.py", line 9, in outputFile
    raise Exception("An exception")
Exception: An exception

Note: The print_lock is used to keep the output from being interleaved.


问:
Can we add the Shipping and Billing addresses form in the cart.liquid file?
I want to add the Shipping and Billing addresses form in the cart.liquid file so it is possible to add these two addresses form in cart page if anybody known then give solution for this. </p>

答: No. It is not possible. Shipping and Billing address are collected in Checkout step, not the cart step.</p>


问:
How to send email with smtp.office365 using PHPMailer
I'm using code below to send mail but I get Authentication unsuccessful. The same code works with smtp.gmail.com, but not with smtp.office365.com.

```<code><?php
/**
 * This example shows settings to use when sending via Google's Gmail servers.
 */

//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');

require '../PHPMailerAutoload.php';

//Create a new PHPMailer instance
$mail = new PHPMailer;

//Tell PHPMailer to use SMTP
$mail->isSMTP();

//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 4;

//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';

//Set the hostname of the mail server
$mail->Host = 'tls://smtp.office365.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6

//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;

//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';

//Whether to use SMTP authentication
$mail->SMTPAuth = true;

//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "anonymized@anonymized.com.br";

//Password to use for SMTP authentication
$mail->Password = "anonymized";

//Set who the message is to be sent from
$mail->setFrom('anonymized@anonymized.com.br', 'First Last');

//Set an alternative reply-to address
$mail->addReplyTo('anonymized@anonymized.com.br', 'First Last');

//Set who the message is to be sent to
$mail->addAddress('anonymized@anonymized.com.br', 'John Doe');

//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';

//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));

//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';

//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');

//send the message, check for errors
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}
</code>```

I get the following output:

```<code>2017-06-06 18:24:34 SERVER -> CLIENT: 220 FR1PR80CA0087.outlook.office365.com Microsoft ESMTP MAIL Service ready at Tue, 6 Jun 2017 18:24:25 +0000
2017-06-06 18:24:34 CLIENT -> SERVER: EHLO desenv
2017-06-06 18:24:34 SERVER -> CLIENT: 250-FR1PR80CA0087.outlook.office365.com Hello [201.47.213.100]250-SIZE 157286400250-PIPELINING250-DSN250-ENHANCEDSTATUSCODES250-STARTTLS250-8BITMIME250-BINARYMIME250 CHUNKING
2017-06-06 18:24:34 CLIENT -> SERVER: STARTTLS
2017-06-06 18:24:34 SERVER -> CLIENT: 220 2.0.0 SMTP server ready
2017-06-06 18:24:35 CLIENT -> SERVER: EHLO desenv
2017-06-06 18:24:35 SERVER -> CLIENT: 250-FR1PR80CA0087.outlook.office365.com Hello [201.47.213.100]250-SIZE 157286400250-PIPELINING250-DSN250-ENHANCEDSTATUSCODES250-AUTH LOGIN250-8BITMIME250-BINARYMIME250 CHUNKING
2017-06-06 18:24:35 CLIENT -> SERVER: AUTH LOGIN
2017-06-06 18:24:35 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2017-06-06 18:24:35 CLIENT -> SERVER: xxx
2017-06-06 18:24:35 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2017-06-06 18:24:35 CLIENT -> SERVER: xxx
2017-06-06 18:24:40 SERVER -> CLIENT: 535 5.7.3 Authentication unsuccessful [FR1PR80CA0087.lamprd80.prod.outlook.com]
2017-06-06 18:24:40 SMTP ERROR: Password command failed: 535 5.7.3 Authentication unsuccessful [FR1PR80CA0087.lamprd80.prod.outlook.com]
SMTP Error: Could not authenticate.
2017-06-06 18:24:40 CLIENT -> SERVER: QUIT
2017-06-06 18:24:40 SERVER -> CLIENT: 221 2.0.0 Service closing transmission channel
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
</code>```

I tried many things. Changing file encoding because in this question smtplib.SMTPAuthenticationError: (535, '5.7.3 Authentication unsuccessful') the problem was the encoding of the password.

I tried using this, as in PHPMailer Authentication unsuccessful:

```<code>$mail->SMTPAuth = False;
</code>```

But I got:

```<code>2017-06-06 18:28:59 SERVER -> CLIENT: 530 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [RO1P215CA0017.LAMP215.PROD.OUTLOOK.COM]
2017-06-06 18:28:59 SMTP ERROR: MAIL FROM command failed: 530 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [RO1P215CA0017.LAMP215.PROD.OUTLOOK.COM]
The following From address failed: rrjuridico@grupopetropolis.com.br : MAIL FROM command failed,5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [RO1P215CA0017.LAMP215.PROD.OUTLOOK.COM],530,SMTP server error: MAIL FROM command failed Detail: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [RO1P215CA0017.LAMP215.PROD.OUTLOOK.COM] SMTP code: 530
Mailer Error: The following From address failed: rrjuridico@grupopetropolis.com.br : MAIL FROM command failed,5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [RO1P215CA0017.LAMP215.PROD.OUTLOOK.COM] ,530,SMTP server error: MAIL FROM command failed Detail: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [RO1P215CA0017.LAMP215.PROD.OUTLOOK.COM] SMTP code: 530SMTP server error: MAIL FROM command failed Detail: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [RO1P215CA0017.LAMP215.PROD.OUTLOOK.COM] SMTP code: 5302017-06-06 18:28:59 CLIENT -> SERVER: QUIT
2017-06-06 18:28:59 SERVER -> CLIENT:
2017-06-06 18:28:59 SMTP ERROR: QUIT command failed:
</code>```

I tried removing line below:

```<code>$mail->isSMTP();
</code>```

I got Message sent!, but email wasn't sent.

Any Idea, any help would be very much apreciated.

答:
It just looks like you have the wrong ID and password. They were easily decoded from the SMTP transcript (I have removed them - you might want to change your PW now), but your password only contained ASCII characters, so it's not an encoding problem.

You do need to authenticate in order to send on most systems, so your second example makes sense.

Not calling isSMTP() means that it defaults to using mail(), which relays your message via a local mail server; the local delivery may succeed, but the onward delivery many still fail - this matches what you're seeing. To check that, look in your mail server log (usually /var/log/mail.log or nearby).

Body:
I'm using code below to send mail but I get Authentication unsuccessful. The same code works with smtp.gmail.com, but not with smtp.office365.com.

<?php
/**
 * This example shows settings to use when sending via Google's Gmail servers.
 */

//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');

require '../PHPMailerAutoload.php';

//Create a new PHPMailer instance
$mail = new PHPMailer;

//Tell PHPMailer to use SMTP
$mail->isSMTP();

//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 4;

//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';

//Set the hostname of the mail server
$mail->Host = 'tls://smtp.office365.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6

//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;

//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';

//Whether to use SMTP authentication
$mail->SMTPAuth = true;

//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "anonymized@anonymized.com.br";

//Password to use for SMTP authentication
$mail->Password = "anonymized";

//Set who the message is to be sent from
$mail->setFrom('anonymized@anonymized.com.br', 'First Last');

//Set an alternative reply-to address
$mail->addReplyTo('anonymized@anonymized.com.br', 'First Last');

//Set who the message is to be sent to
$mail->addAddress('anonymized@anonymized.com.br', 'John Doe');

//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';

//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));

//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';

//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');

//send the message, check for errors
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}

I get the following output:

2017-06-06 18:24:34 SERVER -> CLIENT: 220 FR1PR80CA0087.outlook.office365.com Microsoft ESMTP MAIL Service ready at Tue, 6 Jun 2017 18:24:25 +0000
2017-06-06 18:24:34 CLIENT -> SERVER: EHLO desenv
2017-06-06 18:24:34 SERVER -> CLIENT: 250-FR1PR80CA0087.outlook.office365.com Hello [201.47.213.100]250-SIZE 157286400250-PIPELINING250-DSN250-ENHANCEDSTATUSCODES250-STARTTLS250-8BITMIME250-BINARYMIME250 CHUNKING
2017-06-06 18:24:34 CLIENT -> SERVER: STARTTLS
2017-06-06 18:24:34 SERVER -> CLIENT: 220 2.0.0 SMTP server ready
2017-06-06 18:24:35 CLIENT -> SERVER: EHLO desenv
2017-06-06 18:24:35 SERVER -> CLIENT: 250-FR1PR80CA0087.outlook.office365.com Hello [201.47.213.100]250-SIZE 157286400250-PIPELINING250-DSN250-ENHANCEDSTATUSCODES250-AUTH LOGIN250-8BITMIME250-BINARYMIME250 CHUNKING
2017-06-06 18:24:35 CLIENT -> SERVER: AUTH LOGIN
2017-06-06 18:24:35 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2017-06-06 18:24:35 CLIENT -> SERVER: xxx
2017-06-06 18:24:35 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2017-06-06 18:24:35 CLIENT -> SERVER: xxx
2017-06-06 18:24:40 SERVER -> CLIENT: 535 5.7.3 Authentication unsuccessful [FR1PR80CA0087.lamprd80.prod.outlook.com]
2017-06-06 18:24:40 SMTP ERROR: Password command failed: 535 5.7.3 Authentication unsuccessful [FR1PR80CA0087.lamprd80.prod.outlook.com]
SMTP Error: Could not authenticate.
2017-06-06 18:24:40 CLIENT -> SERVER: QUIT
2017-06-06 18:24:40 SERVER -> CLIENT: 221 2.0.0 Service closing transmission channel
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

I tried many things. Changing file encoding because in this question smtplib.SMTPAuthenticationError: (535, '5.7.3 Authentication unsuccessful') the problem was the encoding of the password.

I tried using this, as in PHPMailer Authentication unsuccessful:

$mail->SMTPAuth = False;

But I got:

2017-06-06 18:28:59 SERVER -> CLIENT: 530 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [RO1P215CA0017.LAMP215.PROD.OUTLOOK.COM]
2017-06-06 18:28:59 SMTP ERROR: MAIL FROM command failed: 530 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [RO1P215CA0017.LAMP215.PROD.OUTLOOK.COM]
The following From address failed: rrjuridico@grupopetropolis.com.br : MAIL FROM command failed,5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [RO1P215CA0017.LAMP215.PROD.OUTLOOK.COM],530,SMTP server error: MAIL FROM command failed Detail: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [RO1P215CA0017.LAMP215.PROD.OUTLOOK.COM] SMTP code: 530
Mailer Error: The following From address failed: rrjuridico@grupopetropolis.com.br : MAIL FROM command failed,5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [RO1P215CA0017.LAMP215.PROD.OUTLOOK.COM] ,530,SMTP server error: MAIL FROM command failed Detail: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [RO1P215CA0017.LAMP215.PROD.OUTLOOK.COM] SMTP code: 530SMTP server error: MAIL FROM command failed Detail: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [RO1P215CA0017.LAMP215.PROD.OUTLOOK.COM] SMTP code: 5302017-06-06 18:28:59 CLIENT -> SERVER: QUIT
2017-06-06 18:28:59 SERVER -> CLIENT:
2017-06-06 18:28:59 SMTP ERROR: QUIT command failed:

I tried removing line below:

$mail->isSMTP();

I got Message sent!, but email wasn't sent.

Any Idea, any help would be very much apreciated.


问:
Looping Error on Android Emulator
I can't seem to launch any of my apps in my Android emulator because every ~2 seconds this error pops up, and I believe this is making my app crash...

Note: I've never once tried to record audio, which I think it's trying to do... so why is it displaying this? Though I was trying to open a 3D model into JPCT-AE with an inputstream that never worked!

The error:

```<code>04-01 21:02:29.798 2160-2160/com.google.android.googlequicksearchbox:search I/MicroDetectionWorker: Micro detection mode: [mDetectionMode: [1]].
04-01 21:02:29.798 2160-2160/com.google.android.googlequicksearchbox:search I/AudioController: Using mInputStreamFactoryBuilder
04-01 21:02:29.805 2160-3055/com.google.android.googlequicksearchbox:search I/MicroRecognitionRunner: Starting detection.
04-01 21:02:29.805 2160-2204/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_starting com.google.android.apps.gsa.staticplugins.z.c@652d8ac
04-01 21:02:29.806 1302-1640/? W/APM_AudioPolicyManager: getInputForAttr() failed opening input: samplingRate 16000, format 1, channelMask 10
04-01 21:02:29.806 2160-2204/com.google.android.googlequicksearchbox:search E/AudioRecord: Could not get audio input for session 441, record source 1999, sample rate 16000, format 0x1, channel mask 0x10, flags 0
04-01 21:02:29.807 2160-2204/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -22.
04-01 21:02:29.807 2160-2204/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
04-01 21:02:29.807 2160-2204/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_started com.google.android.apps.gsa.staticplugins.z.c@652d8ac

                                                                                --------- beginning of system
04-01 21:02:29.808 2160-2204/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
04-01 21:02:29.809 2160-2160/com.google.android.googlequicksearchbox:search I/MicroDetectionWorker: onReady
04-01 21:02:29.844 2160-2204/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_close com.google.android.apps.gsa.staticplugins.z.c@652d8ac
04-01 21:02:29.844 2160-3055/com.google.android.googlequicksearchbox:search I/MicroRecognitionRunner: Detection finished
04-01 21:02:29.844 2160-3055/com.google.android.googlequicksearchbox:search W/ErrorReporter: reportError [type: 211, code: 524300]: Error reading from input stream
04-01 21:02:29.845 2160-2353/com.google.android.googlequicksearchbox:search I/MicroRecognitionRunner: Stopping hotword detection.
04-01 21:02:29.846 2160-3055/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)
                                                                                com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a.a(SourceFile:342)
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a$1.run(SourceFile:1367)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
                                                                                Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
                                                                                at com.google.android.apps.gsa.speech.audio.Tee.g(SourceFile:2531)
                                                                                at com.google.android.apps.gsa.speech.audio.ap.read(SourceFile:555)
                                                                                at java.io.InputStream.read(InputStream.java:101)
                                                                                at com.google.android.apps.gsa.speech.audio.al.run(SourceFile:362)
                                                                                at com.google.android.apps.gsa.speech.audio.ak$1.run(SourceFile:471)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
04-01 21:02:29.846 2160-3055/com.google.android.googlequicksearchbox:search I/AudioController: internalShutdown
04-01 21:02:29.847 2160-2160/com.google.android.googlequicksearchbox:search I/MicroDetector: Keeping mic open: false
04-01 21:02:29.847 2160-2160/com.google.android.googlequicksearchbox:search I/MicroDetectionWorker: #onError(false)
04-01 21:02:29.847 2160-3054/com.google.android.googlequicksearchbox:search I/DeviceStateChecker: DeviceStateChecker cancelled
</code>```

As I said before, this is popping up every ~2 seconds... What could be causing this? I've tried to restart the emulator multiple times and this keeps coming up!!

EDIT: I've also deleted and recreated the emulator and still same errors

Please help me!!
Thanks to all in advance :)

答:
Android is trying to listen on the microphone, which isn't available on the emulator, so it fills logcat with useless stack traces. To stop this, go to the Settings app in Android, and click:

Apps and notifications

App permissions

Microphone

Then disallow microphone use for all the apps.

Title: Looping Error on Android Emulator

Body:
I can't seem to launch any of my apps in my Android emulator because every ~2 seconds this error pops up, and I believe this is making my app crash...

Note: I've never once tried to record audio, which I think it's trying to do... so why is it displaying this? Though I was trying to open a 3D model into JPCT-AE with an inputstream that never worked!

The error:

04-01 21:02:29.798 2160-2160/com.google.android.googlequicksearchbox:search I/MicroDetectionWorker: Micro detection mode: [mDetectionMode: [1]].
04-01 21:02:29.798 2160-2160/com.google.android.googlequicksearchbox:search I/AudioController: Using mInputStreamFactoryBuilder
04-01 21:02:29.805 2160-3055/com.google.android.googlequicksearchbox:search I/MicroRecognitionRunner: Starting detection.
04-01 21:02:29.805 2160-2204/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_starting com.google.android.apps.gsa.staticplugins.z.c@652d8ac
04-01 21:02:29.806 1302-1640/? W/APM_AudioPolicyManager: getInputForAttr() failed opening input: samplingRate 16000, format 1, channelMask 10
04-01 21:02:29.806 2160-2204/com.google.android.googlequicksearchbox:search E/AudioRecord: Could not get audio input for session 441, record source 1999, sample rate 16000, format 0x1, channel mask 0x10, flags 0
04-01 21:02:29.807 2160-2204/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -22.
04-01 21:02:29.807 2160-2204/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
04-01 21:02:29.807 2160-2204/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_started com.google.android.apps.gsa.staticplugins.z.c@652d8ac

                                                                                --------- beginning of system
04-01 21:02:29.808 2160-2204/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
04-01 21:02:29.809 2160-2160/com.google.android.googlequicksearchbox:search I/MicroDetectionWorker: onReady
04-01 21:02:29.844 2160-2204/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_close com.google.android.apps.gsa.staticplugins.z.c@652d8ac
04-01 21:02:29.844 2160-3055/com.google.android.googlequicksearchbox:search I/MicroRecognitionRunner: Detection finished
04-01 21:02:29.844 2160-3055/com.google.android.googlequicksearchbox:search W/ErrorReporter: reportError [type: 211, code: 524300]: Error reading from input stream
04-01 21:02:29.845 2160-2353/com.google.android.googlequicksearchbox:search I/MicroRecognitionRunner: Stopping hotword detection.
04-01 21:02:29.846 2160-3055/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)
                                                                                com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a.a(SourceFile:342)
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a$1.run(SourceFile:1367)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
                                                                                Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
                                                                                at com.google.android.apps.gsa.speech.audio.Tee.g(SourceFile:2531)
                                                                                at com.google.android.apps.gsa.speech.audio.ap.read(SourceFile:555)
                                                                                at java.io.InputStream.read(InputStream.java:101)
                                                                                at com.google.android.apps.gsa.speech.audio.al.run(SourceFile:362)
                                                                                at com.google.android.apps.gsa.speech.audio.ak$1.run(SourceFile:471)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
04-01 21:02:29.846 2160-3055/com.google.android.googlequicksearchbox:search I/AudioController: internalShutdown
04-01 21:02:29.847 2160-2160/com.google.android.googlequicksearchbox:search I/MicroDetector: Keeping mic open: false
04-01 21:02:29.847 2160-2160/com.google.android.googlequicksearchbox:search I/MicroDetectionWorker: #onError(false)
04-01 21:02:29.847 2160-3054/com.google.android.googlequicksearchbox:search I/DeviceStateChecker: DeviceStateChecker cancelled

As I said before, this is popping up every ~2 seconds... What could be causing this? I've tried to restart the emulator multiple times and this keeps coming up!!

EDIT: I've also deleted and recreated the emulator and still same errors

Please help me!!
Thanks to all in advance :)


问:
MachineKey.Protect() equivalent in ASP.NET Core
What is the equivalent (if there is one) of MachineKey.Protect() and MachineKey.Unprotect() in ASP.NET Core

答: the new dataprotection api is what you are looking for https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/</p>


问:
Executing a stored procedure works from Management Studio and localhost but not when published to a server
I am converting a website from Oracle to SQL Server 2016. The website is built in ASP.NET Framework 4 using Visual Studio 2015. The original developer made extensive use of Oracle packages for data manipulation and I have successfully converted everything to stored procedures and user-defined functions. I have successfully rewritten all of the web pages to use the new syntax. I can run the website on the localhost with no errors and am trying to get it to work on our development web server.

The problem: all stored procedures return the same error:

The EXECUTE permission was denied on the object 'USP_My_Procedure', database 'WEB_DB', schema 'WEBDATA'

The user is a member of a Database role which is granted DELETE, EXECUTE, INSERT, REFERENCES, SELECT, UPDATE, and VIEW DEFINITION permissions on the WEBDATA schema:

I am able to SELECT, INSERT, UPDATE, and DELETE data directly from the webpages on the development server when stored procedures are not used. I am able to run the stored procedures from Management Studio when logged on using the application's SQL account. I just can't use the stored procedures to do the work from the website. Unfortunately, I don't have time to rewrite the entire application to eliminate the stored procedures.

Does anyone have any ideas of what to look for? Thank you.

答:
Stored procedures are executed. See the line in your permissions for EXECUTE? It is not granted to this user.

```<code>GRANT EXECUTE ON USP_My_Procedure TO YourUser
</code>```

https://learn.microsoft.com/en-us/sql/t-sql/statements/grant-object-permissions-transact-sql

Body:
Stored procedures are executed. See the line in your permissions for EXECUTE? It is not granted to this user.

GRANT EXECUTE ON USP_My_Procedure TO YourUser

https://learn.microsoft.com/en-us/sql/t-sql/statements/grant-object-permissions-transact-sql


问:
Perl Regex match incorrect
I'm a little confused as to why the output to this search is only the capital letter T. Shouldn't the + operator match the entire word "GREAT"? Any help is appreciated.</p>

```<code>my $content = "The 39 Steps - a GREAT book - colours_15";

    if($content =~ /([A-Z]+)/) {
        print "Matched $1\n";
    }
    else {
        print "No match\n";
    }
</code>```

答:
The regex engine starts at the left of the string. It tries to match capital letters, at least one and as many as possible. That's the T from The. That's at least one, and then it's done. It never even reaches the GREAT.

You can see that if you run your program with use re 'debug', which turns on regex debugging.

```<code>use re 'debug';

"The 39 Steps - a GREAT book - colours_15" =~ /([A-Z]+)/;
</code>```

This will write to STDERR:

```<code>Compiling REx "([A-Z]+)"
Final program:
   1: OPEN1 (3)
   3:   PLUS (15)
   4:     ANYOF[A-Z][] (0)
  15: CLOSE1 (17)
  17: END (0)
stclass ANYOF[A-Z][] plus minlen 1
Matching REx "([A-Z]+)" against "The 39 Steps - a GREAT book - colours_15"
Matching stclass ANYOF[A-Z][] against "The 39 Steps - a GREAT book - colours_15" (40 bytes)
   0 <> <The 39 Ste>         |  1:OPEN1(3)
   0 <> <The 39 Ste>         |  3:PLUS(15)
                                  ANYOF[A-Z][] can match 1 times out of 2147483647...
   1 <T> <he 39 Step>        | 15:  CLOSE1(17)
   1 <T> <he 39 Step>        | 17:  END(0)
Match successful!
Freeing REx: "([A-Z]+)"
</code>```

Title: Perl Regex match incorrect

Body:
I'm a little confused as to why the output to this search is only the capital letter T. Shouldn't the + operator match the entire word "GREAT"? Any help is appreciated.

my $content = "The 39 Steps - a GREAT book - colours_15";

    if($content =~ /([A-Z]+)/) {
        print "Matched $1\n";
    }
    else {
        print "No match\n";
    }

Body:
The regex engine starts at the left of the string. It tries to match capital letters, at least one and as many as possible. That's the T from The. That's at least one, and then it's done. It never even reaches the GREAT.

You can see that if you run your program with use re 'debug', which turns on regex debugging.

use re 'debug';

"The 39 Steps - a GREAT book - colours_15" =~ /([A-Z]+)/;

This will write to STDERR:

Compiling REx "([A-Z]+)"
Final program:
   1: OPEN1 (3)
   3:   PLUS (15)
   4:     ANYOF[A-Z][] (0)
  15: CLOSE1 (17)
  17: END (0)
stclass ANYOF[A-Z][] plus minlen 1
Matching REx "([A-Z]+)" against "The 39 Steps - a GREAT book - colours_15"
Matching stclass ANYOF[A-Z][] against "The 39 Steps - a GREAT book - colours_15" (40 bytes)
   0 <> <The 39 Ste>         |  1:OPEN1(3)
   0 <> <The 39 Ste>         |  3:PLUS(15)
                                  ANYOF[A-Z][] can match 1 times out of 2147483647...
   1 <T> <he 39 Step>        | 15:  CLOSE1(17)
   1 <T> <he 39 Step>        | 17:  END(0)
Match successful!
Freeing REx: "([A-Z]+)"


问:
Can I make two (or more) substitions in a parameter at once?
I want to replace each @ and . by \@ and \. respectively. Right now I'm solving this using the following:

```<code>str="@foo.bar.baz"
str=${str//"."/"\."}
str=${str/"@"/"\@"}
echo $str
</code>```

Can I shorten this?

答:
Using sed:

```<code>echo "@foo.bar.baz"|sed 's/[@.]/\\&/g'
</code>```

Body:
I want to replace each @ and . by \@ and \. respectively. Right now I'm solving this using the following:

str="@foo.bar.baz"
str=${str//"."/"\."}
str=${str/"@"/"\@"}
echo $str

Can I shorten this?

Body:
Using sed:

echo "@foo.bar.baz"|sed 's/[@.]/\\&/g'


答:
The T you printed is the first capital letter found by your regex.  It is the T from the first The word.

If you want to match all occurrences of 1+ capital ASCII letter chunks in a larger string, use your pattern with a g ("global") modifier: /[A-Z]+/g:

```<code>#!/usr/bin/perl
use warnings;
use feature 'say';

$s = "The 39 Steps - a GREAT book - colours_15";
my @res = $s =~ /[A-Z]+/g;
say "@res";
</code>```

See the online Perl demo printing T S GREAT.

If you want to find a whole word that only consists of ALLCAPS letters, use

```<code>/\b([A-Z]+)\b/
</code>```

The \b is a word boundary and will ensure whole word matches.

Note that you might also match GREAT here by using /([A-Z]{2,})/ regex that matches 2 or more capital ASCII letters, but the version with word boundaries looks more practical.

Title: Perl Regex match incorrect

Body:
The T you printed is the first capital letter found by your regex.  It is the T from the first The word.

If you want to match all occurrences of 1+ capital ASCII letter chunks in a larger string, use your pattern with a g ("global") modifier: /[A-Z]+/g:

#!/usr/bin/perl
use warnings;
use feature 'say';

$s = "The 39 Steps - a GREAT book - colours_15";
my @res = $s =~ /[A-Z]+/g;
say "@res";

See the online Perl demo printing T S GREAT.

If you want to find a whole word that only consists of ALLCAPS letters, use

/\b([A-Z]+)\b/

The \b is a word boundary and will ensure whole word matches.

Note that you might also match GREAT here by using /([A-Z]{2,})/ regex that matches 2 or more capital ASCII letters, but the version with word boundaries looks more practical.


问:
Vagrant: How to sync folder from guest back to host?
Why, because it is difficult to work and edit code via legacy editors in the guest. The whole purpose of vagrant is to be more easily for the developer, right:)?

As such I please someone to guide me in this situation:

Need to work on a project. It is git repo. Requires mysql, php, etc, etc.

VM works great(provided)

But editing files in this repo not so easy via ssh and "legacy" editors. Want to use favorite IDE.

On the VM repo is in /home/vagrant/src.
I want it to be visible/editable in ../src in the host.

I read the docs and putted this in the Vagranfile:

config.vm.synced_folder '../src', '/home/vagrant/src'

This "works" except that it overwrites all contents from /home/vagrant/src with those from ../src which is empty.

Any workaround?
I considered the possibility to clone the repo via git(publicly available via github) and sync the folder to the VM but this does not feel right and lose production configs too.

答:
I work with vagrant with this structure:

```<code>Vagrantfile
MyCode.php
</code>```

and Vagrantfile contains:

config.vm.synced_folder ".", "/vagrant"

that means that MyCode.php is visible inside vagrant machine in /vagrant folder. I can edit that file both from vagrant machine (the guest) and from my machine (the host).

Body:
I work with vagrant with this structure:

Vagrantfile
MyCode.php

and Vagrantfile contains:

config.vm.synced_folder ".", "/vagrant"

that means that MyCode.php is visible inside vagrant machine in /vagrant folder. I can edit that file both from vagrant machine (the guest) and from my machine (the host).