text:
Q: How to compile Eigen in iPhone I want to compile Eigen and use it in iPhone with NEON features.
How to compile Eigen in iPhone? Do In need to compile for specific ARM chip? And do I need to modify build script?
Cheers.

A: Since explicit vectorization for ARM NEON is supported out of the box in recent versions of Eigen I'm guessing you shouldn't have to do anything special at all. The section on installation in the manual reads:

In order to use Eigen, you just need to download and extract Eigen's source code (see the wiki for download instructions). In fact, the header files in the Eigen subdirectory are the only files required to compile programs using Eigen. The header files are the same for all platforms. It is not necessary to use CMake or install anything.

Summary: it's an all-header library. No compilation needed.
Assuming you have the proper toolchain set up you should be good to go. If you're using one of the supported compilers (gcc, I assume) it should auto-detect which optimizations to compile (edit: assuming the right compiler flags, e.g. NEON turned on).
As for how to compile stuff for iPhone, well, on that topic I'm oblivious :D


text:
Q: Jquery Trigger listbox selected item from image-map i'm trying to get a link from a image map to change selected item in listbox
so that each link on image-map changes the selected item in listbox
<form id="form1" name="form1" method="post" action="">
  <select name="select" id="select">
    <option>1</option>
    <option>2</option>
    <option>3</option>
  </select>
</form>

how can i do this in jquery ?
thanks in advance ;)

A: This how you can trigger listbox selection according to the image map link:
<img src="http://www.w3schools.com/tags/planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap" />

<map name="planetmap" id="planetmap">
    <area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun" id="sun" />
    <area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury" id="mercury" />
    <area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus" id="venus" />
</map>

<select id="listbox">
    <option value="sun">Sun</option>
    <option value="mercury">Mercury</option>
    <option value="venus">Venus</option>
</select>

<script type="text/javascript">
    $('#planetmap area').click(function(e) {
        alert('Selecting the ' + this.alt + '\n URL: ' + this.href);
        $('#listbox option[value="' + this.id + '"]').attr('selected', 'selected');
        return false;
    });
</script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't display my rows from my data extensions? I have two data extensions, books & subscribers

I am trying to extract the list of books as well as the name of the user assigned to each book via the id ( subscriber id )
This is my code :

        Book name
        Book price
        Owner

%%[

var @bookQueries
set @bookQueries = LookupRows("TaouBenTestBooks","return","1")

If RowCount(@bookQueries) > 0 Then
For @i = 1 to RowCount(@bookQueries) do
SET @bookQuery = ROW(@bookQueries, @i)
SET @subscriberId = FIELD(@bookQuery, 'subscriberId')
SET @bookName = FIELD(@bookQuery, 'bookName')
SET @bookPrice = FIELD(@bookQuery, 'bookPrice')

If IsNull(@subscriberId) Then

SET @firstname = LOOKUP("TaouBenTestSubscribers", "firstname", "id", @subscriberId)
SET @lastname = LOOKUP("TaouBenTestSubscribers", "lastname", "id", @subscriberId)
SET @fullname = Concat(@firstname, " ", @lastname)
]%%

        %%=v(@bookName)=%%
        %%=v(@bookPrice)=%%
        %%=v(@fullname)=%%

%%[

ENDIF

Next @i

Else
]%%
ERROR MAYBE ?
%%[
endif

]%%

What I get is just empty table, I don't neither the data neither the info, and I don't get any errors as well, just the table header
What is wrong in your opinions ?
Any help would be much appreciated.

A: The issue is in the usage of the IsNull function in the IF statement within FOR loop.
You might have confused the logic to check @subscriberId. You need to check if the @subscriberId is not empty, then proceed further and do some Lookups to set the variables which are used later on in the table.
In the code, you have the opposite logic - if @subscriberId is null, then do some Lookups but @subscriberId is not null, thus no Lookups are performed and leads to the empty table.
To fix it, simply change If IsNull(@subscriberId) Then --> If NOT EMPTY(@subscriberId) Then
upd: You do not get a text from the ELSE part because RowCount(@bookQueries) > 0 is true, you do have some records coming from LookupRows. However, your If IsNull(@subscriberId) Then statement is wrapping Lookups + output of Lookups + output of fields from LookupRows. In other words, you are checking when @subscriberId is null and since it is not null, all content below up to the ENDIF (the one before Next @i)is hidden.


text:
Q: Bootstrap ~ "aria-expanded" not accept by element  I lack of idea why the sample copy from Bootstrap are not able to workout and keep throwing the error message on below:

Attribute "aria-expanded" not allowed on element "a" at this point.

Home

Log-In

                                Management

Action

Another action

Something else here

Separated link

One more separated link

Anyone have face the same problem before? Please help!!!

A: Use below

or

instead of directly setting
aria-expanded="false"

and
aria-expanded="true"

respectively


text:
Q: Winapi - Extended Keyboard Scan Codes If I wanted to simulate a keypress using an extended scan code like 0xE0 0x1D (for right CTRL), how would I simulate such a keypress in C? I've tried calling SendInput with two INPUT structs, but only the left CTRL key was "pressed". The same thing happens in the case of other keys that have a "twin" (Shift and Alt).
Secondly, how would one cause a keyup event for an "extended" key?

A: The KEYBDINPUT structure has a KEYEVENTF_EXTENDEDKEY flag to handle the 0xE0 byte for you:

If specified, the scan code was preceded by a prefix byte that has the value 0xE0 (224).

Try something like this:
INPUT inputs[2];
ZeroMemory(inputs, sizeof(inputs));

inputs[0].type = INPUT_KEYBOARD;
inputs[0].ki.wScan = 0x1D;
inputs[0].ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_EXTENDEDKEY;

CopyMemory(&inputs[1], &inputs[0], sizeof(INPUT));
inputs[1].ki.dwFlags |= KEYEVENTF_KEYUP;

SendInput(2, inputs, sizeof(INPUT));

However, I would suggest using a virtual key instead of a scan code:
INPUT inputs[2];
ZeroMemory(inputs, sizeof(inputs));

inputs[0].type = INPUT_KEYBOARD;
inputs[0].ki.wVk = VK_CONTROL;
inputs[0].ki.dwFlags = KEYEVENTF_EXTENDEDKEY;

CopyMemory(&inputs[1], &inputs[0], sizeof(INPUT));
inputs[1].ki.dwFlags |= KEYEVENTF_KEYUP;

SendInput(2, inputs, sizeof(INPUT));

But, if you absolutely need a scan code, at least have a look at MapVirtualKey() to convert a virtual key into a scan code:
inputs[0].type = INPUT_KEYBOARD;
inputs[0].ki.wScan = MapVirtualKey(VK_RCONTROL, MAPVK_VK_TO_VSC);
inputs[0].ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_EXTENDEDKEY;

A: You did not specify whether the keys are to be sent to the same application or another application. Using SendInput, we cannot specify where keys go. We must somehow ensure that the window is active and that the focus is set properly.
Note that a SendInput will send a WM_KEYDOWN or WM_KEYUP message.
You have more flexibility if you use SendMesage directly to send WM_KEYDOWN and WM_KEYUP messages. You specify the window handle of the window to send to.
The window handle is for a text box or a control that takes text, not the window that the text box or other control is in.
This is how to determine the exact parameters to use in a SendMessage. Note that a SendInput will produce a SendMessage.
In Visual Studio click on the Tools menu. You will see "Spy++" and "Spy++ x64". I am not sure when we need one or the other but if one does not work then try the other. In Spy++ click on the Messages menu then "Logging Options...". In the upper-right area click on the Findor Tool and drag to a window. After you release the mouse, click on the Messages tab. Then click on "Clear All" then check the checkbox for "Keyboard". Note that the Messages menu also has commands for starting and stopping the logging but I think it is on by default. Go to the selected window and type the keys you want to try. Then look at the messages logged in Spy++. You will see all the messages that were sent to/from the window. I usually stop the logging as soon as I have everything I need since, depending on the messages selected for logging, there might be too many messages logged to be useful. If you are only logging keyboard messages then you won't get too many messages logged.
For me the Extended field is 1 for the right Ctrl and 0 for the left Ctrl.


text:
Q: Get information from Facebook Graph I'm trying to pull id, gender, birthday, username, friends list and some other information about the user.
Heres my code:
    if ($user) {
  try {
    $user_profile = $facebook->api('/me?fields=id, username, gender, birthday, friends', 'GET');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}

The only thing is it only works when fields=id is the only parameter.
Is there another way i should be doing this?

A: I have been working with the Facebook API today for my App and I managed to create a simple class, maybe this method will help you out.
public function getUserInfo($fields = null)
{
    if($fields == null)
    {
        $fields = array('first_name','last_name','profile_update_time','current_location', 'sex', 'birthday', 'pic_square');
    }

    return $this->facebook->api_client->users_getInfo($this->fbUser, $fields);
}

Basically, $this->Facebook = new Facebook($this->apiKey, $this->secretKey); and $this->fbUser = $this->facebook->getUser();
Hope this helps!


text:
Q: Import a .csv with large numbers into R without scientific notation I have a Microsoft Excel (.xlsx) file which I would like to load into R. I've done this before and used read.csv(), which always worked fine, but with this file something strange happens. Something seems to go wrong with one column, which contains a row name and large numbers with values of 13 digits. This column is - no matter how I try to load the file into R - converted to its scientific notation.
The problem can be simulated as follows: in Excel, type in the first column first
row, a random row name. Type in the first column second row a random big number, e.g. 6345157890027. Then save the file as .csv. Let's suppose I want to open this file in R:
TestData <- read.csv(file = "Test.csv", head = TRUE) and then
View(TestData)
The number 6345157890027 is now displayed as 6.345158e+12, and information is lost somewhere during import. Now, I've tried to solve this multiple ways:

*

*In both the .xlsx and the .csv file, I converted the row
into number format

*Tried all .csv formats that Excel allows me to save it in

*Copied the whole worksheet to a new Excel file

*Used the Import Data function in Excel

*Save the worksheet as .txt and import this into R using File->Import Dataset function

However, none of these solved the problem: the value always seems to appear in scientific notation. Does someone knows a way to make sure either Excel or R does not transform large numbers into scientific notation?

A: I solved this problem by using the format function, as proposed in another post by rnso (see How to prevent scientific notation in R?):
> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"

Also worked perfectly for my wrongly displayed column in my data frame

A: One can just declare options(scipen = 999) and make sure that the environment does not change large numbers to exponential form.

A: you could use the as.bit64 function from the bit64  package. Just make sure to not use 64bit numbers to reference other R objects. This solutions is good for numbers found in the +-2^63 range.


text:
Q: Generating Functions: Solving a Second-Order Recurrence I'm self-studying generating functions (using GeneratingFunctionology as a text).  I came across this programming problem, which I immediately recognized as a modification of the Fibonacci sequence.  I wanted to place my newly found generating function techniques to work, so I tried to solve the recurrence.
The problem basically boils down to solving:

$$a_{n+2} = a_{n+1} + ka_n$$
  Where $n \ge 0$, and $k$ is some positive integer.
  And, $a_0 = 1$, $a_1 = 1$.

However, my solution (below, but not really simplified, since I'm just plugging it into a computer) yields values that too great by a factor of $k$.
My solution:

$$a_n = \frac{r_2^{n+1} - r_1^{n+1}}{(r_2-r_1)r_1^{n+1}r_2^{n+1}}$$
  Where:
  $$r_1 = \frac{-1 - \sqrt{1+4k}}{2k}$$
  $$r_2 = \frac{-1 + \sqrt{1+4k}}{2k}$$

If someone could help me understand where I went wrong, I'd much appreciate it.  (I don't see why I'm too great by a factor of $k$.)
My work is as below:
$$a_{n+2} = a_{n+1} + ka_n$$
$$\sum_{n\ge0}a_{n+2}x^n = \sum_{n\ge0}a_{n+1}x^n + k\sum_{n\ge0}a_{n}x^n$$
Let $A(x) = \sum_{n\ge0}a_nx^n$.  Then:
$$\frac{A(x) - a_0 - xa_1}{x^2} = \frac{A(x) - a_0}{x} + kA(x)$$
$$A(x)\left(\frac{1}{x^2} -\frac{1}{x} - k\right) = \frac{1+x}{x^2} - \frac{1}{x}$$
$$A(x)\left(\frac{1 - x - kx^2}{x^2}\right) = \frac{1}{x^2}$$
$$A(x)= \frac{1}{1 - x - kx^2}$$
Now, factoring the denominator yields two roots, $r_1$ and $r_2$ as denoted above.  This, in turn, yields:
$$A(x) = \frac{1}{(x-r_1)(x-r_2)}$$
Partial fractions:
$$A(x) = \frac{1}{r_2-r_1}\frac{1}{(r_1 - x)} - \frac{1}{r_2-r_1}\frac{1}{(r_2 - x)}$$
$$A(x) = \frac{1}{(r_2-r_1)(r_1)}\frac{1}{(1 - \frac{x}{r_1})} - \frac{1}{(r_2-r_1)(r_2)}\frac{1}{(1 - \frac{x}{r_2})}$$
$$A(x) = \frac{1}{(r_2-r_1)(r_1)}\sum_{n\ge0}{\left(\frac{x}{r_1}\right)^n} - \frac{1}{(r_2-r_1)(r_2)}\sum_{n\ge0}{\left(\frac{x}{r_2}\right)^n}$$
Combining:
$$A(x) = \sum_{n\ge0} x^n \left(\frac{1}{(r_2-r_1)(r_1^{n+1})} - \frac{1}{(r_2-r_1)(r_2^{n+1})}\right)$$
Therefore:
$$a_n = \frac{r_2^{n+1} - r_1^{n+1}}{(r_2-r_1)r_1^{n+1}r_2^{n+1}}$$

A: Something went wrong between
$$A(x)= \frac{1}{1 - x - kx^2}$$
And
$$A(x) = \frac{1}{(x-r_1)(x-r_2)}$$

A: $$1-x-kx^2=-kx^2-x+1\Rightarrow x_{1,2}=\frac{1\pm\sqrt{1+4k}}{2}$$so
$$1-x-kx^2=-kx^2-x+1=(-k)(x-x_1)(x-x_2)=(-k)(x-\frac{1-\sqrt{1+4k}}{2})(x-\frac{1+\sqrt{1+4k}}{2})$$


text:
Q: Selecting rows from a table with specific values per id I have the below table
Table 1
Id   WFID  data1   data2
1    12    'd'     'e'
1    13    '3'     '4f'
1    15    'e'     'dd'
2    12    'f'     'ee'
3    17    'd'     'f'
2    17    'd'     'f'
4    12    'd'     'f'
5    20    'd'     'f'

From this table I just want to select the rows which has 12 and 17 only exclusively. Like from the table I just want to retrieve the distinct id's 2,3 and 4. 1 is excluded because it has 12 but also has 13 and 15. 5 is excluded because it has 20.

*

*2 in included because it has just 12 and 17.

*3 is included because it has just 17

*4 is included because it has just 12

A: If you just want the list of distinct ids that satisfy the conditions, you can use aggregation and filter with a having clause:
select id
from mytable
group by id
having max(case when wfid not in (12, 17) then 1 else 0 end) = 0

This filters out groups that have any wfid other than 12 or 17.
If you want the entire corresponding rows, then window functions are more appropriate:
select
from (
    select t.*,
        max(case when wfid not in (12, 17) then 1 else 0 end) over(partition by id) flag
    from mytable t
) t
where flag = 0

A: You really need to start thinking in terms of sets. And it helps everyone if you provide a script that can be used to experiment and demonstrate. Here is another approach using the EXCEPT operator. The idea is to first generate a set of IDs that we want based on the filter. You then generate a set of IDs that we do not want. Using EXCEPT we can then remove the 2nd set from the 1st.
declare @x table (Id tinyint, WFID tinyint, data1 char(1), data2 varchar(4));

insert @x (Id, WFID, data1, data2) values
(1,    12,    'd',     'e'),
(1,    13,    '3',     '4f'),
(1,    15,    'e',     'dd'),
(2,    12,    'f',     'ee'),
(3,    17,    'd',     'f'),
(2,    17,    'd',     'f'),
(4,    12,    'd',     'f'),
(2,    12,    'z',     'ef'),
(5,    20,    'd',     'f');

select * from @x
select id from @x where WFID not in (12, 17);

select id from @x where WFID  in (12, 17)
except
select id from @x where WFID not in (12, 17);

Notice the added row to demonstrate what happens when there are "duplicates".


text:
Q: How to implement Restful design to request webpage stored for magnolia I have a question concerning how to implement restful design to request webpage stored in magnolia JCR.
For example,
I have a list page called itemList [www.example.com/itemList], which contains a list of item.
And i have a item page [www.example.com/itemList/item/1], which is a child page of itemList (which can be seen in the PAGES app).
If i want to get item with ID no.1, just like other restful design, just use URL [www.example.com/itemList/item/1], and it will return whole page of item with item no.1 data (which i need to store the ID and pass it to the JAVA custom module in template script to get the data)
But here is the problem,
as i study in the magnolia documentation, like
https://documentation.magnolia-cms.com/display/DOCS57/How+to+create+a+custom+Java-based+REST+endpoint
it just tell about create rest endpoint and get the JSON data back as for manuplation.
And i got stuck at how to achieve my goal, may i have some suggestions?
Thanks a lot for any help. ORZ

A: Actually in Magnolia you don't need to create a custom endpoint for that, you can use the pre-defined ones which are sufficient to achieve what you want. Have a look  at https://documentation.magnolia-cms.com/display/DOCS57/REST+API
Let me know if that covers what you need or any other extra questions that should you have.
Hope that helps,
Cheers,


text:
Q: Custom template doesn't visiable in the template suffix section in shopify I have added a new custom template like page.about.liquid in the template folder. But this template is not visible on Template suffix section. screenshot attached below. Can anybody help me here?
https://www.screencast.com/t/hJGH3VzN
https://www.screencast.com/t/PLdBPiuYp
{% include 'page-header', title: 'About Us' %}

        {{page.content}}

A: As per Shopify documentation, only templates present in your published theme will be available in the Theme templates section.

The Theme templates section won't appear on the corresponding page
  unless your theme has more than one template. If you don't see the
  Theme templates section after creating a new template, it's possible
  that you have created a template of a different type. For example, you
  might have created a page template instead of a product template.
Only templates present in your published theme will be available in
  the Theme templates section.


text:
Q: What are the implications of using mutable types as default arguments in Python?
Possible Duplicates:
Why the "mutable default argument fix" syntax is so ugly, asks python newbie
least astonishment in python: the mutable default argument

Here is an example.
def list_as_default(arg = []):
    pass

A: From: http://www.network-theory.co.uk/docs/pytut/DefaultArgumentValues.html
The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:
def f(a, L=[]):
    L.append(a)
    return L

print f(1)
print f(2)
print f(3)

This will print
[1]
[1, 2]
[1, 2, 3]

If you don't want the default to be shared between subsequent calls, you can write the function like this instead:
def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L


text:
Q: After upgrading iphone app to ipad app I upgraded my iphone app an now it is compatible with iOS3 and ipad. I created two copies of my project. I upgraded one copy to two device-specific application and second copy to one universal application.
Now two device specific app runs in ipad and and appears with 1x zoom. it shows a 2x zoom button which makes it fit to the ipad screen. It also changes the size of UI Element. Is it the default behavior of ipad application?
While one universal application opens in ipad withot showing 2x zoom button. It automatically fits the screen size to ipad screen size but the problem is that it doesn't change size of UI elements like datepicker etc. Is it the default behavior of ipad application?
As far as I know ipad application should open with full screen without showing 2x zoom and it should also change the size of UI elements. So both of them are not working fine. Am I wrong? If not, how do I fix this problem.
If I am wrong please tell me which universal app is working correctly for ipad.

A: The UIDatePicker is not supposed to be shown in a screen-filling fashion on the iPad. In fact, even if you manage to get it filling the entire screen (which is possible), your app will get rejected as this is not the way you should be using it on the iPad. Depending on the context, it might be a good idea to consider using a UIPopoverController for showing the UIDatePicker.


text:
Q: When I INSERT multiple rows into a MySQL table, will the ids be increment by 1 everytime? if I have a query like the following:
INSERT INTO table (col1,col2,col3) VALUES
('col1_value_1', 'col2_value_1', 'col3_value_1'),
('col1_value_2', 'col2_value_2', 'col3_value_2'),
('col1_value_3', 'col2_value_3', 'col3_value_3');

Suppose that I have a table where the last id PRIMARY_KEY AUTO_INCREMENT value is 56, then will this insert query always create 3 records with ids 57, 58, 59. Is this operation atomic?
Or, if another query writes on the same table, could the ids not increment always by 1?
Thanks for the attention!
EDIT: Please read the following because maybe I wasn't so clear.
Of course AUTO_INCREMENT increments by one safely, I know that.
The point is:
Let's say I have the following table called table:
 ___________________________________
| id | col1       | col2             |
-------------------------------------
|  1 | "some val" | "some other val" |
|  2 | "some val" | "some other val" |
|  3 | "some val" | "some other val" |
|  4 | "some val" | "some other val" |
|  5 | "some val" | "some other val" |
|  6 | "some val" | "some other val" |
|____________________________________|

If I know run the query:
INSERT INTO table (col1,col2) VALUES
('some val', 'some other val'),
('some val', 'some other val'),
('some val', 'some other val')

I will end up with the following table:
 ___________________________________
| id | col1       | col2             |
-------------------------------------
|  1 | "some val" | "some other val" |
|  2 | "some val" | "some other val" |
|  3 | "some val" | "some other val" |
|  4 | "some val" | "some other val" |
|  5 | "some val" | "some other val" |
|  6 | "some val" | "some other val" |
|  7 | "some val" | "some other val" |
|  8 | "some val" | "some other val" |
|  9 | "some val" | "some other val" |
|____________________________________|

Nothing to say here. But if me and another guy run the same query at the same time, are these queries atomic?, meaning that we will always end up with:
1)
 ___________________________________
| id | col1       | col2             |
-------------------------------------
|  1 | "some val" | "some other val" |
|  2 | "some val" | "some other val" |
|  3 | "some val" | "some other val" |
|  4 | "some val" | "some other val" |
|  5 | "some val" | "some other val" |
|  6 | "some val" | "some other val" |
|  7 | "some val" | "some other val" |<-- My 1st inserted record
|  8 | "some val" | "some other val" |<-- My 2nd inserted record
|  9 | "some val" | "some other val" |<-- My 3rd inserted record
| 10 | "some val" | "some other val" |<-- Another guy's 1st inserted record
| 11 | "some val" | "some other val" |<-- Another guy's 2nd inserted record
| 12 | "some val" | "some other val" |<-- Another guy's 3rd inserted record
|____________________________________|

Or with:
2)
 ___________________________________
| id | col1       | col2             |
-------------------------------------
|  1 | "some val" | "some other val" |
|  2 | "some val" | "some other val" |
|  3 | "some val" | "some other val" |
|  4 | "some val" | "some other val" |
|  5 | "some val" | "some other val" |
|  6 | "some val" | "some other val" |
|  7 | "some val" | "some other val" |<-- Another guy's 1st inserted record
|  8 | "some val" | "some other val" |<-- Another guy's 2nd inserted record
|  9 | "some val" | "some other val" |<-- Another guy's 3rd inserted record
| 10 | "some val" | "some other val" |<-- My 1st inserted record
| 11 | "some val" | "some other val" |<-- My 2nd inserted record
| 12 | "some val" | "some other val" |<-- My 3rd inserted record
|____________________________________|

Depending on which query of the two MySQL schedules first.
Or could the following abnormalities arise too?:
3)
 ___________________________________
| id | col1       | col2             |
-------------------------------------
|  1 | "some val" | "some other val" |
|  2 | "some val" | "some other val" |
|  3 | "some val" | "some other val" |
|  4 | "some val" | "some other val" |
|  5 | "some val" | "some other val" |
|  6 | "some val" | "some other val" |
|  7 | "some val" | "some other val" |<-- My 1st inserted record
|  8 | "some val" | "some other val" |<-- My 2nd inserted record
|  9 | "some val" | "some other val" |<-- Another guy's 1st inserted record - WTF???
| 10 | "some val" | "some other val" |<-- My 3rd inserted record
| 11 | "some val" | "some other val" |<-- Another guy's 2nd inserted record
| 12 | "some val" | "some other val" |<-- Another guy's 3rd inserted record
|____________________________________|

Or something like this:
4)
 ___________________________________
| id | col1       | col2             |
-------------------------------------
|  1 | "some val" | "some other val" |
|  2 | "some val" | "some other val" |
|  3 | "some val" | "some other val" |
|  4 | "some val" | "some other val" |
|  5 | "some val" | "some other val" |
|  6 | "some val" | "some other val" |
|  7 | "some val" | "some other val" |<-- Another guy's 1st inserted record
|  8 | "some val" | "some other val" |<-- My 1st inserted record - WTF???
|  9 | "some val" | "some other val" |<-- Another guy's 2nd inserted record
| 10 | "some val" | "some other val" |<-- My 2nd inserted record - WTF^2???
| 11 | "some val" | "some other val" |<-- Another guy's 3rd inserted record
| 12 | "some val" | "some other val" |<-- My 3rd inserted record - WTF^3???
|____________________________________|

Or any other combination != 3) and 4)?
I consider 1) and 2) as atomic. Is it always guaranteed that I will always end up with 1) or 2) and never ever end up with 3) or 4) or any other combination? And if yes (I will always end up with 1) or 2)), both for MyISAM and InnoDB?
If I do SELECT LAST_INSERT_ID(); and e.g. I get 7, does it automatically mean that the rows with id 8 and 9 were also inserted by my query and not by the query of the other guy?

A: The answer is: well, it depends.
In case of myisam, the answer is a definite yes, since myisam sequences insert requests.
In case of innodb, however, the behaviour is configurable since mysql v5.1. before v5.1, then answer for InnoDB is also yes, after that it depends the on the innodb_autoinc_lock_mode setting. See mysql documentation on InnoDB auto_increment configuration for details.
To give you the highlights, there are 3 innodb_autoinc_lock_mode settings:

*

*traditional (0)

*consequtive (1) - default

*interleaved (2)

With innodb_autoinc_lock_mode set to 0 ("traditional") or 1 ("consecutive"), the auto-increment values generated by any given
  statement will be consecutive, without gaps, because the table-level
  AUTO-INC lock is held until the end of the statement, and only one
  such statement can execute at a time.
With innodb_autoinc_lock_mode set to 2 ("interleaved"), there may be
  gaps in the auto-increment values generated by "bulk inserts," but
  only if there are concurrently executing "INSERT-like" statements.
For lock modes 1 or 2, gaps may occur between successive statements
  because for bulk inserts the exact number of auto-increment values
  required by each statement may not be known and overestimation is
  possible.

Further gaps can be experience in the auto_increment value, if a transactions has been rolled back. A bulk insert can only be rolled back as a whole.
UPDATE:
As described above, you will get scenario 1) or 2), if you use

*

*myisam table engine

*or innodb pre mysql v5.1

*or innodb with mysql v5.1 or newer and the innodb_autoinc_lock_mode is 0 or 1

There is no way of telling which gets inserted first.
You may get scenario 3) or 4) if you use

*

*innodb with innodb_autoinc_lock_mode 2

Again, there is no way of telling how and why mysql mixes up the order of the records.
So, if your question is related to the fact that you insert 3 records with bulk insert and last_insert_id() returns the auto_increment value of the first inserted record only, and you want get the ids of the other 2 records by simple addition is that you may need to check mysql's configuration based on the table engine and mysql version used.

A: If you define any column primary key aut_increment then it will automatically increase value start from 1,
you don't need to define this column in insert query then it will automatically insert incremented value in primary key column.

A: auto_increment is safe in concurrent environment. It's job is to give unique values, no matter how many people you have connected and working on a table. You can control the offset for incrementing, by default it's 1.
Now what does this actually mean - it means that what's written in the table doesn't have to be incremented by 1. This is the famous "gap" problem.
Suppose that you and I are writing to your table at the same time. I wrote records 10, 11, 12 and you wrote 13, 14, 15. However, something bad could have happened (a deadlock, or transaction failed) and my results aren't persisted - the queries failed and the auto_increment got spent. In this scenario, your records (13, 14, 15) are written to the disk and my aren't.
This is normal behaviour. Your table doesn't have to contain numbers that are incremented by 1. It will contain unique numbers and that's the job of auto_increment.

A: mysql treat multi insertion query as a transaction or one query, all rows will be inserted or if it failed there is no rows will be inserted, so if you insert this query:
INSERT INTO table (col1,col2,col3) VALUES
('col1_value_1', 'col2_value_1', 'col3_value_1'),
('col1_value_2', 'col2_value_2', 'col3_value_2'),
('col1_value_3', 'col2_value_3', 'col3_value_3');

mysql will run this as a one query, if your id auto incremental it will take your ids 57,58,59.
if the other user pass insert query in the same time, it will 2 probability if other user query take more time than your query your query will take 57,58,59 if your query take more time than the other user so your ids will start from the other user query end. so whatever the case the multi insert query when id is auto incremental  will be sorted in the query.

A: If you insert value in one statement scenario 3 and 4 don't appear even if you are using them innodb_autoinc_lock_mode = 2. From documentation https://dev.mysql.com/doc/refman/5.7/en/innodb-auto-increment-handling.html

innodb_autoinc_lock_mode = 2
  In this lock mode, auto-increment values are guaranteed to be unique and monotonically increasing across all concurrently executing "INSERT-like" statements.

Tested


text:
Q: How can I reflect on a field annotation (Java) in a Scala program? I'm using Scala 2.13 and I know there's been a lot deprecated since older versions.
I've got this annotation:
@Inherited
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Foo {
    int index() default 0;
}

(I know... I've got lots of ElementTypes there, but I'm struggling to see where this pops up in reflection so wanted to maximize my chances of a hit!)
Used like this:
case class Person(name: String, @Foo(index = 3) age: Int)
val p = Person("Fred", 29)

How can I reflect on this to get the my Java Annotation (Foo), so I can 1) know whether @Foo exists on a given field, and 2) get the index value.  Note I have a declared default value for Foo.index that may be overridden at runtime, so this is a runtime-scoped annotation.

A: Here is solution using Java reflection.
For @(Foo @field)(index = 3) age: Int do
println(classOf[Person].getDeclaredFields.map(_.getDeclaredAnnotationsByType(classOf[Foo]).map(_.index)).deep)
//Array(Array(), Array(3))

For @(Foo @getter)(index = 3) age: Int do
println(classOf[Person].getDeclaredMethods.map(_.getDeclaredAnnotationsByType(classOf[Foo]).map(_.index)).deep)
//Array(Array(), Array(), Array(3), Array(), Array(), Array(), Array(), Array(), Array(), Array(), Array(), Array(), Array())

For @(Foo @param)(index = 3) age: Int or just @Foo(index = 3) age: Int do
println(classOf[Person].getDeclaredConstructors.map(_.getParameters.map(_.getDeclaredAnnotationsByType(classOf[Foo]).map(_.index))).deep)
//Array(Array(Array(), Array(3)))

You can combine meta-annotations @field, @getter, @param.
I guess similar thing can be done with Scala reflection.


text:
Q: Catch all clicks that are not in set I have a navigation drop down that displays on click. However, the pure css functionality requires you to click the link again to close the sub-menu.
I would like to modify it so that any click that is not within the sub-menu closes it.
I've tried something like this, but to no avail:
$('*:not(.submenu > li > a)').click(function() {
    $('nav .dropdown input').removeAttr('checked');
    console.log('clicked outside sub-menu');
});

This registers every click, even those that match .submenu > li > a meaning that the $('nav .dropdown input').removeAttr('checked'); line does work to hide the menu, but it is called even when trying to open the menu, resulting in the menu never opening.
The CSS drop down works via a checkbox input. Here is that CSS if it helps at all, however my problem is in the Javascript, because the CSS functions just fine.
Here is a fiddle, and the CSS is below: https://jsfiddle.net/z3yj7pLs/
ul.dropdown {
    position:fixed;
    top:30px;
    width:100%;
    height:3em;
    margin:0;
    padding:0 10px;
    color:#eee;
}

ul.dropdown > li{
    float:left;
    list-style-type:none;
    position:relative;
}

ul.dropdown label{
    position:relative;
    display:block;
    transition:background 0.3s;
    cursor:pointer;

    bottom: -2px;
    left: -10px;
}

ul.dropdown label:after{
    content:"";
    position:absolute;
    display:block;
    top:50%;
    right:5px;
    width:0;
    height:0;
    border-top:4px solid rgba(255,255,255,.5);
    border-bottom:0 solid rgba(255,255,255,.5);
    border-left:4px solid transparent;
    border-right:4px solid transparent;
    transition:border-bottom .1s, border-top .1s .1s;
}

ul.dropdown label:hover,
ul.dropdown input:checked ~ label{

}

ul.dropdown input:checked ~ label:after{
    border-top:0 solid rgba(255,255,255,.5);
    border-bottom:4px solid rgba(255,255,255,.5);
    transition:border-top .1s, border-bottom .1s .1s;
}

/*hide the inputs*/
ul.dropdown input{display:none}

/*show the second levele menu of the selected voice*/
ul.dropdown input:checked ~ ul.submenu{
    max-height:300px;
    transition:max-height 0.5s ease-in;
}

/*style for the second level menu*/
ul.dropdown ul.submenu{
    max-height:0;
    padding:0;
    overflow:hidden;
    list-style-type:none;
    background:#444;
    box-shadow:0 0 1px rgba(0,0,0,.3);
    transition:max-height 0.5s ease-out;
    position:absolute;
    min-width:100%;
}

ul.dropdown ul.submenu li a{
    display:block;
    padding:12px;
    color:#ddd;
    text-decoration:none;
    box-shadow:0 -1px rgba(0,0,0,.5) inset;
    transition:background .3s;
    white-space:nowrap;
}

ul.dropdown ul.submenu li a:hover{
    background:rgba(0,0,0,.3);
}

A: It would be better to use event delegation for this task:
$('body').on('click', ':not(.submenu > li > a)', function() {
    $('nav .dropdown input').removeAttr('checked');
    console.log('clicked outside sub-menu');
});

That way you aren't adding tons of event handlers to the DOM - just one that ignores clicks to your menu - you may need to adjust the ':not()' selector a bit or use JS in the event handler (e.g. if (!$(this).parents('.submenu').length) { ...collapse }

A: If can listen to clicks on document and then check if the click was not inside the dropdown
$(document).click(function(event) {
    if ($(event.toElement).parents('.dropdown').length > 0) {
        console.log('Clicked inside the dropdown area');
    } else {
        console.log('Clicked outside the dropdown area');
    }
});

Here is a working snippet:

$(document).click(function(event) {
    if ($(event.toElement).parents('.dropdown').length > 0) {
      console.log('Clicked inside the dropdown area');
    } else {
        console.log('Clicked outside the dropdown area');
    }
});
body {
  background: black;
}
ul.dropdown {
  position: fixed;
  top: 30px;
  width: 100%;
  height: 3em;
  margin: 0;
  padding: 0 10px;
  color: #eee;
}

ul.dropdown > li {
  float: left;
  list-style-type: none;
  position: relative;
}

ul.dropdown label {
  position: relative;
  display: block;
  transition: background 0.3s;
  cursor: pointer;
  bottom: -2px;
  left: -10px;
}

ul.dropdown label:after {
  content: "";
  position: absolute;
  display: block;
  top: 50%;
  right: 5px;
  width: 0;
  height: 0;
  border-top: 4px solid rgba(255, 255, 255, .5);
  border-bottom: 0 solid rgba(255, 255, 255, .5);
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  transition: border-bottom .1s, border-top .1s .1s;
}

ul.dropdown label:hover,
ul.dropdown input:checked ~ label {}

ul.dropdown input:checked ~ label:after {
  border-top: 0 solid rgba(255, 255, 255, .5);
  border-bottom: 4px solid rgba(255, 255, 255, .5);
  transition: border-top .1s, border-bottom .1s .1s;
}

/*hide the inputs*/

ul.dropdown input {
  display: none
}

/*show the second levele menu of the selected voice*/

ul.dropdown input:checked ~ ul.submenu {
  max-height: 300px;
  transition: max-height 0.5s ease-in;
}

/*style for the second level menu*/

ul.dropdown ul.submenu {
  max-height: 0;
  padding: 0;
  overflow: hidden;
  list-style-type: none;
  background: #444;
  box-shadow: 0 0 1px rgba(0, 0, 0, .3);
  transition: max-height 0.5s ease-out;
  position: absolute;
  min-width: 100%;
}

ul.dropdown ul.submenu li a {
  display: block;
  padding: 12px;
  color: #ddd;
  text-decoration: none;
  box-shadow: 0 -1px rgba(0, 0, 0, .5) inset;
  transition: background .3s;
  white-space: nowrap;
}

ul.dropdown ul.submenu li a:hover {
  background: rgba(0, 0, 0, .3);
}

    <input id="nav-dropdown-check" type="checkbox" name="menu" />
    More

Sotto menu 1

Sotto menu 2


text:
Q: Inserting Data into Website Textbox, Click on Button and then Retrieve Data Vb.net I am trying to code a program that will go into a website, set a text value to a textbox from this website (which I got the ID), then click in a button. This is how I've codded it:
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim url As String = "https://jucemg.mg.gov.br/ibr"
        Dim Webb As New WebBrowser
        Webb.Navigate(url)
        Webb.ScriptErrorsSuppressed = True
        Webb.Document.GetElementById("numprotocolo").SetAttribute("value", TextBox1.Text)
        Webb.Document.GetElementById("consultar1").InvokeMember("click")
    End Sub
End Class

However, when I run it it gives me a System.NullReferenceException. It says that the WebBrowser.Document.Get has returned Nothing.
What is going wrong with this code?
Also I haven't created a webbrowser in my program, as it is supposed to perform the tasks without the user seeing it, and then just return a value that the website will later give.
Thanks alot!


text:
Q: HttpClient.get does not return observable from Wiki API I'm trying to get some text from specific Wikipedia pages but I cannot access to it. I'm trying to understand how it works and I do not know why it still doesn't, cause no error is given.
I tried several type of URLs like this one: https://www.reddit.com/r/gifs/top/.json?limit=105sort=hot https://gyazo.com/54ee18fe654fcfe2bd5d546b44f85b5d, and it returns.
I suspect it has something to do with CORS but have no idea how it works.
servicio.service.ts code
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class ServicioService {

    constructor(public http: HttpClient) {
        console.log('service working!');
    }

    goWiki(userInput): Observable<any>{
        console.log('goWiki working!');
      //let url = 'https://www.reddit.com/r/gifs/top/.json?limit=105sort=hot';
        return this.http.get('https://es.wikipedia.org/w/api.php?action=query&list=search&srsearch='+ userInput +'&utf8=&format=json',);
    } //took that link from this: <https://en.wikipedia.org/wiki/Special:ApiSandbox#action=query&format=json&meta=siteinfo&siprop=magicwords>

}
...

home.page.ts
import { ServicioService } from '../servicio.service';
...
constructor(
    navcntrlr: NavController,
    private alertcontroller: AlertController,
    public servicio: ServicioService) { }

    userInput = 'alcasser';

    ngOnInit(): void {
      this.search();
    }

    search(){
      console.log("henllo xd");
      const hola = this.servicio.goWiki(this.userInput).
      subscribe((response) => {
       console.log(response);
       });
    }
...

I hope to get an observable json to be able to play with it and take from it the info I need.

A: Your this.userInput is null. When you go to https://es.wikipedia.org/w/api.php?action=query&list=search&srsearch=&utf8=&format=json (this is the url it will try to call), you will see an error
{"error":{"code":"nosrsearch","info":"The \"srsearch\" parameter must be set.","*":"See https://es.wikipedia.org/w/api.php for API usage. Subscribe to the mediawiki-api-announce mailing list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> for notice of API deprecations and breaking changes."},"servedby":"mw1340"}

Try setting this.userInput before your call and try again.
    search(){
      console.log("henllo xd");
      this.userInput = 'test'; // THIS SETS USERINPUT TO 'TEST'
      const hola = this.servicio.goWiki(this.userInput).
      subscribe((response) => {
       console.log(response);
       });
    }

A: When I use their API I get a CORS ERROR too.
I'm able to access their API in the browser
https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=usa&format=json
Here is a quick example i put using your code and passing an actual value to the API, using REACTIVE forms.
import { Component,OnInit } from '@angular/core';
import {FormGroup,FormControl,Validators} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  searchForm:FormGroup;
    constructor(public http: HttpClient) {
        console.log('service working!');
    }

  ngOnInit():void{
    this.searchForm = new FormGroup({
      'searchInput': new FormControl(null),
      });
  }

  onSubmit():void {
    console.log(this.searchForm.value.searchInput);
    this.goWiki(this.searchForm.value.searchInput)
  }

    goWiki(userInput):void{
        console.log('goWiki working!');
        this.http.get('https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch'+ userInput +'&utf8=&format=json').subscribe((response) => {
       console.log(response);
       });
    }
}


text:
Q: Is there a way to know which will be the next bitizen to unlock in TDS? I'm playing TDS without spending any Bux to unlock any bitizens.  (See my other question on that subject.)  And, from conferring with other players, it seems clear that the game unlocks in the same progression for everyone (assuming you don't buy bitizens).
Is there a way to know who is going to unlock next?  I thought it might be the one whose price to unlock is the cheapest in bux, but this has proven incorrect.

A: As it stands, there is no way of knowing which Bitizen will unlock next.
The game does not offer indicators as it does with Levels.

A: As of update 1.3, you can now tell who will be next to unlock by looking in the store or the album.
The price of the next bitizen to unlock will drop to 1 Bux in both places.  If the next to unlock has an associated ? character, then you will see them in the store.  And, the order they appear from the top is the order of unlocking.
This appears to have fixed a bug present in previous versions where this was not working properly.


text:
Q: Как проверить что все элементы массива пустые? Есть массив:
$error = ['url' => null, 'title' => null, 'icon' => null, 'color' => null];

С его помощью я проверяю форму, и если есть ошибки, я в соответствующий элемент массива записываю строку с текстом ошибки.
Например:
Если поле url пустое, тогда массив будет выглядеть так:
Array
    (
        [url] => Это поле обязательно к заполнению
        [title] =>
        [icon] =>
        [color] =>
    )

Сейчас я проверяю так:
if (empty($error['url']) and empty($error['title']) and empty($error['icon']) and empty($error['color'])) {

    'Отправляю форму'

}

Как проверить, что все элементы массива пустые более лучшим способом?
Может есть стандартная функция, которая проверяет на пустоту все элементы массива?

A: $error = ['url' => null, 'title' => "2", 'icon' => null, 'color' => null];
print_r(array_diff($error, array(''))); // Если возвращается пустой массив, значит нет значений. В противном случае вернёт то, которое не пустое.

<?php
$error = ['url' => null, 'title' => "2", 'icon' => null, 'color' => null];

$Empty = ""; // Переменная со значением для вывода
foreach ($error as $key=>$value){ // проверяем массив
    if ($value){
        $Empty = 'есть не пустые значения';
        break;
    } else {
        $Empty = 'Все значения пустые';
    }
}

print_r($Empty); // Выводим сообщение

A: $array = ['url' => null, 'title' => null, 'icon' => null, 'color' => null];

if (empty(array_filter(array_values($array)))) {
    // не заполнено 1 и более полей
}

A: $error = [
    'url' => null,
    'title' => 'Это поле ...',
    'icon' => null,
    'color' => 'Это поле ...'
];
$e = [];

foreach ($error as $k => $v) {
    if ($v) {
        array_push($e, $k);
    }
}

Или проще:
$e = array_keys($error, !null);

Если все элементы $error пустые, массив $e останется пустым, иначе будет содержать значения ключей c непустыми значениями $error
// print_r($e);
Array
(
    [0] => title
    [1] => color
)

A: Можно сделать через array_filter (возвращает все найденные сравнения)
<?php

$error = ['url' => null, 'title' => "2", 'icon' => 2, 'color' => null];

$filter = array_filter($error, function($item) {
    return $item === null;
});

if (empty($filter))
    echo "Все поля заполнены";
else
    foreach($filter as $key => $value) {
        echo "Поле '{$key}' не заполнено" . PHP_EOL;
    }

Можно через array_search (возвращает первый найденный элемент)
<?php

$error = ['url' => null, 'title' => "2", 'icon' => 2, 'color' => null];

$search = array_search(null, $error);

if ($search)
    echo "Поле '{$search}' не заполнено";

Можно через in_array (возвращает bool)
<?php

$error = ['url' => null, 'title' => "2", 'icon' => 2, 'color' => null];

$inArray = in_array(null, $error);

if ($inArray === true)
    echo "Не все поля заполнены";


text:
Q: What "real numbers" (elements in $\mathbb R$), are people referring to? To define mathematical objects, it seems one defines them in terms of other mathematical objects.
However various mathematical objects have different "definitions".
E.g. it seems people "construct" the real numbers (they use objects other than the real numbers, to create an algebraic structure isomorphic to what others consider the real numbers) and then define those as the real numbers. Yet this appears ambiguous to me.
If one were to refer to the "real numbers" would they then be referring to Dedekind Cuts?
Or would they be referring to equivalence classes of Cauchy Sequences?
Or to some other "construction" entirely?

Here are my best two guesses as to what people mean:
$1.$ They are simply referring to any structure isomorphic to the (unique) complete ordered field.
$2.$ They are referring to an equivalence-class$^{*}$ of all structures that are isomorphic to the (unique) complete ordered field.
$*\small(\text{Not an equivalence class in the proper sense with sets as an such object cant be a set by Russell's paradox)}$
The reason $1$ would not result in ambiguity is because we often never need to make use of their original "definitions" per se. Because we can embed the rationals, integers etc. inside the real numbers. However $2$ would avoid this problem entirely as we have only a single definition.

A: Your question is essentially a philosophical one. When ordinary people talk about number, they have a very definite concept in mind. Mathematicians are ordinary people, but have a professional obligation to give logical justifications for their use of the number concept. So when they are concerned about logical foundations, mathematicians give existence proofs for the various number systems by constructing explicit witnesses for systems satisfying the required properties. When they go back to their day-to-day mathematical work, mathematicians forget about the details of these existence proofs and happily work as if $\Bbb{R}$ were a subset of $\Bbb{C}$ and $\sqrt{2}$ were an object that belongs to $\Bbb{R}$, satisfies $x^2 = 2$, but isn't itself a set or a sequence.
There is a seminal paper by Benacerraf What Numbers Could Not Be that anyone interested in the philosophical foundations of mathematics should read.

A: I'd go for (1), slightly modified. If you've just constructed the real numbers in some book or paper, using, say, Dedekind cuts, then in that context a real number is a Dedekind cut, and you use properties of Dedekind cuts to prove theorems about real numbers.
Since there is a unique ordered field (up to unique isomorphism) and your construction provides one, your theorems will be true for anyone else's "real numbers".
Edit: this is essentially @AsafKaraglia 's answer to the duplicate, but much less informative.


text:
Q: Recursive select via LINQ?
Possible Duplicate:
linq to sql recursive query

I got stuck with having to build a Recursive select via LINQ for the self referencing table.

I use this class:
public class DivisionHierarchy
{
    public Division Division { get; set; }
    public IEnumerable<DivisionHierarchy> Divisions { get; set; }
}

and I created this function but somehow it is infinite.
public IEnumerable<DivisionHierarchy> GetDivisionHierarchy(IEnumerable<Division> allDivisions, Division parentDivision)
{
    Guid? parentDivisionId = null;

    if (parentDivision != null)
         parentDivisionId = parentDivision.DivisionID;

    var childDivisions = allDivisions.Where(e => e.DivisionID == parentDivisionId);

    Collection<DivisionHierarchy> hierarchy = new Collection<DivisionHierarchy>();

    foreach (var div in childDivisions)
       hierarchy.Add(new DivisionHierarchy() { Division = div, Divisions = GetDivisionHierarchy(allDivisions, div) });

     return hierarchy;
}

Any clue where I can start?
Thank you!
P.S. Are there any others ways to do it?

UPDATES based on http://www.scip.be/index.php?Page=ArticlesNET18#AsHierarchy
I found my errors.
There are 2 things to implement:
1. The root node should be created under the database.

*I changed code a little bit.
Guid divisionID = Guid.Parse("5b487b3d-e9be-413f-b611-2fd7491e0d0d"); // Hardcoded somehow
var rootDivision = db.Divisions.Where(i => i.ID == divisionID).FirstOrDefault();
var divisionHierarchy = GetDivisionHierarchy(db.Divisions.AsEnumerable(), rootDivision);

...
 public IEnumerable<DivisionHierarchy> GetDivisionHierarchy(IEnumerable<Division> allDivisions, Division parentDivision)
        {
            Guid? parentDivisionId = null;

            if (parentDivision != null)
                parentDivisionId = parentDivision.ID;

            var childDivisions = allDivisions.Where(division => division.DivisionID == parentDivisionId);

            Collection<DivisionHierarchy> hierarchy = new Collection<DivisionHierarchy>();

            foreach (var div in childDivisions)
            {
                DivisionHierarchy divisionHierarchy = new DivisionHierarchy();
                divisionHierarchy.Division = div;
                divisionHierarchy.Divisions = GetDivisionHierarchy(allDivisions, div);
                hierarchy.Add(divisionHierarchy);
            }

            return hierarchy;
        }

A: I would load the divisions in an non-recursive way and then set up the recursive relations in code. Here is an example, which does this in a lazy way
public class Division
{
    public int ID { get; set; }
    public int DivisionID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    private static List<Division> _divisions;
    public static List<Division> Divisions
    {
        get
        {
            if (_divisions == null) {
                LoadAndSetUpDivisionsHierarchy();
            }
            return _divisions;
        }
    }

    private static Dictionary<int, Division> _divisionsByID;
    public static Dictionary<int, Division> DivisionsByID
    {
        get
        {
            if (_divisionsByID == null) {
                LoadAndSetUpDivisionsHierarchy();
            }
            return _divisionsByID;
        }
    }

    private static Division _root;
    public static Division Root
    {
        get
        {
            if (_root == null) {
                LoadAndSetUpDivisionsHierarchy();
            }
            return _root;
        }
    }

    private Division _parentDivision;
    public Division ParentDivision
    {
        get
        {
            if (_parentDivision == null && DivisionID != 0) {
                _parentDivision = DivisionsByID[DivisionID];

            }
            return _parentDivision;
        }
    }

    private List<Division> _subDivisions = new List<Division>();
    public List<Division> SubDivisions
    {
        get { return _subDivisions; }
    }

    private static void LoadAndSetUpDivisionsHierarchyHierarchy()
    {
        // Load the divisions in a non-recursive way using LINQ
        // (details not shown here).
        _divisions = LoadDivisions();

        // Add the divisions in a dictionary by id
        _divisionsByID = new Dictionary<int, Division>(_divisions.Count);
        foreach (Division division in _divisions) {
            _divisionsByID.Add(division.ID, division);
        }

        // Define sub-divisions and root division
        foreach (Division division in _divisions) {
            if (division.DivisionID == 0) {
                _root = division;
            } else if (division.ParentDivision != null) {
                division.ParentDivision.SubDivisions.Add(division);
            }
        }
    }

    private static List<Division> LoadDivisions()
    {
        throw new NotImplementedException();
    }
}


text:
Q: Restore files that where moved to trash I accidentally moved files in folder1 to trash. But I am not sure which files where in this folder so I cannot restore them one by one.
Does ubuntu still know that this files where placed in folder1? Can I restore those files back into the folder?

A: Open files, and navigate to trash, and change the view to list view, that will let you see the original location of the deleted files.  Just highlight the ones you want, and restore.


text:
Q: Capacity Error (with isolated problematic excerpt from code/minimal non-working example) I am working on an article in XeLaTeX and I am getting this error: capacity exceeded main memory size=5000000
By moving around \end{document} and by cutting and pasting various parts of the document, I have isolated the problem to the following section.
Could someone point me towards the problem? Sorry if this is a stupid question.
I believe this to be the minimum (non-)working example:
\documentclass[12pt, letterpaper]{article}

\usepackage{gb4e}
\noautomath

\usepackage{libertine}

\begin{document}
\begin{exe}
\ex \gll suk hapáng\footnote{corresponds to the proclitic /hap=/} \\
house above \\
\glt 'on top of (a) house'
\end{exe}

\begin{exe}
\ex
\gll yątci kį sukhǫ́\footnote{corresponds to the proclitic /suk=/} wąre \\
stream the over sit.{\Ind} \\
\glt '[It] sits over the stream.'
\end{exe}

\begin{exe}
\ex yancámǫntu \\
\gll yancá mǫntu \\
creek in \\
\glt 'in [a] creek'
\end{exe}
\enddocument


text:
Q: socket.send() Exception when using thread and nest_asyncio I am making a discord rich presence inside a bot, I got it working, but when I use .presence off to turn it off, it will begin to sent socket.send() raised exception. after about 3 minutes, I am wondering what would be causing it and how would I fix it.
Temporary fix:
I just ended up rebooting the script after I turn it off, but if you have a better way let me know.
here is the short version of the code:
import nest_asyncio
nest_asyncio.apply()

from pypresence import Presence

import discord
import asyncio
import requests
from discord.ext import commands
from threading import Thread

import json
import os
import time

def configgg():
    paath = os.path.dirname(os.path.realpath(__file__)) + r"\data\config.json"
    if os.path.exists(paath):
        with open(paath) as cock:
            data = json.load(cock)
            global __token__
            __token__ =data['token']
            global __prefix__
            __prefix__ =data['prefix']

configgg()

bot = commands.Bot(command_prefix=__prefix__, self_bot=True, case_insensitive=True)

def actualpresence():
    global presence
    loopie = asyncio.new_event_loop()
    perse = Presence('client id', loop=loopie)

    perse.connect()

    buttons = [{"label": "These buttons are pretty cool", "url": "https://pornhub.com"}]

    perse.update(state="Buttons test", buttons=buttons)

    while True:
        if presence is False:
            perse.close()
        time.sleep(30)

@bot.command()
async def presence(icy, toggle='on'):
    global presence
    if 'on' in toggle or 'true' in toggle:
        presence = True
        thread = Thread(target=actualpresence)
        thread.start()
    if 'off' in toggle or 'false' in toggle:
        presence = False

bot.run(__token__, bot=False)


text:
Q: Kafka Consumer Error - xxxx nodename nor servname provided, or not known When running the console consumer using the following command

$ ~/project/libs/kafka_2.9.2-0.8.1.1/bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic customerevents --autocommit.interval.ms 100 --group customereventsgroup

i get the following error
Exception in thread "main" java.net.UnknownHostException: HQSML-142453: HQSML-142453: nodename nor servname provided, or not known
    at java.net.InetAddress.getLocalHost(InetAddress.java:1473)
    at kafka.consumer.ZookeeperConsumerConnector.<init>(ZookeeperConsumerConnector.scala:107)
    at kafka.consumer.ZookeeperConsumerConnector.<init>(ZookeeperConsumerConnector.scala:128)
    at kafka.consumer.Consumer$.create(ConsumerConnector.scala:89)
    at kafka.consumer.ConsoleConsumer$.main(ConsoleConsumer.scala:178)
    at kafka.consumer.ConsoleConsumer.main(ConsoleConsumer.scala)
Caused by: java.net.UnknownHostException: HQSML-142453: nodename nor servname provided, or not known
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
    at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:901)
    at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1293)
    at java.net.InetAddress.getLocalHost(InetAddress.java:1469)
    ... 5 more

Now this command worked fine when connected to the work network but not when running from my home network.
Checking the hostname of the system I do get the correct response

$hostname
  HQSML-142453
  $

After reading a bit, I noticed that the Kafka server configuration has the following

# Hostname the broker will advertise to producers and consumers. If not set, it uses the
  # value for "host.name" if configured.  Otherwise, it will use the value returned from
  # java.net.InetAddress.getCanonicalHostName().
  advertised.host.name=HQSML-142453

which i updated to include my hostname but that didn't seem to help. Any ideas on what could be the problem here.
I know this is some networking interface related but cannot narrow it down to what it is.
config: Yosemite, osx jdk 7, kafka v0.8.1.1

A: Try the following;
Run
ping HQSML-142453

If the ping is not working that means you don't have have the hostname configured in /etc/hosts or in your router DNS. So you must either edit the /etc/hosts and map your HQSML-142453 name to the IP address where your kafka is running or map it in your router DNS.
Mapping must look like the following in /etc/hosts;
127.0.0.1  HQSML-142453


text:
Q: Commuting Dirac spinor with scalar field I have two Lagrangians which only differ in their interaction term - one of them has $L_{Yuk_{1}}$ while the other has $L_{Yuk_{2}}$. I want to know if this two interaction Lagrangians are equivalent. For that, I need to know how to commute scalar field operators, $\phi$, with Dirac spinor operators, $\psi$. How could I do so?
$$L_{Yuk_{1}}=-i\lambda\overline{\psi}\gamma^{5}\psi\phi$$
$$L_{Yuk_{2}}=-\lambda\phi\overline{\psi}\gamma^{5}\psi$$

A: Scalars and Spinors commute, so your two expressions are equivalent up to a factor of i.

A: The lagrangian is a scalar under the spacetime symmetry group (Poincare group, CPT, gauge invariance etc) so, in particular, there can be no open indices. Your interaction consists of the pseudoscalar-like vertex $\sim \bar \psi_{\alpha} \gamma^5_{\alpha \beta} \psi_{\beta}$ so it doesn't matter whether the scalar $\phi$ is put 'before' or 'after' this combination. This means $L_{Yuk,1}$ and $L_{Yuk,2}$ differ only by a factor $i$.


text:
Q: Removed duplicate element from List I have this list which is collection of GrossBalanceDtlsVO class.
GrossBalanceDtlsVO class contains below field :
private Long customerID = null;

private BigDecimal instAmount = BigDecimal.ZERO;

private BigDecimal instBalanceAmount = BigDecimal.ZERO;

private BigDecimal instRedemptionAmt = BigDecimal.ZERO;

private Long instTxnCnt = null;

private Date monthEndDt = null;
....
....

List<GrossBalanceDtlsVO> grossDetailsVO2 = getPCCustomerDetails(customerID);

This list contains duplicate data. For example :
customerID=1000033195, monthEndDt=2016-05-31, recMonthNo=9, recMonthlyLimit=100, recBalanceAmt=100, recMonthlyRedemption=0, recRollOverEligibility=0, txnId=null, instTxnCnt=null, instAmount=0, instBalanceAmount=0, instRedemptionAmt=0]
customerID=1000033195, monthEndDt=2016-06-30, recMonthNo=10, recMonthlyLimit=100, recBalanceAmt=100, recMonthlyRedemption=0, recRollOverEligibility=0, txnId=null, instTxnCnt=null, instAmount=0, instBalanceAmount=0, instRedemptionAmt=0]
customerID=1000033195, monthEndDt=2016-07-31, recMonthNo=11, recMonthlyLimit=100, recBalanceAmt=100, recMonthlyRedemption=0, recRollOverEligibility=0, txnId=null, instTxnCnt=null, instAmount=0, instBalanceAmount=0, instRedemptionAmt=0]
customerID=1000033195, monthEndDt=2016-05-31, recMonthNo=9, recMonthlyLimit=100, recBalanceAmt=100, recMonthlyRedemption=0, recRollOverEligibility=0, txnId=null, instTxnCnt=null, instAmount=0, instBalanceAmount=0, instRedemptionAmt=0]
customerID=1000033195, monthEndDt=2016-06-30, recMonthNo=10, recMonthlyLimit=100, recBalanceAmt=100, recMonthlyRedemption=0, recRollOverEligibility=0, txnId=null, instTxnCnt=null, instAmount=0, instBalanceAmount=0, instRedemptionAmt=0]
customerID=1000033195, monthEndDt=2016-07-31, recMonthNo=11, recMonthlyLimit=100, recBalanceAmt=100, recMonthlyRedemption=0, recRollOverEligibility=0, txnId=null, instTxnCnt=null, instAmount=0, instBalanceAmount=0, instRedemptionAmt=0]

Now my question is that how to remove those duplicate data from this list?

A: Sort them by given criteria, iterate them and check if the previous element is equal to the current element, if true - push them in separate list/array, and after that iterate this list/array and remove the items from your list.
Note: you should write your own object comparator.
For future use, if you want to have distinct collection - use a set.

A: You could throw your list into a Set and this Set into a new List.
List<GrossBalanceDtlsVO> grossDetailsVO2 = getPCCustomerDetails(customerID);
Set<GrossBalanceDtlsVO> grossDetailsVO2Set = new HashSet<>(grossDetailsVO2);
List<GrossBalanceDtlsVO> grossDetailsVO2WithoutDuplicates = new ArrayList<>(grossDetailsVO2Set);


text:
Q: "Boot device not found" when I try to boot after system installation with USB After installing Ubuntu 18.04.1 LTS I pressed restart now, then

remove the installation medium and reboot

appeared (although it should instead say press enter).
I pulled the USB out and to restart the laptop I pressed the power button.
Now boot freezes with boot device not found. I have changed BIOS boot priority to HDD, but it didn't help.

A:
Based on comments above and the fact that the installation pops out a let me say different kind of button as expected, now it seems to me as install hangs with error forcing it to quit and waiting for restart before grub properly configured itself.

Long story short as you can boot to live USB session, you are able to reinstall grub from there and everything should work as expected then.
Long story • How to reinstall grub using live USB

Double check whether you accidentally installed bootloader on that installation USB or on HDD. You can do that simply by booting with that USB inserted.

Nevertheless, if you can access grub rescue then start from there. If you see the grub rescue > shell (right after the boot error message), continue typing ls to list your drives and partitions. You will see something like:
(hd0) (hd0,msdos1) (hd0,msdos2)

Check them one by one if you don't know which has the system installed on it.
ls (hd0,msdos1)/
ls (hd0,msdos2)/

The right one should have listed lost+found dir etc.
Assuming (hd0,msdos2) is the right one, we can continue by setting grub root and going out of rescue mode to the normal terminal, where more magic is available.
set prefix=(hd0,2)/boot/grub
set root=(hd0,2)
insmod normal
normal

You will be able to boot from here, but if only some rare errors occurs, you can still set the boot image manually as it follows.

insmod linux
* linux /vmlinuz root=/dev/sda
ro

Optionally, you can select the initrd image, too.
initrd /initrd.img

After boot, you have to reinstall grub from terminal and set it to boot from your hard drive.
sudo update-grub
sudo grub-install /dev/sda


text:
Q: undefined method `>' for [1000, []]:Array (NoMethodError) am trying to read the files of months for a year. In files there are some empty values.
am trying to compare value of array (which i read from file) with default value but i keep getting the following error:
undefined method `>' for [1000, []]:Array (NoMethodError)
i checked the class of value which am getting from file it's integer but why then it's showing this error
def monthly_temperature(file_data)

  highest_temp  =  max_humdity = 0
  lowest_temp = 100 , info = []
  array = file_data.map { |string| string.split(',') }

  array.each_with_index do |days, ind|
   array[ind].shift()  #removing every first index

    if highest_temp < array[ind].first.to_i
      highest_temp = array[ind].first.to_i
    end

    a = array[ind].fetch(2).to_i
    #puts a.class

    if lowest_temp > a
      lowest_temp = a
    end
  end
end

A: Your javascript-like assignment:
lowest_temp = 100 , info = []

is equivalent to
lowest_temp = [100, info = []]

resulting lowest_temp holding an array. Correct parallel assignment is done like this:
lowest_temp, info = 100, []

Generally it should be only used when destructuring an array or when assigned values have a similar meaning (and assigning them together makes code easier to understand). In all the other cases, regular assignment is preferable for readability:
lowest_temp = 100
info = []


text:
Q: SlideToggle multiple divs in sequence I currently have this type of layout:
+---------------+
|  hide/show    | <-- button
+---------------+
+---+ +---+ +---+
| 1 | | 2 | | 3 | <- widgets
+---+ +---+ +---+
+---+ +---+ +---+
| 4 | | 5 | | 6 |
+---+ +---+ +---+
+---+ +---+ +---+
| 7 | | 8 | | 9 |
+---+ +---+ +---+

Within each widget, i have a 'close button':
+-------------------------------------------+
|                                        \ /|
|  HEADING                                X |  <--'close widget' button
|                                        / \|
+-------------------------------------------+
|                                          _/
|     CONTENT                          ___/
|                              _______/
|                   __________/
|                  /
|_________________/

Main Issue

I am using Jquery's 'toggle' effect to achieve this.
However, the big button (Hide/Show) is used to hide/show all of them. (all hidden, all shown)
I can't seem to work out how to do this :(
Currently i have this jsfiddle showing if I close a couple of them, and hit the toggle all button, it will close the rest on screen, and show the one's i've just closed (not wanted).
I want this button to show all (or hide all) depending on if

*

*(a) they are all hidden, then show all or

*(b) if some are hidden, then show them.

*(c) if all are shown, then hide all.

How can I get this functionality?

Side Issue
(wanted but not necessarily required)

On the 'show', how can I get them to show div1 first, then div2, then div3/etc until all are shown?
(i.e. toggle them in sequence)

A: Since slideToggle() doesn't care about the state of each individual widget, you're going to have to manually keep track of whether all widgets should be open or closed -- thereby defeating the purpose of using slideToggle()!
$('#widgetToggle').on('click', function () {
    var $widgets = $('.widget');
    if ($widgets.filter(':visible').length == $widgets.length) {
        $widgets.slideUp();
    } else {
        showInSequence($widgets.filter(':hidden'));
    }
    return false;
});

function showInSequence($el) {
    if ($el.length) {
        $el.first().slideDown(function () {
            showInSequence($el.filter(':hidden'));
        });
    }
}

A: Try this.
$('#widgetToggle').click(function () {
    var widgets = $('.widget'),
        total = widgets.length,
        visible = widgets.filter(':visible').length,
        //hide if all are visible
        method = total === visible ? 'slideUp': 'slideDown',
        run = function() {
            var first;
            if(widgets.length) { //there is something left
                first = widgets.first(); //save first
                widgets = widgets.slice(1); //remove processed
                first[method](run); //show hide
            }
        };

    run();
 });

Demo.


text:
Q: Cannot connect Databricks with Azure blob storage I successfully mounted Azure blob storage using SAS key with below code
dbutils.fs.mount(  source = "wasbs://"+user+"@"+account+".blob.core.windows.net",
mount_point = "/mnt/"+mountName,
extra_configs = {"fs.azure.sas."+user+"."+account+".blob.core.windows.net":key})

However, I cannot save output to the blob or display the blob directory (which it was worked before)
Here are some part of an error
"shaded.databricks.org.apache.hadoop.fs.azure.AzureException: java.util.NoSuchElementException: An error occurred while enumerating the result, check the original exception for details."
"Caused by: com.microsoft.azure.storage.StorageException: This request is not authorized to perform this operation using this resource type.
at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:89)
at com.microsoft.azure.storage.core.StorageRequest.materializeException(StorageRequest.java:305)
at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:178)
at com.microsoft.azure.storage.core.LazySegmentedIterator.hasNext(LazySegmentedIterator.java:109)"
Does anyone know cause of this issue?


text:
Q: Inline function ambiguity in Scala When passing an operator lifted to be a function to one of defined higher order functions, Scala allows for very concise syntax, e.g (please ignore the fact that it can be simplified to .product()):
List(1,2,3).fold(1)(_ * _)

To the above I can just pass _ \* _
However having defined my own toy function zipWith(), I need to be very explicit when passing a function:
implicit class EnrichedList[A](val self: List[A]) extends AnyVal {
  def zipWith[B, C](that: List[B])
                   (implicit zipper: A => B => C): List[C] = {

    def zipWithHelper(zipper: A => B => C)
                     (as: List[A])
                     (bs: List[B]): List[C] = {
      (as, bs) match {
        case (_, Nil) => Nil
        case (Nil, _) => Nil
        case (a :: restOfA, b :: restOfB) =>
          zipper(a)(b) :: zipWithHelper(zipper)(restOfA)(restOfB)
      }
    }

    zipWithHelper(zipper)(self)(that)
  }
}

This: List(1, 3, 4).zipWith(List(3, 4, 5))(_ * _) will not work, saying

Error:(60, 46) missing parameter type for expanded function ((x$1: , x$2) => x$1.$times(x$2))
  List(1, 3, 4).zipWith(List(3, 4, 5))(_ * _)

I need to say what type of arguments function takes:
List(1, 3, 4).zipWith(List(3, 4, 5))((x: Int) => (y: Int) => x * y)

Why won't the compiler allow me just to pass in a shorthand version _ * _?

A: The expression _ * _ is not shorthand for (x: Int) => (y: Int) => x * y. It's a shorthand for (x: Int, y: Int) => x * y. If you change the type of zipper to (A, B) => C instead of A => B => C, it should work. Currying is a thing, it's not just a fancy name for an identity function.
This here compiles:
implicit class EnrichedList[A](val self: List[A]) {
  def zipWith[B, C](that: List[B])
                   (implicit zipper: (A, B) => C): List[C] = {

    def zipWithHelper(zipper: (A, B) => C)
                     (as: List[A])
                     (bs: List[B]): List[C] = {
      (as, bs) match {
        case (_, Nil) => Nil
        case (Nil, _) => Nil
        case (a :: restOfA, b :: restOfB) =>
          zipper(a, b) :: zipWithHelper(zipper)(restOfA)(restOfB)
      }
    }

    zipWithHelper(zipper)(self)(that)
  }
}

println( List(1, 3, 4).zipWith(List(3, 4, 5))(_ * _) )

and prints
List(3, 12, 20)


text:
Q: How to build project from another project in TeamCity? Suppose we have a build project which takes a list member as a parameter.
Can I make another build which could run the first project with all parameters from list sequentially?

A: If I understand you correctly you want to reliably trigger multiple builds of type A based on a list you pass to build B.
What you could do is have B parse the list (using powershell or whatever else custom program you want to use) and then use the TeamCity REST API to trigger builds of type A with the right parameters, the syntax described here would apply to this:

To trigger a build with custom parameters (system properties and
  environment variables), use:
http://testuser:testpassword@teamcity.jetbrains.com/httpAuth/action.html?add2Queue=bt10&name=&value=&name=&value=

This allows you to pass the parameters you need for each build.


text:
Q: I am getting duplicate values on Postgres left join query I am getting duplicate values for user roles and teams, a user can have multiple roles, but I am getting duplicates: such:
  "roles": [
        {
            "role_id": 1,
            "role_name": "Admin"
        },
        {
            "role_id": 1,
            "role_name": "Admin"
        },
        {
            "role_id": 2,
            "role_name": "Moderator"
        },
        {
            "role_id": 2,
            "role_name": "Moderator"
        }
    ],

My query:
with aggs as (
  select u.user_id, u.first_name, u.last_name,
         jsonb_agg(to_jsonb(r)) as roles,
         jsonb_agg(to_jsonb(t)) as teams,
         jsonb_agg(to_jsonb(s)) as something_else
    from users u
         left join user_role ur on ur.user_id = u.user_id
         left join roles r on r.role_id = ur.role_id
         left join user_team ut on ut.user_id = u.user_id
         left join teams t on t.team_id = ut.team_id
         left join user_something_else us on us.user_id = u.user_id
         left join something_else s on s.something_else_id = us.something_else_id
   group by u.user_id, u.first_name, u.last_name
)
select to_jsonb(aggs)
  from aggs
 where user_id = 1;

tables example
create table users (
  user_id serial primary key,
  first_name text not null,
  last_name text not null,
  -- other columns here
);

create table roles (
  role_id serial primary key,
  role_name text not null unique,
  -- other columns here
);

create table user_role (
  id serial primary key,
  user_id int not null references users(user_id),
  role_id int not null references roles(role_id),
  unique(user_id, role_id)
);

the user_role table doesn't contain duplicates. But the query is returning duplicates.
How can I elemnate duplicates? I tried DISTNICT on u.user_id but that didn't fix it.


text:
Q: Maximum average, minimum average, and average I am unsure on how to get the maximum average, minimum average, and average of everything in total. I already set variables with values for them in my code, however I am not sure how to input the averages in my code. Any help would be great! Thanks.
    import java.util.Scanner;
public class Averages {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int max = 0;
        int min = 9000;
        int score = 0;
        int n;
        int c;
        int rowMaxNumber = 0;
        int rowMinNumber = 0;
        int columnMax = 0;
        int columnMin = 0;
        int averageMin = 0;
        int averageMax = 0;
        double average = 0;

        System.out.println("How many rows?");
        n = scan.nextInt();

        for (int row = 1; row <= n; row++) {
            System.out.println("How many student in row " + row + "?");
            c = scan.nextInt();

            for (int column = 1; column <= c; column++) {
                System.out.println("Score for student " + column + " in row "
                        + row + "?");
                score = scan.nextInt();

                rowMaxNumber = row;
                columnMax = column;

                rowMinNumber = row;
                columnMin = column;

            }
            if (score >= max) {
                max = score;

            }
            if (score < min) {
                min = score;

            }

        }
        System.out.println("Student " + columnMax + " of row " + rowMaxNumber
                + " was highest with " + max);
        System.out.println("Student " + columnMin + " of row " + rowMinNumber
                + " was lowest with " + min);
        System.out.println("Row " + rowMaxNumber + " had highest average with "
                + averageMax);
        System.out.println("Row " + rowMinNumber + " had lowest average with "
                + averageMax);
        System.out.println("Class average is " + average);
    }
}

A: public class Averages {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int max = 0;
    int min = 9000;
    int score = 0;
    int n;
    int c;
    int rowsum = 0;
    int rowmaxnumber = 0;
    int rowminnumber = 0;
    int columnmax = 0;
    int columnmin = 0;
    int averagemin = 9999;
    int averagemax = 0;
    double average = 0;

    System.out.println("How many rows?");
    n = scan.nextInt();

    for (int row = 1; row <= n; row++) {
        System.out.println("How many student in row " + row + "?");
        c = scan.nextInt();
        rowsum = 0;
        for (int column = 1; column <= c; column++) {

            System.out.println("Score for student " + column + " in row "
                    + row + "?");
            score = scan.nextInt();
            rowsum += score;
            rowmaxnumber = row;
            columnmax = column;

            rowminnumber = row;
            columnmin = column;

            if (score >= max) {
                max = score;
            }
            if (score < min) {
                min = score;
            }

        }
        int avg=rowsum/c;
        if( avg >= averagemax){
            averagemax=avg;
        }
        if( avg <= averagemin){
            averagemin=avg;
        }

    }
    System.out.println("Student " + columnmax + " of row " + rowmaxnumber
            + " was highest with " + max);
    System.out.println("Student " + columnmin + " of row " + rowminnumber
            + " was lowest with " + min);
    System.out.println("Row " + rowmaxnumber + " had highest average with "
            + averagemax);
    System.out.println("Row " + rowminnumber + " had lowest average with "
            + averagemin);
    System.out.println("Class average is " + average);
}

}
I have restructured some code to calculate sum of scores as we see them in a row, and calculate the average on end of scanning row, also avg will give the average by dividing rowsum by no. of students in row, and then avg is compared with the previous highest and previous lowest averages. Just like you do it with score! Good luck.

A: I figured out how to get the maximum average, minimum average, and total average. Thanks for anybody that helped!
import java.util.Scanner;

public class Averages
{
 public static void main ( String[] args )
  {
     Scanner scan = new Scanner(System.in);
        int max = -9999;
        int min = 9999;
        int score = 0;
        int n;
        int c;
        int rowsum = 0;
        int rowMaxNumber = 0;
        int rowMinNumber = 0;
        int columnMax = 0;
        int columnMin = 0;
        double averageMin = 9999;
        double averageMax = 0;
        double avg = 0.0;
        double avgTotal = 0.0;
        double totalScore = 0;
        double totalStudent = 0;

        System.out.println("How many rows?");
        n = scan.nextInt();

        for (int row = 1; row <= n; row++) {
            System.out.println("How many student in row " + row + "?");
            rowsum=0;
            c = scan.nextInt();
            totalStudent += c;

            for (int column = 1; column <= c; column++) {

                System.out.println("Score for student " + column + " in row " + row + "?");
                score = scan.nextInt();
                rowsum += score;
                totalScore += score;

                if (score >= max) {
                    max = score;
                    columnMax = column;

                }
                if (score < min) {
                    min = score;
                    columnMin = column;
                }
            }
            avg = rowsum/c;
            if( avg >= averageMax){
                averageMax=avg;
                rowMaxNumber = row;

            }
            if( avg < averageMin){
                averageMin=avg;
                rowMinNumber = row;
            }
        }
        avgTotal = totalScore/totalStudent;

        System.out.println("Student " + columnMax + " of row " + rowMaxNumber + " was highest with " + max);
        System.out.println("Student " + columnMin + " of row " + rowMinNumber + " was lowest with " + min);
        System.out.println("Row " + rowMaxNumber + " had highest average with " + averageMax);
        System.out.println("Row " + rowMinNumber + " had lowest average with " + averageMin);
        System.out.println("Class average is " + avgTotal);
}
}


text:
Q: How to print and send changing IDs though python to another computer with sockets Basically, I have my code, which finds the Lobby ID of a video-game, which then sends to my laptop. This then opens the exe with a argument and that certain Lobby ID. I want it to change when I start up another game/server. I have the script to output when the lobby ID changes, but when I plug it into my socket script. It only outputs the first one.
If I hash out all the s= socket... part and under it functions correctly
import socket
import glob
import os
import re
placeholder = ''

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.0.17'
port = 50502
s.connect((host,port))

while True:

    GAME_DIRECTORY = 'C:/Program Files/Oculus/Software/Software/ready-at-dawn-echo-arena'

    logs = glob.glob(GAME_DIRECTORY + '/_local/r14logs/*')
    log = max(logs, key = os.path.getctime)
    with open(log, 'r') as f:
        file = f.read()

    lobbyid = re.findall(r'........-....-....-....-............', file)[-1]
    if lobbyid != placeholder:
        if lobbyid != ('00000000-0000-0000-0000-000000000000'):
            placeholder = lobbyid
            print (lobbyid)

            def ts(str):
                s.send(lobbyid.encode())
                data = ''
                data = s.recv(1024).decode()
                s.close ()
            ts(s)


text:
Q: Fibonacci sequence without for loop in octave I'm trying to create a Fibonacci sequence without for loop in octave, but all I get is error and I'm totally stuck here. Any ideas on how to deal with this
x(1)=1;
x(2)=1;
m=3:10
x(m)=x(m-1)+x(m-2)

error: x(9): out of bound 2 (dimensions are 1x2)

I was expecting getting the 1st 10 Fibonacci sequence but it isn't working

A: Unfortunately, Octave does not recalculate in-place vectorized operators at each step (nor MATLAB, as far as I'm aware of), so
octave> x=ones(1,10)
x =
   1   1   1   1   1   1   1   1   1   1

octave> x(3:10)=x(2:9)+x(1:8)
x =
    1   1   2   2   2   2   2   2   2   2

You can either use a closed-form expression, as mentioned on the comments, or just do a simple loop:
octave> x=ones(1,2)
octave> for i=3:10
> x(i)=x(i-1)+x(i-2)
> endfor


text:
Q: Ruby binary method <<= This is several questions wrapped in one. I saw the method "<<=" used recently. I was able to piece together what is does, but not anything else about it.
$ dec = 2
$ dec <<= 1
=> 4
$ dec
=> 4
$ dec <<= 2
=> 16

I think it's basically a shortcut for multiplying the sum plus the next nth position's in binary:
$ a = 2 * 2 ** 1
=> 4
$ a = a * 2 ** 2
=> 16

It doesn't work if you try it on a fixnum itself
$ 4 <<= 1
=> SyntaxError: unexpected tOP_ASGN, expecting end-of-input
1 <<= 1
     ^

I searched for hours and couldn't find where it lives in the ruby docs.

*

*Where is there documentation for this?

*What class or module does this live in?

*Why does is only work if you assign it to a variable first?

Thanks!

A: This is called an abbreviated assignment and is covered in section 11.4.2.3 Abbreviated Assignments of the ISO Ruby Language Specification; specifically it is an abbreviated variable assignment (§11.4.2.3.2).
An abbreviated variable assignment is evaluated (roughly) like this:
a ω= b

is the same as
a = a ω b

where ω is an arbitrary non-equality Ruby operator (&&, ||, &, |, ^, +, -, *, /, **, %, <<, >>).
Note: this simple translation applies only to abbreviated variable assignments. It does not apply to abbreviated indexing assignments (a[b] ω= b) or abbreviated method assignments (a.b ω= c).

*

*Where is there documentation for this?

While the ISO Ruby Language Specification covers only a small subset of the intersection of Ruby 1.8 and Ruby 1.9, abbreviated assignments are covered there.
They are also covered in the Ruby RDocs under syntax/assignment.rdoc.

*

*What class or module does this live in?

None. Assignments are a language feature, not a library feature.

*

*Why does is only work if you assign it to a variable first?

I am not sure what you mean. It works perfectly fine without assigning to a variable first:
class NilClass; def <<(*) :haha end end

a <<= a
#=> :haha


text:
Q: How to setup tests with the appropriate code using rebar3? I have created a simple application via rebar3 templates such as:
apps/myapp/app/myapp_app.erl
-module(myapp_app).

-behaviour(application).

-export([start/2, stop/1]).

start(_StartType, _Params) ->
    ok.

stop(_State) ->
    ok.

I have written a test for that:
apps/myapp/test/myapp_test.erl
-module(myapp_test).

-include_lib("eunit/include/eunit.hrl").

simple_test() ->
    myapp_app:start(ok, 42).

Sadly, when I launch the test, it seems that the link is not done between the two files:
$ rebar3 eunit
===> Verifying dependencies...
===> Compiling shoreline
===> Performing EUnit tests...
F
Failures:

  1) myapp_test:simple_test/0
     Failure/Error: {error,undef,
                        [{myapp_app,start,"*",[]},
                         {myapp_test,simple_test,0,
                             [{file,
                                  "/.../apps/myapp/test/myapp_test.erl"},
                              {line,8}]},
                         {myapp_test,simple_test,0,[]}]}
     Output:

Finished in 0.074 seconds
1 tests, 1 failures
===> Error running tests

Is there something to add in rebar.config?

A: If you have .erl files in a custom directory other than 'src', then you need to add it to the code path.
You can do it using rebar3 by modifying erl_opts section in 'rebar.config' as below.
{erl_opts, [debug_info, {src_dirs, ["src", "app"]}]}.

Hope this can work for you.

A: rebar3 does not find your .erl files if you have been under /app I moved them to /src.
➜  myapp rebar3 eunit
===> Verifying dependencies...
===> Compiling myapp
===> Performing EUnit tests...
.
Finished in 0.081 seconds
1 tests, 0 failures
➜  myapp ls
LICENSE      README.md    _build       rebar.config src          test
➜  myapp mv src app
➜  myapp rebar3 eunit
===> Verifying dependencies...
===> Performing EUnit tests...
F
Failures:

  1) myapp_test:simple_test/0: module 'myapp_test'
     Failure/Error: {error,undef,
                           [{myapp_app,start,[ok,42],[]},
                            {myapp_test,simple_test,0,[]}]}
     Output:

Finished in 0.036 seconds
1 tests, 1 failures
===> Error running tests

undef means could not be found when evaluating the call at runtime. 2 To help see what rebar3 is doing I can highly recommend debug, DEBUG=1.


text:
Q: ODATA Service creation with Java? Is there any sort of ODATA support for Java? I know there are plenty of rest based libraries out there like Jersey, etc. though I would like to utilize ODATA without .NET. and if so, any good guides?

A: Have you taken a look at odata4j?
Let us know if you have suggestions on the documentation.
Thanks,
- john


text:
Q: Convert const char* into a char* I'm always wondering about the complaint of the compiler when I declare and define a char*-variable.
char* myChar = "Char";

The compiler will complain that it cannot convert const char* to char*. It need an explicit conversion like
char* myChar = (char*)"Char";

My first question is if this is the correct way to initialize a char* with a const char*. And my second question is, why the compiler need this explicit conversion. I think there is no great difference between const char* and char* except the const.

A: On a technical level, there is a great difference between const MyType* and MyType* and it is easier to see in your example char* myChar = "Char"; in that the litteral string can be part of memory that may not be changed, but by assigning that to a non-const pointer, you say that you may well planning to change some characters anyway. That behavior is undefined. It may work and it may make your program stop unexpectedly and you can't even rule out any other behavior.
By casting (prefer const_cast in C++), you are saying to the compiler that you know what you're doing and you know better. The normal solution is const char* myChar = "Char"; or even const char* const myChar = "Char"; if you're not planning to point to other char arrays.
In C++, I find it even clearer working with std::string if you want to work with strings.

A: To the advanced programmer, there is definitely a great difference between const and non-const, in terms of integrity, security, and performance.
We basically use const when we want to emphasize that a particular object/function/variable isn't allowed to be changed by the user.
check const correctness
The best-practice way to add/remove const/volatile modifiers is by using const_cast operator.
check The const_case operator


text:
Q: Mongoose TypeError: TypeError: Cannot use 'in' operator to search for 'pluralization' in undefined Not really sure what's going on here. I see that others have encountered this error before, but I guess I just don't understand enough to draw parallels between what they were doing wrong and what I'm doing wrong.
This is just a simple project to learn the MERN stack. The objective here is relatively simple: upload a PDF file to a mongoDB database, retrieve that PDF file, and display it to a preview window. Possibly an iframe, or something simpler, depending on the options available to me. At the moment, my primary issue is with the back end.
So, here is my code:
index.js (username and password omitted, of course):
import express from 'express';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import cors from 'cors';
import { router } from './routes/image-route.js';

const app = express();
const port = 5000;

app.use(bodyParser.json({limit: "20mb", extended: true}));
app.use(bodyParser.urlencoded({limit: "20mb", extended: true}));

app.use('./routes/image-route.js', router)

app.use(cors());

const CONNECTION_URL = 'mongodb+srv://<username>:<password>@cluster0.xxpzv.mongodb.net/myFirstDatabase?retryWrites=true&w=majority';

async function main() {
    await mongoose.connect(CONNECTION_URL).then(() => console.log("SERVER CONNECTION ESTABLISHED"));
}

main().catch(err => console.log(err));

app.listen(port, () => console.log(`listening at port ${port}`));

image_model.js:
import mongoose from 'mongoose';

const imageSchema = mongoose.Schema({
    name: String,
    img:
    {
        data: Buffer,
        contentType: String
    }
});

const imageData = mongoose.model('image', 'imageSchema')

export { imageData };

image-route.js:
import express from 'express';
import { getImage, postImage } from '../controllers/image_controller.js';

const router = express.Router();

router.get('/', getImage);
router.post('/', postImage);

export { router };

image_controller.js:
import { imageData } from '../models/image_model.js';

export const getImage = async (req, res) => {
    try {
        const allImages = await imageData.find();
        req.status(200).json(allImages);
        console.log('Successfully submitted');
    } catch (err) {
        res.status(404).json({message: error.message});
    }
}

export const postImage = async (req, res) => {
    const image = req.body;
    const newImage = new imageData(image);

    try {
        await newImage.save();
        res.status(201).json(newImage);
    } catch (error) {
        res.status(409).json({message: error.message});
    }
}

And this is the error I'm receiving when I attempt to start the server:

I'm not really sure what else to say. I've tried the solutions I've seen for similar problems (to the best of my understanding), but their problems were apparently not quite the same as mine. If there's anything else anyone needs to know to help me with this, I'll provide whatever is necessary. Thanks in advance.

A: file: image_model.js
const imageData = mongoose.model('image', 'imageSchema')
 // imageSchema is not a string

change to:
const imageData = mongoose.model('image', imageSchema)


text:
Q: Does the use a simple-template-id in a nested-name-specifier unambiguously mean a class template specialization? struct A{
    template<typename U>
    void T(){}
};
struct B{
    template<typename U>
    struct T{
       using type = U;
    };
};
struct C:A,B{

};
int main(){
    C::T<int>::type d;
}

This example is accepted by neither GCC nor Clang.
As per basic.lookup.qual#1

The name of a class or namespace member or enumerator can be referred to after the:: scope resolution operator ([expr.prim.id.qual]) applied to a nested-name-specifier that denotes its class, namespace, or enumeration. If a:: scope resolution operator in a nested-name-specifier is not preceded by a decltype-specifier, lookup of the name preceding that :: considers only namespaces, types, and templates whose specializations are types.

That means that when looking up the declarations for the template name T, the specialization of T shall denote a type in this context. On the other hand, as per class.member.lookup#4

If C contains a declaration of the name f, the declaration set contains every declaration of f declared in C that satisfies the requirements of the language construct in which the lookup occurs.

Again, when looking up the template T in the scope of C, only those templates whose specialization is a type should be considered by this lookup.  The scope of C does not have any declarations for T, hence the lookup will be performed for S(T,C) in every one of its base classes. The template T in A does not satisfy the requirement. Meanwhile, the template T declared in the scope of B does satisfy the requirement. So the lookup is not ambiguous and the B::T is the unique result. That means C::T<int>::type d should be well-formed. Why do both GCC and Clang reject this example? Can it be considered a bug of in both? If I missed something, what's the reason that this example should be ill-formed?

A: The lookahead required to have the lookup for T depend on the :: even as the interpretation of < depends on the meaning of T is considered undesirable.  As such, lookup for a name followed by < is not restricted to types and namespaces regardless of any >:: found later.  P1787R6 fixed this, restricting the special lookup to identifiers immediately followed by :: (since other kinds of names can't refer to types or namespaces anyway).