text:
Q: How to set HELM_CACHE_HOME env var (or exclude caching) when running Helm template command? I have a specific request of running Helm template command in environment with filesystem access read-only on the regular location where Helm cache is stored (I'm executing this command inside AWS Lambda).
An error that I get is:
Error: mkdir .cache: read-only file system

Now, to overcome this problem, my idea is to:

*

*either disable cache when running specific command

*point HELM_CACHE_HOME to location which is not read-only (mounted location from EFS file system)

Unfortunately, I was unable to find a way to disable a cache and following command doesn't work (even when running it locally, without any lambda environment):
mkdir -p /tmp/helm/.cache/helm
HELM_CACHE_HOME=/tmp/helm/.cache/helm helm template elasticsearch elastic/elasticsearch --dry-run

ls -la /tmp/helm/.cache/helm
total 0

Any way to do this?
Thanks

A: Eventually, I've figured out that I've used incorrect environment variable.
For Helm 3, correct variable is:
XDG_CACHE_HOME

Reference: https://helm.sh/docs/faq/#xdg-base-directory-support
However, even if this works, docs say that HELM_CACHE_HOME should also work (which is not the case).


text:
Q: Calendar with selectable range of dates I'm searching for a library that provodes a calendar that allows me to select single dates and whole ranges of dates that I can use on my app.
Is there any iOS library that provide such features?

A: Use EKEventStore it allows a lot of calendar access including selection of specific date ranges. I posted some sample here: Using EventKit with swift on OSX

redpajama_set_name: RedPajamaStackExchange


text:
Q: Printing 100 to 200, with three exceptions? I am trying to write a  program that prints the numbers from 100 to 200, with three exceptions:
If the number is a multiple of 3, the string "yes" should be returned instead of the number.
If the number is a multiple of 4, the string "yes and yes" instead of the number should be returned.
If the number is a multiple of both 3 and 4, the string "yes, yes and yes" instead of the number.
I am new to JavaScript so I try to do this step by step.
I wrote this code to print the numbers from 100 to 200:
function hundredTwoHundred() {
  result = [];
  for (let i = 100; i <= 200; i++) {
  result.push(i);
}
  return result;
}

console.log(hundredTwoHundred());

Then I tried to use else/if for the exceptions:
function hundredTwoHundred() {
  result = [];
  for (let i = 100; i <= 200; i++) {
    if (i % 3 == 0) {
    console.log("yes");
  } else if (i % 4 == 0) {
    console.log("yes and yes")
  } else if (i % 3 == 0 && i % 4 == 0) {
    console.log("yes, yes and yes");
  } else {
    result.push(i)
  }
}
  return result;
}

console.log(hundredTwoHundred());

The code of course, does not work. I have tried moving result.push(i) around, but I don't want to just mindlessly move things around, without knowing the reasoning behind it.
How do I use conditional operators to find these exceptions? What am I doing wrong?
Thank you.

A: You need to test if the number is (divisible by 3 and divisible by 4) before checking whether it's (individually) divisible by 3 or 4, otherwise the first condition if (i % 3 == 0) will evaluate to true and you'll get yes rather than yes, yes and yes. You should also push to the result in the conditionals rather than console.logging in the conditionals, since you want to create an array of numbers and yeses and then console.log the whole constructed array afterwards.
Also make sure to declare the result with const (or var, for ES5) - it's not good to implicitly create global variables.
Also, although it doesn't matter in this case, when comparing, it's good to rely on === by default rather than == - best to only use == when you deliberately want to rely on implicit type coercion, which can result in confusing behavior.

function hundredTwoHundred() {
  const result = [];
  for (let i = 100; i <= 200; i++) {
    if (i % 3 === 0 && i % 4 === 0) {
      result.push("yes, yes and yes");
    } else if (i % 3 === 0) {
      result.push("yes");
    } else if (i % 4 === 0) {
      result.push("yes and yes")
    } else {
      result.push(i)
    }
  }
  return result;
}

console.log(hundredTwoHundred());

A: If a number is a multiple of 3 and 4, then it is a multiple of 12. I'd also use a switch statement, so you can rewrite as follow:
for (let i = 100; i <= 200; i = i + 1) {
  switch (0) {
    case i % 12: console.log('yes, yes and yes'); break;
    case i % 4:  console.log('yes and yes'); break;
    case i % 3:  console.log('yes'); break;
    default:     console.log(i);
  }
}

If you want it as an array:
// Fill an array with numbers from 100 to 200
const arr = Array(101).fill().map((_, i) => i + 100);

// Map it to numbers and strings
const hundredTwoHundred = arr.map(i => {
  switch (0) {
    case i % 12: return 'yes, yes and yes';
    case i % 4:  return 'yes and yes';
    case i % 3:  return 'yes';
    default:     return i
  }
});

// Print it:
console.log(hundredTwoHundred);

A: When you have a complex set of conditions you need to be careful with the order in which you evaluate them.
function logExceptions(start, end) {
    var divisibleByThree, divisibleByFour;
    for (var i = start; i <= end; ++i) {
        divisibleByThree = i % 3 == 0;
        divisibleByFour = i % 4 == 0;
        if (divisibleByThree && divisibleByFour) {
            console.log("yes, yes and yes");
        }
        else if (divisibleByThree) {
            console.log("yes");
        }
        else if (divisibleByFour) {
            console.log("yes and yes");
        }
        else {
            console.log(i);
        }
    }
}
logExceptions(100, 200);

If you want to save the result in an array and only later print it:
function logExceptions(start, end) {
    var result = [];
    var divisibleByThree, divisibleByFour;
    for (var i = start; i <= end; ++i) {
        divisibleByThree = i % 3 == 0;
        divisibleByFour = i % 4 == 0;
        if (divisibleByThree && divisibleByFour) {
            result.push("yes, yes and yes");
        }
        else if (divisibleByThree) {
            result.push("yes");
        }
        else if (divisibleByFour) {
            result.push("yes and yes");
        }
        else {
            result.push(i);
        }
    }
    return result;
}
console.log(logExceptions(100, 200).toString());


text:
Q: Correctly output dictionary to a file (fimi format) python I have a text file containing string values separated by space "  ". I need to set each of those string values to be equal to a some number.
So far I have done a reading from the file to a dictionary where each unique key corresponds to a value number.
import collections

with open('test.txt', 'r') as f:
     c = collections.Counter(f.read().split())

newvalue = 0
for key, value in c.iteritems():
    newvalue +=1
        c[key] =  newvalue
    print key, newvalue

My problem is now that I don't know how to write the output in another file, keeping this structure:
my text file:

*

*computer phone library desk book

*book yard spring phone

*book spring

desired output file:

*

*1 2 3 4 5

*5 6 7 2

*5 7

Can someone please help me?

A: A few problems:

*

*Counter objects do not have an iteritems method.

*Indentation.

*Splitting the whole file at once produces a single list, destroying the desired layout.

Here is a working sample that does what you want. The biggest change is to preserve the layout of the input file by using nested lists.
import collections

with open('test.txt', 'r') as f: # open the file
    lines = [] # initialize a list
    for line in f: # for each line in the file,
        # add a list of that line's words to the initialized list
        lines.append(line.split())
    # save a Counter out of the concatenation of those nested lists
    c = collections.Counter(sum(lines, []))

with open('testout.txt', 'w') as output: # start a file
    for line in lines: # for each list in the list we made,
        result = [] # initialize a list
        for word in line: # for each word in the nested list,
            # add that word's count to the initialized list
            result.append(str(c[word]))
        # write a string representation of the list to the file
        output.write(' '.join(result) + '\n')


text:
Q: How to create node project using npm init? Getting stuck at version I am a newbie of nodejs, I am trying to a create node js project using npm init command but it stops at version. Can someone please help?
Below is error:

Press ^C at any time to quit.
  name: (node_init)
  version: (1.0.0)

A: It's an error in the newest version. You can use npm init -f as a workaround until it is fixed.

A: You could also make use of
    npm init --yes
or
    npm init -y
and npm initializes a project with the default package.json values, or
npm init -f

using --force
Reference: https://docs.npmjs.com/cli/init


text: Q: Is my ER Diagram correct according this business rules? Tiny Hospital keeps information on patients and hospital rooms. The system assigns each patient a patient ID number. In addition, the patient's last name, first name, date of birth, and date of admission are recorded. Also, every patient is seen by a Physician who develops a treatment plan for the patient. Each Physician may see many patients. Some patients are resident patients (they spend at least one night in the hospital) and others are outpatients (they are treated and released). A Check back date is recorded for all out patients, and a Date of discharge is recorded for all resident patients. Resident patients are assigned to a room. Each room is identified by a room number.   The system also stores the room type (private or semiprivate), and room fee. Over time, each room will have many resident patients that stay in it. Each resident patient will stay in only one room. Every room must have had a patient, and every resident patient must have a room.


text:
Q: Using java in JSP So I wanted to create new Country object in jsp file. When I do:
Country test = new Country("Poland");

In normal file.java it works all ok. But when I try to do this in jsp file I have errors:
An error occurred at line: 17 in the jsp file: /index.jsp
Country cannot be resolved to a type
14:

15:
Date=<%= new Date() %>
16:
17: <% Country test = new Country("Poland"); %>
18:

19:
20:

Stacktrace:
    at org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
    at org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:366)
    at org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:468)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:378)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:646)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Here is my all jsp file:
<%@page import="java.util.Date"%>
<%@page import="pl.marek.reader.*" %>
<%@page import="pl.marek.preparer.*" %>
<%@page import="pl.marek.country.*" %>
<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Hello</title>

Date=<%= new Date() %>

<% Country test = new Country("Poland"); %>

What I'm doing wrong? By the way, I'm totally new in doing java dynamic pages, I just started read some tutorials today.
BTW2. I'm using maven. It's maven project, where I chosen "maven-archetype-webapp".


text:
Q: Write to specific row in CSV according to query Python I am trying to lookup a value in my csv file and if I find it, write back a value at the end of its row.
For example, if the csv looks like this:
 #   A  B
111  1
112  0
113  0
114  1

and I lookup 111 and want to write 0 in the first empty cell in its row, how can I do it?

A: There is no way to insert data in the middle of a file. Writing to the middle of a file will overwrite the data at that position. Instead:

*

*open the file in read mode

*read all the data in the file

*close the file

*reopen the file in write mode

*write the first few lines

*write your extra data

*write the rest of the original data

an example:
with open('test.csv') as f:
l = f.readlines()

l[4] += '0'
with open('test2.csv', 'w') as f:
    f.writelines(l)

A: with open('text.csv', 'r') as f:
    rows = [x.split() for x in f]
with open('text_1.csv', 'w') as f:
    for row in rows:
        f.write(row[0] + " " + row[1])
        if row[0] == '111': # or you can check for multiple values here.
            f.write("0")
        f.write("\n")

A: This will let you open, read and write to the file within a single context manager in one shot.
search_term = '112' # This is what you are looking
                    # for at the start of the lines.
##-------------------------------------------------------##
# Define separator
sep = '\t' # Use '\t' (TAB) or " " (SPACE)
val = 0 # This is the value you want to insert
        # at the end of the target line.
##-------------------------------------------------------##
write_to_file = False # Set this to True when
                      # you want to write to the file.

##-------------------------------------------------------##
with open("dummy.csv","r+") as f:
    content = f.readlines()
    for i,line in enumerate(content):
        if line.startswith(search_term):
            line = line.strip() + '{}{}\n'.format(sep,val)
            content[i] = line
    if write_to_file:
        f.writelines(content)

print(''.join(content))


text:
Q: How to prevent the default action of urllib2.Request class from capitalizing the header in python 2.7? How to prevent the default action of urllib2.Request class from capitalizing the header in python 2.7.When I create a urllib2.Request class instance and pass headers by default in does capitalization of headers passed, instead I want headers to be in uppercase when i do a request.How can i do the same. Webservice where i do a request accepts headers in capitals(example HTTP_REQUEST_VAL).
Thanks in advance

A: HTTP header names are case-insensitive as per the spec, but if your webservice seems to have problems with that, you'll have to resort to some hacks, as the title casing is hardwired into urllib2. There's no getting around it unless you want to subclass half of the library just to get rid of it.
An alternative would be to subclass str and use SafeString('foo') instead of 'foo' for the header name, but that seems like a bad hack:
class SafeString(str):
    def title(self):
        return self

    def capitalize(self):
        return self

A better solution would be to use Requests, which doesn't modify your headers:
import requests

requests.get('http://example.com', headers={
    'EXAMPLE-header': 'foo'
})

A: Override the add_adder functionality
import urllib.request

class CustomHttp(urllib.request.Request):
    def add_header(self, key, value):
        self.headers[key] = value

req = CustomHttp(url, data=data, headers=headers, method="POST")

and continue as it is.


text:
Q: Trouble with "trivial" example of a semi-simple Lie algebra If the radical of a Lie algebra is zero, we call it semi-simple. In the lecture notes that I'm following its stated that for any arbitrary Lie algebra (over a field with characteristic zero and finite dimensional) $\mathfrak{g}$ we have, $\mathfrak{h}:=\mathfrak{g}/\mathrm{rad}(\mathfrak{g})$ semi-simple. I have trouble seeing why.
I need to show that $\mathrm{rad}(\mathfrak{h})=0$. I think we can use the fact that if $\mathfrak{I}$ is a solvable ideal of $\mathfrak{g}$ such that $\mathfrak{g}/\mathfrak{I}$ is solvable, then $\mathfrak{g}$ is solvable, but I'm not really sure how...

A: $\mathfrak{g}$ is semisimple if it has no non-zero abelian ideals.
Let $\pi: \mathfrak{g} \rightarrow \mathfrak{h}$ be the quotient map.
if $\mathfrak{h}$ is not semisimple, then $(0)\subsetneq rad(\mathfrak{h})$
therefore $\pi^{-1}(0) = rad(\mathfrak{g}) \subsetneq \pi^{-1}(rad(\mathfrak{h}))$
But $\pi^{-1}(rad(\mathfrak{h}))$ is an abelian ideal, this is a contradiction of the maximality of $rad(\mathfrak{g}).$

A: HINT:
Suppose for contradiction that $\mathfrak{h}$ is not semi-simple. Write down exactly what this means.
You can now utilize a particular fact, and show that $\mathfrak{g}$ would have to therefore have a non-zero solvable ideal. This gives a contradiction.


text:
Q: Dynamic Page according to React-Redux state not updating rendered data I want to build a one-page login system which renders different pages according to the state I set in the React-Redux store. The render() {} function isn't updating when the state of the store updates.
App.js
import React from 'react'

import store from './redux/store'
import { Provider } from 'react-redux'

// Route to Renderer.js below
import Renderer from './Renderer'

class App extends React.Component {
    render() {
        return (
            <Provider store={ store }>
                <Renderer page={store.getState().page} />
            </Provider>
        )
    }
}

export default App;

Renderer.js
import React, { Component } from 'react'

// Routes to my pages I plan to render
import Login from './routes/Login'
import About from './routes/About'
import Register from './routes/Register'

class Renderer extends Component {
    render() {
        let page = this.props.page
        let returned

        switch (page) {
            case 'About':
                returned = <About />
                break
            case 'Login':
                returned = <Login />
                break
            case 'Register':
                returned = <Register />
                break
            default:
                returned = <About />
        }

        return returned
    }
}

export default Renderer

I have a component linked to a Redux Action which changed the state of the page field. This isn't shown for simplicity sake. The change in the state is confirmed because the Redux Development Tools tells me that the state changed when I dispatch the actions to change the page Redux state. When I change the Redux state of the page field, the rendered page doesn't update and stays at the default page.

A: Instead of passing page as an implicit prop to Renderer, use react-redux connect in order to pass this prop to the component using a mapStateToProps function:
Renderer.js
import React, { Component } from 'react'
import {connect} from 'react-redux'

// Routes to my pages I plan to render
import Login from './routes/Login'
import About from './routes/About'
import Register from './routes/Register'

class Renderer extends Component {
    render() {
        let page = this.props.page
        let returned

        switch (page) {
            case 'About':
                returned = <About />
                break
            case 'Login':
                returned = <Login />
                break
            case 'Register':
                returned = <Register />
                break
            default:
                returned = <About />
        }

        return returned
    }
}

const mapStateToProps = (state)=>({
  page: state.page
})

export default connect(mapStateToProps)(Renderer)

App.js
import React from 'react'

import store from './redux/store'
import { Provider } from 'react-redux'

// Route to Renderer.js below
import Renderer from './Renderer'

class App extends React.Component {
    render() {
        return (
            <Provider store={ store }>
              // remove the page prop here
                <Renderer />
            </Provider>
        )
    }
}

export default App;

By passing the page prop like this:
page={store.getState().page} your Renderer component doesn't actually subscribe to store changes, so it will always return the initial page value.
The react-redux connect wrapper takes care of this subscription to the store - so your component will get an updated page value from the Provider on each store update.


text:
Q: Need help understand logic behind concocurrent of goroutine ,select and channel I try to understand logic behind concurrency of goroutine ,select and channel. The sample code is below. The base code is from tour go. I add some Printf to help me understand better.
package main
import "fmt"
func fibonacci(c, quit chan int) {
    x, y := 0, 1
    for {
        select {
        case c <- x:
            fmt.Printf("(%v, %v)\n", x ,y)
            x, y = y, x+y
            fmt.Printf("(%v, %v)\n", x ,y)
        case <-quit:
            fmt.Println("quit")
            return
        }
    }
}
func main() {
    c := make(chan int)
    quit := make(chan int)
    go func() {
        for i := 0; i < 4; i++ {
            fmt.Println(<-c)
            fmt.Printf("%v from main\n",i)
        }
        quit <- 0
    }()
    fibonacci(c, quit)
}

Output is
0
0 from main
(0, 1)
(1, 1)
(1, 1)
(1, 2)
1
1 from main
1
2 from main
(1, 2)
(2, 3)
(2, 3)
(3, 5)
2
3 from main
quit

There are concurrency behind goroutine and channel operation. My question is why the output is not
0
0 from main
(0, 1)
(1, 1)
1
1 from main
(1, 1)
(1, 2)
1
2 from main
(1, 2)
(2, 3)
2
3 from main
(2, 3)
(3, 5)
quit

A: It might clarify things to rewrite the body of the for loop in the goroutine slightly:
x := <-c
// block until a value has been read, then continue
fmt.Println(x)
fmt.Printf("%v from main\n",i)

And similarly the body of the select loop in fibonacci() is effectively:
c <- x
// block until a value has been written, then continue
fmt.Printf("(%v, %v)\n", x ,y)
x, y = y, x+y
fmt.Printf("(%v, %v)\n", x ,y)

In both cases you have a guarantee that the second print statement will print after the first.
When you run the program, say the goroutine starts immediately.  It gets up to this read, but there is no value in the channel, so it blocks.  Then the main program calls fibonacci().  It gets to the select statement.  There is a reader for the channel c, so it sends the number x there.
Once this has happened both the goroutine and the main program are free to go.  The select statement has triggered one of its branches and sent its value; the read has completed.  Both goroutines are free to run, and can do so in any order (so long as each executes its own statements in order).  You'll eventually reach a point where either the goroutine is blocked on the read or fibonacci() is blocked on the select, and once both catch up to each other, both will be free to execute again.
The order you propose would require the reader to "wake up" before the writer did, but nothing in Go requires this, and indeed on a multi-core system both can be running at the same time.


text:
Q: Use of PHP built-in ltrim() to remove a single character Is there a simple way to use ltrim() to remove a single instance of a match instead of all matches?
I'm looping through array of strings and I'd like to remove the first, and only first, match (vowels in this case):
ltrim($value, "aeiouyAEIOUY");

With default behavior the string aardvark or Aardvark would be trimmed to be "rdvark". I'd like result to be "ardvark".
I'm not bound to ltrim by any means but it seemed the closest built-in PHP function. It would be nice of ltrim and rtrim had an optional parameter "limit", just saying... :)

A: Just use preg replace it has a limit option
eg
$value = preg_replace('/^[aeiouy]/i', '', $value, 1);

A: Regular expressions is probably overkill, but:
$value = preg_replace('/^[aeiouy]/i', '', $value);

Note the i makes it case-insensitive.

A: You can't use ltrim to do this for the reasons you say, nor can you use str_replace (which also has no limit).  I think it's easiest just to use a regex:
$value = preg_replace('/^[aeiouy]/i', '', $value);

However if you really don't want to do that, you can use a substring, but you would have to check the position of any of those strings in the string in a loop as there is no php function that does such a check that I know of.

A: You can use the preg_replace function:
<?php
    $value = preg_replace('/^[aeiouy]/i', '', $value);
?>

A: There are several way you can go about doing what you are looking to do.
Perhaps most straightforward would be a regular expression replacement like this:
$pattern = '/^[aeiouy]{1}/i';
$result = preg_replace($pattern, '', $original_string);

A: This is probably the most efficient way (so ignore my regular expressions answer):
if (strpos('aeiouyAEIOUY', $value[0]) !== false) $value = substr($value, 1);

Or,
if (stripos('aeiouy', $value[0]) !== false) $value = substr($value, 1);


text:
Q: Probability that notes are in the same scale What is the probability that a random sequence of notes (on the 12-note chromatic scale) of length n is in the same major scale?
Quite some time ago, I came across a song written by converting pi to base-12. (The song didn't go on forever, obviously, but it was really cool.) The guy who wrote the song claimed that pi is a "musical number".
I wanted to make it a project to figure out whether pi is truly a musical number. That is, if pi in base-12 begins with a string of digits that, when converted to musical notes, stay in the same scale longer than statistically expected.
This is a big topic depending on what types of scale(s) one could choose and what key transitions would be allowable, but I thought major would be a good place to start.
Haven't gotten very far mathematically, mainly because I can't figure out exactly what to do or whether this is an easy or difficult problem.
Edit: Since I saw this in the comments—which scale is not specified in advance. So you have the notes, and then you see if they fit ANY scale.

A: Having run a simulation, I am finding an average run of $4.69086$ notes all able to be said to stay in the same major key having run over 10 million trials... with a standard deviation of around $2.327$.  That said, the initial string of digits of $\pi$ in base 12 is not significantly more than the average.
Here is my javascript code.  Note, I use a few custom methods for looping over objects and cloning and removing.  It should be clear what they do
//Generate the scales
majorscale = [0,2,4,5,7,9,11];
majorscales = [];
for (i=0; i<12;i++){cur = [];
  majorscale.$each(function(i){cur.push((i+1)%12)});
  majorscale = cur; majorscales.push(cur)}

//Define a function to generate a random song, length 25 is probably fine
generateSong = function(){song = []; for(i=0;i<25; i++){song.push(Math.floor(Math.random()*12))};
  return song}

//Define a function to find the length of a run in the same key
testLength = function(song,dbug){if (dbug){console.log(song)};
  //Scales not yet disqualified stored in remainingScales
  remainingScales = majorscales.$clone();
  len = 0;
  //Loop until all scales disqualified
  while(remainingScales.length){
    clone = remainingScales.$clone();
    if(dbug){console.log(song[len]);
      console.table(clone)}
    remainingScales.$each(function(scale){if(!scale.contains(song[len])){
      //If current note in song does not appear in a remaining scale, disqualify it
      //modify the clone so as to not mess up where we are in the loop and skip a scale
      clone.$remove(scale)}});
    remainingScales = clone;
    len=len+1}
  return len-1} //Off by one

//Run simulation
tot=0; for(i=0; i<10000000; i++){tot = tot + testLength(generateSong())};
console.log("Average: " + (tot/10000000))
tot2=0; for(i=0; i<10000000; i++){tot2 = tot2 + (testLength(generateSong())-tot/10000000)**2};
console.log("Std dev: " + Math.sqrt(tot2/10000000))

A: Number the 12 notes, starting from Middle C = $0$, $(0,1,2,3,4,5,6,7,8,9,10,11)$, and consider mod 12. Then the notes in C Major are $(0,2,4,5,7,9,11)$, D Major are $(2,4,6,7,9,11,1)$, etc for all 12 Major Scales.
Represent the notes in each scale by a vector of length 12 with $1$s and $0$s. Where the $i$th value is $1$ if note $i-1$ is contained in that scale and $0$ otherwise. Eg, C Major has the representation $(1,0,1,0,1,1,0,1,0,1,0,1)$.
Consider the bijection $(0,1,2,3,4,5,6,7,8,9,10,11) \to (5,0,7,2,9,4,11,6,1,8,3,10)$. This sends all 12 Major scales to a representation where the $1s$ and $0s$ are consecutive (allowing wrapping at the ends). Eg, C Major has the transformed representation $(1,1,1,1,1,1,1,0,0,0,0,0)$, C Sharp Major has the transformed representation $(1,1,0,0,0,0,0,1,1,1,1,1)$.
Therefore the probability that a set of $n$ notes are all in the same major scale is then equal to the probability that $n$ numbers selected with replacement from the numbers 1 to 12 have a consecutive gap of at least 5 numbers, allowing wrapping at the ends.

To find this probability we use Markov Chains. WLOG, let the first note played be Middle C, and we enter the state 1, with representation $(1,0,0,0,0,0,0,0,0,0,0,0)$ indicating that note 0 has been hit and no other notes have been hit. At the next note we either stay in this state with probability 1/12, or move to another state where a different note is hit, each with probability 1/12. With each note we continue to either stand in the same state, with probability of the sum of that state's representation / 12, or move to another state by hitting a new note. If ever we reach a state where there is not a sequence of 5 consecutive $0$'s we instead go to the absorbing state of $(1,1,1,1,1,1,1,1,1,1,1,1)$. There are 256 valid states. Denote the $256\times256$ matrix of transition probabilities as $T$. The probability of hitting the absorbing state on the nth note is the vector $(1,0,0,\ldots) \times T^{n-1}$. (Recall that we are assuming the first note hit is Middle C)
The probabilities of hitting the absorbing state on the nth note and by at least the nth note are (rounded to 3 decimal places, code to calculate is below).

n
P(X=n)
P(X <= n)

1
0.000
0.000

2
0.000
0.000

3
0.139
0.139

4
0.226
0.365

5
0.201
0.565

6
0.150
0.715

7
0.103
0.818

8
0.068
0.886

9
0.044
0.930

10
0.027
0.957

11
0.017
0.974

12
0.010
0.984

13
0.006
0.991

14
0.004
0.994

15
0.002
0.997

Note that this is the time to hit a note that is not in the major key, so we must subtract 1 to find the number of notes that can be played within the major key.
The mean number of notes to hit the absorbing state is $5.690909$. Subtracting 1 from this gives $4.690909$ notes before hitting a note which is not in the major key. This is in excellent agreement with @JMoravitz' simulation

R Code:
library(tidyverse)
# Construct list of scales and show bijection works
CMajor = c(0,2,4,5,7,9,11)
majors = matrix(0,nrow=12,ncol=12)
for(i in 0:11) {
  for(j in 0:11) {
    if(j %in% ((CMajor+i)%%12)) {
      majors[i+1,j+1] <- 1
    }
  }
}
perm_mat <- matrix(data = c(
  0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
  0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
  0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
  1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
  0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
  0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0),
  nrow = 12, ncol = 12, byrow = TRUE)
permuted_maj <- majors %*% perm_mat
print(permuted_maj)
print(matrix(1:12, nrow = 1,ncol = 12) %*% perm_mat)

# construct a list of valid states ------------------------
# 12 x T will be the absorbing state.
# Any time there is no longer a string of 5+
# Falses, it will go to the absorbing state,
# WLOG, let the first hit strike position 1

# Create the list of states and simplify it
states <- expand.grid(
  x1 = c(T, F), x2 = c(T, F), x3 = c(T, F), x4 = c(T, F),
  x5 = c(T, F), x6 = c(T, F), x7 = c(T, F), x8 = c(T, F),
  x9 = c(T, F), x10 = c(T, F), x11 = c(T, F), x12 = c(T, F))
states <- states %>%
  subset(x1 == T)
states$rowsum <- rowSums(states)
states <- states %>%
  filter((rowsum < 8)|(rowsum == 12))
states <- as.matrix(states)
for(i in nrow(states):2) {
  drop <- TRUE
  for(j in 1:12) {
    if(sum(states[i,(((j:(j+4)%%12)+1))]) == 0) {
      drop <- FALSE
    }
  }
  if(drop == TRUE) {
    states <- states[-c(i),]
  }
}
states <- states[order(
  states[, 13],
  states[, 1], states[, 2], states[, 3], states[, 4],
  states[, 5], states[, 6], states[, 7], states[, 8],
  states[, 9], states[, 10], states[, 11], states[, 12]), ]
print(head(states))
print(tail(states))

# construction transition matrix --------------------------------
transition <- matrix(data = 0, nrow = 256, ncol = 256)
for(i in 1:nrow(transition)) {
  rowcount <- states[i,13]
  transition[i,i] <- states[i,13]/12
  for(j in 1:nrow(transition)) {
    if(i == j) next
    if((states[i,13]+1) == states[j,13]) {
      if(sum(xor(states[i,c(1:12)],states[j,c(1:12)]))==1) {
        rowcount <- rowcount + 1
        transition[i,j] <- 1/12
      }
    }
    if(i != 256) transition[i,256] <- (12-rowcount)/12
  }
}
# Calculate probabilities --------------------------------------
probs <- matrix(data = c(1,rep(0,255)),nrow = 1, ncol = 256) %*%
  transition
cum_hits <- c(0,probs[256])
for(i in 1:50) {
  probs <- probs %*% transition
  cum_hits <- c(cum_hits,probs[256])
}
hits <- rep(0,length(cum_hits))
for(i in 2:length(hits)) {
  hits[i] <- cum_hits[i]-cum_hits[i-1]
}
print(round(cum_hits,3))
print(round(hits,3))
print(sum(hits*1:length(hits)))


text:
Q: How to right-click to paste in mcedit On a bash terminal I can right-click to paste to vim or nano, but mcedit does not receive my clipboard data on right-click.
How to right-click to paste in mcedit?

A: I found my own way. I'm using bash terminal on Windows, on title bar there's an icon on left side, clicking on it shows a menu.
Copy to system clipboard: menu >> edit >> copy
Paste to mcedit: menu >> edit >> paste

A: I found my own way. I'm using bash terminal on Windows, on title bar there's an icon on left side, clicking on it shows a menu.


text:
Q: Delete attribute from SQLAlchemy model object I'm trying to delete an attribute from model object that is created on the go, but there seems to be some problem doing so. So, far I've searched through every place including SQLAlchemy documentation and some of its code to find a potential fix but unable to find one.
Below code works fine on python classes but not with a class inherited from declarative_base
    for row in data:
        model_obj = DBEngine.models.User()
        [setattr(model_obj, key, value) for key, value in row.items()]

        # below line doesn't work as expected, instead of deleting the
        # attribute it just sets the value of attribute to None
        delattr(model_obj, 'localedit')

        session.add(model_obj)

User model
Base = declarative_base()

class User(Base):
    __tablename__ = 'user'

    id        = Column('id', Integer, primary_key=True)
    localedit = Column('localedit', String,  default="0000-00-00 00:00:00")

I've also tried deleting the attribute using del but it's doing the same job as delattr, I guess both del and delattr calling the same code under the hood.
I'm totally stumped on this problem and couldn't come up with anything.
Any help would be appreciated, Thanks.

A: So this was expected, as SQLAlchemy ORM mapped objects don't support this particular state for an attribute, that is, attribute doesn't exist and would raise AttributeError. for an ORM mapped class, a mapped attribute always defaults to None and/or empty collection. there's a little bit of an introduction to this here: https://docs.sqlalchemy.org/en/14/tutorial/orm_data_manipulation.html#instances-of-classes-represent-rows
For this particular problem, you can define your column as
localedit = Column('localedit', String,  FetchedValue())

FetchedValue is used when the database is configured to provide some automatic default for a column. So, in this case you only want to ignore the column this would work like a charm. Updated model would look something like:
Base = declarative_base()

class User(Base):
    __tablename__ = 'user'

    id        = Column('id', Integer, primary_key=True)
    localedit = Column('localedit', String,  FetchedValue())


text:
Q: Set multiple state values with React useState hook I would like to set multiple state values with React useState hook, so that I can I update them separately with useEffect hook. I have the following code:
import React, { useState } from "react";

const initialValues = {
  phone: "",
  email: ""
};

const App = () => {
  const [order, setOrder] = useState("");
  const [paid, setPaid] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(initialValues);

  return (
    <div className="App">
    </div>
  );
};

export default App;

But when I inspect the App with React DevTools, I see multiple "State" values for my hook, instead of "order", "paid", "submitting" etc.
Here is the link to my codesandbox.
Where is my mistake? How can I set multiple state values to update them separately later on?

A: There is nothing wrong with your solution. The name you give to those states is only local to your component when you destructure the array that useState returns. React does not know about the name you give to those elements in the array that useState returns. Don't worry about the generic name that shows up in dev-tools, just try your solution and you'll see it works.
For something that shows up in dev-tools, you could use useDebugValue.

A: You can make one state with useState hook and put every value there like this.
import React, { useState } from "react";

const initialValues = {
  phone: "",
  email: ""
};

const App = () => {
  const [state, setState] = useState({
     order:'',
     paid: false,
     submitting: false,
     loading: false,
     data: initialValues
  });
  // example of setting this kind of state
  const sampleChanger = () => {
     setState({...state, paid: true, order: 'sample'});
  }
// etc...

A: You haven't made a mistake. If you want to use separate hooks like this, this is how they will appear in React DevTools. If you want to have name label associated with each hook, check out this StackOverflow answer:
Is there any way to see names of 'fields' in React multiple state with React DevTools when using 'useState' hooks


text:
Q: PHP - Cannot start even the most basic session Here is my code:
<?php
session_start();

No other includes, spaces or anything.  The entire file has two lines.
The output I get:

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at C:\xampp\htdocs\webpage\test.php:1) in C:\xampp\htdocs\webpage\test.php on line 2
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\webpage\test.php:1) in C:\xampp\htdocs\webpage\test.php on line 2

I am using Xampp.  Any ideas?
EDIT:  From php.ini
session.save_handler=files
session.save_path="C:\xampp\tmp" (which exists and is writable by everyone)

A: As per my comment (asking what the encoding was), it's an encoding issue (as per what you said also).
If UTF-8 is the format you must use, then you need to save that file without the BOM (byte order mark).
It counts as output.
More on that can be found here:

*

*https://en.wikipedia.org/wiki/Byte_order_mark
Read the following on Stack in regards to the differences between with and without BOM:

*

*What's different between UTF-8 and UTF-8 without BOM?

"@Fred it seems it was encoding. Weird thing is I am am using PHPStorm. Shouldn;t the encoding always be UTF8? – Jacques"

Not always. Certain applications require a UTF-8 format be used (databases, accents on characters, etc.). You can use any format you want, just as long as it works for the way it is to be used.
If you don't need to use sessions, then don't add session_start();.
Here is an article on the W3C website that you can read:

*

*http://www.w3.org/International/questions/qa-choosing-encodings
and one here on Stack:

*

*Is there any reason not to use UTF-8, 16, etc. for everything?
and if you have time:

*

*https://wordtothewise.com/2010/03/which-is-better-utf-8-or-iso/
You can further your research by using "why should I use utf-8?" as keywords in your favorite search engine.

A: Check either session was started or not.
Recommended way for versions of PHP >= 5.4.0
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

Source: http://www.php.net/manual/en/function.session-status.php
For versions of PHP < 5.4.0
if(session_id() == '') {
    session_start();
}

A: Add a line after the opening PHP tag:
<?php

ob_start(); //Add this!
session_start();

A: Besides what others say, you can also enable output buffering in your php.ini. If you set for instance:
output_buffering = 4096

Then all your output will be buffered (up to 4k) before being sent to browser. This will prevent any accidental output to be sent before your session_start().


text:
Q: How to enlarge java swing panel I create some panel with a lot of components as images text ... . Now I have one problem. Customers tell me that panel is too small. Is there some option to enlarge this whole panel or I have to enlarged components one by one ?
UPDATE:
from this:
to this:

A: everything depends of used LayoutManager,
Is there some option to enlarge this whole panel or I have to enlarged
components one by one

-> no, basically this is reason why LayoutManager exists there, most of them there are created especially for this reasons, GridLayout, GridBagLayout, BoxLayout (maybe without glue), BorderLayout and todays MigLayout are best way how to do it

A: it depends, if you have a GridLayout or some Layout witch set all the components with some order, for example, all the components at the same distance or all the components like a Matrix, if you enlarge the panel, all the components will enlarge with it. If not, you have to enlarge by hand.


text:
Q: Finding the no. of points at which $f$ is non-differentiable and the no. of integral points for which $f$ is minimum. If $$f(x) = |x| + |x - 1| + |x - 3| + |x - 6| + \cdots + |x - (1 + 2 + \cdots + 101)|$$ for all $x \in \mathbb R$ and $m,n$ are respectively the number of points at which $f(x)$ is non differentiable and the number of integral points for which $f(x)$ is minimum, then find the value of $(m+n-10)/18$.
I've graphed a part of the function, and I observe that when I graph in odd number of terms, I get minima at only one point, while for even number of terms I get a constant line as the minima which has in its range half the number of integers as the number of terms in the graphed functions. But I have no idea why this happens.
Do answer keeping in mind that I'm only a high school student :) I have looked for this everywhere and couldn't find any insight. Any help is much appreciated.

A: When you see a relatively big number, like $101$, it's useful to generalise first. So let $r$ be a natural number, and $$ f_r(x) := |x| + |x-1| + \dots |x - (1+\dots + r)| \\= \sum_{k = 0}^r |x - k(k+1)/2| =: \sum_{k = 0}^r |x - a_k|,$$ where $a_k = k(k+1)/2$. Note that the $a_k$ are increasing.
We know that the aboslute values will have some interesting feature at the $a_k$s. So imagine drawing vertical stumps at each of the $a_k$ on the x axis, which gives us a total of $r+2$ regions.
In the left-most region, i.e. $\{x < 0\}$, all the absolute values resolve to $a_k - x$, so the function has slope $-(r+1)$ in the interior of this region, and it's decreasing in this range. Now move to the next region. $|x|$ now resolves to $+x$, everything else is the same. So we get slope $-(r+1) + 2 = -(r-1) < 0$. Still decreasing.
Continuing this way, you will notice that (for odd $r$) for the region starting at $a_{(r-1)/2}$ and ending at $a_{(r+1)/2}$, the number of $+x$-terms exactly balance the number of $-x$ terms, so the function has slope $0$ in the interior of this region. This is our large flat region where the function is minimum. After this region, the $+x$ terms will start outnumbering the $-x$ terms, and the function will increase. (If $r$ were even, we'd have a single point as the minima. Can you see why?)
So, where does this flat region start? At $a_{(r-1)/2}$. Ends at $a_{(r+1)/2}.$ Note that both these points, which are natural numbers, are also minima, since the function is continuous. So the number of natural number points which attain the minimum is $a_{(r+1)/2} - a_{(r-1)/2} + 1$. This is equal to $$ \frac{(r+1)(r+3)}{8} - \frac{(r-1)(r+1)}{8} + 1 = \frac{r+3}{2}.$$
So, for this question, $n = 104/2 = 52$.
On the other hand, clearly at each of the points $0, a_1, \dots, a_{r},$ the function has a non-differentiability - the slope jumps by $2$. So the number of points $m$ is $r+1 = 102$ for us.
This means, of course, that $m+n - 10 = 144 = 8 \times 18$.

A: The absolute value function is continuous, with continuous derivative everywhere except at the point where the value is zero. We also know that the derivative of $|x|$ is either $1$ or $-1$. So the first hint that I've mentioned in the comments says that $f(x)$ is not differentiable when the value of any of the terms is $0$, You have $102$ such values, so $m=102$.
Now let's concentrate on finding the minimum. We know that such a minimum exists because $f(\infty)=f(-\infty)=\infty$, $f(0)=0+1+3+...+(1+2+...+101)<\infty$, and the function is continuous. We don't know if there is only one minimum or more than that. When you expand the absolute value, you have $|x|=-x$ if $x<0$ and $|x|=x$ if $x>0$. Whys is this important? Let's choose $x>1+2+...+101$. Then all the absolute values in the $f(x)$ are on the positive side for the arguments and $$f(x)=x+x-1+...+x-(1+...+101)=102x+C_0$$
Here $C_0$ is just a number. So in this case the slope is $102$, so the minimum on the segment from $1+...+101$ to infinity must be at the beginning. Now let's compare it to the previous interval. $1+...+100<x<1+...+101$. In this case you will need to change sign in the last term. Then $$f(x)=x+x-1+...+(x-(1+...+100))-(x+(1+...+101))=100x+C_1$$.
Obviously this is an increasing function, so the minimum is achieved at the beginning of the interval. You can continue this procedure. At every step you decrease the coefficient of $x$ by $2$. You should be able to figure out when that coefficient is $0$ (between $1+...+50$ and $1+...+51$). In that interval, $f(x)$ is constant. If you go to earlier intervals, the coefficient of $x$ will be negative, so on those segments the function is decreasing.
So the number of integers when the function is minimum is $52$ (you need to include the ends of the interval). Therefore $$m+n-10=102+52-10=144$$
Note: If the number of intervals is odd, you would have a single number as minimum. The slope on one side is positive, on the other is negative. You would not get a constant interval


text:
Q: How to make a paginated repository call from column entity in Spring Boot JPA I have this entity model class (Book) where an author can have written multiple books.
@Entity
@Table(name="book")
public class Book {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name="book_name")
    private String bookName;

    @Column(name="author_id")
    private Long authorId;

    //Setters and getters
}

In my Spring Boot project, I don't want to have an author table since there is a third part service that defines authors and their ids, how could I make a paginated repository call for all authorIds and their books?
I would want to have an endpoint that takes in (page, size) and returns a paginated list of a AuthorDTO like so:
public abstract class AuthorDTO implements Serializable {
    public abstract Long authorId();

    public abstract List<Book> books();
}

[
    {
        "authorId": 123,
        "books": [...]
    },
    ...

]

My first thought is to create a repository call not sure how we can get a page of a custom object. This is not valid below, but I would like to do something like the following.
Page<AuthorDTO> findAllBooksGroupedByAuthorId(Pageable pageable);

A: Your code seems to suggest you are trying to show the foreign key relationship in the class as an id.
JPA doesn't really do that.
JPA = "Java Persistence Language" i.e. you represent the relations between Java classes that mirror the database.
So in the database you may have a foreign key like 'author_id' in the book table, but in JPA/Java side it will be an "Author" class and not just a long/int.
I hope the below helps. Iv'e just slapped it on the main() of my code so it may not be perfect but I have left some comments as well.
Once you have a Page<Book> you may then want to map it to the DTO in java.
As the query is "get books by author id" we can assume that they all have the same author ID...so there is no real need to try get this projection in the database.
EDIT: Is it not at all possible to have a reference to the author from the 3rd party?
I.e. I don't know how you are populating "Book"...but could you not as you get "Book" from the 3rd party see if you have an Author entity with the books 'author_id' and not persist a new "Author" with that ID if it doesn't already exist?
In this case you can then do an AuthorRepo and simply query like:
Page<Author> findAllBy(Pageable page)
==========================================================================
Seeming as you are fetching a Page of Books by an author Id...you should really have a JPA relationship to show that:
    @Entity
    private class Book{

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private long id;

        @Column(name = "book_name")
        private String name;

        //Technically this could be Many:Many as a book could have 2 authors? If so....@ManyToMany
        //For simplicity (and what you seem to want) Many Books have ONE author.
        @ManyToOne(fetch = FetchType.LAZY)
        private Author author;

    }

    @Entity
    private class Author{

        //ID here - omitted for clarity

        @Column(name = "authors_name")
        String name;

        //The Author has many books.
        // Mapped by shows the bi-direction relationship. You can then do 'Author.getAuthorsBooks()'
        //Lazy means it wont fetch all the books from database/(hibernate wont) when you do AuthorRepo.get()
        //and will only do the `JOIN ON Books where` if you do Author.getAuthorsBooks()
        @OneToMany(fetch = FetchType.LAZY,mappedBy = "author")
        private Set<Book> authorsBooks = new HashSet<>();
    }

    private interface AuthorRepo extends JpaRepository<Author,Long>{
        //Note the JPA syntax.
        Page<Book> findAll(Pageable pageable);
    }

EDIT:
I have only written this in an empty file...so it may need tweaking or has typos etc
If you can NOT have a separate entity for some reason for Author, having to keep your entity as it currently is...I'd do 2 queries.
I feel you can either do this in various ways.
If you MUST stick with spring's Pageable:
Get the page request in the controller and make it in to a new PageRequest.of(pagenum,size)
and feed it in to do the Page query below
List<Long> getPageOfUniqueAuthorIds(Pageable pageable);

This will give a page of author Ids.
Then you want to use that List of Longs (aithorIds) to do the second query.
List<AuthorDTOProjection> getBooksAndAuthorIdsWithAuthorsIdsIn(List<Long> authorIds);

    @Entity
    @Table(name="book")
    public class Book {

        @Id
        @GeneratedValue
        private Long id;

        @Column(name="book_name")
        private String bookName;

        @Column(name="author_id")
        private Long authorId;

        //Setters and getters
    }

    private interface BookRepo extends JpaRepository<Book,Long> {

        //The countQuery is required by Spring Paging.
        //Hibernate will need to use the count query when doing paging on a native query.
        @Query(nativeQuery = true,
        value = "SELECT DISTINCT(author_id) FROM book b ",
        countQuery = "SELECT count(*) \n" +
                "FROM (SELECT DISTINCT(author_id) FROM book b) authorIds ")
        List<Long> getPageOfUniqueAuthorIds(Pageable pageable);

        //This is not paged. You want all books with the author IDs from the page query above.
      List<Book> findAllByAuthorIdIn(List<Long> authorIds);
    }

You will then have to map the Entity to the DTO in your service layer.
        @Autowired
        BookRepo bookRepo;

        //This would be from the controller method...not declared here...
        Pageable pageableFromController = PageRequest.of(0,10);

        List<Long> pageOfUniqueAuthorIds = bookRepo.getPageOfUniqueAuthorIds(pageableFromController);

        //Get All the books with Author Ids.
        List<Book> books = bookRepo.findAllByAuthorIdIn(pageOfUniqueAuthorIds);

        //Your abstract AuthorDTO.
        abstract class AuthorDTO implements Serializable {
            public abstract Long authorId();

            public abstract List<Book> books();
        }

        //Your Author DTO needs to be implemented so I made a "View".
        @AllArgsConstructor
        class AuthorView extends AuthorDTO{

            private long authorId;
            private List<Book> books;

            @Override
            public Long authorId() {
                return authorId;
            }

            @Override
            public List<Book> books() {
                return books;
            }
        }

        //Get a List of the authorIds in the List<Books>. Could also use the original Page<Long> authorIds...
        //As an author without a book is not possible in your database.
        final List<Long> authorIdsInBooks = books.stream().map(it -> it.authorId).distinct().collect(Collectors.toList());

        //Map the Ids of authors to an Impl of your abstract DTO. Personally I don't see why the AuthorDTO is abstract.
        //I'd have expected just an abstract DTO class called "DTO" or something and then AuthorDTO impl that.
        //But as the way you have it this will work. I guess you may want more impl of the  AuthorDTO so maybe leave the AuthorDTO as abstract.
        //This can be returned to client.
        final List<AuthorView> authorViews = authorIdsInBooks.stream()
                .map(authorId -> new AuthorView(
                        authorId,
                        books.stream().filter(it -> it.authorId.equals(authorId)).collect(Collectors.toList()))
                )
                .collect(Collectors.toList());


text:
Q: How to download a file with progress with IdHTTP via https I'm trying to download a file using indy10 http components TIdHttp while getting the progress , I have just setted the libraries in the application folder while using the code for http URL it works and progress but with https it simply does nothing and it doesn't raises any exception :/
 with TIdHTTP.Create(nil) do
   begin
    IOHndl:=TIdSSLIOHandlerSocketOpenSSL.Create(nil);
    Request.BasicAuthentication:=True;
    HandleRedirects:=True;
    IOHandler:=IOHndl;
    OnWork:=FOnWork;
    OnWorkBegin:=FOnWorkBegin;
    OnWorkEnd:=FOnWorkEnd;
    Get(FUrl,FStream);
end;

Best Regards

A: First you have to create a small class to wrap the HTTP component:
unit IdHTTPProgressU;

interface

uses
  Classes, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, IdSSLOpenSSL;

{$M+}

type
  TIdHTTPProgress = class(TIdHTTP)
  private
    FProgress: Integer;
    FBytesToTransfer: Int64;
    FOnChange: TNotifyEvent;
    IOHndl: TIdSSLIOHandlerSocketOpenSSL;
    procedure HTTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64);
    procedure HTTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
    procedure HTTPWorkEnd(Sender: TObject; AWorkMode: TWorkMode);
    procedure SetProgress(const Value: Integer);
    procedure SetOnChange(const Value: TNotifyEvent);
  public
    Constructor Create(AOwner: TComponent);
    procedure DownloadFile(const aFileUrl: string; const aDestinationFile: String);
  published
    property Progress: Integer read FProgress write SetProgress;
    property BytesToTransfer: Int64 read FBytesToTransfer;
    property OnChange: TNotifyEvent read FOnChange write SetOnChange;
  end;

implementation

uses
  Sysutils;
{ TIdHTTPProgress }

constructor TIdHTTPProgress.Create(AOwner: TComponent);
begin
  inherited;
  IOHndl := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
  Request.BasicAuthentication := True;
  HandleRedirects := True;
  IOHandler := IOHndl;
  ReadTimeout := 30000;
  OnWork := HTTPWork;
  OnWorkBegin := HTTPWorkBegin;
  OnWorkEnd := HTTPWorkEnd;
end;

procedure TIdHTTPProgress.DownloadFile(const aFileUrl: string; const aDestinationFile: String);
var
  LDestStream: TFileStream;
  aPath: String;
begin
  Progress := 0;
  FBytesToTransfer := 0;
  aPath := ExtractFilePath(aDestinationFile);
  if aPath <> '' then
    ForceDirectories(aPath);

  LDestStream := TFileStream.Create(aDestinationFile, fmCreate);
  try
    Get(aFileUrl, LDestStream);
  finally
    FreeAndNil(LDestStream);
  end;
end;

procedure TIdHTTPProgress.HTTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
begin
  if BytesToTransfer = 0 then // No Update File
    Exit;

  Progress := Round((AWorkCount / BytesToTransfer) * 100);
end;

procedure TIdHTTPProgress.HTTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64);
begin
  FBytesToTransfer := AWorkCountMax;
end;

procedure TIdHTTPProgress.HTTPWorkEnd(Sender: TObject; AWorkMode: TWorkMode);
begin
  FBytesToTransfer := 0;
  Progress := 100;
end;

procedure TIdHTTPProgress.SetOnChance(const Value: TNotifyEvent);
begin
  FOnChance := Value;
end;

procedure TIdHTTPProgress.SetProgress(const Value: Integer);
begin
  FProgress := Value;
  if Assigned(FOnChance) then
    FOnChance(Self);
end;

end.

I wont go in to details with the calss: Just say that it bacally wraps a TIdhttp component in and assign the 3 events: OnBegin, onWork and OnEnd
The Method DownloadFile does the actually download,
Then when you have to use it you could do like this:
Place a Button and a PrograssBar on an empty form. Add IdHTTPProgressU to the uses list.
Declare a vaiable of TIdHTTPProgress and a local onChangeEvent
Your form definition should lokke like this:
type
  TForm1 = class(TForm)
    Button1: TButton;
    ProgressBar1: TProgressBar;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    procedure IdHTTPProgressOnChange(Sender : TObject);
  public
    IdHTTPProgress: TIdHTTPProgress;
  end;

Then you just have to implement the methods:
    { TForm1 }

    procedure TForm1.Button1Click(Sender: TObject);
    begin
       IdHTTPProgress.OnChange := IdHTTPProgressOnChance;
          IdHTTPProgress.OnChance := IdHTTPProgressOnChance;
   IdHTTPProgress.DownloadFile('https://wordpress.org/latest.zip', 'latest.zip');
    end;

    procedure TForm1.FormCreate(Sender: TObject);
    begin
      IdHTTPProgress := TIdHTTPProgress.Create(Self);
    end;

    procedure TForm1.IdHTTPProgressOnChance(Sender: TObject);
    begin
      ProgressBar1.Position := TIdHTTPProgress(Sender).Progress;
      Application.ProcessMessages;
    end;

Thats about it. Give it at try.


text:
Q: WebDriverException when I use NoraUI and Chrome web driver on my windows laptop I use NoraUI (Non-Regression Automation for User Interfaces) and Chrome web driver on my windows laptop and I have this big error stack trace. Yesterday, my code worked and I am sure I have not changed anything.
The below error appears when instanciating the Chrome selenium web driver on opening any URL:
com.google.inject.ProvisionException: Unable to provision, see the following errors:

1) Error injecting constructor, org.openqa.selenium.WebDriverException: unknown error: cannot get automation extension
from unknown error: page could not be found: chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
  (Session info: chrome=57.0.2987.133)
  (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 10.58 seconds
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:49:13 -0700'
System info: host: 'ITEM-72885', ip: '192.168.56.1', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_66'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9), userDataDir=d:\Profiles\sgrillon\AppData\Local\Temp\scoped_dir8244_3992}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=57.0.2987.133, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=accept}]
Session ID: 94defa860dff1660a2881b2d597ee974
  at noraui.application.steps.CommonSteps.<init>(CommonSteps.java:22)
  while locating noraui.application.steps.CommonSteps

1 error
            at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1025)
            at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1051)
            at cucumber.runtime.java.guice.impl.GuiceFactory.getInstance(GuiceFactory.java:42)
            at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
            at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:48)
            at cucumber.runtime.Runtime.runStep(Runtime.java:300)
            at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
            at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
            at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
            at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:102)
            at org.junit.runners.Suite.runChild(Suite.java:128)
            at org.junit.runners.Suite.runChild(Suite.java:27)
            at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
            at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
            at cucumber.runtime.junit.ExamplesRunner.run(ExamplesRunner.java:59)
            at org.junit.runners.Suite.runChild(Suite.java:128)
            at org.junit.runners.Suite.runChild(Suite.java:27)
            at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
            at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
            at cucumber.runtime.junit.ScenarioOutlineRunner.run(ScenarioOutlineRunner.java:53)
            at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
            at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
            at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
            at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
            at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
            at cucumber.api.junit.Cucumber.runChild(Cucumber.java:95)
            at cucumber.api.junit.Cucumber.runChild(Cucumber.java:38)
            at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
            at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
            at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
            at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
            at cucumber.api.junit.Cucumber.run(Cucumber.java:100)
            at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:367)
            at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274)
            at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238)
            at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161)
            at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290)
            at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242)
            at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121)
            at ✽.Given I check mandatory fields:(steps/scenarios/RAPID-TRT-ASS.feature:5)
Caused by: org.openqa.selenium.WebDriverException: unknown error: cannot get automation extension
from unknown error: page could not be found: chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
  (Session info: chrome=57.0.2987.133)
  (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 10.58 seconds
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:49:13 -0700'
System info: host: 'ITEM-72885', ip: '192.168.56.1', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_66'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9), userDataDir=d:\Profiles\sgrillon\AppData\Local\Temp\scoped_dir8244_3992}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=57.0.2987.133, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=accept}]
Session ID: 94defa860dff1660a2881b2d597ee974
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
            at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
            at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
            at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:635)
            at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:658)
            at org.openqa.selenium.remote.RemoteWebDriver$RemoteWebDriverOptions$RemoteWindow.maximize(RemoteWebDriver.java:882)
            at noraui.browser.DriverFactory.generateWebDriver(DriverFactory.java:153)
            at noraui.browser.DriverFactory.getDriver(DriverFactory.java:57)
            at noraui.utils.Context.getDriver(Context.java:284)
            at noraui.application.steps.Step.<init>(Step.java:43)
            at noraui.application.steps.CommonSteps.<init>(CommonSteps.java:22)
            at noraui.application.steps.CommonSteps$$EnhancerByGuice$$60d24c4c.<init>(<generated>)
            at noraui.application.steps.CommonSteps$$EnhancerByGuice$$60d24c4c$$FastClassByGuice$$5ab45fbb.newInstance(<generated>)
            at com.google.inject.internal.cglib.reflect.$FastConstructor.newInstance(FastConstructor.java:40)
            at com.google.inject.internal.ProxyFactory$ProxyConstructor.newInstance(ProxyFactory.java:266)
            at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:105)
            at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:85)
            at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:267)
            at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1016)
            at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1092)
            at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1012)
            at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1051)
            at cucumber.runtime.java.guice.impl.GuiceFactory.getInstance(GuiceFactory.java:42)
            at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
            at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:48)
            at cucumber.runtime.Runtime.runStep(Runtime.java:300)
            at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
            at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
            at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
            at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:102)
            at org.junit.runners.Suite.runChild(Suite.java:128)
            at org.junit.runners.Suite.runChild(Suite.java:27)
            at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
            at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
            at cucumber.runtime.junit.ExamplesRunner.run(ExamplesRunner.java:59)
            at org.junit.runners.Suite.runChild(Suite.java:128)
            at org.junit.runners.Suite.runChild(Suite.java:27)
            at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
            at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
            at cucumber.runtime.junit.ScenarioOutlineRunner.run(ScenarioOutlineRunner.java:53)
            at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
            at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
            at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
            at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
            at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
            at cucumber.api.junit.Cucumber.runChild(Cucumber.java:95)
            at cucumber.api.junit.Cucumber.runChild(Cucumber.java:38)
            at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
            at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
            at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
            at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
            at cucumber.api.junit.Cucumber.run(Cucumber.java:100)
            at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:367)
            at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274)
            at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238)
            at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161)
            at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290)
            at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242)
            at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121)

com.google.inject.ProvisionException: Unable to provision, see the following errors:

1) Error injecting constructor, org.openqa.selenium.WebDriverException: unknown error: cannot get automation extension
from unknown error: page could not be found: chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
  (Session info: chrome=57.0.2987.133)
  (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 10.10 seconds
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:49:13 -0700'
System info: host: 'ITEM-72885', ip: '192.168.56.1', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_66'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9), userDataDir=d:\Profiles\sgrillon\AppData\Local\Temp\scoped_dir4416_8177}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=57.0.2987.133, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=accept}]
Session ID: d187a933403bfcb6f6ca60d5d35a1df5
  at noraui.application.steps.CommonSteps.<init>(CommonSteps.java:22)
  while locating noraui.application.steps.CommonSteps

1 error
            at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1025)
            at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1051)
            at cucumber.runtime.java.guice.impl.GuiceFactory.getInstance(GuiceFactory.java:42)
            at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
            at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:48)
            at cucumber.runtime.Runtime.runStep(Runtime.java:300)
            at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
            at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
            at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
            at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:102)
            at org.junit.runners.Suite.runChild(Suite.java:128)
            at org.junit.runners.Suite.runChild(Suite.java:27)
            at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
            at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
            at cucumber.runtime.junit.ExamplesRunner.run(ExamplesRunner.java:59)
            at org.junit.runners.Suite.runChild(Suite.java:128)
            at org.junit.runners.Suite.runChild(Suite.java:27)
            at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
            at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
            at cucumber.runtime.junit.ScenarioOutlineRunner.run(ScenarioOutlineRunner.java:53)
            at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
            at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
            at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
            at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
            at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
            at cucumber.api.junit.Cucumber.runChild(Cucumber.java:95)
            at cucumber.api.junit.Cucumber.runChild(Cucumber.java:38)
            at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
            at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
            at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
            at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
            at cucumber.api.junit.Cucumber.run(Cucumber.java:100)
            at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:367)
            at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274)
            at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238)
            at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161)
            at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290)
            at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242)
            at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121)
            at ✽.Given I check mandatory fields:(steps/scenarios/RAPID-TRT-ASS.feature:5)
Caused by: org.openqa.selenium.WebDriverException: unknown error: cannot get automation extension
from unknown error: page could not be found: chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
  (Session info: chrome=57.0.2987.133)
  (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 10.10 seconds
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:49:13 -0700'
System info: host: 'ITEM-72885', ip: '192.168.56.1', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_66'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9), userDataDir=d:\Profiles\sgrillon\AppData\Local\Temp\scoped_dir4416_8177}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=57.0.2987.133, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=accept}]
Session ID: d187a933403bfcb6f6ca60d5d35a1df5
            ...

Would you have any idea about this issue ?
Thanks in advance !

A: You Chrome update version automatically. You need update version of your Chrome Webdriver in :

YourRobot\java\src\test\resources\drivers\windows\googlechrome\64bit\chromedriver.exe

with good version : https://sites.google.com/a/chromium.org/chromedriver/downloads
Example for version 2.29 => https://chromedriver.storage.googleapis.com/index.html?path=2.29/
EDIT for V4+:

*

*check your Chrome version

*kill all webdriver process

*remove your local webdriver

*edit pom.xml

*

*search your version on https://chromedriver.chromium.org/

*copy version in profile(preIC) > build > plugins > plugin(download-maven-plugin) > executions > execution(download-googlechrome-webdriverxxxx) > configuration > url

*search your ETag on https://chromedriver.storage.googleapis.com/index.html?path=83.0.4103.39/

*copy ETag in profile(preIC) > build > plugins > plugin(download-maven-plugin) > executions > execution(download-googlechrome-webdriverxxxx) > configuration > md5

*run robot

A: I also had this issue. As @sgrillon said, you need to update your chromedriver.exe.
If you can't update the driver, then try to kill running chrome processes, and then retry.


text:
Q: Problemas ao fechar splash screen do RAD (v7.5) Estou tendo um problema incomum (quem não?), Minha tela de launcher / splash abre, mas ela mantém este estado mesmo depois de eu escolher a área de trabalho e depois do RAD carregar o projeto. Ele só fecha quando eu paro todo o software.
A última mudança que o meu RAD sofreu antes disso começar a acontecer foi a adição de alguns plugins para um projeto que usa Jasper e Crystal.
Eu já tentei usar o parâmetro -clean um milhar de vezes, mas nada mudou.
[update]
Investigando a causa do problema eu reparei que ao trocar de workspace a loading screen fecha e quando volta, junto com a janela principal da IDE, ela continua lá, mas o windows não a "vê", mais como uma segunda janela do mesmo software; não aparece no alt+tab ou na taskbar mais até eu fechar e abrir o RAD de novo.
obrigada


text:
Q: Project Export never completes and link expires My project is too big (9.9GB) because it has many commited versions of a ~400MB tar file. I was suggested to use filter-repo (https://docs.gitlab.com/ee/user/project/repository/reducing_the_repo_size_using_git.html). But I have to export the project.
I started the Export process and after I received a link by email (also there is a Download button on the export page). But when I try to download the exported file, I get this message:  "The file containing the export is not available yet; it may still be transferring. Please try again later."
How am I supposed to download the file? Please don't tell me that it cannot be exported because it is too big and there is no available space...
The download link is valid only for 24h. Maybe the export process is taking more than 24h...
Any hint to reduce the repo size?
Thank you
Luis

A:
But I have to export the project.

You should not have to export a GitLab project to apply git filter-repo.
You should only git clone the GitLab repository locally.
Once locally cloned:

*

*perform the git filter-repo (for instance git filter-repo --strip-blobs-bigger-than 10M)

*Check the size of your local repository with git-sizer

*git push --mirror
As usual, this kind of command rewrites history, so make sure to notify any collaborator.
The OP LuisGomes also mention Reduce repository size with git-filter-repo.
That thread mentions the workaround:

I had to create a new empty project and copy all the files from the big project to it.
If you need, you can change the name and the path of the old project so the new project can have the original ones, and you won't have to change other source codes.


text:
Q: How to make the TextBox placed properly under the search entry in Tkinter? def initUI(self):
     self.columnconfigure(5, weight=1)
     self.rowconfigure(3, weight=1)
     self.search_label = Label(self, text='Keyword:')
     self.search_label.grid(row=0, column=0, padx=5)

     self.keywords = StringVar()
     self.search_bar = Entry(self, width=30,textvariable=self.keywords)
     self.search_bar.grid(row=0, column=1)

     self.search_button = Button(self, text="Search",
                          command=self.handler_search)
     self.search_button.grid(row=0, column=3, padx=5)
     self.pack(fill=BOTH)#, expand='yes')
     #self.pack(fill=BOTH)
     self.box = Text(self, state='disabled')
     self.box.grid(row=1, column=0)

The UI is made up of three sub frames, the text editor is one, the side buttons are formed inside another one, and the search is inside another one. The snippet above is the UI for search.
See screenshot: http://i.imgur.com/Vip1t.png
I want to place a text box to be part of the search frame, which is under the search entry. I want it to extend the bottom area as much as possible.
I've tried to expand, fill, etc, but it doesn't solve the problem that entry gets stretched, and my textbox is cut off (I've added scrollbar previously but it was cut off as well).
Where is the problem? Thanks.

A: Get yourself a piece of graph paper and draw out your GUI. The problem should become evident.
You are putting the entry widget in column 1, the text widget in column 0. I'm not entirely sure of the effect you are looking for, but you can either move the text widget to column 1, or leave it in column 0 and have it span a couple of columns.
Assuming you want the text widget to be the whole width of the label-entry-button combination, and you want the label widget to be only as big as it needs to be, I would stop using grid and start using pack for this part of the GUI by doing the following:

*

*create a frame for the area as a whole; you can set it's borderwidth to zero if you want it to be invisible

*create an inner frame for the entry widget, label and search button. pack it to the top, fill=x

*create the text widget, pack it to the bottom, fill=both, expand=True

*create the label, pack it on the left of the inner frame

*create the search button, pack it on the right of the inner frame

*create the entry widget, pack it on the left of the inner frame, fill=x, expand=True

That will give you a self-contained megawidget with proper resize behavior that you can place wherever you want in the main application.
Build your GUI in sections, and make liberal use of inner frames to achieve the look and behavior you are striving for, and use a geometry manager that is right for each section. If you need something aligned in a grid, use grid. If you don't need a true grid but you do have independent rows or columns, use pack. pack excels at placing things in rows or columns. Grid excels at lining things up in a grid.  Pick the right tool for the job.


text:
Q: EF 6 include() not solving N + 1 I've got a class similar to
 public class Entity
 {
    virtual ICollection<Contact> Contacts { get; set; }
    virtual ICollection<PhoneNumber> PhoneNumbers { get; set; }
 }

In the repository I do
  return Context.Entities
                .Include(x => x.Contacts)
                .Include(x => x.PhoneNumbers)
                .AsNoTracking()
                .toList();

EFProf still shows Select N + 1?? I thought include was supposed to handle this?

EDIT: It seems the issue is occuring during serialization? I'm just trying to return a paged list of objects via a Web API.

A: In this case the related entities has lazily loaded relationships.
One of the properties on my original models (Contact) had a list of phone numbers to itself. So although the Contacts were not lazily evaluated, each Contact had it's own phone numbers lazy loaded due to being virtual and not explicitly included.


text:
Q: is it possible to check the XMLHttpRequestObject.responseText value using if condition Is it possible to check the XMLHttpRequestObject.responseText value using if condition instead of just displaying it?
I have tried like this.
var a=XMLHttpRequestObject.responseText;
if(a=="false")
{
    document.getElementById("show_mark").innerHTML =a;
}

I know its wrong,but i need to do like this.Is there any other alternative way for doing this?Help me i am completely a newbie to AJAX.

A: It is possible that the response text has added white spaces. To remove white spaces at the start and end of  a string use string.trim().
In your case a=a.trim()
If trim is not available in your browser's JavaScript interpreter add in
if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, '');
  };
}

Source

A: Finally i found the mistake.Its not the white spaces around the value.Actually its all the html tags like <html><body>false</body> etc., I removed these characters with the help of this code. I got the answer.
 var a=XMLHttpRequestObject.responseText;
    a = a.replace(/&(lt|gt);/g, function (strMatch, p1){
    return (p1 == "lt")? "<" : ">";
    });
    var b = (a.replace(/<\/?[^>]+(>|$)/g, "")).trim();
    if(b=="false")
    {
        document.getElementById("show_mark").innerHTML =b;
    }

Thanks for the support.


text:
Q: Is $d\theta$ a vector and does the equation $d\vec{s}=d\theta \times \vec{r}$ make sense? I was reading about torque on Wikipedia and I found this passage (in the section "Relationship between torque, power, and energy")

The work done by a variable force acting over a finite linear
displacement $s$ is given by integrating the force with respect to an
elemental linear displacement $d\vec{s}$
$$W=\int_{s_1}^{s_2} \vec{F} \cdot \vec{ds}$$

Note that I inserted the vector arrows above, though in the Wikipedia article the variables are in bold (though it isn't very clear always whether there is a bold font or not so I may make a mistake in transcribing). In particular, I am not sure if $d\theta$ is a vector or not.

However, the infinitesimal linear displacement $d\vec{s}$ is related
to a corresponding angular displacement $d\theta$ and the radius
vector $\vec{r}$ as
$$d\vec{s}=d\theta \times \vec{r}$$

Is the last equation correct? It seems like $d\theta$ is a scalar and $\vec{r}$ is a vector. My question is if I read the passage correctly, and if so, if it is correct as written.
Later in the passage, it seems like $d\theta$ is in fact a vector, because the $d\vec{s}$ expression is substituted into the work equation
$$W=\int_{s_1}^{s_2} \vec{F}\cdot d\theta \times \vec{r}$$
I am confused because usually I see arc length being $ds=rd\theta$.

A: The key is that $\text d\boldsymbol\theta$ is a differential, and thus is an infinitesimal quantity. This can be seen by doing the simple "experiment" below. While this answer is not mathematically rigorous, I think it shows how we get a vector from angular displacements. This experiment is from a "discussion question" exercise from Sears & Zemansky's "University Physics with Modern Physics" 13th edition:

Although angular velocity and angular acceleration can be treated as vectors, the angular displacement $\theta$, despite having a magnitude and direction, cannot. This is is because $\theta$ does not follow the commutative law of vector addition.
Prove this to yourself in the following way: Lay your physics textbook flat on the desk in front of you with the cover side up so that you can read the writing on it. Rotate it through $90^\circ$ about a horizontal axis so that farthest edge comes toward you. Call this angular displacement $\theta_1$. Then rotate by $90^\circ$ about a vertical axis so that the left edge comes toward you. Call this angular displacement $\theta_2$. The spine of the book should now face you, with the writing oriented so that you can read it.
Now start over again but carry out the two rotations in the reverse order. Do you get a different result? That is, does $\theta_1+\theta_2$ equal $\theta_2+\theta_1$?
Now repeat this experiment but this time with an angle of $1^\circ$ rather than $90^\circ$. Do you think that the infinitesimal displacement $\text d\boldsymbol\theta$ obeys the commutative law of addition and hence qualifies as a vector? If so, how is the direction of $\text d\boldsymbol\theta$ related to the direction of $\boldsymbol
\omega$?

The infinitesimal angular displacement can be treated as a vector just fine, even if "larger" displacements cannot be.

A: In the wikipedia's article, it is written $d\boldsymbol \theta \times \mathbf r$, the cross product of a (pseudo)vector and a vector. As the direction of the pseudovector is perpendicular to the plane of movement, the resultant vector is tangent to the trajectory.

A: Lets start with this equation
$$\vec v=\vec\omega\times \vec r\tag 1$$
with :
$$\vec v=v\,\vec e_v=\frac{ds}{dt}\,\vec e_v$$
and
$$\vec\omega=\omega\,\vec e_\omega=\frac{d\theta}{dt}\,\vec e_\omega$$
you obtain that
$$ds\,\vec e_v=d\theta\,\vec e_\omega\times \vec r$$
hence
$$\vec{ds}=ds\,\vec e_v\quad,\vec{d\theta}=d\theta\,\vec e_\omega\\
\text{so that}\\
\vec{ds}=\vec{d\theta}\times\vec{r}$$
so
$$\vec F\cdot\vec{ds}\mapsto \vec F\cdot(\vec{d\theta}\times\vec{r})=\vec F\cdot\left(d\theta\,\vec e_\omega\times \vec r\right)=\vec F\cdot\left(\vec e_\omega\times \vec r\right)\,d\theta$$
this make sense


text:
Q: Determinant for equivalent matrices? $A$ be a non singular matrix of order $4$ and $B$ is the matrix obtained from $A$ by adding twice of it's first row to third row, then find the determinant of $2A^{-1}B$ ?
I'm confused about determinant of equivalent matrices. Is this the right approach?

A: Adding a multiple of a line to another line doesn't change the determinant and $\det(A^{-1})=\det^{-1}(A)$, hence $$\det(2A^{-1}B)=2^4\det(A^{-1})\det(B)=2^4\frac{\det A}{\det A}=16.$$

A: Determinants of equivalent matrices are not same in general but here you are adding rows ,therefore determinant remains same.
Yes, if two matrices are similar then their trace/rank/determinant/eigenvalue will be equal.


text:
Q: need help calling text_a(), that was initially declared in foo(), inside the called function foo() I am creating code similar to this:
function foo(type,callback) {
 if(type === "a") {
  function text_a() {
   return "a";
  }
 }else if(type === "b") {
  function text_b() {
   return "b";
  }
 }else if(type === "c") {
  function text_c() {
   return "c";
  }
 }
 if(typeof callback === "function") callback();
}

foo("a",function() {
 console.log(text_a());
});

I want the function text_a() inside foo() to only be available when the type is equal to the relevant type and is called inside the foo() function. However this does not work. I keep getting an error message saying that text_a() is not defined, which makes no sense because when the foo function is called it should also declare the text_a function if the type is "a".

A: Just save a reference to the function and pass it to the callback..
eg.

function foo(type,callback) {
 var fn;
 if(type === "a") {
  fn = function text_a() {
   return "a";
  }
 }else if(type === "b") {
  fn = function text_b() {
   return "b";
  }
 }else if(type === "c") {
  fn = function text_c() {
   return "c";
  }
 }
 if(typeof callback === "function") callback(fn);
}

foo("a",function(fn) {
 console.log(fn());
});

foo("b",function(fn) {
 console.log(fn());
});