text:
Q: Python - BeautifulSoup - Iterating through findall by specific elements in list I'm pretty new to the world of web scraping so am looking for some guidance to an issue I've been trying to resolve for a few hours.
I'm trying to loop through a table looking structure (it's not an actual table though) and have used findall to bring back all the details of a certain tag.
The challenge I have is that every element of the "table" has the same class name "final-leaderboard__content" so I'm left with a huge list so I want to iterate through and retrieve the details for so I can create a csv/excel with the details.  This is the code below

from bs4 import BeautifulSoup
import requests

TournamentURL = "https://www.theopen.com/previous-opens/19th-open-st-andrews-1879/"
TournamentResponse = requests.get(TournamentURL)
TournamentData = TournamentResponse.text
TournamentSoup = BeautifulSoup(TournamentData, 'html.parser')

RowContents = TournamentSoup.findAll("div", {"class": "final-leaderboard__content"})
     for RowContent in RowContents:

The result is something like this and I can't work out the best way without there being any explicit tag/id to know that item 0,8,16 etc is the Player Name, item 1,9,17 is the Finish etc etc
[0] - Name
[1] - Finish
[2] - R1
[3] - R2
[4] - R3
[5] - R4
[6] - Total
[7] - Par
[8] - Name (The second Name)
[9] - Finish (The second Finish)
etc
etc

I've tried splice, modulo and various other variants of the same but can't seem to work it out.

A: You can use the fact that this is indeed a kind of tabular data and grab all divs that represent a row, split it by a number of columns, and there's your data:
import requests
from bs4 import BeautifulSoup
from tabulate import tabulate

url = "https://www.theopen.com/previous-opens/19th-open-st-andrews-1879/#leaderboard"
page = requests.get(url).content

leaderboard = BeautifulSoup(page, "html.parser").find_all("div", {"class": "final-leaderboard__content"})

column_count = 8
split_by_columns = [
    leaderboard[i:i+column_count] for i in range(0, len(leaderboard), column_count)
]

table = [[i.getText(strip=True) for i in row] for row in split_by_columns]
print(tabulate(table[1:], headers=table[0]))

Output:
Name                             Finish    R1    R2  R3    R4      Total  Par
-----------------------------  --------  ----  ----  ----  ----  -------  -----
Jamie ANDERSONChampion Golfer         1    84    85  -     -         169  M/C
Andrew KIRKALDY                       2    86    86  -     -         172  M/C
Jamie ALLAN                           2    88    84  -     -         172  M/C
George  PAXTON                        4    89    85  -     -         174  M/C
Tom KIDD                              5    87    88  -     -         175  M/C
Bob FERGUSON                          6    89    87  -     -         176  M/C
J.O.F. MORRIS                         7    92    87  -     -         179  M/C
Jack KIRKALDY                         8    92    89  -     -         181  M/C
James RENNIE                          8    93    88  -     -         181  M/C
Willie FERNIE                         8    92    89  -     -         181  M/C
David AYTON                          11    95    89  -     -         184  M/C
Henry LAMB                           11    91    93  -     -         184  M/C
Tom ARUNDEL                          11    95    89  -     -         184  M/C
Tom MORRIS SR                        14    92    93  -     -         185  M/C
William DOLEMAN                      14    91    94  -     -         185  M/C
Robert KINSMAN                       14    88    97  -     -         185  M/C
Bob MARTIN                           17    93    93  -     -         186  M/C
Ben SAYERS                           18    92    95  -     -         187  M/C
David ANDERSON SR                    19    94    94  -     -         188  M/C
David CORSTORPHINE                   20    93    96  -     -         189  M/C
Tom DUNN                             20    90    99  -     -         189  M/C
Peter PAXTON                         20    99    90  -     -         189  M/C
[A] SMITH                            20    94    95  -     -         189  M/C
D. GRANT                             20    95    94  -     -         189  M/C
Bob DOW                              20    95    94  -     -         189  M/C
Walter GOURLAY                       20    92    97  -     -         189  M/C
A.W. SMITH                           27    91    99  -     -         190  M/C
Douglas Argyll ROBERTSON             27    97    93  -     -         190  M/C
Robert ARMIT                         29    95    96  -     -         191  M/C
George  STRATH                       29    97    94  -     -         191  M/C
J.H. BLACKWELL                       31    96    96  -     -         192  M/C
Tom MANZIE                           32    96    97  -     -         193  M/C
George LOWE                          33    94   100  -     -         194  M/C
G. HONEYMAN                          33    97    97  -     -         194  M/C
James FENTON                         35    99    97  -     -         196  M/C
Robert TAIT                          35    99    97  -     -         196  M/C
Bob KIRK                             37    99    98  -     -         197  M/C
Rev. D. LUNDIE                       37    98    99  -     -         197  M/C
Fitz BOOTHBY                         39    96   102  -     -         198  M/C
J. Thomson WHITE                     40   102    99  -     -         201  M/C
James KIRK                           41   105    97  -     -         202  M/C
W.H. GOFF                            42   105    99  -     -         204  M/C

A: import requests
from bs4 import BeautifulSoup

def parse_row(row):
    for div in row.find_all("div", {"class": "final-leaderboard__content"}):
        yield div.text.strip().replace('\n', ' ')

url = "https://www.theopen.com/previous-opens/19th-open-st-andrews-1879/#leaderboard"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

table = soup.find("div", {"class": "final-leaderboard__table"})
rows = table.find_all('div', {'class':"final-leaderboard__row"})
header = list(parse_row(rows[0]))
for row in rows[1:]:
    print(dict(zip(header, list(parse_row(row)))))

output
{'Name': 'Jamie ANDERSON     Champion Golfer', 'Finish': '1', 'R1': '84', 'R2': '85', 'R3': '-', 'R4': '-', 'Total': '169', 'Par': 'M/C'}
{'Name': 'Andrew KIRKALDY', 'Finish': '2', 'R1': '86', 'R2': '86', 'R3': '-', 'R4': '-', 'Total': '172', 'Par': 'M/C'}
{'Name': 'Jamie ALLAN', 'Finish': '2', 'R1': '88', 'R2': '84', 'R3': '-', 'R4': '-', 'Total': '172', 'Par': 'M/C'}
{'Name': 'George  PAXTON', 'Finish': '4', 'R1': '89', 'R2': '85', 'R3': '-', 'R4': '-', 'Total': '174', 'Par': 'M/C'}
{'Name': 'Tom KIDD', 'Finish': '5', 'R1': '87', 'R2': '88', 'R3': '-', 'R4': '-', 'Total': '175', 'Par': 'M/C'}
{'Name': 'Bob FERGUSON', 'Finish': '6', 'R1': '89', 'R2': '87', 'R3': '-', 'R4': '-', 'Total': '176', 'Par': 'M/C'}
{'Name': 'J.O.F. MORRIS', 'Finish': '7', 'R1': '92', 'R2': '87', 'R3': '-', 'R4': '-', 'Total': '179', 'Par': 'M/C'}
{'Name': 'Jack KIRKALDY', 'Finish': '8', 'R1': '92', 'R2': '89', 'R3': '-', 'R4': '-', 'Total': '181', 'Par': 'M/C'}
{'Name': 'James RENNIE', 'Finish': '8', 'R1': '93', 'R2': '88', 'R3': '-', 'R4': '-', 'Total': '181', 'Par': 'M/C'}
{'Name': 'Willie FERNIE', 'Finish': '8', 'R1': '92', 'R2': '89', 'R3': '-', 'R4': '-', 'Total': '181', 'Par': 'M/C'}
{'Name': 'David AYTON', 'Finish': '11', 'R1': '95', 'R2': '89', 'R3': '-', 'R4': '-', 'Total': '184', 'Par': 'M/C'}
{'Name': 'Henry LAMB', 'Finish': '11', 'R1': '91', 'R2': '93', 'R3': '-', 'R4': '-', 'Total': '184', 'Par': 'M/C'}
{'Name': 'Tom ARUNDEL', 'Finish': '11', 'R1': '95', 'R2': '89', 'R3': '-', 'R4': '-', 'Total': '184', 'Par': 'M/C'}
{'Name': 'Tom MORRIS SR', 'Finish': '14', 'R1': '92', 'R2': '93', 'R3': '-', 'R4': '-', 'Total': '185', 'Par': 'M/C'}
{'Name': 'William DOLEMAN', 'Finish': '14', 'R1': '91', 'R2': '94', 'R3': '-', 'R4': '-', 'Total': '185', 'Par': 'M/C'}
{'Name': 'Robert KINSMAN', 'Finish': '14', 'R1': '88', 'R2': '97', 'R3': '-', 'R4': '-', 'Total': '185', 'Par': 'M/C'}
{'Name': 'Bob MARTIN', 'Finish': '17', 'R1': '93', 'R2': '93', 'R3': '-', 'R4': '-', 'Total': '186', 'Par': 'M/C'}
{'Name': 'Ben SAYERS', 'Finish': '18', 'R1': '92', 'R2': '95', 'R3': '-', 'R4': '-', 'Total': '187', 'Par': 'M/C'}
{'Name': 'David ANDERSON SR', 'Finish': '19', 'R1': '94', 'R2': '94', 'R3': '-', 'R4': '-', 'Total': '188', 'Par': 'M/C'}
{'Name': 'David CORSTORPHINE', 'Finish': '20', 'R1': '93', 'R2': '96', 'R3': '-', 'R4': '-', 'Total': '189', 'Par': 'M/C'}
{'Name': 'Tom DUNN', 'Finish': '20', 'R1': '90', 'R2': '99', 'R3': '-', 'R4': '-', 'Total': '189', 'Par': 'M/C'}
{'Name': 'Peter PAXTON', 'Finish': '20', 'R1': '99', 'R2': '90', 'R3': '-', 'R4': '-', 'Total': '189', 'Par': 'M/C'}
{'Name': '[A] SMITH', 'Finish': '20', 'R1': '94', 'R2': '95', 'R3': '-', 'R4': '-', 'Total': '189', 'Par': 'M/C'}
{'Name': 'D. GRANT', 'Finish': '20', 'R1': '95', 'R2': '94', 'R3': '-', 'R4': '-', 'Total': '189', 'Par': 'M/C'}
{'Name': 'Bob DOW', 'Finish': '20', 'R1': '95', 'R2': '94', 'R3': '-', 'R4': '-', 'Total': '189', 'Par': 'M/C'}
{'Name': 'Walter GOURLAY', 'Finish': '20', 'R1': '92', 'R2': '97', 'R3': '-', 'R4': '-', 'Total': '189', 'Par': 'M/C'}
{'Name': 'A.W. SMITH', 'Finish': '27', 'R1': '91', 'R2': '99', 'R3': '-', 'R4': '-', 'Total': '190', 'Par': 'M/C'}
{'Name': 'Douglas Argyll ROBERTSON', 'Finish': '27', 'R1': '97', 'R2': '93', 'R3': '-', 'R4': '-', 'Total': '190', 'Par': 'M/C'}
{'Name': 'Robert ARMIT', 'Finish': '29', 'R1': '95', 'R2': '96', 'R3': '-', 'R4': '-', 'Total': '191', 'Par': 'M/C'}
{'Name': 'George  STRATH', 'Finish': '29', 'R1': '97', 'R2': '94', 'R3': '-', 'R4': '-', 'Total': '191', 'Par': 'M/C'}
{'Name': 'J.H. BLACKWELL', 'Finish': '31', 'R1': '96', 'R2': '96', 'R3': '-', 'R4': '-', 'Total': '192', 'Par': 'M/C'}
{'Name': 'Tom MANZIE', 'Finish': '32', 'R1': '96', 'R2': '97', 'R3': '-', 'R4': '-', 'Total': '193', 'Par': 'M/C'}
{'Name': 'George LOWE', 'Finish': '33', 'R1': '94', 'R2': '100', 'R3': '-', 'R4': '-', 'Total': '194', 'Par': 'M/C'}
{'Name': 'G. HONEYMAN', 'Finish': '33', 'R1': '97', 'R2': '97', 'R3': '-', 'R4': '-', 'Total': '194', 'Par': 'M/C'}
{'Name': 'James FENTON', 'Finish': '35', 'R1': '99', 'R2': '97', 'R3': '-', 'R4': '-', 'Total': '196', 'Par': 'M/C'}
{'Name': 'Robert TAIT', 'Finish': '35', 'R1': '99', 'R2': '97', 'R3': '-', 'R4': '-', 'Total': '196', 'Par': 'M/C'}
{'Name': 'Bob KIRK', 'Finish': '37', 'R1': '99', 'R2': '98', 'R3': '-', 'R4': '-', 'Total': '197', 'Par': 'M/C'}
{'Name': 'Rev. D. LUNDIE', 'Finish': '37', 'R1': '98', 'R2': '99', 'R3': '-', 'R4': '-', 'Total': '197', 'Par': 'M/C'}
{'Name': 'Fitz BOOTHBY', 'Finish': '39', 'R1': '96', 'R2': '102', 'R3': '-', 'R4': '-', 'Total': '198', 'Par': 'M/C'}
{'Name': 'J. Thomson WHITE', 'Finish': '40', 'R1': '102', 'R2': '99', 'R3': '-', 'R4': '-', 'Total': '201', 'Par': 'M/C'}
{'Name': 'James KIRK', 'Finish': '41', 'R1': '105', 'R2': '97', 'R3': '-', 'R4': '-', 'Total': '202', 'Par': 'M/C'}
{'Name': 'W.H. GOFF', 'Finish': '42', 'R1': '105', 'R2': '99', 'R3': '-', 'R4': '-', 'Total': '204', 'Par': 'M/C'}

of course, instead of dict you may use other data structure like namedtuple

A: Another way is to create a dictionary , enumerate through your Rowcontents and update the dictionary with key as enumerated index(i) mod 8 (i%8) and value "the text"
RowContents = TournamentSoup.findAll("div", {"class": "final-leaderboard__content"})
d={}
for i, RowContent in enumerate(RowContents):
    key = (i)%8
    d.setdefault(key, []).append(' '.join(RowContent.text.strip().split()))

>>> d
{
   0: ['Name','Jamie ANDERSON Champion Golfer','Andrew KIRKALDY','Jamie ALLAN',....]
   1: ['Finish','1','2','2','4',....]
   2: ['R1','84','86','88','89','87',....]
   .......
  7: ['Par','M/C','M/C','M/C','M/C','M/C',.....]

if you can use pandas
df = pd.DataFrame(d).rename(columns=df.iloc[0]).drop(df.index[0])
>>> print(df)

                              Name Finish   R1   R2 R3 R4 Total  Par
1   Jamie ANDERSON Champion Golfer      1   84   85  -  -   169  M/C
2                  Andrew KIRKALDY      2   86   86  -  -   172  M/C
3                      Jamie ALLAN      2   88   84  -  -   172  M/C
4                    George PAXTON      4   89   85  -  -   174  M/C
5                         Tom KIDD      5   87   88  -  -   175  M/C
6                     Bob FERGUSON      6   89   87  -  -   176  M/C
7                    J.O.F. MORRIS      7   92   87  -  -   179  M/C

to save a dataframe to csv use pandas.to_csv()
df.to_csv('yourfile.csv', index=False)


text:
Q: dynamically switching 'background-image' doesn't work in IE I'm dynamically switching a div's background-image with the jquery bit below. Works just fine in FF, but turns out in IE it does not. Any ideas why? Does IE not reload the image if a css property changed? Any pointers would be appreciated.
$(function(){
   $('.header').each(function(){
      $(this).hover(function(){
         $('#headertab').css('background-image','url(/tab_'+$(this).attr('href').split('path=')[1]+'.gif');
      });
   });
});

A: Try setting backgroundImage instead of background-image.
CSS attributes, when accessed via Javascript, traditionally use camelCase instead of dashes, to avoid questions of syntax. (element.style.background-image looks like you're doing subtraction.) Firefox is probably progressive enough to allow the dashes as well, but IE... it would seem not.

A: I had an issue where an element had a predefined style-attribute setting a background image:

The background-image rule could be changed using jQuery but the image would not update.
The solution was to first remove the attribute and then add the attribute again with the new value:
jQuery('#bg-element').removeAttr('style').attr('style', 'background-image: url(bar.jpg);');

A: You're setting CSS properties incorrectly with jquery. You can read here how to reference the names of the properties (camelcased, with no hyphen).
$("#element").css({"backgroundImage":"url(/images/image.jpg)",....etc})

A: if you have the images paths set inside the VALUE of a SELECT listbox element, you could probably use:
<select onchange="document.getElementById('background').style.backgroundImage='url("'+this.value+'")';">

A: I usually use class names to handle this sort of thing:
$(function(){
   $('.header').each(function(){
      $(this).hover( function () {
        $('#headertab').addClass('dynamic-background-image-class');
      }, function () {
        $('#headertab').removeClass('dynamic-background-image-class');
      });
   });
});

css:
.dynamic-background-image-class {
  background: transparent url(/path/to/image.png) 0 0 no-repeat;
}

I don't know if this would help your situation as your header image names are based on the url. One of the benefits is the image is pulled and cached when the css file is requested by the client.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unity3d why doesn't changing an object's localposition by 1 correspond to moving one grid division? I opened the example standard assets project after reading about half the unity documentation to try to get a feel for things as I read through the documentation.
However, I'm very confused about positioning things in unity.
I am looking at the 2d character scene in the project, and when i move the platforms' Transform components' Local position property by 1, it doesn't seem to move one unit on the grid that unity displays. What determines unity's grid size?
Platform 04x01 is located at position x = 45 y = 7.5002 z = 0 in the example project in scene 2dplatformer.
in the screenshot here:
http://postimg.org/image/inhbr3b47/
it is located within a blue grid.
When i change x to 46, I expect the platform to move over by 1 according to the grid.
Instead it looks like this: http://postimg.org/image/4ps2rcvgv/
Why could this occur?

A: After looking at your images, the problem that is occuring is that you are in debugging mode. To exit debugging mode do the following:
In the inspector, in the top right corner you will see a tiny drop down menu next to a lock. Click the dropdown menu and select normal. Now the Transform will have Position, Rotation, and Scale, rather than local versions of these.
Now in Normal mode, the grid squares will be ten by ten unit squares. When I say unit, I am refering to the units used in the scale in Transform.
To put this into perspective, say I make a square and unity and set its scale values all to 10, by doing this our cube will now have a base that is 10 by 10 units in size and will therefore take up the entire grid scale.
Now instead say I dont change the scale, and keep it at unity's default values of 1. We now have a cube with a base that is 1 by 1 units in size. So in order to move it from one side of the grid square to the other, we must move the object by 10 units in the x or y transform.
So in short, to fix your problem, follow my steps to exit debugging mode, and from here keep in mind that the grid in unity is composed of 10 by 10 unity squares. However, if in your game you want to make your objects locked in a grid, you will need to set this up on your own as unity's grid view is only meant for reference and has no functionality as for grid locking objects.


text:
Q: How many different arrangements are possible if $3$ letters are randomly selected from the word CHALLENGE and arranged into 'words'? How many different arrangements are possible if $3$ letters are randomly selected from the word CHALLENGE and arranged into 'words'?
$$\frac{9P3}{2! \cdot 2!} = 126$$
but the answer is $246$.

A: Consider the words with all different letters: select from CHALENG:
$${7\choose 3}\cdot 3!=210.$$
Consider the words with two letters L: select from CHAENG:
$${6\choose 1}{3\choose 1}=18.$$
Consider the words with two letters E: select from CHALNG:
$${6\choose 1}{3\choose 1}=18.$$
Add up to get $246$.

A: The given word is
$$CHALLENGE $$
we can write it as $$CHALLEENG$$
where there are total 9 words and 7 distinct words
We can think of this problem as- there are 9 balls in a box A out of which there are 7 balls of different colur and two balls which share the same colour out of 7 balls.
{R,B,G,Y,V,I,O,R,G}.Now in how many ways can we take out 3 balls and keep it in another box B ?
CASE $1$
We can keep balls of all different colours in the box B.
.ie
$$7P3$$
$${7\choose 3}\cdot 3!=210 ways.$$
CASE $2$
Say box B has 3 different holes in which 3 balls can be kept
We can keep 2 balls of same colour different colours in two holes and in the 3rd hole we can keep 6 different balls.
Therefore in the third hole 6 different balls can be kept.which can we again be done in three places
.ie
$$6*3$$
$$=18 ways.$$
Now case two repeates itself of the ball of another colour therefore again 18 ways
therefore total number of ways of doing so-$$18+18+210=246ways.$$
PS-I know that the solution to the problem was already given ,but i thought of doing it in another way.


text:
Q: Linker error when try to call ObjC method from C Actually, I'm a Unity developer and I know nothing about XCode and Objective C. But I have to use ObjC library for some integration and call this function from Unity. So I import that library to created XCode project and write some wrapper code between Unity and XCode. When I try to call empty function, it works for me. But when i try to write ObjC method in C file it causes linker error and I have no idea what's wrong with it. So, here's the deal:
In Unity MonoBehaviour.cs:
[DllImport("__Internal")]
public static extern void startWithAPIKey(string apiKey);
...
startWithAPIKey(apiKey);

In XCode Wrapper.h:
@interface IOSYandexMetricaWrapper : NSObject
@end

In XCode Wrapper.m:
#import "YandexMobileMetrica.h" //library header
#import "IOSYandexMetricaWrapper.h"

void startWithAPIKey(char *apiKey) {
    //method that i want to call
    [YMMYandexMetrica startWithAPIKey:(NSString *)apiKey];
}

So it compiles, but linker says something like this:
Undefined symbols for architecture armv7: "_OBJC_CLASS_$_YMMYandexMetrica", referenced from: objc-class-ref in IOSYandexMetricaWrapper.o
Someone can help me with my problem?

A: This can sometimes be caused because YMMYandexMetrica hasn't been included in your target.
To tell if it is included in your target, press on the YMMYandexMetrica.m file in the Navigator and open the Utilities side bar. You should see a subsection called "Target Membership" - the tickbox beside your project's name should be ticked.
Some more details about this issue can be here:
http://williamboles.me/_objc_class__-errors/
(It's a little out of date as it's for Xcode 4 but I think still relevant for your issue)

A: Add YMMYandexMetrica to your projects build phase setting :)


text:
Q: Qserialport on Beaglebone Black I'm running a BBB with debian, kernel 3.8. I've got Qt up and running, I can do a simple hello world program on it. Everything works great.
My host machine is running Ubuntu 12.04 32 bit.
I'm trying to install the qserialport library, but its giving me a lot of grief. I've tried following the wiki here.
Running from the command line seems promising, but I'm not sure how to resolve the error that I'm seeing. When I've run the qmake successfully, but when I run the make command I run into the error: arm-linux-bnueabihf/bin/ld: cannot find -ludev.
I have libudev-dev installed in my host computer, so I don't think this is the problem.
Any thoughts on what might be the problem or how to fix it?
Thanks in advance.

A: So I figured out how to do this with a shout out to Sam in the comments above.
I cheated a little and copied the libraries that I needed from the Beaglebone Black to my host computer and put them in the folder that contained all cross-compiled Qt libraries. As I found out later on, I also would need to to this with the tslib libraries as well (I have enabled Qt with touchscreen support).
These steps allowed me to at least complete the make command of the serialport library.
I then used the sudo make install command to install the library, with no problems there.
Running a program with the serial port library was also causing problems. I cheated again and used scp -r /opt/qt-arm/lib root@beagleboneblacknetworkip:/usr/ to copy my entire cross-compiled qt library from my host machine over to the Beaglebone Black. Copying that directory over got me up and running.


text:
Q: Seeding data into a new microservice I've been reading though Architecture for containerized .NET applications  book, and I have a question about replicating data from from service into another:

And finally (and this is where most of the issues arise when building
microservices), if your initial  microservice needs data that's
originally owned by other microservices, do not rely on making
synchronous requests for that data. Instead, replicate or propagate
that data (only the attributes you  need) into the initial service's
database by using eventual consistency (typically by using integration
events, as explained in upcoming sections).

If we deploy two services at the same time, I understand how we can replicate a subset of the data from one service into another using events, but what happens if the second service (that needs to replicate data) is deployed at a later stage when the first service already has data in its database? How can the new service "catch up" and get in sync?
Is it reasonable for the new service to use a synchronous call the first time it starts, and seed its own database? Should there be some sort of script that runs and reads from database A and writes to database B?

A: From your quote

do not rely on making synchronous requests for that data. Instead, replicate or propagate that data (only the attributes you need) into the initial service's database by using eventual consistency

So no, it does not sounds reasonable to do a synchronous big-bang import from one data store into another. At least not if we consider what we are learning from the book. The release of the new service should not depend on data it has no accountability. If the data is already in the data store, then good. If not, it should be confident that at some point it will have it. The whole point of MS is they can appear or disappear at any time within the system's lifespan.
Ideally, the new service gathers data as it arrives from the existing system and saves only the necessary one (besides the one generated by the service itself) even if this data already exists in someone else's database. That's the " data duplication ". Each service might hold data (sometimes only chunks of it) that already exists in other domains (e.g the customer name can be in many databases each of which is managed by a different service).
New services should not be born upon the premise that concrete services already exist. That will couple and drag'em forever at different levels, not only at the technical level.
The autonomy doesn't only involves IPCs (inter-process communication protocols), it also involves the ALM (application lifecycle management). Relying on synchronous calls might lead you to ask another team for a new feature they don't have. Imagine deploying tens or hundreds of services a year. It can impacts everyone's roadmap, making project management unbearable. Leave alone product management.
However, it's reasonable for new services to need (historical) data. This can be achieved in many ways. One could be broadcasting a sort of newServiceRegistered event so existing services can react to this one and push data. How to move this data without direct communication between services is another problem to solve. I guess that's what the book will introduce in sections explaining the integration events.
That's all the theory and it might or might not fit your current needs and expectations.
If you can provide the new service with the required data without involving coupling among services, say by scripts executed once during the release, ETLS, etc, then it's fine. But bear in mind that, as new services appear, more of those scripts are needed and how to generate the scripts for each data store and how to execute'em from environment to environment can be a lot of work and could end up impacting several teams. Releasing a new service is not just deploying something to the wild, there's a whole ceremony around that event. It's not rare that MS dev teams build their own tools to feed and operate the service. If the infrastructure doesn't provide any mechanism, then they have to create it.
The goal is always the same: _to be as autonomous and independent from other services/teams/management as possible.


text:
Q: Grails with ObjectDB Is it possible to use ObjectDB with Grails?
Or in other words, do I have to use Hibernate when i developing applications with grails?

A: Yes it is possible.
I think if you do well formed configuration it works nice

A: yes it is possible.
simply add library to your grails project and use like in java but in my option hibernate in full stack for all simpl


text:
Q: Help with OnTouch I am trying to create a few circles when the user touches, and if they touch again depending where they touch another one would show... but when I use the ontouch event.. it crashes... I am new by the way, how can I fix it?
public class GameView extends View{

    private final float x;
    private final float y;
    private final int r;
    private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public GameView(Context context, float x, float y, int r) {
        super(context);
        mPaint.setColor(0xFFFF0000);
        this.x = x;
        this.y = y;
        this.r = r;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(x, y, r, mPaint);
    }

}
public class GameActivity extends Activity {
/** Called when the activity is first created. */
GameView gm;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    FrameLayout main = (FrameLayout) findViewById(R.id.my_view);

    main.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(final View v, MotionEvent e) {
             final float x = e.getX();
             final float y = e.getY();
              final Handler handler = new Handler()
              {
                public void handleMessage(Message msg) {

                         gm.postInvalidate();

                  }
                };
                Thread graphicThread = new Thread()
                {
                    public void run() {

                        try {

                            //Do the drop
                               FrameLayout flView = (FrameLayout) v;
                              flView.addView(new GameView(getParent(), x,y,25));

                                 Thread.sleep(1000);

                                 handler.sendMessage(handler.obtainMessage());
                            }
                         catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }
                    };
                     boolean isRunning=true;
                    graphicThread.start();
                    return true;

                    }

    });

  }
}

A: It could be anything really, but one thing you never do is instantiate your gm. When you do this
 gm.postInvalidate();

You probably get a nullpointerexception. This isn't enough:
GameView gm;

You need to actually call
gm = new GameView(/*insert stuff here*/);


text:
Q: Centos6... PHP73x provisioning/configuration woes - anyone know why? NOOOB question! I'm running CentOS 6 still - and it seems my installation got glitched, or misconfigured. First of all there were issues getting PHP7.1 in at all (IUS repo was all there was at the time).. Later uninstalled and used REMI 7.3.
This was all pretty delicate, as its a live server. Anyway, got PHP73 in, but the last couple of PHP updates (7.3.9 and 7.3.11)  have been 'hellish' in that they killed the PHP functionality of our main website entirely.
I got the error 'module php7_module is already loaded, skipping' - and with a little scrambling managed to fix it by commenting a line in php.conf as shown:

    #LoadModule php7_module modules/libphp7.so

I think this is what I edited last time an update killed things...
Should I just be deleting the php.conf entirely??
Because I also have a php73-php.conf ... which contains this:

    LoadModule php7_module modules/libphp73.so

I'm wondering if it's safe to delete the other conf file (which seems to get rewritten every time there is a PHP patch!) - this seems logical but I haven't been able to google any clear confirmation of this. Can anyone enlighten me?  TIA!

A:
got the error 'module php7_module is already loaded, skipping'

It looks like your installation is not correct as if you have this message, this mean you really have various module installed. Perhaps the old one from IUS and a newer one from Remi, which have SCL, i.e. version designed for parallel installation.
Edit: according to comment you have both php (mod_php as base package) and php73-php (mod_php as SCL). I recommend the remove the second.
Of course only 1 version of mod_php can be load at the same time.
A list of installed packages will help
rpm -qa php\* | sort

For a proper installation, I recommend you follow the Wizard instructions


text:
Q: Error when using async Azure Text Analytics I am using async on Azure text analytics, and I have been trying to figure out why my code couldn't work. Here is my code.
import os
import asyncio
import pandas as pd
from azure.ai.textanalytics.aio import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

#this is the input list of documents
ace = [{'doc_name': 'doc_1',
        'mention': 'Chris Evans',
        'title': 'Chris Evans',
        'full_text': "Chris Evans started as human torch......."},
        {'doc_name': 'doc_2',
        'mention': 'Tony Stark',
        'title': 'Chris Evans',
        'full_text': "Tony Stark is ironman which likes......."},
        {'doc_name': 'doc_3',
        'mention': 'Chris Evans',
        'title': 'Thor',
        'full_text': "Thor loves to drink......."},
        ....... more docs......
        }]

key = "my-key"
endpoint = "my-endpoint"

azure_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))

async def entity_linking(text,doc_name,azure_client):

    name = []
    i_d = []
    url = []
    temp = []
    text = []
    doc_n = []

    documents = [text]

    try:
        result = await client.recognize_linked_entities(documents = documents)
        docs = [doc for doc in result if not doc.is_error]

        for doc in docs:

            for entity in result.entities:
                doc_n.append(doc[i]['doc_name'])
                name.append(entity.name)
                i_d.append(entity.data_source_entity_id)
                url.append(entity.url)
                temp.append(entity.matches)

    except Exception as err:
        print("Encountered exception. {}".format(err))

    for i in range(len(temp)):
        text.append(temp[i][0]['text'])

    dataframe = pd.DataFrame({
        'doc_name': doc_n,
        'name': name,
        'id': i_d,
        'text': text,
        'wiki_url': url
    })

    return dataframe

async def agg_azure_pred(doc, doc_name, azure_client):
    pred_df = pd.DataFrame()

    async with azure_client:

        coro_df = [entity_linking(doc[i]['full_text'],doc[i]['doc_name'], azure_client) for i in range(len(doc))]
        results = await asyncio.gather(*coro_df)

        for df in results:
            pred_df = pd.concat([pd.DataFrame(df), pred_df])

    return pred_df

#I ran the code use this command below
await agg_azure_pred(ace, azure_client)

After I ran the code the error I got is Encountered exception. 'NoneType' object has no attribute 'request' I am wondering which part of my code has bugs/errors in it, I have been trying to figure but still couldn't solve it. That will be great if any of you here can help me with it.
The output will look something like this
doc_name      name            id           text         wiki_url
doc_1      Chris Evans    Chris Evans    Chris Evans     url_1
doc_2      Tony Stark     Tony Stark     Tony Stark      url_2
doc_3         Thor          Thor           Thor          url_3

I believe the problem is this line coro_df = [entity_linking(doc[i]['full_text'],doc[i]['doc_name'], azure_client) for i in range(len(doc))] I may be doing something wrong about it but I couldn't figure what did I do wrong.

A: The example code provided was not runnable as-is, nor could I reproduce the exception you described. I made some tweaks to your code to make it run, but this was without context of what the expected result should be. Please give it a try and see if it helps.
import os
import asyncio
import pandas as pd
from azure.ai.textanalytics.aio import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

# this is the input list of documents
ace = [{'doc_name': 'doc_1',
        'mention': 'Chris Evans',
        'title': 'Chris Evans',
        'full_text': "Chris Evans started as human torch......."},
       {'doc_name': 'doc_2',
        'mention': 'Tony Stark',
        'title': 'Chris Evans',
        'full_text': "Tony Stark is ironman which likes......."},
       {'doc_name': 'doc_3',
        'mention': 'Chris Evans',
        'title': 'Thor',
        'full_text': "Thor loves to drink......."}]

key = "my-key"
endpoint = "my-endpoint"

azure_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))

async def entity_linking(full_text, doc_name, azure_client):

    name = []
    i_d = []
    url = []
    temp = []
    text = []
    doc_n = []

    documents = [full_text]

    try:
        result = await azure_client.recognize_linked_entities(documents=documents)
        docs = [doc for doc in result if not doc.is_error]

        for doc in docs:
            for entity in doc.entities:
                doc_n.append(doc_name)
                name.append(entity.name)
                i_d.append(entity.data_source_entity_id)
                url.append(entity.url)
                temp.append(entity.matches)

    except Exception as err:
        print("Encountered exception. {}".format(err))

    for i in range(len(temp)):
        text.append(temp[i][0]['text'])

    dataframe = pd.DataFrame({
        'doc_name': doc_n,
        'name': name,
        'id': i_d,
        'text': text,
        'wiki_url': url
    })

    return dataframe

async def agg_azure_pred(doc, azure_client):
    pred_df = pd.DataFrame()

    async with azure_client:
        coro_df = [entity_linking(doc[i]['full_text'], doc[i]['doc_name'], azure_client) for i in range(len(doc))]
        results = await asyncio.gather(*coro_df)

        for df in results:
            pred_df = pd.concat([pd.DataFrame(df), pred_df])

    return pred_df
    # I ran the code use this command below

async def main():
    await agg_azure_pred(ace, azure_client)

if __name__ == '__main__':
    asyncio.run(main())

Output:
  doc_name                                    name                                      id         text                                           wiki_url
0    doc_3                             Thor (band)                             Thor (band)         Thor          https://en.wikipedia.org/wiki/Thor_(band)
0    doc_2  Tony Stark (Marvel Cinematic Universe)  Tony Stark (Marvel Cinematic Universe)   Tony Stark  https://en.wikipedia.org/wiki/Tony_Stark_(Marv...
0    doc_1                     Chris Evans (actor)                     Chris Evans (actor)  Chris Evans  https://en.wikipedia.org/wiki/Chris_Evans_(actor)

My pip freeze from installing azure-ai-textanalytics, aiohttp, and pandas:
aiohttp==3.8.1
aiosignal==1.2.0
async-timeout==4.0.2
attrs==21.4.0
azure-ai-textanalytics==5.1.0
azure-common==1.1.28
azure-core==1.22.1
certifi==2021.10.8
charset-normalizer==2.0.12
frozenlist==1.3.0
idna==3.3
isodate==0.6.1
msrest==0.6.21
multidict==6.0.2
numpy==1.22.2
oauthlib==3.2.0
pandas==1.4.1
python-dateutil==2.8.2
pytz==2021.3
requests==2.27.1
requests-oauthlib==1.3.1
six==1.16.0
urllib3==1.26.8
yarl==1.7.2


text:
Q: Where can I store logs in PHP app so that they cannot be accessed via HTTP? Sorry if this is a trivial question.
I am a kind of new to PHP and I'm creating a project from scratch.  I need to store my application logs (generated using log4php) as files, and I don't want them to be public.
They are now stored in a subfolder under my PHP application folder, (/myAppFolder/logs) so they are served by Apache.
Where shall I store them, or what shall I do to keep them away from being served as content by Apache?

A: You can either have them in a directory above the root, or, if you're on shared host/ can't have the files above the root for whatever reason, you can have them in a directory that denies all HTTP access.
So you could have a folder called "secret_files" with a .htaccess file sitting inside:
.htaccess:
deny from all

Which will prevent HTTP access to files/subfolders in that folder.

A: Somewhere not under the public root!?
This is more a server config question as it depends on your server, but in apache you could use the custom log directives to set the location, so if you have
/www/myapp

Create
/www/log

and put them there instead. You need control over the config to do this so look up your web hosts docs to find out how.


text:
Q: AppsScript Store unique value per users across executions I am attempting to store data generated by one function, and retrieve it in another function within apps script. This value is unique to each user. I've tried doing userProperties, but that does not seem to carry properly. Is this possible within AppsScripts?
I'm running this within a google sheet that is publicly editable.
For example: In an assigned script that runs when a user clicks on an image, lets call it "onButtonClick()", it collects some information from the user (such as "what is your favorite cookie).
Then, in a trigger for an on-change event (which checks which cell was changed), get that user's saved 'favorite cookie'.
userProperties saves data for the owner of the document which can be accessed, but there is no way to tell what the current user's "favorite cookie" is without an accessible unique identifier.
It seems google wont let the script access 'confidential info' in a trigger such as onChange/onEdit, even once the OAuth scope of the script is authorized by a user (via the initial button press gathering the favorite cookie info).
If I could get a unique value for the user from the onChange/onEdit trigger, I would use that...but triggers don't let that happen.
Edit::
It is requested to have a minimal reproducible example.
Have OAuth scope for "https://www.googleapis.com/auth/userinfo.email"
In main body of apps script:
function doGetEmailPermissions(){
//button action to get user to trigger authorization from script.
var userInfo=Session.getActiveUser().getEmail();
  if (userInfo!=null){
     setProp("userId",userInfo);
      SpreadsheetApp.getUi().alert('Thank you for verifying '+userInfo+"!");
  }else{
    SpreadsheetApp.getUi().alert("You must be logged in with a google account!");
  }
}

function doOnEdit(e){
//use neither method returns the editor's information
 SpreadsheetApp.getUi().alert("Cell changed by:"+Session.getActiveUser().getEmail());
SpreadsheetApp.getUi().alert("Cell changed by:"+e.user);
}

Create an installable trigger for onEdit to call 'doOnEdit'. Create a button in the sheet and assign the script "doGetEmailPermissions".
Clicking the button will correctly request the user's authorization to run the script, and respond with the user's email.
Making a change by anyone other than the owner of the doc, returns empty strings for the email/user info.

A: Get and Set User Properties
function setProp(key,value) {
  const ps = PropertiesService.getUserProperties();
  ps.setProperty(key,value);
}

function getProp(key) {
  const  ps = PropertiesService.getUserProperties();
  return ps.getProperty(key);
}


text:
Q: Apache couchDB good for pre-defined queries? I see below statement at When to use CouchDB over MongoDB and vice versa

For accumulating, occasionally changing data, on which pre-defined
  queries are to be run. Places where versioning is important.

I am not sure what predefined queries means here ?

A: It was referred to the view definition in CouchDB. The pre-defined queries are defined as map/reduced views that are indexed by CouchDB.
These views are defined in design documents stored in the database (pre-defined)
By the time of the post you refer, it is based in the features of CouchDB 1.x, now in CouchDB 2.x you can use Mango Queries for dynamic query expressions.


text:
Q: React app crashed with Heroku after deployment I'm trying to deploy a new React application to Heroku. I already did that without problems, but this afternoon I have this error:

The full error message is:
heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=XXXhiddenXXX.herokuapp.com request_id=199e3ff6-54c9-4711-bb1c-b6775dfe8799 fwd="92.148.12.118" dyno= connect= service= status=503 bytes= protocol=https

I tried a lot of solutions exposed here:
Heroku deployment error H10 (App crashed)
Without success.
I restarted (several times) the dyno : without success.
My heroku-postbuild is:
npm install && npm install --only=dev --no-shrinkwrap && npm run build

Perhaps it is this script which generates this error?

A: I find this solution :
I added a buidpack on my project. To do that :

*

*go to your dashboard, tab 'Settings'

*see the section 'buildpacks' :

Add the buildpack https://github.com/mars/create-react-app-buildpack.git
note : you can also add this build pack from your terminal :
heroku buildpacks:add https://github.com/mars/create-react-app-buildpack.git --app YOURAPP

Rebuild your application and that's all.
I must admit that I did not understand everything, but it is clear that it worked for me.

A: The default buildpack when deploying is that of node.js. You needed to use the create-react-app buildpack (as seen below).
heroku create $APP_NAME --buildpack mars/create-react-app
git push heroku master
heroku open

A: You need to have the app running on a Heroku port using Express.
Step 1: Add server.js file to your project add add the following:
var express  = require('express');
var app      = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var cors = require('cors');

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(cors());

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.use(express.static('build'));
app.set('port', process.env.PORT || 5000);
app.listen(app.get('port'), function () {
  console.log('Express server listening on port ' + app.get('port'));
});

Step 2: Npm Install morgan, express and cors
Step 3: In package.json, change the "start" in scripts to "node server.js"
Step 4: Commit and Push to Heroku.
Step 5: Hard refresh your page.
You're welcome...


text:
Q: Django Model DateField and input fixture Model file includes :
class Foo(models.Model):
    bar = models.DateTimeField()

Fixture file.json includes:
  {
  "model": "app.Foo",
  "pk": "1",
  "fields": {
      "bar": "2018/4/20",
  }
},

when I'm trying to add fixtures with "python manage.py loaddata" result is:
django.core.serializers.base.DeserializationError: Problem installing fixture
'C:\Projects\TestProject\app\fixtures\file.json': ['"2018/4/20" value has an
invalid format. It must be in Y
YYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']: (app.Foo:pk=1) field_value was '2018/4/20'

so my question is how can I add date format with "YYYY/MM/DD" to my Model files ?

A: your using DateTimeField() and your getting  data is only date that's why it's getting the  error instead of DateTimeField() use DateField()
for example:class Foo(models.Model):
                bar = models.DateField()

A: The Django models.DateField and models.DateTimeField expect input either as python datetime objects or in ISO format (with "-" separators, not "/" separators). This is not something you can easily change because it is also what is used to save the values in the database. So what you want isn't possible.
The only option I see is that you write your own management command that first parses your json fixture, changing the dates format to ISO and saving to a new file, then calling the loaddata command from within your own handle() method.
Note: The corresponding form fields, forms.DateField, are flexible and accept various input formats and allow you to specify which input format you want to use. In fact, if you enable i18n then they will accept international input formats like 2020/03/12. But that doesn't really help you with loaddata which doesn't use a form at all.


text:
Q: Where to write backend coding for dashcode I am new to iphone web apps and trying to use database(sqlite3) in my iphone web app  but not getting material for getting started with db connection where to do bacend coding in dashcode because ,there are only css ,html and js files and so my basic question is where should do I start with the backend coding .
If any one has solution please do write to me .
Kind Regards
Parag Deshpande

A: There is no backend in Dashcode. As you say it is html, css and JavaScript. The "normal" way of accessing data is to define a data source in the JavaScript, go to the library for the code samples to do this and this lets you access xml files.
As far as i am aware it is not possible to access sqlite either from dashcode or even for that matter from JavaScript as JS is sandboxed in browsers to prevent malicious access.
It might be possible to use server side JS such as node or rhino but at that point i would think you were loosing the advantages of DashCode and would be better to move to a more comprehensive platform like xcode or Sencha Touch etc.

A: sqlite3 is available as part of html5 localstorage. There is a fair bit of info on the web.
http://blog.darkcrimson.com/2010/05/local-databases/
https://developer.apple.com/videos/wwdc/2011/
Look at session using HTML5 offline storage.
I have used this in a few apps and have been impressed with capabilities and speed.


text:
Q: Sums of squared distances between points on an $n$-sphere I have discovered the following results about the sums of squared distances between points on an $n$-sphere (and proved them).  To the best of my knowledge (and my advisor's knowledge), these results are new.  However, since this is classical geometry and the proofs are not hard, I wanted to ask if anyone knows of their existence in the literature.
I have searched the literature, and I do find authors considering similar questions (e.g., what distribution of points on an $n$-sphere maximizes the sum of distances between the points) but I do not see anyone considering the sum of squared distances.
I want to emphasize that I am not asking for proofs of these results.  I have already proven them myself.
First, a bit of terminology:

*

*An $n$-sphere is the set of all points equidistance from a fixed point in $\mathbb{R}^n$.

*A set of points $\mathcal{V}$ is centrally symmetric if it is closed under the antipodal map, i.e., for every $P \in \mathcal{V}$, the point $-P$ is in $\mathcal{V}$.

*A set of points $\mathcal{V}$ is transitive if for each $P, Q \in \mathcal{V}$, there exists a symmetry of $\mathcal{V}$ such that $P$ is mapped to $Q$.

Result 1. Let $\mathcal{V}$ be a set of $V$ points on a unit $n$-sphere, and let $\mathcal{C}$ be the multiset of the lengths of all the chords between them.
Then: $$\sum_{c \, \in \, \mathcal{C}}c^2= V^{2}(1-d^2)$$
where $d$ is the distance between the centroid of $\mathcal{V}$ and the center of the unit $n$-sphere.
This leads to a nice corollary:  The centroid of $\mathcal{V}$ coincides with the center of the $n$-sphere if and only if $\sum_{c \, \in \, \mathcal{C}}c^2= V^{2}$.
Result 2. Let $\mathcal{V}$ be a transitive, centrally symmetric set of $V$ points on a unit $n$-sphere, and let $\mathcal{L}$ be the set of distinct lengths of all the chords between them.
Then: $$\sum_{l \, \in \, \mathcal{L}}l^2 = 2k+2$$
where $k$ is the cardinality of $\mathcal{L}$.
Question:  Has anyone seen these results in the literature?  If so, where?  (I suppose reference to any similar results would be helpful as well...)
Note:  My research was motivated by the following two facts found in the literature.  My results subsume these (if one thinks of the vertices of a regular polygon as a point configuration).

*

*For a regular polygon inscribed in a unit circle, $\sum_{c \, \in \, \mathcal{C}}c^2= V^{2}$.

*For a regular polygon inscribed in a unit circle, $\sum_{l \, \in \, \mathcal{L}}l^2 \in \mathbb{Z}$.

Fact 1 is in an unpublished paper by S. Mustonen at
https://www.survo.fi/papers/Roots2013.pdf.  Fact 2 is in a popular math book by J. Kappraff: "Beyond Measure: A
Guided Tour through Nature, Myth, and Number." (World Scientific
Publishing, River Edge, NJ, 2002). A related question was stated as
a 1923 MAA Monthly problem (Morley, F. V., Harding, A. M.: 2925. Am.
Math. Mon. 30(1), 44 (1923)).

A: The sum of squares of chords has proven to be particularly useful in studying arrangements of lines for redundant linear encodings of data.
Suppose $n=\binom{d+1}{2}$. In this case, we may identify $\mathbb{R}^n$ with the vector space of real symmetric $d\times d$ matrices, and $\mathbb{R}\mathbf{P}^{d-1}$ with the subset of matrices that represent orthogonal projections of rank 1:
$$
\mathbb{R}\mathbf{P}^{d-1}
\cong\{xx^\top:x\in S^{d-1}\}.
$$
Notice that these matrices have unit Frobenius norm, and so they reside in the unit sphere in this space of matrices. The square of the chord length between $xx^\top$ and $yy^\top$ is given by
$$
\|xx^\top-yy^\top\|_F^2
=2-2(x^\top y)^2.
$$
As such, the sum of the squared chord lengths between pairs in $\mathcal{V}=\{x_ix_i^\top\}_{i=1}^V$ is given by
$$
\sum_{1\leq i<j\leq V}\|x_ix_i^\top-x_jx_j^\top\|_F^2
=V^2-\sum_{i=1}^V\sum_{j=1}^V(x_i^\top x_j)^2.
$$
The double sum on the right-hand side is the frame potential of $\{x_i\}_{i=1}^V$, studied extensively by Benedetto and Fickus in "Finite Normalized Tight Frames." (It's a beautiful paper!)

A: I read your paper (Sums of squared distances between points on a Unit sphere 2020 arXiv), but I must inform you that your theorem 2.1 was already established by Tom M. Apostol in a paper in Math Monthly 2003 (Sums of squares of distances in m-space) in a more general way (weighted).

A: There are two basic formulae for the moment of inertia, which I formulate for the system of unit masses: given $V$ points $p_1,\dots,p_V\in \mathbb{R}^n$, define by $J(q)=\sum |q-p_i|^2$ the moment of intertia of a point $q$. Then
1) (Lagrange formula) $J(q)=J(z)+V|q-z|^2$, where $z$ is the centroid of our $V$ points.
2) (Jacobi formula) $J(z)=V^{-1}\sum_{i<j} |p_i-p_j|^2$.
These formulae are known under different names, I follow the book of Balk and Boltyanskiy "Geometry of masses".


text:
Q: Is there any way I can rewrite my methods better? I'm not entirely sure if there is an easier answer to this question and I'm thinking to hard about it or what, but I'm currently programming a rectangular block program to practice Java. It's structured to have 4 methods: getInput, volBlock, saBlock, and display, and I want to use only local variables for these methods. Is there a way that I can utilize getInput to accept and return a single double from the user and if so, how can I use that input in my other methods?
I constructed this code, which uses local variables in getInput() and then passes those values to other methods, but I couldn't figure out a display method so I hard coded it into the calculation methods themselves.
Here is that code:
import java.util.*;
public class Block {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String choice = "Y";
        while (choice.equals("Y")){
            getInput();
            System.out.println("Would you like to do another calculation?(Y/N): ");
            choice = in.next().toUpperCase();
        }
        System.out.println("Program now ending...");
    }

    public static void getInput() {
        double l, w, h;
        Scanner fin = new Scanner(System.in);
        System.out.println("Please enter the length, width, and height in that order: ");
        l = fin.nextDouble();
        w = fin.nextDouble();
        h = fin.nextDouble();

        volBlock(l, w, h);
        surfaceAreaBlock(l,w,h);
    }

    public static void volBlock(double length, double width, double height) {
        double volume;

        volume = length * width * height;

        System.out.println("The volume is: " + volume);
    }

    public static void surfaceAreaBlock (double l, double w, double h) {
        double surfaceArea;

        surfaceArea = 2 * (l*h+l*w+h*w);

        System.out.println("The surface area is: " + surfaceArea);
    }
}

I'm sorry if this question is kind of scrambled, I am having a hard time figuring all of this out. I'm quite new to Java.
Any help is appreciated, thank you!

A: If you're practicing java, you should probably familiarize yourself more with object oriented programming before you go any further, because your code leads me to believe that you're more used to procedural languages (e.g. C, C++, etc). Java doesn't rely on having several static helper methods in its main; the preferred approach is to construct a few classes that perform these calculations for you, and you use the results created by these functions for your basic input/output, which is normally what main is used for.
I implemented a block class to demonstrate what I mean:
public class Block {
    private double length;
    private double width;
    private double height;

    public Block(double l, double w, double h) {
        length = l;
        width = w;
        height = h;
    }

    public double getVolume() {
        return length * width * height;
    }

    public double getSurfaceArea() {
        return 2 * length * (height + width) + height * width;
    }

    /* This is the "display" method that you want */
    public String toString() {
        return "The volume is: " + getVolume() + "\n"
               "The surface area is: " + getSurfaceArea();
    }
}

using the Block class, your main becomes much more simple:
public static void main() {
    Scanner in = new Scanner(System.in);
    char choice = 'y';

    do {
        System.out.print("Please enter the dimensions of the block: ");
        double length = in.nextDouble();
        double width  = in.nextDouble();
        double height = in.nextDouble();
        Block block = new Block(length, width, height);

        System.out.println(block);
        System.out.print("continue (y/n)? ");
        choice = in.nextLine.toLowerCase().charAt(0);
    } while (choice == 'y');
}

A: If you return the values from your getInput(), volBlock() and surfaceAreaBlock() methods you might be able to structure the rest as you want to.
For instance surfaceAreaBlock becomes:
public static double surfaceAreaBlock (double l, double w, double h){
    double surfaceArea;

    surfaceArea = 2 * (l*h+l*w+h*w);

    return surfaceArea;
}

and then when you call surfaceAreaBlock you can do this:
public static void main(String[] args) {
    ...

    double surfaceArea = surfaceAreaBlock();

    // Do something with the surface area in this method
    ...
}


text:
Q: Python - Perspective transform for OpenCV from a rotation angle I'm working on depth map with OpenCV. I can obtain it but it is reconstructed from the left camera origin and there is a little tilt of this latter and as you can see on the figure, the depth is "shifted" (the depth should be close and no horizontal gradient):

I would like to express it as with a zero angle, i try with the warp perspective function as you can see below but i obtain a null field...
P = np.dot(cam,np.dot(Transl,np.dot(Rot,A1)))

dst = cv2.warpPerspective(depth, P, (2048, 2048))

with :
#Projection 2D -> 3D matrix
A1 = np.zeros((4,3))
A1[0,0] = 1
A1[0,2] = -1024
A1[1,1] = 1
A1[1,2] = -1024
A1[3,2] = 1

#Rotation matrice around the Y axis
theta = np.deg2rad(5)
Rot = np.zeros((4,4))
Rot[0,0] = np.cos(theta)
Rot[0,2] = -np.sin(theta)
Rot[1,1] = 1
Rot[2,0] = np.sin(theta)
Rot[2,2] = np.cos(theta)
Rot[3,3] = 1

#Translation matrix on the X axis
dist = 0
Transl = np.zeros((4,4))
Transl[0,0] = 1
Transl[0,2] = dist
Transl[1,1] = 1
Transl[2,2] = 1
Transl[3,3] = 1

#Camera Intrisecs matrix 3D -> 2D
cam = np.concatenate((C1,np.zeros((3,1))),axis=1)
cam[2,2] = 1
P = np.dot(cam,np.dot(Transl,np.dot(Rot,A1)))

dst = cv2.warpPerspective(Z0_0, P, (2048*3, 2048*3))

EDIT LATER :
You can download the 32MB field dataset here: https://filex.ec-lille.fr/get?k=cCBoyoV4tbmkzSV5bi6. Then, load and view the image with:
from matplotlib import pyplot as plt
import numpy as np

img = np.load('testZ0.npy')
plt.imshow(img)
plt.show()

A: I have got a rough solution in place. You can modify it later.
I used the mouse handling operations available in OpenCV to crop the region of interest in the given heatmap.
(Did I just say I used a mouse to crop the region?) Yes, I did. To learn more about mouse functions in OpenCV SEE THIS. Besides, there are many other SO questions that can help you in this regard.:)
Using those functions I was able to obtain the following:

Now to your question of removing the tilt. I used the homography principal by taking the corner points of the image above and using it on a 'white' image of a definite size. I used the cv2.findHomography() function for this.
Now using the cv2.warpPerspective() function in OpenCV, I was able to obtain the following:

Now you can the required scale to this image as you wanted.
CODE:
I have also attached some snippets of code for your perusal:
#First I created an image of white color of a definite size
back = np.ones((435, 379, 3)) # size
back[:] = (255, 255, 255)     # white color

Next I obtained the corner points pts_src on the tilted image below :
pts_src = np.array([[25.0, 2.0],[403.0,22.0],[375.0,436.0],[6.0,433.0]])

I wanted the points above to be mapped to the points 'pts_dst' given below :
pts_dst = np.array([[2.0, 2.0], [379.0, 2.0], [379.0, 435.0],[2.0, 435.0]])

Now I used the principal of homography:
h, status = cv2.findHomography(pts_src, pts_dst)

Finally I mapped the original image to the white image using perspective transform.
fin = cv2.warpPerspective(img, h, (back.shape[1],back.shape[0]))
# img -> original tilted image.
# back -> image of white color.

Hope this helps! I also got to learn a great deal from this question.
Note: The points fed to the 'cv2.findHomography()' must be in float.
For more info on Homography , visit THIS PAGE


text:
Q: seeing garbled output with Popen communicate Am seeing garbled output with below code. Can someone help on how to synchronize the output?
import subprocess
from subprocess import Popen, PIPE
def do_shell(cmd):
p = Popen('/bin/bash', shell=False, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
o, e = p.communicate(cmd)
p.wait()
print('Output: ' + o.decode('utf8'))

Is it possible to wait for 5 sec after each command execution passed to communicate?
Note:Here cmd is string of commands (cmd=cmd1\ncmd2\ncmd3\n)


text:
Q: save arrays in mysql with php and reactj I have a form in reactjs that saves a variable "name" and two dynamic arrays, one is called "data1" and "data2", each array can contain several values since I can add more dynamic values from reactjs to there, but not I have been able to pass those values of the array that are saved in mysql from the php since it only saves the name and the first two data of the array of data1 and data2:
https://codesandbox.io/s/ecstatic-browser-nvcee?file=/src/App.js:0-8794
I need to be able to save the complete arrays "data1" and data2 in the database.

reactjs

import React, {useState} from 'react';
import axios from 'axios';

import {
  Grid,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper
} from "@material-ui/core";
import AddCircleOutlineIcon from "@material-ui/icons/AddCircleOutline";
import { withStyles, makeStyles } from "@material-ui/core/styles";
import DeleteIcon from "@material-ui/icons/Delete";

const StyledTableRow = withStyles((theme) => ({
  root: {
    "&:nth-of-type(odd)": {
      backgroundColor: theme.palette.action.hover
    }
  }
}))(TableRow);

/*const useStyles = makeStyles((theme) => ({
  paper: {
    display: "flex",
    flexDirection: "column",
    padding: "30px 40px",
    marginTop: "50px",
    marginLeft: "20px",
    marginRight: "20px"
  },

  heading: {
    paddingLeft: "10px"
  },

  label: {
    lineHeight: "2",
    fontSize: "14px"
  },
  input: {
    height: "10px"
  },
  table: {
    minWidth: 700
  }
}));*/

const options = [
  { value: 1, label: 1 },
  { value: 2, label: 2 },
  { value: 3, label: 3 }
];

function Pruebas() {
    const baseUrlAd = 'https://www.inventarios.gemcont.com/apiGemcont/compras/ingresos/index2.php';
    const [data, setData]=useState([]);
    const [frameworkSeleccionado, setFrameworkSeleccionado]=useState({
        id_ingreso:'',
        nombre:'',
        dato1:'',
        dato2:''
      });

    const handleChange=e=>{
        const {name, value}=e.target;
        setFrameworkSeleccionado((prevState)=>({
          ...prevState,
          [name]: value
        }))
       console.log(frameworkSeleccionado);
      }

      /*const peticionPost = async() =>{
        var f = new FormData();
        f.append("nombre", frameworkSeleccionado.nombre);

        f.append("dato1", frameworkSeleccionado.dato1);
        f.append("dato2", frameworkSeleccionado.dato2);
        f.append("METHOD", "POST_prueba");
        await axios.post(baseUrlAd,f)
        .then(response=>{
         setData(data.concat(response.data));
        }).catch(error=>{
          console.log(error);
        })

      }*/

      const peticionPost = async () => {
        var f = new FormData();
        f.append("nombre", frameworkSeleccionado.nombre);
        /* Los datos están en la matriz bidimensional "roomInputs" */
       /* f.append("dato1", roomInputs[0].dato1);
        f.append("dato2", roomInputs[0].dato2);*/
        f.append("data", JSON.stringify(roomInputs));
        f.append("METHOD", "POST_prueba");
        await axios
          .post(baseUrlAd, f)
          .then((response) => {
            setData(data.concat(response.data));
          })
          .catch((error) => {
            console.log(error);
          });
      };

  //const classes = useStyles();

  const [roomInputs, setRoomInputs] = useState([
    { dato1: "", dato2: "" }
  ]);

  /*const handleRoomChange = (option, index, name) => {
    const value = option.value;
    console.log(value);
    const list = [...roomInputs];
    list[index][name] = value;
    setRoomInputs(list);
  };*/

  /*const handleRoomChange = (value, index, name) => {
    const list = [...roomInputs ];
    list[index][name] = value;
    setRoomInputs(list);
  };*/

  /*const handleRoomChange = (value, index, name) => {
   setFrameworkSeleccionado((prevState) => ({
      ...prevState,
      [name]: value
    }));

  };*/

  const handleRoomChange = (value, index, name) => {
    const list = [...roomInputs ];
    list[index][name] = value;
    setRoomInputs(list);
  };

  const handleRemoveClickRoom = (index) => {
    const list = [...roomInputs];
    list.splice(index, 1);
    setRoomInputs(list);
  };

  const handleAddClickRoom = () => {
    setRoomInputs([...roomInputs, { dato1: "", dato2: "" }]);
  };

    return (

Datos

                  <input type="text" name="nombre"
                  placeholder='nombre' className="form-control" onChange={handleChange}/>

          <Grid item sm={12}>
            <TableContainer component={Paper} variant="outlined">

                <TableHead>
                  <TableRow>
                    <TableCell>#</TableCell>
                    <TableCell align="left">dato1</TableCell>
                    <TableCell align="left">dato2</TableCell>
                  </TableRow>

                </TableHead>
                <TableBody>
                  {roomInputs.map((x, i) => (

                  ))}
                </TableBody>

            </TableContainer>
          </Grid>

                  <button className="btn btn-primary" onClick={()=>peticionPost()}> Registrar</button>

    )
}

export default Pruebas

php - failed attempts

<?php

include '../../bd/global.php';

header('Access-Control-Allow-Origin: *');

//tried 1
if($_POST['METHOD']=='POST_prueba'){
    unset($_POST['METHOD']);
    $nombre=$_POST['nombre'];
    $dato1=$_POST['dato1'];
    $dato2=$_POST['dato2'];
    $query="insert into ingresos2(nombre,dato1,dato2) values ('$nombre','$dato1','$dato2')";
    $queryAutoIncrement="select MAX(id_ingreso) as id_ingreso from ingresos2";
    $resultado=metodoPost($query, $queryAutoIncrement);
    echo json_encode($resultado);
    header("HTTP/1.1 200 OK");
    exit();
}

//tried 2
if($_POST['METHOD']=='POST_prueba'){
        unset($_POST['METHOD']);
        $nombre=$_POST['nombre'];
        $data=json_decode($_POST['data']);
foreach ($data as $row) {
    $dato1=$row['dato1'];
    $dato2=$row['dato2'];
  //aqui debes hacer cada inserción en base de datos
}
        $query="insert into ingresos2(nombre,dato1,dato2) values ('$nombre','$dato1','$dato2')";
        $queryAutoIncrement="select MAX(id_ingreso) as id_ingreso from ingresos2";
        $resultado=metodoPost($query, $queryAutoIncrement);
        echo json_encode($resultado);
        header("HTTP/1.1 200 OK");
        exit();
    }

 //tried 3

if($_POST['METHOD']=='POST_prueba'){
    unset($_POST['METHOD']);
    $nombre=$_POST['nombre'];
    $query="insert into ingresos(nombre) values ('$nombre')";
    $queryAutoIncrement="select MAX(id_ingreso) as id_ingreso from ingresos";
    $resultado=metodoPost($query, $queryAutoIncrement);
    echo json_encode($resultado);
        $num_elementos=0;
        $sw=true;
        while ($num_elementos < count($id_detalle))
        {
            $sql_detalle = "INSERT INTO detalle_ingresos(id_ingreso, dato1, dato2) VALUES ('$idingresonew', '$idarticulo[$num_elementos]','$dato1[$num_elementos]','$dato2[$num_elementos]')";
            ejecutarConsulta($sql_detalle) or $sw = false;
            $num_elementos=$num_elementos + 1;
        }

    return $sw;

    header("HTTP/1.1 200 OK");
    exit();
}

header("HTTP/1.1 400 Bad Request");

?>

mysql

A: try to do 'json_encode' before putting the array into the base
example :
$array = [1,2,3,4,5];
$array = json_encode($array);

if the data does not fit into the database, change the field from 'varchar' to 'json' , then everything will work
your php sript won't work, it has a lot of errors
This line of your code:
$query="insert into ingresos2(nombre,dato1,dato2) values ('$nombre','$dato1','$dato2')";
should look like this:
$query="INSERT iNTO ingresos2 (nombre,dato1,dato2) values ($nombre,$dato1,$dato2)";

and in all other inserts the same way (if it's easy to explain)
ideally you should bind your parameters before Insert here is an example :
$this->db->openPdo();
        $update = "INSERT INTO imported_error_logs (product_id,errors)
                    VALUES(:productId,:error)";
        $sql = $this->db->pdo->prepare($update);
        $sql->execute([
            ':error' => $error,
            ':productId' => $productId,
        ]);


text:
Q: I am getting error message on accessing menu-endpoint I am trying to access wordpress menus using the /wp/v2 api.
The endpoint that I am using is:
My wordpress Staging Site's WP-API Endpoint
The Plugin I am using is:
https://wordpress.org/plugins/wp-api-menus/#description
But on accessing menus I am getting this error message for permission denied:
Error is:
{
"code": "rest_cannot_view",
"message": "Sorry, you cannot view these menus, unless you have access to permission edit them. ",
"data": {
"status": 401
}
}

How can i Set public if it is possible?

A: You didn't change your prefix for that plugin's API.
Instead of
/MC-ACF/wp-json/wp/v2/menus

try
/MC-ACF/wp-json/wp-api-menus/v2/menus

That plugin developer states it right on the page you referenced in your question.  If you're wondering how I solved this.
I'm not sure what your use case is, but there are newer versions of similar plugins as well.  That one works fine, but has not been updated in some time.


text:
Q: Suppress GCC warnings when storing function pointers I am writing a cross-platform OpenGL function loading library. On Windows, the compiler (oddly enough, both VS and GCC) seems fine with implicitly converting one kind of function pointer (the return type from wglGetProcAddress being a void(*)()) into another type of function pointer.
GCC on Linux however is not. glXGetProcAddress will return a void(*)(), but it will always issue a warning about it. And since OpenGL has literally thousands of these things, it adds up to a giant diagnostic spew that's entirely irrelevant.
Is there some way to disable this particular warning? Either with a #pragma or some way of rearranging the code so GCC shuts up? I tried the whole #pragma diagnostic ignore -Wblahblah, but I couldn't find a "blahblah" that matched the warning I was getting.

A: I'm pretty sure you're supposed to use the provided macros to get the correct types out. For example, taken from the gl3w OpenGL extension loader (you have to run the python script to get it to generate code like this), it has lines that look like:
gl3wBindImageTexture = (PFNGLBINDIMAGETEXTUREPROC)get_proc("glBindImageTexture");

That weird PFNGLBINDIMAGETEXTUREPROC in the middle is a macro for the correct function type of the glBindImageTexture function (you can see its name is actually Pointer FunctioN GLBINDIMAGETEXTURE PROC).


text:
Q: Sorting numeric column in QTableWidget I am trying to sort a numeric column in QTableWidget using PyQT5. I read some examples and tried but it doesn't work very well.
It always give same result back.
This is before sorting

This is after sorting

A: The problem is that using strings in the QTableWidgetItem instead of numbers. Given this, there are several options:

*

*Store numbers instead of strings:
import sys
  from PyQt5 import QtCore, QtWidgets

  app = QtWidgets.QApplication(sys.argv)

  w = QtWidgets.QTableWidget(100, 1)
  w.setSortingEnabled(True)

  for i in range(w.rowCount()):
      it = QtWidgets.QTableWidgetItem()
      it.setData(QtCore.Qt.DisplayRole, i)
      w.setItem(i, 0, it)

  w.resize(640, 480)
  w.show()

  sys.exit(app.exec_())

*Override the __lt__ method of QTableWidgetItem:
import sys
from PyQt5 import QtWidgets

class TableWidgetItem(QtWidgets.QTableWidgetItem):
    def __lt__(self, other):
        try:
            return float(self.text()) < float(other.text())
        except ValueError:
            return super().__lt__(other)

app = QtWidgets.QApplication(sys.argv)

w = QtWidgets.QTableWidget(100, 1)
w.setSortingEnabled(True)

for i in range(w.rowCount()):
    it = TableWidgetItem(str(i))
    w.setItem(i, 0, it)

w.resize(640, 480)
w.show()

sys.exit(app.exec_())


text:
Q: defining a function using other functions I have the following code:
c[theta_, xi_] = theta*xi + theta^xi^2;
xbar[theta_, xi_] = theta/xi +  xi^2 + theta^3;
f[x_, y_, theta_, xi_] = x*y*c[theta, xi]*theta*xi + xbar[theta, xi];

That is, I would like to define $f$ as a function $x,y,theta,xi$ using two predefined functions $c$ and $xbar$.
But mathematica gives tag times is protected.
How to deal with it? Many thanks!

A: You need to make sure there are no active definitions on the constituent parameters.  You can do this with ClearAll as E.Doroskevic proposes, though I imagine you will not want to clear all Global` definitions.
You can Block the Symbols in use as described in Scoping in assigning a derivative.  To make this convenient I propose using the function localSet which I wrote for How to make a function like Set, but with a Block construct for the pattern names.
xi = "fail!";
y = "bad!";

localSet[c[theta_, xi_], theta*xi + theta^xi^2]
localSet[xbar[theta_, xi_], theta/xi + xi^2 + theta^3]
localSet[f[x_, y_, theta_, xi_], x*y*c[theta, xi]*theta*xi + xbar[theta, xi]]

?f

Global`f
f[x_, y_, theta_, xi_] = theta^3 + theta/xi + xi^2 + theta x xi (theta^xi^2 + theta xi) y

Observe that the definition is correct despite the definitions on xi and y.

A: Try:
ClearAll["Global`*"]

c[theta_, xi_] = theta*xi + theta^xi^2;
xbar[theta_, xi_] = theta/xi +  xi^2 + theta^3;
f[x_, y_, theta_, xi_] = x*y*c[theta, xi]*theta*xi + xbar[theta, xi];


text:
Q: Is it possible to add Instagram action to Activity Sheet using UIActivityViewController? I am creating an iOS app which enables users to post an image to one of three (or all three) social media providers including: Twitter, Facebook and Instagram.

I have tried implementing this functionality using the UIDocumentInteractionController(), whilst this was effective in adding the 'Copy to Instagram' icon option, it didn't allow me to add icons/options for Facebook and Twitter sharing.

After spending an hour or so Googling solutions to my problem, I came across UIActivityViewController which looked promising. I have implemented an activity sheet which allows me to share via Facebook and Twitter which is brilliant, however, does anybody know how I go about integrating the 'copy in instagram' option to the sheet?
    @IBAction func shareInstagramPressed(sender: AnyObject) {
        if(newImageData.length != 0){
            let image = UIImage(data:newImageData, scale:1.0)
            displayShareSheet(image!)
        }
        else {
            print("Please select an image first")
        }
    }

    func displayShareSheet(shareContent:UIImage) {
        let activityViewController = UIActivityViewController(activityItems: [shareContent as UIImage], applicationActivities: nil)
        activityViewController.excludedActivityTypes = [
            UIActivityTypePostToWeibo,
            UIActivityTypePrint,
            UIActivityTypeAssignToContact,
            UIActivityTypeAddToReadingList,
            UIActivityTypePostToVimeo,
            UIActivityTypePostToTencentWeibo,
            UIActivityTypeOpenInIBooks,
            UIActivityTypeMessage,
            UIActivityTypeMail
        ]
        presentViewController(activityViewController, animated: true, completion: {})
    }

A: Yes:
...it is technically possible, but this support should probably come from Instagram.
From the Apple Documentation:

You should subclass UIActivity only if you want to provide custom services to the user. The system already provides support for many standard services and makes them available through the UIActivityViewController object. For example, the standard activity view controller supports emailing data, posting items to one of the user's social media accounts, and several other options. You do not have to provide custom services for any of the built-in types.

No:
Instagram has no current support for UIActivity.
From the Instagram Documentation:
NSURL *instagramURL = [NSURL URLWithString:@"instagram://location?id=1"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
    [[UIApplication sharedApplication] openURL:instagramURL];
}


text:
Q: MVC application: json + view output I developed an mvc-razor app the classical way: I do some computation in my controller and show the results in the view.
Now, in addition to the formatted output I already provide through the view,  I need to add the ability to provide the same results in json, so that my controller acts as a service.
Something like
if (json == true)
{
    return JsonOutput(model);
}
else
{
    return View(model);
}

Since I don't want to reinvent the wheel, I wonder if there is a standard approach to this task.
Thank you

A: What you are looking for is an ApiController:
[Route("api/[controller]")]
[ApiController]
public class EmployeesController : ControllerBase { ... }

In this controller you will define your action methods, very much like in Mvc, but not return a View:
[HttpGet]
public async Task<IActionResult> Get()
{
   /* ... retrieve results*/
   return Ok(yourPayload);
}

I suggest you follow along the excellent documentation: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-5.0&tabs=visual-studio


text:
Q: How to publish an Object message via jmeter Jmeter JMS publisher has an option to select the Message Type as Object Message and there is text area saying Text Message or Object Message serialized to XML by XStream.
But I couldn't send a Object message to the Message Broker
If I simple enter an XML in the text area and select the message type as Object Message (Obviously this is wrong :) ). I am getting the following exception
jmeter.protocol.jms.sampler.PublisherSampler: hello com.thoughtworks.xstream.mapper.CannotResolveClassException: hello
at com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:79)

How can I send a simple Object message via Jmeter

A: These tutorials might be useful;
http://wso2.com/library/tutorials/2013/08/how-to-use-apache-jmeter-to-publishsubscribe-to-jms-queuestopics-in-wso2-message-broker/
http://aparnaank.blogspot.nl/2013/06/how-to-use-jmeter-jms-publisher.html


text:
Q: Opinions on Solr and spatial data structures for very large datasets Ok so I'll try to keep this simple.  The technical aspects of the problem are, no problem...
I'm looking for some opinions on Solr database indexer.  I have 25 million approx items that need to be stored in some kind of spatial structure.  These are all GIS records with coordinates stored as lat/lon.  One of my co-workers has been using Solr for this task but I'm looking to do some performance tests against several spatial tree types.  We're currently using mySQL for storing all of our data, Solr for indexing and I'm investigating Postgres with PostGIS.  I'm assuming Solr is using some kind of multi-dimensional B-Tree, but I could be wrong and am looking for confirmation on this.
I'm also going to be running tests on this dataset using...
- B-Tree
- B-Tree (with Morton Hash Index)
- B-Tree (with Hilbert Hash Index)
- BSP-Tree
- Quad-Tree
- KD-Tree
- R-Tree
I'm going to be writing either an Apache module or MySQL/PostgreSQL extension in C++ for each of these tests, and following implementation once we make our decision.
I'm just looking for opinions/suggestions on said implementation.
Thanks


text:
Q: Showing the contents of a SPAN using JavaScript I have this code. I've done this for years now but I'm stumped with the result of this example. The purpose is to make the text box visible and put the contents of the clicked SPAN tag in it.
document.onclick = CaptureClickedElement;

function CaptureClickedElement(e)
{
var EventElement;
if(e==null)
    EventElement = event.srcElement;// IE
else
    EventElement = e.target;// Firefox

if( EventElement.tagName == "SPAN")
    {
    document.getElementById("divTXT").style.display="";
    document.getElementById("txt").value = document.getElementById("Span1").innerHTML;
    alert(document.getElementById("Span1").innerHTML)
    }
}

Strangely though, it DOES show the contents but also shows open/close SPAN tags at the end of it. If I alert ther results, the same thing is shown.
Please find the attached screen shot of it here.

Does anyone have an idea of why this is happening?
Thanks!
Here is the HTML (copied from comments by mplungjan)

    <form name="frm" method="post" action="">

        <input type="text" id="txt" name="txt" value="" size="30" />

    </form>

    hi, this is a test.

A: Structure problem:
hi, this is a test.

Note the absence of a proper close to the span.

A: Need to use .innerText (for IE) and .text for others.


text:
Q: Not able to ref dataSource from other bean configuartion in Spring <bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
        <property name="poolName" value="${models.DS_POOL_NAME}" />

        </property>
    </bean>
<bean id="DBPlaceholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="properties">
            <bean class="org.apache.commons.configuration2.ConfigurationConverter" factory-method="getProperties">
                <constructor-arg>
                    <bean id="DatabaseConfigurator" class="org.apache.commons.configuration2.DatabaseConfiguration">
                        <property name="dataSource" ref="dataSource" />
                        <property name="table" value="sample" />
                        <property name="keyColumn" value="PROPERTY" />
                        <property name="valueColumn" value="VALUE" />
                        <property name="configurationNameColumn" value="GROUP_NAME" />
                        <property name="configurationName" value="new" />
                    </bean>
                </constructor-arg>
            </bean>
        </property>
    </bean>

when we ref dataSource in DBPlaceholder bean then ${models.DS_POOL_NAME} will showing error because this value is coming from properties


text:
Q: React Material Design Icon hover not working correctly I'm using mdi-react icons and the hovering doesnt work well. Sometimes it works, sometimes it doesnt.
import MagnifyPlusOutline from "mdi-react/MagnifyPlusOutlineIcon";
import MagnifyMinusOutline from "mdi-react/MagnifyMinusOutlineIcon";
import DoubleDownChevron from "mdi-react/ChevronDoubleDownIcon";
import DoubleUpChevron from "mdi-react/ChevronDoubleUpIcon";

export default function App() {
  return (
    <div className="App">
      <DoubleUpChevron className="viewIcon" size={38} />
      <DoubleDownChevron className="viewIcon" size={38} />
      <MagnifyPlusOutline className="viewIcon" size={32} />
    </div>
  );
}

CSS
.viewIcon :hover {
  color: grey;
  cursor: pointer;
}

You can see on the sandbox, if you hover sometimes it works, but sometimes the cursor doesnt become a pointer,even if I'm right over the icon
Sandbox: https://codesandbox.io/s/staging-leftpad-j2tj9?file=/src/App.js

A: Rookie css mistake I guess, Try removing the extra space before :hover
.viewIcon:hover {
  color: grey;
  cursor: pointer;
}


text:
Q: make Simple Fragment always get InstantiationException hello guys i just try to make a simple fragment start up using support library v4 here...
this is my main activity
public class MainActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    Fragment testFragment = manager.findFragmentById(R.id.listTestFragment);
    transaction.show(testFragment);
    transaction.commit();
}

}

and my activity_main.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<fragment android:name="com.drikvy.testfragmentgame.ListTestFragment"
        android:id="@+id/listTestFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

and my ListTestFragment.java
public class ListTestFragment extends Fragment {

String[] data = {"aaaa", "bbbb", "cccc", "dddd"};
MainActivity activity;

public ListTestFragment(MainActivity activity) {
    this.activity = activity;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
            View view = inflater.inflate(R.layout.fragment_lores_list, null, false);

            ListView lvLores = (ListView) view.findViewById(R.id.lv_saved_lores);
            lvLores.setAdapter(new ArrayAdapter<String>(activity, android.R.id.text1, data));

            return view;
}
}

sadly android runtime said that i havent empty constructor and that my fragment class is not public class etc
what's wrong?
UPDATE
Thanks to Sir Miro for pointing out the main problem in my code through his answer.
I just want to make clear some matters here:

*

*first of all, i didnt know that by putting the fragment in the xml layout would require the fragment class to provide an empty constructor, that's why im always getting instantiate exception error in logcat

*the reason behind why i didnt put an empty constructor in my fragment class is that because from my previous attempts for making fragments i had successfully show the fragments by using non-empty constructor and i usually add activity parameters inside it for context utilization within the fragment class. but i didnt noticed that none of these fragments was declared on my xml layout! and thats when the error start to popped up

*so in conclusion we have to provide an empty constructor or no constructor at all if we have declared the fragments on our xml layout. but if we didnt declared them on our xml layout then we can deliberately add any kinds of constructor with any parameters we could possibly wanted within our fragment class!

A: You can't pass in your activity from the fragment constructor. Fragment has a method called onAttach which is called when the fragment is attached to an activity. You can set the activity variable from onAttach.
Try this as your Fragment code:
public class ListTestFragment extends Fragment {

    String[] data = {"aaaa", "bbbb", "cccc", "dddd"};
    MainActivity activity;

    public ListTestFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.fragment_lores_list, null, false);

        ListView lvLores = (ListView) view.findViewById(R.id.lv_saved_lores);
        lvLores.setAdapter(new ArrayAdapter<String>(activity, android.R.id.text1, data));

        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = (MainActivity) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        this.activity = null;
    }
}

And also you won't need all that code in your activity. Android will initialize and show the fragment for you automatically.


text:
Q: Passing json object from grails controller to a gsp rendering a d3 chart? I'm creating a d3 chart using a json object created in a grails controller..At the moment I'm passing the json to the view as a string which does't seem to be the best approach.
d3 provides a method to pass a json file with a url e.g
d3.json("https://api.github.com/repos/mbostock/d3/git/blobs/2e0e3b6305fa10c1a89d1dfd6478b1fe7bc19c1e?" + Math.random())
.on("progress", function() {

I would like to use this method by providing a contoller action url. I'm wondering if this is possible and if so what should the return type be? A json object or a file? I'm fairly new to grails and d3 so am having a bit of trouble

A: render as JSON in controller should be helpful in this case.
If your response can be represented as a map or list, then use
import grails.converter.JSON

render myRespone as JSON

In case you need the response to be rendered in different formats, withFormat can be used to suffice the purpose.


text:
Q: Is there a way to add an 'X more events' style message to the Kendo Scheduler in month view? I'm using ASP.NET MVC with Kendo UI version: "2014.2.716".
Is there a way to change the default '...' in the Kendo Scheduler control to a custom message with say '13 more events'?

This is what I have tried so far. I know I can capture the data bound event ...
@(Html.Kendo().Scheduler<MyViewModel>()
        .Name("myScheduler")
        .Selectable(true)
        .EventTemplateId("event-template")
        .Events(e =>
        {
            e.DataBound("calDataBound");
        })
        .Views(views =>
        {
            views.DayView();
            views.WeekView();
            views.MonthView();
            views.AgendaView();
        })
       @* Other markup removed for brevity ... *@

... then in javascript use jQuery to get these elements ...
function calDataBound(e) {
        $(".k-more-events span").each(function (index, element )
        {

        });
}

... but what I don't know is how would I get the number of events in the day represented by this cell?!

A: So this has worked for me ...
function calDataBound(e) {

    var scheduler = this;
    var view = scheduler.view();
    var dataSourceData = scheduler.dataSource.data();

    // For every element that has the more events ellipses '...'
    view.table.find(".k-more-events span").each(function () {
        if ($(this) != null) {
            var element = $(this);
            if (element != null) {
                var slot = scheduler.slotByElement(element);
                if (slot != null) {
                    var slotStart = slot.startDate;
                    var slotEnd = slot.endDate;

                    var totalAppts = 0;
                    var visibleAppts = 0;

                    for (var i = 0; i < dataSourceData.length; i++) {
                        var appt = dataSourceData[i];
                        var apptStartDt = appt.start;
                        var apptEndDt = appt.end;

                        // Include only appointments that are in or overlap the entire day
                        if (slotStart < apptEndDt && slotEnd > apptStartDt) {
                            totalAppts += 1;

                            var selector = 'div[data-uid="' + appt.uid + '"]';
                            if ($(selector).length > 0) {
                                visibleAppts += $(selector).length;
                            }
                        }
                    }

                    var totalHidden = totalAppts - visibleAppts;
                    if (totalHidden > 0) {
                        element.text(totalHidden + ' more ...');
                    }
                }
            }
        }
    });
}

I also had to tweak the css for .k-more-events so that the panel was big enough to show the text e.g.
.k-more-events > span {
  margin-top: 0em;
  height: 20px;
}

div.k-more-events {
  font-size: 12px;
  height: 20px;
}


text:
Q: const std::map? // BOOST Includes
#include <boost/assign.hpp>             // Boost::Assign
#include <boost/assign/list_of.hpp>     // Boost::Assign::List_Of
#include <boost/assign/std/map.hpp>     // Boost::Assign::Map_List_Of
#include <boost/tuple/tuple.hpp>        // Boost::Tuples
// STD Includes
#include <map>
#include <vector>
#include <string>
// Using namespaces
using namespace std;
using namespace boost;
using namespace boost::assign;
// Consts
    const map<string, string> query_map = map_list_of<string, string>
    ("4556_SELECT_FILENAME", "SELECT FILENAME FROM Files WHERE PMU_ID = 4556")
    ("7552_SELECT_FILENAME", "SELECT FILENAME FROM Files WHERE PMU_ID = 7552")
    ("234x_SELECT_FILENAME", "SELECT FILENAME FROM Files WHERE PMU_ID = 2344 OR PMU_ID = 2345 OR PMU_ID = 2346 OR PMU_ID = 2347 OR PMU_ID = 2348")
    ("813x_SELECT_FILENAME", "SELECT FILENAME FROM Files WHERE PMU_ID = 8132 OR PMU_ID = 8133 OR PMU_ID = 8134 OR PMU_ID = 8135 OR PMU_ID = 8136");
    const map<string, std::vector<int>> vector_map = map_list_of<string, std::vector<int>>
    ("4556", list_of(4556))
    ("7552", list_of(7552))
    ("234x", list_of(2344)(2345)(2346)(2347)(2348))
    ("813x", list_of(8132)(8133)(8134)(8135)(8136));

Using boost - it's possible to init const std::containers for testing etc.
making a const std::map or std::map is pretty easy as the above code shows. Creating a const map<string, std::vector<int>> is a bit more complex - but still fairly easy.
I'm trying to come up with a const std::map<boost::tuples::tuple<string, string, string>, string> but I'm failing to initialize it. Has anyone else had any luck with it ?
// Typedefs
typedef boost::tuples::tuple<string, string, string> x3_string_tuple;
// Constants
const map<x3_string_tuple, string> query_selector_map = map_list_of<x3_string_tuple, string>
("4556", "SELECT", "FILENAME"), "4556_SELECT_FILENAME"); // ETC.

A: I tried this, and it fails because the keys of the map need to be comparable (with std::less, thus there needs to be an operator< defined). boost::tuple's comparison operators are defined in the header boost/tuple/tuple_comparison.hpp.
Having included that, this code works fine:
#include <boost/assign/list_of.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>
#include <map>
#include <string>

using std::string;
typedef boost::tuple<string, string, string> tpl_t;

int main() {
    using boost::assign::map_list_of;
    std::map<tpl_t, string> const m =
        map_list_of(tpl_t("a","b","c"), "c")(tpl_t("x","y","c"), "z");
}

A: I would try
const map<x3_string_tuple, string> query_selector_map = map_list_of<x3_string_tuple, string>
(x3_string_tuple("4556", "SELECT", "FILENAME"), "4556_SELECT_FILENAME");

But, honestly, maybe it's easier just to have 3 separate lists of strings, and then one-by-one combine them into a tuple and add that to a map.


text:
Q: Calculating the area of a triangle using methods in the System.Math class (C#) I am studying C# and found this practice problem:
Write a program that calculates the area of a triangle with the following given:
the lengths of two sides and the angle between them (hint: side-angle-side)
I know how to find the area of a triangle in C# if I have the base and the height, and I know that there's a way to use the .Cos method in the .Math class in order to get the cosine that I need for my problem. However, my program does not seem to like the syntax that I am using. May I have any advice for how to implement methods in the .Math class in order to solve a geometry problem like this that takes user input for the side, the angle, and the other side?
I know that the formula is
c^2 = a^2 + b^2 - 2ab * cos(y)   //where y = the degree of the angle
Here is what I have so far, which I think will get across what I am trying to do:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace day_of_the_week
{

    class Program

    {

        static void Main(string[] args)

        {

            double side1;
            double side2;
            double angle;

            Console.WriteLine("Enter one side length.");
            side1 = Convert.ToDouble(Console.ReadLine());

            Console.WriteLine("Enter the other side's height.");
            side2 = Convert.ToDouble(Console.ReadLine());

            Console.WriteLine("Enter the value of the angle.");
            angle = Convert.ToDouble(Console.ReadLine());

            double thirdside = Program.thirdside(side1, side2);
            Console.WriteLine(thirdside);
            Console.ReadLine();
            }
      public static double thirdside(double side1, double side2, double angle)
        {
            return (side1*side1 +  side2*side2 - 2*side1*side2.Cos(angle));
        }
        }
    }

A: Implement your function with calls to Math.Cos and Math.Sqrt, like this:
public static double rad(double deg)
{
    return deg * Math.PI / 180;
}

public static double thirdside(double side1, double side2, double angleDeg)
{
    double angleRad = rad(angleDeg);
    return Math.Sqrt(side1*side1 + side2*side2 - 2*side1*side2*Math.Cos(angleRad));
}

Bear in mind that it is likely that you will want to input the angle in degrees. But Math.Cos accepts the angle in radians, hence the conversion.
And the code in the question neglected to take the square root of the expression. The code in this answer does so.

A: Need to specify class. so that is Math.Cos(angle). Also use Math.Pow(side1, 2) to square numbers.

A: Note that the area of the triangle is
0.5*side1*side2*sin(toRadians(angle))

if angle is the angle between side1 and side2.