text:
Q: Javascript Building a Nested Object (tree) from an very weird array Debugging I could really use some help Debugging a problem. Im trying to build a nested object (tree) from a very unusual array im getting from a backend (dont have access to the BE so i have to work with what i got). I've gotten 95 percent of it done but im running into a bug
I know there are many of these flat arrays to nested objects in StackOverFlow, but this array i'm given to work with is way different. It does not have ids or typical properties of a flatten array. The good thing is that I have most of it done.
Here is a basic example of The problem I'm having:
Data:

    let stackTest = {
        predicates: [
            {
                primaryTerm: "test1",
                level: 1,
                condition: 0,
            },
            {
                primaryTerm: "and",
                level: 1,
                condition: 2,
            },
            {
                primaryTerm: "test2",
                level: 1,
                condition: 0,
            },
            {
                primaryTerm: "and",
                level: 1,
                condition: 2,
            },
            {
                primaryTerm: "test3",
                level: 2,
                condition: 0,
            },
            {
                primaryTerm: "or",
                level: 2,
                condition: 1,
            },
            {
                primaryTerm: "test4",
                level: 2,
                condition: 0,
            },
            {
                primaryTerm: "or",
                level: 2,
                condition: 1,
            },
            {
                primaryTerm: "test5",
                level: 3,
                condition: 0,
            },
            {
                primaryTerm: "and",
                level: 3,
                condition: 2,
            },
            {
                primaryTerm: "test5",
                level: 3,
                condition: 0,
            },

        ]

Desired Function output:

    [
        {
            id: 1,
            children: [
                {
                    id: 2,
                    children: [],
                    parentId: 1,
                    level: 1,
                    primaryTerm: 'test1',
                    condition: 0
                },
                {
                    id: 3,
                    children: [],
                    parentId: 1,
                    primaryTerm: 'test2',
                    level: 1,
                    condition: 0
                },
                {
                    id: 4,
                    children: [
                        {
                            primaryTerm: 'test3',
                            level: 2,
                            condition: 0,
                            id: 5,
                            children: [],
                            parentId: 4
                        },
                        {
                            id: 6,
                            children: [],
                            parentId: 4,
                            primaryTerm: 'test4',
                            level: 2,
                            condition: 0
                        },

                        {
                            id: 8,
                            children: [
                                {
                                    primaryTerm: 'test5',
                                    level: 3,
                                    condition: 0,
                                    id: 9,
                                    children: [],
                                    parentId: 8
                                },
                                {
                                    id: 10,
                                    children: [],
                                    parentId: 8,
                                    primaryTerm: 'test5',
                                    level: 3,
                                    condition: 0
                                }
                            ],
                            parentId: 4,
                            level: 2,
                            primaryTerm: 'and',
                            condition: 2
                        }

                    ],
                    parentId: 0,
                    level: 1,
                    primaryTerm: 'or',
                    condition: 1
                }
            ],
            parentId: 0,
            level: 0,
            primaryTerm: 'and',
            condition: 2
        }
    ]

Desired Tree Representation:

                                           AND

                                    /       |       \

                               Test1      Test2        OR

                                                     /    |    \

                                                   Test3  Test4   AND

                                                                   |   \

                                                                  Test5   Test6

Actual Function output:

    [
      {
        id: 1,
        children: [
          {
            id: 2,
            children: [],
            parentId: 1,
            level: 1,
            primaryTerm: 'test1',
            condition: 0
          },
          {
            id: 3,
            children: [],
            parentId: 1,
            primaryTerm: 'test2',
            level: 1,
            condition: 0
          },
          {
            id: 4,
            children: [
              {
                primaryTerm: 'test3',
                level: 2,
                condition: 0,
                id: 5,
                children: [],
                parentId: 4
              },
              {
                id: 6,
                children: [],
                parentId: 4,
                primaryTerm: 'test4',
                level: 2,
                condition: 0
              },
              {
                id: 7,
                children: [
                  {
                    id: 8,
                    children: [
                      {
                        primaryTerm: 'test5',
                        level: 3,
                        condition: 0,
                        id: 9,
                        children: [],
                        parentId: 8
                      },
                      {
                        id: 10,
                        children: [],
                        parentId: 8,
                        primaryTerm: 'test5',
                        level: 3,
                        condition: 0
                      }
                    ],
                    parentId: 7,
                    level: 2,
                    primaryTerm: 'and',
                    condition: 2
                  }
                ],
                parentId: 1,
                level: 1
              }
            ],
            parentId: 0,
            level: 1,
            primaryTerm: 'or',
            condition: 1
          }
        ],
        parentId: 0,
        level: 0,
        primaryTerm: 'and',
        condition: 2
      }
    ]

Actual Tree Representation:

                                           AND

                                  /          |     \

                         Test1          Test2          OR

                                                  /     |    \

                                              Test3   Test4    {}  --here is the issue

                                                                 \

                                                                    AND

                                                                     |     \

                                                                   Test5    Test6

The Problem:
An extra empty object is being created, this object shouldn't be there at all. not sure why this extra node is being created. I suspect it may have to do with the buildEmptyFlatArr, it may not be properly appending the parentId since that too is messed up. This issue only happens when a nested branch is to the right of the Tree, if the nested branch was to the left of the tree it wouldn't happen.
What i have done so far:
rule:
objects that have 'and' / 'or' are considered Logical operators
only logical (AND/OR) objects can have children
steps

*

*1: Initialize the nested obj(tree) to the level of the first
predicate:

The functions buildEmptyFlatArr and listToTree handle this

*

*2: when we get to the (And/OR) object, give the properties of a logical container to the new nodes where the level of that empty node
matches (logicalObject level -1 )

The updatedTreeNode function handles this

*

*3: if the following item in the array has the same level as the last logical object, then append the following object to the logical
operator from step #2. if the levels differ, append an empty node until you reach the level of that currently looped object.

The updatedTreeNode function handles this

The Code:

    let id = 1;
    let lastLogical = {};
    let lastItemAdded = {};
    let initTree;

    const buildEmptyFlatArr = (num, branch = false, branchLastValue) => {
        let initArr = [];

        for (let i = 0; i  {
        let map = {},
            node,
            roots = [],
            i;

        for (i = 0; i  {
        tree.forEach((item, index) => {
            if (logical) {

                if (item.level === target.level - 1
                     ) {
                    let objToMod = item;

                    if (item.condition === undefined) {
                        for (const [key, value] of Object.entries(target)) {
                            if (key === "level") {
                                objToMod["level"] = target.level - 1;
                            } else {
                                objToMod[key] = value;
                            }
                        }
                    }

                    lastLogical = item;
                    lastItemAdded = item;

                } else if (item.children.length > 0 ) {
                    lastLogical = item;
                    updateTreeNode(item.children, target, first, logical);
                }
            } else if (first) {
                if (item.level === target.level) {
                    let objToMod = item;
                    for (const [key, value] of Object.entries(target)) {
                        objToMod[key] = value;
                    }
                    lastItemAdded = item;
                    return;
                } else if (item.children !== null && item.children.length > 0) {
                    updateTreeNode(item.children, target, first, logical);
                }
            } else if (!first && !logical) {
                if (Math.abs(lastLogical.level - target.level) > 1) {
                    let buildArrayLength =  target.level - 1;
                    let arrToAppend = buildEmptyFlatArr(buildArrayLength, true, target);
                    let newBranchToAppend = listToTree(arrToAppend);

                    lastLogical.children = [...lastLogical.children, { ...newBranchToAppend[0] }];
                    lastItemAdded = item;
                    lastLogical = item;

                } else if (item.level === target.level - 1 && lastLogical === item) {
                    let objToMod = item;
                    objToMod.children = [
                        ...objToMod.children,
                        { id: id, children: [], parentId: item.id, ...target },
                    ];
                    id += 1;
                    lastItemAdded = item;
                    lastLogical = item
                } else {
                    updateTreeNode(item.children, target);
                }
            }
        });
    };

    const buildTree = (templateData) => {
        templateData.forEach((item, index) => {
            if (index === 0) {
                let list = buildEmptyFlatArr(item.level);
                initTree = listToTree(list);
                updateTreeNode(initTree, item, true, false);
            } else if (item.condition === 1 || item.condition === 2) {
                updateTreeNode(initTree, item, false, true);
            } else {
                updateTreeNode(initTree, item);
            }
        });
    };

    buildTree(templateObj8.predicates);
        console.dir(initTree, { depth: null });

EDIT: I did not do a good job asking this question (first question i think) additional example of how the tree is suppose to look like. The initial example i've given is a tree weighted to the right. but the tree should be able to handle a more complex tree like this
second set of Data

    let stackTest = {
        predicates: [
            {
                primaryTerm: "test1",
                level: 3,
                condition: 0,
            },
            {
                primaryTerm: "and",
                level: 3,
                condition: 2,
            },
            {
                primaryTerm: "test2",
                level: 3,
                condition: 0,
            },
            {
                primaryTerm: "and",
                level: 1,
                condition: 2,
            },
            {
                primaryTerm: "test3",
                level: 2,
                condition: 0,
            },
            {
                primaryTerm: "or",
                level: 2,
                condition: 1,
            },
            {
                primaryTerm: "test4",
                level: 2,
                condition: 0,
            },
            {
                primaryTerm: "or",
                level: 2,
                condition: 1,
            },
            {
                primaryTerm: "test5",
                level: 3,
                condition: 0,
            },
            {
                primaryTerm: "and",
                level: 3,
                condition: 2,
            },
            {
                primaryTerm: "test5",
                level: 3,
                condition: 0,
            },
            {
                primaryTerm: "and",
                level: 1,
                condition: 2,
            },
            {
                primaryTerm: "test6",
                level: 2,
                condition: 0,
            },
            {
                primaryTerm: "or",
                level: 2,
                condition: 1,
            },
            {
                primaryTerm: "test7",
                level: 2,
                condition: 0,
            },

        ]

current output of my code

    [
      {
        id: 1,
        children: [
          {
            id: 2,
            children: [
              {
                id: 3,
                children: [
                  {
                    id: 4,
                    children: [],
                    parentId: 3,
                    level: 3,
                    primaryTerm: 'test1',
                    condition: 0
                  },
                  {
                    id: 5,
                    children: [],
                    parentId: 3,
                    primaryTerm: 'test2',
                    level: 3,
                    condition: 0
                  }
                ],
                parentId: 2,
                level: 2,
                primaryTerm: 'and',
                condition: 2
              }
            ],
            parentId: 1,
            level: 1,
            primaryTerm: 'or',
            condition: 1
          },
          {
            id: 6,
            children: [
              {
                primaryTerm: 'test3',
                level: 2,
                condition: 0,
                id: 7,
                children: [],
                parentId: 6
              },
              {
                id: 8,
                children: [],
                parentId: 6,
                primaryTerm: 'test4',
                level: 2,
                condition: 0
              },
              {
                id: 9,
                children: [
                  {
                    id: 10,
                    children: [
                      {
                        primaryTerm: 'test5',
                        level: 3,
                        condition: 0,
                        id: 11,
                        children: [],
                        parentId: 10
                      },
                      {
                        id: 12,
                        children: [],
                        parentId: 10,
                        primaryTerm: 'test5',
                        level: 3,
                        condition: 0
                      }
                    ],
                    parentId: 9,
                    level: 2,
                    primaryTerm: 'and',
                    condition: 2
                  }
                ],
                parentId: 1,
                level: 1
              }
            ],
            parentId: 0,
            level: 1,
            primaryTerm: 'or',
            condition: 1
          },
          {
            id: 13,
            children: [
              {
                primaryTerm: 'test6',
                level: 2,
                condition: 0,
                id: 14,
                children: [],
                parentId: 13
              },
              {
                id: 15,
                children: [],
                parentId: 13,
                primaryTerm: 'test7',
                level: 2,
                condition: 0
              }
            ],
            parentId: 0,
            level: 1,
            primaryTerm: 'or',
            condition: 1
          }
        ],
        parentId: 0,
        level: 0,
        primaryTerm: 'and',
        condition: 2
      }
    ]

Here is the current output of my function, test6 and test 7 are properly inserted. where the empty object exists is where the extra node is being inserted. if this extra empty object wasnt there it would be perfect

                                       AND

                                  /     |     \

                             OR         OR          OR

                           /         /  |  \         |  \

                     AND       test3 test4  {}      test6  test7
                   /   \                     |
               test1    test2               and
                                            / \
                                       test5  test5

as you can see object with id: #9 is an extra object that should not be there that is the issue im dealing with. thank you

A: This is an approach with an array for the operator for every level.
The tree contains always sub trees with an operator as root and operands as leaves. Any operand can contains sub trees as well.
If a level is deeper than the level before, it creates a new sub tree with the operand at top and children for the operands.

const
    getTree = predicates => {
        const
            result = [],
            levels = [{ children: result }];

        let id = 1,
            lastLevel = -Infinity;

        predicates.forEach(o => {
            const level = o.level;

            if (level > lastLevel) {
                let l = level - 1;
                while (!levels[l]) l--;
                while (l < level) {
                    // generate new operator
                    // assign children to levels
                    levels[l].children.push(levels[l + 1] = { id, parentId: levels[l]?.id || 0, children: [] });
                    id++;
                    l++;
                }
            }

            if (o.condition) { // update operators
                if (!levels[level].condition) Object.assign(levels[level], o);
            } else { // assign levels
                levels[level].children.push({ id, parentId: levels[level].id, ...o, children: [] });
                id++;
            }

            lastLevel = level;
        });
        return result;
    },
    predicates1 = [{ primaryTerm: "test1", level: 1, condition: 0 }, { primaryTerm: "and", level: 1, condition: 2, }, { primaryTerm: "test2", level: 1, condition: 0 }, { primaryTerm: "and", level: 1, condition: 2 }, { primaryTerm: "test3", level: 2, condition: 0 }, { primaryTerm: "or", level: 2, condition: 1 }, { primaryTerm: "test4", level: 2, condition: 0 }, { primaryTerm: "or", level: 2, condition: 1 }, { primaryTerm: "test5", level: 3, condition: 0 }, { primaryTerm: "and", level: 3, condition: 2 }, { primaryTerm: "test5", level: 3, condition: 0 }],
    predicates2 = [{ primaryTerm: "test1", level: 3, condition: 0 }, { primaryTerm: "and", level: 3, condition: 2 }, { primaryTerm: "test2", level: 3, condition: 0 }, { primaryTerm: "and", level: 1, condition: 2 }, { primaryTerm: "test3", level: 2, condition: 0 }, { primaryTerm: "or", level: 2, condition: 1 }, { primaryTerm: "test4", level: 2,  condition: 0 }, { primaryTerm: "or", level: 2, condition: 1 }, { primaryTerm: "test5",level: 3,  condition: 0 }, { primaryTerm: "and",level: 3,  condition: 2 }, { primaryTerm: "test5", level: 3, condition: 0 }, { primaryTerm: "and", level: 1, condition: 2 }, { primaryTerm: "test6", level: 2, condition: 0 }, { primaryTerm: "or", level: 2, condition: 1 }, { primaryTerm: "test7", level: 2, condition: 0 }];

console.log(getTree(predicates1));
console.log(getTree(predicates2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: This should get you started:
function parse(tokens, level) {
    let expr = []

    while (tokens.length) {
        let tok = tokens[0]
        if (tok.level < level) {
            break;
        }
        if (tok.level === level) {
            expr.push(tok.primaryTerm);
            tokens.shift();
            continue;
        }
        expr.push(parse(tokens, tok.level))
    }

    return {op: expr[1], args: expr.filter((_, n) => n % 2 === 0)}
}

For your input, parse(stackTest.predicates, 1) returns this AST:
{
    "op": "and",
    "args": [
        "test1",
        "test2",
        {
            "op": "or",
            "args": [
                "test3",
                "test4",
                {
                    "op": "and",
                    "args": [
                        "test5",
                        "test5"
                    ]
                }
            ]
        }
    ]
}


text:
Q: How do I solve "AttributeError: 'Resource' object has no attribute 'documents'" error? I'm programming a script to create multiple Google Docs files.
I have followed the Google Docs API Guides:
Quickstart (https://developers.google.com/docs/api/quickstart/python)
and Creating and managing documents (https://developers.google.com/docs/api/how-tos/documents)
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

    # Call the Drive v3 API
    results = service.files().list(
        pageSize=10, fields="nextPageToken, files(id, name)").execute()
    items = results.get('files', [])

    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))

    print("Creating blank Google Docs file")
    title = 'My Document'
    body = {
        'title': title
    }
    doc = service.documents() \
        .create(body=body).execute()
    print('Created document with title: {0}'.format(
        doc.get('title')))
    return

if __name__ == '__main__':
    main()

Note:
This website does not display the indentation around "print("Creating blank Google Docs file")" and "return" correctly. That should be indented once and not twice as it is showing here. The block is not part of the "else: print('Files:')" branch.
Instead of creating a Google Docs file I get the following error:
Traceback (most recent call last):
  File "create-teamwork-sops.py", line 234, in <module>
    main()
  File "create-teamwork-sops.py", line 227, in main
    doc = service.documents() \
AttributeError: 'Resource' object has no attribute 'documents'

redpajama_set_name: RedPajamaStackExchange


text:
Q: URLResourceKey.quarantinePropertiesKey is only available on OS X 10.10 or newer when installing chromedriver I am downloading chromedriver through a brew cask install (see related issue ) and when I try to download it I get the following error (pasted full output from command entry):
(env) MacBook:project_dir owner$ brew cask install chromedriver
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
==> Updated Formulae
dnstwist            grpc                pdns                uftp
firebase-cli        lf                  pdnsrec             wildfly-as
glslviewer          libxlsxwriter       tile38              zabbix

==> Satisfying dependencies
==> Downloading https://chromedriver.storage.googleapis.com/2.41/chromedriver_ma
######################################################################## 100.0%
/usr/local/Homebrew/Library/Homebrew/cask/lib/hbc/utils/quarantine.swift:29:30: error: 'quarantinePropertiesKey' is only available on OS X 10.10 or newer
      forKey: URLResourceKey.quarantinePropertiesKey
                             ^
/usr/local/Homebrew/Library/Homebrew/cask/lib/hbc/utils/quarantine.swift:29:30: note: add 'if #available' version check
      forKey: URLResourceKey.quarantinePropertiesKey
                             ^
Error: Failed to quarantine /Users/user/Library/Caches/Homebrew/downloads/42621d77ecaa889fa8ca73ac4b2a2228e3c1d11f20d84c6898e7645397d00f1d--chromedriver_mac64.zip. Here's the reason:
/usr/local/Homebrew/Library/Homebrew/cask/lib/hbc/utils/quarantine.swift:29:30: error: 'quarantinePropertiesKey' is only available on OS X 10.10 or newer
      forKey: URLResourceKey.quarantinePropertiesKey
                             ^
/usr/local/Homebrew/Library/Homebrew/cask/lib/hbc/utils/quarantine.swift:29:30: note: add 'if #available' version check
      forKey: URLResourceKey.quarantinePropertiesKey

My current macbook specs are as follows:
Has anyone ran into this issue before? Any help would be appreciated. I am trying to set up a headless chrome driver and failing.
UPDATE_EDIT: I've since moved on from Chrome and had more luck using Firefox headless instead, but this is still no solution to the issue above.

A: https://github.com/Homebrew/homebrew-cask/issues/51554#issuecomment-418215466
try below.
$ brew cask install --no-quarantine chromedriver

A: This is due to a current bug in Homebrew, and a fix has been merged
Per issue #4809:

Hi, PR #4656 appears to break brew cask install on 10.11. I get an error on 10.11, but not on 10.12. As a workaround, re-running with the --no-quarantine flag is successful. I'm not sure why this swift feature isn't available, my OS is up to date.
(snip)
/usr/local/Homebrew/Library/Homebrew/cask/lib/hbc/utils/quarantine.swift:29:30: error: 'quarantinePropertiesKey' is only available on OS X 10.10 or newer
      forKey: URLResourceKey.quarantinePropertiesKey

(etc)

(snip and etc mine)
This is the same issue you are facing.
There is a PR (#4796) that addresses this, which has been merged into master as of a day ago (2018-09-06):

The Gatekeeper API I've written relies on an up-to-date CLT (or Xcode) install, and xattr's -r flag for native recursion. There are cases where Swift is too old or is set to a deployment target earlier than MacOS 10.10, and thus cannot use the URLResourceKey.quarantinePropertiesKey constant. And in the current Mojave beta, xattr does not have Apple's -r extension for doing native filesystem traversal.
This pull request inserts an additional check in the Swift script, the Quarantine.available? function and brew cask doctor, and changes propagate to use xargs for recursion.

I just ran a brew update and it tells me I am running 1.7.3 running at commit 5d894, which was committed today (2018-09-07) and is the latest version of homebrew-core at time of writing.


text:
Q: DXGI AcquireNextFrame receives the next frame only after 20ms (50fps), is it possible to speed up to 10ms? Good afternoon.
I'm writing a program that would record video from the desktop at 100 fps, but I ran into a problem, AcquireNextFrame receives the next image from the desktop only after 20 ms, because of this, the maximum fps that I can get will be 50, you can do something with this?
Thanks.

A: IDXGIOutputDuplication::AcquireNextFrame will receive nothing if nothing changes on the captured output.
It's not like a "PleaseCaptureScreenNow" command.
Timouts are expected and must taken into account. That's why you can't really design a workflow for example like capture => convert => copy/encode on just one unique thread.
Microsoft official DXGIDesktopDuplication sample is designed with multiple threads for that reason.
This method can perfectly capture at 100fps or more if the screen changes at that speed (and you have good GPU, drivers, etc.).


text:
Q: Is diffraction affected by interaction between photons and electrons? Suppose we take a sheet of ordinary metal, make a narrow slit in it, and shine a light beam through the slit onto a screen.  The light beam will diffract from the edges of the slit and spread out onto the screen.
Now let's take an identical sheet, with an identical slit, but this time made of neutronium, and shine an identical light through it.
Will the image on the screen be the same?  Or are there additional interactions with the electrons in the first sheet which aren't present in the second experiment, and which cause the images to be different in the two experiments?

A: Generally, what causes diffraction patterns is the blocking or absorbing of some parts of a wavefront of light while allowing other parts to pass through unaltered. That in turn means that the exact nature of the material use to block some parts of the wavefront makes almost no difference in determining what kind of pattern will be formed. In particular -- and a bit counter-intuitively -- the edges of the material in a mask normally have almost no influence on the diffraction pattern produced.
The reason is that diffraction phenomena are wave phenomena, not particle effects. Unlike particles, waves always try to disperse. In fact, they are kept from dispersing almost entirely by the constructive interference effects of other nearby waves.
For example, if you pass light through a very small pinhole, the result is not at all like particles traveling through a hole. If it was, shining a bright light through a small pinhole would produce a sharp, tiny spot of light on the other side. Instead, you get light spreading out in all directions in a uniform, almost hemispherical pattern. If you have several such pinholes for a single distant source of light, you start seeing a really interesting effect: Interference patterns in which the light appears and disappears on the far side of the pinholes. These patterns reflect the geometry of the holes, where different distance cause the light waves to reinforce each other or destroy each other in different directions.
The more pinholes you add, the more complicated the patterns get -- and they can get very complicated indeed. A hologram is nothing more than an extraordinarily complex version of this effect of selectively passing and blocking sections of a wave front.
The reason we tend to think that light goes "straight" as its default path is very much an illusion. It happens because light has quite small wavelengths, compared to us, and a flashlight projects a very broad front of these waves. Even though such ordinary light is quite jumbled in terms of frequency and wave alignments (phase), the average result ends up being surprisingly well focused and able to project in a straight line.
A laser does even better. A laser uses one frequency with precise phase, and can produce wave fronts that "stick together" for absurdly long distances before they begin to fray out. Even more so than flashlights, lasers give the illusion that light naturally travels in straight lines, but it's really all smoke and mirrors (and even more so, waves).
So, to assess how light will react after going through any kind of mask that removes or blocks some parts of it and passes other parts of it, the trick is to assess the situation almost entirely in terms of wave theory: What kinds of waves are arriving? How orderly are they? And most importantly, exactly which parts of a wavefront are allowed to pass through, while the other parts are blocked?
It's a fascinating field with many important applications in modern life, from radio cell towers to lasers to the manufacture of silicon chips for electronics. All of these vital technologies depend on the specifics of how waves and wave diffraction patterns work.

A: If the geometry of the sheets is the same, they will usually have very similar diffraction patterns. Textbook derivations of diffraction patterns only make use of the geometry; their equations do not involve, e.g. the dielectric constant of the material. They are using a simple model in which the only way light interacts with the material is that the material blocks it. This model is generally very accurate for the materials used in the experiment.
If you wanted a more refined picture, then the material could indeed affect the diffraction pattern. A simple example is to make the material transparent. Then the light would mostly pass right through, drastically altering the interference pattern.
Another drastic case would be if the photons were interacting incoherently with the material - e.g. flipping electron spins states. Then the electrons would contain "which path" information about the photons. This would destroy interference altogether.
Even neutrons can scatter photons, so there will always be at least some minor interaction, but the difference between diffraction from 1 micron slits in gold foil and a 1 micron slits in tin foil will probably be so slight as to be undetectable, simply because the interaction can be modeled well enough by saying that the slit itself is radiating coherently while the surrounding metal is not radiating at all.
If you really wanted to calculate the diffraction pattern accurately, you would need to account for the way light interacts with the metal in detail, but you would also need to account for the exact atomic structure of your slit and the exact shape of your wavefront and the exact density of the gas it's traveling through and the exact position of the screen you're observing on and the exact efficiency of your detectors, etc. My guess is that in most typical cases the error in being able to construct the geometry you want and to get a really pure wavefront dominates over the error due to the interactions of light with the material.
Finally, in x-ray diffraction, the material is not only important, but is the object of study. When we use light with wavelength of a few Angstroms to a few nanometers, we can see diffraction off of the atomic structure itself. The atoms become the "slits". This is a major source of our knowledge of the structure of crystals.


text:
Q: How come eclipse doesn't find my intent How come eclipse doesn't find my intent...
Intent menuIntent = new Intent("com.project.MyProj.MenuActivity");

                    startActivity(menuIntent);

if it is clearly declered in manifest ??
 <activity
            android:name="com.project.MyProj.MenuActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="com.project.MyProj.MenuActivity"/>
               <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity

In Debugger I get the error: Source not found

A: Have you tried Intent menuIntent = new Intent(this, MenuActivity.class); (http://developer.android.com/training/basics/firstapp/starting-activity.html) ?

A: I know what was wrong, it happened, but I don't know why exactly it happened. In my MenuActivity I was writing a method onCreateOptionsMenu. and if something goes wrong there then I get this error.


text:
Q: Drawing outside a UICollectionViewCell's bounds when using a UICollectionViewFlowLayout Has anyone been able to draw outside the bounds of a UICollectionViewCell without the cell clipping to its bounds?  I have a vanilla collection view that uses a UICollectionViewFlowLayout (horizontal) and I would like to be able to draw a path outside the bounds of the UICollectionViewCell without disrupting any of the layout provided by UICollectionViewFlowLayout. Setting clipsToBounds to NO does not seem to do the trick.

A: I got it to work by setting the cell's layer's maskToBounds property to NO. (You'll need to bring in the QuartzCore framework and import it into the View Controller…)
If that doesn't work, try setting the cell's contentView's layer's maskToBounds property to NO.
Good luck!

A: For me using maskToBounds did the job
   override func awakeFromNib() {
    super.awakeFromNib()
    self.layer.masksToBounds = false
   }


text:
Q: How to convert varchar to date format I want to convert my field (dateVar = '08/2018') to a real date field. Actually i have only months and years, so i need to add just 01 like a day.
My final result should be 2018-08-01.
CREATE TABLE dateTable (
    dateVar varchar(10)
);

insert into dateTable (dateVar)
values('08/2018'),('01/2015');

i used this to convert to date but doesnt work
SELECT CONVERT(date, dateVar, 103) FROM dateTable

A: You could concatenate missing 01:
SELECT CONVERT(date, '01/'+dateVar, 103)
FROM tab

DBFiddle Demo
To avoid problems with incorrect user input you could use TRY_CONVERT. In case of conversion error it will return NULL instead.

A: You should use standard formats for dates:
insert into dateTable (dateVar)
    values('2018-08-01'), ('2015-01-01');

The hyphens is ISO standard and standard in most databases.  It almost always works correctly in SQL Server, but the real SQL Server standard drops the hyphens -- '20180801' and '20150101'.
The table should then be declared to have a date for the column:
CREATE TABLE dateTable (
    dateVar date
);

If you need to see this in a particular format, use a computed variable:
CREATE TABLE dateTable (
    dateVar date,
    date_mmyyyy as (right(convert(varchar(10), dateVar, 103), 7))
);

Then date_mmyyyy shows the value as you would like to see it.

A: The trick is just to manipulate the string into YYYYMMDD format and cast it.
cast(right(dateVar,4) + left(dateVar,2) + '01' as date)


text:
Q: How to SELECT rows from table A where JOIN with table B matches condition 1 or doesn't exist for condition 2 I came upon a problematic query to be made on my two tables.
My tables can be simplified to:
Table A:
id
(PRIMARY KEY - id)

Table B:
id (matches id from table A)
shop
active
(PRIMARY KEY id, shop)

Now I want to select rows from Table A for shops 2 and 3 where active = false, or row for those shops doesn't exist at all.
So for example I have:
Table 1:
(1)
(2)
(3)

Table 2:
(1, 1, true)
(1, 2, false)
(2, 3, false)
(1, 3, true)
(3, 2, false)
(3, 3, false)

I should get id 2 and 3.
2 - because row for shop 2 doesnt exist and row for shop 3 has active = false.
3- because it has both rows with active = false

A: Really difficult to work out what you mean as you appear to be mixing up whether it is id or shop on tableB that you want to match on. And your sample data doesn't seem to match up with your description.
However it looks like a LEFT OUTER JOIN, and checking for no matched records in the WHERE clause. Put a check for active in the ON clause of the join to exclude match which are active as well as those that do not match:-
SELECT TableA.id
FROM TableA
LEFT OUTER JOIN TableB
ON TableA.id = TableB.shop
AND TableB.active = true
WHERE TableB.id IS NULL

EDIT - following your comment to clarify the columns, this should do it.
It does a LEFT OUTER JOIN from TableA to TableB where the active field is true. Any matches mean that record is rejected. This means you will only get a record back where either there is no record on TableB for that id, or there is a match on id but active is set to false.
SELECT DISTINCT TableA.id
FROM TableA
LEFT OUTER JOIN TableB
ON TableA.id = TableB.id
AND TableB.active = true
WHERE TableB.id IS NULL


text:
Q: Resharper hiding documentation Resharper has a "feature" that seems to hide parameter information, XML based documentation, and just about anything useful in Intellisense. I wish to disable this "feature". Note: I have seen Resharper not disable parameter information before, so I know it's possible, somehow.
Here's what Visual Studio's parameter information looks like with Resharper disabled:

And this is what Resharper's information looks like:

As can be seen, Resharper's "feature" here is beyond useless. I have tried to resolve this by following all the steps in this question and given that question was asked over 3 years ago, my question is not a duplicate. After over 3 years I was hoping this had been fixed, because it must be a bug, there's no sane reason for this to even exist.
How do I get parameter information back?

A: It is a known issue if XML doc file for a library has "redirect" attribute for <doc> tag, e.g.
<?xml version="1.0" encoding="utf-8"?>
<doc redirect="%PROGRAMFILESDIR%Reference Assemblies\Microsoft\Framework\.NETFramework\v4.X\mscorlib.xml" />

The issue has been fixed in R# 2017.2 EAP builds.


text:
Q: WPF Countdown too slow (DispatcherTimer) I am currently writing a WPF application that I want to have a Countdown Timer in it. Here is my CountDown class:
 internal class CountDown : INotifyPropertyChanged
{
    private readonly DispatcherTimer _timer;
    private string _currentTimeString;
    private TimeSpan _runTime;
    private TimeSpan _timeleft;

    public CountDown(TimeSpan runTime)
    {
        if (runTime == null) throw new ArgumentNullException("runTime");
        _runTime = runTime;

        _timer = new DispatcherTimer();
        _timer.Interval = new TimeSpan(0, 0, 0, 0, 10);

        _timer.Tick += Update;
    }

    public CountDown(TimeSpan runTime, TimeSpan interval)
    {
        if (runTime == null) throw new ArgumentNullException("runTime");
        _runTime = runTime;

        _timer = new DispatcherTimer();

        if (interval == null) throw new ArgumentNullException("interval");
        _timer.Interval = interval;

        _timer.Tick += Update;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public string CurrentTimeString
    {
        get { return _currentTimeString; }
        private set
        {
            _currentTimeString = value;
            NotifyPropertyChanged();
        }
    }

    public void Start()
    {
        var task = new Task(_timer.Start);
        _timeleft = _runTime;
        task.Start();
    }

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    private void Update(object sender, EventArgs e)
    {
        _timeleft -= _timer.Interval;

        DateTime newTime = new DateTime();
        newTime = DateTime.MinValue;
        newTime += _timeleft;

        CurrentTimeString = newTime.ToString("mm:ss:ff");
    }
}

Composition Root:
public MainWindow()
    {
        CountDown countDown = new CountDown(new TimeSpan(0, 1, 0));

        InitializeComponent();
        tb1.DataContext = countDown; //tb1 = TextBlock
        countDown.Start();
    }

Everything is working fine except when I set the interval to like 10ms, then it's slower than real seconds. How can I fix this?
EDIT: I can't answer my own questions yet, so here it goes:
I completely rewrote my class without using any timers. Found out that these aren't accurate enough for me.
public class CountDown : INotifyPropertyChanged
{
    private string _currentTimeString;
    private TimeSpan _runTime;
    private bool _shouldStop;
    private DateTime _timeToStop;
    private TimeSpan _updateInterval;

    public CountDown(TimeSpan runTime)
    {
        if (runTime == null) throw new ArgumentNullException("runTime");
        _runTime = runTime;

        _updateInterval = new TimeSpan(0, 0, 0, 0, 10);

        Tick += Update;
    }

    public CountDown(TimeSpan runTime, TimeSpan updateInterval)
    {
        if (runTime == null) throw new ArgumentNullException("runTime");
        _runTime = runTime;

        if (updateInterval == null) throw new ArgumentNullException("updateInterval");
        _updateInterval = updateInterval;

        Tick += Update;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public event Action Tick;

    public string CurrentTimeString
    {
        get { return _currentTimeString; }
        set
        {
            _currentTimeString = value;
            NotifyPropertyChanged();
        }
    }
    public void Start()
    {
        _shouldStop = false;
        _timeToStop = DateTime.Now + _runTime;
        var task = new Task(GenerateTicks);
        task.Start();
    }

    public void Stop()
    {
        _shouldStop = true;
    }

    private void GenerateTicks()
    {
        while (_shouldStop == false)
        {
            if (Tick != null)
                Tick();

            Thread.Sleep(_updateInterval);
        }
    }

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    private void Update()
    {
        var timeLeft = _timeToStop - DateTime.Now;

        if (timeLeft <= TimeSpan.Zero)
        {
            _shouldStop = true;
            return;
        }

        var timeLeftDate = DateTime.MinValue + timeLeft;

        CurrentTimeString = timeLeftDate.ToString("mm:ss:ff");
    }
}

A: First of all you don't need Tasks in order to accomplish a countdown. If you use a timer which ticks every 50ms you won't block anything. Faster ticks than 50ms won't make sense, because I guess your countdown shows hours, minutes or seconds. Milliseconds are a bit too much for a timer, isn't it? And even if you want to display the ms-range the human eye won't notice whether the countdown was updated every 10 or 50ms.
Next it would probably be easier to handle if you used DateTime as time-base. It makes it easier to calculate the actually remaining time.
using System;
using System.Timers;

public class Countdown
{
    private readonly TimeSpan countdownTime;
    private readonly Timer timer;
    private DateTime startTime;

    public Countdown(TimeSpan countdownTime)
    {
        this.countdownTime = countdownTime;
        this.timer = new Timer(10);
    }

    public string RemainingTime { get; private set; }

    public void Start()
    {
        this.startTime = DateTime.Now;
        this.timer.Start();
    }

    private void Timer_Tick(object state)
    {
        var now = DateTime.Now;
        var difference = now - this.startTime;
        var remaining = this.countdownTime - difference;
        if (remaining < TimeSpan.Zero)
        {
            this.timer.Stop();
            // Raise Event or something
        }

        this.RemainingTime = remaining.ToString("mm:ss:fff");
    }
}

An asynchronous countdown would be a bit overpowered for this situation. But if you require it, it's easily upgraded.

A: Your Countdown class has 2 parameters in the constructor. Your single parameter constructor is not being called in this case (the one you had with 10ms). You ARE supplying 1s (new TimeSpan(0,0,1)) for the interval in the second parameter, so that is what you see in the UI when you run it.


text:
Q: Excel: Select every 5th column on another sheet, drag and autofill I'm looking to select every 5th column from another sheet, and put it into one row where they're next to each other, and be able to drag it so it autofills as there is a lot more columns.
It should come out like:
=Sheet1!B$4 | =Sheet1!G$4 | =Sheet1!L$4 | =Sheet1!Q$4 ...
=Sheet1!C$4 | =Sheet1!H$4 | =Sheet1!M$4 | =Sheet1!R$4 ...
...

How can I do this with a formula?

A: In your first cell of choice:
=INDEX(Sheet1!$4:$4,5*(COLUMNS($A:A)-1)+ROWS($1:2))
Copy across and down as required.
Note that INDEX set-ups should be preferred to volatile OFFSET/INDIRECT ones.
Regards


text:
Q: Conditional expectation of book Shiryaev page 233
Possible Duplicate:
Help with conditional expectation question

I have problem with exercise, I didn't solve.
Let $X$ and $Y$ be i.i.d. random variables with $E(X)$ defined. Show that
$$E(X|X+Y)=E(Y|X+Y)= \frac{X+Y}{2}$$ (a.s.)
Thanks very much for your help.

A: The first part of the equation:
$$E(X|X+Y) = E(Y|X+Y)$$
is true by symmetry.  They are independent and identical.
Now, what is $E(X|X+Y)+E(Y|X+Y)$?

A: Hint:

*

*Using the linearity of conditional expectation (and an other property), show that $E(X\mid X+Y)+E(Y\mid X+Y)=X+Y$.

*Show that $E(X\mid X+Y)=E(Y\mid X+Y)$ by the following argument. Take $B$ a set in the $\sigma$-algebra generated by $X+Y$ ($B=(X+Y)^{-1}(B')$ for some $B'$), then write
$$\int_B X \, dP=\int_{\Bbb R}\int_{\mathbb R}x\chi_{x+y\in B'} \, dP_X(x)\, dP_Y(y),$$
then use independence and a substitution.


text:
Q: FIFO with /dev/urandom I got a problem. Trying to write a simple programm which forks once
The parent proccess sends child bytes from /dev/urandom and child outputs them to screen (15 bytes in HEX per line). The problem is: when i first open the compiled programm the output looks like:
B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0
B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0
B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0
B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0
B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0
...
B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0
(not always "B0", but surely the same ONE byte)
When I run the same program (not re-compiled) once again the output seems to be OK... Any ideas ?
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>

int main(int argc, char *argv[])
{

        char bufforek[256];

        printf("P1: READING /dev/urandom\n");

        FILE *file_ptr = fopen("/dev/urandom", "r");

        int file=open("FIFO",O_RDWR);
        mkfifo("FIFO",0666);
        char pomoc;
        int hexa;
        int i=1;

        if(fork()==0)
        {

            char bufforek1[256];
            while(read(file,bufforek1,sizeof(bufforek1)))
            {

                pomoc = *bufforek1;
                // printf("%hhX ", pom);

                hexa = (int)pomoc;
                pomoc = *bufforek1;
                printf("%hhX ", pomoc);
                if(i==15)
                {
                    printf("\n");
                    i=1;
                }
                else i++;
                // write(pipe_table[1],bufforek,sizeof(bufforek));

            }
            return 0;
        }
        while ((fgets(bufforek, sizeof(bufforek), file_ptr))!=NULL) write(file, bufforek, sizeof(bufforek));

        unlink("FIFO");

    return 0;
}

A: As rodrigo points out, your instructions mkfifo and open("FIFO"...) are backwards, also if you are going to use a temporary fifo, you can simply use pipe(2) call rather than creating and deleting a fifo.


text:
Q: Is there a name for when we extend the codomain of a function? (sort of like the opposite of the restriction) If I have a function $f: X \to Y$ and a subset $A \subseteq X$ then I can define the restriction $f|_{A}: A \to X$ by $f|_{A}(a) = f(a)$ for all $a \in A$. This can be interpreted as composing with the inclusion map $\iota: A \to X$ given by $\iota(a) = a$ for all $a \in A$ since we have $f|_{A} = f \circ \iota$, and interpreting $f|_{A}$ in this way can be quite useful (for example because the inclusion map is continuous in topology and a homomorphism in algebra, and so if $f$ is continuous/a homomorphism, so is $f|_{A}$ since it is a composition of continuous functions/homomorphisms).
However what if instead I have a superset $B$ containing $Y$? Let's say I call my altered function $f_B^{\ast}: X \to B$ so that $f_B^{\ast}(x) = f(x)$ for all $x \in X$. I can similarly define the inclusion map $\iota: Y \to B$ and then I have $f_B^{\ast} = \iota \circ f$. All I am doing is increasing the codomain to include values which don't get mapped to. For example any function into the natural numbers can equally be considered a function into the integers, or the rationals, or reals, complex numbers, quaternions, and so on. I feel like this is something mathematicians do without reflecting it in their notation. However to me it seems very much dual to the restriction of a function, and I was wondering if it has a name. Thanks for taking the time to read.

A: To answer my own question, see here: https://mathoverflow.net/questions/29911/whats-the-notation-for-a-function-restricted-to-a-subset-of-the-codomain (I have no idea why I couldn't find this when I was Googleing for answers). What I'm talking about is indeed dual to the usual restriction, and so the obvious name for it is the "corestriction".


text:
Q: Why does the Java compiler say my class needs to be defined in a separate file? This keeps on saying to define it in it's own file.
public class MathCalculator {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner number = new Scanner(System.in);
        double fnum, snum, answer;
        {System.out.println("This is the addition calculator");
        System.out.println("Your first number: ");
        fnum = number.nextDouble();
        System.out.println("Your second number: ");
        snum = number.nextDouble();
        answer = fnum + snum;
        System.out.println(answer);
        }
        {System.out.println("This is the subtraction calculator");
        System.out.println("Your first number: ");
        fnum = number.nextDouble();
        System.out.println("Your second number: ");
        snum = number.nextDouble();
        answer = fnum - snum;
        System.out.println(answer);
    }
        {   System.out.println("This is the multiplication calculator");
        System.out.println("Enter your first number: ");
        fnum = number.nextDouble();
        System.out.println("Enter your second number: ");
        snum = number.nextDouble();
        answer = fnum * snum;
        System.out.println(answer);
    }
        {   System.out.println("This is the division calculator: ");
        System.out.println("Enter your first number: ");
        fnum = number.nextDouble();
        System.out.println("Enter your second number: ");
        snum = number.nextDouble();
        answer = fnum / snum;
        System.out.println(answer);}
        System.out.println("What review do you give us from terrible bad ok good and great?");
        answer = number.nextDouble();
        int terrible = 1;
        int bad = 2;
        int ok = 3;
        int good = 4;
        int great = 5;
        {if (answer == terrible);
        System.out.println("I'm sorry, we'll try and improve.");
        }{if (answer == bad);
        System.out.println("Ok, we'll improve a bit more.");
        }{if (answer == ok);
        System.out.println("Thank you for your ok review.");
        }{if (answer == good);
        System.out.println("Why, thank you!");
        }{if (answer == great);
        System.out.println("WOW! THANK YOU SO MUCH!");
        }

    }

}

I know this is a really simple code, but if you look at the bottom, can you also tell me why it's printing all five arguments?

A: The semi-colons after the if statement ensure that the following statement blocks are always executed
if (answer == terrible);
                       ^

Simply remove them all

A: First, all public classes need their own file named after them.  Place your public class MathCalculator in MathCalculator.java.
Second, remove those semicolons after each if condition.  They act as the block for the if condition, and the println statements after that will always print, because they're not attached to the if condition.

A: You need to fix your formatting, your IDE will do this for you.
{
    if (answer == terrible); // do nothing
    System.out.println("I'm sorry, we'll try and improve.");
}{
    if (answer == bad); // do nothing
    System.out.println("Ok, we'll improve a bit more.");
 }{
    if (answer == ok); // do nothing
    System.out.println("Thank you for your ok review.");
 }{
    if (answer == good); // do nothing
    System.out.println("Why, thank you!");
 }{
    if (answer == great);
    System.out.println("WOW! THANK YOU SO MUCH!");
 }

For some reason, the code runs smoothly, even with errors. However, when I hit the System.out.println("What review do you give us from terrible bad ok good and great?"); It says something different

Most likely you are running an old version of the code if it's not compiling, or you are using eclipse which allows you to run code which doesn't compile and you get an error at runtime.  I suggest you turn this "feature" off and only run code which compiles.


text:
Q: Tesseract Function to Split Into 2 Columns I would like to use PyTesseract and OpenCV to read (hundreds) of pages of information like the following into JSON or CSV. How can I let tesseract know about the solid line in the middle dividing the two columns of information? Furthermore, some rows of data are 2 lines instead of 1. What's the best way to account for that?
I'm fairly new at using tesseract and any help would be appreciated!

Edit!!
This is what I have now:
# OCR
txt = pytesseract.image_to_string(thr, config="--psm 11")

# Add ocr to the corresponding part
txt = txt.split("\n")

row = 0
col = 0

for txt1 in txt:

    # Skip over OCR strings that are just spaces or ''
    if txt1.isspace() or txt1 == '':
        continue

    # Hard code detection in...let's just place it into the last column for now
    # Theoretically, the state ("Alaska" in this case) will be in column 0 in the same row
    if re.match(r"\d*\sOpen\sRestaurants", txt1):
        col == 3

    worksheet.write(row//4, col%4, txt1)
    col += 1
    row += 1

workbook.close()

Everything above this code chunk is identical.
However, there are still a lot of miss-alignments, especially when some addresses or names take more than one line. Additionally, why is the text on the first line read in a different order compared to the rest of the rows?
I was thinking that perhaps I could enforce that every fourth txt is in alphabetical order and use that to detect misalignment? But if even the first row is incorrect, I'm not sure how much I want to hard code corrections. Additionally, sometimes the multiple line entries arise from the address column while other times it arises from the name column (e.g.  258 Interstate Commercial Park Loop on the left-hand side of the page).
Here are some screenshots of the mix-ups on the left:

And on the right:

A: *

*I would like to use PyTesseract and OpenCV to read (hundreds) of pages of information like the following into JSON or CSV.
You have multiple choices, xlswriter, pandas, etc. For instance you can look at the tutorial for xlswriter.

*

*How can I let tesseract know about the solid line in the middle dividing the two columns of information?
You can't. You need to manually divide the image by width into two parts. For instance: first-part, second-part
How do you manually divide the image by width?
First get the size of the image, then set the indexes.
# Get the size
(h, w) = img.shape[:2]

# First part
first_part = img[0:h, 0:int(w/2)]

# Second part
second_part = img[0:h, int(w/2):w]

*

*Furthermore, some rows of data are 2 lines instead of 1. What's the best way to account for that?
Tesseract will account that but you need to know the followings:

*

*Image processing techniques for improving the quality

*Page-segmentation-modes

The input image contains no artifact. Therefore at the first glance image preprocessing seems unnecessary. Still you can apply binarisation to make sure to get the best accuracy.

Part-1
Part - 2

Northpor. 13620 Highway 43 North Hardikkumar Patel (205) 339-1188  Northport 1836 McFaland Bld Harikkumar Patel {205} 339-1782  Northport 5550 McFarland Bld Sharmishta Patel (205) 200-7822  Odenvile 130 Council Orive Gratton Curbow (205) 629-7827  Oneonta 511 nd Ave E Govinddhai Patel (205) 625.5847   velxa 1017 Columbus Parkway Luis Cribb (934) 749-3628   alka 2300 Gateway Or Donna Cribb (234) 749-2308  pp 101 Stewart Ave 'Utpa! Patel {334} 433-7325,  Orange Beach 25755 Perdido Beach Bhd. Patrick Shedd (251) 981-6881  Orange Beach 25814 Canal Rd Patrick Shed (251) 91-4184  Owens Crossroads 6707 Hwy 43) South Richard Hyde (256) 519-2425  Owns Gross Road 330 Sutton Road Richard Hyde (256) 518-2004  . . .  . . .  . . .
Talladega 244 Haynes SI tus Crisp (258} 315-0191 Talladega 608 East Batle Street Luis Cribb (256) 362-0781 Tallassee 454 Gimere Ave Donna Cribb (334) 283-2067 Tanner 5956 Hwy 31 N Mike Nadesi (256) 352-9808 Torani 1806 Pingon Valley Re Sanjayknat Patel (205) 849-0112 Theodore 5827 Hwy SOW Mukeshkumar Soparwala (251) 854-0048, Theodore 6860 Theodore Dawes Rd Anthony Laf enier (251) 853-2010 Thamasvilie 33202 Hwy 43 Ranjeev Acharya (334) 636-0333 Thomasville 3430S Huy 43 Ranjeey Acharya (334) 636-0830 Tius 80 Tus Road Garret Gray (G34) 514-9930 Town Creek 2795 Hwy 20 Madhav Maina (256) 686-3900 Troy 1003 Highway 231 South Luis Cribb (339) 568-7944 Troy 1420 US 231 South Dehua Patel (334) 670-6390 . . .  . . .  . . .

Images are rescaled to fit the size. As we can see we can get the output by assume the image as a single uniform block of text.
How do you write the result?

*

*First, you need to store the OCR results in lists.

*

*
if i == 0:
    for sentence in txt:
        part1.append(sentence)
else:
    for sentence in txt:
        part2.append(sentence)

*Second, you need to pair the list tuples.

*

*
for txt1, txt2 in zip(part1, part2):
    worksheet.write(row, col, txt1)
    worksheet.write(row, col + 1, txt2)
    row += 1

zip function enable us to get the pair of data from each column in each iterator. Then we write the values to the corresponding columns.
Some data in the excel may not be accurate. If that's the case then you need to try the image with different processing methods with different page-segmentation-modes.

Code:
# Load the libraries
import cv2
import pytesseract
import xlsxwriter

# Load the image in BGR format
img = cv2.imread("WFJO2.jpg")

# Initialize the workbook
workbook = xlsxwriter.Workbook('result.xlsx')
worksheet = workbook.add_worksheet()

row = 0
col = 0

part1 = []
part2 = []

# Get the size
(h, w) = img.shape[:2]

# Initialize indexes
increase = int(w / 2)
start = 0
end = start + increase

# For each part
for i in range(0, 2):

    # Get the current part
    cropped = img[0:h, start:end]

    # Convert to the gray-scale
    gry = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)

    # Threshold
    thr = cv2.threshold(gry, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

    # OCR
    txt = pytesseract.image_to_string(thr, config="--psm 6")

    # Add ocr to the corresponding part
    txt = txt.split("\n")

    if i == 0:
        for sentence in txt:
            part1.append(sentence)
    else:
        for sentence in txt:
            part2.append(sentence)

    # Set indexes
    start = end
    end = start + increase

for txt1, txt2 in zip(part1, part2):
    worksheet.write(row, col, txt1)
    worksheet.write(row, col + 1, txt2)
    row += 1

workbook.close()


text:
Q: How do I fix the Bootstrap Accordion Arrow direction? I am using Bootstrap 5.1 with the Accordion feature. However, when the page loads the Chevron is upside down and only rights itself after clicking on it a couple of times.
Here is the code:

                <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                        Current Courses
                </button>

                    {current_courses}

{current_courses:title}
                        {current_courses:hours} CPE Hours {current_courses:course_date}

                    {/current_courses}

The Accordion works correctly but the chevron first appears like this:

Here is the css for the accordion:
.accordion-button::after {
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23A81912'%3e%3cpath fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e");
        }
.accordion-button:not(.collapsed)::after {
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23A81912'%3e%3cpath fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e");
        }

Any help in getting the chevron turn around would be appreciated.

A: First make sure that you use unique id's for both .accordion-button and .accordion-collapse.

If it is collapsed by default, add the .collapsed on the .accordion-button  and set aria-expended to true.

.accordion-button::after {
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23A81912'%3e%3cpath fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e");
}

.accordion-button:not(.collapsed)::after {
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23A81912'%3e%3cpath fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e");
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css" rel="stylesheet"/>

      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
         Current Courses
     </button>

        {current_courses}

{current_courses:title} {current_courses:hours} CPE Hours {current_courses:course_date}

        {/current_courses}


text:
Q: Simulating Pareto distribution in R Jags (Bayesian) I'm trying to simulating the Pareto distribution in R jags to get the posterior mean and 95% credible set for α.
The Pareto distribution for y ≥ u is:
f(y;α,u)= αu^α / y^(α+1), u,α > 0, and f(y;α,u) = 0 when y < u
The expectation is E[Y;α,u] = αu/(α − 1) if α > 1 and ∞,otherwise.
I'm using dpar(alpha, u) to compute the distribution for y ≥ u in JAGS.
Set u = 35 and under the uniform prior, p(α) = U[0, 50], generate 20,000 posterior samples with thin=1 and n.adapt=1000. This is the code I did, but I'm not too sure about the likelihood and
the model.
Any help would be appreciate!
cat("model
{
    alpha ~ dpar(50,35)
  #Not too sure about the code above
  }", file="HIghTemp.csv")
data_temp = list(temp$MaxTemp)
jags.temp = jags.model(file="HIghTemp.csv",data=data_temp,n.chains=1, n.adapt=1000)
params.temp=c("alpha")
samps.temp = coda.samples(jags.temp, params.temp, n.iter=20000,thin=1)
summary(samps.temp)


text:
Q: Bootrstrap masonry grid click here for sample image
click sample 2
how i can create masonry type cards by using bootsrap col,
what classs do i need to use, or do i  need to re code the structure?

.box1{
  height:150px;
  background:red;

}
.box2{
  height:220px;
  background:green;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">


text:
Q: Prove that (n!+1) is not divisible by any natural number between 2 and n. I tried this question solving by mathematical induction. But no luck
Is there is any easy way to prove that?

A: Hint:   If $k|m$ and $k> 1$ then $k\not \mid m+1$.

Pf:  Do we need to prove it?  If $m = bk$ for some integer $b$ then $m+1 = bk + 1$ and $\frac {m+1}k = b + \frac 1k$ which is not an integer.

And if $2\le k \le n$ then $n! = 1*2*........ * n = \prod_{j:1\le j \le n} j$. So $k$ is between $2.... n$ then it is one of the factors of $n!$.
FORMAL ANSWER (don't read this)

  if $2\le k \le n$ then $k$ is a factor of $n! = 1*2*.....*n$.  And so $\frac {n!}k$ is an integer.  Lets call $\frac {n!}k :=M$.  Then $n! = Mk$.  So $n!+1 = Mk + 1$ and $\frac {n!+1}k = \frac {Mk+1}k = M + \frac 1k$.  But $k > 1$ so $\frac 1k$ is not an integer.  So $M + \frac 1k$ is not an integer.  So $k\not \mid n! + 1$.

Or a single-line unbelievably short proof:

 $n!$ is divisible by all natural number $2$ to $n$ and $1$ is not divisible by any.  So $n!+1$ is not divisible by any.

QED

A: I never want to say don't use induction but...  you shouldn't.
But I never want to say don't so:
BASE CASE:  $n=2$
$2! + 1=3$. and $2\not \mid 3$.
INDUCTION STEP:
If $k!+1$ is not divisible but any natural number between $2$ and $k$.
Then $(k+1)! + 1 = k!(k+1) + 1= k\cdot k! + k! + 1= k\cdot k! + (k!+1)$.  Now any natural number between $2$ and $k$ will divide* $k\cdot k!$ but will not divide $k!+1$ so it will not divide $k\cdot k! + (k!+1)$.
And  $k+1$ does divide $k!(k+1)$ but does not divide $1$.  SO $k+1$ does not divide $k!(k+1) + 1$.
So no natural number between $2$ and $k+1$ will divide $(k+1)!$.  So that is the induction step.
......
SO it can be proven by induction.  And it wasn't as hard as I thought it would be.  But it wasn't what I'd call easy.
There is a much easier and direct prove that is based on the same idea:

$n!$ is divisible by all natural numbers between $2$ and $n$ and $1$ is not.  So $n! + 1$ is not.  End of proof.  QED.


text:
Q: How to display data on hover inside doughnut chart in Angular Chart? Hi how to display data on hover inside doughnut chart using  Angular Chart
Something like this:

A: Extend the answer of Alesana from this:
How to add text inside the doughnut chart using Chart.js?
and register an additional plugin service:
Chart.pluginService.register({
  beforeTooltipDraw: function(chart) {
    if (chart.config.options.elements.center) {
        if (chart.tooltip._active && chart.tooltip._active.length > 0) {
            chart.config.options.elements.center.text =
                chart.tooltip._active[0]._view.label + ':' + chart.tooltip._data.datasets[0].data[chart.tooltip._active[0]._index];
        }
    }
  }
});

For the chart, you may also want to put:
options: {
    tooltips: { enabled: false }
}

I know that it may not be a good idea to use _view, _data, etc. Please correct this to a better way to access the label and dataset values.


text:
Q: Calculate a CRC / CRC32 hash / checksum on a binary file in Python using a buffer I've been trying to teach myself Python so I don't fully understand what I'm doing.  I'm embarrassed to say this but my question should be really easy to answer.  I want to be able to do a CRC checksums on binary files with code similar to this:
# http://upload.wikimedia.org/wikipedia/commons/7/72/Pleiades_Spitzer_big.jpg

import zlib

buffersize = 65536

with open('Pleiades_Spitzer_big.jpg', 'rb') as afile:
    buffr = afile.read(buffersize)
    while len(buffr) > 0:
        crcvalue = zlib.crc32(buffr)
        buffr = afile.read(buffersize)

print(format(crcvalue & 0xFFFFFFFF, '08x'))

The correct result should be "a509ae4b" but my code's result is "dedf5161". I think what is happening is the checksum is being calculated on either the first or last 64kb of the file instead of the whole file.
How should the code be altered so it checks the entire file without loading the entire file into memory?
As it is, the code "works" in either Python 2.x or 3.x.  If the code has to be in one or the other, I'd prefer it to be in 3.x.

A: You're currently calculating CRC of only the last chunk of the file. In order to fix this pass current crcvalue to crc32 as starting value:
import zlib

buffersize = 65536

with open('Pleiades_Spitzer_big.jpg', 'rb') as afile:
    buffr = afile.read(buffersize)
    crcvalue = 0
    while len(buffr) > 0:
        crcvalue = zlib.crc32(buffr, crcvalue)
        buffr = afile.read(buffersize)

print(format(crcvalue & 0xFFFFFFFF, '08x')) # a509ae4b

Here's the relevant part from Python docs:

If value is present, it is used as the starting value of the checksum; otherwise, a default value of 0 is used. Passing in value allows computing a running checksum over the concatenation of several inputs.

A: While the accepted answer by @niemmi is excellent and accurate, here is Python 3.8+ compatible solution which helps simplify the code a bit.

Python 3.8+
The sample below makes use of the walrus assignment operator ( := ) to keep track of the chunks being read:
import zlib

size = 1024*1024*10  # 10 MiB chunks
with open('/tmp/test.txt', 'rb') as f:
    crcval = 0
    while chunk := f.read(size):
        crcval = zlib.crc32(chunk, crcval)

print(f'{crcval & 0xFFFFFFFF:08x}')

Testing
echo "Some boring example text in a file." > /tmp/test.txt

$ crc32 /tmp/test.txt
2a30366b

Checksum value using the example code above:
2a30e66b


text:
Q: java.lang.ArrayIndexOutOfBoundsException: length=8; index=-1 Al rotar el dispositivo por segunda vez mi problema es que este error me aparece al rotar la pantalla por segunda vez, los fragments no se pierden cuando hago rotacion del dispositivo por primera vez pero al hacerlo por segunda, automaticamente me tira este error, no sé que puede estar pasando, agradecería mucho su ayuda.
Dejo el onCreate de mi Actividad
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FragmentManager.enableDebugLogging(true);

    concederPermisos();
    //preguntar si es tablet
    esTablet=getResources().getBoolean(R.bool.es_tablet);
    mBundle=new Bundle();
    mBundle.putBoolean("es_tablet",esTablet);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    //Asignacion Fragment Manager
    miFragmentManager=getFragmentManager();
    //Toast

    //Mostrando el primer fragment

    if (esTablet==false){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }else{
        //Si es una tablet de siete pulgadas bloqueará la rotación de pantalla, los únicos con este privilegio serán las de diez pulgadas.
        if (getResources().getBoolean(R.bool.es_tablet_de_7_pul)==true){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        LinearLayout.LayoutParams params = new TableRow.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f);
        findViewById(R.id.content_main).setLayoutParams(params);

    }

    if (savedInstanceState==null){
        main=new MainFragment();
        main.setArguments(mBundle);
        miFragmentManager.beginTransaction().replace(R.id.content_main, main,"fragment_main").commit();

        //dialogs
        miFragmentManager.beginTransaction().replace(R.id.alphem_container,new AlphemFragment()).commit();
    }
    //dialog salir
    salirDialog=new Dialog(this);
    salirDialog.setContentView(R.layout.dialog_salir);
    salirDialog.findViewById(R.id.salir_no).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            salirDialog.dismiss();
        }
    });
    salirDialog.findViewById(R.id.salir_si).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            salirDialog.dismiss();
            finish();
        }
    });

}

  @Override
  public void onSaveInstanceState(Bundle outState){
    super.onSaveInstanceState(outState);

    if (getResources().getBoolean(R.bool.es_tablet)==true){

        Bundle Test=outState;

        ArrayList<android.support.v4.app.Fragment> listasFragment= (ArrayList<android.support.v4.app.Fragment>) getSupportFragmentManager().getFragments();

        getFragmentManager().putFragment(outState,"fragment_main",getFragmentManager().findFragmentByTag("fragment_main"));
        getFragmentManager().putFragment(outState,"datos_fragment",getFragmentManager().findFragmentByTag("datos_fragment"));
    }

}
@Override
public void onRestoreInstanceState(Bundle inState){
    super.onRestoreInstanceState(inState);

    if (esTablet==true){
        mBundle=new Bundle();
        mBundle.putBoolean("es_tablet",esTablet);
        main = getFragmentManager().getFragment(inState,"fragment_main");

        getFragmentManager().beginTransaction().show(main);

    }
}

Y el LogCat del error

03-08 01:46:00.557 8355-8355/com.alphemsoft.education.regression
  E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.alphemsoft.education.regression, PID: 8355
  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.alphemsoft.education.regression/com.alphemsoft.education.regression.MainActivity}:
  java.lang.ArrayIndexOutOfBoundsException: length=8; index=-1
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
      at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947)
      at android.app.ActivityThread.access$900(ActivityThread.java:151)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:135)
      at android.app.ActivityThread.main(ActivityThread.java:5254)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=8; index=-1
      at java.util.ArrayList.get(ArrayList.java:310)
      at android.app.BackStackState.instantiate(BackStackRecord.java:147)
      at android.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1832)
      at android.app.Activity.onCreate(Activity.java:933)
      at android.support.v4.app.BaseFragmentActivityGingerbread.onCreate(BaseFragmentActivityGingerbread.java:54)
      at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:319)
      at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
      at com.alphemsoft.education.regression.MainActivity.onCreate(MainActivity.java:69)
      at android.app.Activity.performCreate(Activity.java:5990)
      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
      at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947)
      at android.app.ActivityThread.access$900(ActivityThread.java:151)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:135)
      at android.app.ActivityThread.main(ActivityThread.java:5254)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

La linea 69 es exactamente el super.onCreate(savedInstanceState) del onCreate, por favor, agradeceria su ayuda, ya no sé que más hacer.


text:
Q: HTML / JAVASCRIPT : Disable HTML CONTENT in contentEditable=true What I want?

I want a div what works like a textarea, I don't want to have the ability to edit things in the div, and paste images and so on just plain text.
Example

www.facebook.com
- The best example is facebook's news feed.
Why I need this way?

If you check out facebook's news feed, you well see that the area where you can write your post, expands as you write your post or hit a lots of enters.
This is the same reason why I want to use a div with contentEditable, because in textarea I can't do that.
#
PLEASE NO JQUERY only JAVASCRIPT

A: Resizable Textarea using pure JavaScript without frameworks:

        <title>ItzWarty - Untitled Document</title>

        <textarea id="resizableTA">Trololololol</textarea>

Very hackish, put it together in less than 10 minutes.  Hopefully it'll at least give you an idea.
ONLY tested on Google Chrome 5.0.308.0
Explanation of code, since i fail at commenting
1) before window.onload, the textarea of id "resizableTA" has been created and appended to document.body of DOM tree.
2) window.onload attaches an event handler, taOnInput [textarea on input].
3) textarea on input creates a dummy span, forces its width to the width of the textarea and font style to "Lucida Console", which AFAIK is the default font for textareas, copies the value of the textarea to the span's innerHTML, while replacing %0A [newline that textareas use] with  [line break]...
4) span's offsetHeight is the height of the span, which can now be used to force the height of the textarea.
Can anyone confirm that Lucida Console is the default font of textarea?  Is it Consola?  Courier New?  I assumed any fixed-width font would work.  I don't use Mac, so I dont know what fonts it shared with windows, though i think Courier New is a better choice...

A: It seems to me that the best solution to this is still to use a textarea element, and to use Javascript to resize it as needed in response to content changes.
Textarea elements do allow for manual resizing by default (and this can be controlled by the "resize" CSS property.  But sites that implement auto-expanding multi line text fields without rich formatting would primarily do so with textareas combined with styling and Javascript.

A: You don't have to use a DIV. You can still have a textarea and expand it when necessary.
Here is a jQuery plugin that does just that: http://plugins.jquery.com/project/TextAreaResizer
Here is a demo: http://www.itsavesyou.com/TextArea_Resizer_example.htm


text:
Q: How to handle EOS in Gstreamer pipeline with webrtcbin I am using GStreamer 1.18.4 using GstSharp binding. And I am using following pipeline:
filesrc name=source location=video.raw ! videoparse width=1920 height=1080 framerate=30/1 format=40 !  videoconvert ! openh264enc ! h264parse ! rtph264pay ! webrtcbin bundle-policy=max-bundle

I initialize pipeline with code:
_pipeline = (Gst.Pipeline)Gst.Parse.Launch("...");
_pipeline.MessageForward = true;
_pipeline.Bus.AddSignalWatch();
_pipeline.Bus.Message += HandleBusMessage;
_pipeline.SetState(Gst.State.Playing);
_loop.Run();
private void HandleBusMessage(object o, Gst.MessageArgs args) {
   var msg = args.Message;
   _logger.LogInformation($"Received message: {msg.Type}");
}

I need to stop the whole pipeline when filesrc read the whole file. I thought that I just need to handle the EOS message and exit the loop, but no EOS is received from the bus.
I never get EOS message type in HandleBusMessage method, when filesrc read whole file. I only get StreamStatus, Tag, StateChanged message types.
I tried set the property "message-forward" on pipeline (I also try to set this property on the webrtcbin),but no Element message type is received in the method (https://gstreamer.freedesktop.org/documentation/gstreamer/gstbin.html?gi-language=c#GstBin:message-forward).
I also tried to remove the webrtcbin from the pipeline. Then the method HandleBusMessage is called also with Element and EOS message type. So the problem must be somehow with the webrtcbin element.
How can I get information that filesrc read whole file and generated EOS?
Thanks


text:
Q: Calculating values of a column and writing them to an excel file I have an excel file with some column data. The second column contains time values in the following format: HH:MM:SS. I would like to calculate some new values, based on the values from column A, and write them to another, empty column.
Example of the excel sheet layout:
A           B        C         D
12:30:00    xxx      xxx       calculated value
00:30:00    xxx      xxx       calculated value

The values in column D would be calculated in this way (pseudo code):
for every value in column A:
   val temp = convert value in column A to minutes and divide by 30
   (e.g. 00:30 --> (0 * 60) + 30 = 30/30 = 1)

   if (temp < 24):
      cellDValue = -180 + (temp * 7,5)
   else
      temp = temp - 24
      cellDValue = temp * 7,5

So the above sheet would look like this:
A           B        C         D
12:30:00    xxx      xxx       7,5
00:30:00    xxx      xxx       -127,5

What would be the fastest way to achieve this?

A: you can retrieve the values from the dates with this code:
dim intSecond as integer
    dim intMin as integer
    dim intHour as integer
    dim intDay as integer
    dim intMonth as integer
    dim intYear as integer
dim objDate as date
objDate = now

intSecond = Second(objDate)
intMin=  Minute(objDate)
intHour = Hour(objDate)
intDay = Day(objDate)
intMonth = Month(objDate)
intYear = Year(objDate)

Copy them to another cell and to the calculations you need.


text:
Q: Change app title dynamically in UWP I'm currently building an app that starts recording the screen at some point using Windows Game DVR. That recorder takes the app name as file name when it's done recording.
I found out how to change the app title using Applicationview.GetForCurrentView(); and it does change the title of the window of my app. However, it doesn't take this title into the filename after recording.
When I record something like a Word document or my Visual Studio Project, it does show the specific name in the filename, so there must be another level where the name needs to be changed.
Anyone has an idea?

A: Based on this thread you cannot do that.
It seems that Xbox DVR gets the name of the installed app and that cannot be changed at runtime.
For changing the app title you need to first uninstall the app, modify Package.appxmanifest and then install the app.
What about a little workaround here. You know your app name when it is installed and you know where Xbox DVR saves video file recordings. You can write a file system watcher that will sense new files in that directory and rename those to your needs.


text:
Q: Android studio: thread app not returning same value as non thread app I'm working on an app that goes through all of the phone directories, and collecting all the songs.
When i run it normally it works fine, just takes about 6 seconds to go through everything, and causes the app to skip a lot of frames.
I changed it so every time a file is found, a different thread reads the metadata and saves it.
I'm also waiting for all of them in the end, because after that I'm trying to use that list.
All of a sudden several of the song are null, even though they're not initialized as such anywhere.
What can cause that? an app that works fine, but not with threads..?
the constructor that calls the search:
phoneSongsList = new Playlist();
findSongs(Environment.getExternalStorageDirectory().getAbsolutePath()); //.concat("/Music")
for (Thread thread : threads) {
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

The function that recursively looks for songs:
public void findSongs(String path) {
    File home = new File(path);
    for (final File file : home.listFiles()) {
        if (file.isDirectory())
            findSongs(path.concat("/" + file.getName()));
        else if (isAcceptableExtension(file.getName())) {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    phoneSongsList.add(fileToSong(file));
                }
            });
            t.start();
            threads.add(t);
        }
    }
}

The function that converts the file to a song object:
private Song fileToSong(File file) {
    final Album album = new Album();
    Song song = new Song();
    song.setName(file.getName().substring(0, (file.getName().length() - 4))); // remove suffix
    song.setPath(file.getPath());

    final MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
    metaRetriever.setDataSource(file.getPath());

    song.setArtists(metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
    album.setName(metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
    album.setYear(metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_YEAR));
    album.setCover(metaRetriever.getEmbeddedPicture(), context);
    song.setAlbum(album);
    song.setDuration(Long.parseLong(metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)));
    song.setGenre(metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE));

    metaRetriever.release();
    return song;
}

The Playlist.add function:
public void add(Song song) {
    add(list.size(), song);
}
public void add(int index, Song song) {
    if(song==null)
        return;
    if (index > list.size())
        index = list.size();
    if (list.contains(song))
        list.remove(song);
    list.add(index, song);
}

Even when i explicitly specify that no null objects would be added to the list, it runs fine when it saves the songs, but give a null error when trying to read.
Each time i run different songs and a different number of songs are set to null.
Please help.

A: You're dynamically trying to add new Threads to the list of threads on other threads, but reading that thread on one thread.  That means you'll finish the loop on some subset of those threads before all of them are added.  This entire approach is one big race condition.
This isn't something threads are going to speed up much, and you're doing your threading all wrong anyway.  Throw this out and just do it on a single background thread, and do not join on that thread (or you may as well do it sequentially)-  have it post back to the main thread when done.


text:
Q: How to scan join query results into a struct containing a slice of structs using sqlx Here are the tables that are relevant to this question:
lists:
                      Table "public.lists"
   Column    |  Type  | Collation | Nullable |      Default
-------------+--------+-----------+----------+-------------------
 id          | uuid   |           | not null | gen_random_uuid()
 user_id     | uuid   |           | not null |
 list_name   | text   |           | not null |
 description | text   |           | not null |
 created_at  | bigint |           | not null |
 updated_at  | bigint |           | not null |
Indexes:
    "lists_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "fk_user_id" FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
Referenced by:
    TABLE "todos" CONSTRAINT "fk_list_id" FOREIGN KEY (list_id) REFERENCES lists(id) ON DELETE SET NULL

and todos:
                      Table "public.todos"
   Column   |  Type   | Collation | Nullable |      Default
------------+---------+-----------+----------+-------------------
 id         | uuid    |           | not null | gen_random_uuid()
 list_id    | uuid    |           | not null |
 user_id    | uuid    |           | not null |
 content    | text    |           | not null |
 done       | boolean |           | not null | false
 created_at | bigint  |           | not null |
 updated_at | bigint  |           | not null |
Indexes:
    "todos_pkey" PRIMARY KEY, btree (id)
    "todos_content_key" UNIQUE CONSTRAINT, btree (content)
Foreign-key constraints:
    "fk_list_id" FOREIGN KEY (list_id) REFERENCES lists(id) ON DELETE SET NULL
    "fk_user_id" FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL

and these are the structs that I would ideally like to use:
type Todo struct {
    ID        string `db:"id"`
    ListID    string `db:"list_id"`
    UserID    string `db:"user_id"`
    Content   string `db:"content"`
    Done      bool   `db:"done"`
    CreatedAt int64  `db:"created_at"`
    UpdatedAt int64  `db:"updated_at"`
}

type ListWithTodos struct {
    ID          string `db:"id"`
    UserID      string `db:"user_id"`
    ListName    string `db:"list_name"`
    Description string `db:"description"`
    Todos       []Todo
    CreatedAt   int64  `db:"created_at"`
    UpdatedAt   int64  `db:"updated_at"`
}

What I would like to do is select a list and add all of its children todos (todos with a list_id equal to the list's id) to the field ListWithTodos.Todos. I currently have this query which returns all of the todos with the parent list attached (and I know this won't work with the struct I have):
SELECT l.*, t.* FROM lists l RIGHT JOIN todos t ON l.id=t.list_id WHERE l.id='insert uuid here';

and my go code and structs obviously don't work with the query.
What query would I use to get the results into a single struct and what sqlx functions would I use to do this?


text:
Q: (python) Can you please tell me what is the problem in the code below I just start to learn python and i have a problem:
arr = [1,3,3,3,0,1,1]
def solution(arr):
    a=[]
    for r in range(len(arr)-1):
        if arr[r] == arr[r+1]:
            a.append(r+1)
    print(a)
    for i in range(len(a)):
        k = int(a[i])
        arr[k] = -1
        arr.remove(-1)
    return arr

There's a message
IndexError: list index out of range for ''arr[k] = -1''

Can you please tell me the reason for the Error and correct it?

A: In short, you cannot modify the array shape when you have determined the indices based on the unmodified array to index into it.
Here is something that you might be looking for:
def solution(arr):
    a = []
    for r in range(len(arr) - 1):
        if arr[r] == arr[r + 1]:
            a.append(r + 1)
    print(a)
    for i in range(len(a)):
        k = int(a[i])
        arr[k] = -1

        # In the following line, you cannot modify the array length
        # when you have already computed the indices based on the unmodified array
        # arr.remove(-1)
    arr = [x for x in arr if x != -1]  # This is a better way to deal with it
    return arr

print(solution(arr=[1, 3, 3, 3, 0, 1, 1]))

A: Of course, it results in a Runtime exception. The list a stores indices. For each element v in a, you are trying to remove the value arr[v]. Doing this will reduce the size of arr by one every time. So, in the next iteration, v can be greater than the size of arr. Hence, it results in List index out of bound exception.
Your code, corrected:
arr = [1,3,3,3,0,1,1]
def solution(arr):
    a=[]
    for r in range(len(arr)-1):
        if arr[r] == arr[r+1]:
            a.append(r+1)
    print(a)
    c = 0
    for i in range(len(a)):
        k = int(a[i])
        arr[k - c] = -1
        arr.remove(-1)
        c += 1
    return arr

print(solution(arr))

It looks like you are trying to remove consecutive duplicates from the list. This can be easily solved using the following code.
def remove_duplicates(arr):
    stack = [arr[0]]
    for i in range(1, len(arr)):
        if stack[-1] != arr[i]:
            stack.append(arr[i])
    return stack

print(remove_duplicates([1,3,3,3,0,1,1]))

A: You don't want to mess with the original list. Otherwise you'll run into index errors. Index errors mean the item you were looking for in the list no longer exists. Most likely this line was the culprit arr.remove(-1).
arr = [1,3,3,3,0,1,1]

solution = []
for i, v in enumerate(arr):
    if i == 0 or v != arr[i -1]:
        solution.append(v)

print(solution)

This should get you what you are after. enumerate tells you want index you are at when looping through the list. More information can be found here: https://realpython.com/python-enumerate/

A: Well, you've probably already know what wrong happened here, removing the element inside the loop:
for i in range(len(a)):
    k = int(a[i])
    arr[k] = -1
    arr.remove(-1)

You can fix the whole thing just changing the line to this list filter+lambda implementation, well, not inside the loop, but after the completion of loop iterations, just like follows:
for i in range(len(a)):
    k = int(a[i])
    arr[k] = -1
arr = list(filter(lambda x: x != -1, arr))

And you'll get what you want just from your solution!