N00b alert: Cat 6A keystones with Cat6/Cat5e wires and Cat6A wires with Cat6/Cat5e connectors

Question: So first off, I have no idea how this ish works but I got myself deep down with it.
I was building my new house and in the garb of moment, when I was thinking of having Ethernet connectors all over the house (41 to be exact), I got convinced to put Cat6a all over the house. I also got Cat6a metal keystone connectors all over the house.
I never realized that industry doesn't like/care/need Cat6a and is still lurking with Cat6 or Cat5e. I have my Cameras or other equipment which have their own old Cat cables.
My question is: can I use Cat6a cable in these equipment (router/consoles/video hub/etc)? or can I use Cat6 or Cat5e cable in my connectors all over the house.
As you might have guessed through my post, I am so confused.
Comment: You will need a lot of experience and expensive testers and tools to properly install Category-6 or Category-6a cabling. Even experienced installers have trouble getting those to pass the test suite. You need a professional cable tester that costs several thousand dollars to even run the test suite, and the horizontal cable is solid-core and fragile. Even with Category-5e, you must not exceed the maximum pulling tension, or the minimum bend radius, and you cannot staple it to studs the way electricians do for residential wiring, otherwise your risk permanently damaging the cabling.
Comment: I hope you just answered the question instead of whining about why it would be so expensive and usual blah. Thanks though.
Comment: I was neither whining nor answering the question. I made a comment that I hope you found useful.
Answer: You can use cat5e or cat6 for the equipment without issues. There is not any benefit you will see using Cat6A cable with security camera at this time due to the low bandwidth of the cameras.
If you use a lower cable than Cat6A between switch and end terminals (ehich are Cat6A from your statement) the capability will round down to the lowest item such as cable, connector or patch cable. Running cat6 or cat5e wire with cat6a keystones is a waste of money as there would not be any benefit, because it is being limited by the cable. Also the metal keystones are only beneficial is you have a grounding wire in the cable and a place to ground on switch or patch panel.
I am also in the same boat of building a new home, I will be running Cat6A to all points, including cameras (PoE). This is not needed now, but while walls are open it will alloe for future expansion to 10Gbe in the future without having the additonal cost of time and money.
Answer: Cat6A is fully backwards compatible, it'll just be bulkier cabling, and more expensive.  But you'll be more future-proof, as 6A supports 10 gig ethernet over much longer distances than regular Cat6 would.  25 gig and 40 gig ethernet will require Cat8, though.
Comment: Actually the standards for Cat 8 were published in July 2016 (ANSI/TIA-568-C.2-1 "Addendum 1, Specifications for 100Ω Category 8 Cabling").  I've been in no hurry to consider this as a replacement for any of my existing fiber runs though. (in other words, no idea if SFPs, switches, etc. are commercially available yet)
Comment: There is no such thing as `Cat8` cabling. ANSI/TIA/EIA register the cable categories, and there currently are no cable categories above Category-6a.
Comment: [TIA's announcement of the Cat8 spec](http://www.tiaonline.org/tia-issues-new-balanced-twisted-pair-telecommunications-cabling-and-components-standard-addendum-1)


Filter more than One ID to add attributes

Question: I am using this code to add a "top" attribute's value to all the ids with the transcript word.
Here is how the DIV look :-

The JQuery Code I use is:-
 $(this).leanModal(
        {
            top: $(this).filter('[id*="transcript"]')[0] ? 500 : null,
            closeButton: ".modal_close, .modal_close_for_shoutout"
        }
    );

This adds the "top" value for any div with transcript in it. Problem is that now I want it to filter all the divs with shoutout too. Is there any efficient way that I can filter more then one DIV IDs ?
Thanks
Answer: $(this).leanModal({
     top: $(this).filter(function() {
              return this.id.indexOf('transcript') != -1 ||
                     this.id.indexOf('shoutout') != -1
          }).length ? 500 : null,
     closeButton: ".modal_close, .modal_close_for_shoutout"
});


How to find out whether a URL is up and running?

Question: I have four URLs and I was trying to build a simple HTML-JavaDcript way of finding out whether the URLs are up and running.
The URLs are like this:

https://www.kbhome1.com
https://www.kbhome2.com
https://www.kbhome3.com
https://www.kbhome4.com

Now when the URLs are loaded using the address bar in IE, they all provide a common text which has some variations with respect to the URL used like this:

Your app1 is up and running
Your app2 is up and running
Your app3 is up and running
Your app4 is up and running

So I was trying to get the URLs loaded in iframe and then I was trying to get the common text Your app, which will let me know that the individual URLs are up. Now the problem is the URLs are hosted in different servers and as such due to Same Origin Policy violation, I keep getting this error:

iframe error permission denied to access property

Now does anybody know any other way to achieve what I am trying to do? Any help is deeply appreciated.
Answer: A couple of options for you:

It sounds like you have iframes open with those URLs loaded in them. You can send the iframe windows a message via postMessage (which is allowed cross-origin) and have them reply saying whether they're up. E.g., in your main window:
window.addEventListener("message", function(e) {
    // Check iframe reply's origin and handle it here
}, false);

theIframe.contentWindow.postMessage("ack", "https://kbhome1.com");

There, you're listening for a message back, and sending a message to the iframe asking it to reply.
More on postMessage:

In the spec
On MDN
Article on using it cross-origin

But it doesn't need to be that complicated. If all you want to do is make sure those apps are up, put a small script file on each of them, e.g. https://kbhome1.com/up.js, with this in it:
hostStatus("kbhome1", true);

...and then on your page, include a function:
function hostStatus(host, up) {
    // ...mark that host as "up" or "down" based on the `up` flag
}

...and include a script tag for each host:
var script = document.createElement('script');
script.src = "https://kbhome1.com/up.js";
script.onerror = function() {
    hostStatus("kbhome1", false); // It's not up
};
document.querySelector("script").parentNode.appendChild(script);

If you see the hostIsUp call, it's up; if you don't, it isn't (and we can use the error event, above, to get a positive "it's not up" result).
You can do that more than once if you're doing an ongoing "live" status page.
Comment: Thanks , this looks like  a very good idea . Let me check whether this works out for me .
Comment: @TheDarkKnight: If you can't control the content of the sites you're trying to look at, I don't think there's a purely client-side solution. You'll have to have a server somewhere that you query, which can in turn query the hosts you're testing (since server-side code won't run up against the Same Origin Policy).
Comment: So, the problem with both the options are that they depend on me having control over the urls . Unfortunately the urls are hosted in a server to which I have no access . When i tried out the first option, I realized that the `receiveMessage()` function must be on the app from the hosted url. But that's not possible in my case, since I do not have permission to change anything in that app and from my side of the code I can't anyways access anything inside the web page depicted via the urls . Hence , none of these options actually work out for me .
Comment: But I was not aware of the `postmessage()`  functionality . That was a good read though . If you can think of any other ways of doing it , please let me know .
Comment: Yes, you are quite right . However, what I was thinking now is that : Since I cannot access anything inside the iframe ; what if I pro grammatically take a snap shot of the iframe content and extract the text `Your app` from it. If I am able to extract the text, then that will mean that the site is up . Just a thought , dunno about the complexity of this though .
Comment: @TheDarkKnight: But to access the text, you'd have to get around the SOP, which is there specifically to *prevent* you accessing the text. :-)
Comment: Will it be so ? Because, I will be taking the snapshot(using html2canvas probably) and keep it my HDD and read the text from that image . Do you reckon I will face the SOP violation problem there  ?
Comment: @TheDarkKnight: Your HDD? What? I thought you were looking for a client-side solution. If you can involve a server, there's no need for anything that complex at all.
Comment: Yes, I think that will be the best way to go  instead of making it very complicated . Thanks for the assist .
Answer: You might try to send  simple AJAX GET request to each of these URLs and see if you get a 200 status back.
Again, this might fails for cross domain issues you might try with jsonp datatype.
Comment: Do you have any sample examples of doing this using jsonp ?


Sum daily values for every month in matlab

Question: I have got a matrix with values in.
The first column of the matrix is the date in the following form, 19260701 pr YYYYMMDD.
The other columns of the matrix are series.
19260702    0.026   0.000   NaN 1.175
19260706    0.009   0.000   NaN 1.842
19260707    1.388   0.001   NaN 9.061
19260708    1.147   0.028   NaN 0.067
19260709    0.604   0.018   NaN 0.000
19260710    7.255   0.020   NaN 0.005
19260712    0.085   0.093   NaN 1.832
19260713    0.163   0.025   NaN 3.897
19260714    1.294   0.545   NaN 0.188
19260715    0.256   0.077   NaN 0.001
19260716    0.001   0.002   NaN 0.018
19260717    0.000   0.015   NaN 1.863
19260719    0.002   0.062   NaN 1.465
19260720    2.761   0.028   NaN 6.453
19260721    1.998   0.067   NaN 0.328
19260722    0.160   0.123   NaN 0.651
19260723    0.009   0.000   NaN 0.001
19260724    0.005   0.000   NaN 0.000
19260726    0.016   0.002   NaN 0.860
19260727    0.022   0.000   NaN 0.329
19260728    0.002   0.001   NaN 0.857
19260729    0.000   0.343   NaN 2.125
19260730    0.002   0.001   NaN 1.265
19260731    0.000   0.000   NaN 0.283
19260802    0.000   0.010   NaN 0.815
19260803    0.000   1.020   NaN 27.701
19260804    0.000   0.197   NaN 4.162
19260805    0.027   0.016   NaN 42.120
19260806    0.046   0.200   NaN 15.163
19260807    0.284   0.004   NaN 0.382
19260809    1.330   0.000   NaN 3.102
19260810    1.066   0.016   NaN 0.035
19260811    0.261   0.119   NaN 0.249
19260812    0.014   0.031   NaN 328.139
19260813    0.024   0.042   NaN 40.248
19260814    0.094   0.047   NaN 1.460
19260816    0.042   0.007   NaN 25.928

Is it possible to Sum the values in each column of the matrix based on the month?
Apologise,
Following the comments,
I dont just want to sum by month, but each yearmonth, i.e sum Jan 1960, Feb 1960 etc.
Comment: i want to sum for each month each year, so 199607 is a month I want to sum, I dont just want ot sum every 07
Comment: Does _the same month_ mean _the same month and year_, or _the same month regardless of year_?
Comment: t = datetime(num2str(data(:,1)),'InputFormat','yyyyMMdd');
[y,m]= ymd(t);

[y,m] = mod(floor(data2(:,1)/100-1), 100)+1;
[~, ~, month_id] = rows([y,m]);
result = splitapply(@sum, data2(:,2:end), month_id)
Comment: @SardarUsama please be patient with me, but this doesn't work what am I doing wrong
Comment: `rows` is not a function. You are supposed to use `unique` with the `rows` flag. `[~, ~, month_id] = unique([y,m],'rows');` and you do not need the line with `mod` and `floor` functions
Comment: Do this: `t = datetime(num2str(data(:,1)),'InputFormat','yyyyMMdd');`
`[y,m]= ymd(t);` and then you can use `[y,m]` instead of `month` and `unique` with the `rows` flag in Luis' answer
Comment: LuisMendo has  edited his answer to include a better approach.
Answer: You can use unique to get a label for each month, and then splitapply to accumulate values in the other columns based on month label (accumarray would work but only on one column).
If you consider April 2018 and April 2019 the same month:
month = mod(floor(data(:,1)/100-1), 100)+1;
[month_name, ~, month_id] = unique(month);
result = splitapply(@sum, data(:,2:end), month_id);
result_with_month = [month_name result];

If you consider  April 2018 and April 2019 different months:
month = floor(data(:,1)/100);
[month_name, ~, month_id] = unique(month);
result = splitapply(@sum, data(:,2:end), month_id);
result_with_month = [month_name result];

Example results with the provided data:
result =
   1.0e+02 *
   0.172050000000000   0.014510000000000   NaN   0.345660000000000
   0.031880000000000   0.017090000000000   NaN   4.895040000000000
result_with_month =
   1.0e+05 *
   1.926070000000000   0.000172050000000   0.000014510000000   NaN   0.000345660000000
   1.926080000000000   0.000031880000000   0.000017090000000   NaN   0.004895040000000

Comment: Why not simply use `month = ceil(data(:, 1) / 100)`, when the "information" stored in `month` is neglected after applying `unique`? :-)
Comment: @HansHirse I'm using `mod` to gather the same month across years. I'll clarify
Answer: This is a typical example where you can use table instead of matrix.
A = [19260702    0.026   0.000   NaN 1.175
     ...
     19260816    0.042   0.007   NaN 25.928];

% Matrix to table conversion
T = array2table(A,'VariableNames',{'DATE','S1','S2','S3','S4'});
% We add a new column "month"
T.MONTH = floor(T.DATE/100);
% varfun can apply a custom function to your table and group the result according
% to one (or more) variable(s)
Result = varfun(@sum,T,'InputVariables',{'S1','S2','S3','S4'},'GroupingVariables','MONTH')

Lazy guy option:
If you're lazy and don't want to add manualy the variable's name you can also use linear indexing:
T = array2table(A) %column name will be 'A1','A2',....
T.MONTH = floor(T{:,1}/100);
Result = varfun(@sum,T,'InputVariables',2:5,'GroupingVariables','MONTH')

Code golf option
If you like short code the arguments name can be shortened. For example if InputVariables is the only argument name starting with I you can simply use I instead of InputVariables.
Result = varfun(@sum,T,'I',2:5,'G',6)

Comment: It's a matter of personal preference. Both methods work. For example a Python user will probably find this approach more familiar if he already used a Dataframe. It's also possible to apply several function at once with: `varfun(@(x) [sum(x),mean(x)],...`
Comment: The method by @LuisMendo seems to work perfectly. What would be the benefits if any of your method. Thanks very much for your answer!
Answer: Yes. You could for example use accumarray here.
With it, it is possible to identify if a value belongs to a certain month and "tag" it using histc function. Values with similar "tags" are summed by the accumarray function.
Comment: @user22485: This is not a link-only answer. Links to the documentation are just a convenience. The function names are right there in the answer, typing `doc ` in MATLAB gets you to exactly the same page. It's not a complete answer, but it's a valid answer.
Comment: @user22485 downvoting is fine if you dislike it but it's not link-only. [Here's some help](https://meta.stackoverflow.com/a/288056/5067311) to get you started with not-an-answers. And [another explanation](https://meta.stackexchange.com/questions/225370/your-answer-is-in-another-castle-when-is-an-answer-not-an-answer).
Comment: I appreciate your answer, I have heard of accumarray but I am still having troubles with actually summing them with the date in the current format etc.
Comment: This should've been posted as a comment. This is not a complete answer
Comment: @user30609 I don't quite understand your problem then. Do you just need a sample code of how to sum values inside a matrix?
Comment: @SardarUsama What do you think I should add in order to make this a complete answer?


Where to check for node value constraints on services data receive

Question: I have a REST service to create nodes. On data receive, node.create is executed, but before actually creating the node I need to check some constraints like node type and other node values.
Is there any I can use?
Answer: To have more control on the node creation you need to write up your own service for nodes using  hook_services_resources(). By default you can control only the access for creating a particular node using permissions.
If you need to control node creation via node values, you need to go with your own services.


Setting MySQL table_cache variable

Question: Greetings,
I've set the table_cache variable in /etc/mysql/my.cnf on Ubuntu to 512, but the reported value is only 64. How can I fix this?
Thanks
Comment: I presume you restarted MySQL? And the line in /etc/mysql/my.cnf says "table_cache = 512"?
Comment: This is correct, yes.
Answer: table_cache increases the amount of file descriptors that mysqld requires.  This is a system limitation, which can also be limited in MySQL with the open-files-limit configuration option.
To see the current system wide limitation in Linux you can run cat /proc/sys/fs/file-max.  This can also be limited on a per-user basis using ulimit -n.
If file descriptors are not the issue and you configured the setting correctly, MySQL could be using a different my.cnf.  Look at the processlist, where the --defaults-extra-file could specify the cnf.  Also, if unspecified the --datadir is often where the my.cnf can live.
You could also search the filesystem for additional my.cnf files.
Comment: Thanks, I'll give it a go. ( I'll vote this up when I have enough rep )
Comment: Assuming this addresses your issue @kobrien, you can click the check mark to accept the answer.  Thanks!
Comment: I'll get to test this in the morning, I'll accept right afterwards if it works. :)
Comment: Still haven't gotten around to testing this. Don't worry, I haven't forgotten. :)

Setting MySQL table_cache variable


Showing a node edit page with drupal_get_form() and hook_menu()

Question: I am using drupal 7 and am stuck at a very basic problem. I would like to simply show the edit page to a known node id. I know there are similar posts but they either didn't work or I didn't understand theme.
My module looks like this:
<?php
/*
 * Show the edid page to a specific nid.
 */

function control_center_menu() {
  $items = array();
  module_load_include('inc', 'node', 'node.pages');
  $nid = '4';
  $node = node_load($nid);
  $items['test/test'] = array(
    'title' => 'Edit this node',
    'description' => 'Edit this node.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('page_node_form', $node),
    'access callback' => TRUE,
  );
  return $items;
}

However, at test/test I get a bunch of errors:
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_form' not found or invalid function name in drupal_retrieve_form() (line 795 of /home/christian/workspace/gigs/includes/form.inc).
Notice: Undefined index: #node in menu_form_node_form_alter() (line 629 of /home/christian/workspace/gigs/modules/menu/menu.module).
Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 629 of /home/christian/workspace/gigs/modules/menu/menu.module).
Notice: Undefined index: #node in menu_form_node_form_alter() (line 630 of /home/christian/workspace/gigs/modules/menu/menu.module).
Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 630 of /home/christian/workspace/gigs/modules/menu/menu.module).

And instead of the hole form I only get the Menu setting check box and the URL path settings.
What am I doing wrong? I tried hard to find a noob friendly copy past example but didn't find any... Thanks a lot in advance!
Answer: hook_menu() is only evaluated when the caches are rebuilt, so the call to module_load_include() won't be called when the path is actually visited.
That hook is only meant for declaring menu items, if there's any logic that needs to be added for a path it should happen in the access callback/page callback like so:
function control_center_menu() {
  $items = array();

  $items['test/test'] = array(
    'title' => 'Edit this node',
    'description' => 'Edit this node.',
    'page callback' => 'control_center_test_callback',
    'page arguments' => array('page_node_form', $node),
    'access callback' => TRUE,
  );
  return $items;
}

function control_center_test_callback() {
  module_load_include('inc', 'node', 'node.pages');
  $nid = '4';
  $node = node_load($nid);

  return drupal_get_form('page_node_form', $node);
}

Since you're forwarding to a static node edit page though, it might be easier just to set the page callback to drupal_goto() and hardcode the URL:
function control_center_menu() {
  $items = array();

  $items['test/test'] = array(
    'title' => 'Edit this node',
    'description' => 'Edit this node.',
    'page callback' => 'drupal_goto',
    'page arguments' => array('node/4/edit'),
    'access callback' => TRUE,
  );
  return $items;
}

Comment: Thanks, now it seems so obvious! The node ID is not meant to be static in the end, that was just for testing purposes. The idea is to append the form to a view which has the nid as a field. So I suppose solution 2 is not the way to go since it redirects?
Comment: Yeah the redirect won't help if you're attaching the form to another page. You might also want to look at [views_embed_view()](http://api.drupal.org/api/views/views.module/function/views_embed_view/7), it might help if you're building up a page with a few different things in it
Comment: So what is the best practice to load the include files? your solution, kiamlaluno solution(at this question) , or this http://fragmentedthought.com/fragments/loading-drupal-core-include-files-right-way? @Clive
Answer: You should define the menu callback as in the following code.
  $items['test/test'] = array(
    'title' => 'Edit this node',
    'description' => 'Edit this node.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('page_node_form', $node),
    'file path' => drupal_get_path('module', 'node'),
    'file' => 'node.pages.inc',
    'access callback' => TRUE,
  );

Remember that an implementation of hook_menu() is being invoked only when menus are rebuild, not each times a new page is requested to Drupal. As consequence of this, the form would get an updated node object only when your module is installed, or when the menus are being rebuilt; in other cases, the form will get a static copy of the node object, which doesn't reflect the actual node object.
It would be better to make test/test a path alias for node/4/edit. In that way, the form would get an updated node object every time.
Comment: Thanks as well for the prompt answer, you guys rock! As said above, I just set it to a static nid for testing purposes.
Answer: I've used code as follow:
function mymodule_menu() {

  $items = array();

  $items['user/%user/firm'] = array(
    'title' => 'Firm',
    'page callback' => 'firm_callback',
    'page arguments' => array(1),
    'access callback' => 'user_check',
    'access arguments'  => array(1),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

function firm_callback($userobj) {
    ....

    if ( isset($node) ) { // existed node

        $form_state['build_info']['args'] = array($node);
        form_load_include($form_state, 'inc', 'node', 'node.pages');
        $form = drupal_build_form('firm_node_form', $form_state);
        return $form;

    } else { // new node

        module_load_include('inc', 'node', 'node.pages');
        $form = node_add('firm');
        return drupal_render($form);

    }
}

function mymodule_form_firm_node_form_alter(&$form, &$form_state, $form_id) {
  form_load_include($form_state, 'inc', 'node', 'node.pages');
}


What is the savart unit in Persian music theory?

Question: I was heard about Savart unit in Persian music that divides a chromatic interval into smaller units.
Persian musicians using an interval smaller than the chromatic intervals, called: Kron. they measure it using the Savart unit.
is this true?
if is true, then how can I convert it into cent or vise-versa?
Answer: An article by Joe Monzo at http://tonalsoft.com/enc/s/savart.aspx defines the savart as 1/300 of an octave.

A savart is calculated as the 300th root of 2, or 2(1/300), with a
  ratio of approximately 1:1.002313162. It is an irrational number. A
  savart has an interval size of approximately 4 cents.

savart = 1000log10(f2/f1)
cents = 1200log2(f2/f1)

Answer: Cents, as the name implies, are 1/100th of a semitone (or "chromatic interval"), when working in 12-tone equal temperment (12-TET).
So, as long as your definition of "savar" is in relation to a "chromatic interval" that is defined as a 12th of an octave, then you should be able to convert back and forth by simply defining 1 savar = 2 cents.
However, if the Persian chromatic interval is not 1/12 of an octave, you will have to draw an equivalence in relation to the octave. The cent is 1/1200th of an octave. The savar is 1/(50*c) of an octave, where c is the number of equal chromatic intervals that make up an octave. You can then easily compare the two.
Comment: yes, in persian called savar, but i just found the true spell, savart
Comment: I couldn't find any references to `savar` beyond your question, but [this thread](https://groups.google.com/forum/?fromgroups=#!topic/rec.music.iranian/qX_0ibaM_2o) seems to indicate a scale that is not strictly equal-tempered, though it may be based on choosing certain 24-TET notes to end up with 17 unequal tones.
Comment: @pylover I see your edits--does this mean the Persian chromatic interval is 1/6 of an octave?
Comment: no. we have a concept named: dastgah. so the intervals are variable across dastgah.for example, in dastgah: shoor ,E-F is 20 savar.
Comment: @NReilingh It takes its name from the French physicist Savart. See Jean During's article for instance: Théories et pratiques de la gamme iranienne. https://www.jstor.org/stable/928594.


Errno 14 HTTP Error 401: Authorization Required Yum

Question: I am having an issue with my own yum repo; I have basic auth on Apache running on a RHEL 6.2 machine on EC2.
It holds the yum repo for both a RHEL 6 machine and a RHEL 5 machine in which I have the RPM's in a separate folder within.
When I do my yum update on any RHEL 6 machine, it's fine, everything works, but when I run it on a RHEL 5.5 machine, I get the error below;

[Errno 14] HTTP Error 401: Authorization Required.

I know for a fact that I can access the machine and the username and password is correct as I can copy and paste what is in the repo file and it works in a web browser no problem.
I suspect there is an issue with a RHEL6x machine serving up a repo for a 5.x machine but can't find the solution.
What could be the problem and how can I resolve it?
Answer: Double check that the repositories configured are indeed the ones that you are expecting to see. You can run yum repolist -v | grep baseurl to see all URLs that yum would try to download. You could then use wget to download each of them and see if you get a similar error. Maybe even append /repodata/repomd.xml to the end of each URL which is what yum would do first anyway.


Unable to make docker image using sbt-native-packager

Question: I'm learning to make docker image of scala application using sbt-native-packager. My application contains akka-http and running fine on localhost:8080 (scala-version: 2.13.1, sbt-version: 1.2.8). Now for making docker image. First I make 'plugins.sbt'.
projects/plugins.sbt:
resolvers += "Typesafe repository" at "https://repo.typesafe.com/typesafe/releases/"
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.7.2")

Then I enable plugins in 'build.sbt'.
build.sbt:
ThisBuild / version := "0.1.0-SNAPSHOT"

ThisBuild / scalaVersion := "2.13.1"

lazy val root = (project in file("."))
  .settings(
    name := "book_system_task"
  )

enablePlugins(
  JavaAppPackaging,
  DockerPlugin
)
Compile / mainClass := Some("server.Server")
Docker / packageName := "testImage/book-system-task"

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-actor" % "2.6.0",
  "com.typesafe.akka" %% "akka-stream" % "2.7.0",
  "com.typesafe.akka" %% "akka-http" % "10.5.0",
  "ch.qos.logback" % "logback-classic" % "1.4.4",
  "com.typesafe.akka" %% "akka-http-spray-json" % "10.5.0",
  "com.google.inject" % "guice" % "5.1.0",
  "com.typesafe.akka" %% "akka-stream-testkit" % "2.7.0",
  "com.typesafe.akka" %% "akka-http-testkit" % "10.5.0",
  "org.scalatest" %% "scalatest" % "3.2.11",
  "com.outworkers" %% "phantom-dsl" % "2.59.0"
)

Now I have to run 'sbt docker:publishLocal' (I'm confused where to run this command in intellij idea), I run this command(docker:publishLocal) in sbt-shell.
Output after running 'docker:publishLocal' in sbt-shell:
docker:publishLocal
[info] Packaging /home/zaryab/Downloads/book_system_task/target/scala-2.13/book_system_task_2.13-0.1.0-SNAPSHOT-sources.jar ...
[info] Wrote /home/zaryab/Downloads/book_system_task/target/scala-2.13/book_system_task_2.13-0.1.0-SNAPSHOT.pom
[info] Done packaging.
[info] Updating ...
[info] Done updating.
[warn] There may be incompatibilities among your library dependencies; run 'evicted' to see detailed eviction warnings.
[info] Main Scala API documentation to /home/zaryab/Downloads/book_system_task/target/scala-2.13/api...
[info] Compiling 30 Scala sources to /home/zaryab/Downloads/book_system_task/target/scala-2.13/classes ...
model contains 60 documentable templates
[info] Main Scala API documentation successful.
[info] Packaging /home/zaryab/Downloads/book_system_task/target/scala-2.13/book_system_task_2.13-0.1.0-SNAPSHOT-javadoc.jar ...
[info] Done packaging.
[info] Done compiling.
[info] Packaging /home/zaryab/Downloads/book_system_task/target/scala-2.13/book_system_task_2.13-0.1.0-SNAPSHOT.jar ...
[info] Done packaging.
[info] :: delivering :: book_system_task#book_system_task_2.13;0.1.0-SNAPSHOT :: 0.1.0-SNAPSHOT :: integration :: Fri Apr 14 11:59:55 PKT 2023
[info]  delivering ivy file to /home/zaryab/Downloads/book_system_task/target/scala-2.13/ivy-0.1.0-SNAPSHOT.xml
[info]  published book_system_task_2.13 to /home/zaryab/.ivy2/local/book_system_task/book_system_task_2.13/0.1.0-SNAPSHOT/poms/book_system_task_2.13.pom
[info]  published book_system_task_2.13 to /home/zaryab/.ivy2/local/book_system_task/book_system_task_2.13/0.1.0-SNAPSHOT/jars/book_system_task_2.13.jar
[info]  published book_system_task_2.13 to /home/zaryab/.ivy2/local/book_system_task/book_system_task_2.13/0.1.0-SNAPSHOT/srcs/book_system_task_2.13-sources.jar
[info]  published book_system_task_2.13 to /home/zaryab/.ivy2/local/book_system_task/book_system_task_2.13/0.1.0-SNAPSHOT/docs/book_system_task_2.13-javadoc.jar
[info]  published ivy to /home/zaryab/.ivy2/local/book_system_task/book_system_task_2.13/0.1.0-SNAPSHOT/ivys/ivy.xml
[success] Total time: 9 s

But still after this, I'm not able to see where Dockerfile is created. Or Docker Image/File is created or not.
Comment: execute: docker images
Answer: As you can see in the docs of sbt-native-packager, you have 4 tasks that you can execute.

docker:publishLocal: will build the image and publish in your local docker server. Based on your output, looks like you have already installed it. Just running docker images from the terminal you should be able to see an image with the name testImage/book-system-task.

If you want to generate a Dockerfile, you should use the task docker:stage. The output of executing that task will tell you where the file is located


Why are tennis players active in multiple events during a Grand Slam?

Question: Now Wimbledon is going on for over a week, I wonder why some players enter mutliple events on the same Grand Slam, e.g. the Williams sisters that in the past participated in the Women's Singles and Doubles. There are plenty of players that start in the Single or (midex) Double.
My question is why do tennis-players do this?
I can imagine that playing in multiple events is exhausting if you survive a few rounds, and playing in the doubles does negatively affect once performance in the singles. On the other hand they might earn more money, or don't expect to get far in either of the events, but that does not hold for the Williams sisters.
Answer: First reason is Money as you stated.
Wining double on Wimbledon worth 260,000£ per pair meaning 130,000£ for each player.
Winning Mixed double worth 92,000£ per pair meaning 46,000£ for each player.
http://www.wimbledon.com/pdf/2012-prizemoney-breakdown.pdf
Second, a big tournament has it's glory.
Winning a Grand Slam or an Olympic looks very well on your resume, No matter if it is not singles..
Last reason, It's FUN, some tennis players love to play tennis! a.k. Andy Ram
also Williams sister love to play with each other and this is their chance.
It's a way to meet and make friends
Double/ Mixed double require smaller effort then single.
As an example Roger Federer, one of the greatest, played doubles in only 4 grand slams (The last one was on 2003!).
But on 2008 Summer Olympics in Beijing Federer played and won the gold medal

**
So, to conclude: Money, Glory & Fun.
**
Comment: I can guess that some top ten will play doubles at Olympic to win Gold medal
Comment: But the top 10 man do not participate, because they have enough money and glory?
Comment: @Bernhard off course..
Comment: Sometimes even the top 10 players play doubles, often just before a Davis Cup tie to get some practice.


another char shift C

Question: so i've looked through here and on google and tried various forms to try and accomplish this. it doesn't seem like it should be hard. i've tried getting a value from the char, tried just using math on it since i've read that a char in C is a number to the compiler anyway. what i have is an array of 4 strings. each element is another array of 20 + 1 characters (to include the null \0) what i'm trying to do is shift the value of each character in each string by a predefined amount using a variable "decryption_shift". what i thought i was doing is using 2 for loops, one to do one string at a time, the other to change each character in the strings. i've tried using pointers, tmp variables. yes this is a homework assignment, problem is it's a higher level class and they aren't teaching us methods/functions/syntax, they want us to research and learn on our own how to do it. i've already spent 2 hours trying to figure out this one snippet and don't know where else to turn. any help is greatly appreciated.
~justin
void decrypt_chunks()
{
    for (m = 0; m < 0; m++)
    {
        for (n = 0; n < 20; n++)
        {
            // int *chunksp = &chunks[m][n];
            chunks[m][n] = chunks[m][n] - DECRYPTION_SHIFT;
            // *chunksp[m][n]=tmp;
            // chunks[m][n]=tmp;
        }
    }
}

Comment: what happens with the code you posted? errors? wrong behaviour?
Comment: Have you defined `m` and `n` as global variables? If not, define them above the for loop.
Answer: Your problem is here:
for (m = 0; m < 0; m++)

The loop will never execute because the termination condition is met on initialization. Try
for (m = 0; m < 4; m++)

Comment: ya sorry. i'm an idiot sometimes lol. looking at too much code and need to take a step back
Answer:
I can't see where DECRYPTION_SHIFT or chunks is defined (and initialized), so make sure you're actually define it globally or in the decrpyt_chunks() function (note: usually you write variables lowercase and macros uppercase, and if DECRYPTION_SHIFT is a variable you should write it in lowercase letters)
for (m = 0; m < 0; m++) while never run, this statement in words would be something like: set m to ziro (btw where did you defined m?) and do the following things as long as m is less than ziro (never the case, as you set it to ziro)

As this seems like a very basic problem, make sure you actually understand what a programming language is and how it works and consider reading one or two books about c (or almost any other programming language, as this homework would be in most modern languages pretty much the same).
To really make this thing interresting, what you basically do is encrypting like Caesar, so to implement this, the code could look similar to this one:
#include <stdio.h>
#include <string.h>

void decrypt_chunks(int decryption_shift);

char chunks[4][21];

int main(int stdr, char *stdv[])
{
    strcpy(chunks[0],"Hello World! And Bye");

    printf("message string:   %s\n", chunks[0]);
    decrypt_chunks(1);
    printf("encrypted string: %s\n", chunks[0]);
    decrypt_chunks(-1);
    printf("decrypted sring:  %s\n", chunks[0]);
}

void decrypt_chunks(int decryption_shift)
{
    for (int m = 0; m < 4; m++)
    {
        for (int n = 0; n < 20; n++)
        {
            chunks[m][n] = chunks[m][n] - decryption_shift;
        }
    }
}

another char shift C


Linha abaixo do texto

Question: Estou tentando colocar uma linha abaixo do título h3, só que respeitando o tamanho da linha de 100px e de acordo como justificado à esquerda ou à direita.
Desta forma:

ou

Porém, quando a resolução da tela diminui (como por exemplo 1029px), as linhas que estão alinhadas a direita não acompanham e se deslocam.

O meu código é (porém não funciona corretamente):

.box-geral-esquerda div.box-texto h3, .box-geral-direita div.box-texto h3 {
    font-size:22px;
    color:#27461f;
    line-height:42px;
}

.box-geral-esquerda div.box-texto h3:before {
    content: "";
    position: absolute;
    border-bottom: 3px solid #27461f;
    width: 100px;
    left:10px;
    top:68px
}

.box-geral-direita div.box-texto h3:after {
    content: "";
    position: absolute;
    border-bottom: 3px solid #27461f;
    width: 100px;
    right:190px;
    top:130px
}

CORPORATIVO LOREM IPSUM

CORPORATIVO LOREM IPSUM

Como posso fazer isto?
Answer: Faltou colocar position: relative nos H3 para que os pseudo-elementos, que são as linhas, se posicionem absolutamente dentro dos H3. Com isso, basta usar bottom e left, para as linhas à esquerda, e bottom e right para as linhas à direita, todos com valor 0.

.box-geral-direita div.box-texto h3{
   text-align: right;
}

.box-geral-esquerda div.box-texto h3, .box-geral-direita div.box-texto h3 {
    font-size:22px;
    color:#27461f;
    line-height:42px;
    position: relative;
}

.box-geral-esquerda div.box-texto h3:before {
    content: "";
    position: absolute;
    border-bottom: 3px solid #27461f;
    width: 100px;
    left:0;
    bottom:0
}

.box-geral-direita div.box-texto h3:after {
    content: "";
    position: absolute;
    border-bottom: 3px solid #27461f;
    width: 100px;
    right:0;
    bottom:0
}

CORPORATIVO LOREM IPSUM

CORPORATIVO LOREM IPSUM

Linha abaixo do texto


Is there a valid way to disable autocomplete in a HTML form?

Question: When using the xhtml1-transitional.dtd doctype, collecting a credit card number with the following HTML
<input type="text" id="cardNumber" name="cardNumber" autocomplete='off'/>

will flag a warning on the W3C validator:

there is no attribute "autocomplete".

Is there a standards-compliant way to disable browser auto-complete on sensitive fields in a form?
Comment: Even for something as sensitive as Credit card number? I can't think of very many people who would want that remembered - especially since auto-complete is on by default in most browsers. If they want it remembered that bad, they can use something that fills out forms like Google toolbar.
Comment: My use case is slightly different - I am rolling my own autocomplete and I don't want it to clash with the browser's. I only just discovered that autocomplete="off" is invalid, but it seems there's no other simple solution (injecting it with js is just silly)
Comment: @rmeador because sometimes we want to provide a more user-friendly alternative to the standard auto-suggest box.
@corydoras please don't push your OSX weight around, it's not helpful to the resolution of this question.
Comment: The problem is that the banks will hold the merchant liable if a fraudulent transaction took place... even if its the customer's fault at 100%. Therefore, in some circumstances, it is legitimate to disable the feature for the customer.
Comment: Are you sure that messing with the user's autocomplete setting is what you want to do?  If they have it turned on, they probably like it.  Autocomplete is a completely browser-side feature, much like the button that allows the user to change font size, etc.  You shouldn't interfere with their wishes
Comment: @rmeador The problem that led me to this question was that I have an admin interface to change someones password, but my browser is auto-filling the 'new password' field with my password, which is obviously not what I want.
Comment: @curiousguy it can be harmful for security in the case where multiple users are sharing the same computer in a small office. Consider the case where an eye doctor has one computer in the office and web based practice management software. The receptionist who also uses the computer shouldn't get the option to login to the practice management software with the doctors credentials. That would be wrong and also could be a HIPAA violation. Of course they shouldn't be using the same account at the OS level but this is the real world.
Comment: HTML 5 autocomplete atrribute: http://www.w3schools.com/html5/att_form_autocomplete.asp
Comment: @curiousguy your comment is wrong. It is legitimate whenever there is a business need for it. You can't possibly think about all use cases of an html element. My client for example is specifically requesting to disable it for certain fields of his intranet as it doesn't make sense there (the text is always different by definition on those fields).
Comment: I need to turn it off in situations where I use OTP generated passwords from tokens in my forms. This number is never the same and autocomplete is totally unneeded there...
Comment: It is not working on firefox 6. I tried setting `autocomplete=off` for form and also for the input fields but none of them seem to work. Though it works for the first input of the form, doesn't work for the second input of the same form
Comment: @AlexandreH.Tremblay It is never legitimate, period. The reckless behavior of bank is another issue.
Comment: @Durden81 I do agree that it is a nice to disable history/autofill for a CAPTCHA form field, as by definition value don't repeat. Nice to have for the user, as the feature is pure distraction, but not necessary in any way (the user can ignore the history) and not having the `autocomplete=off` option it is not harmful for security.
Comment: It's ridiculous that this is even a discussion. I'm building a form that requires entry of address info for clients around the country. When I start typing my own state name, the browser "helpfully" suggests my complete address history (including alternate shipping addresses I've used in Amazon), instead of the js-based typeahead suggestion of, you know, the NAME of the state. Why is it even a question which makes more sense?
Answer: Here is a good article from the MDC which explains the problems (and solutions) to form autocompletion.
Microsoft has published something similar here, as well.
To be honest, if this is something important to your users, 'breaking' standards in this way seems appropriate. For example, Amazon uses the 'autocomplete' attribute quite a bit, and it seems to work well.
If you want to remove the warning entirely, you can use JavaScript to apply the attribute to browsers that support it (IE and Firefox are the important browsers) using someForm.setAttribute( "autocomplete", "off" ); someFormElm.setAttribute( "autocomplete", "off" );
Finally, if your site is using HTTPS, IE automatically turns off autocompletion (as do some other browsers, as far as I know).
Update
As this answer still gets quite a few upvotes, I just wanted to point out that in HTML5, you can use the 'autocomplete' attribute on your form element. See the documentation on W3C for it.
Comment: Looks like Firefox doesn't turn off autocomplete on https, but that's a useful piece of knowledge. Thanks!
Comment: Safari does not respect the autocomplete="off" attribute. See http://stackoverflow.com/questions/22817801/how-to-disable-auto-fill-in-safari-7
Comment: `autocomplete` may be used [not only on `form` element](http://www.w3.org/TR/html5/forms.html#attr-fe-autocomplete), and `off` value works at least in `chromium-40.0.2214.115`
Comment: If nothing works, Use textarea instead of textbox to turn off autocomplete.
Comment: The w3c seems to be expanding the standards for autocomplete in HTML5.1 (in draft as of this comment) http://w3c.github.io/html/single-page.html#autofilling-form-controls-the-autocomplete-attribute
Answer: I would be very surprised if W3C would have proposed a way that would work with (X)HTML4. The autocomplete feature is entirely browser-based, and was introduced during the last years (well after the HTML4 standard was written).
Wouldn't be surprised if HTML5 would have one, though.
Edit: As I thought, HTML5 does have that feature. To define your page as HTML5, use the following doctype (i.e: put this as the very first text in your source code). Note that not all browsers support this standard, as it's still in draft-form.
<!DOCTYPE html>

Comment: All browsers expect older versions of Konqueror support it. Even IE6 supports it. It's the doctype to go.
Answer: HTML 4: No
HTML 5: Yes

The autocomplete attribute is an enumerated attribute. The attribute
  has two states. The on keyword maps to the on state, and the off
  keyword maps to the off state. The attribute may also be omitted. The
  missing value default is the on state. The off state indicates that by
  default, form controls in the form will have their autofill field name
  set to off; the on state indicates that by default, form controls in
  the form will have their autofill field name set to "on".

Reference: W3
Comment: @freestock.tk Yeah it's clearer than all the others. Simplicity matters.
Answer: No, but browser auto-complete is often triggered by the field having the same name attribute as fields that were previously filled out. If you could rig up a clever way to have a randomized field name, autocomplete wouldn't be able to pull any previously entered values for the field.
If you were to give an input field a name like "email_<?= randomNumber() ?>", and then have the script that receives this data loop through the POST or GET variables looking for something matching the pattern "email_[some number]", you could pull this off, and this would have (practically) guaranteed success, regardless of browser.
Comment: Would make automatic testing harder, only if your testing software cant cope check for / read fields that might have a random number appended to them. Might be time to upgrade your automated testing software.
Comment: The autocomplete info would still be saved in the browser's data directory, would it not?
Comment: This would make automatic testing harder.
Comment: Presumably. But it wouldn't be expected to ever actually appear again to the user.
Comment: Chrome now uses the type="password" attribute rather than the name attribute for a particular site.  I have name="newpassword" autocomplete='off' type="password" and it gets autofilled! If I change the type, no autofill
Comment: To remove autocomplete and enable automated testing use a random value for `name` and put the name in a `data-*` attribute.
Comment: @enigma I think it is new-password not newpassword that you want.
Answer: No, a good article is here in Mozila Wiki.
I would continue to use the invalid attribute. I think this is where pragmatism should win over validating.
Answer: How about setting it with JavaScript?
var e = document.getElementById('cardNumber');
e.autocomplete = 'off'; // Maybe should be false

It's not perfect, but your HTML will be valid.
Comment: Using javascript as a workaround to validation errors is like sweeping dust under the rug. While the HTML document may become valid, the resulting HTML+JS page will not be.
Answer: I suggest catching all 4 types of input:
$('form,input,select,textarea').attr("autocomplete", "off");

Reference:

http://www.w3.org/Submission/web-forms2/#the-autocomplete
http://dev.w3.org/html5/markup/input.html
Comment: could use `:input` too
Answer: If you use jQuery, you can do something like that :
$(document).ready(function(){$("input.autocompleteOff").attr("autocomplete","off");});

and use the autocompleteOff class where you want :
<input type="text" name="fieldName" id="fieldId" class="firstCSSClass otherCSSClass autocompleteOff" />

If you want ALL your input to be autocomplete=off, you can simply use that :
$(document).ready(function(){$("input").attr("autocomplete","off");});

Comment: this isn't really valid html anyway, it's just setting the (invalid) `autocomplete` attribute in a different way other than in the html
Comment: Using javascript as a workaround to validation errors is like sweeping dust under the rug. While the HTML document may become valid, the resulting HTML+JS page will not be.
Comment: Just using HTML5 doctype is easier and better.
Comment: This code doesn't work for me; I've used `$('input.autocompleteOff').val('');` which seems to be OK.
Answer: Another way - which will also help with security is to call the input box something different every time you display it: just like a captha.  That way, the session can read the one-time only input and Auto-Complete has nothing to go on.
Just a point regarding rmeador's question of whether you should be interfering with the browser experience:  We develop Contact Management & CRM systems, and when you are typing other people's data into a form you don't want it constantly suggesting your own details.
This works for our needs, but then we have the luxury of telling users to get a decent browser:)
autocomplete='off'

Answer: autocomplete="off" this should fix the issue for all modern browsers.
<form name="form1" id="form1" method="post" autocomplete="off"
   action="http://www.example.com/form.cgi">
  [...]
</form>

In current versions of Gecko browsers, the autocomplete attribute works perfectly. For earlier versions, going back to Netscape 6.2, it worked with the exception for forms with "Address" and "Name"
Update
In some cases, the browser will keep suggesting autocompletion values even if the autocomplete attribute is set to off. This unexpected behavior can be quite puzzling for developers. The trick to really forcing the no-autocompletion is to assign a random string to the attribute, for example:
autocomplete="nope"

Since this random value is not a valid one, the browser will give up.
Documetation
Comment: Modern browsers don't respect autocomplete=off by choice. :/ Unfortunately.
Comment: @Alexus added some update...internet change very fast
Answer: Using a random 'name' attribute works for me.
I reset the name attribute when sending the form so you can still access it by name when the form is sent. (using the id attribute to store the name)
Answer: Note that there's some confusion about location of the autocomplete attribute. It can be applied either to the whole FORM tag or to individual INPUT tags, and this wasn't really standardized before HTML5 (that explicitly allows both locations). Older docs most notably this Mozilla article only mentions FORM tag. At the same time some security scanners will only look for autocomplete in INPUT tag and complain if it's missing (even if it is in the parent FORM). A more detailed analysis of this mess is posted here: Confusion over AUTOCOMPLETE=OFF attributes in HTML forms.
Answer: Not ideal, but you could change the id and name of the textbox each time you render it - you'd have to track it server side too so you could get the data out.
Not sure if this will work or not, was just a thought.
Answer: I think there's a simpler way.
Create a hidden input with a random name (via javascript) and set the username to that.  Repeat with the password.  This way your backend script knows exactly what the appropriate field name is, while keeping autocomplete in the dark.
I'm probably wrong, but it's just an idea.
Answer: if (document.getElementsByTagName) {
    var inputElements = document.getElementsByTagName("input");
    for (i=0; inputElements[i]; i++) {
        if (inputElements[i].className && (inputElements[i].className.indexOf("disableAutoComplete") != -1)) {
            inputElements[i].setAttribute("autocomplete","off");
        }
    }
}

Answer: I MADE THIS WORK IN 2020!
I basically create a css class that applies -webkit-text-security to my inputs.
Here's the link to a more recent discussion:
https://stackoverflow.com/a/64471795/8754782
Answer: This solution works with me:
$('form,input,select,textarea').attr("autocomplete", "nope");

if you want use autofill in this region: add autocomplete="false" in element
ex:
<input id="search" name="search" type="text" placeholder="Name or Code" autcomplete="false">

Answer: Valid autocomplete off

Comment: surely if a user had JS switched off though, they can't complete an order as they can't enter their card number?

Better to supplement the attribute via JS I'd say - worst case, JS off gives the card number field with the potential for auto-complete, but at least they can place an order...

just a thought :)


How do I filter entity reference fields based on language?

Question: In a Drupal 8 site I have a node content type "page" that references a custom entity type using inline entity form. "Page" also has a paragraphs field usig the Paragraphs module.
The site have multiple languages and therefore the following scenario appears:

I have an existing "page" node in both english and german containing entity references and paragraphs.
On the english node I add a new paragraph and a new entity reference and save the node.
When viewing the node in english I see the  added content.
When viewing the node in german I also see the new content, which is in english.

I don't want number 4 to happen. That is, I don't want the new untranslated entity and paragraph to be visible on the german translation of the node. The entity reference and paragraph fields are not set as translatable but the target entities are translatable. From what I understand, this means that the newly created entity will be in english, the same is true for the paragraph.
To solve this I'm thinking I should be able to filter out the untranslated entities and paragraph items when viewing the node so that any item that is not in the current language is not shown. The they won't be visible until I go and edit the german node and resave it, which will create translated versions of the entity and paragraph item.
But I am unsure how to go about filtering the fields. Is there any suitable hook that can be used? Or am I going about this in the wrong way?
Comment: Paragraph does currently not support translatable fields. If not yet, then possibly in the future, things might break. You can still translate the paragraph itself, it's only the reference to the paragraph that you make translatable or not. Editing and resaving and things like that won't work as you think, your paragraphs will get out of sync and you will have completely different paragraphs in each.
Comment: Sorry, I'm not actually having the paragraph reference field translatable, only the paragraph itself is set as translatable along with some of its fields. This seems to work fine, except when I add a new paragraph to a node which already has translations. From what I understamd the new paragraph will not yet have a translated version and should therefore by "filterable" like I'm describing above. Would that be possible?
Comment: I have edited the question to clarify that the fields are not set as translatable but te target entities are.
Comment: Ah, I see. Good :) Not easily, but I'll see about adding a quick answer.
Answer: The logic that defines if entities should be shown is in \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::getEntitiesToView()
As you can see, translation is checked there, but the API doesn't directly support skipping something, the hooks behind that only allow to control applicable fallback languages and their order.
It's possible that you can use entity access, which is checked after that. Implement hook_paragraph_access(), for the view operation, check if the paragraph has a translation in the current content language and if not, forbid access. The same should work for your other entity reference, it's the same could, just implement hook_ENTITY_TYPE_access() for that too.
If that doesn't work, you can write your own field formatter plugin and override that method.
Comment: Brilliant solution! Using an access hook is working great. It's also very easy to extend it to include additional entity types to restrict. It actually solved another question I had about hiding untranslated menu items by simply adding a language check on nodes, http://drupal.stackexchange.com/questions/190213/how-do-i-filter-a-menu-to-only-show-menu-items-translated-into-current-language/192887#192887. Here is a gist of my current solution for filtering based on language https://gist.github.com/reekris/e6f64de799df75d724c2. Thank you so much Berdir!
Comment: I've override the  `getEntitiesToView` method and loop through all entities and checked if it has translation in current language.


is it technically wrong to write $(\lvert x\rvert)^2$ as $(x)^2$?

Question: kind of a simple question , I know, but just in case I'm wrong
is writing an absolute value necessary when said absolute value is squared?
for example something like this:
$(\lvert x-3\rvert)^2 = (x-3)^2$
since absolute value functions can be written as
$\lvert x \rvert = \sqrt{(x)^2}$
I thought that maybe $ (\lvert x \rvert)^2 = (\sqrt{(x)^2})^2 $ and the square root cancels out ,making $(x)^2$
thanks
Comment: For real $x$, it is absolutely fine to write $|x|^2=x^2$. For complex x, these two have different meaning.
Comment: No, it's not wrong.
Comment: okay, thanks. I'm not dealing  with complex numbers or vectors, so it works then
Comment: It is a basic result that on $\mathbf R$, $\;\lvert x\rvert^2=x^2$. Of course this is wrong on $\mathbf C$.
Comment: For vectors in $\mathbb R^n$ writing $|x|^2 = x \cdot x = x^2$ can be motivated by geometric algebra:
https://en.wikipedia.org/wiki/Geometric_algebra
Answer: In general, it is not the case that $|A|^2 = A^2$ (for example, if $A$ is a complex number, or a vector, or some other kind of object where some notions of absolute values and squaring make sense).  However, if $A$ is a real number, then you are fine.
Comment: ok , thanks. real numbers is what I'm dealing with right now so I'll just write it like that
Comment: However for a vector you have an analog: $\lVert A\rVert^2=A\cdot A$.


determining a linear transformation

Question: For a linear transformation, the property to be satisfied is:
<code>T(cu+dv) = cT(u) + dT(v)
</code>
But, given a standard matrix for transformation A such that the transformation for a vector x is: Ax, where A takes the form:
$$
  \begin{pmatrix}
a & b\\
c & d\\
e & f\\
g & h
  \end{pmatrix}
$$ .
Is this form of Ax sufficient to declare it as a linear transformation, given that the transformation exists. Or, is it necessary to check it for the aforementioned properties?
Comment: I would say the form $Ax,$ understood as matrix multiplication, is sufficient to declare it as a linear transformation, yes.
Comment: Every matrix product is a linear transformation. You don't need to check something.
Comment: Is there any proof of that?
Comment: @lind If you are ok, you can accept the answer and set as solved. Thanks!
Answer: It should be sufficient. To assure yourself of this, take an arbitrary matrix of arbitrary dimensions, take two arbitrary vectors $u$ and $v$ of finite dimension matching the appropriate dimension of the matrix, and show that the condition $T(cu+c'v) = cT(u) + c'T(v)$ is satisifed. It's a bit tedious, but now you've shown all matrices express linear transformations.
Answer: At each linear transformation (for a given basis) correspond a matrix and viceversa (for a given basis) at each matrix correspond a linear transformation. Indeed (it's a theorem) a linear transformation is completely defined once we know how the basis vectors are "transformed" that is once the coefficient of the Matrix are defined.
Comment: can you point me to this theorem on a page or something. If there's a name?
Comment: Take a look here https://math.stackexchange.com/questions/289397/a-theorem-concerning-unique-linear-mapping-between-vector-spaces-what-does-it-s
Answer: You are wrong about what a linear transformation is. You should have written$$T(\alpha u+\beta v)=\alpha T(u)+\beta T(v).$$
It is not clear to me what the rest of your question means, but if you are asking if every map of the form$$(x,y)\mapsto A.(x,y)=(ax+by,cx+dy,ex+fy,gx+hy)$$is linear, then, yes, it is true (assuming that your base field is $F$ and that this is a map from $F^2$ to $F^4$). And it is easy to check.
Comment: It is better to write in comment. As you see it is said that *use comments to ask more information or suggest improvements!*

determining a linear transformation


Convert all elements of a collection into strings | MongoDB

Question: In my DB, all my collection's entries have tweet_id: number here. I would like to map through the entire collection with one command and reformat all these numbers (Int64) to string. Is there a command to do that? Doing it manually through the web interface would be very time-consuming.
Answer: Use $toString in the aggregation pipeline in the update.
db.collection.update({},
[
  {
    $set: {
      tweet_id: {
        $toString: "$tweet_id"
      }
    }
  }
],
{
  multi: true
})

Mongo Playground


AttributeError: 'generator' object has no attribute 'set_configuration'

Question: I would want to collect DATA from a USB audio codec connected to a raspberry pi.
So first I'm trying a simple program to write some data
import usb.core
import usb.util

# find our device
dev = usb.core.find(idVendor=0xfffe, idProduct=0x0001)

# was it found?
if dev is None:
raise ValueError('Device not found')

# set the active configuration. With no arguments, the first
# configuration will be the active one
dev.set_configuration()

# get an endpoint instance
cfg = dev.get_active_configuration()
intf = cfg[(0,0)]

ep = usb.util.find_descriptor(
    intf,
    # match the first OUT endpoint
    custom_match = \
    lambda e: \
        usb.util.endpoint_direction(e.bEndpointAddress) == \
        usb.util.ENDPOINT_OUT)

assert ep is not None

# write the data
ep.write('test')

Here is my error :
AttributeError: 'generator' object has no attribute 'set_configuration'
Here is what the tutorial says about this function :
After, we set the configuration to use. Note that no argument indicating what configuration we want was supplied. As you will see, many PyUSB functions have defaults for most common devices. In this case, the configuration set is the first one found.
So I didn't understand why I'm getting this error.
Any ideas please ?
Comment: Fix the indentation on `raise ValueError('Device not found')`
Comment: Yeah thanks I did that in my code but I badly copy paste x)
Comment: Try adding an explicit `find_all=False` in your `usb.core.find` call
Comment: What is printed if you add a line `print dev` after the usb.core.find call?
Comment: print dev gives me a long list of all the features of my USB device (bLength, bDescriptorType, bcdUSB...)
Answer: The error messages suggests that usb.core.find is a generator function. That is, it returns an iterable generator object, not a single device object, like you seem to expect. You need to iterate over the generator in some way (e.g. with a for loop, or by passing it to list) to get the device objects. You may need to add logic to your code to deal with not only getting zero devices (e.g. the "Device not found" case), but also to deal with getting more than one!
Comment: The error does certainly suggests that ... although the actual docs suggest that `usb.core.find` returns an actual item (or None), not an iterator  (unless you pass `find_all=True` in which case it returns you an iterator over all devices satisfying your criteria).
Comment: I have tried to add a while loop like this: while dev is None: dev=usb.core.find(find_all=True, bDeviceClass=1) but I get NameError: name 'dev' is not defined. So how can I defined my object dev ?
Comment: I think a package is missing because I also have AttributeError: 'generator' object has no attribute 'get_active_configuration'...


Dovecot "Address already in use" error

Question: I've some problem with starting dovecot server. I get the following error:
Failed to start Dovecot :
Error: service(imap-login): listen(*, 143) failed: Address already in use
Error: service(imap-login): listen(::, 143) failed: Address already in use
Error: service(imap-login): listen(*, 993) failed: Address already in use
Error: service(imap-login): listen(::, 993) failed: Address already in use
Fatal: Failed to start listeners

So I run netstat command for 993 port:
# netstat -lnp | grep 993
tcp        0      0 0.0.0.0:993             0.0.0.0:*               LISTEN      1/init
tcp6       0      0 :::993                  :::*                    LISTEN      1/init

What can I do to stop init process listening on these ports?
EDIT
Result of systemctl -all list-sockets command:
# systemctl -all list-sockets
LISTEN                          UNIT                            ACTIVATES
/run/acpid.socket               acpid.socket                    acpid.service
/run/dmeventd-client            dm-event.socket                 dm-event.service
/run/dmeventd-server            dm-event.socket                 dm-event.service
/run/lvm/lvmetad.socket         lvm2-lvmetad.socket             lvm2-lvmetad.service
/run/systemd/initctl/fifo       systemd-initctl.socket          systemd-initctl.service
/run/systemd/journal/dev-log    systemd-journald-dev-log.socket systemd-journald.service
/run/systemd/journal/socket     systemd-journald.socket         systemd-journald.service
/run/systemd/journal/stdout     systemd-journald.socket         systemd-journald.service
/run/systemd/journal/syslog     syslog.socket                   rsyslog.service
/run/systemd/shutdownd          systemd-shutdownd.socket        systemd-shutdownd.service
/run/udev/control               systemd-udevd-control.socket    systemd-udevd.service
/var/run/clamav/clamd.ctl       clamav-daemon.socket            clamav-daemon.service
/var/run/dbus/system_bus_socket dbus.socket                     dbus.service
0.0.0.0:143                     dovecot.socket                  dovecot.service
0.0.0.0:993                     dovecot.socket                  dovecot.service
[::]:143                        dovecot.socket                  dovecot.service
[::]:993                        dovecot.socket                  dovecot.service
kobject-uevent 1                systemd-udevd-kernel.socket     systemd-udevd.service
18 sockets listed.

Comment: Please show output for `systemctl -all list-sockets`.
Comment: What version of debian are you running?
Answer: Try to stop socket and restart dovecot.
systemctl stop dovecot.socket
systemctl start dovecot.service

Looks like socket for dovecot was started before dovecot start.

Dovecot "Address already in use" error


How to download webform data to an Excel file?

Question: I'm using the Webform module (version 7.x-4.8), which I only enabled (I didn't change any configuration). I have 10 records in the database.
I want to download the data from Webform to an Excel file, using the typical screen to do so, as in this screenprint:

I tried using these Export Formats:

Microsoft Excel: I can't open the download with with Microsoft Excel 2007.
Delimited text: No data in the file.

I also tried using these Download Range Options (which didn't help either):

Set All submissions (10 total).
Set Submissions by number from '1' and optionally to:(blank).

Any suggestions about what the problem might be?
Answer: Above the Download button,you can select range option from here.
Comment: @estoyausente Oh...this... I had already set All submissions (10 total). Microsoft excel 2007 cant open and I tried Delimited text. No data in the file.
Comment: I have set Submissions by number from '1' and optionally to:(blank) and It's working fine for me.
Comment: I had tried your method. Still the same problem.
Comment: strange!!! Which version you used? Did you cleared the cache? Could you provide the steps of configuration. So, we can find out the actual root cause.
Comment: https://www.drupal.org/project/webform (7.x-4.8). I never change any configuration. Only enable the module.
Answer: Have you try to configure the  "Download range options"? I'm not sure but the default config is "Download element that never have been downloaded yet" or something similar.
Comment: Where is download range options?
Comment: Above the Download button. Do you have any log message in dblog, php log or any other log that you have?


How do I register a user logon script using PowerShell?

Question: My company manufactures a medical instrument and the software that runs on it. Under the hood, it's got a PC running Windows 7. I'm developing a process so that untrained technicians can configure the system and install our applications.
I developed a set of PowerShell scripts and wrote a work instruction on how to use them. One of the scripts requires a restart of the computer. And the next script needs to be started manually after the technician logs back on (using a service account).
I want to simplify the process by registering the second script to run on user logon. I know that there are several mechanisms to do that

Group Policy Logon/Logoff Scripts
Startup programs
Task Scheduler

But, I'm looking for a mechanism that can be configured from PowerShell (adding and removing scripts is necessary). And preferably from a vanilla installation of Windows 7 and PowerShell. I don't have the ability to install the Group Policy PowerShell module, so that mechanism is out.
Answer: Using this article as a reference to start with, the following code will add user login script to the local user profile.  Per the article, you may need to provide the whole path name to get the script to run on login.
<code>$ComputerName = $env:COMPUTERNAME
$Computer = [adsi]"WinNT://$ComputerName"
$user = $Computer.psbase.Children.Find("SomeLocalUserName")
$user.LoginScript = "testscript.ps1"
$user.SetInfo()
</code>
Hope this helps.


Atualização por json não reconhece UTF8 pelo banco de dados

Question: Quando eu aperto no botão CARREGAR no meu portfolio, o $NOME e $TIPO bugam quando tem algum tipo de acento. Os primeiros 6 blocos do portfolio que já são carregados com a pagina, ficam em UTF8 porem os outros não.
Confiram no site:
somospixel.com/test
na parte PORTFOLIO
<code><?php

function fn_conexao(){

    $dbuser = "######";
    $dbpass = "#####";

    try {

        $pdo = new PDO('mysql:host=#####;dbname=#####',  $dbuser, $dbpass);
        $pdo -> setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
        $pdo->exec("SET CHARACTER SET utf8");//corrige os acentos na hora de gravar no BD
    } catch(Exception $e) {

        echo 'Erro na conexao: ' . $e->getMessage();
    }

    return $pdo;
}

function dados($pdo){

    try {

            if(!isset($_GET['id']) or $_GET['id'] == null){

                $id = 0; //se o GET nao for enviado o for enviado como nullo , a variável ID pega o valor de 0

            }else{

                $id = $_GET['id']; //pega o valor passado via GET
            }

            $arr = array();

            $sql = "ALTER DATABASE pot CHARSET = UTF8 COLLATE = utf8_general_ci";
            $sql = "SELECT * FROM pot WHERE id < $id ORDER BY id DESC LIMIT 6";
            $stmt = $pdo->prepare($sql);
            $stmt->execute();
            $linha = $stmt->fetchAll(PDO::FETCH_ASSOC);
            if($stmt->rowCount() >= 1){

                return $linha; //retorna o resultado da query

            }else {

                return 0;

            }
        } catch(Exception $e) {

            print 'Erro ao inserir os dados no banco: ' . $e->getMessage();
            $conexao = desconecta($conexao);

        }
}

$conexao = fn_conexao();
$dados = dados($conexao);

$dados = json_encode($dados); //converte o resultado para json

print $dados; //imprime os dados na tela
?>
</code>
Comment: hum, hosting service. Eh, não consigo ajudá-lo mais :(
Comment: no head do html coloca: ``
Comment: dei uma analisada no seu site, e percebi que seus dados já vem com o charset errado do servidor mesmo, logo, o problema não está na hora de mostrar no HTML. Tentei reproduzir seu problema aqui colocando strings acentuadas no meu mysql e fazendo request desses dados, tudo OK... **Talvez** seu problema esteja na hora de enviar os dados pelo servidor HTTP, então o que você precisa fazer é adicionar o charset correto ao Apache (caso esse seja seu servidor HTTP). Vide [1](http://stackoverflow.com/a/1348521/5953895) e [2](http://stackoverflow.com/a/10926894/5953895)
Comment: @tayllan eu não entendi como vou fazer para ele enviar com o charset certo
Comment: então @kaiquemix, eu apenas chutei o que poderia resolver seu problema: configurar o Apache para utilizar o charset UTF-8. Mas ao mesmo tempo acho difícil ser esse seu problema, e eu não entendo muito mais disso para poder ajudá-lo :(. No [link](http://stackoverflow.com/q/1344692/5953895) que comentei ali encima tem um pessoal discutindo sobre como eles consertaram problemas similares, talvez ajude.
Comment: @tayllan estou usando o phpadmin do hostgator para isso..
Answer: só retirar o
<code>$pdo->exec("SET CHARACTER SET utf8");//corrige os acentos na hora de gravar no BD
</code>
estáva fazendo a conversão duas vezes, com isso ele bugava


Salvar o contato, e-mail e telefone ao clicar num link

Question: Queria saber se isso é possível, pois tenho um cliente que queria fazer isso, eu acredito que não seja.
Como o título diz, preciso que ao clicar numa imagem (isso no celular, claro) ele salve ou pelo menos vá para a parte do celular de cadastro de contatos.
Alguém já viu algo parecido? Sabe se tem como fazer?
Sei que tem como fazer com a chamada telefônica:
Telefone

Comment: A forma mais prática de fazer isso é utilizando AJAX, leia um pouco sobre e provavelmente conseguirá solucionar esse problema.
Obs: Apenas com PHP é possível também, mas isso seria apenas com reload, então, todos optam pelo AJAX.
Answer: Não é possível, HTML5 e APIs JavaScript não permitem tão interação, seria legal se existisse uma janela que abrisse perguntando se o usuário gostaria de salvar, mas não existe tal funcionalidade.
No iOS (iPhone) se segurar o touch no link dá a opção Add Contacts:

Creio ser o máximo possível com HTML, no entanto talve Vcard possa ajudar, se criar um documento com a extensão .vcf (e o servidor http estiver configurado com o Content-Type correto) ou então setar no header de um script dinâmico server-side (como php) o Content-Type: text/vcard, com um formato semelhante a este:
BEGIN:VCARD
VERSION:3.0
N:Doe;John;;;
FN:John Doe
ORG:Example.com Inc.;
TITLE:Imaginary test person
EMAIL;type=INTERNET;type=WORK;type=pref:firstname.lastname@example.com
TEL;type=WORK;type=pref:+1 617 555 1212
TEL;type=WORK:+1 (617) 555-1234
TEL;type=CELL:+1 781 555 1212
TEL;type=HOME:+1 202 555 1212
item1.ADR;type=WORK:;;2 Enterprise Avenue;Worktown;NY;01111;USA
item1.X-ABADR:us
item2.ADR;type=HOME;type=pref:;;3 Acacia Avenue;Hoemtown;MA;02222;USA
item2.X-ABADR:us
NOTE:John Doe has a long and varied history\, being documented on more police files that anyone else. Reports of his death are alas numerous.
item3.URL;type=pref:http\://www.example/com/doe
item3.X-ABLabel:_$!<HomePage>!$_
item4.URL:http\://www.example.com/Joe/foaf.df
item4.X-ABLabel:FOAF
item5.X-ABRELATEDNAMES;type=pref:Jane Doe
item5.X-ABLabel:_$!<Friend>!$_
CATEGORIES:Work,Test group
X-ABUID:5AD380FD-B2DE-4261-BA99-DE1D1DB52FBE\:ABPerson
END:VCARD

Ao abrir no seu celular é provavel que veja uma tela semelhante a esta:

Então o usuário vai notar o "Open in Contacts" (em celulares em Português o texto vai estar em português, não se preocupe)
Fonte: https://www.w3.org/2002/12/cal/vcard-examples/
Comment: Valeu, Gui. Vou testar desta forma que você recomendou.


How to draw a polyline with webgl earth

Question: I am trying to draw a polyline between multiple coordinates using webgl earth. There is an API for drawing a polygon but I can't seem to find anything equivalent for a polyline.
Thanks for your help!
Answer: Use polygon, set 3 waypoint,  A/B/A, then you get a super simple polyline !

How to draw a polyline with webgl earth


Piece-wise proportional hazards model as equivalent Poisson model

Question: A proportional hazards model $\lambda_i(t|x_i) = \lambda_0(t)\exp\{x_i^T \beta\}$ can be approximated using a piece-wise constant hazard, where the duration is partitioned into intervals and the baseline hazard is constant within each interval. In these notes, for example, it is shown that the death indicators $d_{ij}$ for individual $i$ and interval $j$, can be modeled as independent Poisson observations with means $\mu_{ij} = t_{ij} \lambda_{ij}$, with obvious notations.
While I can follow the proof,  this still seems wrong to me, as a Poisson distribution places probability mass on values > 1, and yet $d_{ij}$ can only be 0 or 1. Intuitively, how can you model a random variable that only takes values 0 and 1 with a Poisson distribution? I understand that for small means, the Poisson does converge to a Bernoulli distribution, but this approximation does not appear anywhere in the proof, and there are cases where the rate of death may be quite high.
Answer: It doesn't have a Poisson distribution, only a Poisson likelihood.  That is, for any observed values $y$ of $Y$ the likelihood ratios $P(Y=y;\theta_1)/P(Y=y;\theta_0)$ are the same as they would be for a Poisson distribution (which is all you need for estimation and other parameter inference). The probabilities of values of $Y$ that you don't observe don't enter into the likelihood ratios, so they need not match.
The reason you have a Poisson likelihood is that you can model the data as produced by a stopped non-homogeneous Poisson process. The process for any individual stops when that individual first dies (or when they are censored). This sort of early stopping alters the sampling distribution of the data but doesn't alter the likelihood ratios.
A simpler example is binomial vs negative binomial: the likelihood ratios for a given set of data are the same even though the sampling distributions over sets of data are different.  Here we have 5 successes and 2 failures in 7 seven trials, as binomial and negative binomial
<code>> dbinom(5,7,.5)/dbinom(5,7,.3)
[1] 6.561266
> dnbinom(2,5,.5)/dnbinom(2,5,.3)
[1] 6.561266
</code>
Comment: Yes, that's correct. There are also problems when you put very large numbers of nuisance parameters into a logistic regression.  *Conditional* logistic regression at each time point *is* the same as the Cox partial likelihood, but that conditions out all the time-specific nuisance parameters and conditions on the total number of events at each time point.
Comment: This is the critical distinction I was missing: the likelihood is identical, not the distribution. I was also wondering why I couldn't use logistic regression (ie a GLM w/ Bernoulli distribution) to fit the death indicators $d_{ij}$, instead of a Poisson. I presume this is because the likelihoods do not match, and hence the coefficients $\beta$ I would obtain would not exactly correspond to those from the Cox model.
Comment: This may be a separate question, but do you have a quick explanation or other sources that explain why a Poisson regression is less sensitive to large numbers of nuisance parameters than a logistic regression?
Comment: I don't think there's a simple heuristic explanation, though it has something to do with the fact that the log link can be passed through an expectation.  The paper showing how logistic regression breaks is: https://doi.org/10.1093/biomet/68.1.73
Answer: One way to think about this is that, within each time interval $j$, you are modeling the Poisson parameter $\mu_{ij}$ based on the time $t_{ij}$ to the first event within interval $j$ for individual $i$, where interval $j$ starts at time $\tau_{j-1}$ and ends at $\tau_j$.
Similarly to how individuals with censored event times don't contribute information beyond the last follow-up time, individual $i$ provides no information after the observed event time $(\tau_{j-1}+t_{ij})$--even if more than one event might be possible in principle. Put slightly differently, the derivation on that page shows that the likelihood of the data you have is equivalent to that of a Poisson model, except for a parameter-independent constant.
The extension of this approach to multiple independent individuals having the same baseline hazard then leads to a Poisson model for the total number of deaths during a shared time interval.


Are "random sample" and "iid random variable" synonyms?

Question: I have been facing hard time understanding meaning of "random sample" as well as "iid random variable". I tried to find out the meaning from several sources, but just got more and more confused. I am posting here what I tried and got to know:
Degroot's Probability & Statistics says:

Random Samples / i.i.d. / Sample Size : Consider a given probability distribution on the real line that can be represented by either a p.f. or a p.d.f. $f$. It is said that $n$ random variables $X_1 , . . . , X_n$ form a random sample from this distribution if these random variables are independent and the marginal p.f. or p.d.f. of each of them is $f$. Such random variables are also said to be independent and identically distributed, abbreviated i.i.d. We refer to the number n of random variables as the sample size.

But one of the other statistics book I have says:

In a Random Sampling, we guarantee that every individual unit in the population gets an equal chance(probability) of being selected.

So, I have a feeling that i.i.d.s are elements that construct random sample, and the procedure to have random sample is random sampling. Am I right?
P.S.: I am very confused about this topic, so I will appreciate elaborate reply. Thanks.
Comment: The _independence_ part is very important because we can have a sample in which all the variables are identically distributed (have the same marginal distribution) but are _not_ independent. Such a sample can still be considered as a _random sample_ but not of the experiment that you think it is a random sample of.  See [this question](http://stats.stackexchange.com/q/17868/6633).
Comment: @subhashc.davar Are they? According to one definition: "A random sample is a sequence of independent, identically distributed (IID) random variables". So it seems iid and random sample are the same thing? The cited paragraph in Degroot's Probability & Statistics basically says the same. I find it confusing because a "sample" is sometimes an individual or a set of individuals, and sometimes a sequence of random variables.
Comment: The question does not seem to make a statistical sense. The iid and random sample are clearly distinct concepts established by literates.
Comment: @Gary Chang The definition you cited  pertains to pdf. The sample of random variables has been popular in the discipline of  psychometry. Generally, it is used with reference to reliability Or validity estimate and for a factor analysis. The psychometry are interested in establishing equivalence of tests for a domain. The iid concept appears to originate from linear algebra. A sample could be from a given population of individuals and/ or from  a population of (random) variables depending on the purpose of a study. The present day statistics appears to have borrowed from the measurementtheory.
Answer: You don't say what the other statistics book is, but I'd guess that it is a book (or section) about finite population sampling.
When you sample random variables, i.e. when you consider a set $X_1,\dots,X_n$ of $n$ random variables, you know that if they are independent, $f(x_1,\dots,x_n)=f(x_1)\cdots f(x_n)$, and identically distributed, in particular $E(X_i)=\mu$ and $\text{Var}(X_i)=\sigma^2$ for all $i$, then:
$$\overline{X}=\frac{\sum_i X_i}{n},\quad E(\overline{X})=\mu,\quad
\text{Var}(\overline{X})=\frac{\sigma^2}{n}$$
where $\sigma^2$ is the second central moment.
Sampling a finite population is somewhat different. If the population is of
size $N$, in sampling without replacement there are $\binom{N}{n}$ possible
samples $s_i$ of size $n$ and they are equiprobable:
$$p(s_i)=\frac{1}{\binom{N}{n}}\quad\forall i=1,\dots,\binom{N}{n}$$
For example, if $N=5$ and $n=3$, the sample space is $\{s_1,\dots,s_{10}\}$
and the possible samples are:
$$\begin{gather}s_1=\{1,2,3\},s_2=\{1,2,4\},s_3=\{1,2,5\},s_4=\{1,3,4\},s_5=\{1,3,5\},\\
s_6=\{1,4,5\},s_7=\{2,3,4\},s_8=\{2,3,5\},s_9=\{2,4,5\},s_{10}=\{3,4,5\}\end{gather}$$
If you count the number of occurrences of each individual, you can see that they are six, i.e. each individual has an equal chance of being selected (6/10). So each $s_i$ is a random sample according to the second definition. Roughly, it is not an i.i.d. random sample because individuals
are not random variables: you can consistently estimate $E[X]$ by a sample mean but will
never know its exact value, but you can know the exact population mean if $n=N$ (let me repeat: roughly.)${}^1$
Let $\mu$ be some population mean (mean height, mean income, ...). When $n<N$
you can estimate $\mu$ like in random variable sampling:
$$\overline{y}_s=\sum_{i=1}^n y_i,\quad E(\overline{y}_s)=\mu$$
but the sample mean variance is different:
$$\text{Var}(\overline{y}_s)=\frac{\tilde\sigma^2}{n}\left(1-\frac{n}{N}\right)$$
where $\tilde\sigma^2$ is the population quasi-variance:
$\frac{\sum_{i=1}^N(y_i-\overline{y})^2}{N-1}$.
Factor $(1-n/N)$ is usally called "finite population correction factor".
This is a quick example of how a (random variable) i.i.d. random sample and a
(finite population) random sample may differ. Statistical
inference is mainly about
random variable sampling, sampling
theory is about finite
population sampling.

${}^1$ Say you are manufacturing light bulbs and wish to know their average life
span. Your "population" is just a theoretical or virtual one, at least if you
keep manufacturing light bulbs. So you have to model a data generation
process and interpret a set of light bulbs as a (random variable) sample. Say
now that you find a box of 1000 light bulbs and wish to know their average
life span. You can select a small set of light bulbs (a finite population
sample), but you could select all of them. If you select a small sample, this
doesn't transform light bulbs into random variables: the random variable is
generated by you, as the choice between "all" and "a small set" is up to
you. However, when a finite population is very large (say your country
population), when choosing "all" is not viable, the second situation is better
handled as the first one.
Comment: What do you mean "individuals are not random variables?"  Whuber has some really nice answers [here](http://stats.stackexchange.com/a/96000/44451) and [here](http://stats.stackexchange.com/a/54894/44451) which use finite population sampling to explain the concept of a random variable.
Comment: I mean what I've said: if $n=N$ then there is no uncertainty.
Comment: That was not helpful in clarifying your statement that appears to be in direct contradiction with those made in the links. Please, there is no need to be defensive. The point about $n=N$ has nothing to do with the statement I'm curious about. Besides, is a degenerate random variable not a random variable?
Comment: Defensive? You didn't understand those links. As whubner says, a) the tickets-in-a-box model is just a _toy example_ to avoid "this is graduate level stuff" complains; b) he _avoids_ calling "population" the tickets in a box, and explains why. _So there is no contradiction_. If one can understand what whubner has said. BTW, I'm not a random variable, are you?
Comment: IMHO, of course.
Comment: No, I am not a random variable, but aren't I the realization of one?  Isn't $X_i=$value of the $i^{th}$ person randomly chosen, a random variable that maps from $\Omega=$ set of all people in population, to the real line?  Only after the $i^{th}$ person is randomly chosen does $X_i$, the random variable, become $x_i$, the value corresponding to the particular individual chosen, right?
Comment: In probability theory $\Omega$ is a _sample space_, the set of all possible outcomes or results of an experiment. In sampling theory the "set of all people in population" is $\mathcal{U}=\{u_1,\dots,u_N\}$ and is _given_, it is _not_ the outcome of an experiment. When you select a sample of size $n<N$, you can and must look at the probability of selecting every individual unit in the population, and it depends on your sampling design. It is the _unique_ source of randomness in sampling theory. I hope you can see the difference.
Comment: More formally: in probability theory a probability space is $(\Omega,\mathcal{F},P)$. In finite sample theory you cannot just replace $\Omega$ with $\mathcal{U}$. The probability space is $(\mathcal{S},2^{\mathcal{S}},P)$, i.e. the sample space is _not_ the population, it is a set of samples.
Comment: Thanks for clarifying.  I see the distinction you are making, though I don't think I have ever seen it before. I am not currently able to see a formal reason why you cannot simply replace $\Omega$ with $U$.  I suppose at this point the distinction appears to be coming down to accepted terminology?  Are you saying that in finite sample theory, I'm not allowed to define a random variable for the probability space?
Comment: If $\Omega$ is a set of outcomes of an experiment, it can't be a finite set of individuals! "Five coins" is a finite population, "five coin _tosses_" (even of a single coin) is an experiment. $\mathcal{U}$ is _given_, $\Omega$ is _generated_ (by an experiment), $\mathcal{S}$ is generated (by a sampling design). In probability theory a random variable is a function $\Omega\to\mathbb{R}$, in finite sample theory a random variable is a function $\mathcal{S}\to\mathbb{R}$, _not_ $\mathcal{U}\to\mathbb{R}$. If you have never seen it before, apparently you have never studied sampling theory.
Comment: Indeed, I have not.  It seems I have only been exposed to a more abstract definition of $\Omega$ which would seem to cover both scenarios and not require the distinction being drawn here. I suppose I can see how the distinction in notation might be helpful.  I still, however, am not able to see a practical reason why finite sample theory would not allow a random variable to be a function $U \rightarrow \mathbb{R}$.  If the sample size is 1, then $S=U$, right?
Comment: Are you looking for a "practical" reason? Well: nobody minds drawing samples of size 1. Why? You can easily find the answer. However, I can't recap sampling theory in short comments.
Comment: Unfortunately, it appears the conventions you are advocating are not standard? I seem to be able to easily find alternative definitions of random variables for finite population sampling in books [pg. 5](http://books.google.com/books?id=tkSE_KyNs7wC&printsec=frontcover&source=gbs_ge_summary_r&cad=0#v=onepage&q&f=false), [pg. 311](http://books.google.com/books?id=JlstYbznwQAC&printsec=frontcover&source=gbs_ge_summary_r&cad=0#v=onepage&q&f=false).
Comment: pg. 5: "Definition 1.5. A sampling scheme gives the conditional probability of selection of units". This is _exactly_ what I've said: the probability of selection of units is the unique source of randomness. Sure, you can'uderstand what you have never studied by reading short comments. So, please, stop. I'll stop.
Comment: READ THE BOTTOM OF PG 5!!!
Comment: There are also numerous examples throughout the statistical literature.  A quick search led me to Hoeffding JASA 1963 pg 28. Also, Royall Biometrika 1970 discusses precisely the philosophical issues we are discussing and provides arguments for and against treating the values in the population as either fixed or random variables, pg. 10.
Comment: Ridicolous. You can't quote sentences out of a context THAT YOU IGNORE and pretend that they contradict something. Ridicolous. Conceited. Impolite.
Comment: Allow me to quote directly word for word from pg 5 of Theory and Method of Survey Sampling. "We shall denote by $y_i$ the value of $y$ on the unit selected at the $i$th draw, $(i=1,2,...n)$.  Thus for example, if the sample is $S=\{4,5,1\}$, $y_1 = Y_4$, $y_2 = Y_5$, $y_3 = Y_1$.  Clearly, $y_i$ is a random variable whose possible values lie in the set $(Y_1, Y_2, ... Y_N)$."
Comment: Hoeffding 1963 JASA, pg 28, section titled  "Sampling from a finite population" "Let the population $C$ consist of $N$ values $c_1, c_2, ..., c_N$. ... let $Y_1$, $Y_2$, ... $Y_n$ denote a random sample with replacement from $C$.  The random variables $Y_1$, $Y_2$, ... $Y_n$ are independent and identically distributed"
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/14598/discussion-between-sergio-and-jsk)
Answer: I will not bore you with probabilistic definitions and formulas, which you may easily pick up at any textbook (or here is a good place to start)
Just think of this intuitively, random sample is a set of random values.  In general, each one of the values may either be identically or differently distributed. $i.i.d.$ sample is a special case of random sample, such that every value comes from the same distribution as the others and its value does not have any influence upon other values. Independence deals with $how$ the values were generated
$i.i.d$ example: draw a random card from a deck and return it back (do this 5 times).  You will get 5 realized values (cards).  Each one of these values comes from a uniform distribution (there is equal probability to get each one of the  outcomes) and each draw is independent of the others (i.e. the fact that you get an ace of spades in the first draw, does not influence in any way the result you may get in other draws).
non $i.i.d.$ example: Now do the same thing, but without returning the card to the deck (I hope you feel the difference by now).  Again you will have 5 realized values (cards) after you do this.  But clearly they are dependent (the fact that you draw the ace of spades on the first draw, means you will not have a chance to get in on the 2nd draw).
Answer: A Random Variable usually written X, is a variable whose possible values are numerical outcomes of a random phenomenon. The random phenomenon may produce outcomes that have numerical values captured by the random variable --e.g. number of heads in 10 tosses of a coin or incomes/heights etc in a sample -- but that is not necessary .
More generally a Random Variable is a function that maps random outcomes to numeric values. E.g. each day may be sunny, cloudy or rainy.  We can define a Random Variable that takes the value 1 if it is rainy, 2 if it is cloudy and 3 if it is sunny.
The domain of a random variable is the set of possible outcomes.
To establish a Random Variable there must be a process or experiment that is associated with possible outcomes that can not be predicted with certainty.
Coming now to the issue of independence.  Two Random Variables are independent if the value of one of them does not affect the PDF of the other.  We don't revise our predictions regarding the probabilities of different values of one variable when we know something about the other variable.  Therefore in the case of independence the Posterior PDFs are identical to the Prior PDFs.  E.g. when we toss a unbiased coin repeatedly, the information we have about the outcome of the 5 prior tosses does not affect our prediction about the current toss, it will be always 0.5.  However, if the bias of the coin is unknown and is modeled as a Random Variable, then the outcome of the previous 5 tosses affects our predictions regarding the current toss because it allows us to make inferences regarding the unknown bias of the coin.  In that case the Random Variables capturing the number of Heads in a sequence of n tosses are dependent and not independent.
Coming now to the issue of Sampling.  The purpose of Sampling is to inform us about the properties of an underlying distribution that is not known and must be inferred.  Remember that a Distribution refers to the relative likelihood of possible outcomes in the Sample Space (which may also be a Conditional Universe).  So when we Sample we chose a finite number of outcomes from the Sample space and we reproduce the Sample Space in a smaller more manageable scale.  Equal probability then refers to the process of the Sampling not the probability of the Outcomes in the Sample.  Equal probability sampling implies that the Sample will reflect the proportions of the outcomes in the original Sample Space.  E.g. if we ask 10,000 people if they have ever been arrested it is probable that the sample we will end up will not be representative of the Population -- the Sample Space-- since people who would have been arrested might refuse to reply, therefore the proportion of possible outcomes (arrested - not arrested) will differ between our sample and the population for systematic reasons.  Or if we chose a particular neighborhood to conduct a survey the results will not be representative of the City as a whole.  So equal probability sampling implies that there are no systematic reasons --other than pure randomness-- that makes us believe that the proportions of possible outcomes in our sample are different from the proportions of outcomes in the Population / Sample Space.
Answer: A random sample is a realization of a sequence of random variables. Those random variables may be i.i.d or not.


Non-vanishing 2-form on quartic surface.

Question: Let $S\subset \mathbb P^3$ be a quartic surface defined by a homogeneous degree 4 polynomial $F\in k[x_0,x_1,x_2,x_3]$. $S$ is a K3 surface, so it has a unique non-vanishing $(2,0)$-form $\omega$ up to scalar.
How can this $\omega$ be computed?
Answer: If $S$ is smooth, $\omega$ can be calculated as a Poincaré residue (see Griffiths and Harris, pg. 147, for details).
It boils down to the following:  in an affine patch with coordinates $z_1,z_2,z_3$, where $F$ is represented by $f(z_1,z_2,z_3)$,
$$
\omega = \int_{f=0} \frac{dz_1\wedge dz_2\wedge dz_3}{f}
$$
where the integral is a higher-dimensional contour integral -- it is taken over the boundary of some arbitrarily smooth tubular neighbourhood of $S$.
Comment: Right!  And from this point of view, the necessity that $S$ is smooth comes from the fact that in this case, $\partial f/\partial z_i$ is non-zero for at least one $z_i$ at each point.
Comment: So $\omega$ is by definition $\frac{dz_2\wedge dz_3}{\partial f/\partial z_1}$ if $\partial f/\partial z_1$ is not zero.