问:
Sort distinct string values by the decimal value
I have following query:

```<code>SELECT Main.DEALER_CODE
     , LEFT(Main.[fees], LEN(Main.[fees]) - 1) AS [fees]
  FROM
       (   SELECT DISTINCT vlp2.DEALER_CODE
                , (   SELECT DISTINCT CAST(FUNDING_FEE_AMOUNT AS VARCHAR(20)) + ';' AS [text()]
                        FROM dbo.valid_lease_programs AS vlp
                        JOIN dbo.lease_programs       AS lp ON lp.LEASE_PROGRAM = vlp.LEASE_PROGRAM
                       WHERE lp.LEASE_REMARKS IS NOT NULL AND vlp.DEALER_CODE = vlp2.DEALER_CODE
                       ORDER BY 1
                      FOR XML PATH('')) [fees]
             FROM dbo.valid_lease_programs AS vlp2) [Main];
</code>```

FUNDING_FEE_AMOUNT is the decimal column, but when it is casted to the VARCHAR, when the ORDER BY is ordering it as a string, so 2 > 19. I would normally order by FUNDING_FEE_AMOUNT without casting, but in that case I can't do that because of the DISTINCT keyword and I can't remove casting as I will not be able to add ";" as separator.

So the question, how can I concatenate these values but have number-like order?

答:
You can use data() instead of text(), it will give you spaces between concatenated values, then just replace spaces with ';', this permits to not to cast your decimal as varchar and will give correct order.

Here is an example:

```<code>declare @t table (col decimal(10, 2));
insert into @t values (100.05), (11.01), (2.33), (20), (1);

select replace((  select distinct col  as 'data()' from @t order by col for xml path('')  ), ' ', ';') as res
</code>```

Body:
I have following query:

SELECT Main.DEALER_CODE
     , LEFT(Main.[fees], LEN(Main.[fees]) - 1) AS [fees]
  FROM
       (   SELECT DISTINCT vlp2.DEALER_CODE
                , (   SELECT DISTINCT CAST(FUNDING_FEE_AMOUNT AS VARCHAR(20)) + ';' AS [text()]
                        FROM dbo.valid_lease_programs AS vlp
                        JOIN dbo.lease_programs       AS lp ON lp.LEASE_PROGRAM = vlp.LEASE_PROGRAM
                       WHERE lp.LEASE_REMARKS IS NOT NULL AND vlp.DEALER_CODE = vlp2.DEALER_CODE
                       ORDER BY 1
                      FOR XML PATH('')) [fees]
             FROM dbo.valid_lease_programs AS vlp2) [Main];

FUNDING_FEE_AMOUNT is the decimal column, but when it is casted to the VARCHAR, when the ORDER BY is ordering it as a string, so 2 > 19. I would normally order by FUNDING_FEE_AMOUNT without casting, but in that case I can't do that because of the DISTINCT keyword and I can't remove casting as I will not be able to add ";" as separator.

So the question, how can I concatenate these values but have number-like order?

Body:
You can use data() instead of text(), it will give you spaces between concatenated values, then just replace spaces with ';', this permits to not to cast your decimal as varchar and will give correct order.

Here is an example:

declare @t table (col decimal(10, 2));
insert into @t values (100.05), (11.01), (2.33), (20), (1);

select replace((  select distinct col  as 'data()' from @t order by col for xml path('')  ), ' ', ';') as res


来源: stackexchange

问:
How do you get the number of words in a NSTextStorage/NSString?
So my question is basically how do you get the number of words in a NSTextStorage/NSString?  I don't want the character length but the word length.  Thanks.</p>

答:
When using NSTextStorage, you can use the words method to get to the number of words. It might not be the most memory-efficient way to count words, but it does a pretty good job at ignoring punctuation marks and other non-word characters:

```<code>NSString *input = @"one - two  three   four .";
NSTextStorage *storage = [[NSTextStorage alloc] initWithString:input];
NSLog(@"word count: %u", [[storage words] count]);
</code>```

The output will be word count: 4.

ContentLicense: CC BY-SA 2.5

Body:
When using NSTextStorage, you can use the words method to get to the number of words. It might not be the most memory-efficient way to count words, but it does a pretty good job at ignoring punctuation marks and other non-word characters:

NSString *input = @"one - two  three   four .";
NSTextStorage *storage = [[NSTextStorage alloc] initWithString:input];
NSLog(@"word count: %u", [[storage words] count]);

The output will be word count: 4.


问:
How can I assert that the argument only contains listed integers in Python
I have a method in Python and I only want to accept integers listed or singular, how can I define this?

```<code>def autoInt(integers):
    assert int(integers)
    assert len(integers) > 0
</code>```

This fails as I cannot have a list. I'm sure it's something easy.

TypeError: int() argument must be a string or a number, not 'list'

Edit: I have been tasked so that this method can ONLY accept integers in a list.

答:
You can test a list of integers like this:

```<code>assert(all(isinstance(item, int) for item in integers))
</code>```

From How to test if every item in a list of type 'int'?

ContentLicense: CC BY-SA 3.0

Body:
I have a method in Python and I only want to accept integers listed or singular, how can I define this?

def autoInt(integers):
    assert int(integers)
    assert len(integers) > 0

This fails as I cannot have a list. I'm sure it's something easy.

TypeError: int() argument must be a string or a number, not 'list'

Edit: I have been tasked so that this method can ONLY accept integers in a list.

Body:
You can test a list of integers like this:

assert(all(isinstance(item, int) for item in integers))

From How to test if every item in a list of type 'int'?


问:
Selenium working only for few pages -- Element is not clickable at point
I tried to automate Amazon/novels list page using selenium. It is working sometimes and not working sometimes. I am unable to understand the mistake in the code. It worked fine for some time and scrolled 13 pages out of 20. But from next time, it is not working properly. Till now it didn't scroll complete 20 pages.

```<code>from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup

class App:

    def __init__(self,path='F:\Imaging'):

        self.path=path
        self.driver = webdriver.Chrome('F:\chromedriver')
        self.driver.get('https://www.amazon.in/s/ref=sr_pg_1?rh=i%3Aaps%2Ck%3Anovels&keywords=novels&ie=UTF8&qid=1510727563')
        sleep(1)
        self.scroll_down()
        self.driver.close()

    def scroll_down(self):

        self.driver.execute_script("window.scrollTo(0,5500);")
        sleep(1)
        load_more = self.driver.find_element_by_xpath('//span[@class="pagnRA"]/a[@title="Next Page"]')
        load_more.click()
        sleep(2)

        for value in range(2,19):

            print(self.driver.current_url)
            sleep(3)
            self.driver.execute_script("window.scrollTo(0,5500);")
            sleep(2)
            load_more = self.driver.find_element_by_xpath('//span[@class="pagnRA"]/a[@title="Next Page"]')
            load_more.click()

        sleep(3)

if __name__=='__main__':
    app=App()
</code>```

The output for this code which i am getting is:

```<code>    C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/Akhil/Scrape/amazon.py
https://www.amazon.in/s/ref=sr_pg_2/257-8503487-3570721?rh=i%3Aaps%2Ck%3Anovels&page=2&keywords=novels&ie=UTF8&qid=1510744188
https://www.amazon.in/s/ref=sr_pg_3?rh=i%3Aaps%2Ck%3Anovels&page=3&keywords=novels&ie=UTF8&qid=1510744197
https://www.amazon.in/s/ref=sr_pg_4?rh=i%3Aaps%2Ck%3Anovels&page=4&keywords=novels&ie=UTF8&qid=1510744204
Traceback (most recent call last):
  File "C:/Users/Akhil/Scrape/amazon.py", line 31, in <module>
    app=App()
  File "C:/Users/Akhil/Scrape/amazon.py", line 11, in __init__
    self.scroll_down()
  File "C:/Users/Akhil/Scrape/amazon.py", line 26, in scroll_down
    load_more.click()
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 501, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Element <a title="Next Page" id="pagnNextLink" class="pagnNext" href="/gp/search/ref=sr_pg_5?rh=i%3Aaps%2Ck%3Anovels&page=5&keywords=novels&ie=UTF8&qid=1510744210">...</a> is not clickable at point (809, 8). Other element would receive the click: <a href="/gp/prime/ref=nav_prime_try_btn/257-8503487-3570721" class="nav-a nav-a-2" data-ux-mouseover="true" id="nav-link-prime" tabindex="26">...</a>
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)

Process finished with exit code 1
</code>```

How to solve this problem?

答:
The error is that there is no Next Page element visible or clickable. You can either wait for the presence of this element like this, or put the .click() in a try / exception block to detect when it fails.

It is probably that either your target has legitimately run out of next pages (you have seen them all), or the page is still loading, or the format of the next link has changed.

ContentLicense: CC BY-SA 4.0

Body:
I tried to automate Amazon/novels list page using selenium. It is working sometimes and not working sometimes. I am unable to understand the mistake in the code. It worked fine for some time and scrolled 13 pages out of 20. But from next time, it is not working properly. Till now it didn't scroll complete 20 pages.

from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup

class App:

    def __init__(self,path='F:\Imaging'):

        self.path=path
        self.driver = webdriver.Chrome('F:\chromedriver')
        self.driver.get('https://www.amazon.in/s/ref=sr_pg_1?rh=i%3Aaps%2Ck%3Anovels&keywords=novels&ie=UTF8&qid=1510727563')
        sleep(1)
        self.scroll_down()
        self.driver.close()

    def scroll_down(self):

        self.driver.execute_script("window.scrollTo(0,5500);")
        sleep(1)
        load_more = self.driver.find_element_by_xpath('//span[@class="pagnRA"]/a[@title="Next Page"]')
        load_more.click()
        sleep(2)

        for value in range(2,19):

            print(self.driver.current_url)
            sleep(3)
            self.driver.execute_script("window.scrollTo(0,5500);")
            sleep(2)
            load_more = self.driver.find_element_by_xpath('//span[@class="pagnRA"]/a[@title="Next Page"]')
            load_more.click()

        sleep(3)

if __name__=='__main__':
    app=App()

The output for this code which i am getting is:

    C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/Akhil/Scrape/amazon.py
https://www.amazon.in/s/ref=sr_pg_2/257-8503487-3570721?rh=i%3Aaps%2Ck%3Anovels&page=2&keywords=novels&ie=UTF8&qid=1510744188
https://www.amazon.in/s/ref=sr_pg_3?rh=i%3Aaps%2Ck%3Anovels&page=3&keywords=novels&ie=UTF8&qid=1510744197
https://www.amazon.in/s/ref=sr_pg_4?rh=i%3Aaps%2Ck%3Anovels&page=4&keywords=novels&ie=UTF8&qid=1510744204
Traceback (most recent call last):
  File "C:/Users/Akhil/Scrape/amazon.py", line 31, in <module>
    app=App()
  File "C:/Users/Akhil/Scrape/amazon.py", line 11, in __init__
    self.scroll_down()
  File "C:/Users/Akhil/Scrape/amazon.py", line 26, in scroll_down
    load_more.click()
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 501, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Element ... is not clickable at point (809, 8). Other element would receive the click: ...
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)

Process finished with exit code 1

How to solve this problem?


问:
PyPDF2 PdfReadError: Could not read Boolean object
I am getting the following error, when reading certain PDF files using PyPDF2. Due to the confidential nature of these documents, I can't share them, but I can try and provide information which can help solve this problem.

Stacktrace -

```<code>    inputpdf = PdfFileReader(open(pdfpath, "rb"), strict=False)
  File "/home/tata/.virtualenvs/obu/local/lib/python2.7/site-packages/PyPDF2/pdf.py", line 1084, in __init__
    self.read(stream)
  File "/home/tata/.virtualenvs/obu/local/lib/python2.7/site-packages/PyPDF2/pdf.py", line 1732, in read
    num = readObject(stream, self)
  File "/home/tata/.virtualenvs/obu/local/lib/python2.7/site-packages/PyPDF2/generic.py", line 74, in readObject
    return BooleanObject.readFromStream(stream)
  File "/home/tata/.virtualenvs/obu/local/lib/python2.7/site-packages/PyPDF2/generic.py", line 137, in readFromStream
    raise utils.PdfReadError('Could not read Boolean object')
PdfReadError: Could not read Boolean object
</code>```

The exception seems to be raised from the following function, in generic.py:

```<code>def readFromStream(stream):
    word = stream.read(4)
    if word == b_("true"):
        return BooleanObject(True)
    elif word == b_("fals"):
        stream.read(1)
        return BooleanObject(False)
    else:
        raise utils.PdfReadError('Could not read Boolean object')
</code>```

Printing the variable word prints the string trai, but I am not sure what this string represents.

Since the PyPDF2 project seems unmaintained, can someone help me figure out a solution for this?

Note : Please note that these PDFs are not password protected.

答:
It seems as if all  pdfs are encrypted in some way. Using the solution cited in this issue  #53 in PyPDF2's github repository, I used the following command to generate another pdf ( The Decrypted version of the original pdf ) - </p>

```<code>qpdf --password= --decrypt input.pdf output.pdf
</code>```

<p>and then reading output.pdf worked for me. I am not sure as to how I can determine beforehand, whether a pdf is encrypted ( or in this particular state ) or not. But this solution temporarily solves the problem. </p>

Body:
I am getting the following error, when reading certain PDF files using PyPDF2. Due to the confidential nature of these documents, I can't share them, but I can try and provide information which can help solve this problem.

Stacktrace -

    inputpdf = PdfFileReader(open(pdfpath, "rb"), strict=False)
  File "/home/tata/.virtualenvs/obu/local/lib/python2.7/site-packages/PyPDF2/pdf.py", line 1084, in __init__
    self.read(stream)
  File "/home/tata/.virtualenvs/obu/local/lib/python2.7/site-packages/PyPDF2/pdf.py", line 1732, in read
    num = readObject(stream, self)
  File "/home/tata/.virtualenvs/obu/local/lib/python2.7/site-packages/PyPDF2/generic.py", line 74, in readObject
    return BooleanObject.readFromStream(stream)
  File "/home/tata/.virtualenvs/obu/local/lib/python2.7/site-packages/PyPDF2/generic.py", line 137, in readFromStream
    raise utils.PdfReadError('Could not read Boolean object')
PdfReadError: Could not read Boolean object

The exception seems to be raised from the following function, in generic.py:

def readFromStream(stream):
    word = stream.read(4)
    if word == b_("true"):
        return BooleanObject(True)
    elif word == b_("fals"):
        stream.read(1)
        return BooleanObject(False)
    else:
        raise utils.PdfReadError('Could not read Boolean object')

Printing the variable word prints the string trai, but I am not sure what this string represents.

Since the PyPDF2 project seems unmaintained, can someone help me figure out a solution for this?

Note : Please note that these PDFs are not password protected.

Body:
It seems as if all  pdfs are encrypted in some way. Using the solution cited in this issue  #53 in PyPDF2's github repository, I used the following command to generate another pdf ( The Decrypted version of the original pdf ) -

qpdf --password= --decrypt input.pdf output.pdf

and then reading output.pdf worked for me. I am not sure as to how I can determine beforehand, whether a pdf is encrypted ( or in this particular state ) or not. But this solution temporarily solves the problem.


问:
c++ Finite State Machine
I've been given a homework assignment that I can't seem to wrap my head around. Our teacher wants us to program a finite state machine. Here is the code

```<code>#ifndefine
#define FINITE_STATE_MACHINE_H
#include <iosfwd>

class FiniteStateMachine
    {
        Private:
        friend std::ostream &operator<< (std::ostream &, FiniteStateMachine const &);

        public:
            FiniteStateMachine(){}
            virtual FiniteStateMachine *changeState() const = 0;
            virtual char const *toString() const = 0;
            virtual ~FiniteStateMachine(){}
    };

class ON : public FiniteStateMachine
    {
        private:

        public:
            ON(){}
            FiniteStateMachine *changeState() const;
            char const *toString() const;
    };

class OFF : public FiniteStateMachine
    {
        private:

        public:
            OFF(){ }
            FiniteStateMachine *changeState() const;
            char const *toString() const;
    };

#endif
</code>```

The instructions are to create a FiniteStateMachine.cpp file that contains all the pertinent member functions such that the state of OFF transitions to the state of ON and vice versa.

I have attempted to write the changeState() function to return a new instance of the opposite state, but it doesn't seem to want to work and I'm not sure where I'm going wrong.

I was trying to instantiate and return a new ON object with the following in the FiniteStateMachine.cpp

```<code>    FiniteStateMachine *OFF::changeState() const
        {
            FiniteStateMachine *on = new ON;
            return *on;
        }
</code>```

and the compiler was returning the following error
    cannot convert 'FiniteStateMachine' to 'FiniteStateMachine*' in return

A classmate suggested putting it into the constructor instead of simply calling changeState()

```<code>OFF::OFF()
    {

        FiniteStateMachine *OFF::changeState() const
            {
                FiniteStateMachine *on = new ON;
                return *on;
            }

    }
</code>```

the compiler returns the error
        qualified-id in declaration before '(' token

indicating it's in between changeState and the ()'s

after more keyboard banging it seems I needed to write

```<code>FiniteStateMachine *OFF::changeState() const
    {
        return new OFF();
    }
</code>```

答:
Try to look up 'state pattern'. eg https://sourcemaking.com/design_patterns/state

This design pattern is made to solve what you ask for.

Title: c++ Finite State Machine

Body:
I've been given a homework assignment that I can't seem to wrap my head around. Our teacher wants us to program a finite state machine. Here is the code

#ifndefine
#define FINITE_STATE_MACHINE_H
#include <iosfwd>

class FiniteStateMachine
    {
        Private:
        friend std::ostream &operator<< (std::ostream &, FiniteStateMachine const &);

        public:
            FiniteStateMachine(){}
            virtual FiniteStateMachine *changeState() const = 0;
            virtual char const *toString() const = 0;
            virtual ~FiniteStateMachine(){}
    };

class ON : public FiniteStateMachine
    {
        private:

        public:
            ON(){}
            FiniteStateMachine *changeState() const;
            char const *toString() const;
    };

class OFF : public FiniteStateMachine
    {
        private:

        public:
            OFF(){ }
            FiniteStateMachine *changeState() const;
            char const *toString() const;
    };

#endif

The instructions are to create a FiniteStateMachine.cpp file that contains all the pertinent member functions such that the state of OFF transitions to the state of ON and vice versa.

I have attempted to write the changeState() function to return a new instance of the opposite state, but it doesn't seem to want to work and I'm not sure where I'm going wrong.

I was trying to instantiate and return a new ON object with the following in the FiniteStateMachine.cpp

    FiniteStateMachine *OFF::changeState() const
        {
            FiniteStateMachine *on = new ON;
            return *on;
        }

and the compiler was returning the following error
    cannot convert 'FiniteStateMachine' to 'FiniteStateMachine*' in return

A classmate suggested putting it into the constructor instead of simply calling changeState()

OFF::OFF()
    {

        FiniteStateMachine *OFF::changeState() const
            {
                FiniteStateMachine *on = new ON;
                return *on;
            }

    }

the compiler returns the error
        qualified-id in declaration before '(' token

indicating it's in between changeState and the ()'s

after more keyboard banging it seems I needed to write

FiniteStateMachine *OFF::changeState() const
    {
        return new OFF();
    }


问:
Microservice Architecture design
I have few doubts on Microservice architecture.

Lets say there are microservices A, B and C.
A maintains the context of a job apart from other things it does and B,C work to fulfill that job by doing respective tasks for that job.

Here I have questions.

1. DB design

I am talking about SQL here.
Usage of foreign keys simplifies lot of things.
But as I understand microservice architecture, every microservice maintaines its own data and data has to be queried from that service if required.

Does it mean no foreign keys referring to tables in another microservices?

2. Data Flow

As I see here are two ways.

All the queries are done using jobId maintained uniquely in all microservices for a job.

Client requests go directly to individual service for a task.  To get summary of the job, client queries individual microservices collects the data and passes to user.

Do everything through coordinating microservice. Client requests go to service A and in tern service A will gather info from all other microservices for that jobId and passed that to user.

Which of the above two has to be followed and why?

答:
Does it mean no foreign keys referring to tables in another microservices?

Not in the database sense. One microservice may hold IDs of remote entities but should not assume anything about the remote microservice persistence (i.e. the database type, it could be anything from SQL to NoSQL).

Which of the above two has to be followed and why?

This really depends. There are two types of architectures: choreography and orchestration. Both of them are good. Which one to use? Only you can decide. Here are a few blog posts about them:

Microservices — When to React Vs. Orchestrate

Benefits of Microservices - Choreography over Orchestration, Low Coupling and High Cohesion

Also, the solution to this SO question might be useful.

Title: Microservice Architecture design


问:
Parsing specific rows in a tab-separated file in python
I have a tab-separated file with no format. The file format is just listed as FILE. When I open it with a text editor, it looks like:

```<code>Job Wanted_VERB "_. 2000    1   1
Job Wanted_VERB "_. 2001    1   1
Job Wanted_VERB "_. 2002    5   5
Job Wanted_VERB "_. 2004    2   2
Job Wanted_VERB "_. 2005    2   2
Job Wanted_VERB "_. 2006    2   2
Job Wanted_VERB "_. 2007    1   1
Job Well Done   1917    1   1
Job Well Done   1930    3   2
Job Well Done   1937    1   1
Job Well Done   1940    5   4
Job Well Done   1941    3   3
Job Well Done   1942    1   1
Job Well Done   1943    2   2
Job Well Done   1944    1   1
Job Well Done   1945    1   1
Job Well Done   1946    3   3
Job Well Done   1948    1   1
Job Well Done   1949    4   4
Job Well Done   1950    1   1
Job Well Done   1951    3   2
Job Well Done   1952    6   4
Job Well Done   1953    9   5
Job Well Done   1954    6   4
Job Well Done   1955    5   5
....
....
</code>```

where the first three columns are 3 gram sentence and the rest are related to the word frequency.

It is a huge file, so I just want to parse the part that only contains the 3 gram word that I am looking for. For example, from the table above, I would like to parse only the Job Well Done part.

```<code>Job Well Done   1917    1   1
Job Well Done   1930    3   2
Job Well Done   1937    1   1
Job Well Done   1940    5   4
Job Well Done   1941    3   3
Job Well Done   1942    1   1
Job Well Done   1943    2   2
Job Well Done   1944    1   1
Job Well Done   1945    1   1
Job Well Done   1946    3   3
Job Well Done   1948    1   1
Job Well Done   1949    4   4
Job Well Done   1950    1   1
Job Well Done   1951    3   2
Job Well Done   1952    6   4
Job Well Done   1953    9   5
Job Well Done   1954    6   4
Job Well Done   1955    5   5
</code>```

I am currently doing this to parse the whole file and put it into a list:

```<code>with open(file, 'rt', encoding='UTF8') as input:
    z = [line.strip().split('\t') for line in input]
</code>```

Any help?

答:
Yes, add startswith as an if statement, like this:</p>

```<code>with open(file, 'rt', encoding='UTF8') as input:
    z = [line.strip().split("\t") for line in f if line.startswith("Job Well Done")]
</code>```

Body:
I have a tab-separated file with no format. The file format is just listed as FILE. When I open it with a text editor, it looks like:

Job Wanted_VERB "_. 2000    1   1
Job Wanted_VERB "_. 2001    1   1
Job Wanted_VERB "_. 2002    5   5
Job Wanted_VERB "_. 2004    2   2
Job Wanted_VERB "_. 2005    2   2
Job Wanted_VERB "_. 2006    2   2
Job Wanted_VERB "_. 2007    1   1
Job Well Done   1917    1   1
Job Well Done   1930    3   2
Job Well Done   1937    1   1
Job Well Done   1940    5   4
Job Well Done   1941    3   3
Job Well Done   1942    1   1
Job Well Done   1943    2   2
Job Well Done   1944    1   1
Job Well Done   1945    1   1
Job Well Done   1946    3   3
Job Well Done   1948    1   1
Job Well Done   1949    4   4
Job Well Done   1950    1   1
Job Well Done   1951    3   2
Job Well Done   1952    6   4
Job Well Done   1953    9   5
Job Well Done   1954    6   4
Job Well Done   1955    5   5
....
....

where the first three columns are 3 gram sentence and the rest are related to the word frequency.

It is a huge file, so I just want to parse the part that only contains the 3 gram word that I am looking for. For example, from the table above, I would like to parse only the Job Well Done part.

Job Well Done   1917    1   1
Job Well Done   1930    3   2
Job Well Done   1937    1   1
Job Well Done   1940    5   4
Job Well Done   1941    3   3
Job Well Done   1942    1   1
Job Well Done   1943    2   2
Job Well Done   1944    1   1
Job Well Done   1945    1   1
Job Well Done   1946    3   3
Job Well Done   1948    1   1
Job Well Done   1949    4   4
Job Well Done   1950    1   1
Job Well Done   1951    3   2
Job Well Done   1952    6   4
Job Well Done   1953    9   5
Job Well Done   1954    6   4
Job Well Done   1955    5   5

I am currently doing this to parse the whole file and put it into a list:

with open(file, 'rt', encoding='UTF8') as input:
    z = [line.strip().split('\t') for line in input]

Any help?

Body:
Yes, add startswith as an if statement, like this:

with open(file, 'rt', encoding='UTF8') as input:
    z = [line.strip().split("\t") for line in f if line.startswith("Job Well Done")]


问:
Limit number of selected cells by section in TableView
I've spent a lot of time searching a solution to limit the number of selected cells in a UITableView.

Here is a piece of code I found :

```<code>func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    if let selectedRows = tableView.indexPathsForSelectedRows {
        if selectedRows.count == limit {
            return nil
        }
    }

    return indexPath
}
</code>```

The problem is that tableView.indexPathsForSelectedRows contains selected cells that are VISIBLE and from any section.

Does a property like : tableView.selectedCellsForSection(section: 0) exist ?

Thanks for your help !

UPDATE 1

This is an example with a car that containts several options

```<code>var selectedOptions = [IndexPath : Option]() // Option can be for example, the color of the car

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    let maxOptionForSection = car.options![indexPath.section]?.max
    let numberOfSelectedOptions = selectedOptions.filter { $0.key.section == indexPath.section }

    if numberOfSelectedOptions.count == maxOptionForSection {
        return nil
    }

    return indexPath
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) as? OptionCell {
        cell.checkButton.isChecked = true
        cell.option.isSelected = true
        selectedOptions[indexPath] = cell.option
    }
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) as? OptionCell {
        cell.checkButton.isChecked = false
        cell.option.isSelected = false
        selectedOptions.removeValue(forKey: indexPath)
    }
}
</code>```

SOLUTION

```<code>func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    let optionCell = cell as! OptionCell

    if optionCell.option.isSelected {
        optionCell.checkButton.isChecked = true
    } else {
        optionCell.checkButton.isChecked = false
    }
}
</code>```

答:
This will limit it to the section in which the row was clicked:</p>

```<code>func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    if let selectedRows = tableView.indexPathsForSelectedRows?.filter({ $0.section == indexPath.section }) {
        if selectedRows.count == limit {
            return nil
        }
    }

    return indexPath
}
</code>```

Body:
I've spent a lot of time searching a solution to limit the number of selected cells in a UITableView.

Here is a piece of code I found :

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    if let selectedRows = tableView.indexPathsForSelectedRows {
        if selectedRows.count == limit {
            return nil
        }
    }

    return indexPath
}

The problem is that tableView.indexPathsForSelectedRows contains selected cells that are VISIBLE and from any section.

Does a property like : tableView.selectedCellsForSection(section: 0) exist ?

Thanks for your help !

UPDATE 1

This is an example with a car that containts several options

var selectedOptions = [IndexPath : Option]() // Option can be for example, the color of the car

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    let maxOptionForSection = car.options![indexPath.section]?.max
    let numberOfSelectedOptions = selectedOptions.filter { $0.key.section == indexPath.section }

    if numberOfSelectedOptions.count == maxOptionForSection {
        return nil
    }

    return indexPath
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) as? OptionCell {
        cell.checkButton.isChecked = true
        cell.option.isSelected = true
        selectedOptions[indexPath] = cell.option
    }
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) as? OptionCell {
        cell.checkButton.isChecked = false
        cell.option.isSelected = false
        selectedOptions.removeValue(forKey: indexPath)
    }
}

SOLUTION

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    let optionCell = cell as! OptionCell

    if optionCell.option.isSelected {
        optionCell.checkButton.isChecked = true
    } else {
        optionCell.checkButton.isChecked = false
    }
}

Body:
This will limit it to the section in which the row was clicked:

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    if let selectedRows = tableView.indexPathsForSelectedRows?.filter({ $0.section == indexPath.section }) {
        if selectedRows.count == limit {
            return nil
        }
    }

    return indexPath
}


问:
Looping through a recordset to output Ms-Access report to a pdf file
I'm trying to get pdf file by tenant_id using docmd.outputTo. Unfortunately this routine produce output pdf file that all are in a same single tenant_id. If I remove docmd.outputTo last parameter pathName & fileName then it's require file name through dialogue and output file nicely filtered by tenant_id. Any help would be appreciated.

Here's the query of invoice: SELECT * FROM tblInvoice WHERE tenant_id = CurTenantID()

```<code>Public Sub Output()
    Dim MyRs As DAO.Recordset
    Dim rpt As Report
    Dim fileName As String, pathName As String, todayDate As String

    pathName = "C:\Users\abzalali\Dropbox\tenant_db\Invoice\"
    todayDate = Format(Date, "MMDDYYYY")
    Set MyRs = CurrentDb.OpenRecordset("SELECT tenant_id, name, company, email FROM qryEmailClientList")

    DoCmd.OpenReport "Invoice", acPreview, , , acHidden
    Set rpt = Reports("Invoice")

    With MyRs
        .MoveFirst
            Do While Not .EOF
                fileName = "Invoice_" & todayDate & !tenant_id & ".pdf"
                rpt.Filter = "[tenant_id] = " & !tenant_id
                rpt.FilterOn = True
                DoCmd.OutputTo acOutputReport, "Invoice", acFormatPDF, pathName & fileName
               .MoveNext
            Loop
    End With

End Sub
</code>```

答:
Since DoCmd.OutputTo lacks parameters for filtering, the best option is to base the report on a public function to get the current ID.

E.g.

```<code>' Function to both set and retrieve the current Tenant ID
Public Function CurTenantID(Optional SetTenantID As Long = 0) As Long

    Static TenantID As Long

    If SetTenantID > 0 Then
        TenantID = SetTenantID
    End If

    CurTenantID = TenantID

End Function
</code>```

Your report uses this function in its record source, e.g.

SELECT * FROM tblInvoice WHERE tenant_id = CurTenantID()
```

<p>And when generating the PDF reports in the loop, you use the <code>SetTenantID</code> parameter:</p>

```Public Sub Output()

    Dim MyRs As DAO.Recordset
    Dim fileName As String, pathName As String, todayDate As String

    pathName = "C:\Users\abzalali\Dropbox\tenant_db\Invoice\"
    todayDate = Format(Date, "MMDDYYYY")
    Set MyRs = CurrentDb.OpenRecordset("SELECT tenant_id, name, company, email FROM qryEmailClientList")

    With MyRs
        ' .MoveFirst -- unneeded after OpenRecordset()
        Do While Not .EOF
            fileName = "Invoice_" & todayDate & !tenant_id & ".pdf"
            Call CurTenantID(!tenant_id)
            DoCmd.OutputTo acOutputReport, "Invoice", acFormatPDF, pathName & fileName
            .MoveNext
        Loop
    End With

End Sub
```

Body:
I'm trying to get pdf file by tenant_id using docmd.outputTo. Unfortunately this routine produce output pdf file that all are in a same single tenant_id. If I remove docmd.outputTo last parameter pathName & fileName then it's require file name through dialogue and output file nicely filtered by tenant_id. Any help would be appreciated.

Here's the query of invoice: SELECT * FROM tblInvoice WHERE tenant_id = CurTenantID()

Public Sub Output()
    Dim MyRs As DAO.Recordset
    Dim rpt As Report
    Dim fileName As String, pathName As String, todayDate As String

    pathName = "C:\Users\abzalali\Dropbox\tenant_db\Invoice\"
    todayDate = Format(Date, "MMDDYYYY")
    Set MyRs = CurrentDb.OpenRecordset("SELECT tenant_id, name, company, email FROM qryEmailClientList")

    DoCmd.OpenReport "Invoice", acPreview, , , acHidden
    Set rpt = Reports("Invoice")

    With MyRs
        .MoveFirst
            Do While Not .EOF
                fileName = "Invoice_" & todayDate & !tenant_id & ".pdf"
                rpt.Filter = "[tenant_id] = " & !tenant_id
                rpt.FilterOn = True
                DoCmd.OutputTo acOutputReport, "Invoice", acFormatPDF, pathName & fileName
               .MoveNext
            Loop
    End With

End Sub

Body:
Since DoCmd.OutputTo lacks parameters for filtering, the best option is to base the report on a public function to get the current ID.

E.g.

' Function to both set and retrieve the current Tenant ID
Public Function CurTenantID(Optional SetTenantID As Long = 0) As Long

    Static TenantID As Long

    If SetTenantID > 0 Then
        TenantID = SetTenantID
    End If

    CurTenantID = TenantID

End Function

Your report uses this function in its record source, e.g.

SELECT * FROM tblInvoice WHERE tenant_id = CurTenantID()

And when generating the PDF reports in the loop, you use the SetTenantID parameter:

Public Sub Output()

    Dim MyRs As DAO.Recordset
    Dim fileName As String, pathName As String, todayDate As String

    pathName = "C:\Users\abzalali\Dropbox\tenant_db\Invoice\"
    todayDate = Format(Date, "MMDDYYYY")
    Set MyRs = CurrentDb.OpenRecordset("SELECT tenant_id, name, company, email FROM qryEmailClientList")

    With MyRs
        ' .MoveFirst -- unneeded after OpenRecordset()
        Do While Not .EOF
            fileName = "Invoice_" & todayDate & !tenant_id & ".pdf"
            Call CurTenantID(!tenant_id)
            DoCmd.OutputTo acOutputReport, "Invoice", acFormatPDF, pathName & fileName
            .MoveNext
        Loop
    End With

End Sub


问:
Graph API - Insufficient privileges to complete the operation
When trying to access the Graph Service Client using  I am receiving the error:

Code: Authorization_RequestDenied

Message: Insufficient privileges to complete the operation.

After researching this error the most common solution was to set the permissions for the API. This had already been done and has permissions to read basic/full profiles.

I've delete and re-added the APIs.

Below is the code in my AzureAuthenticationProvider class which inherits from IAuthenticationProvider:

```<code>public class AzureAuthenticationProvider : IAuthenticationProvider
{
    private string _azureDomain = "myDevDom.onmicrosoft.com";

    public async Task AuthenticateRequestAsync(HttpRequestMessage request)
    {
        try
        {
            string clientId = "2b823c67-1b0d-4a10-a9e1-737142516f5q";
            string clientSecret = "xxxxxx";

            AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/" + _azureDomain + "/oauth2/token");

            ClientCredential credentials = new ClientCredential(clientId, clientSecret);

            AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credentials);

            request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
        }
        catch (Exception ex)
        {
        }
    }
}
</code>```

I've tried changing the client secret to an invalid Id and it threw an error, so the client key is correct. I've  also tried to verify that the access token is valid by altering the access token, this also returns a error.

The above code seems to work fine.

Below is the code where I'm trying to access Azure AD:

```<code>public async Task<IGraphServiceUsersCollectionPage> GetUsersByLastName(string lastname)
{
    GraphServiceClient graphClient = new GraphServiceClient(new AzureAuthenticationProvider());
    string filter = String.Format("startswith(surname, '{0}')", lastname);
    IGraphServiceUsersCollectionPage users = await graphClient.Users.Request().Filter(filter).GetAsync(); //Fails on this line
    return users;
}
</code>```

答: Make sure click "Grant Permissions" and than Yes for all users accounts.

Body:
When trying to access the Graph Service Client using  I am receiving the error:

Code: Authorization_RequestDenied

Message: Insufficient privileges to complete the operation.

After researching this error the most common solution was to set the permissions for the API. This had already been done and has permissions to read basic/full profiles.

I've delete and re-added the APIs.

Below is the code in my AzureAuthenticationProvider class which inherits from IAuthenticationProvider:

public class AzureAuthenticationProvider : IAuthenticationProvider
{
    private string _azureDomain = "myDevDom.onmicrosoft.com";

    public async Task AuthenticateRequestAsync(HttpRequestMessage request)
    {
        try
        {
            string clientId = "2b823c67-1b0d-4a10-a9e1-737142516f5q";
            string clientSecret = "xxxxxx";

            AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/" + _azureDomain + "/oauth2/token");

            ClientCredential credentials = new ClientCredential(clientId, clientSecret);

            AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credentials);

            request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
        }
        catch (Exception ex)
        {
        }
    }
}

I've tried changing the client secret to an invalid Id and it threw an error, so the client key is correct. I've  also tried to verify that the access token is valid by altering the access token, this also returns a error.

The above code seems to work fine.

Below is the code where I'm trying to access Azure AD:

public async Task<IGraphServiceUsersCollectionPage> GetUsersByLastName(string lastname)
{
    GraphServiceClient graphClient = new GraphServiceClient(new AzureAuthenticationProvider());
    string filter = String.Format("startswith(surname, '{0}')", lastname);
    IGraphServiceUsersCollectionPage users = await graphClient.Users.Request().Filter(filter).GetAsync(); //Fails on this line
    return users;
}


问:
ChartJS Line chart cut off at the top and bottom
I'm using ChartJS to display some weather data. The problem I have is that the lines going right to the edge at the top and bottom look like they've been cut off.

I threw some example data together and uploaded it to this codepen: https://codepen.io/anon/pen/zELEWd

Is there some way to just add more space above the highest and the lowest point?

I read from this thread that there's the padding option, but that one affects the whole canvas and not the chart itself.

There are also some tips from this stockoverflow question, but I can't really put a suggestedMin and suggestedMax value in there, since I have more than one dataset in there that all have slightly different min and max values. (eg. for Pressure[hPa] I don't want to set suggestedMin to 0, since its values are all somewhere around 1200)

答:
A very recent fix is shown here.
You'd have to manually edit your Chart.js file src/controllers/controller.line.js
(For Angular 2, this file path will be located inside directory node_modules/chart.js/.)

Or just wait for the next Chart.js release which will most likely contain the fix.

An alternative workaround is described in comment 1 of this bug ticket: https://github.com/chartjs/Chart.js/issues/4202

Note that I posted the same comment to an identical question (though not for AngularJS):
https://stackoverflow.com/a/47306019/3061684


问:
Video training program
I am looking to create a video training program which records videos - via webcam, user screen capture and captures sound. Now the main problem is that I need a cross-platform (mac and windows) solutions.

I know its possible to use flash to record webcam + audio. But its not possible to record the user's screen via flash.

So am wonder if I should use Java (which i believe will work on mac & windows). I do not want to develop to separate versions because of the cost involved in developing two versions.

Please guide me as I am new to this.

Thank you.

UPDATE

Hello again,

I had a look at the following site: www.screencast-o-matic.com or www.screentoaster.com. I see that they have developed a java applet which helps interact with Windows/Mac to record the screen.

I am wondering how to go about developing something like that and integrating it with Flash (for webcam and audio recording).

Is this a better idea?

答: Try CamStudio. I don't know, if it works on Mac, but on windows, it's the best solution I know. It's open source, so you can use it's source code, if you want to :)</p>

OwnerDisplayName: Alec Smart

Title: Video training program

LastEditorDisplayName: Alec Smart

OwnerDisplayName: guerda


问:
Connecting two parallel join models in Rails
Let's say that I have Projects, Users, and two ways to connect Users to Projects - Rsvps and Memberships. Like so:

```<code>class User < ActiveRecord::Base
  has_many :memberships
  has_many :rsvps
  has_many :projects, :through => :memberships
end

class Project < ActiveRecord::Base
  has_many :memberships
  has_many :rsvps
  has_many :members, :through => :memberships, :class_name => 'User'
end

class Rsvp < ActiveRecord::Base
  belongs_to :project
  belongs_to :user
end

class Membership < ActiveRecord::Base
  belongs_to :project
  belongs_to :user
end
</code>```

Rsvps and Memberships are different enough in their other functions that I don't especially want to combine them into one model, but I do want to be able to associate Rsvps and Memberships. My ideal-world scenario would be something like this:

```<code>class Membership < ActiveRecord::Base
  has_one :rsvp, :through => [:project, :user]
end
</code>```

but obviously that's a pipe dream.

The two potential solutions I've thought of so far are trying to fake an association with something like

```<code>def rsvp
  project.rsvps.find(:conditions => {:user_id => user_id})
end
</code>```

but that's less than ideal as it doesn't duplicate all the fun other features that come with Association objects. Alternatively I could add a membership_id field to Rsvp, but that smells like it'll attract syncing-related bugs.

Does anyone have any better ideas?

答:
You could use the :conditions parameter to specify the has_one or has_many relationship:

```
has_one ... :conditions => lambda{ ['project_id = ? AND user_id = ?', self.project_id, self.user_id] }
```

I think you can also do this in a shorthand format, but make sure that you use single quotes and not double quotes in your definition:

```
has_one ... :conditions => 'project_id = #{project_id} AND user_id = #{user_id}'
```

Body:
Let's say that I have Projects, Users, and two ways to connect Users to Projects - Rsvps and Memberships. Like so:

class User < ActiveRecord::Base
  has_many :memberships
  has_many :rsvps
  has_many :projects, :through => :memberships
end

class Project < ActiveRecord::Base
  has_many :memberships
  has_many :rsvps
  has_many :members, :through => :memberships, :class_name => 'User'
end

class Rsvp < ActiveRecord::Base
  belongs_to :project
  belongs_to :user
end

class Membership < ActiveRecord::Base
  belongs_to :project
  belongs_to :user
end

Rsvps and Memberships are different enough in their other functions that I don't especially want to combine them into one model, but I do want to be able to associate Rsvps and Memberships. My ideal-world scenario would be something like this:

class Membership < ActiveRecord::Base
  has_one :rsvp, :through => [:project, :user]
end

but obviously that's a pipe dream.

The two potential solutions I've thought of so far are trying to fake an association with something like

def rsvp
  project.rsvps.find(:conditions => {:user_id => user_id})
end

but that's less than ideal as it doesn't duplicate all the fun other features that come with Association objects. Alternatively I could add a membership_id field to Rsvp, but that smells like it'll attract syncing-related bugs.

Does anyone have any better ideas?

Body:
You could use the :conditions parameter to specify the has_one or has_many relationship:

has_one ... :conditions => lambda{ ['project_id = ? AND user_id = ?', self.project_id, self.user_id] }

I think you can also do this in a shorthand format, but make sure that you use single quotes and not double quotes in your definition:

has_one ... :conditions => 'project_id = #{project_id} AND user_id = #{user_id}'


问:
Render string as html in filter-menu
I'm currently working with kendo Grid and I've run in to a issue..
In my grid I have a column that displays only FA (Font Awesome) icons. It looks like this:

```<code>columns: [
            {
                field: "Icon", encoded: false, title: " ",
                filterable: {
                    multi: true
                },
                width: "25px",
                attributes: {
                    "class": "custom-td"
                }
            }
</code>```

My datasource look like this: Icon = ""

In my grid I add encoded: false, and it then renders the string as HTML.
But I need to somehow do the same to the filter menu. As of right now, the filter looks like this:

I have found nowhere in the documentation on how to enable string to be rendered as HTML in the filter menu.
The perfect solution would be to add encoded: false below filterable.

I hope someone can help me, thank you in advance!

EDIT:
I'm adding this picture for further clarification.

答:
I solved my problem by creating a custom item template for the multi checkbox using the itemTemplate function.

Here's a dojo with an example.

Title: Render string as html in filter-menu

Body:
I'm currently working with kendo Grid and I've run in to a issue..
In my grid I have a column that displays only FA (Font Awesome) icons. It looks like this:

columns: [
            {
                field: "Icon", encoded: false, title: " ",
                filterable: {
                    multi: true
                },
                width: "25px",
                attributes: {
                    "class": "custom-td"
                }
            }

My datasource look like this: Icon = ""

In my grid I add encoded: false, and it then renders the string as HTML.
But I need to somehow do the same to the filter menu. As of right now, the filter looks like this:

I have found nowhere in the documentation on how to enable string to be rendered as HTML in the filter menu.
The perfect solution would be to add encoded: false below filterable.

I hope someone can help me, thank you in advance!

EDIT:
I'm adding this picture for further clarification.


问:
Getting textView margin and setting ImageView margin programatically.
In my current activity i'm trying to get margin of ImageView and write in TextView, but i always recieving "0". Top margin is about 390px.</p>

```<code>final ImageView Brick_1 = (ImageView)findViewById(R.id.Brick_1);
int a = Brick_1.getTop();

TextView t = (TextView) findViewById(R.id.tekstas);
t.setText(a+"");
</code>```

答:
You can use like that:</p>

```<code>LinearLayout.LayoutParams lp =(LinearLayout.LayoutParams) Brick_1.getLayoutParams();

int margin = lp.topMargin;
</code>```

Body:
In my current activity i'm trying to get margin of ImageView and write in TextView, but i always recieving "0". Top margin is about 390px.

final ImageView Brick_1 = (ImageView)findViewById(R.id.Brick_1);
int a = Brick_1.getTop();

TextView t = (TextView) findViewById(R.id.tekstas);
t.setText(a+"");

Body:
You can use like that:

LinearLayout.LayoutParams lp =(LinearLayout.LayoutParams) Brick_1.getLayoutParams();

int margin = lp.topMargin;


答:
```<code>>>> my_list = [1, 2, 3.25]
>>> all(isinstance(item, int) for item in my_list)
False
>>> other_list = range(3)
>>> all(isinstance(item, int) for item in other_list)
True
>>>
</code>```

Source: https://stackoverflow.com/a/6009630/6748523

Title: How can I assert that the argument only contains listed integers in Python

Body:
I have a method in Python and I only want to accept integers listed or singular, how can I define this?

def autoInt(integers):
    assert int(integers)
    assert len(integers) > 0

This fails as I cannot have a list. I'm sure it's something easy.

TypeError: int() argument must be a string or a number, not 'list'

Edit: I have been tasked so that this method can ONLY accept integers in a list.

Body:
>>> my_list = [1, 2, 3.25]
>>> all(isinstance(item, int) for item in my_list)
False
>>> other_list = range(3)
>>> all(isinstance(item, int) for item in other_list)
True
>>>

Source: https://stackoverflow.com/a/6009630/6748523


问:
How to limit query results with Django Rest filters
I am working on an api built with Django Rest Framework. I have defined several model classes and I have also created some filters to apply on certain queries that happen in the specified api-endpoints.

I am trying to apply LIMIT in the queryset but I would prefer to not
use the Django notation e.x. Entry.objects.all()[:5]. Instead I would like to be able to apply the limit from inside the filter associated with the model.

Until now I haven't find any solution. I am thinking that I should find a way to define a filter with default value something that would result in not limiting the queryset and if a request reaches the endpoint and contains something like ?filter=10 then the queryset should be limited to the first 10.

答:
You can extend or customize pagination classes available in drf

```<code>  class UserSpecificPagination(LimitOffsetPagination):
      def get_limit(self, request):
          if logic_met(request.user):
            self.max_limit = custom_limit
      return super(UserSpecificPagination, self).get_limit(request)
</code>```

set the class as pagination_class in ListAPIView or DRF settings

Body:
You can extend or customize pagination classes available in drf

  class UserSpecificPagination(LimitOffsetPagination):
      def get_limit(self, request):
          if logic_met(request.user):
            self.max_limit = custom_limit
      return super(UserSpecificPagination, self).get_limit(request)

set the class as pagination_class in ListAPIView or DRF settings


答:
That depends on what passes as an integer by your definition. For example, do instances of bool count? Does the float 1.0?

Anyway - you can combine the all builtin with a generator expression.

```<code>>>> a = [1,2,True]
>>> all(isinstance(x, int) for x in a)
True
</code>```

As a sidenote: rigorously checking the argument types in not something Python programmers do when there's no specific reason. A better approach is usually to write clear docstrings and/or type hints.

Here is an answer which explains how to do the latter. Apart from that, there's usually a "garbage in -> garbage (or error)" out mentality.

Body:
That depends on what passes as an integer by your definition. For example, do instances of bool count? Does the float 1.0?

Anyway - you can combine the all builtin with a generator expression.

>>> a = [1,2,True]
>>> all(isinstance(x, int) for x in a)
True

As a sidenote: rigorously checking the argument types in not something Python programmers do when there's no specific reason. A better approach is usually to write clear docstrings and/or type hints.

Here is an answer which explains how to do the latter. Apart from that, there's usually a "garbage in -> garbage (or error)" out mentality.


问:
How to make tkinter button raised before executing command
Am trying to make GUI app which compulsory you have to select one of predict button before the number entered will be printed to the terminal,if none of predictbutton is selected the should print outselect predict button to proceed.

In pseudecode something like:

```<code>def check:
    now = new.get()
    if no lotto_button is selected:
        print("select predict button to proceed")
    else:
        print(now)
</code>```

But having  challenges:

1:when i select one predict button both buttons raised.

2:How to make the predict compulsory to be selected before the content in the entry will  be printed.

```<code>import tkinter as tk

def terminal():
    now = new.get()
    print(now)

def start_func():
    lotto_button.configure(relief=tk.SUNKEN, state=tk.DISABLED)
    lotto_button1.configure(relief=tk.SUNKEN, state=tk.DISABLED)

def stop_func():
    lotto_button.configure(relief=tk.RAISED, state=tk.ACTIVE)
    lotto_button1.configure(relief=tk.RAISED, state=tk.ACTIVE)

root = tk.Tk()
root.geometry("400x400")

new = tk.StringVar()
en = tk.Entry(root, textvariable=new).pack()

lotto_button = tk.Button(root, text="predict one", command=start_func)
lotto_button.pack(side="left")
lotto_button1 = tk.Button(root, text="predict two", command=start_func)
lotto_button1.pack()

tk.Button(root, text="print number", command=lambda :[stop_func(),
terminal()]).place(x=150, y=300)

root.mainloop()
</code>```

Thank you and your advice to do is welcome.

答:
As for making it compulsory for picking, you can define a flag in outermost scope (in same level as root = tk.Tk()) so that you can see in your functions if it's set or not like:

```<code>isPredicted = False
</code>```

And as for disabling each button when one is picked, you can define your your start_func such that it takes button object (lotto_button or lotto_button1) as argument:

```<code>def start_func(button_object):

    global isPredicted
    isPredicted = True

    button_object.configure(relief=tk.SUNKEN, state=tk.DISABLED)
</code>```

To be able to use this function, you need to configure your buttons in the following way, so that they pass themselves as the argument:

```<code>lotto_button.configure(command=lambda button_object=lotto_button: start_func(button_object))

lotto_button1.configure(command=lambda button_object=lotto_button1: start_func(button_object))
</code>```

You should have isPredicted flag in your stop_func as well so that it unsets it:

```<code>def stop_func():

    global isPredicted
    isPredicted = False

    lotto_button.configure(relief=tk.RAISED, state=tk.ACTIVE)
    lotto_button1.configure(relief=tk.RAISED, state=tk.ACTIVE)
</code>```

As for your terminal function, you'd want to act based on the state of isPredicted so it needs to be defined as:

```<code>def terminal():

    global isPredicted

    if isPredicted:
        now = new.get()
        print(now)

    else:
        print("select predict button to proceed")
</code>```

finally in your "print number" button you need to swap the order of the functions in lambda or isPredicted is always False as far as that button's command is concerned:

```<code>tk.Button(root, text="print number", command=lambda :[terminal(),
stop_func()]).place(x=150, y=300)
</code>```

Your final code should look like:

```<code>import tkinter as tk
from tkinter import messagebox

def terminal():

    global isPredicted

    if isPredicted:
        now = new.get()
        print(now)

    else:
        print("select predict button to proceed")

def start_func(button_object):

    global isPredicted
    isPredicted = True

    button_object.configure(relief=tk.SUNKEN, state=tk.DISABLED)

def stop_func():

    global isPredicted
    isPredicted = False

    lotto_button.configure(relief=tk.RAISED, state=tk.ACTIVE)
    lotto_button1.configure(relief=tk.RAISED, state=tk.ACTIVE)

root = tk.Tk()
root.geometry("400x400")

new = tk.StringVar()
en = tk.Entry(root, textvariable=new).pack()

isPredicted = False

lotto_button = tk.Button(root, text="predict one")
lotto_button.configure(command=lambda button_object=lotto_button: start_func(button_object))
lotto_button.pack(side="left")
lotto_button1 = tk.Button(root, text="predict two")
lotto_button1.configure(command=lambda button_object=lotto_button1: start_func(button_object))
lotto_button1.pack()

tk.Button(root, text="print number", command=lambda :[terminal(),
stop_func()]).place(x=150, y=300)

root.mainloop()
</code>```

Body:
Am trying to make GUI app which compulsory you have to select one of predict button before the number entered will be printed to the terminal,if none of predictbutton is selected the should print outselect predict button to proceed.

In pseudecode something like:

def check:
    now = new.get()
    if no lotto_button is selected:
        print("select predict button to proceed")
    else:
        print(now)

But having  challenges:

1:when i select one predict button both buttons raised.

2:How to make the predict compulsory to be selected before the content in the entry will  be printed.

import tkinter as tk

def terminal():
    now = new.get()
    print(now)

def start_func():
    lotto_button.configure(relief=tk.SUNKEN, state=tk.DISABLED)
    lotto_button1.configure(relief=tk.SUNKEN, state=tk.DISABLED)

def stop_func():
    lotto_button.configure(relief=tk.RAISED, state=tk.ACTIVE)
    lotto_button1.configure(relief=tk.RAISED, state=tk.ACTIVE)

root = tk.Tk()
root.geometry("400x400")

new = tk.StringVar()
en = tk.Entry(root, textvariable=new).pack()

lotto_button = tk.Button(root, text="predict one", command=start_func)
lotto_button.pack(side="left")
lotto_button1 = tk.Button(root, text="predict two", command=start_func)
lotto_button1.pack()

tk.Button(root, text="print number", command=lambda :[stop_func(),
terminal()]).place(x=150, y=300)

root.mainloop()

Thank you and your advice to do is welcome.

Body:
As for making it compulsory for picking, you can define a flag in outermost scope (in same level as root = tk.Tk()) so that you can see in your functions if it's set or not like:

isPredicted = False

And as for disabling each button when one is picked, you can define your your start_func such that it takes button object (lotto_button or lotto_button1) as argument:

def start_func(button_object):

    global isPredicted
    isPredicted = True

    button_object.configure(relief=tk.SUNKEN, state=tk.DISABLED)

To be able to use this function, you need to configure your buttons in the following way, so that they pass themselves as the argument:

lotto_button.configure(command=lambda button_object=lotto_button: start_func(button_object))

lotto_button1.configure(command=lambda button_object=lotto_button1: start_func(button_object))

You should have isPredicted flag in your stop_func as well so that it unsets it:

def stop_func():

    global isPredicted
    isPredicted = False

    lotto_button.configure(relief=tk.RAISED, state=tk.ACTIVE)
    lotto_button1.configure(relief=tk.RAISED, state=tk.ACTIVE)

As for your terminal function, you'd want to act based on the state of isPredicted so it needs to be defined as:

def terminal():

    global isPredicted

    if isPredicted:
        now = new.get()
        print(now)

    else:
        print("select predict button to proceed")

finally in your "print number" button you need to swap the order of the functions in lambda or isPredicted is always False as far as that button's command is concerned:

tk.Button(root, text="print number", command=lambda :[terminal(),
stop_func()]).place(x=150, y=300)

Your final code should look like:

import tkinter as tk
from tkinter import messagebox

def terminal():

    global isPredicted

    if isPredicted:
        now = new.get()
        print(now)

    else:
        print("select predict button to proceed")

def start_func(button_object):

    global isPredicted
    isPredicted = True

    button_object.configure(relief=tk.SUNKEN, state=tk.DISABLED)

def stop_func():

    global isPredicted
    isPredicted = False

    lotto_button.configure(relief=tk.RAISED, state=tk.ACTIVE)
    lotto_button1.configure(relief=tk.RAISED, state=tk.ACTIVE)

root = tk.Tk()
root.geometry("400x400")

new = tk.StringVar()
en = tk.Entry(root, textvariable=new).pack()

isPredicted = False

lotto_button = tk.Button(root, text="predict one")
lotto_button.configure(command=lambda button_object=lotto_button: start_func(button_object))
lotto_button.pack(side="left")
lotto_button1 = tk.Button(root, text="predict two")
lotto_button1.configure(command=lambda button_object=lotto_button1: start_func(button_object))
lotto_button1.pack()

tk.Button(root, text="print number", command=lambda :[terminal(),
stop_func()]).place(x=150, y=300)

root.mainloop()


问:
Scroll to bottom when dynamically inflating view
I have a LinearLayout and I'm inflating a CardView in it like this:

```<code>final LinearLayout itineraryDetailLL = (LinearLayout) findViewById(R.id.itineraryDetailLinearlayout);
final View childView = getLayoutInflater().inflate(R.layout.cardview, null);
itineraryDetailLL.addView(childView);
</code>```

The inflation of the child view is done on a onclick of a button. I want to scroll to the bottom of the screen whenever a new cardview is inflated. I'm doing it like this:

```<code>ScrollView scrollview = ((ScrollView) findViewById(R.id.masterScrollView));
scrollview.fullScroll(View.FOCUS_DOWN);
</code>```

but this scrolls to somewhere middle of the screen and not to bottom. What am I doing wrong?

答:
You have to post an event to happen on the next frame, when this ScrollView would be laid out:

```
<code>
    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
        }
    });
</code>
```

Body:
I have a LinearLayout and I'm inflating a CardView in it like this:

final LinearLayout itineraryDetailLL = (LinearLayout) findViewById(R.id.itineraryDetailLinearlayout);
final View childView = getLayoutInflater().inflate(R.layout.cardview, null);
itineraryDetailLL.addView(childView);

The inflation of the child view is done on a onclick of a button. I want to scroll to the bottom of the screen whenever a new cardview is inflated. I'm doing it like this:

ScrollView scrollview = ((ScrollView) findViewById(R.id.masterScrollView));
scrollview.fullScroll(View.FOCUS_DOWN);

but this scrolls to somewhere middle of the screen and not to bottom. What am I doing wrong?

Body:
You have to post an event to happen on the next frame, when this ScrollView would be laid out:

    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
        }
    });


问:
how to select Table View row selection with custom checkbox button?
How to select tableview row with custom button . i have another button called select all its outside of the table view my question is while clicking outside of the tableview button how to select and deselect inside tableview rows? At the same time i could able to select single row in the tableview ? how to do it in swift 3? This is my code in cellforrow method</p>

```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let identifier = "Custom"
    var cell: TStudentAttendanceCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? TStudentAttendanceCell
    if cell == nil {
        tableView.register(UINib(nibName: "TStudentAttendanceCell", bundle: nil), forCellReuseIdentifier: identifier)
        cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? TStudentAttendanceCell
    }
    print("studentAttendanvceArray--",studentAttendanceArray.object(at: indexPath.row) )
    var localDic :NSDictionary!

    localDic = studentAttendanceArray.object(at: indexPath.row) as! NSDictionary

    Common.sharedInstance.StopActivity()
    cell.profile_img.image = self.image
    cell.name_lbl.text = localDic["student_name"] as? String
    cell.selectionStyle = UITableViewCellSelectionStyle.none
    cell.contentView.backgroundColor = UIColor.clear
    let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 8, width: self.view.frame.size.width - 20, height: 90))

    whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9])
    whiteRoundedView.layer.masksToBounds = false
    whiteRoundedView.layer.cornerRadius = 2.0
    whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
    whiteRoundedView.layer.shadowOpacity = 0.2
    cell.contentView.addSubview(whiteRoundedView)
    cell.contentView.sendSubview(toBack: whiteRoundedView)

    return cell

}
</code>```

答:
ViewController

```<code>class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

  @IBOutlet var tableView: UITableView!
  var allStudentsArr:[[String:String]] = []
  var selectedRows:[IndexPath] = []

  override func viewDidLoad() {
    super.viewDidLoad()
    tableView.allowsSelection = false
    allStudentsArr = [["name":"name1"],["name":"name2"],["name":"name3"],["name":"name4"],["name":"name5"],["name":"name6"],["name":"name7"],["name":"name8"]]
  }
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return allStudentsArr.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CustomTableViewCell
    cell.nameLbl.text = allStudentsArr[indexPath.row]["name"]
    if selectedRows.contains(indexPath)
    {
      cell.checkBox.setImage(UIImage(named:"selected"), for: .normal)
    }
    else
    {
      cell.checkBox.setImage(UIImage(named:"unselected"), for: .normal)
    }
    cell.checkBox.tag = indexPath.row
    cell.checkBox.addTarget(self, action: #selector(checkBoxSelection(_:)), for: .touchUpInside)
    return cell
  }
  @objc func checkBoxSelection(_ sender:UIButton)
  {
    let selectedIndexPath = IndexPath(row: sender.tag, section: 0)
    if self.selectedRows.contains(selectedIndexPath)
    {
      self.selectedRows.remove(at: self.selectedRows.index(of: selectedIndexPath)!)
    }
    else
    {
      self.selectedRows.append(selectedIndexPath)
    }
    self.tableView.reloadData()
  }
  @IBAction func selectAllBtnAction(_ sender: UIBarButtonItem) {
    self.selectedRows = getAllIndexPaths()
    self.tableView.reloadData()
  }

  func getAllIndexPaths() -> [IndexPath] {
    var indexPaths: [IndexPath] = []
      for j in 0..<tableView.numberOfRows(inSection: 0) {
        indexPaths.append(IndexPath(row: j, section: 0))
      }
        return indexPaths
  }
}
</code>```

Custom Cell

```<code>class CustomTableViewCell: UITableViewCell {

  @IBOutlet var nameLbl: UILabel!
  @IBOutlet var checkBox: UIButton!
}
</code>```

Body:
How to select tableview row with custom button . i have another button called select all its outside of the table view my question is while clicking outside of the tableview button how to select and deselect inside tableview rows? At the same time i could able to select single row in the tableview ? how to do it in swift 3? This is my code in cellforrow method

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let identifier = "Custom"
    var cell: TStudentAttendanceCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? TStudentAttendanceCell
    if cell == nil {
        tableView.register(UINib(nibName: "TStudentAttendanceCell", bundle: nil), forCellReuseIdentifier: identifier)
        cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? TStudentAttendanceCell
    }
    print("studentAttendanvceArray--",studentAttendanceArray.object(at: indexPath.row) )
    var localDic :NSDictionary!

    localDic = studentAttendanceArray.object(at: indexPath.row) as! NSDictionary

    Common.sharedInstance.StopActivity()
    cell.profile_img.image = self.image
    cell.name_lbl.text = localDic["student_name"] as? String
    cell.selectionStyle = UITableViewCellSelectionStyle.none
    cell.contentView.backgroundColor = UIColor.clear
    let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 8, width: self.view.frame.size.width - 20, height: 90))

    whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9])
    whiteRoundedView.layer.masksToBounds = false
    whiteRoundedView.layer.cornerRadius = 2.0
    whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
    whiteRoundedView.layer.shadowOpacity = 0.2
    cell.contentView.addSubview(whiteRoundedView)
    cell.contentView.sendSubview(toBack: whiteRoundedView)

    return cell

}

Body:
ViewController

class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

  @IBOutlet var tableView: UITableView!
  var allStudentsArr:[[String:String]] = []
  var selectedRows:[IndexPath] = []

  override func viewDidLoad() {
    super.viewDidLoad()
    tableView.allowsSelection = false
    allStudentsArr = [["name":"name1"],["name":"name2"],["name":"name3"],["name":"name4"],["name":"name5"],["name":"name6"],["name":"name7"],["name":"name8"]]
  }
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return allStudentsArr.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CustomTableViewCell
    cell.nameLbl.text = allStudentsArr[indexPath.row]["name"]
    if selectedRows.contains(indexPath)
    {
      cell.checkBox.setImage(UIImage(named:"selected"), for: .normal)
    }
    else
    {
      cell.checkBox.setImage(UIImage(named:"unselected"), for: .normal)
    }
    cell.checkBox.tag = indexPath.row
    cell.checkBox.addTarget(self, action: #selector(checkBoxSelection(_:)), for: .touchUpInside)
    return cell
  }
  @objc func checkBoxSelection(_ sender:UIButton)
  {
    let selectedIndexPath = IndexPath(row: sender.tag, section: 0)
    if self.selectedRows.contains(selectedIndexPath)
    {
      self.selectedRows.remove(at: self.selectedRows.index(of: selectedIndexPath)!)
    }
    else
    {
      self.selectedRows.append(selectedIndexPath)
    }
    self.tableView.reloadData()
  }
  @IBAction func selectAllBtnAction(_ sender: UIBarButtonItem) {
    self.selectedRows = getAllIndexPaths()
    self.tableView.reloadData()
  }

  func getAllIndexPaths() -> [IndexPath] {
    var indexPaths: [IndexPath] = []
      for j in 0..<tableView.numberOfRows(inSection: 0) {
        indexPaths.append(IndexPath(row: j, section: 0))
      }
        return indexPaths
  }
}

Custom Cell

class CustomTableViewCell: UITableViewCell {

  @IBOutlet var nameLbl: UILabel!
  @IBOutlet var checkBox: UIButton!
}


问:
docker-compose - env vars based on the ports
So I have 2 services running - my website and the API.

In my code for the website I specified that it should use the API that has port equal to API_PORT env var.

My question: is there a way to set the API_PORT variables based on the ports from api service?

Overview of my docker-compose.yml:

```<code>api-service:
    ...otherconfig
    ports:
      - 8009:8009
website:
    ...
</code>```

答:
Just inject the API_PORT env var into your compose file too:

export API_PORT=8009

then in the compose file

```<code>api-service:
    ...otherconfig
    ports:
      - ${API_PORT}:${API_PORT}
website:
    ...
</code>```

Body:
So I have 2 services running - my website and the API.

In my code for the website I specified that it should use the API that has port equal to API_PORT env var.

My question: is there a way to set the API_PORT variables based on the ports from api service?

Overview of my docker-compose.yml:

api-service:
    ...otherconfig
    ports:
      - 8009:8009
website:
    ...

Body:
Just inject the API_PORT env var into your compose file too:

export API_PORT=8009

then in the compose file

api-service:
    ...otherconfig
    ports:
      - ${API_PORT}:${API_PORT}
website:
    ...


问:
How to create a schema the mongo/nosql way
I am just trying to get into mongo (,couch or nosql in general), and started with good old blog example. From what I read on the mongo page entities should be put in a separate collection when there is the need for direct access, so I put comments and users within the posts-collection and have another collection for the categories.

My question is where to place the tags. I saw in some examples, that there were placed in the post collection as well, but I am not sure how to easily create a tag-cloud then

as mentioned: this is just for learning purpose..

thanks!
harpax

答:
You can store the tags in your document and then run an aggregate query on your documents to get the cloud ...

However, I'd think the best idea would be to run a query (on a schedule) to build your tag cloud as it's own document ... that way you can simple just query that document to build your list (instead of trying to run that on the fly each time.)

There is a great example of how to do this here.

http://cookbook.mongodb.org/patterns/count_tags/

Example Document

```<code>{
    "title" : "A blog post",
    "author" : "Kristina",
    "content" : "...",
    "tags" : ["MongoDB", "Map/Reduce", "Recipe"]
}
</code>```

Example Cloud

```<code>{"_id" : "MongoDB", "value" : 4}
{"_id" : "Map/Reduce", "value" : 2}
{"_id" : "Recipe", "value" : 7}
{"_id" : "Group", "value" : 1}
</code>```

Body:
You can store the tags in your document and then run an aggregate query on your documents to get the cloud ...

However, I'd think the best idea would be to run a query (on a schedule) to build your tag cloud as it's own document ... that way you can simple just query that document to build your list (instead of trying to run that on the fly each time.)

There is a great example of how to do this here.

http://cookbook.mongodb.org/patterns/count_tags/

Example Document

{
    "title" : "A blog post",
    "author" : "Kristina",
    "content" : "...",
    "tags" : ["MongoDB", "Map/Reduce", "Recipe"]
}

Example Cloud

{"_id" : "MongoDB", "value" : 4}
{"_id" : "Map/Reduce", "value" : 2}
{"_id" : "Recipe", "value" : 7}
{"_id" : "Group", "value" : 1}


问:
Orleans - how to implement storage sharding by Tenant with AdoNetStorageProvider
I am trying to find how we can implement storage sharding by tenant using the built in AdoNetStorageProvider.
We are planning for SQL Server on-premises.

for example:

Grain that belong to tenant 1 should persist to shard A

Grain that belong to tenant 2 should persist to shard B

Grain that belong to tenant 3 should persist to shard A

Where our Sharding function will indicate which shard to use.
For this purpose the sharding function gets its grain sharding from DB based on grain extended key. (so should not all be in configuration files, as number of shards rarely changes but new tenants added frequently).
If this can be implemented by some built in framework then even better.

AS Per https://dotnet.github.io/orleans/Documentation/Core-Features/Grain-Persistence.html?q=sharded#shardedstorageprovider
shardedstorageprovider will distribute (shard) the data equally across the shards based on hash function. which does not achieve this purpose. The shards may (or may not) be geo located.

The sharding example in github is referring to Elastic SQL Client on Azure which as per my understanding is not available for SQL server.

I know we can write our own storage provider. but whenever possible we try to stay with the core.

答:
Based on the answer on the project Gitter,
There is no built in ability to shard by tenant.

The way to implement this is by deriving from https://github.com/dotnet/orleans/blob/master/src/OrleansProviders/Storage/ShardedStorageProvider.cs
and overriding HashFunction method.
Credit to @SebastianStehle


问:
How can one function call another function in the same class? How to fix Unresolved reference error?
I want to create a class that includes two functions where one of them calls the other one, for example:

class Parser:

    def foo(a):
        return a

    def bar(b):
        return foo(b * 2)
```
<p>This errors out with:</p>
```Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in bar
NameError: name 'foo' is not defined
```

答:
You either forgot to have self as one of the parameters, or forgot to set the methods to be static with @staticmethod.

If you'd like the methods to be instance methods use self:

```<code>class Parser:

    def __init__(self):
        pass

    def foo(self, a):
           return a

    def bar(self, a):
           return self.bar(a)
</code>```

You will then have to create an instance of the parser and call bar on this instance, for example:

```<code>parser = Parser()
print(parser.bar('test'))
</code>```

If you'd like the methods to be static, you'll need to change your class to the following for the static method:

```<code>class Parser:
    @staticmethod
    def foo(a):
        return a

    @staticmethod
    def bar(a):
        return Parser.foo(a)
</code>```

This will allow you to call the functions without an instance.

```<code>print(Parser.bar('test'))
</code>```

Body:
I want to create a class that includes two functions where one of them calls the other one, for example:

class Parser:

    def foo(a):
        return a

    def bar(b):
        return foo(b * 2)

This errors out with:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in bar
NameError: name 'foo' is not defined

Body:
You either forgot to have self as one of the parameters, or forgot to set the methods to be static with @staticmethod.

If you'd like the methods to be instance methods use self:

class Parser:

    def __init__(self):
        pass

    def foo(self, a):
           return a

    def bar(self, a):
           return self.bar(a)

You will then have to create an instance of the parser and call bar on this instance, for example:

parser = Parser()
print(parser.bar('test'))

If you'd like the methods to be static, you'll need to change your class to the following for the static method:

class Parser:
    @staticmethod
    def foo(a):
        return a

    @staticmethod
    def bar(a):
        return Parser.foo(a)

This will allow you to call the functions without an instance.

print(Parser.bar('test'))


问:
Gradle Connection timed out
after updating android studio 2.3 to 3.0 i got lots of errors so many work i done it but didn't work

Error:Could not resolve all files for configuration ':app:debugCompileClasspath'.

Could not resolve com.android.support:appcompat-v7:26.1.0.
    Required by:
        project :app
  Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not parse POM https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom
  Already seen doctype.
  Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not get resource 'https://jcenter.bintray.com/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Could not HEAD 'https://jcenter.bintray.com/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Connect to jcenter.bintray.com:443 [jcenter.bintray.com/108.168.243.150] failed: Connection timed out: connect

gradle wrapper properties

```<code>#Mon Nov 06 17:20:27 IRST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
</code>```

my gradle  (module app)

```<code> apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "curlpagetutorial.example.com.mydd"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

New errors

Required by:
    project :app

Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not parse POM https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom
  Already seen doctype.

Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support.test:runner:1.0.1.

Could not resolve com.android.support.test.espresso:espresso-core:3.0.1.

I'm stuck here for long time please help me

答:
Ihave had the same problem.
Finally I fixed it ussing an external gradle instalation. To make it you need to configure File->Settings->Build,Execution and deployments->Gradle
Check -> Use local gradle distribution
Select gradle home instalation.

If you are using an corporative connection, you also have to configure gradle proxy properties configuring or creating file gradle.properties in folder "/Users/user/.gradle":

```<code>#http proxy setup
systemProp.http.proxyHost=url
systemProp.http.proxyPort=port
systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost

#https proxy setup
systemProp.https.proxyHost=url
systemProp.https.proxyPort=port
systemProp.https.nonProxyHosts=*.nonproxyrepos.com|localhost
</code>```

That's all!

Title: Gradle Connection timed out

Body:
after updating android studio 2.3 to 3.0 i got lots of errors so many work i done it but didn't work

Error:Could not resolve all files for configuration ':app:debugCompileClasspath'.

Could not resolve com.android.support:appcompat-v7:26.1.0.
    Required by:
        project :app
  Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not parse POM https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom
  Already seen doctype.
  Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not get resource 'https://jcenter.bintray.com/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Could not HEAD 'https://jcenter.bintray.com/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Connect to jcenter.bintray.com:443 [jcenter.bintray.com/108.168.243.150] failed: Connection timed out: connect

gradle wrapper properties

#Mon Nov 06 17:20:27 IRST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

my gradle  (module app)

 apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "curlpagetutorial.example.com.mydd"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

New errors

Required by:
    project :app

Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not parse POM https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom
  Already seen doctype.

Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support.test:runner:1.0.1.

Could not resolve com.android.support.test.espresso:espresso-core:3.0.1.

I'm stuck here for long time please help me

Body:
Ihave had the same problem.
Finally I fixed it ussing an external gradle instalation. To make it you need to configure File->Settings->Build,Execution and deployments->Gradle
Check -> Use local gradle distribution
Select gradle home instalation.

If you are using an corporative connection, you also have to configure gradle proxy properties configuring or creating file gradle.properties in folder "/Users/user/.gradle":

#http proxy setup
systemProp.http.proxyHost=url
systemProp.http.proxyPort=port
systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost

#https proxy setup
systemProp.https.proxyHost=url
systemProp.https.proxyPort=port
systemProp.https.nonProxyHosts=*.nonproxyrepos.com|localhost

That's all!


问:
What Datatypes should i use for following requirement in C#
First I will explain the name of different properties and function that will be performed on them.
Afterwards you tell me which datatype should i use for them ??

1) Gross Weight(user will enter) : Will be in quintals(weight category). For Example : 147.3800.

2) Less Tear(user will enter : Also be in quintals(weight category). For Example : .3800.

3) Net Weight(Auto-Computed) : In quintals(weight category). For Example : GrossWeight - Less Tear.

4) Rate/Quintal(user will enter) : Amount for per quintal. For Example : 4560.55

5) Total Amount(Auto-Computed) : For Example : NetWeight x Rate/Quintal

Now tell me the preferable data-types for above five fields in C#.

答:
When possible, use decimal for money (#4 and #5) to avoid floating-point representation errors.

For physical measurements like weight, or for irrational-valued functions like sin or log, prefer double.


问:
List comprehension rebinds names even after scope of comprehension. Is this right?
Comprehensions show unusual interactions with scoping. Is this the expected behavior?

```<code>x = "original value"
squares = [x**2 for x in range(5)]
print(x)  # Prints 4 in Python 2!
</code>```

At the risk of whining, this is a brutal source of errors. As I write new code, I just occasionally find very weird errors due to rebinding -- even now that I know it's a problem. I need to make a rule like "always preface temp vars in list comprehensions with underscore", but even that's not foolproof.
The fact that there's this random time-bomb waiting kind of negates all the nice "ease of use" of list comprehensions.

答:
some workaround, for python 2.6, when this behaviour is not desirable</p>

```<code># python
Python 2.6.6 (r266:84292, Aug  9 2016, 06:11:56)
Type "help", "copyright", "credits" or "license" for more information.
>>> x=0
>>> a=list(x for x in xrange(9))
>>> x
0
>>> a=[x for x in xrange(9)]
>>> x
8
</code>```

Body:
Comprehensions show unusual interactions with scoping. Is this the expected behavior?

x = "original value"
squares = [x**2 for x in range(5)]
print(x)  # Prints 4 in Python 2!

At the risk of whining, this is a brutal source of errors. As I write new code, I just occasionally find very weird errors due to rebinding -- even now that I know it's a problem. I need to make a rule like "always preface temp vars in list comprehensions with underscore", but even that's not foolproof.
The fact that there's this random time-bomb waiting kind of negates all the nice "ease of use" of list comprehensions.

Body:
some workaround, for python 2.6, when this behaviour is not desirable

# python
Python 2.6.6 (r266:84292, Aug  9 2016, 06:11:56)
Type "help", "copyright", "credits" or "license" for more information.
>>> x=0
>>> a=list(x for x in xrange(9))
>>> x
0
>>> a=[x for x in xrange(9)]
>>> x
8


问:
Android Life cycle
In what cases on Destroy method is not called but application is killed out? I didn't make such situation, but need to do it. So I need to get a situation where on Destroy method will not be called but application will be killed?</p>

答:
onStop() will be called every time but onDestroy() will not be called if

• User remove application from recent

• User force stop application from app info

• User uninstalls application even if App is in background.

Title: Android Life cycle


问:
Where to put inner classes?
Some might like to argue that this is a candidate for the least important issue of all times. Yet code style is a very important topic for me, and I want to ensure that I write code in a readable way - for me and the majority of developers.

That's why I'm wondering where you guys are declaring your inner classes.

I'm following the following method ordering scheme, because it is quite common:

```<code>public void foo() {
    usedByFoo();
}

private void usedByFoo() {
}

public void bar() {
}
</code>```

I order them from top to bottom, every method as close to where it is used.

Now I could do the same with inner classes, like this:

```<code>class Outer {
    private Inner inner;

    private class Inner {};

    public Outer() {
    }

    ...
}
</code>```

I think this is the most consistent style to follow for me, but I've also often seen people declare all inner classes either at the top or at the bottom of the file.

Which style should I follow, given my way of ordering methods? What is the most common way to do this?

答:
My preferred style is to put them wherever they seem to make most sense. Usually this is at the bottom so they're out the way, but sometimes I find it makes more sense to put them before a certain group of methods (if these are the methods that use the inner class.)

If the class gets too unwieldy with loads of methods and inner classes though, it's probably a bad design choice (cohesion is too low.) I've sometimes let classes get this way by accident and they're horrible to deal with later - these days if I can see one going that way I'll generally refactor it out, perhaps even into its own package. If you get to the point where you've got so many inner classes you don't know what to do with them, I'd take this approach. There's even some that advise against using inner classes at all for this reason (though I disagree - they're a valuable resource when used properly, you just need to take care they don't get out of hand.

Title: Where to put inner classes?

Body:
Some might like to argue that this is a candidate for the least important issue of all times. Yet code style is a very important topic for me, and I want to ensure that I write code in a readable way - for me and the majority of developers.

That's why I'm wondering where you guys are declaring your inner classes.

I'm following the following method ordering scheme, because it is quite common:

public void foo() {
    usedByFoo();
}

private void usedByFoo() {
}

public void bar() {
}

I order them from top to bottom, every method as close to where it is used.

Now I could do the same with inner classes, like this:

class Outer {
    private Inner inner;

    private class Inner {};

    public Outer() {
    }

    ...
}

I think this is the most consistent style to follow for me, but I've also often seen people declare all inner classes either at the top or at the bottom of the file.

Which style should I follow, given my way of ordering methods? What is the most common way to do this?


问:
Windows form setting datetimepicker to 31st march of every year
```<code>private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    {

    }
</code>```

Right now the code display current date in the date time picker.
How do I display 31st March in 2017 and once it is 2018, it will display 31st March 2018 and so on and so forth as the year progress

Anyone help would be greatly appreciated

答:
```<code>int currentYear = DateTime.Today.Year;
DateTime desiredDate = new DateTime(currentYear, 3, 31);
</code>```

Additional info: apparently Asker doesn't know class DateTime

You asked:

How do I display 31st March in 2017 and once it is 2018, it will
  display 31st March 2018 and so on and so forth as the year progress

This is a difficult way to say that you want  31 march of the current year (= the year of Today)

DateTime.Today fetches the date of Today (surprise, surprise!)

Property Year contains the Year of Today

On 15th November 2017, Year was 2017

new DateTime(currentYear, 3, 31) will make the date of 31st March of the current year (which in my example was 2017

Surely you did read the documentation of the DateTime structure, didn't you?

Body:
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    {

    }

Right now the code display current date in the date time picker.
How do I display 31st March in 2017 and once it is 2018, it will display 31st March 2018 and so on and so forth as the year progress

Anyone help would be greatly appreciated

Body:
int currentYear = DateTime.Today.Year;
DateTime desiredDate = new DateTime(currentYear, 3, 31);

Additional info: apparently Asker doesn't know class DateTime

You asked:

How do I display 31st March in 2017 and once it is 2018, it will
  display 31st March 2018 and so on and so forth as the year progress

This is a difficult way to say that you want  31 march of the current year (= the year of Today)

DateTime.Today fetches the date of Today (surprise, surprise!)

Property Year contains the Year of Today

On 15th November 2017, Year was 2017

new DateTime(currentYear, 3, 31) will make the date of 31st March of the current year (which in my example was 2017

Surely you did read the documentation of the DateTime structure, didn't you?