text:
Q: Let $z = 5e^{2πi/3}$ . Find the smallest positive integer n such that $(zi)^n ∈ \mathbb{Q}$ I need to solve the following problem:
Let $z = 5e^{2πi/3}$ . Find the smallest positive integer n such that $(zi)^n ∈ \mathbb{Q}$.
So i equated $(zi)^n$ to $a/b$, where $a$ and $b$ are integers.
Then I have
$(zi)^n=(5ie^{2πi/3})^n = a/b$ which $= (5i)^n e^{2nπi/3}$ and $i = e^{π/2 i}$ so $i^n = e^{π/2in}$
so subbing in $i^n$ gives $$5e^{π/2in}  e^{2πin/3} = 5e^{7πin/6}$$
This is where i got up to so far, not sure if its correct though. How do i go on from this point?
Really appreciate your help! Thanks!

A: $i=\cos{\pi/2}+i\sin{\pi/2}=e^{i\pi/2}$
$\displaystyle z=(5ie^{2πi/3})^n=(5e^{i\pi/2}e^{2πi/3})^n= (5e^{(2\pi/3+\pi/2)i})^n =5^ne^{n(2\pi/3+\pi/2)i}=5^n(\cos{(7n\pi/6)}+i\sin{(7n\pi/6)})=a+ib$
If $b=0$ then $(zi)^n ∈ \mathbb{Q}$
$\to 7n\pi/6=k\pi \to n=\dfrac{6k}{7}(n,k ∈ \mathbb{N})$
For $k=7$, $n=6$. This is the first and least integer $n$ that satisfies the conditions.


text:
Q: Match price with multiple comma I want to match values having multiple comma in them. I'm able to match values with only 1 comma.  regex: (\$\d+\,\d+)  Example Value: $567,76  but i need to match this value $567,76,87 but this regex is not working.

A: Try this pattern, maybe it could help.
^\$\d+(,\d+)*$

This will match on
$567
$567,76
$567,76,87

but not
$567,76,87,

*

*Regex Demo (click on .Net button)

A: You can parse the value using double.Parse(currency, NumberStyles.Currency) instead of using a regular expression.

A: Try like this;
^\$\d+(,\d+)+$

Some random matches;
$1622,40,749
$37,5844

Regex r = new Regex(@"^\$\d+(,\d+)+$");

string[] partNumbers = { "$567,76", "$567,76,87", "$567,76,87," };
foreach (var i in partNumbers)
{
       Console.WriteLine("{0} {1} a valid part number.", i, r.IsMatch(i) ? "is" : "is not");
}

$567,76 is a valid part number.
$567,76,87 is a valid part number.
$567,76,87, is not a valid part number.

Here is a DEMO.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android: ContentProvider Request in AsyncTask get delayed when some other ContentProvider operations/sqlite writes are happening I have a ContentProvider access in a AsyncTask which generally works fine while looking up some data stored in sqlite on the phone.
However I also have some other background services that do network checks and download and update some data.
It is observed that this network related background activity is affecting my ContentProvider. The ContentProvider which entirely works on offline data either delays the response or just never returns for a long time.
Are then any locking/queuing mechanisms on the ContentProvider or the sqlite database? The writes do not happen to the same tables as the reads.

A:
Are then any locking/queuing mechanisms on the ContentProvider or the sqlite database? The writes do not happen to the same tables as the reads.

*

*ContentProvider implementations require additional synchronization to be thread-safe, i.e the developer is in charge of it

*SQLite is synchronized, i.e. writes exclude reads
In your case you might want to enable write-ahead-logging (WAL), api 11+. This enables writes to happen in a separate journal in parallel: holding the lock and excluding parallel reads is not necessary anymore.
See for instance:
SQLite, Content Providers, & Thread Safety
Official docs for SQLite locking
Good explanation of WAL


text:
Q: how to write dynamic route in nginx location proxy config for example I want anyone hits localhost/api to be redirected to a proxy of 127.0.0.1/api and whatever after it, for example, if I got localhost/api/getMyName then the config redirect it to 127.0.0.1/api/getMyName. or if someone hits localhost/api/getSomeone/1, it will proxy to  127.0.0.1/api/getSomeone/1
I tried something like
location /api {
        proxy_pass http://127.0.0.1/api;
    }

But the nginx just not responding at or, and adding /* or * after them just do not do the work... what should it actually be written to match the scenario I want above?


text:
Q: Extract substring from between two words I'm trying to find a clean way to extract a substring from between two other substrings.So far I can do it based on targeting a specific character, but not a string. E.g (this doesn't work)
 var element = "Firstconstantmystring_lastconstant";
 var mySubString = element.substring(
                            element.lastIndexOf("Firstconstant") + 1,
                            element.lastIndexOf("_lastconstant")
                        );

I'm trying to extract "mystring" from the full string. I know that "Firstconstant" and "_lastconstant" will always be the same. Grateful for any help.

A: You can use a regular expression.

var string = 'Firstconstantmystring_lastconstant'
console.log(string.match(/(?<=Firstconstant)[\s\S]*(?=_lastconstant)/))

This will return an array with the first element being the result you want if there is a match, or null if there is no match.
Resources:

*

*MDN Reference for String.prototype.match: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

*MDN regex cheatsheet: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet

A: You should take the length from the first:

var element = "Firstconstantmystring_lastconstant";
var mySubString = element.substring(
                            "Firstconstant".length,
                            element.lastIndexOf("_lastconstant")
                        );
console.log(mySubString);

A: function substringBetween(s, a, b) {
var p = s.indexOf(a) + a.length;
return s.substring(p, s.indexOf(b, p));
}

var element = "Firstconstantmystring_lastconstant;";
var mySubString = substringBetween(element,'Firstconstant','_lastconstant')

console.log({mySubString })


text:
Q: similarTrees in java This is what I have to do. The Binary Search Tree ADT is extended to include a bool ean method si m i l ar Trees that receives references to two binary trees and determines whether the shapes of the trees are the same. (The nodes do not have to contain the same values, but each node must have the same number of children.) I have code to show what I have.
public static <T> boolean  similarTrees(BSTNode<T> a, BSTNode<T> b) {
    // check for reference equality and nulls
    if (a == b) return true; // note this picks up case of two nulls
    if (a == null) return false;
    if (b == null) return false;

    // check for data inequality
    if (a.data != b.data) {
        if ((a.data == null) || (b.data == null)) return false;
        if (!(a.data.equals(b.data))) return false;
    }

    // recursively check branches
    if (!similarTrees(a.left, b.left)) return false;
    if (!similarTrees(a.right, b.right)) return false;

    // we've eliminated all possibilities for non-equality, so trees must be equal
    return true;
}


text:
Q: in html file, how do I convert DateTime format to Hrs:Min? I'm running an API REQUEST to retrieve schedules for classes. Here is my code below in the index.html file
{% for class in listofclasses %}

{{ class.ClassDescription.Name }} with {{ class.Staff.FirstName }} at {{ class.StartDateTime }}

{% endfor %}

In the code above, the class.StartDateTime will retrieve the time as follows: 2020-03-30T18:00:00
How would I convert that to something like 6:00pm? Or 3/30 at 6:00pm?
I tried the following but it does not work:
{% for class in listofclasses %}

{{ class.ClassDescription.Name }} with {{ class.Staff.FirstName }} at {{ class.StartDateTime|date:"SHORT_DATE_FORMAT" }}

{% endfor %}

Please help

A: Howabout...
import datetime
input_time_date = datetime.datetime.strptime('2020-03-20T18:00:00', '%Y-%m-%dT%H:%M:%S')
new_time_date = input_time_date.strftime('%m/%d at %I:%M%p').replace('at 0', 'at ')
new_time_only = input_time_date.strftime('%I:%M%p').lstrip('0')
print(new_time_date)
print(new_time_only)

03/20 at 6:00PM
6:00PM


text:
Q: Applying multiple buffers to roads through arcpy I'm looking to apply multiple buffer of 100, 200, 300, and 400 meters to the roads feature class of a geodatabase. I keep running into an error in executing tool.
This is my code:
distances = [100, 200, 300, 400]
arcpy.env.workspace = r"C:\Users\public\Desktop\python\data\NewGeodatabase.gdb"
for distance in distances:
     arcpy.Buffer_analysis("roads", "roads_"+ str(distances) + "buff", distances, "FULL", "ROUND", "All")

A: Looks like the issue is because of using distances instead of distance while creating a buffer
Correct code will be
distances = [100, 200, 300, 400]
arcpy.env.workspace = r"C:\Users\public\Desktop\python\data\NewGeodatabase.gdb"
for distance in distances:
     # Change is on the following line - distances => distance
     arcpy.Buffer_analysis("roads", "roads_"+ str(distance) + "buff", distance, "FULL", "ROUND", "All")

If you want to define the unit of each distance separately for each buffer, you'll need the distances to be a list of strings where each string has the value and a valid unit i.e.
distances = ["100 Meters", "200 Miles", "300 Kilometers", "400 Feet"]


text:
Q: Spring Boot: Why isn't entity being scanned in createQuery when using multiple datasources? I am using Spring Boot 2.3.0. I have 2 data sources one for oracle and one for h2 defined in application.properties.
I have to 2 @Configuration classes for the data configurations. Both classes implement:

*

*DataSource

*PlatformTransactionManager

*LocalContainerEntityManagerFactoryBean
In LocalContainerEntityManagerFactoryBean I set up:

*

*setDataSource

*setPackagesToScan

*setJpaVendorAdapter
The application starts up properly, I can even do .findAll on the table in the H2 database, however
as soon as I start executing custom methods in the repository implementation, such as this:
@Transactional(readOnly = true)
private Optional<List<Foo>> findFooByState(Optional<Integer> id, Foo.State state) {
CriteriaBuilder cp = em.getCriteriaBuilder();
CriteriaQuery<Foo> cqFoo= cp.createQuery(Foo.class);
Root<Foo> fooRoot = cqFoo.from(Foo.class);
[...]

Spring throws an exception such as:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
[Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Not an entity: class foo.Foo;
nested exception is java.lang.IllegalArgumentException: Not an entity: class foo.Foo] with root cause

Package foo is added in setPackagesToScan as I wrote earlier.
I have tried various things with @Transactional, e.g. remove it, add the name of the transaction manager specified in the DataSource in it, move the @Transactional to the @GetMapping, but none of it helped.
Does anybody have any clue what am I doing wrong?
Thanks,

A: I had a similar problem. Most probably you haven`t configured JPA repositories base packages to pick up different entities for different data sources. You can have a look at my guide on how to configure two data sources
in Spring Boot application. Hope it will help!

A: Ok, I was lame. I had to:

*

*setPersistenceUnitName in the LocalContainerEntityManagerFactoryBean instantiation method

*I had to use the proper @PersistenceContext with the proper unitName


text:
Q: css pdf: force page break on overflow content I'm using handlebars and puppeteer to generate a pdf. The pdf is very design heavy with a lot of dynamic data so I'm using css to mock out the A4 formatted pages but I've reached a point where the data size is no longer predictable due to user input. By this I mean, if the data overflows beyond the pages bottom constraint, it keeps going into the void rather than automatically break out into the next page. My question is, is there a way to see if the page content is beyond the constraints of the parent, and if so.. break it out into another div/page with css or JavaScript?
Here is a small mockup of what my code looks like.
https://codepen.io/LTFoReal/pen/wvKboNJ

body {
  background: rgb(204,204,204);
}
page {
  background: white;
  display: block;
  margin: 0 auto;
  margin-bottom: 0.5cm;
  box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);
}
page[size="A4"] {
  width: 21cm;
  height: 29.7cm;
  padding: 5em 30px 0 30px;
  position: relative;
}

@media print {
  body, page {
    margin: 0;
    box-shadow: 0;
  }
}

.essay-data-container {
    min-height: 300px;
}

.essay-data-container .essay-data-header {
  text-transform: uppercase;
}
<page size="A4">

A RANDOM HEADER

This is the sub-title

Lorem ipsum dolor sit amet, consectetur adipiscing elit. In euismod luctus neque, eu pulvinar ante elementum vel. Pellentesque rutrum sapien vitae neque ornare, id vehicula nibh fermentum. Aliquam accumsan dictum gravida. Integer nec molestie mauris, sit amet placerat risus. Nam dolor dui, fringilla ac fermentum ac, mattis non enim. Vestibulum porttitor justo sed arcu porta dapibus. Suspendisse varius eros et ante ultricies congue. Nam magna ante, ornare sed tincidunt eget, euismod et nunc. Suspendisse venenatis aliquet ex et lacinia. Curabitur vitae ornare nibh. Suspendisse hendrerit fermentum egestas. Duis in nibh eros.

Phasellus eu imperdiet mauris. Nam iaculis metus eget nisi volutpat mollis. Praesent luctus nulla non lacus porta, nec cursus lorem eleifend. Quisque libero justo, fringilla vitae vestibulum in, bibendum vehicula justo. Fusce non leo porttitor, consequat enim vitae, luctus lacus. Nulla in sollicitudin quam, in vestibulum nisl. Etiam congue metus nunc, a tincidunt diam lobortis quis. Ut sodales mi magna, sit amet suscipit tellus semper id. Sed mattis efficitur justo eget tincidunt. Mauris vel commodo velit. Fusce augue magna, faucibus id venenatis sit amet, luctus id neque. Maecenas sed justo pellentesque, porttitor eros at, lobortis est. Nunc fringilla nisi eget erat aliquet, non tristique nulla imperdiet. Proin posuere elementum elit. Praesent massa massa, condimentum et consectetur non, ullamcorper et odio.

Nunc malesuada eu leo eget bibendum. Sed vitae justo euismod, vestibulum tortor sit amet, cursus augue. Nunc aliquet ullamcorper mollis. Nulla blandit porttitor tempor. Curabitur egestas dolor a enim lobortis iaculis sit amet non enim. Vestibulum sagittis est sollicitudin eros elementum, a pulvinar ante euismod. Phasellus pulvinar rhoncus tortor eget congue. Integer mattis vestibulum ex sit amet pulvinar. Praesent luctus felis urna, at bibendum justo eleifend ut. Nullam facilisis faucibus arcu, nec ultrices turpis consequat nec. Aliquam in lacus libero. Praesent tempor malesuada rutrum. Suspendisse potenti. Aenean nec ligula nisi.

Quisque a faucibus nibh. Vestibulum faucibus elit a elementum semper. Phasellus ac felis porta, finibus nibh gravida, fermentum metus. Donec a mauris dui. Morbi a turpis ac augue commodo ornare quis auctor purus. Cras consectetur turpis at nisi hendrerit gravida. Duis auctor faucibus mi, at hendrerit justo scelerisque in. Morbi bibendum leo sed arcu ultricies, a varius ante maximus. Donec molestie orci id rhoncus aliquam. Morbi id sodales elit.

Aenean viverra iaculis ante, nec sodales ipsum tempor a. Fusce risus nisl, aliquet quis arcu quis, consequat faucibus nibh. Aliquam eu pellentesque nulla, sed cursus leo. Vestibulum vel nibh orci. Phasellus vitae lacinia nulla. Ut at magna mollis, venenatis metus quis, ultricies enim. Integer ullamcorper sit amet magna at interdum. Pellentesque a mauris nec sem condimentum tincidunt. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In ac lectus vitae eros aliquam condimentum. Donec luctus ullamcorper neque, ut lobortis odio aliquet ut.

            Nulla ornare eros vel mattis feugiat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed vitae dolor velit. Aliquam egestas pharetra accumsan. Integer lobortis massa nec felis egestas, quis finibus neque aliquam. Integer consectetur nibh augue, at ultrices sem sagittis vel. Aliquam eu venenatis neque. Fusce aliquet sem ac lorem fringilla, malesuada luctus risus sodales. Mauris sed lectus ut tellus rhoncus lacinia. Pellentesque ultrices condimentum leo eu pharetra. Maecenas sit amet tortor at nisl mollis accumsan. Etiam volutpat tortor et libero mollis, ut facilisis massa feugiat.

            Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse eget dignissim magna. Integer efficitur risus vitae leo blandit semper.

</page>
<page size="A4"></page>

A: This is what I manage to do. It's not perfect but works fine for these two pages, and with some extra javascript you can make this work for the entire pdf.
Basically I check if it's overflowing based on the client/scroll width and height. Here is the place that I get inspiration and most of the code for check the overflow https://www.geeksforgeeks.org/how-to-determine-the-content-of-html-elements-overflow-or-not/
Then, I get the li tags that are overflowing and push into a new array called removedLis. After that, I just append this removedLis on the next page
--EDIT
Now it's working with countless pages
You can test here https://codepen.io/paulodelia/pen/ZEbNKBX
<!DOCTYPE HTML>

    <title>
        How to determine the content of
        HTML elements overflow or not
    </title>

    <page size="A4">

A RANDOM HEADER

This is the sub-title

Lorem ipsum dolor sit amet, consectetur adipiscing elit. In euismod luctus neque, eu pulvinar
                        ante elementum vel. Pellentesque rutrum sapien vitae neque ornare, id vehicula nibh fermentum.
                        Aliquam accumsan dictum gravida. Integer nec molestie mauris, sit amet placerat risus. Nam dolor
                        dui, fringilla ac fermentum ac, mattis non enim. Vestibulum porttitor justo sed arcu porta
                        dapibus. Suspendisse varius eros et ante ultricies congue. Nam magna ante, ornare sed tincidunt
                        eget, euismod et nunc. Suspendisse venenatis aliquet ex et lacinia. Curabitur vitae ornare nibh.
                        Suspendisse hendrerit fermentum egestas. Duis in nibh eros. 1

Phasellus eu imperdiet mauris. Nam iaculis metus eget nisi volutpat mollis. Praesent luctus nulla
                        non lacus porta, nec cursus lorem eleifend. Quisque libero justo, fringilla vitae vestibulum in,
                        bibendum vehicula justo. Fusce non leo porttitor, consequat enim vitae, luctus lacus. Nulla in
                        sollicitudin quam, in vestibulum nisl. Etiam congue metus nunc, a tincidunt diam lobortis quis.
                        Ut sodales mi magna, sit amet suscipit tellus semper id. Sed mattis efficitur justo eget
                        tincidunt. Mauris vel commodo velit. Fusce augue magna, faucibus id venenatis sit amet, luctus
                        id neque. Maecenas sed justo pellentesque, porttitor eros at, lobortis est. Nunc fringilla nisi
                        eget erat aliquet, non tristique nulla imperdiet. Proin posuere elementum elit. Praesent massa
                        massa, condimentum et consectetur non, ullamcorper et odio. 2

Nunc malesuada eu leo eget bibendum. Sed vitae justo euismod, vestibulum tortor sit amet, cursus
                        augue. Nunc aliquet ullamcorper mollis. Nulla blandit porttitor tempor. Curabitur egestas dolor
                        a enim lobortis iaculis sit amet non enim. Vestibulum sagittis est sollicitudin eros elementum,
                        a pulvinar ante euismod. Phasellus pulvinar rhoncus tortor eget congue. Integer mattis
                        vestibulum ex sit amet pulvinar. Praesent luctus felis urna, at bibendum justo eleifend ut.
                        Nullam facilisis faucibus arcu, nec ultrices turpis consequat nec. Aliquam in lacus libero.
                        Praesent tempor malesuada rutrum. Suspendisse potenti. Aenean nec ligula nisi. 3

Quisque a faucibus nibh. Vestibulum faucibus elit a elementum semper. Phasellus ac felis porta,
                        finibus nibh gravida, fermentum metus. Donec a mauris dui. Morbi a turpis ac augue commodo
                        ornare quis auctor purus. Cras consectetur turpis at nisi hendrerit gravida. Duis auctor
                        faucibus mi, at hendrerit justo scelerisque in. Morbi bibendum leo sed arcu ultricies, a varius
                        ante maximus. Donec molestie orci id rhoncus aliquam. Morbi id sodales elit. 4

Aenean viverra iaculis ante, nec sodales ipsum tempor a. Fusce risus nisl, aliquet quis arcu
                        quis, consequat faucibus nibh. Aliquam eu pellentesque nulla, sed cursus leo. Vestibulum vel
                        nibh orci. Phasellus vitae lacinia nulla. Ut at magna mollis, venenatis metus quis, ultricies
                        enim. Integer ullamcorper sit amet magna at interdum. Pellentesque a mauris nec sem condimentum
                        tincidunt. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus
                        mus. In ac lectus vitae eros aliquam condimentum. Donec luctus ullamcorper neque, ut lobortis
                        odio aliquet ut. 5

                        Nulla ornare eros vel mattis feugiat. Pellentesque habitant morbi tristique senectus et netus et
                        malesuada fames ac turpis egestas. Sed vitae dolor velit. Aliquam egestas pharetra accumsan.
                        Integer lobortis massa nec felis egestas, quis finibus neque aliquam. Integer consectetur nibh
                        augue, at ultrices sem sagittis vel. Aliquam eu venenatis neque. Fusce aliquet sem ac lorem
                        fringilla, malesuada luctus risus sodales. Mauris sed lectus ut tellus rhoncus lacinia.
                        Pellentesque ultrices condimentum leo eu pharetra. Maecenas sit amet tortor at nisl mollis
                        accumsan. Etiam volutpat tortor et libero mollis, ut facilisis massa feugiat. 6

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper. 7

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper. 8

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper. 9

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.10

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.11

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.12

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egesas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.13

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egesas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.14

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egesas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.15

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egesas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.16

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egesas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.17

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egesas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.18

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egesas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.19

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egesas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.20

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egesas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.21

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egesas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.22

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egesas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.23

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egesas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.24

                        Integer sodales lorem ac fringilla ornare. Fusce ac ultrices odio. Maecenas aliquam orci ac urna
                        egestas placerat. Maecenas lacus massa, dictum vitae felis vel, semper elementum urna. Curabitur
                        eu ex sed ex varius aliquam eget ut sapien. Sed ac tellus quis arcu hendrerit hendrerit a ac
                        dui. Nunc tortor libero, consequat ut ligula at, suscipit mollis ante. Ut ultrices id libero in
                        congue. Nunc a justo scelerisque, finibus lacus at, pellentesque dolor. Pellentesque habitant
                        morbi tristique senectus et netus et malesuada fames ac turpis egesas. Suspendisse eget
                        dignissim magna. Integer efficitur risus vitae leo blandit semper.25

    </page>


text:
Q: HowTo do Cassandra insert in multi-thread? I read a big file to insert to Cassandra.
I tried to create a Cassandra session, and pass it to multiple thread. I wish all thread use same session, to avoid thousands times reconnection.
I found the pool never call insert_chunk function because not see logging.
Any idea why the session can't be passed to in a thread?
I also tried to make session a global instead of parameter, the insert_chunk be called, but stuck at session.prepare
def insert_chunk(chunk, session):
    logging.info("insert chunck started")
    prepared = session.prepare(...)
    for line in chunck:
       session.execute(prepared, values)

main():
        cluster = Cluster()
        session = cluster.connect()
        with open("BIG_JSON", mode="r") as _file:
            objects = ijson.items(_file, "item")
            with Pool(20) as pool:
                while True:
                    chunk = list(itertools.islice(objects, 10000))
                    if len(chunk) <= 0:
                        break
                    pool.apply_async(
                        insert_chunk,[chunk, session],
                    )
                pool.close()
                pool.join()

A: Driver documentation says:

All of the patterns discussed above may be used over multiple processes using the multiprocessing module. Multiple processes will scale better than multiple threads, so if high throughput is your goal, consider this option.
  Be sure to never share any Cluster, Session, or ResponseFuture objects across multiple processes. These objects should all be created after forking the process, not before.

and links to the blog post that describe how to do it correctly.
But if everything you need is to load the data from a giant JSON file, then I have another suggestion - use DSBulk tool from DataStax (works with both DSE & Cassandra). This tool can read data from JSON, heavily optimized for loading & unloading of the data, and very flexible about mapping data from JSON into a table.
There is a series of blog posts on its usage:

*

*https://www.datastax.com/blog/2019/03/datastax-bulk-loader-introduction-and-loading

*https://www.datastax.com/blog/2019/04/datastax-bulk-loader-more-loading

*https://www.datastax.com/blog/2019/04/datastax-bulk-loader-common-settings

*https://www.datastax.com/blog/2019/06/datastax-bulk-loader-unloading

*https://www.datastax.com/blog/2019/07/datastax-bulk-loader-counting

*https://www.datastax.com/blog/2019/12/datastax-bulk-loader-examples-loading-other-locations


text:
Q: Python Requests POST returning incomplete content I am trying to download a csv file using the Python Requests library. I am using the Requests library because I first must get past a Disclaimer page so I use the Session object to store all the cookies and all that jazz. My POST request keeps returning with a response content that is only the first 6 lines of the csv file.  When I download the file using a browser, it is 1622 rows long.
My current script:
import logging
logging.basicConfig(level=logging.DEBUG)
import pdb
import requests

s = requests.Session()

## Disclaimer page session
dis_url = 'http://a100.gov.bc.ca/pub/gwl/disclaimer.do'
accept_form = {'submitType':'Accept'}
s.post(dis_url, data=accept_form)

## POST request
base_url = 'http://a100.gov.bc.ca/pub/gwl/plot.do'
postContent = {
'fromYear':'2012',
'fromMonth':'1',
'fromDay':'1',
'toYear':'2013',
'toMonth':'1',
'toDay':'1',
'emsIDs':'E290172' ,
'mode':'GRAPH',
'mmaFlags':'false',
'submitType':'Download'}

httpHeaders = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Host': 'a100.gov.bc.ca',
'Connection': 'keep-alive',
'Content-Length': '155',
'User-Agent': 'python-requests/1.2.3 CPython/2.7.3 Linux/3.5.0-23-generic',
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': 'http://www.env.gov.bc.ca/wsd/data_searches/obswell/map/obsWells.html',
'Accept-Encoding': 'gzip,deflate,sdch',
'Accept-Language': 'en-US,en;q=0.8'}

r = s.post(base_url, data=postContent, headers=httpHeaders, stream=False, timeout=3600)
print r.content

I should also mention that I have also tried to return the csv via chunking like so:
with open("report.csv",'wb') as file:
    r = s.post(base_url,stream=True,timeout=3600, data=postContent, headers=httpHeaders)
    for chunk in r.iter_content(chunk_size=1024):
        if chunk:
            file.write(chunk)
            file.flush()

But I still only get the first 6 lines in the report.csv.
I'm thinking that my content isn't being fully loaded because I am missing something in my request header. Here is the (working) browser request header:
POST /pub/gwl/plot.do HTTP/1.1
Host: a100.gov.bc.ca
Connection: keep-alive
Content-Length: 155
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: http://www.env.gov.bc.ca
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://www.env.gov.bc.ca/wsd/data_searches/obswell/map/obsWells.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.
Cookie: JSESSIONID=73de9312c8dcf1c4c657d19adbe811b88792479fe72eb2e2feeedea7d88bdbf8.e3uMah8KbhmLe3mMbN8Pa3uPbi1ynknvrkLOlQzNp65In0; WT_FPC=id=2fcd604924a9af3c13e1374599088181:lv=1383612362138:ss=1383612301792

And the working browser response header:
HTTP/1.1 200 OK
Date: Mon, 04 Nov 2013 20:59:52 GMT
Server: Oracle-Application-Server-10g/10.1.2.2.0 Oracle-HTTP-Server
Content-Disposition: attachment; filename="gwl_report.csv"
Cache-Control: must-revalidate
Content-Type: application/download
Set-Cookie: JSESSIONID=61d874e1b5ce07df96aaabe504d7c18788e5aaf773a7bee7ab4b0cf349a88aaa.e3uMah8KbhmLe3mMbN8Pa3uPbi1ynknvrkLOlQzNp65In0; path=/pub/gwl
Transfer-Encoding: chunked

The request headers from the python post request (my response is missing Transfer-Encoding: chunked):
Content-Length : 126
Accept-Language : en-US,en;q=0.8
Accept-Encoding : gzip,deflate,sdch
Connection : keep-alive
Accept : text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent : python-requests/1.2.3 CPython/2.7.3 Linux/3.5.0-23-generic
Host : a100.gov.bc.ca
Referer : http://www.env.gov.bc.ca/wsd/data_searches/obswell/map/obsWells.html
Cookie : JSESSIONID=9a51e637cccc6164e4784631ef9a0ab21574c518c1c5c86cf0892bbf2aa22c95.e3uMah8KbhmLe3mMbN8Pa3uPbi1ynknvrkLOlQzNp65In0
Content-Type : application/x-www-form-urlencoded

Python response header (mine is missing Transfer-Encoding: chunked):
content-length : 200
content-disposition : attachment; filename="gwl_report.csv"
set-cookie : JSESSIONID=9a51e637cccc6164e4784631ef9a0ab21574c518c1c5c86cf0892bbf2aa22c95.e3uMah8KbhmLe3mMbN8Pa3uPbi1ynknvrkLOlQzNp65In0; path=/pub/gwl
server : Oracle-Application-Server-10g/10.1.2.2.0 Oracle-HTTP-Server
cache-control : must-revalidate
date : Tue, 05 Nov 2013 00:51:47 GMT
content-type : application/download

Does anyone know how I can make a POST request that will return the whole csv file?

A: It maybe bug in requests and urllib3 https://github.com/psf/requests/issues/4956
see also: https://blog.petrzemek.net/2018/04/22/on-incomplete-http-reads-and-the-requests-library-in-python/


text:
Q: Is it possible to center a single item on a listview? I have a custom listview in a relative layout and I was wondering if it is possible to center a single item in a listview? The custom adapter handles two TextView fields from the custom_listview.xml
For example:
My List view

A    B
C    D
   E
F    G

I've included my xml layouts below.
summary.xml
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
        android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context="com.myapp.Summary">

        <TextView android:id="@+id/Welcome" android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <ListView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/mainListView"
            android:layout_below="@+id/Welcome"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="21dp" />

    </RelativeLayout>

    <!-- Side navigation drawer UI -->
    <ListView
        android:id="@+id/navList"
        android:layout_width="200dp"
        android:layout_height="match_parent"
        android:layout_gravity="left|start"
        android:background="#ffeeeeee"/>

</android.support.v4.widget.DrawerLayout>

custom_listview.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:id="@+id/listView1"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
     tools:context=".LoginActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Please wait.."
        android:layout_weight="1"
        android:id="@+id/txtFieldName" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Please wait.."
        android:id="@+id/txtFieldValue" />
</LinearLayout>

A: The easiest way to do this in your situation is to set the second TextView's Visibility to View.GONE. Since you are wrapping the TextViews in a LinearLayout and the first view has a weight attribute, it will fill the whole parent layout when there are no "sibling" views for it.
In this case, you have to be careful to reset the visibility of the second item in your getView method using an if/else statement.
Keep in mind that the View will have the same width as the parent in this case - even though it's written as wrap_content, it will fill all the horizontal space contained by the parent, effectively rendering it as match_parent.

A: You need to set the Gravity to CENTER programatically on that particular element to center it in your Adapter's getView() method. If you use the ViewHolder pattern, make sure you set the other ones to default; so you'll need an if/else statement.


text:
Q: Windowed function/pivot way to aggregate different values of the same column into different columns? I have a hierarchy of tables:

*

*GrandParentFoo, which has zero or more

*ParentFoo, which has zero or more

*ChildFoo
ParentFoo and ChildFoo both have a Status column with a total of 4 possible statuses:

*

*Pending (1)

*Active (2)

*Paused (3)

*Complete (4)

I am trying to write a query that gives me a rollup for any particular GrandParentFoo along the following lines:

*

*GrandParentFooId

*Total ParentFoos

*Total ParentFoos Pending

*Total ParentFoos Active

*Total ParentFoos Paused

*Total ParentFoos Completed

*Total ChildFoos

*Total ChildFoos Pending

*Total ChildFoos Active

*Total ChildFoos Paused

*Total ChildFoos Completed

I was starting down the path of:
select
    gp.GrandParentFooId,
    count(distinct pf.ParentFooId) as TotalParentFoos,
    sum(case pf.Status
        when 1 then 1
        else 0 end) as TotalParentFoosPending

...when I realized this was going to give me an inflated count where multiple ChildFoo records existed on the ParentFoo records.
Do I have to write this out as a series of CTE's, or is there a cleaner, simpler way to do this?  It seems like a pivot or windowed function of some kind would work here, but I can't conceptualize it.

A: One relatively simple method uses conditional aggregation with count(distinct):
select gp.GrandParentFooId,
    count(distinct pf.ParentFooId) as TotalParentFoos,
       count(distinct case when fp.status = 1 then pf.ParentFooId end) as parent_pending,
       count(distinct case when fp.status = 2 then pf.ParentFooId end) as parent_active,
       count(distinct case when fp.status = 3 then pf.ParentFooId end) as parent_paused,
       count(distinct case when fp.status = 4 then pf.ParentFooId end) as parent_completed,
       count(distinct c.ChildId) as num_children,
       count(distinct case when fp.status = 1 then c.ChildId end) as child_pending,
       count(distinct case when fp.status = 2 then c.ChildId end) as child_active,
       count(distinct case when fp.status = 3 then c.ChildId end) as child_paused,
       count(distinct case when fp.status = 4 then c.ChildId end) as child_completed
from grandparentfoo gp left join
     parentfoo p
     on gp.GrandParentFooId = p.GrandParentFooId left join
     childfoo c
     on p.ParentFooId = c.ParentFooId;

Notes:

*

*COUNT(DISTINCT) is probably not needed for the children.  COUNT(c.ChildId) is probably sufficient.

*For larger data, I would suggest a more complex query to avoid the COUNT(DISTINCT)s.


text:
Q: How can I log messages from an ASP.NET Core application to a specific file on Linux? I installed an ASP.NET Core application as a Linux daemon. By default .NET writes logs into /var/log/message but I would like the application to write its logs in a specific file and store it permanently.
How I can do this? The application uses Microsoft.Extensions.Logging.

A: Logs go where you tell them to go, not a specific location. /var/log/message is the location used by the Debug Provider only.
You need to specify which logging providers you want to use in the logging configuration of your project, as shown in the Logging in .NET Core article.
There's no built-in file provider and there's an ongoing discussion about whether there should be one. Logging to files isn't as simple as it sounds at first - how should the messages be formatted? What about rolling files? File names? Perhaps you want errors and verbose messages to be written to different files? Or use different files per subsystem/area/logger/business  in your application, eg one log for the sales service, another to log external service calls?
There are a lot of good open source logging libraries, like Serilog and NLog that address these concerns. Some of the most popular ones are listed in .NET Core's documentation. .NET Core's logging can be configured to easily use those libraries.
For example, you can add a Serilog file target with the appropriate package.
To use it, you need to add a reference to the package, eg in your csproj file :
<PackageReference Include="Serilog.Extensions.Logging.File" Version="2.0.0" />

And add it to the logging configuration with a call to AddFile :
WebHost.CreateDefaultBuilder(args)
    .ConfigureLogging((hostingContext, logging) =>
    {
        logging.AddFile("path/to/Logs/myapp-{Date}.txt");
    })
    .UseStartup<Startup>()
    .Build();

The {Date} argument is used to create rolling log files per date.
You can combine multiple loggers,eg you can write to the console with logging.AddConsole() or keep writing to /var/log/message during development with logging.AddDebug();
You can find many logging providers is you search for Extensions.Logging in NuGet.
You could also integrate other libraries like Serilog in your application and use their loggers. For example, you can use the Serilog.Sinks.Fluentd package to target Fluentd

A:
By default dotnet write logs into /var/log/message

Only if you use the "Debug logging provider" that simply logs calls to Debug.WriteLine. These calls are ignored in "release" builds, the compiler simply removes them from your app unless you have the DEBUG build constant.
Now back to the question: I was also kinda surprised there's no built-in logging in .NET 5 for Linux.
Especially considering that Linux has had great built-in logging tools for decades. Like syslog for example. Just send stuff to the /dev/log socket and linux will take care of the rest - write to a file, rotate logs, etc etc.
So I wrote a (very!) short C# file that just calls the built-in syslog() function from libc using DllImport.
It's not a huge Nuget dependency, not a "logging provider", not a DI-service or whatever. Just one 1kb C# file you can throw into your project and log stuff like this:
Syslog.Write(Syslog.Level.Warning, "MyAwesomeApp", "something went wrong");

Here's the gist https://github.com/jitbit/SyslogCore
P.S. This does not directly answer the question, but this page keeps popping up when I search for ways to log under Linux in .NET 5. So I decided to post another answer.


text:
Q: 'Return' column name My database tables have a Return column name. Now I'm having a problem whenever I'm trying to use it as condition.
I'm also having an SQL error saying

Incorrect syntax near the keyword 'Return'

whenever I'm trying to do this SELECT Return FROM My_Table. I know I'm having that error because Return is one of the SQL syntax.
I've been searching on google, but I couldn't find the right keywords for that answer. Now, I want to know if is there any possible solution for that problem without renaming my column as it would cause a big effect on my system?

A: Wrap the column name in bracket [Return].
select [Return] from table;

A: In MSSQL you can use special characters or reserved words using [] or "".
SELECT 1 AS [RETURN], 2 AS "RETURN"

My suggestion: avoid, if possibile to use spec chars and res. words, and use plain simple names.


text:
Q: asking for suggestions on modelling the data structure of my PDP emulator (Please dont close as a being a subjective question - I am asking for advice from fellow travelers on the 'discovering rust idioms' track)
I am porting my PDP11 emulator from c++ to rust. I am trying to get the right data structures.
Logically a PDP11 system consists of a CPU, a bus (that owns all the IO devices) and some ram. Each component needs to talk to each other. So I started with this
pub struct System {
    ram: Memory,
    cpu: Cpu,
    bus: Bus,
}

And lets look at one function
impl Cpu{
    pub fn step(&self) -> (){
        let inst = ram.get_word(self.pc);
       // decode inst
       // execute it
    }
}

single step. The core of the emulator. It needs access to the ram (and the bus but not shown here). OF course this is incomplete and doesnt have a way to get at the ram
My first effort was then to some how wire up these 'child' structs to have pointers back to this system object. No can do, they need to be mut in both directions, chaos ensues.
Then I thought that since there is only one of each thing I just flatten the whole thing into one object, all the methods and data exist on the system object. But thats just not clean, these are logically distinct subsystems that I really want to model as separate entities .
Then I had a revelation. What would rust want me to do? Pass into the function calls the data it needs. Like this
impl System{
  pub fn step(&mut self){
        self.cpu.step(&mut self)
    }
}

and
impl Cpu{
    pub fn step(&self, &mut sys:System) -> (){
        let inst = sys.ram.get_word(self.pc);
       // decode inst
       // execute it
    }
}

(There is a UI calling these System methods higher up the stack via FFI). Now I know that this doesn't work and have read why it does work.
I have been stuck for a week now trying to work out whats the best way to arrange these structures. Any advice please?

A:
My first effort was then to some how wire up these 'child' structs to have pointers back to this system object

That would be a bad idea in C++ too (or any language, really). Cycles are bad!

Pass into the function calls the data it needs.

Yes, that is a solution that can be seen in many projects out there, but take into account that you are also creating a cycle. In this case, the cycle is temporary rather than permanent, but it is still a cycle.
Instead, what you can to do is pass only the subsystems that the first subsystem needs. This removes the cycle. Or even just the pieces of a subsystem you may need.

Then I thought that since there is only one of each thing I just flatten the whole thing into one object, all the methods and data exist on the system object. But thats just not clean, these are logically distinct subsystems that I really want to model as separate entities .

Perhaps, but take into account that in many cases real-life entities are not the best partitioning points when modeling a system.
When you have subsystems that depend on many of the other subsystems or even the entire system, perhaps creating cycles, then it might be a symptom that the partition you chose is not the best.
If you want to keep the subsystems separated as they are and avoiding cycles turns out to be impossible, you can resort to solutions like RefCell or copy semantics.


text:
Q: C# How to get the date mouseover with a DateTimePicker? I want to add a tooltip to the DateTimePicker Calendar that show some informations based on the date that the mouse is over. Is there a way to retrive the date under the mouse without clicking it?

A: The native Windows DTP control is quite primitive.  It doesn't support anything like HitTest() as supported by ListView and TreeView.  Trying to guess where the mouse is located from the mouse position is dangerous, DTP is sensitive to format overrides in the Control Panel's Region settings.  Don't try to make this work.

A: Are you talking about the Calendar control (AFAIK there is no DateTimePicker built into WPF as it stands).
See the section Replacing the CalendarItem Template in the article below: you can add your ToolTip there, right in the control.

http://msdn.microsoft.com/en-us/magazine/dd882520.aspx

It shows a calendar with phases of the moon, modified to look like a planner: very customisable!
Edit: Obviously I should say, there is source code included.
Hope that helps!


text:
Q: How to crop a FITS image in Python in a given shape? I want to crop a FITS image area between two circles. For example, I want to crop out an area in the FITS image between circles of radii of R1 and R2. How do I go about it?

A: You will probably find what you're looking for in the regions package:
https://astropy-regions.readthedocs.io/en/latest/
It can create regions with pixel or sky coordinates, combine them, and create pixel masks:
In [1]: from regions import CirclePixelRegion, PixCoord

In [2]: c1 = CirclePixelRegion(center=PixCoord(6, 6), radius=3)

In [3]: c2 = CirclePixelRegion(center=PixCoord(9, 9), radius=3)

In [4]: (c1 & c2).to_mask().data
Out[4]:
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

In [5]: (c1 | c2).to_mask().data
Out[5]:
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 1, 1, 1, 1, 0],
       [0, 0, 0, 0, 1, 1, 1, 1, 1, 0],
       [0, 0, 0, 0, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 0, 0, 0, 0],
       [0, 1, 1, 1, 1, 1, 0, 0, 0, 0],
       [0, 1, 1, 1, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])


text:
Q: Multiple the numbers of a specific column with a number in libre office How can I multiple the numbers of column A with the number eg 5? I use LibreOffice. Thank you

A: *

*Enter the factor (multiplicant) 5 in an empy cell and copy it (CTRL+C);

*Select the column with the values to multiply;

*Select Menu Edit -> Paste special... (or hit CTRL+SHIFT+V);

*Under Operations, select Multiply - leave everything else as default; hit OK:

That's it - LO Calc will multiply the selected cell values with the value copied in step 1.


text:
Q: Diagnosing why my MBP keeps crashing and restarting? I am currently getting occasional 'crashes' while running OS X 10.9 on an Early 2011 Macbook Pro. The crashes very much resemble the Blue Screen of Death on Windows (i.e. it happens suddenly, and it triggers an instant restart).
Here is a crash report from the most recent crash. Can anyone see what might be going on?
Thu Nov 14 23:01:11 2013
panic(cpu 0 caller 0xffffff80276dc19e): Kernel trap at 0xffffff7fa9c12829, type 14=page fault, registers:
CR0: 0x000000008001003b, CR2: 0x0000000000000028, CR3: 0x000000002a290000, CR4: 0x00000000000606e0
RAX: 0x0000000000000000, RBX: 0xffffff805f77b608, RCX: 0xffffffffffffffff, RDX: 0x000000000000000e
RSP: 0xffffff81fa313c70, RBP: 0xffffff81fa313ca0, RSI: 0x000000000000006a, RDI: 0x000000000000ffff
R8:  0xffffff7fa9c1dd74, R9:  0xffffffffffffff00, R10: 0x00000000000003ff, R11: 0xffffffffffffffff
R12: 0x0000000000000001, R13: 0xffffff804e8a7b48, R14: 0xffffff804f0f6a08, R15: 0x0000000000000020
RFL: 0x0000000000010286, RIP: 0xffffff7fa9c12829, CS:  0x0000000000000008, SS:  0x0000000000000010
Fault CR2: 0x0000000000000028, Error code: 0x0000000000000000, Fault CPU: 0x0

Backtrace (CPU 0), Frame : Return Address
0xffffff81fa313900 : 0xffffff8027622f69
0xffffff81fa313980 : 0xffffff80276dc19e
0xffffff81fa313b50 : 0xffffff80276f3606
0xffffff81fa313b70 : 0xffffff7fa9c12829
0xffffff81fa313ca0 : 0xffffff7fa9c12d52
0xffffff81fa313d00 : 0xffffff7fa8238bf1
0xffffff81fa313d60 : 0xffffff7fa822d16b
0xffffff81fa313e30 : 0xffffff8027aae4b3
0xffffff81fa313e90 : 0xffffff7fa822cc84
0xffffff81fa313ec0 : 0xffffff8027ab05fb
0xffffff81fa313f20 : 0xffffff802764a15a
0xffffff81fa313fb0 : 0xffffff80276d6aa7
      Kernel Extensions in backtrace:
         com.apple.iokit.IOHIDFamily(2.0)[1185D338-98A5-345E-84F8-E59DF819A61B]@0xffffff7fa820e000->0xffffff7fa827ffff
            dependency: com.apple.driver.AppleFDEKeyStore(28.30)[558B2575-5197-3C4C-BAD2-8CB465638FA8]@0xffffff7fa8203000
         org.pqrs.driver.KeyRemap4MacBook(9.0)[722DA168-34C5-309C-8DF0-2D51ADCAEC49]@0xffffff7fa9c0a000->0xffffff7fa9c24fff
            dependency: com.apple.iokit.IOHIDFamily(2.0.0)[1185D338-98A5-345E-84F8-E59DF819A61B]@0xffffff7fa820e000

BSD process name corresponding to current thread: kernel_task

Mac OS version:
13A603

Kernel version:
Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE_X86_64
Kernel UUID: 1D9369E3-D0A5-31B6-8D16-BFFBBB390393
Kernel slide:     0x0000000027400000
Kernel text base: 0xffffff8027600000
System model name: MacBookPro8,2 (Mac-94245A3940C91C80)

System uptime in nanoseconds: 4118026041294
last loaded kext at 247448385431: com.apple.filesystems.msdosfs 1.9 (addr 0xffffff7fa9c25000, size 65536)
last unloaded kext at 307752918395: com.apple.filesystems.msdosfs   1.9 (addr 0xffffff7fa9c25000, size 57344)
loaded kexts:
org.pqrs.driver.KeyRemap4MacBook    9.0.0
net.telestream.driver.TelestreamAudio   1.0.5
com.globaldelight.driver.BoomDevice 1.1
com.apple.driver.AppleBluetoothMultitouch   80.14
com.apple.driver.AppleHWSensor  1.9.5d0
com.apple.filesystems.autofs    3.0
com.apple.iokit.IOBluetoothSerialManager    4.2.0f6
com.apple.driver.AGPM   100.14.11
com.apple.driver.AppleMikeyHIDDriver    124
com.apple.kext.AMDFramebuffer   1.1.4
com.apple.driver.AppleHDA   2.5.2fc2
com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport 4.2.0f6
com.apple.AMDRadeonX3000    1.1.4
com.apple.driver.AppleSMCLMU    2.0.4d1
com.apple.driver.AppleMikeyDriver   2.5.2fc2
com.apple.driver.AppleSMCPDRC   1.0.0
com.apple.driver.AppleUpstreamUserClient    3.5.13
com.apple.driver.AppleUSBDisplays   360.8.14
com.apple.kext.AMD6000Controller    1.1.4
com.apple.driver.AudioAUUC  1.60
com.apple.iokit.IOUserEthernet  1.0.0d1
com.apple.Dont_Steal_Mac_OS_X   7.0.0
com.apple.driver.AppleHWAccess  1
com.apple.driver.AppleIntelHD3000Graphics   8.1.8
com.apple.driver.AppleIntelSNBGraphicsFB    8.1.8
com.apple.driver.ACPI_SMC_PlatformPlugin    1.0.0
com.apple.driver.SMCMotionSensor    3.0.4d1
com.apple.driver.AppleMuxControl    3.4.12
com.apple.driver.AppleMCCSControl   1.1.12
com.apple.driver.AppleLPC   1.7.0
com.apple.driver.AppleThunderboltIP 1.0.10
com.apple.driver.AppleUSBTCButtons  240.2
com.apple.driver.AppleUSBTCKeyboard 240.2
com.apple.driver.AppleIRController  325.7
com.apple.AppleFSCompression.AppleFSCompressionTypeDataless 1.0.0d1
com.apple.AppleFSCompression.AppleFSCompressionTypeZlib 1.0.0d1
com.apple.BootCache 35
com.apple.driver.XsanFilter 404
com.apple.driver.AppleUSBHub    650.4.4
com.apple.iokit.IOAHCIBlockStorage  2.4.0
com.apple.driver.AirPort.Brcm4331   700.20.22
com.apple.driver.AppleSDXC  1.4.0
com.apple.iokit.AppleBCM5701Ethernet    3.6.9b9
com.apple.driver.AppleFWOHCI    4.9.9
com.apple.driver.AppleAHCIPort  2.9.5
com.apple.driver.AppleUSBEHCI   650.4.1
com.apple.driver.AppleSmartBatteryManager   161.0.0
com.apple.driver.AppleACPIButtons   2.0
com.apple.driver.AppleRTC   2.0
com.apple.driver.AppleHPET  1.8
com.apple.driver.AppleSMBIOS    2.0
com.apple.driver.AppleACPIEC    2.0
com.apple.driver.AppleAPIC  1.7
com.apple.driver.AppleIntelCPUPowerManagementClient 216.0.0
com.apple.nke.applicationfirewall   153
com.apple.security.quarantine   3
com.apple.driver.AppleIntelCPUPowerManagement   216.0.0
com.apple.driver.AppleBluetoothHIDKeyboard  170.15
com.apple.driver.AppleHIDKeyboard   170.15
com.apple.driver.IOBluetoothHIDDriver   4.2.0f6
com.apple.driver.AppleMultitouchDriver  245.13
com.apple.kext.triggers 1.0
com.apple.iokit.IOSCSIArchitectureModelFamily   3.6.0
com.apple.iokit.IOSerialFamily  10.0.7
com.apple.driver.DspFuncLib 2.5.2fc2
com.apple.vecLib.kext   1.0.0
com.apple.iokit.IOBluetoothHostControllerUSBTransport   4.2.0f6
com.apple.iokit.IOAcceleratorFamily 98.7.1
com.apple.iokit.IOFireWireIP    2.2.5
com.apple.driver.AppleUSBAudio  2.9.3f17
com.apple.kext.AMDSupport   1.1.4
com.apple.AppleGraphicsDeviceControl    3.4.12
com.apple.iokit.IOSurface   91
com.apple.iokit.IOBluetoothFamily   4.2.0f6
com.apple.iokit.IOAudioFamily   1.9.4fc11
com.apple.kext.OSvKernDSPLib    1.14
com.apple.driver.IOPlatformPluginLegacy 1.0.0
com.apple.driver.AppleSMBusPCI  1.0.12d1
com.apple.driver.AppleGraphicsControl   3.4.12
com.apple.driver.AppleBacklightExpert   1.0.4
com.apple.iokit.IONDRVSupport   2.3.6
com.apple.driver.AppleSMBusController   1.0.11d1
com.apple.driver.AppleHDAController 2.5.2fc2
com.apple.iokit.IOGraphicsFamily    2.3.6
com.apple.iokit.IOHDAFamily 2.5.2fc2
com.apple.driver.AppleSMC   3.1.6d1
com.apple.driver.IOPlatformPluginFamily 5.5.1d27
com.apple.driver.AppleThunderboltPCIUpAdapter   1.4.0
com.apple.driver.AppleThunderboltDPOutAdapter   2.5.0
com.apple.driver.AppleThunderboltDPInAdapter    2.5.0
com.apple.driver.AppleThunderboltDPAdapterFamily    2.5.0
com.apple.driver.AppleThunderboltPCIDownAdapter 1.4.0
com.apple.driver.AppleUSBMultitouch 240.6
com.apple.iokit.IOUSBHIDDriver  650.4.4
com.apple.driver.AppleUSBMergeNub   650.4.0
com.apple.driver.AppleUSBComposite  650.4.0
com.apple.driver.AppleThunderboltNHI    1.9.2
com.apple.iokit.IOThunderboltFamily 2.8.5
com.apple.iokit.IOUSBUserClient 650.4.4
com.apple.iokit.IO80211Family   600.34
com.apple.iokit.IOEthernetAVBController 1.0.3b3
com.apple.driver.mDNSOffloadUserClient  1.0.1b4
com.apple.iokit.IONetworkingFamily  3.2
com.apple.iokit.IOFireWireFamily    4.5.5
com.apple.iokit.IOAHCIFamily    2.6.0
com.apple.iokit.IOUSBFamily 650.4.4
com.apple.driver.AppleEFINVRAM  2.0
com.apple.driver.AppleEFIRuntime    2.0
com.apple.iokit.IOHIDFamily 2.0.0
com.apple.iokit.IOSMBusFamily   1.1
com.apple.security.sandbox  278.10
com.apple.kext.AppleMatch   1.0.0d1
com.apple.security.TMSafetyNet  7
com.apple.driver.AppleKeyStore  2
com.apple.driver.DiskImages 371.1
com.apple.iokit.IOStorageFamily 1.9
com.apple.iokit.IOReportFamily  21
com.apple.driver.AppleFDEKeyStore   28.30
com.apple.driver.AppleACPIPlatform  2.0
com.apple.iokit.IOPCIFamily 2.8
com.apple.iokit.IOACPIFamily    1.4
com.apple.kec.corecrypto    1.0
com.apple.kec.pthread   1

A: It appears you have KeyRemap4MacBook installed which may be causing the problem. If you restart with the [shift] key held down does it make a difference?
Holding the [shift] key down at startup until you get to the login screen and see 'Safe Boot' at the login window prevents 3rd party extensions from loading which will help you determine if it's the KeyRemap4MacBook extension that's causing the problem.
More on Safe Boot here: http://support.apple.com/kb/HT1564
I would hazard a guess that you updated the OS to 10.9 without updating KeyRemap4MacBook to a Mavericks compatible version.
I looked again, you appear to be running v 9.0 which is the latest version. My guess then would be a messed up preference file or cache.
~W


text:
Q: Validating form fields in Blazor Serverside manually with errors I need to choose when to validate certain model fields on a Blazor component, specifically on submission.
So, I need to figure out how to manually validate model values so that I can use the built in error handlers to handle displaying the errors.
Ex:
If you choose RadioValue: type A
    only validate Textfield 1,
    do not validate Textfield 2, Textfield 3
If you choose RadioValue: type B
    validate Textfield 1, Textfield 2, and Textfield 3
If you choose RadioValue: type C
    validate no fields

Any fields not being validated are being set behind the scenes on submission.
Extra notes:

*

*Using custom Radio input components, since MS doesn't provide them.
They do however have an example of one in their docs, so mine is
essentially a clone of that.

*I've tried an event listener with OnFieldsChanged to get the fields
but I have no way of
   A) Validating a specific model
   B) Ensuring an error message is associated with that model, and works with the ValidationMessage component.

*It seems I can only check if eveything is valid using the EditContext.Validate() but I can't choose what to validate.

*Also if I could validate with and without attributes, that would
makes things easier.
MS' version of validation on a separate server, I'd prefer the same app, yet they don't explain how they validate the values and return an error.
<EditForm EditContext="@_editContext" OnSubmit="@HandleSubmit">

    ...

    <button type="submit">Submit</button>
</EditForm>

@code {
    private Starship _starship = new Starship();
    private EditContext _editContext;

    protected override void OnInitialized()
    {
        _editContext = new EditContext(_starship);
    }

    private async Task HandleSubmit()
    {
        var isValid = _editContext.Validate() &&
            await ServerValidate(_editContext);

        if (isValid)
        {
            ...
        }
        else
        {
            ...
        }
    }

    private async Task<bool> ServerValidate(EditContext editContext)
    {
        var serverChecksValid = ...

        return serverChecksValid;
    }
}

I'll get an example of my code soon to provide more context, but I'm hoping that maybe it can be solved without it.


text:
Q: Seach two columns together in a single search column I am using filterrifc gem in my rails app for adding filters to the index list.I have a users table with firstname, lastname and middlename as the field. What I am trying to do is search through all these column in a single search column. The issue I am facing is:
 When I am search for Jimmy then I get a list of all Jimmys in firstname, lastname and middlename. But When I try search for specific Jimmy Wilson it doesnt work. It still just shows Jimmys not the specific Jimmy Wilson. Please help me find the issue.
user.rb
scope :search_name, lambda { |query|
    return nil  if query.blank?

    terms = query.downcase.split(/\s+/)

    terms = terms.map { |e|
      ('%' + e + '%').gsub(/%+/, '%')
    }

    num_or_conds = 3
    where(
      terms.map { |term|
        "(LOWER(users.lastname) LIKE ?) OR (LOWER(users.firstname) LIKE ?) OR (LOWER(users.middlename) LIKE ?)"
      }.join(' AND '),
      *terms.map { |e| [e] * num_or_conds }.flatten
    )
  }

A: AND has higher precedence than OR therefore you have to change where you add parentheses:
where(
  terms.map { |term|
    "(LOWER(users.lastname) LIKE ? OR LOWER(users.firstname) LIKE ? OR LOWER(users.middlename) LIKE ?)"
  }.join(' AND '),
  *terms.map { |e| [e] * num_or_conds }.flatten
)


text:
Q: Sonos event subscription without cloud service to receive events I'm trying to wrap my head around how to subscribe to events in the new Sonos API for an iOS app.
It seems like a cloud service is needed to receive events from the Sonos Cloud.
As described here:

*

*[Subscribing to events with Sonos API

*[https://developer.sonos.com/build/direct-control/connect]
Is there any way for an iOS app to subscribe to events (volume and grouping change) without having to run a cloud service?
If not, any features based on event subscriptions will not be able to work if there is trouble connecting to the cloud for whatever reason.

A: No, there's no way to run without a cloud service. You must have a reliable cloud service for events and subscriptions.

A: Each device also has a super fast / local / undocumented, UPNP service that also supports events.
this answer should give you some pointers on how to get it working in node.
In a nutshell:

*

*Setup an http endpoint on the device (not sure how that works in Swift)

*Tell (in node) the speaker to start sending events for a specific service

*Handle the received XML events.

Sample event from RenderingControlService (yes it has nested encoded xml in the <LastChange> property):
<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0"><e:property><LastChange><Event xmlns="urn:schemas-upnp-org:metadata-1-0/RCS/"><InstanceID val="0"><Volume channel="Master" val="15"/><Volume channel="LF" val="100"/><Volume channel="RF" val="100"/><Mute channel="Master" val="0"/><Mute channel="LF" val="0"/><Mute channel="RF" val="0"/><Bass val="0"/><Treble val="0"/><Loudness channel="Master" val="1"/><OutputFixed val="0"/><HeadphoneConnected val="0"/><SpeakerSize val="3"/><SubGain val="0"/><SubCrossover val="0"/><SubPolarity val="0"/><SubEnabled val="1"/><SonarEnabled val="1"/><SonarCalibrationAvailable val="1"/><PresetNameList val="FactoryDefaults"/></InstanceID></Event></LastChange></e:property></e:propertyset>


text:
Q: Expected output of a addition generator I'm confused as to the expected output of the following algorithm (this is all the information provided):

Consider the following small algorithm X:

*

*If Algorithm X is called with input n=8, that is X(8), what will be the output?

*How many iterations occur of the loop for the general value of n?

Algorithm X(n)
// Input n is an integer
Start
    Initialise i to 1
    While (i ≤ n) do
        Report i
        Increment i by 2
    End while
End

I Interpreted this: to be a pre-test loop, where (i ≤ n) is checked before iteration and that it is not a generator type algorithm.
With my answers being:

*

*An output of 1

*Once for i ≤ n (assuming report i terminates the function) and zero times otherwise

And the actual answers being:

*

*1, 3, 5, 7, 9

*floor(n / 2) + 1

I can see my mistake guessing that the function terminates at report i (it clearly doesn't), it must be some sort of generator.
But I don't understand how 9 is returned?
This is obviously against the condition (9 ≤ 8). I was told "this was because this loop is post-test". But this doesn't seem very intuitive from the while (cond) do {block} syntax. And it doesn't seem correct in practice as (9 ≤ 8) evaluated before or after the loop still returns false.
Should't it be structured as do {block} while (cond) (to be considered post-test)? and stop yielding values after 7?
So:

*

*How is 9 returned? i.e, how does the loop continue from the condition (9 ≤ 8)

*Why is while (cond) do {block} syntax considered pre-test?

Edit:
Wouldn't 2 equal floor((x + 1)/2) for x >= 0 | 0 otherwise ?


text:
Q: How to display a component or not in a view without using many lines of code I have seen many examples but I still believe that there can be an easier way without the need to include code in each component that is created. My idea is not to show 2 components in my login, but in the rest of my components, yes.
app.component.html

<menu></menu>
<router-outlet></router-outlet>
<footer_component></footer_component>

A: If you do not want to render all the components in the app.component.html , you could use the *ngIf directive with condition
<menu *ngIf="condition"></menu>
<router-outlet></router-outlet>
<footer_component *ngIf="condition"></footer_component>


text:
Q: netbeans using terminal window
Above is the image from netbeans terminal window. I want to use it to check the version of nodeJS.
Problem is when i click on the computer icon(single) to use the terminal so I can type it just refresh.

It becomes like above then after 1 sec returns to original state. I cant type anything on it

A:
You must cgwin in order to resolve your issue here is link  cgwin


text:
Q: Thresholds for top tags in Careers too high: introduce vote for exceptions I'm active in one of the major programming languages in engineering: Matlab and its important toolbox Simulink. Like other tags, which are not directly involved in software development, e.g. R and LabView, they are clearly underrepresented here on SO. Basically because SO is not that known amongst engineers, physicists, etc. - but they are of significant importance for their respective fields.
While I really don't care that in tags like C++ even beginners can earn 10k+ reputation in a fairly short time, and in Matlab just a handful of all-time top users can ever achieve that, it bothers me that I'm not able to share my experience in small tags on Careers 2.0.
I understood what are the requirements for a tag to get the ability to be a top tag, and yes Matlab fulfills the requirements. But Simulink does not, though it is very important for future employers.

So for my opinion there should be exceptions. One should be able to vote for, let's call them major language tags, not to follow the rules linked above. On the other hand it should be possible to vote for exclusions of meaningless tags like matrix, I would be able to include.

Actually there shouldn't be restrictions at all, as like for a real CV everybody should be able to decide for themselves, what tags he wants to show. And if anybody wants to state that they are in the "Top 10% of plot", making the employer asking themselves: "What does he want to tell me with that, is he a printer?" - it should be their choice.

A: On the idea of voting (or community moderation of any type for tags on Careers) we're going to deny the request.  That being said, we had a lot of good conversation about this.
We've had it in mind to eventually allow all tags in the top %, and we're also going to score you against the SO universe, not just people on Careers.  A bit of history here as to why we were using only Careers participants is fairly simple, when this feature went live we were still only sending invitations to users with substantially higher rep requirements than we are today.  Everyone was top 10% in 10-20 tags.  It made the feature kind of worthless because it looked like no one stood out.  At that time we had ~25k Careers profiles total, and today we have over 125k searchable profiles.  This change will be coming in the next few weeks.
In the meantime, I'd encourage you to put the Simulink tag on your likes, projects and work experience sections as applicable to make yourself searchable by that technology.


text:
Q: Pass select value to masterpage when it changes I am working with an ASP.NET application for my company. I have a MasterPage with a navbar with options. One of the options displays another page but now the company ask me to pass a parameter to the link. I already find out how to do that (with a property in the Main.Master class). But here is where I have the problem. Tha parameter must be the value from a select element in the main page and it must be saved in the property as soon as the user select one.
I can't call the onChange event because the element isn't an asp component and i mustn't change it because and API (Select2) need it to be a normal html element. But maybe there is a way; if you know please tell me how.
I also try to retrieve the value with JS and pass it from to the master page with ajax, but it didn't work because it only calls a static method and a static method can't use the MasterType reference to change the Main.Master.
So, does exist some way to achieve what I want? Also, sorry for not post code but this is a bit confidential.

A: yes,  you can. Probably the most easy?
Well, in your main menu (likey based on the bootstrap default menu), you can in place of a href link, drop in a menu button (use a link button).
So, say we have this menu markup

Home

About

Contact

            <asp:LinkButton ID="LinkButton1" runat="server" Text="My Test Update" OnClick="LinkButton1_Click"></asp:LinkButton>

So, you have your standard menus - hrefs - they jump without any code.
But, note the last one menu - the My Test Update.
That is a link button. so now you have a event stub in your master page code stub.
You get a menu like this:

And I just dropped in a text box on that page. Like this:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

<%: Title %>.

Your app description page.

Use this area to provide additional information.

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

</asp:Content>

so far, that's as plan jane as it can be.
So, now how can we pick up the text box? Well, you can do this, in master page - code behind:
 Protected Sub LinkButton1_Click(sender As Object, e As EventArgs)

    Dim MyContent As ContentPlaceHolder
    MyContent = Me.FindControl("MainContent")

    Dim MyTextBox As TextBox = MyContent.FindControl("TextBox1")

    Debug.Print("text box value = " & MyTextBox.Text)
    Response.Redirect("~/RadioFun.aspx")

End Sub

So notice how we simply grabbed the text box value. Now how to pass to the next page? Gee, you could use session, or use that value as a parameter in the url that you jump to, or whatever.
So, by replacing the menu navigation from a href to a link button? Well, it looks the same, but now you get a event code behind in your master page code. And as above shows, it quite easy to pull/pluck out the values - at that point, as noted, you can shove that value into session() and then jump to the page that the menu click button (link button) supposed to navigate too. You also cound consider using post-back URL. if you look close, note that Page.PreviousPage is a property of the page. The "previous" page ONLY works on first page load, and ONLY works if the button in question uses a postback URL. So, we could dump the linkbutton event (but still use the link button). Set the post-back url of the link button in the markup. That way, then on page load (only first load - postback = false, then you are free to use page.prevous - and you can use find control against that page like I did as per above - your free to grab "many" controls - not just pass one value.
PostBackURL is thus another way - and I often use PostBackURL in a button dropped on a page - it will navigate to the new page - does so without a event code behind stub, but MORE important using PostBackURL settings for that button/control ALSO enables you to use/get/grab the page.previousPage property - that previous page is in fact the WHOLE previous page that was passed to the server - and you can then grab say values from a WHOLE form or whatever. Just keep in mind that since you have a master page, then the two step process (get the content page, then then a find control on that page is still required).
So either above approaches will work.


text:
Q: jQuery hover function not working on 'BxSlider' loop Hi guys I have a slightly strange problem, and basically on this page:
http://www.carbondelight.co.uk
I have 6 images/products on an infinite loop powered by the BxSlider (http://bxslider.com/), that bit is simple.
I have then coded in jQuery a function that displays the products name when you hover over the respective product image.
The problem I'm having is that the hovering only works on each loop and does not cross over to the next loop. For example if you take a look at the page mentioned earlier you'll notice that the last image in the loop is two back seats of a red car, and if you try and hover between that image and the boat image next to it you will get no change in the product name. But if you move completley into the next loop all of the jQuery works again. And for the life of me I cannot solve this issue. Does anyone have any ideas?
Thank you everyone in advance.
Daniel.
The code is here.
    $('.newp-hover').mouseenter(function() {
    var imgValue = $(this).attr("name");
    //alert(imgValue);
    $('.newp-pre').hide();
    $('.newp-name').hide();
    $('.' + imgValue).fadeIn('slow');
});

and the HTML is here

NEW PRODUCTS

                        <?php

                        for ( $j = 0 ; $j < $rows ; ++$j )
                        {
                            $row = mysql_fetch_row($result3);
                            $sql4 = "SELECT smlImg FROM imageTable WHERE partID='$row[0]'";
                            $product = performQuery($sql4);
                             //displays the product images
                            echo "

";
                        }
                        ?>

        <?php
            //finds the first product name
            $showyou = performQuery($sql5);

        for ( $j = 0 ; $j < $rows5 ; ++$j )
        {
            $row2 = mysql_fetch_row($result5);
            //displays the first product name so a name shows when page is loaded
            echo "
$row2[1]
";
        }

        ?>

A: I've got a feeling that the slider is creating more elements after you do the initial binding of the mouseover event. Since you are binding using .mouseover() only elements that exist at the time you bind will trigger the event.
If the slider is adding more after you bind a live event will fix your issue. Instead of binding to elements existing at the time of binding, it does that plus all future elements matching the selector:
$('.newp-hover').live('mouseenter', function() {
    var imgValue = $(this).attr("name");
    //alert(imgValue);
    $('.newp-pre').hide();
    $('.newp-name').hide();
    $('.' + imgValue).fadeIn('slow');
});

EDIT
.live() is deprecated as of jQuery v1.7. Instead you should use delegate events:
$(documents).on('mouseenter', '.newp-hover', function() {
    var imgValue = $(this).attr("name");
    //alert(imgValue);
    $('.newp-pre').hide();
    $('.newp-name').hide();
    $('.' + imgValue).fadeIn('slow');
});


text:
Q: Total number of subatomic particles in the universe. Are they finite ? assuming any of GR or QM or even ST Total number of subatomic particles in the universe. Are they finite ? assuming any of GR or QM or even ST.

A: It's possible to make an estimate of the amount of baryons in the observable universe. But it's more difficult to make an estimate of anything else. It gets particularly more difficult when you consider things like photons, because they can pop in and out of existance, i.e. the number of photons is not constant. Actually, that is true for all elementary particles, since they are considered as excitations of quantum fields in most modern physics theories. Thus, the number of particles is not constant. But the heavier the particle, the less likely it will pop in existance. And if it's too heavy, it'll decay in lighter, more stable particles. So maybe you'll have something a couple of orders bigger than the amount of baryons, but probably not much larger.
Then, there is dark matter, of which we don't really know much. So, I have no idea if an estimate has been attempted of the amount of dark matter particles. Any estimate will be highly dependent on the theory we have for these particles.
In his book The Emperor's New Mind, Penrose estimates the number of baryons in the observable universe to be of the order of $10^{80}$. This seems to confirm it.

A: By composition
The elementary particles of the Standard Model include
Six "flavors" of quarks: up, down, bottom, top, strange, and charm;
Six types of leptons: electron, electron neutrino, muon, muon neutrino, tau, tau neutrino;
Twelve gauge bosons (force carriers): the photon of electromagnetism, the three W and Z bosons of the weak force, and the eight gluons of the strong force;
The Higgs boson.
Fermions
Fermions are one of the two fundamental classes of particles, the other being bosons. Fermion particles are described by Fermi–Dirac statistics and have quantum numbers described by the Pauli exclusion principle. They include the quarks and leptons, as well as any composite particles consisting of an odd number of these, such as all baryons and many atoms and nuclei.
Quarks are the fundamental constituents of hadrons and interact via the strong interaction. Quarks are the only known carriers of fractional charge, but because they combine in groups of three (baryons) or in pairs of one quark and one antiquark (mesons), only integer charge is observed in nature.
Leptons do not interact via the strong interaction. Their respective antiparticles are the antileptons, which are identical, except that they carry the opposite electric charge and lepton number. The antiparticle of an electron is an antielectron, which is nearly always called a "positron" for historical reasons. There are six leptons in total; the three charged leptons are called "electron-like leptons", while the neutral leptons are called "neutrinos".
Bosons are one of the two fundamental classes of particles, the other being fermions. Bosons are characterized by Bose–Einstein statistics and all have integer spins. Bosons may be either elementary, like photons and gluons, or composite, like mesons.
And there are many more which are hypothetical like graviton , chargino, photino, etc... And many more at least a hundred if you count most fundamental
If you know protons and neutrinos are not fundamental paricles

A: What are particles?  I don't think they are sub-atomic, incredibly tiny billiard balls whizzing around.  If so, then what is the substance of these particles?
My logic - and I could be wrong - is that what we refer to as particles are persistent standing waves in the ocean of electromagnetic radiation in which the entire universe bathes. These incredibly tiny eddies in the EM ocean, when aggregated in vast numbers and in a huge number of permutations and combinations making up the elements we are more familiar with, form the substance and the space of what we perceive and detect as matter, inertia, gravity, space and so on..
I read that there are about 10 to the power 80 particles in the universe.  Seems like a manageable number except that it is far, far greater number than the grains of sand on every beach and in every desert on earth.  And when you dig deep into the atomic structure of each of those grains of sand......you find things like electrons and protons which we detect as wave forms of electromagnetic energy.
Weird isn't it!


text:
Q: My answer is changing with the same code I am a complete python beginner and I am trying to solve this problem :

A number is called triangular if it is the sum of the first n positive
  integers for some n For example, 10 is triangular because 10 = 1+2+3+4
  and 21 is triangular because 21 = 1+2+3+4+5+6. Write a Python program
  to find the smallest 6-digit triangular number. Enter it as your
  answer below.

I have written this program:
n = 0
trinum = 0
while len(str(trinum)) < 6:
    trinum = n*(n+1)/2
    n += 1
print(trinum)

And it only works in the python I have installed on my computer if I say while len(str(trinum)) < 8: but it is supposed to be while len(str(trinum)) < 6:. So I went to http://www.skulpt.org/ and ran my code there and it gave me the right answer with while len(str(trinum)) < 6: like it's supposed to. But it doesn't work with 6 with the python i have installed on my computer. Does anyone have any idea what's going on?

A: In Python 2, the / operator performs integer division when possible: "x divided by y is a remainder b," throwing away the "b" (use the % operator to find "b"). In Python 3, the / operator always performs float division: "x divided by y is a.fgh." Get integer division in Python 3 with the // operator.

A: You have two problems here, that combine to give you the wrong answer.
The first problem is that you're using /, which means integer division in Python 2 (and the almost-Python language that Skulpt implements), but float division in Python 3. So, when you run it on your local machine with Python 3, you're going to get floating point numbers.
The second problem is that you're not checking for "under 6 digits" you're checking for "under 6 characters long". For positive integers, those are the same thing, but for floats, say, 1035.5 is only 4 digits, but it's 6 characters. So you exit early.
If you solve either problem, it will work, at least most of the time. But you really should solve both.
So:
n = 0
trinum = 0
while trinum < 10**6: # note comparing numbers, not string length
    trinum = n*(n+1)//2 # note // instead of /
    n += 1
print(trinum)

The first problem is fixed by using //, which always means integer division, instead of /, which means different things in different Python versions.
The second problem is fixed by comparing the number as a number to 10**6 (that is, 10 to the 6th power, which means 1 with 6 zeros, or 1000000) instead of comparing its length as a string to 6.

A: Taking Malik Brahimi's answer further:
from itertools import *
print(next(dropwhile(lambda n: n <= 99999, accumulate(count(1))))

*

*count(1) is all the numbers from 1 to infinity.

*accumulate(count(1)) is all the running totals of those numbers.

*dropwhile(…) is skipping the initial running totals until we reach 100000, then all the rest of them.

*next(…) is the next one after the ones we skipped.

Of course you could argue that a 1-liner that takes 4 lines to describe to a novice isn't as good as a 4-liner that doesn't need any explanation. :)
(Also, the dropwhile is a bit ugly. Most uses of it in Python are. In a language like Haskell, where you can write that predicate with operator sectioning instead of a lambda, like (<= 99999), it's a different story.)

A: Short Answer
In Python 3, division is always floating point division. So on the first pass you get something like str(trinum) == '0.5'. Which isn't what you want.
You're looking for integer division. The operator for that is //.
Long Answer
The division operator changed in Python 2.x to 3.x. Previously, the type of the result was dependent on the arguments. So 1/2 does integer division, but 1./2 does floating point division.
To clean this up, a new operator was introduced: //. This operator will always do integer division.
So in Python 3.x, this expression (4 * 5)/2 is equal to 10.0. Note that this number is less than 100, but it has 4 characters in it.
If instead, we did (4*5)//2, we would get the integer 10 back. Which would allow your condition to hold true.

A: The division method in Py2.x and 3.x is different - so that is probably why you had issues.
Just another suggestion - which doesn't deal with divisions and lengths - so less buggy in general. Plus addition is addition anywhere.
trinum = 0
idx =0

while trinum < 99999: #largest 5 digit number
    idx += 1
    trinum += idx

print trinum

A: import itertools # to get the count function
n, c = 0, itertools.count(1) # start at zero

while n <= 99999:
    n = n + next(c)


text:
Q: Keyboard and fan problems after battery replacement in 2017 MBP I just replaced the battery in my 2017 Macbook Pro (no fancy bar above the keyboard). I used the Egoway battery for A1708, which is the model number shown on the bottom of the computer. I had read some reviews on battery replacement, and made sure to carefully follow the instructions step by step. While not a pro, I've replaced batteries and screens on phones and computers before. This was not a brute force attack on the battery. I made sure that cables and connectors were seated securely. Anyway, I got everything put back together and now there are a few main issues.
First, the keyboard doesn't work. Other than the power button, no keys function. A USB keyboard will work. The trackpad works fine.
Second, the fan runs whenever the computer is on.
Third, the computer is running slow from startup. The black screen with white apple logo and white loading bar is taking several minutes before switching to the user login screen. Even once the computer is on, there's a noticeable lag to it.
I have read this really great thread on a 2015 MBP with a similar issue. But, my trackpad works fine. I've tried resetting the SMC two ways - by holding down keys and by disconnecting the battery and holding down the power key. I don't think either method worked, or if it did it failed to address the problem.
I have read that others suggest replacing the keyboard or the trackpad. But my trackpad works! And given the age of the computer, I'm hesitant to throw too much more money at it right now.
Any suggestions? I'd greatly appreciate it!