问:
Tesseract invalid memory access when i am using tess4j1.3.0
When using OCR tess4j using rest controller getting exception "java.lang.Error: Invalid memory access". Have also set the data path but as soon as i run the program it throws the above mentioned exception.
And i have added the -Djava.jna.path with the libtesseract 302 dll. As withouth specifying the jna path i was getting "UnsatisfiedLinkError".

My Rest Controller Code

```<code> private Logger LOGGER = LoggerFactory.getLogger(Tess4jV1.class);

        @Autowired
        private ImageRepository repository;

        @RequestMapping(value = "ocr/ping", method = RequestMethod.GET)
        public Status ping() throws Exception {
            return new Status("OK");
        }

        @RequestMapping(value = "ocr/v0.9/upload", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
        public Status doOcrFile(@RequestBody final Image image) throws Exception {
            // File tmpFile = File.createTempFile("ocr_image",
            // image.getExtension());
            String uplodPath = "";
            String selectedDocument = "";

            String OriginalFilename = "ocr_image";

            byte[] bytes = image.getImage();

            uplodPath = System.getProperty("java.io.tmpdir");
            uplodPath = uplodPath.replace("\\", "/");
            if (!uplodPath.endsWith("/"))
                uplodPath = uplodPath + "/";
            uplodPath = uplodPath + "OCR_DMSIMGS";
            File fath = new File(uplodPath);
            if (!fath.exists())
                fath.mkdirs();
            String fileNme = "";
            String recogniseStr = "";
            try {
                fileNme = System.nanoTime() + OriginalFilename;
                uplodPath = uplodPath + "/" + fileNme + image.getExtension();
                FileOutputStream dfos = new FileOutputStream(uplodPath);
                dfos.write(bytes);
                dfos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.err.println(fath.getAbsolutePath());
            //
            // System.err.println(tmpFile.getAbsolutePath());
            try {
                // FileUtils.writeByteArrayToFile(tmpFile,
                // Base64.decodeBase64(image.getImage()));
                Tesseract tesseract = Tesseract.getInstance(); // JNA Interface
                                                                // Mapping
                tesseract.setDatapath("C://Users//58181.INFOTECH//Downloads//Tess4J-1.3-src//Tess4J//tessdata");
                ImageIO.scanForPlugins();
                String imageText = tesseract.doOCR(new File(uplodPath));
                LOGGER.debug("OCR Image Text = " + imageText);
            } catch (Exception e) {
                LOGGER.error("Exception while converting/uploading image: ", e);
                throw new TesseractException();
            } /*
                 * finally { tmpFile.delete(); }
                 */
            return new Status("success");
        }

        @RequestMapping(value = "ocr/v1/upload", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
        public Status doOcr(@RequestBody Image image) throws Exception {
            try {
                // FileUtils.writeByteArrayToFile(tmpFile,
                // Base64.decodeBase64(image.getImage()));
                ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(image.getImage()));
                Tesseract tesseract = Tesseract.getInstance(); // JNA Interface
                                                                // Mapping
                String imageText = tesseract.doOCR(ImageIO.read(bis));
                image.setText(imageText);
                repository.save(image);
                LOGGER.debug("OCR Result = " + imageText);
            } catch (Exception e) {
                LOGGER.error("TessearctException while converting/uploading image: ", e);
                throw new TesseractException();
            }

            return new Status("success");
        }

        @RequestMapping(value = "ocr/v1/images/users/{userId}", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
        public List<Image> getUserImages(@PathVariable String userId) throws Exception {
            List<Image> userImages = new ArrayList<>();
            try {
                userImages = repository.findByUserId(userId);
            } catch (Exception e) {
                LOGGER.error("Exception occurred finding image for userId: {} ", userId, e);
                throw new Exception();
            }
            return userImages;
        }
</code>```

Exception:

```<code>Adding paths from jna.library.path: C:\Users\58181.INFOTECH\Downloads\Tess4J-1.3-src\Tess4J\lib\win32-x86-64
Trying C:\Users\58181.INFOTECH\Downloads\Tess4J-1.3-src\Tess4J\lib\win32-x86-64\libtesseract302.dll
Found library 'libtesseract302' at C:\Users\58181.INFOTECH\Downloads\Tess4J-1.3-src\Tess4J\lib\win32-x86-64\libtesseract302.dll
9226 [http-nio-8080-exec-2] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.Error: Invalid memory access] with root cause
java.lang.Error: Invalid memory access
    at net.sourceforge.tess4j.TessAPI1.TessBaseAPIInit2(Native Method)
    at net.sourceforge.tess4j.Tesseract1.init(Tesseract1.java:274)
    at net.sourceforge.tess4j.Tesseract1.doOCR(Tesseract1.java:209)
    at net.sourceforge.tess4j.Tesseract1.doOCR(Tesseract1.java:158)
    at net.sourceforge.tess4j.Tesseract1.doOCR(Tesseract1.java:142)
    at com.tess4j.rest.OcrRestController.doOcrFile(OcrRestController.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
</code>```

答:
Invalid memory access for Tess4J usually means incorrect datapath, which should be set to the parent folder of tessdata folder, such as:

tesseract.setDatapath("C:/Users/58181.INFOTECH/Downloads/Tess4J-1.3-src/Tess4J/");

Note the double slashes should be double backslashes or single slashes.

Body:
When using OCR tess4j using rest controller getting exception "java.lang.Error: Invalid memory access". Have also set the data path but as soon as i run the program it throws the above mentioned exception.
And i have added the -Djava.jna.path with the libtesseract 302 dll. As withouth specifying the jna path i was getting "UnsatisfiedLinkError".

My Rest Controller Code

 private Logger LOGGER = LoggerFactory.getLogger(Tess4jV1.class);

        @Autowired
        private ImageRepository repository;

        @RequestMapping(value = "ocr/ping", method = RequestMethod.GET)
        public Status ping() throws Exception {
            return new Status("OK");
        }

        @RequestMapping(value = "ocr/v0.9/upload", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
        public Status doOcrFile(@RequestBody final Image image) throws Exception {
            // File tmpFile = File.createTempFile("ocr_image",
            // image.getExtension());
            String uplodPath = "";
            String selectedDocument = "";

            String OriginalFilename = "ocr_image";

            byte[] bytes = image.getImage();

            uplodPath = System.getProperty("java.io.tmpdir");
            uplodPath = uplodPath.replace("\\", "/");
            if (!uplodPath.endsWith("/"))
                uplodPath = uplodPath + "/";
            uplodPath = uplodPath + "OCR_DMSIMGS";
            File fath = new File(uplodPath);
            if (!fath.exists())
                fath.mkdirs();
            String fileNme = "";
            String recogniseStr = "";
            try {
                fileNme = System.nanoTime() + OriginalFilename;
                uplodPath = uplodPath + "/" + fileNme + image.getExtension();
                FileOutputStream dfos = new FileOutputStream(uplodPath);
                dfos.write(bytes);
                dfos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.err.println(fath.getAbsolutePath());
            //
            // System.err.println(tmpFile.getAbsolutePath());
            try {
                // FileUtils.writeByteArrayToFile(tmpFile,
                // Base64.decodeBase64(image.getImage()));
                Tesseract tesseract = Tesseract.getInstance(); // JNA Interface
                                                                // Mapping
                tesseract.setDatapath("C://Users//58181.INFOTECH//Downloads//Tess4J-1.3-src//Tess4J//tessdata");
                ImageIO.scanForPlugins();
                String imageText = tesseract.doOCR(new File(uplodPath));
                LOGGER.debug("OCR Image Text = " + imageText);
            } catch (Exception e) {
                LOGGER.error("Exception while converting/uploading image: ", e);
                throw new TesseractException();
            } /*
                 * finally { tmpFile.delete(); }
                 */
            return new Status("success");
        }

        @RequestMapping(value = "ocr/v1/upload", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
        public Status doOcr(@RequestBody Image image) throws Exception {
            try {
                // FileUtils.writeByteArrayToFile(tmpFile,
                // Base64.decodeBase64(image.getImage()));
                ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(image.getImage()));
                Tesseract tesseract = Tesseract.getInstance(); // JNA Interface
                                                                // Mapping
                String imageText = tesseract.doOCR(ImageIO.read(bis));
                image.setText(imageText);
                repository.save(image);
                LOGGER.debug("OCR Result = " + imageText);
            } catch (Exception e) {
                LOGGER.error("TessearctException while converting/uploading image: ", e);
                throw new TesseractException();
            }

            return new Status("success");
        }

        @RequestMapping(value = "ocr/v1/images/users/{userId}", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
        public List<Image> getUserImages(@PathVariable String userId) throws Exception {
            List<Image> userImages = new ArrayList<>();
            try {
                userImages = repository.findByUserId(userId);
            } catch (Exception e) {
                LOGGER.error("Exception occurred finding image for userId: {} ", userId, e);
                throw new Exception();
            }
            return userImages;
        }

Exception:

Adding paths from jna.library.path: C:\Users\58181.INFOTECH\Downloads\Tess4J-1.3-src\Tess4J\lib\win32-x86-64
Trying C:\Users\58181.INFOTECH\Downloads\Tess4J-1.3-src\Tess4J\lib\win32-x86-64\libtesseract302.dll
Found library 'libtesseract302' at C:\Users\58181.INFOTECH\Downloads\Tess4J-1.3-src\Tess4J\lib\win32-x86-64\libtesseract302.dll
9226 [http-nio-8080-exec-2] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.Error: Invalid memory access] with root cause
java.lang.Error: Invalid memory access
    at net.sourceforge.tess4j.TessAPI1.TessBaseAPIInit2(Native Method)
    at net.sourceforge.tess4j.Tesseract1.init(Tesseract1.java:274)
    at net.sourceforge.tess4j.Tesseract1.doOCR(Tesseract1.java:209)
    at net.sourceforge.tess4j.Tesseract1.doOCR(Tesseract1.java:158)
    at net.sourceforge.tess4j.Tesseract1.doOCR(Tesseract1.java:142)
    at com.tess4j.rest.OcrRestController.doOcrFile(OcrRestController.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)


来源: stackexchange

问:
Get excel cell address in Python 2 using openpyxl
I have the following scenario:

Read the excel file of column A for all active rows

Run if else statement: if column A == 'registered', do nothing and just read the next row. Else, get cell address (not value) and do some actions

For example, here is my "sample.xlsx":

[row 1] A1=registered B1=user1

[row 2] A2=registered B2=user2

[row 3] A3=null B3=user3

my code should ignore row1 and row2 and proceed with row 3. In row 3, I should get "A3" and do some actions.

```<code>from openpyxl import load_workbook
book = load_workbook(filename='sample.xlsx')
sheet = book.active
first_column = sheet['A']

for x in xrange(len(first_column)):
    status = first_column[x].value

    if status == 'registered':
      #enter code to just proceed with the next row

    else:
      #enter code to get the column cell range and do some actions

book.save('sample.xlsx')
</code>```

I got stucked with the scenario 2, I am a newbie in python, I have a code in java using FileScanner but I need it in Python 2. Appreciate your help.

UPDATE:
I already have an answer below but just wondering if there are any other method??

答:
It always helps to read the documentation</p>

```<code>for cell in ws['A']:
    pass
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following scenario:

Read the excel file of column A for all active rows

Run if else statement: if column A == 'registered', do nothing and just read the next row. Else, get cell address (not value) and do some actions

For example, here is my "sample.xlsx":

[row 1] A1=registered B1=user1

[row 2] A2=registered B2=user2

[row 3] A3=null B3=user3

my code should ignore row1 and row2 and proceed with row 3. In row 3, I should get "A3" and do some actions.

from openpyxl import load_workbook
book = load_workbook(filename='sample.xlsx')
sheet = book.active
first_column = sheet['A']

for x in xrange(len(first_column)):
    status = first_column[x].value

    if status == 'registered':
      #enter code to just proceed with the next row

    else:
      #enter code to get the column cell range and do some actions

book.save('sample.xlsx')

I got stucked with the scenario 2, I am a newbie in python, I have a code in java using FileScanner but I need it in Python 2. Appreciate your help.

UPDATE:
I already have an answer below but just wondering if there are any other method??

Body:
It always helps to read the documentation

for cell in ws['A']:
    pass


问:
What are these pipe characters?
I know in java | means inclusive or, which I never really used but now I saw it in this piece of code that I used in my application. Why is it used this way and what does it do ?</p>

```<code>mDecorView.setSystemUiVisibility(
        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
        | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
        | View.SYSTEM_UI_FLAG_IMMERSIVE);
</code>```

答:
In android API View.setSystemUiVisibility() is used to modify visibility of various view decorations.

You can select various features using flags.

Different flags have different meaning and they are documented in detail in the official docs: setSystemUiVisibility.

If you are not familiar with bitwise operations you should skim through this first.

This notation is a very common technique which is used to encode "sets" in a single machine word:

```<code>View.SYSTEM_UI_FLAG_LAYOUT_STABLE
    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
    | View.SYSTEM_UI_FLAG_IMMERSIVE
</code>```

Mathematically OR-ing machine words which have only one bit set would produce a unique value for every two unique operands. Therefore, if you have a composite value you always can decompose it back to the original values which were used to produce it. The bits must be offset, otherwise there's no way to extract the original values.

If you have two binary values with only one bit set 0001 and 0010 then OR-ing them would produce binary value 0011. Now you can pass that machine word around and then when necessary decompose it back to two original values.

After reading that wikipedia article you should be able to understand how the following works:

```<code>int FLAG1 = 0x1; //0001
int FLAG2 = 0x2; //0010
int FLAG3 = 0x4; //0100
// combine using OR
int flags = FLAG1 | FLAG3; //==0101 (5)
// using + is possible as well but can lead to errors:
// flags += FLAG1
// flags now is 0110 but you didn't mean to enable FLAG2
...
// remove a flag
flags &= ~FLAG1;
// toggle a flag
flags ^= FLAG3
// decompose
if(flags & FLAG1)
{
    //we know flag1 was set.
}
</code>```

If you open android docs again you will see that it mentions a constant value in hexadecimal for every flag:

SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION

...

Constant Value: 512 (0x00000200)

```<code>SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100 (256)
SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200 (512)
</code>```

these are used as I described above: value | FLAG requests some feature, value & ~FLAG turns it off, value ^ FLAG toggles it.

Deep inside of android code combined value will be decomposed and various features enabled and disabled based on the flags which you set.

Title: What are these pipe characters?

Body:
I know in java | means inclusive or, which I never really used but now I saw it in this piece of code that I used in my application. Why is it used this way and what does it do ?

mDecorView.setSystemUiVisibility(
        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
        | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
        | View.SYSTEM_UI_FLAG_IMMERSIVE);

Body:
In android API View.setSystemUiVisibility() is used to modify visibility of various view decorations.

You can select various features using flags.

Different flags have different meaning and they are documented in detail in the official docs: setSystemUiVisibility.

If you are not familiar with bitwise operations you should skim through this first.

This notation is a very common technique which is used to encode "sets" in a single machine word:

View.SYSTEM_UI_FLAG_LAYOUT_STABLE
    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
    | View.SYSTEM_UI_FLAG_IMMERSIVE

Mathematically OR-ing machine words which have only one bit set would produce a unique value for every two unique operands. Therefore, if you have a composite value you always can decompose it back to the original values which were used to produce it. The bits must be offset, otherwise there's no way to extract the original values.

If you have two binary values with only one bit set 0001 and 0010 then OR-ing them would produce binary value 0011. Now you can pass that machine word around and then when necessary decompose it back to two original values.

After reading that wikipedia article you should be able to understand how the following works:

int FLAG1 = 0x1; //0001
int FLAG2 = 0x2; //0010
int FLAG3 = 0x4; //0100
// combine using OR
int flags = FLAG1 | FLAG3; //==0101 (5)
// using + is possible as well but can lead to errors:
// flags += FLAG1
// flags now is 0110 but you didn't mean to enable FLAG2
...
// remove a flag
flags &= ~FLAG1;
// toggle a flag
flags ^= FLAG3
// decompose
if(flags & FLAG1)
{
    //we know flag1 was set.
}

If you open android docs again you will see that it mentions a constant value in hexadecimal for every flag:

SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION

...

Constant Value: 512 (0x00000200)

SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100 (256)
SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200 (512)

these are used as I described above: value | FLAG requests some feature, value & ~FLAG turns it off, value ^ FLAG toggles it.

Deep inside of android code combined value will be decomposed and various features enabled and disabled based on the flags which you set.


问:
plotting users and their visits by date
I have a data set with nearly 1Mn records of Users and their visit on an App by date. There are two columns, one with user Id's and the other having the date on which the user has visited on the app. Each row is a unique combination of User and Date. Now I want to know for all the users who came on the App on day1, how have they been visiting the App in a month and similarly for all the users who came on 2,3,4 and so on.

Is it possible to draw a graph to show how these users have visited on the platform starting from Day1.

Data looks like this.

```<code>x=sprintf("M_%03d", 1:25)
y=seq(as.Date('2011-01-01'),as.Date('2011-01-31'),by = 1)
dat = expand.grid(x = x, y = y)
dat2 = data.frame( ID = sample( dat$x , nrow( dat ) ) , Score = sample(
dat$y , nrow( dat ) ) )
</code>```

Any help would be greatly appreciated.

答:
I'd consider approaching this by constructing a factor tag indicating which week (or day) a particular user started using the service.

First, tag each User ID with the date they joined:

```<code>require(dplyr)

dat3 <- dat2 %>% group_by(ID) %>% mutate(JoinDate = min(Score))
</code>```

Calculate the earliest date:

```<code>start_Date <- min(dat3$Score))
</code>```

Tag each row with the day the user first visited:

```<code>dat3 <- dat3 %>% ungroup() %>% mutate(DaysSince = difftime(JoinDate, start_Date, units="days"))
</code>```

Convert to factor for plotting so we can use it as a categorical tag.

```<code>dat3$DaysSince <- as.factor(dat3$DaysSince)
</code>```

Graph using ggplot. Using geom_jitter() to avoid overlapping points where users visited multiple times per day.

There are a lot of ways you might visualize something like this, but here's one approach. You might also try a heat map.

```<code>require(ggplot2)

ggplot(dat3, aes(DaysSince,Score, color=DaysSince)) +geom_point()+geom_jitter()+coord_flip()
</code>```

Title: plotting users and their visits by date

Body:
I have a data set with nearly 1Mn records of Users and their visit on an App by date. There are two columns, one with user Id's and the other having the date on which the user has visited on the app. Each row is a unique combination of User and Date. Now I want to know for all the users who came on the App on day1, how have they been visiting the App in a month and similarly for all the users who came on 2,3,4 and so on.

Is it possible to draw a graph to show how these users have visited on the platform starting from Day1.

Data looks like this.

x=sprintf("M_%03d", 1:25)
y=seq(as.Date('2011-01-01'),as.Date('2011-01-31'),by = 1)
dat = expand.grid(x = x, y = y)
dat2 = data.frame( ID = sample( dat$x , nrow( dat ) ) , Score = sample(
dat$y , nrow( dat ) ) )

Any help would be greatly appreciated.

Body:
I'd consider approaching this by constructing a factor tag indicating which week (or day) a particular user started using the service.

First, tag each User ID with the date they joined:

require(dplyr)

dat3 <- dat2 %>% group_by(ID) %>% mutate(JoinDate = min(Score))

Calculate the earliest date:

start_Date <- min(dat3$Score))

Tag each row with the day the user first visited:

dat3 <- dat3 %>% ungroup() %>% mutate(DaysSince = difftime(JoinDate, start_Date, units="days"))

Convert to factor for plotting so we can use it as a categorical tag.

dat3$DaysSince <- as.factor(dat3$DaysSince)

Graph using ggplot. Using geom_jitter() to avoid overlapping points where users visited multiple times per day.

There are a lot of ways you might visualize something like this, but here's one approach. You might also try a heat map.

require(ggplot2)

ggplot(dat3, aes(DaysSince,Score, color=DaysSince)) +geom_point()+geom_jitter()+coord_flip()


问:
AngularJS pre-fill input fields based on data from controller
I'm trying to pre-fill a form with a data from a controller.

Simple code looks like

```<code><div ng-app="app" ng-controller="MainCtrl">
    <input name="widget.title" ng-model="widget.title">
    <input name="widget.content" ng-model="widget.content">
    <button ng-click="set('foo')">set to foo</button>
</div>
</code>```

and

```<code>angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.widget = {title: 'abc'};
        $scope.widget = {content: 'test'};
        $scope.set = function(new_title) {
            this.widget.title = new_title;
        }
    });
</code>```

but it always pre-fill only last input field

JSFiddle: http://jsfiddle.net/b40nLuf2/

答:
you can try this code snippets

```<code>angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.widget = {title: 'abc',content: 'test'};
        $scope.set = function(new_title) {
            this.widget.title = new_title;
        }
    });
</code>```

JSFIDDLE : click here to see

Body:
I'm trying to pre-fill a form with a data from a controller.

Simple code looks like

    <input name="widget.title" ng-model="widget.title">
    <input name="widget.content" ng-model="widget.content">
    <button ng-click="set('foo')">set to foo</button>

and

angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.widget = {title: 'abc'};
        $scope.widget = {content: 'test'};
        $scope.set = function(new_title) {
            this.widget.title = new_title;
        }
    });

but it always pre-fill only last input field

JSFiddle: http://jsfiddle.net/b40nLuf2/

Body:
you can try this code snippets

angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.widget = {title: 'abc',content: 'test'};
        $scope.set = function(new_title) {
            this.widget.title = new_title;
        }
    });

JSFIDDLE : click here to see


问:
How to update metadata about Trade Representative Contact Information using Fastlane/Deliver?
I uploaded all the metadata to appstore including Screenshots, App review information , Rating and  all other things but unable to get any command to pass the Trade Representative Contact Information using Fastlane/Deliver. </p>

答:
you should add in your Deliverfile something like this</p>

```<code>trade_representative_contact_information(
  first_name: "Alex",
  last_name: "Kosyakov",
  address_line1: "Nevsky pr., 1",
  address_line2: "",
  address_line3: "",
  city_name: "Saint-Petersburg",
  state: "",
  country: "Russia",
  postal_code: "190000",
  phone_number: "+7921XXXXXXX",
  email_address: "blabal@gmail."
)
</code>```

Body:
you should add in your Deliverfile something like this

trade_representative_contact_information(
  first_name: "Alex",
  last_name: "Kosyakov",
  address_line1: "Nevsky pr., 1",
  address_line2: "",
  address_line3: "",
  city_name: "Saint-Petersburg",
  state: "",
  country: "Russia",
  postal_code: "190000",
  phone_number: "+7921XXXXXXX",
  email_address: "blabal@gmail."
)


问:
tf.Variable and tf.constant
I was reading the CNN model for text classification, code link, and I was wondering, in line 70, the code:

```<code>b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b")
</code>```

Why it can be defined as Variable and constant at same time? is this equal to:

```<code>b = tf.Variable(0.1, shape=[num_classes], name="b")
</code>```

答:
Yes, both are same. Tensorflow implicitly copies tf.constant value into tf.Variable value. Operations a.op,b.op and c.op explain everything

```<code>  import tensorflow as tf

    with tf.Session() as sess:
        a=tf.constant(0.1);
        b = tf.Variable(tf.constant(0.1), name="b");
        c = tf.Variable(0.1, name="b");
        sess.run(tf.global_variables_initializer());
        print(a.dtype);
        print(b.dtype);
        print(c.dtype);
        print("**********************")
        print(a.op);
        print(b.op);
        print(c.op);
</code>```

Output:

```<code><dtype: 'float32'>
<dtype: 'float32_ref'>
<dtype: 'float32_ref'>
**********************

name: "Const_40"
op: "Const"
attr {
  key: "dtype"
  value {
    type: DT_FLOAT
  }
}
attr {
  key: "value"
  value {
    tensor {
      dtype: DT_FLOAT
      tensor_shape {
      }
      float_val: 0.10000000149
    }
  }
}

name: "b_38"
op: "VariableV2"
attr {
  key: "container"
  value {
    s: ""
  }
}
attr {
  key: "dtype"
  value {
    type: DT_FLOAT
  }
}
attr {
  key: "shape"
  value {
    shape {
    }
  }
}
attr {
  key: "shared_name"
  value {
    s: ""
  }
}

name: "b_39"
op: "VariableV2"
attr {
  key: "container"
  value {
    s: ""
  }
}
attr {
  key: "dtype"
  value {
    type: DT_FLOAT
  }
}
attr {
  key: "shape"
  value {
    shape {
    }
  }
}
attr {
  key: "shared_name"
  value {
    s: ""
  }
}
</code>```

Title: tf.Variable and tf.constant

Body:
I was reading the CNN model for text classification, code link, and I was wondering, in line 70, the code:

b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b")

Why it can be defined as Variable and constant at same time? is this equal to:

b = tf.Variable(0.1, shape=[num_classes], name="b")

Body:
Yes, both are same. Tensorflow implicitly copies tf.constant value into tf.Variable value. Operations a.op,b.op and c.op explain everything

  import tensorflow as tf

    with tf.Session() as sess:
        a=tf.constant(0.1);
        b = tf.Variable(tf.constant(0.1), name="b");
        c = tf.Variable(0.1, name="b");
        sess.run(tf.global_variables_initializer());
        print(a.dtype);
        print(b.dtype);
        print(c.dtype);
        print("**********************")
        print(a.op);
        print(b.op);
        print(c.op);

Output:

<dtype: 'float32'>
<dtype: 'float32_ref'>
<dtype: 'float32_ref'>
**********************

name: "Const_40"
op: "Const"
attr {
  key: "dtype"
  value {
    type: DT_FLOAT
  }
}
attr {
  key: "value"
  value {
    tensor {
      dtype: DT_FLOAT
      tensor_shape {
      }
      float_val: 0.10000000149
    }
  }
}

name: "b_38"
op: "VariableV2"
attr {
  key: "container"
  value {
    s: ""
  }
}
attr {
  key: "dtype"
  value {
    type: DT_FLOAT
  }
}
attr {
  key: "shape"
  value {
    shape {
    }
  }
}
attr {
  key: "shared_name"
  value {
    s: ""
  }
}

name: "b_39"
op: "VariableV2"
attr {
  key: "container"
  value {
    s: ""
  }
}
attr {
  key: "dtype"
  value {
    type: DT_FLOAT
  }
}
attr {
  key: "shape"
  value {
    shape {
    }
  }
}
attr {
  key: "shared_name"
  value {
    s: ""
  }
}


问:
How to create n degree Identity Matrix with mathematica?
How to make n degree Identity Matrix with mathematica....

Set id[n] :=????? -> Perform the id[2] (Shift+enter)-> Get {1,0},{0,1}(2X2 Identity Matrix)

not using command( IdentityMatrix, DiagonalMatrix, Inverse, SparseArray).

答:
```<code>degree = 4;

id = Reverse@Sort@Select[Tuples[{0, 1}, degree], Total[#] == 1 &];

id == IdentityMatrix[degree]
</code>```

True

Body:
degree = 4;

id = Reverse@Sort@Select[Tuples[{0, 1}, degree], Total[#] == 1 &];

id == IdentityMatrix[degree]

True


问:
Retain focus on previous fragment's view
Suppose I have 5 views (1,2,3,4,5) in a fragment A and each view is focusable.
Then, if the current focus in fragment A is at view 3 and clicking that view loads a new fragment, let's say fragment B.

Now, is there any way that when I press back button, the focus is retained on view 3 of fragment A automatically?

Note: I have added those fragments in the backstack. But my fragment contains recycler views. Clicking on an item of recycler view will load another fragment and on back press the Main Activity gets the default focus.
I can implement focusing on recycler view's first item by implementing fragment's onBackPressListener() method. But I have no idea on how to retain focus on a fragment as it was before.

答: If you are adding fragment on top of fragment A with add to backstack, it will resume in last focused item when you press back button </p>

ContentLicense: CC BY-SA 4.0


问:
Is there a way to detect the exception in dispose?
I have the following scenario:

```<code>class Program
{
    static void Main(string[] args)
    {
        try
        {
            using (new Foo())
            {
                throw new Exception("Inside using block");
            }
        }
        catch (Exception e)
        {

        }
    }
}

public class Foo : IDisposable
{
    public void Dispose()
    {
        throw new Exception("Inside dispose");
    }
}
</code>```

Is it somehow possible, to get the thrown exception - "Inside using block" - in the Dispose method of Foo and make it an InnerException of the Exception Inside dispose?

Edit:

For example:

```<code>class Program
{
    static void Main(string[] args)
    {
        try
        {
            using (var fi = new FileHandler())
            {
                //open the file
                fi.Open();

                //write to the file
                fi.Write();

                //excption occurs
                throw new Exception("Inside using block");

                fi.Close();
            }
        }
        catch (Exception e)
        {
            //now I only have the exception from the dispose but not the exception that occured in the using block itself
            //I know I could wrap the code inside the using in a try/catch itself, just asking if it is possible without 2 try/catches
        }
    }
}

public class FileHandler : IDisposable
{
    public void Dispose()
    {
        //Close the file
        //for some reason it fails with an exception
        throw new Exception("Inside dispose");
    }
}
</code>```

答:
Per the Framework Design Guidelines (Cwalina, Abrams), section 9.3:

AVOID throwing an exception from within Dispose(bool) except under critical situations where the containing process has been corrupted.

If Dispose could raise an exception, further finally block cleanup logic will not execute. To work around this, the user would need to wrap every call to Dispose (within their finally block!) in a try block, which leads to very complex cleanup handlers. If executing a Dispose(bool) method, never throw an exception if disposing is false.

Also from section 9.3:

AVOID making types finalizable. Carefully consider any case in which you think a finalizer is needed. There is a real cost associated with instances with finalizers, from both a performance and code complexity standpoint."

Body:
I have the following scenario:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            using (new Foo())
            {
                throw new Exception("Inside using block");
            }
        }
        catch (Exception e)
        {

        }
    }
}

public class Foo : IDisposable
{
    public void Dispose()
    {
        throw new Exception("Inside dispose");
    }
}

Is it somehow possible, to get the thrown exception - "Inside using block" - in the Dispose method of Foo and make it an InnerException of the Exception Inside dispose?

Edit:

For example:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            using (var fi = new FileHandler())
            {
                //open the file
                fi.Open();

                //write to the file
                fi.Write();

                //excption occurs
                throw new Exception("Inside using block");

                fi.Close();
            }
        }
        catch (Exception e)
        {
            //now I only have the exception from the dispose but not the exception that occured in the using block itself
            //I know I could wrap the code inside the using in a try/catch itself, just asking if it is possible without 2 try/catches
        }
    }
}

public class FileHandler : IDisposable
{
    public void Dispose()
    {
        //Close the file
        //for some reason it fails with an exception
        throw new Exception("Inside dispose");
    }
}


问:
SequelizeInstance object not rendering in Express Handlebars view (NodeJS, Express)
Using NodeJS, Express and Sequilize,

I am rendering in my view [object SequelizeInstance:Todo] as oppose to actual data instance value when called with res.render(), however is when called by .send (see commented line below) the data instance value is sent to the view.

```<code>exports.test_todo_view = function(req, res) {
return Todo
    .findAll({
        //attributes: ['id'] //select fields
        })
    //.then((todos) => res.status(200).send(todos))
    .then((todos) => res.render('test/test_view', {layout: 'ca_layout.handlebars', test_data: todos}))
.catch((error) => res.status(400).send(error));
}
</code>```

Output is[object SequelizeInstance:Todo] for each entry in database.

Can anyone advise? It works ie i can see the data - [{"id":1,"title":"fasdfsd","createdAt":"2017-11-15",...] when i use the .send(todos) as shown.

I am using the below to call the view.

```<code>app.get('/test/view', authCarePlan.test_todo_view);
</code>```

My .handlebars file  looks like this

```<code><div>test_data:{{test_data}}</div>
</code>```

where i want the query output to come through as test_data

答:
The following config was required in the .handlebars view

```<code>{{#test_data}}
{{title}}
{{/test_data}}
</code>```

Where test_data is the name of the variable placeholder and title is name of a field within it.

Body:
Using NodeJS, Express and Sequilize,

I am rendering in my view [object SequelizeInstance:Todo] as oppose to actual data instance value when called with res.render(), however is when called by .send (see commented line below) the data instance value is sent to the view.

exports.test_todo_view = function(req, res) {
return Todo
    .findAll({
        //attributes: ['id'] //select fields
        })
    //.then((todos) => res.status(200).send(todos))
    .then((todos) => res.render('test/test_view', {layout: 'ca_layout.handlebars', test_data: todos}))
.catch((error) => res.status(400).send(error));
}

Output is[object SequelizeInstance:Todo] for each entry in database.

Can anyone advise? It works ie i can see the data - [{"id":1,"title":"fasdfsd","createdAt":"2017-11-15",...] when i use the .send(todos) as shown.

I am using the below to call the view.

app.get('/test/view', authCarePlan.test_todo_view);

My .handlebars file  looks like this

test_data:{{test_data}}

where i want the query output to come through as test_data

Body:
The following config was required in the .handlebars view

{{#test_data}}
{{title}}
{{/test_data}}

Where test_data is the name of the variable placeholder and title is name of a field within it.


问:
How can I bind two IO () monads without executing them?
In the below code, I am using >> to concatenate IO actions together. But AFAIU, m1>>m2 gets de-sugared to m1>>=(\_.m2) and thus it is executing the first IO action right when it is binding. I want all printing to happen in the main, i.e. print statements should not get interleaved with the input statements ("Enter Code"). Since do doesn't allow me to return any other monad than IO like [IO ()]. How can I have the desired printing effect?

```<code>f :: [Int] -> IO ()
f inventory = do
        putStrLn "Enter Code\n"
        x <- getLine
        let idx = nameToIndex x
        putStrLn "Quantity\n"
        y <- getLine
        putStrLn "More?\n"
        c <- getChar
        let q = (read y :: Int)
        let curM = if inventory !! idx >= q then (putStrLn "sdaf\n") else (putStrLn "Overflow!\n")
        if c == 'Y' then curM>>(f (update inventory idx)) else curM

main = f [1, 2]
</code>```

答:
I'm not 100% sure I understand the problem, but I think it goes like this: you'd like to do some interactions with the user, storing up information about the interaction, then display all the information at once at the end of the entire interaction.

Here's a very simplified version of your code, that skips all the business logic and just keeps asking the user if they want to continue.

```<code>prompt = do
    putStrLn "Continue?"
    s <- getLine
    case s of
        "y" -> putStrLn "Okay, let's continue." >> prompt
        _ -> return ()

main = prompt
</code>```

I think the effect you're asking for is to delay the display of "Okay, let's continue." until the user has stopped hitting "y". That's no problem. There's lots of ways you can do this. The most flexible is to have prompt return the action it wants to be executed after it completes:

```<code>prompt = do
    putStrLn "Continue?"
    s <- getLine
    case s of
        "y" -> do
            act <- prompt
            return (putStrLn "Okay, let's continue." >> act)
        _ -> return (return ())

main = do
    act <- prompt
    act
</code>```

(There are combinators that can make this code more compact, as well.) But I don't like this design; it makes it difficult to introspect on the result of prompt. A more specialized but also more maintainable approach is to return some data describing the interaction, which the caller can then turn into an IO action summarizing things. In this case, a list of strings seems like a suitable description.

```<code>prompt = do
    putStrLn "Continue?"
    s <- getLine
    case s of
        "y" -> do
            results <- prompt
            return ("Okay, let's continue." : results)
        _ -> return []

main = do
    results <- prompt
    mapM_ putStrLn results
</code>```

Hopefully this explanation is clear enough that you can combine this idea with your more complicated business logic.

Body:
In the below code, I am using >> to concatenate IO actions together. But AFAIU, m1>>m2 gets de-sugared to m1>>=(\_.m2) and thus it is executing the first IO action right when it is binding. I want all printing to happen in the main, i.e. print statements should not get interleaved with the input statements ("Enter Code"). Since do doesn't allow me to return any other monad than IO like [IO ()]. How can I have the desired printing effect?

f :: [Int] -> IO ()
f inventory = do
        putStrLn "Enter Code\n"
        x <- getLine
        let idx = nameToIndex x
        putStrLn "Quantity\n"
        y <- getLine
        putStrLn "More?\n"
        c <- getChar
        let q = (read y :: Int)
        let curM = if inventory !! idx >= q then (putStrLn "sdaf\n") else (putStrLn "Overflow!\n")
        if c == 'Y' then curM>>(f (update inventory idx)) else curM

main = f [1, 2]

Body:
I'm not 100% sure I understand the problem, but I think it goes like this: you'd like to do some interactions with the user, storing up information about the interaction, then display all the information at once at the end of the entire interaction.

Here's a very simplified version of your code, that skips all the business logic and just keeps asking the user if they want to continue.

prompt = do
    putStrLn "Continue?"
    s <- getLine
    case s of
        "y" -> putStrLn "Okay, let's continue." >> prompt
        _ -> return ()

main = prompt

I think the effect you're asking for is to delay the display of "Okay, let's continue." until the user has stopped hitting "y". That's no problem. There's lots of ways you can do this. The most flexible is to have prompt return the action it wants to be executed after it completes:

prompt = do
    putStrLn "Continue?"
    s <- getLine
    case s of
        "y" -> do
            act <- prompt
            return (putStrLn "Okay, let's continue." >> act)
        _ -> return (return ())

main = do
    act <- prompt
    act

(There are combinators that can make this code more compact, as well.) But I don't like this design; it makes it difficult to introspect on the result of prompt. A more specialized but also more maintainable approach is to return some data describing the interaction, which the caller can then turn into an IO action summarizing things. In this case, a list of strings seems like a suitable description.

prompt = do
    putStrLn "Continue?"
    s <- getLine
    case s of
        "y" -> do
            results <- prompt
            return ("Okay, let's continue." : results)
        _ -> return []

main = do
    results <- prompt
    mapM_ putStrLn results

Hopefully this explanation is clear enough that you can combine this idea with your more complicated business logic.


问:
Jasper Report JasperReportsPdfView SpringBoot Subreport error
Report structure:

```<code>main report - myreport.jrxml
sub report  - myreport_detail.jrxml
</code>```

Running my main report with sub report works fine in Jasper Report Studio. In my Spring Boot environment I use JasperReportsPdfView.

However running myreport.jrxml here I get:

```<code>Caused by: net.sf.jasperreports.engine.JRException: Resource not found at: jasper/repo/myreport_detail.jasper.
at net.sf.jasperreports.repo.RepositoryUtil.getResourceFromLocation(RepositoryUtil.java:153)
at net.sf.jasperreports.repo.RepositoryUtil.getReport(RepositoryUtil.java:112)
at net.sf.jasperreports.engine.fill.JRFillSubreport.loadReport(JRFillSubreport.java:411)
at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluateReport(JRFillSubreport.java:378)
at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluateSubreport(JRFillSubreport.java:440)
at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluate(JRFillSubreport.java:354)
at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:383)
at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:506)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnBand(JRVerticalFiller.java:2412)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:761)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:240)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:99)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:607)
at net.sf.jasperreports.engine.fill.BaseReportFiller.fill(BaseReportFiller.java:387)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:109)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:456)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:863)
at org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsView.doFillReport(AbstractJasperReportsView.java:702)
at org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsView.fillReport(AbstractJasperReportsView.java:669)
at org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsView.renderMergedOutputModel(AbstractJasperReportsView.java:566)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1271)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
... 97 common frames omitted
</code>```

Note: running one single report without sub report works fine

Endpoint:

```<code>    @RequestMapping(value = "/api", params = {"dir", "name"})
public ModelAndView report(
    HttpServletRequest request,
    @RequestParam(value = "dir") String dir,
    @RequestParam(value = "name") String name) throws Exception {

    JasperReportsPdfView view = new JasperReportsPdfView();
    view.setJdbcDataSource(dataSource);
    view.setUrl("classpath:jasper/" + dir + "/" + name + ".jrxml");
    view.setApplicationContext(context);
    view.setHeaders(getProperties(name, false));
    return new ModelAndView(view, getParameters(request));
}
</code>```

Java code crash RepositoryUtil:

```<code>    public <K extends Resource> K getResourceFromLocation(String location, Class<K> resourceType) throws JRException
{
    K resource = null;
    List<RepositoryService> services = getServices();
    if (services != null)
    {
        for (RepositoryService service : services)
        {
            resource = service.getResource(location, resourceType);
            if (resource != null)
            {
                break;
            }
        }
    }
    if (resource == null)
    {
        throw
        new JRException(
            EXCEPTION_MESSAGE_KEY_RESOURCET_NOT_FOUND,
            new Object[]{location});    //FIXMEREPO decide whether to return null or throw exception; check everywhere
    }
    return resource;
}
</code>```

Error line:

```<code>    resource = service.getResource(location, resourceType);
</code>```

Variable:

```<code>  location -> jasper/repo/myreport_detail.jasper
  resourceType -> class net.sf.jasperreports.repo.ReportResource
</code>```

Exception line thrown because resource = null:

```<code>    public static final String EXCEPTION_MESSAGE_KEY_RESOURCET_NOT_FOUND = "repo.resource.not.found";
</code>```

Anyone?

答: Supplied the .jasper files and then it worked. Running one report only without sub report I did not need to supply them though:-) Thought they where generated on the fly in the Spring Boot environment.</p>

Body:
Report structure:

main report - myreport.jrxml
sub report  - myreport_detail.jrxml

Running my main report with sub report works fine in Jasper Report Studio. In my Spring Boot environment I use JasperReportsPdfView.

However running myreport.jrxml here I get:

Caused by: net.sf.jasperreports.engine.JRException: Resource not found at: jasper/repo/myreport_detail.jasper.
at net.sf.jasperreports.repo.RepositoryUtil.getResourceFromLocation(RepositoryUtil.java:153)
at net.sf.jasperreports.repo.RepositoryUtil.getReport(RepositoryUtil.java:112)
at net.sf.jasperreports.engine.fill.JRFillSubreport.loadReport(JRFillSubreport.java:411)
at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluateReport(JRFillSubreport.java:378)
at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluateSubreport(JRFillSubreport.java:440)
at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluate(JRFillSubreport.java:354)
at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:383)
at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:506)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnBand(JRVerticalFiller.java:2412)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:761)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:240)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:99)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:607)
at net.sf.jasperreports.engine.fill.BaseReportFiller.fill(BaseReportFiller.java:387)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:109)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:456)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:863)
at org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsView.doFillReport(AbstractJasperReportsView.java:702)
at org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsView.fillReport(AbstractJasperReportsView.java:669)
at org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsView.renderMergedOutputModel(AbstractJasperReportsView.java:566)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1271)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
... 97 common frames omitted

Note: running one single report without sub report works fine

Endpoint:

    @RequestMapping(value = "/api", params = {"dir", "name"})
public ModelAndView report(
    HttpServletRequest request,
    @RequestParam(value = "dir") String dir,
    @RequestParam(value = "name") String name) throws Exception {

    JasperReportsPdfView view = new JasperReportsPdfView();
    view.setJdbcDataSource(dataSource);
    view.setUrl("classpath:jasper/" + dir + "/" + name + ".jrxml");
    view.setApplicationContext(context);
    view.setHeaders(getProperties(name, false));
    return new ModelAndView(view, getParameters(request));
}

Java code crash RepositoryUtil:

    public <K extends Resource> K getResourceFromLocation(String location, Class<K> resourceType) throws JRException
{
    K resource = null;
    List<RepositoryService> services = getServices();
    if (services != null)
    {
        for (RepositoryService service : services)
        {
            resource = service.getResource(location, resourceType);
            if (resource != null)
            {
                break;
            }
        }
    }
    if (resource == null)
    {
        throw
        new JRException(
            EXCEPTION_MESSAGE_KEY_RESOURCET_NOT_FOUND,
            new Object[]{location});    //FIXMEREPO decide whether to return null or throw exception; check everywhere
    }
    return resource;
}

Error line:

    resource = service.getResource(location, resourceType);

Variable:

  location -> jasper/repo/myreport_detail.jasper
  resourceType -> class net.sf.jasperreports.repo.ReportResource

Exception line thrown because resource = null:

    public static final String EXCEPTION_MESSAGE_KEY_RESOURCET_NOT_FOUND = "repo.resource.not.found";

Anyone?