Chrome Extension/JavaScript - Saving data to Chrome Sync not storing correctly

Question: Brief
I'm making an Options page for a Chrome Extension. I have multiple fields however I'm unable to store the data for retrieval later, as it keeps storing an empty array (instead of what I'm asking it to store).
Code

//On load
$(function() {
  $("#saveBtn").click(saveAll);
});

//Function to save all data
function saveAll() {
  var settings = [];

  //Go through all inputs with [data-input-settings] attribute
  $("[data-input-settings]:not(.ignore)").each(function(e) {
    var $t = $(this);
    var n = $t.attr("data-input-settings");

    //Add this setting key and value to settings array
    settings[n] = getVal(n);
  });

  //Save to storage
  chrome.storage.sync.set({
    "settings": settings
  }, function() {
    console.log(settings);
    console.log("Saved");

    //Output to check (development environment)
    chrome.storage.sync.get("settings", function(o) {
      console.log(o.settings);
    });
  });
}

//Function to retrieve value by field name
function getVal(field){
 return $("[data-input-settings='"+field+"']").val() || false;
}

  <input type="checkbox" data-input-settings="adv-debug">Enable debug mode
  <button type="submit" id="saveBtn">Save All</button>

Expected Output to Console (on Save All button click when checkbox is selected):
[adv-debug: "on"]
Saved
[adv-debug: "on"]

Actual Output to Console (on Save All button click when checkbox is selected):
[adv-debug: "on"]
Saved
[]

When calling the following function at any stage, the output to console is "[]" (even when called on pageload):

function retrieveAll() {
  chrome.storage.sync.get("settings", function(o) {
    console.log(o.settings);
  });
}

Question
Why isn't the settings array being saved to the Chrome sync storage, and what changes are needed to make it work?
Answer: In this line:
settings[n] = getVal(n);

since n is a string and not a number, you are adding a property to the array settings, not adding values to it. Remember that arrays are objects, too. After that operation, settings is still a zero-length array with another property (in your case avd-debug: "on" ).
You can try to one of these two things:
1) declare settings as an object instead of an array. I.e. change
var settings = [];

for
var settings = {};

2) add key:value pairs to settings array using, for instance, push, like:
settings.push({[n]:getVal(n)});


Is it ok to load the data from server every time, when fragment or activity is resumed?

Question: I want to create a Android app which shows the list of users registered to my app and other functionalities.
Users of the application are fetched from server every time, when user open the activity or fragment. But it will show a lag of some seconds to user means user can't interact with the view. Is it ok?
On the other side, i think of storing the users in local database for the first time and load the users from the local database in next time. And If any new user will registered to my App, then i must send push notification to all users, which will store the details of the user in the local database.
I am confused on this. If anyone has better solution to this, please let me know.
Thanks.
Comment: *Is it ok?* - Can you be more specific by what you mean by "OK"? Is there a specific outcome you're looking to avoid? If you're just asking whether users will be OK with the lag, that would be primarily opinion based.
Comment: so let me know, what would be ok for you?
Comment: saving battery life ,good app responsiveness ,avoiding unnecessary processing, avoiding huge amount of short lived data, keeping your heap small seems okay for me. hope it helps
Comment: Mean to make Network call each time, when user open the activity or fragment.
Comment: That wouldn't be *ok* to me but we might have different definitions of ok...
Answer: I think you already know the right answer.
Implement a database in your app (SQLite) and use data from there on launch and only then update it (on background thread). Add a Service to your app and download new data in some interval using Job Scheduler (to save some battery life).


Jackson JSON deserialization

Question: I am trying to deserialize the following Json payload using Jackson:
[{
  "owner" : "345MWyh7w4hY98W6",
  "url" : "http://www.google.com",
  "items" : [{
    "createdAt" : 1342099411415,
    "amount" : 1,
    "note" : "item 1",
    "product" : "car"
  }, {
    "createdAt" : 1342100231111,
    "amount" : 4,
    "note" : "item 2",
    "product" : "wheels"
  }],
  "createdAt" : 1342096943777,
  "title" : "Car order",
  "description" : "car order",
  "id" : "98hw85Y945e6U358"
}]

I am using the following code to deserialize:
ObjectMapper mapper = new ObjectMapper().configure(
        DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

List<Order> result = null;
try {
    result = mapper.readValue(jsonString,new TypeReference<List<Order>>() { });
} catch (IOException e) {
    e.printStackTrace();
}

However I get the following error:
org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo
SEVERE: MessageBodyWriter not found for media type=application/json, type=class org.glassfish.jersey.client.InboundJaxrsResponse, genericTyp
e=class org.glassfish.jersey.client.InboundJaxrsResponse.
Feb 06, 2015 8:14:45 PM org.glassfish.jersey.filter.LoggingFilter log

The class Orders is generated by RAML -> JAX-RS maven plug-in and this does not have a zero argument constructor. Is there any way of doing this de-serialization other than modifying the generated class to add a zero-args constructor ?
Comment: check this http://stackoverflow.com/questions/23601842/jersey-messagebodywriter-not-found-for-media-type-application-json-type-class
You have MessageBodyWrite not found exception.
Answer: Was able to fix with a work-around. I created a wrapper DTO over the Order as follows:
@XmlRootElement
public class OrderDTO {

    private List<Order> orderList;

    public List<Order> getOrderList() {
        return orderList;
    }

    public void setOrderList(List<Order> orderList) {
        this.orderList = orderList;
    }

    public void addOrder(Order order){
        orderList.add(order);
    }

    public OrderDTO() {
        super();
        orderList = new ArrayList<Order>();
    }
}

here I was able to add the zero-args constructor. Now it works :).

Jackson JSON deserialization


Workflow for Entity relationship / relations

Question: I have a content type called Blog. I want the end users to be able to add new relations between the blogs, so that we can build a network of related blogs. But the challenges I am facing are

Users should be able to add the relations without having the access to edit blogs.
The relations(references) added by the users should be monitored. I need to have a workflow around it. Eg : If more than 2 users with the role moderator upvote this relations/reference then it should become public.

I have searched quite a bit for workflow and entity relationship but nothing worthwhile seems to come up. Currently the only option seems to be a combination of relations and workflow module. I haven't used in relations in any projects earlier and would try to avoid it if possible.
Any suggestions or inputs are greatly appreciated. TIA
Answer: How about a content type with two Entity Reference fields?  One for each of the two blogs.
Each node of that content type will then be a connector, and you can use the workflow module or perhaps Workbench Moderation to manage the connections.


Does the Intergral Test require the integrand to converge to zero to be applicable?

Question: Is there an error in the following statement of the Integral Test (from David Brannan's Mathematical Analysis)?

The author requires the integrand (equivalently, the general term of the series) to converge to zero for the test to be applied. Is this correct? For if the integrand converges to zero, then the series converges, so there is no need to apply the Integral Test, is there?
Comment: I guess no, the integrand converges doesn't imply summation of integrand converges.
Answer: ADD The condition that $a_n\not \to 0$ is sufficient for a sequence $a_n$ to fail to have a sum $$\sum_{n=0}^\infty a_n$$
That is, if $a_n\not\to 0$ then $\sum a_n$ fails to exists.
This implies, by contrapositiveness, that the condition $a_n\to 0$ is necessary for the sequence to have a sum, but it is not sufficient. That is, if $\sum a_n$ exists, then $a_n\to 0$.
However, there is a canonical example where we see how this fails:
$$\frac 1 n\to 0\text{ however } \sum \frac 1 n $$ fails to exist.

Observe that because $f$ is positive and decreasing
$$\sum_{k=2}^n f(k)\leq \int_1^n f \leq \sum_{k=1}^{n-1}f(k)$$
From the first side of the above, and assuming  $$\int_1^n f $$ is bounded above by some number $R$, we get that $$\sum_{k=2}^n f(k)\leq R$$ for each $n$.
Since $f$ is positive, the series is monotone increasing, so that by the monotone convergence theorem, the result follows.
On the other hand, the rightmost inequality implies that if $$ \int_1^n f $$ diverges, so does $$\sum_{k=1}^{n-1}f(k)$$
by direct comparison.
Comment: Does the word "contrapositiveness" even exist? Came in handy, but I think I just invented it.
Comment: There are surprisingly plenty of english words (or word forms) that haven't been officially "invented" that should be and are probably in wide private usage anyway.:)  Thanks for helping me sort out the confusion. My new question then, is, why have that stipulation? If $f$ *doesn't* converge to zero, then the series automatically diverges, yes, but the Integral Test would still be applicable (if we insisted to use it), so isn't the stipulation unnecessarily restrictive of the theorem's sphere of applicability?
Comment: I.e. my original question  in the title still stands: Does the integral test **require** the integrand to converge to zero to be *applicable*?
Comment: @Ryan If the integrand doesn't converge to zero, you already know the sequence diverges, so why bother applying the test?
Comment: @Ryan The theorem is perfect as it stands. The stipulation that $f\to 0$ *is needed*, since else the theorem *wouldn't be true*. Note that if $f$ didn't tend to $0$; the hypothesis that $\int_1^n f$ is bounded would be utterly impossible, for instance. On the other hand, the "divergence" criterion in this theorem is a "finer" test than $a_n\not\to 0$. We get past that, i.e. assume it is true, and show that even if that is true, the $f$ failing to be integrable is all we need to show divergence.
Comment: "Note that if f didn't tend to 0; the hypothesis that ∫n1f is bounded would be utterly impossible" Which is precisely why the theorem (*minus* the stipulation that $f$ converges to zero) (correctly) implies that such a series is divergent! So how is the theorem untrue in this regard?
Comment: @Ryan But that part of the theorem asserts convergence, not divergence! Read carefully. The theorem enunciates that $a_n\to 0$ because it is part of its hypothesis. The first part, which asserts convergence needs this (because else it would make no sense) and the second part which asserts divergence assumes this because else divergence would already be true, and one wouldn't need the theorem at all.
Comment: If $f$ did $not$ converge to zero, then Part (a)'s hypthesis is false, so its conclusion doesn't hold. At the same time, part (b)'s hypothesis would be true, so its conclusion (that the series diverges) is true.  In short, the Integral Test *does* apply even when $f$ does not converge to zero! (Though we wouldn't need to use the integral test since the "non-null test" already immediately tells us that the series diverges. But this is beside the point.)
Answer: This may help: Note that the convergence test states that IF a series converges, THEN the limit of $f(n)$/"the integrand" is $zero$.
The converse does not necessarily follow.
That is, if the $\lim_{n\to \infty} f(n) = 0,\;$ we cannot conclude that the series converges. We don't know. Recall the example of $f(n) = \large\frac 1n.\;$ It's limit as $n\to \infty$ is $0$, but the series $\sum_{n^\infty} f(n)$ does not converge.
It's cases like this when the integral test comes in handy.
Indeed, the condition that $\lim_{n \to \infty} f(n) = 0$ must be met for the integral test to apply.


Save and storage inside a App directory

Question: I used this code to take two images and merge in only one IMG so save inside in my camera roll, and working very well!
But how can save the same img inside the app?
Like a App/Document Directory
Here the code:
- (IBAction)onSavePhoto:(id)sender{

    UIImage *bottomImage = self.imageViewPick.image;
    UIImage *image       = self.scelta.image;

    CGSize newSize = CGSizeMake(640, 640);
    UIGraphicsBeginImageContext( newSize );

    [bottomImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];

    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height) blendMode:kCGBlendModeNormal alpha:1.0];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil);

    [self.navigationController popViewControllerAnimated:YES];

}

Answer: Try with this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *docs = [paths objectAtIndex:0];
NSString* path =  [docs stringByAppendingFormat:@"/myImage.jpg"];

NSData* imageData = [NSData dataWithData:UIImageJPEGRepresentation(newImage, 80)];
NSError *writeError = nil;
[imageData writeToFile:path options:NSDataWritingAtomic error:&writeError];

If writeError is still nil after it, everything went fine, if not, it will contain the error.
Answer: There is no App/Document folder and instead you should write into the folder returned from:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

Save and storage inside a App directory


Can't Repair Mysql Table

Question: I have one ARCHIVE table that I simply can't repair, I already try to remove the partitioning but still get this error:
alter table promo_tool_view_44 REMOVE PARTITIONING;
ERROR 1034 (HY000): Incorrect key file for table 'promo_tool_view_44'; try to repair it

I already try to repair the table but I get this reply:
repair table promo_tool_view_1;
+-----------------------------+--------+----------+-----------------------------+
| Table                       | Op     | Msg_type | Msg_text                    |
+-----------------------------+--------+----------+-----------------------------+
| vad_stats.promo_tool_view_1 | repair | error    | Partition p1 returned error |
| vad_stats.promo_tool_view_1 | repair | error    | Corrupt                     |
+-----------------------------+--------+----------+-----------------------------+

2 rows in set (0.21 sec)

How can I solve this?
Thanks,
Pedro
Comment: For ARCHIVE tables the only way I found to fix was to overwrite the table files, from one of the slave servers. But please guys if anyone as one solution for that please help us, to prevent future disasters!
Answer: If you have not done it yet: Shut down your DB and back it up. Repair operations are dangerous.
Sad to say, I would strongly recommend a backup tape. Something is obviously broken in partition p1. But there are some tricks that might get your data back.
myisamchk implements lots of stuff not found in the cli. Try
myisamchk --safe-recover
myisamchk --recover

in that order and see if you have any more luck. There are plenty of flags that can help you. The full documentation can be found at
http://dev.mysql.com/doc/refman/5.5/en/myisamchk.html
The full documentation for repair in the cli can be found at http://dev.mysql.com/doc/refman/5.5/en/repair-table.html
Once you are done repairing you should track down why you got the DB corrupted in the first place. That's is not normal for MySQL databases.
Comment: Thanks, but I can't use myisamchk because the tables are not MyIsam are in ARCHIVE
Comment: Then you are pretty much out of luck. Backups are a nice thing. You could also monitor this bug report which seems to be related http://bugs.mysql.com/bug.php?id=46565
Comment: I have buckups in several slaves, I was able to restore info, but it will be nice to know one way to restore ARCHIVE tables after corruption.
Answer: For ARCHIVE tables the only way I found to fix was to overwrite the table files, from one of the slave servers. But please guys if anyone as one solution for that please help us, to prevent future disasters

Can't Repair Mysql Table


Prove $(V_1 \cap V_2)^{\perp_L} = V_1^{\perp_L} + V_2^{\perp_L}$ if $f$ is non-degenerate

Question: Let $f(\alpha, \beta)$ be a bilinear form on the $n$-dimensional linear space $V$ over the number field $F$. Prove, if $f(\alpha, \beta)$ is non-degenerate, for any subspaces $V_1$ and $V_2$ of $V$,
then
\begin{align*}
& (V_1 \cap V_2)^{\perp_L} = V_1^{\perp_L} + V_2^{\perp_L}, \\
& (V_1 \cap V_2)^{\perp_R} = V_1^{\perp_R} + V_2^{\perp_R}.
\end{align*}
where for any subspace $W$ of $V$, the left orthogonal group $W^{\perp_L}$ and the right orthogonal group $W^{\perp_R}$ are defined by
\begin{align*}
& W^{\perp_L} = \{\alpha \in V: f(\alpha, \beta) = 0, \forall \beta \in W\}, \\
& W^{\perp_R} = \{\beta \in V: f(\alpha, \beta) = 0, \forall \alpha \in W\}.
\end{align*}
By definition, I am able to show (in this direction, non-degeneracy of $f$ is not needed) that $V_1^{\perp_L} + V_2^{\perp_L} \subseteq (V_1 \cap V_2)^{\perp_L}$. I don't have much thoughts on the other direction, in particular, how the non-degeneracy of $f$ should be applied?
Answer: $\newcommand{\lbot}{\perp_L}$
$\newcommand{\rbot}{\perp_R}$
We first prove by definition that
\begin{align*}
& (V_1 + V_2)^{\lbot} = V_1^{\lbot} \cap V_2^{\lbot}; \tag{1} \\
& (V_1 + V_2)^{\rbot} = V_1^{\rbot} \cap V_2^{\rbot}. \tag{2}
\end{align*}
Let $\alpha \in (V_1 + V_2)^{\lbot}$, then for any $\beta_1 \in V_1, \beta_2 \in V_2$, we have
\begin{align*}
& f(\alpha, \beta_1 + \beta_2) = f(\alpha, \beta_1) + f(\alpha, \beta_2) = 0, \\
& f(\alpha, \beta_1 - \beta_2) = f(\alpha, \beta_1) - f(\alpha, \beta_2) = 0.
\end{align*}
Hence $f(\alpha, \beta_1) = f(\alpha, \beta_2) = 0$, i.e., $\alpha \in V_1^{\lbot} \cap V_2^{\lbot}$. Conversely, if $\alpha \in V_1^{\lbot} \cap V_2^{\lbot}$, then for any $\beta = \beta_1 + \beta_2 \in V_1 + V_2$, where $\beta_1 \in V_1, \beta_2 \in V_2$, we have
$$f(\alpha, \beta_1 + \beta_2) = f(\alpha, \beta_1) + f(\alpha, \beta_2) = 0 + 0 = 0,$$
i.e., $\alpha \in (V_1 + V_2)^{\lbot}$. The second equality can be proved similarly.
If $f(\alpha, \beta)$ is non-degenerate, we show that for any subspace $W$ of $V$, $W = (W^{\lbot})^{\rbot}$. By definition, $W \subset (W^{\lbot})^{\rbot}$. To show the other direction, it can be shown by $f$ is non-degenerate that for any subspace $W$,
$$\dim(W^{\lbot}) = \dim(W^{\rbot}) = \dim(V) - \dim(W).$$
It then follows that
\begin{align*}
\dim((W^{\lbot})^{\rbot}) = \dim(V) - \dim(W^{\lbot}) = \dim(V) - (\dim(V) - \dim(W)) = \dim(W). \tag{*}
\end{align*}
This equality and $W \subset (W^{\lbot})^{\rbot}$ imply that $W = (W^{\lbot})^{\rbot}$. Similarly, $W = (W^{\rbot})^{\lbot}$.
Now by $(1)$ and $(2)$, we have
\begin{align*}
(V_1 \cap V_2)^{\lbot} = ((V_1^{\lbot})^{\rbot} \cap (V_2^{\lbot})^{\rbot})^{\lbot} = ((V_1^{\lbot} + V_2^{\lbot})^{\rbot})^{\lbot} = V_1^{\lbot} + V_2^{\lbot}.
\end{align*}
This completes the proof.
(The equality $(*)$ can be established by constructing a map between $W^{\lbot}$ to the solution space of the first $\dim(W)$ columns of the matrix $(f(\alpha_i, \alpha_j))$.)


confirn in link on overlay lists

Question: I create in administration list of some content and create link delete. On link delete I add attribute
onclick="return confirm('Are you sure?);"

but when you click "cancel" on confirm block drupal still go to link href:
http://www.supermarket.hr/#overlay=admin/categories/delete/6939/0

How can I anticipate some hidden overlay functions that ignore added confirm?
thx
Comment: you want the confirm for delete or cancel ? drupal usually asks anyway again if you try to delete content.
Comment: I create table list with that link and add to it onclick option, but when you click on link on the overlay it still open href.
Comment: can you show some src pls
Answer: Some code:
$option_delete = array(
        'attributes' => array(
            'onclick' => "return confirm('Delete order?');",
            'class' => "delete"
        )
    );

link:
l('delete', 'admin/orders/categories/'.$node->id.'/'.$page, $option_delete),

this link is showing up in list on administration overlay.
Comment: Found answer here: http://drupal.stackexchange.com/a/36518/6520 interesting :)
Comment: so default was prevented ..

confirn in link on overlay lists


drag multiple DIV in a same time without Click or Ctrl Click

Question: I'm stack of this case.
Can anybody help me please?
I want to drag multiple item/DIV in a same time without Clicking/Control Click the item I want to drag.
That meant, by default, the items I want to drag is already "selected" when my page is loaded.
I want something like this this , I tried it in my local server but it's not working for me.
<code>$(document).ready(function () {
    var selectedClass = 'ui-state-highlight';

    var $draggableElems = $("#draggable div").draggable({
        start: function (e, ui) {
            if (e.target.id == "start") $draggableElems.addClass(selectedClass);
            else return false;
        },
        stop: function (e, ui) {
            // reset group positions
            $('.' + selectedClass).css({
                top: 0,
                left: 0
            });
        },
        drag: function (e, ui) {
            if (e.target.id == "start") {
                // this works because the position is relative to the starting position
                $('.' + selectedClass).css({
                    top: ui.position.top,
                    left: ui.position.left
                });
            }
        }
    });

    $("#droppable").droppable({
        drop: function (e, ui) {
            var $selectedElems = $('.' + selectedClass).remove().clone();
            $selectedElems.appendTo($(this)).add(ui.draggable) // ui.draggable is appended by the script, so add it after
            .removeClass(selectedClass).css({
                top: 0,
                left: 0
            });
        }
    });
});
</code>
i ll appreciate if somebody can help me
Thanks a lot!
Comment: so what's the problem? the jsFiddle example works fine after including jQuery UI libraries. http://jsfiddle.net/MmWbH/1/
Comment: tks arie. i am the beginner with jquery drag. the problem is which jquery version will used for this code. i add this
 in my top code. but its not working
Comment: You also need to include the jQuery UI library after jQuery, you need the Draggable & Droppable plugin to enable drag and drop. Check the official site of [jQuery UI](http://jqueryui.com/)
Comment: Try to search more information [here](http://jqueryui.com/).
Comment: tks for the info, its working now. but i need to customize that all. - how to make it all dragged only in horizontal mode. forget about droppable. and i want to modify the position, i meant box 1, box 2 box 3 is separated, and when i want to drag the position is still separated
Comment: I meant, something like this. http://jsfiddle.net/delfi/eCEU3/1/ but the problem is when i drag all 3 boxes the position changed. i want  all the boxes  will follow the location  when it first loaded.
Answer: You forgot the jQuery UI library, on jsfiddle you just need to check the checkbox that says jQuery UI 1.8.18
<code><script type="text/javascript" src"js/jquery_ui_1.8.18"></script>
</code>
http://jsfiddle.net/MmWbH/2/
Comment: I meant, something like this. http://jsfiddle.net/delfi/eCEU3/1/ but the problem is when i drag all 3 boxes the position changed. i want  all the boxes  will follow the location  when it first loaded.
Comment: Do you mean that it works well for the same code on the jsfiddle, but not working on your server?
Do you see any errors in the console?


Removing all punctuation from a list and return the entire list in Python

Question: I have a list that I'm trying to strip all punctuation and the character "·" from and then returning that list without any of the above. However, when I try to return the list, only the first word of the list appears and I'm not sure where I went wrong with this.
Here is the list I'm trying to strip punctuation from:
['in·vis·i·ble', 'in·vis·i·bil·i·ty, ', 'in·vis·i·ble·ness, ', 'in·vis·i·bly, ', 'qua·si-in·vis·i·ble, ', 'qua·si-in·vis·i·bly, ', 'inˌvisiˈbility, ', 'inˈvisibleness, ', 'inˈvisibly, ']
Here's what I'm getting: ['invisible']
Here is a portion of my code (it's part of a larger function)
syl = []
for words in span:
    if words not in syl:
        syl.append(words)
for text in syl:
    drop_sep = re.sub(r'·', '', text)
    return drop_sep

Comment: If you put a return in a loop, the loop runs only once obviously.
Comment: What is `·`? Is it a period?
Comment: It's a separator used to separate syllables. It's used on dictionary.com
Answer: Use a list comprehension where each element of the resulting list is a string with all occurrences of dot substring '·' replaced by the void '':
[word.replace('·', '') for word in words]

Example
>>> words = ['in·vis·i·ble',
...          'in·vis·i·bil·i·ty, ',
...          'in·vis·i·ble·ness, ',
...          'in·vis·i·bly, ',
...          'qua·si-in·vis·i·ble, ',
...          'qua·si-in·vis·i·bly, ',
...          'inˌvisiˈbility, ',
...          'inˈvisibleness, ',
...          'inˈvisibly, ']
>>>
>>> from pprint import pprint
>>> pprint([word.replace('·', '') for word in words])
['invisible',
 'invisibility, ',
 'invisibleness, ',
 'invisibly, ',
 'quasi-invisible, ',
 'quasi-invisibly, ',
 'inˌvisiˈbility, ',
 'inˈvisibleness, ',
 'inˈvisibly, ']

Comment: He wants to keep the dash
Comment: Thank you so much!


Selecionar registro mais recente de determinada tabela - PostgreSQL

Question: Preciso selecionar o registro mais recente de minha Estoque caso a coluna data seja diferente, consegui da seguinte forma trazer o mais antigo quando as datas são diferentes:
SELECT codigosuprimento, numeroserie, max(data)
FROM public.estoque where usado = '1' and numeroserie = '1201607048733'
group by codigosuprimento, numeroserie;

Porém quando a coluna data for igual quero que ele traga todos os registros que as datas sejam iguais, por exemplo:

Traria as duas linha já que as datas são iguais, mas quando for assim:

Iria trazer o da data 2017-08-18 por ser a mais atual.
Answer: Uma solução pode ser um subselect com MAX
SELECT codigosuprimento, numeroserie, data
FROM public.estoque p1----faz uma primeira instancia da tabela
where usado = '1'
and numeroserie = '1201607048733'
-- este subselect procura a maior data da mesma chave do registro
and data = (SELECT max(data)
            --faz uma segunda instancia da tabela
            --renomeia o "alaias" para diferenciar
            FROM public.estoque p2
            where p2.usado       = p1.usado
            and   p2.numeroserie = p1.numeroserie)

Comment: roda o seguinte comando: `CREATE INDEX estoque_data_idx ON public.estoque
  USING btree (data DESC);` ele vai indexar a coluna para agilizar a pesquisa. Veja o tempo de retorno da consulta em ambos os casos e posta aí o resultado
Comment: Deu certo :) Poderia só me explicar como funcionou seu `select`? Assim que liberar já marco como correta a resposta
Comment: Só uma questão, tentei executar esse comando sem a restrição de um numero de serie definido e ficou carregando e me retornou algo depois de algum tempo processando, na questão de processamento tu saberia algo que consumisse menos quem sabe?
Comment: @RovannLinhalis Tem uns 10.000 registros mais ou menos, a questão de índice na tabela data como assim índice?
Comment: @RovannLinhalis depois de criar o `index` o tempo de resposta foi mais rápido mesmo, demorou um pouco ainda mas menos do que antes, obrigado
Comment: Só uma questão referente a isso, caso eu queira deletar os dados que possuem datas inferiores ao invés de só trazer os mais atuais como poderia fazer isso?
Comment: @R.Santos aí você tem que ver, vai precisar desse registro ainda ? é inútil ? apaga. Mas pensando por esse lado, talvez o certo fosse atualizar a data e não apagar um registro e inserir outro com os mesmos dados. Não entendi qual o proposito de uma tabela de estoque com esses dados, mas ok.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/67942/discussion-between-r-santos-and-rovann-linhalis).
Comment: Sem a restrição de número de séria se cai quase com certeza em um "full table scan".


Setting httpd to be accessible through network

Question: I have set up my httpd and it's running. My problem is when I access my ip to another pc (my ip 192.168.1.234), I get only a response something like Not Avaible. did I miss something? when it its os was ubuntu, it was working fine
Comment: Are you using Fedora Server, Fedora Workstation, or something else?
Answer: 2 possibilities:

Check the binding address of the htttpd.conf, if it is pointing to 127.0.0.1, this restricts access only via localhost. You can change to 0.0.0.0 to bind on all addresses.
Check your iptables for possible firewall restrictions. This very common problem in desktop general use linux, like openSUSE.


# of seating arrangement in a 6 seat car

Question: I'm getting hung up on a probability question:
A car has six seats including the driver's, which must be occupied by a driver. In how many ways is it possible to seat 4 people if all 4 can drive.
for one possible way you can choose the driver first and then choose seat options per person left so that would look like:
$$4*5*4*3$$
what I keep getting hung up on is when I try to determine seat options
so the first seat has 4 options since all 4 people can drive and it must be chosen.
seat 2: I think should be 4, 3 people can choose it or it can be left empty
seat 3: should be 3, 3 people can choose it if the seat 2 isn't chosen, or 2 people can choose it if seat 2 is chosen, or it can be left empty
seat 4: 5 possibilities; if seat 2 isn't chosen and seat 3 isn't chosen then 3 people can choose this, or if seat 2 is chosen and seat 3 isn't chosen then 2 people can choose it, or if seat 2 and 3 are chosen then 1 person can choose this seat, or if seat 2 isn't chosen and seat 3 is chosen then 2 can choose it, or it can be left empty
seat 5:  no clue
seat 6: no clue
this is a lot of text and should be easier (I think) but this is the process my mind is taking.
any help would be greatly appreciated.
Comment: You could also think of this as first choosing the 3 seats besides the driver's, which can be done in $\binom{5}{3}=10$ ways.  Now you just have to arrange the 4 people in their 4 seats, which can be done in $4!$ ways, so you get $10\cdot4!$.
Comment: Here's another way to think about it. We can permute the $4$ people among the $6$ seats in $_6P_4$ ways. But now we need to remove all the permutations which don't have a person in seat position 1, since we need an assigned driver. But this is just $_5P_4$. So we have ${_6}P_4 - {_5}P_4 = 240$ ways of wanted seating arrangements.
Answer: Your first way of counting is perfectly good.
If you want to count another way, let us invent $2$ identical ghosts. The seats for them can be chosen in $\binom{5}{2}$ ways, since ghosts aren't allowed to drive. (There  is a problem with taking their picture for the licence.) The rest of the seats can be filled in $4!$ ways.
Comment: I understand that approach but what I wanted to know is if there was an alternative approach to getting the same answer. like possibilities per seat, not per person.
Comment: There is, but it is far messier. You can construct a tree and count the number of nodes.
Comment: @Arkamis that is exactly how I am trying to figure it out.
Comment: Just draw a picture. Start at the top, that's Seat 1. There are five possibilities: A, B, C, D, nobody. Draw a line representing each possibility. Repeat for seat 2. Repeat until all possibilities are enumerated. You'll soon find that this method is horrible.
Comment: We shouldn't discriminate against ghosts.
Answer: There are three parts to this.  There's always a driver and all 4 can drive so whatever the combination in the other 5 seats, you are going to multiply that combination by 4 to represent the 4 different sets of people who could be in the other seats.
Next, you have three people to fill five seats.  You will want to determine the number of combinations of filled seats and the order of the 3 people as separate factors.  If seats 1 & 2 are always occupied, you have 3 combinations.  If seats 1 & 3 are always occupied, you have 2 new additional combinations. If seats 1 & 4 are occupied, there is 1 new combination.  So if seat 1 is always occupied, there are 6 combinations.  Now, if seat 1 is always vacant, you are distributing through seats 2 through 5.  Same method of counting shows 3 new combinations with seat 1 vacant and seat 2 occupied. Finally, if you vacate seats 1 & 2, you have one new combination.  So, that's 10 combinations of occupied seats.  Then there is the order of each person sitting for any particular combination of occupied seats. That's a simple 3x2. So 4 (driver sets) x 10 (seating combinations) x 6 (order of people) = 240 combinations.
Now, we want more mathematical eloquence than just counting the five seat positions.  If we were dealing with a genome instead of a 6 passenger car, counting wouldn't be very practical.  To count the combination of occupied seats, I did that counting occupied seats.  I could have counted vacant combinations. If seat 1 is vacant there are 4 combinations for the other vacant seat. If seat 2 is always vacant there are 3 new combinations, seat 3 vacant adds 2 new combinations and seat 4 one new combination.  That still adds up to 10, but it is still not eloquent.  If we are using Google sheets, we could use combin(5,2) to get the number of combinations, so what is the math behind combin?  See, https://corporatefinanceinstitute.com/resources/excel/functions/combin-function/ for the actual formula.
Please point out my errors and be critical of the answer.  I'm old and have forgotten a lot.


Use an image for a header border bottom

Question: I want to use an image for the bottom border of an image. The image used for the border bottom is 400px for example, however I don't want it to display a 400px bottom border for headings the are only short, I want it to auto-scale.
Is there a way to display only the amount required for individual headings rather than having to make up lots of image sizes for multiple heading widths.
Thank you for any help in advance...
Comment: Not quite understanding the question, you only provide one dimension for your picture and you worded it quite confusingly.
Comment: will the border be a static height? can you just use a single pixel width and repeat it across the bottom?
Answer: You can use the CSS3 border-image property.
For instance
DIV {
  border: double orange 1em;
  border-image: url("border.png") 27 round stretch;
 }

You can stretch or repeat as necessary.
Read more here: http://www.w3.org/TR/css3-background/#border-images
If looks as if you could also slice the image
And more here: http://www.w3.org/TR/css3-background/#border-image-slice
Comment: @user699872 - if you provided the image (preferably) and/or the code you have so far, we can fiddle with it.

Use an image for a header border bottom


Why angularjs html template request does not show in browser in top sites?

Question: I have referred following link https://wappalyzer.com/applications/angularjs to know which sites may use which programming tool to developing an application. I debug HTTP requests log in firebug and it does not show an HTML request in firebug.
There are so many sites which may use angularjs but there is one strange thing I noticed. When I show loading panel in firebug it does not load an HTML explicitly in an application means I am not able to see any HTML request in an application. While I am also developing an application in MEAN stack. It shows HTML request in firebug in browser whether I include an HTML template by ng-include or directive.
So can I know how could it possible to hide html request or is there any other way to manage templating in AngularJS?
Answer: Because they use angular factory <code>$templateCache</code> see https://docs.angularjs.org/api/ng/service/$templateCache

$templateCache is angular's build in key-value store for the template
  contents. When fetching a template declared by a remote url through
  ng-include or templateUrl, angular looks for it first in the
  $templateCache and if the template is found there it doesn't perform
  the http request.
Comment: @sahil: Thank you.. but at least first time when page loads it may seem html request log in firebug but it does not
Comment: yes first time it makes html request and then it doesn't
Comment: yes sure , I am referring it and once my issue will resolve I shall definitely give you positive wait.
Comment: you may check this post it gives a good material on $templateCache http://pracujlabs.io/2015/12/28/using-templatecache-in-angularjs.html


Onclick function on checkbox still functioning even if it's replaced with other function by javascript

Question: I'm planning to let the user when clicked on one of the radio button A, and B:
A - will allow the user to check the checbox with the javascript replaced the onclick function checkRequired(), where the function will remove the "required" from the input once its checked.
B - will only allow the user check only 1 checkbox with the function of checkOne(), replaced the function checkRequired()
The problem is I don't understand why the javascript keeps on using the checkOne() function, even if I've checked the entire code and syntax, even the developer tool from Google Chrome browser DID SHOW THE FUNCTION HAS BEEN REPLACED BY checkRequired() ONCE THE RADIO BUTTON A IS CHECKED. Logically speaking IT SHOULD WORKING WELL, BUT for some reason it's not working at all.
function checkRequired() {
        var n = $( "input:checkbox:checked" ).length;
        var requiredCheckboxes = $(':checkbox[required]');
        var chkboxes = $(':checkbox');
        if(n < 1) {
            chkboxes.attr('required', 'required');
        } else {
            requiredCheckboxes.removeAttr('required');
        }
    }

function checkOne() {
        $('.regid-chkbox').on('change', function() {
           $('.regid-chkbox').not(this).prop('checked', false);
        });
    }

function editMeal() {
        var editBrand = document.getElementById("radio-edit-meal-brand");
        var editInfo = document.getElementById("radio-edit-meal-info");

        if (editBrand.checked){
            $('.regid-chkbox').removeAttr('onclick');
            $('.regid-chkbox').attr('onclick', 'checkRequired();');
        } else if (editInfo.checked) {
            /* Making the checkbox only one can be checked */
            $('.regid-chkbox').removeAttr('onclick');
            $('.regid-chkbox').attr('onclick', 'checkOne();');
        }
    }

HTML Codes:

      <form method="POST" action="">

          Enter your information to verify and edit the meal.

 Click here to Upload

            <input type="file" onchange="preview_image(event)" style="display: none;" name="bran-img" id="bran-image-reg">

                Edit Categories*
                 EDIT MEAL\'S BRAND
                  <input required type="radio" checked="checked" value="0" id="radio-edit-meal-brand" name="meal-edit" onclick="editMeal()">

                 EDIT MEAL\'S INFO
                  <input required type="radio" value="1" id="radio-edit-meal-info" name="meal-edit" onclick="editMeal()">

                Account Code*
                <input class="string optional" name="enable-acccode" maxlength="8" minlength="8" id="user-account-code-res" placeholder="Account Code" type="password" size="8" />

                Password *
                <input class="string optional first-pw" name="enable-pw" maxlength="255" id="user-pw-res" onkeyup="check_verlist_res();" placeholder="Password" type="password" size="50" />

                Repeat password *
                <input class="string optional" name="enable-pw-repeat" maxlength="255" id="user-pw-repeat-res" onkeyup="check_verlist_res();" placeholder="Repeat password" type="password" size="50" />
                SHOW

                BRAND *
                <select class="role-select" id="brand-type-meal" name="meal-edit-brand" style="width:30vw; height:4vh;">
                  <option value="" selected disabled>BRAND</option>

                  ';
                    $BRANDTYPE = "SELECT * FROM meal_brand WHERE active = 1";
                    $result = $con->query($BRANDTYPE);
                    if ($result->num_rows > 0) {
                      while ($row = $result->fetch_assoc()) {
                        echo '
                        <option value="'.$row["brand_id"].'">' .$row["brand_name"]. '</option>
                        ';
                      }
                    }
                echo
                '</select>

                Meal Name *
                <input class="string optional meal-name" name="meal-name-edit" maxlength="255" id="meal-name-edit" placeholder="Meal Name"/>

                Meal Default Quantity *
                <input class="string optional meal-quantity" type="number" min="1" step="1" onkeypress="validate(event)" name="meal-quantity-edit" id="meal-quantity-edit" placeholder="00"/>

                BRAND *
                <select class="role-select" id="brand-type-meal-info" name="meal-edit-info-brand" style="width:30vw; height:4vh;">
                  <option value="" selected disabled>BRAND</option>

                  ';
                    $BRANDTYPE = "SELECT * FROM meal_brand WHERE active = 1";
                    $result = $con->query($BRANDTYPE);
                    if ($result->num_rows > 0) {
                      while ($row = $result->fetch_assoc()) {
                        echo '
                        <option value="'.$row["brand_id"].'">' .$row["brand_name"]. '</option>
                        ';
                      }
                    }
                echo
                '</select>

                Meal Price *
                <input class="string optional meal-price" type="number" step="0.25" min="1" onkeypress="validate(event)" name="meal-price-edit" id="meal-price-edit" placeholder="RM 0.00"/>

                Meal Details*
                <textarea style="height:20vh!important;width:68vw!important" class="string optional meal-details" type="textarea" name="meal-details-edit" id="meal-details-edit" placeholder="Meal Details" /></textarea>

              <input disabled class="sumbit" name="submit-list-edit-meal" style="font-family:oswald!important;" type="submit" id="submit-res" value="Confirm Edit" />

              By editing the brand, you are here and agree our Terms & Conditions

The expected result should be working under these condition, but for some reason it's not working even if the developer tool from Chrome shown the function already been replaced.
Answer: EDIT 2:
I have found the problem. In checkOne you set the onChange event and we never unset it. That's why the check stays even when you switch radio buttons.
Try:
function editMeal() {
    var editBrand = document.getElementById("radio-edit-meal-brand");
    var editInfo = document.getElementById("radio-edit-meal-info");

    if (editBrand.checked){
        $('.regid-chkbox').off('click');
        $('.regid-chkbox').off('change');
        $('.regid-chkbox').on('click', checkRequired);
    } else if (editInfo.checked) {
        /* Making the checkbox only one can be checked */
        $('.regid-chkbox').off('click');
        $('.regid-chkbox').off('change');
        $('.regid-chkbox').on('click', checkOne);
    }
}

EDIT:
I made a quick mock-up code snippet and that seems to work the way you desired. Is there any other place you are modifying event handlers that can cause your issue?

function checkRequired() {
    console.log('Check required');
}

function checkOne() {
    console.log('check one');
}

function editMeal() {
      var editBrand = document.getElementById("radio-edit-meal-brand");
      var editInfo = document.getElementById("radio-edit-meal-info");
      if (editBrand.checked){
          $('.regid-checkbox').off('click');
          $('.regid-checkbox').on('click', checkRequired);
      } else if (editInfo.checked) {
          /* Making the checkbox only one can be checked */
          $('.regid-checkbox').off('click');
          $('.regid-checkbox').on('click', checkOne);
      }
}

$(document).ready(() => {
  $('input[type="radio"]').on('change', editMeal);
});

<form>
  <input type="radio" id="radio-edit-meal-brand" name="edit-meal">Check Required
  <input type="radio" id="radio-edit-meal-info" name="edit-meal">Check One

  <input type="checkbox" class="regid-checkbox">
</form>

Original:
Maybe using event handler syntax instead of setting the attr onclick?
function editMeal() {
    var editBrand = document.getElementById("radio-edit-meal-brand");
    var editInfo = document.getElementById("radio-edit-meal-info");

    if (editBrand.checked){
        $('.regid-chkbox').off('click');
        $('.regid-chkbox').on('click', checkRequired);
    } else if (editInfo.checked) {
        /* Making the checkbox only one can be checked */
        $('.regid-chkbox').off('click');
        $('.regid-chkbox').on('click', checkOne);
    }
}

Comment: Tried, it still using the checkOne() function.
Comment: Okay, I realized that this odd scenario will occurred once the function has been replaced to checkOne() and if you checked the checkbox at least once, otherwise if the function replaced with checkOne() and you didnt check any checkbox yet, the javascript seems wont use the checkOne() function, but the checkRequired() when it's replaced with checkRequired() function.
Comment: @MEMYSELF I think I found the issue, please let me know if updated (Edit 2) change fixes the issue
Answer: Your code should work if you correct the attribute to be .attr('onClick') instead of .attr('onclick'). This is case sensitive.
Although, as kht pointed out it may make more sense to just use the on('click') function instead.
Comment: Tried, it still using the checkOne() function. >_<
Comment: Will you add the HTML?
Comment: Preferably the related
Comment: It contains some PHP code, I hope you wouldn't mind that.

Edited in the post.
Comment: Can you put the HTML after it's been processed by PHP?
Comment: It's kinda long tho because the PHP calls out quite some of the records from the database. Edited in the post.
Comment: Nevermind, its too dam long, heres the link to the related codes.

https://codeshare.io/5wxLBR
Comment: Just search for the keyword "radio-edit-meal-brand" then you will saw the related codes with the question
Answer: Similar to the answer kht posted, even the original unmodified Javascript OP posted works as expected.

function checkRequired() {
  console.log('checkRequired');
  var n = $("input:checkbox:checked").length;
  var requiredCheckboxes = $(':checkbox[required]');
  var chkboxes = $(':checkbox');
  if (n < 1) {
    chkboxes.attr('required', 'required');
  } else {
    requiredCheckboxes.removeAttr('required');
  }
}

function checkOne() {
  console.log('checkOne');
  $('.regid-chkbox').on('change', function() {
    $('.regid-chkbox').not(this).prop('checked', false);
  });
}

function editMeal() {
  var editBrand = document.getElementById("radio-edit-meal-brand");
  var editInfo = document.getElementById("radio-edit-meal-info");

  if (editBrand.checked) {
    $('.regid-chkbox').removeAttr('onclick');
    $('.regid-chkbox').attr('onclick', 'checkRequired();');
  } else if (editInfo.checked) {
    /* Making the checkbox only one can be checked */
    $('.regid-chkbox').removeAttr('onclick');
    $('.regid-chkbox').attr('onclick', 'checkOne();');
  }
}

$(document).ready(() => {
  $('input[type="radio"]').on('change', editMeal);
});

<form>
  <input type="radio" id="radio-edit-meal-brand" name="edit-meal">Check Required
  <input type="radio" id="radio-edit-meal-info" name="edit-meal">Check One

  <input type="checkbox" class="regid-chkbox" />
</form>


Effect of Caratheodory criterion on a subset of a measurable set

Question: I met with a multiple choice question,
Q. Let $E\subset M \subset \Bbb R^n$, where $M$ is a measurable (Lebesgue) set with $m(M)<\infty, $ then $E$ is measurable if
($m^*$ denotes the Lebesgue outer measure)

$m(M)=m^*(E)+m^*(M\backslash E)$.

$m(M)=m^*(E)+m^*(M\cap E)$.

$m(M)=m^*(E)+m^*(M \triangle E)$, $\triangle$ denotes the symmetric difference.

$m(M)=m^*(E)+m^*(M\cap E^c)$.

Caratheodory criterion says '$E$ is measurable if and only if $m^*(A)=m^*(A \cap E)+m^*(A \cap E^c)$ for all $A \subseteq \Bbb R^n$'. Thus, here I can see the measurability of $E$ implies the statements of First, Third and Fourth options (which are exactly the same). But how can we make a necessary and sufficient statement using the condition 'being a subset of a measurable set $M$'?
Answer: I'll do the proof for $1$.
I'll denote set difference by "$-$" for easier typing.
There exists a $G_{\delta}$ set $G$ such that $M-E\subset G $ and $m^{*}(M-E)=m(G)$ (I am assuming you know that Borel sets are measurable).
Then $M-E\subset M\cap G\subset G$ and hence $m^{*}(M-E)\leq m(M\cap G)\leq m(G) = m^{*}(M-E)\implies m^{*}(M-E)=m(M\cap G)$ .
As $M\cap G$ is measurable we have by Caratheodory cut condition on $M\cup G$ with $M$
$M\cap(M\cap G)= M\cup G$ and $M\cap(M\cap G)^{c}=M-G$
So $m(M)=m(M\cup G)+m(M-G)=m^{*}(M-E)+m(M-G)$ .
Now $m^*(M-E)=m(G)$ and  we have the following claim that if $E$ is measurable and $F$ is any set then $m^{*}(E\cup F)+m^{*}(E\cap F)=m(E)+m^{*}(F)$ (You can prove this by using Cut condition on $E\cup F$ and $ F$ and is a standard result if you already know it. It is widely used in probability) . Now using this result for $E\subset F$ and $F-E$ to get $m^{*}(E\cup(F-E))+m^{*}(E\cap(F-E))=m^{*}(F)+m^{*}(\emptyset)=m(E)+m^{*}(F-E)$
Hence we have for $E$ measurable and $E\subset F$ that $m^{*}(F)=m(E)+m^{*}(F-E)$
Thus we can apply this to have $m(M)-m^{*}(M-E)=m^{*}(E)$ and this would mean $m^{*}(E)=m(M-G)$
Thus we have a measurable set $M-G$ whose measure equals the outer measure of $E$ and $m^{*}(E)<\infty$ .
This means that $m^{*}(E-(M-G))=m^{*}(E)-m^{*}(M-G)=0$ and hence $E-(M-G)$ is of measure $0$ and hence measurable.
This means $E=(E-(M-G))\cup (M-G)$ is measurable.
Comment: We are merely using the assumptions. We have $m^{*}(M-E)=m(G)$ . And $m(M)-m^{*}(M-E)=m(E)$. Hence So $m(M)-m(G)=m^{*}(E)$ and hence $m(M-G)=m^{*}(E)$
Comment: Now $M-G$ is a measurable set and as I said in the claim that if $E$ is measurable(and of finite measure) and $F$ is ANY set then $m^*(F-E)+m(E)=m^{*}(F)$.
Comment: The equation $m^{*}(E-(M-G))=m^{*}(E)-m^{*}(M-G)=0$ is not well clear for me. How can we justify the additivity of $m^*$ on the sets $E-(M-G)$ and $M-G$ using the measurability of $M-G$?
Comment: Thanks a lot Sir
Comment: @Mr.GandalfSauron Can we say some thing about option (1) whenever $m(A)$ is not finite.


Using CORS and Fetch API to return Authenticated Cookie from another domain

Question: I am trying to get the background on a login button that is on the navigation of my WordPress site I work on to change based on if someone is logged into their account on another website that doesn't share a domain. I reached out to the guys who work on the other site and they have set CORS up on there end and I have set it up on my WordPress site too. I am using the Fetch API to retrieve the Authenticated Cookie that is generated when someone is logged in and the cookie appears in the cookie list on my WordPress website through the Chrome devtools but when I try to return the value within my JavaScript code, the cookie appear to not be detected. The code I am using is below.
// Replace with the URL of the other website you want to access cookies from
const otherWebsiteUrl = 'www.othersite.com';

// Replace with the name of the cookie you want to access
const cookieName = 'Authenticated';

async function getCookieValue() {
  // Wrap the code that contains the `await` keyword in an async function
  const response = await (async () => {
    const response = await fetch(otherWebsiteUrl, {
      method: 'GET',
      mode: 'cors',
      credentials: 'include',
    });

    if (response.ok) {
      const responseText = await response.text();
      const parsedCookies = responseText.split(';');

      for (const cookie of parsedCookies) {
        const [name, value] = cookie.split('=');
        if (name.trim() === cookieName) {
          return value;
        }
      }
    }

    return null;
  })();

  return response;
}

// Wrap the code that uses the `cookieValue` variable in an async function
async function setLoginButtonBackgroundColor() {
  const cookieValue = await getCookieValue();

  if (cookieValue) {
    document.querySelector('#loginBTN').computedStyleMap.backgroundColor = '#d9d9d9';
  }
}

setLoginButtonBackgroundColor();

const cookieValue = document.cookie.split(';').find(cookie => cookie.includes('Authenticated'));

if (cookieValue) {
  // The cookie exists
  console.log("Authenticated Cookie Exists");
} else {
  // The cookie does not exist
  console.log("Authenticated Cookie Doesn't Exist");
}

I have tried asking the other engineers on the other team but they don't seem to know how to get it to work.
I have tried just getting the value of the cookie back but it doesn't appear in the console. Only place I can see the Authenticated cookie is within the list of cookies under the application tab within the dev tools, so that should mean that the CORS and Fetch API is working right? It has to be my code.
Answer: Client-side JavaScript has access (through document.cookie) to same-origin cookies. It has no access to cross-origin cookies.
Using credentials: 'include' will allow an Ajax request to send cross-origin cookies and for a cross-origin response's Set-Cookie header to set cookies for that origin.
This is handled transparently. There is no way for client-side JS to access the value of those cookies. It can only make requests to which they are automatically attached.
You are using await response.text(). This will return the response body as a string. Cookies are set using the Set-Cookie header, not the body.
To read headers, you can generally use the headers object but Set-Cookie is a forbidden response header so it will not work for that particular one.
It is possible for the URL you are making the request to to return a copy of the cookie data in the request body, but you've given not indication that it does.
Comment: Thanks for the information, not sure I am closer to understanding what it going on but I will read up on the links you provided. Just want to ask though, even though I am not planning to change the Authenticated cookie, just want to see if it is there, would I still need to use set-cookie in order for the cookie within the code to have a value?


TKinter image background comes out a different color

Question: When my images are displayed, they all have a green background. When I open the original photos, the background is white. I'm using PIL.ImageTk.PhotoImage() as I know you are supposed to with .png files. but I'm unsure why this is happening.
from tkinter import *
from tkinter import font
from turtle import color
from webbrowser import *
import PIL.Image
import PIL.ImageTk

lastClickX = 0
lastClickY = 0

class App(Tk):
  def __init__(self):
    super().__init__()

    self.configure(bg= '#65737e')
    self.geometry("450x500")
    #self.overrideredirect(True)
    self.attributes('-topmost', True)
    self.resizable(False, True)
    self.bind('<Button-1>', self.SaveLastClickPos)
    self.bind('<B1-Motion>', self.Dragging)
    self.print_game()

  def SaveLastClickPos(self, event):
      global lastClickX, lastClickY
      lastClickX = event.x
      lastClickY = event.y

  def Dragging(self, event):
    x, y = event.x - lastClickX + self.winfo_x(), event.y - lastClickY + \
    self.winfo_y()
    self.geometry("+%s+%s" % (x, y))

  def print_game(self):
    im = PIL.Image.open('./Logos/Celtics.png')
    resized = im.resize((100, 100))
    celtics = PIL.ImageTk.PhotoImage(resized)

    label = Label(self, image = celtics, borderwidth=0, highlightbackground='#65737e' ,bg='#65737e')
    label.photo = celtics
    label.grid(row= 0, column = 0, padx= 20, pady= 10, sticky=W)

    frame = Frame(self, bg='#65737e')

    text = Label(frame, font=("Pacifico", 22, 'bold'), text="VS", highlightbackground='#65737e', bg='#65737e')
    text.grid()

    time = Label(frame, text="7:00pm EST", highlightbackground='#65737e', bg='#65737e')
    time.grid()

    frame.grid(row= 0, column= 1, padx=50)

    im = PIL.Image.open('./Logos/Bulls.png')
    resized = im.resize((100, 100))
    bulls = PIL.ImageTk.PhotoImage(resized)

    #team_2 = Label(root, image=bulls, borderwidth=0, highlightbackground='#65737e', bg='#65737e')
    team_2 = Label(self, image=bulls, borderwidth=0)
    team_2.photo = bulls
    team_2.grid(column=2, row=0, padx = 20, pady= 10, sticky = W)

if __name__ == "__main__":
  app = App()
  app.mainloop()

Could this have to do with resizing, or maybe one of the imported libraries? Or does it have something to do with the png files themselves?
Link to the photos I used: https://www.stickpng.com/cat/sports/basketball/nba-teams?page=1
Comment: It has transparent background and you may see color of your widget.
Comment: if you would reduce code to single Label with single image then we could test it on our coumputers - maybe it is problem only on some systems (Windows, Linux, Mac)
Comment: If you print the information of the image, i.e. `print(im)`, you will see that it is a mode "P" image (8-bit color image).  I think you need to convert it to "RGBA" mode in order to let Pillow module to handle the transparency correctly.
Comment: Is this something easy to do in python or would you suggest just converting all my images separately?
Comment: looks like you need to use canvas instead of label. Read it [here](https://stackoverflow.com/questions/56554692/unable-to-put-transparent-png-over-a-normal-image-python-tkinter)
Comment: Try `im = PIL.Image.open(...).convert("RGBA")`.
Answer: I believe the issue is that transparent backgrounds will only work on canvas widget. I also noticed when reading the image, it's mode is 'P' (or at least when I ran it), and it needs to be 'RGBA'. So what I did was I left most of what you had, but added/changed a few things.

I open the image, convert to RGBA, resized, then saved that new image.
Then can PhotoImage on the new resized image
Utilized the canvas widget as opposed to the label.
Changed the im variable to a instance variable because local variable will be destroyed after the function exits

Code:
from tkinter import *
from tkinter import font
from turtle import color
from webbrowser import *
import PIL.Image
import PIL.ImageTk

lastClickX = 0
lastClickY = 0

class App(Tk):
  def __init__(self):
    super().__init__()

    self.configure(bg= '#65737e')
    self.geometry("450x500")
    #self.overrideredirect(True)
    self.attributes('-topmost', True)
    self.resizable(False, True)
    self.bind('<Button-1>', self.SaveLastClickPos)
    self.bind('<B1-Motion>', self.Dragging)
    self.print_game()

  def SaveLastClickPos(self, event):
      global lastClickX, lastClickY
      lastClickX = event.x
      lastClickY = event.y

  def Dragging(self, event):
    x, y = event.x - lastClickX + self.winfo_x(), event.y - lastClickY + \
    self.winfo_y()
    self.geometry("+%s+%s" % (x, y))

  def print_game(self):
    frameAway = Frame(self, bg='#65737e')
    canvasAway = Canvas(frameAway, bg="#65737e", width=100, height=100, highlightthickness=0)
    canvasAway.grid()

    imAway = PIL.Image.open('./Logos/Celtics.png').convert('RGBA')
    imAway = imAway.resize((100, 100), PIL.Image.ANTIALIAS)

    imAway.save('./Logos/Celtics_resize.png')

    self.imAway = PhotoImage(file='./Logos/Celtics_resize.png')
    canvasAway.create_image(50, 50, image=self.imAway)
    frameAway.grid(row= 0, column = 0, padx= 20, pady= 10, sticky=W)

    frame = Frame(self, bg='#65737e')

    text = Label(frame, font=("Pacifico", 22, 'bold'), text="VS", highlightbackground='#65737e', bg='#65737e')
    text.grid()

    time = Label(frame, text="7:00pm EST", highlightbackground='#65737e', bg='#65737e')
    time.grid()

    frame.grid(row= 0, column= 1, padx=50)

    frameHome = Frame(self, bg='#65737e')
    canvasHome = Canvas(frameHome, bg="#65737e", width=100, height=100, highlightthickness=0)
    canvasHome.grid()

    imHome = PIL.Image.open('./Logos/Bulls.png').convert('RGBA')
    imHome = imHome.resize((100, 100), PIL.Image.ANTIALIAS)

    imHome.save('./Logos/Bulls_resize.png')

    self.imHome = PhotoImage(file='./Logos/Bulls_resize.png')
    canvasHome.create_image(50, 50, image=self.imHome)
    frameHome.grid(row= 0, column = 2, padx= 20, pady= 10, sticky=W)

if __name__ == "__main__":
  app = App()
  app.mainloop()

Output:


PreviewMouseLeftButtonDown event occasionally fires when touching outside the control

Question: I have a WPF TextBox with a PreviewMouseLeftButtonDown event handler running on a laptop with a touch screen.
When I touch the TextBox the event handler fires as expected. However, if I then touch somewhere else in the application the event will fire after 8 or 9 touches. It seems that .NET thinks the control has been directly touched even though the touch is not on top of the TextBox control. From what I can tell, the sender and mouse event args of the event handler don't show any identifiable difference between legitimate TextBox touches and the 9th touch outside the control.
This can easily be reproduced in a standalone application (see code and steps below):

Touch the TextBox once. A new window should open to show the event fired.
Close the window created by the event handler
Touch anywhere in the application window that is NOT the TextBox 9 times.
A window should open again which means the event fired.

public MainWindow()
{
    InitializeComponent();
    MyTextBox.PreviewMouseLeftButtonDown += MyTextBox_PreviewMouseLeftButtonDown;
}

private void MyTextBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var win = new Window();
    win.ShowDialog();
}

Is there any explanation for why a touch outside of a control can sometimes trigger a control's mouse event in .NET?
Is there a workaround for this issue so that both touch and mouse can be supported without false positive event triggers?
Answer: Figured out the solution after more searching.
This is a known bug (see https://github.com/dotnet/wpf/issues/2491).
The workaround is to execute the ShowDialog() code within a Dispatcher.BeginInvoke() call in the event handler.
The theory behind what might be happening is that changing focus to a new window during the event handler causes the control to continue thinking it's in a "touch down" state. When a subsequent touch is made WPF thinks it's the "second finger" of a multi touch operation and creates another handler. It does this until all "ten fingers" have been pressed. After that, it cycles back to the first handler. Since the control still thinks it's being touched it will fire when your "first finger" touches anywhere on the application.
This explains why the event triggers consistently after 9 touches outside the text box and why invoking the ShowDialog after the event handler finishes fixes the problem.


Global beforeAll in Jest?

Question: I need to simulate different window sizes in my tests using React Testing Library and Jest.
Currently I'm having to have this beforeAll in every test file:
import matchMediaPolyfill from 'mq-polyfill';

beforeAll(() => {
  matchMediaPolyfill(window)
  window.resizeTo = function resizeTo(width, height) {
    Object.assign(this, {
      innerWidth: width,
      innerHeight: height,
      outerWidth: width,
      outerHeight: height,
    }).dispatchEvent(new this.Event('resize'))
  }
})

Which I use like so:
it('does something at small screen sizes', async () => {
  window.resizeTo(320, 800);
  // actual test here

Can I have a global beforeAll that will apply to every test file in my project?
The docs mention globalsetup:
https://jestjs.io/docs/en/configuration#globalsetup-string
However it errors as it doenst recognise the beforeAll function. I seemed to me that that option is meant for setting up an environment but not adding something to the test files?
Answer: globalSetup runs in another process and cannot access beforeAll or other variables from test scope. It's meant for initializations made before any test is started, e.g. setting up a server, like the documentation shows.
It's setupFiles that runs in test process. beforeAll should be executed after Jest environment is initialized, so it should be moved to setupFilesAfterEnv.
Comment: No, it's globalSetup, there's an example for that in docs
Comment: if i just want to initialize the database once for all tests, it setupFilesAfterEnv still the place to put ? Doc says "In other words, setupFilesAfterEnv modules are meant for code which is repeating in each test file."

Global beforeAll in Jest?


How to delete \ from a text?

Question: I need to delete \ from a text. For instance, if the input is as below:
if the executive\\'s employment terminates due to disability, the executive will receive payment majority of the directors then in office.\', \'5% of the amount paid to the executive pursuant to (i)(c) above), (v)
How can I delete \\ from \\'s and \ from \'? I tried to do some ways but they don't work.
q4 = re.sub(r'\*','',q3)

Comment: Are you sure your text actually has backslashes in it? More likely, you're confusing the `repr` representation with the actual string contents. Try `print`ing it and see what happens.
Comment: (Even if it turns out your string does have backslashes in it, you'll need to learn about what backslashes in a string literal mean, because your regex attempt isn't escaping the backslash.)
Comment: I tried using PRint and it still shows \. I just want to delete it from the text so that the text is easier to read. Thanks.
Answer: nobackslashes = withbackslashes.replace('\\', '')

You don't need anything as sophisticated as regexes; ordinary string replacement works fine. The important thing is to escape the backslash; in a string literal, a backslash represents the start of an escape sequence, generally used to put untypeable characters into a string. Two backslashes is the escape sequence for a literal backslash character.
Once you do this, if you still see backslashes, you're probably displaying the string in a way that adds an extra layer of escaping. For example, if you make a file with the contents
O'Connor says, "Hi."

and view the contents in an interactive interpreter session:
>>> with open('asdf.txt') as f:
...     text = f.read()
...
>>> text
'O\'Connor says, "Hi."'

you'll see a backslash, because Python is showing you a string literal that would produce a string with the same contents, rather than printing the string's characters directly. On the other hand, if you use print:
>>> print text
O'Connor says, "Hi."

that doesn't happen.

How to delete \ from a text?


Is the distribution of this random variable normal?

Question: Suppose that there're two independent random variables X and Y, both of which are normal. X has parameters N(-1, 1) while Y has parameters N(1, 1).
And for the third random variable Z, its value is equal to either X or Y, with both probabilities as 50%. Is Z normally distributed? If it is what is its variances?
Comment: Related: https://stats.stackexchange.com/questions/16608/what-is-the-variance-of-the-weighted-mixture-of-two-gaussians/16609#16609.  For more similar questions, please search our site: https://stats.stackexchange.com/search?tab=votes&q=mixture%20moment.
Comment: You could plot the density function of $Z$ at several points, e.g., $-3, -2.9, -2.8, ..., 3$ to get an idea of what it looks like.  This would provide you with a lot of information!
Comment: @whuber Thank you! For my question, can RV Z be expressed as Z = 0.5X + 0.5Y? For all "weighted mixtures" Z, can they be expressed as Z = X*Px + Y*Py?
Comment: @jbowman Thank you jbowman! I did plot that with R and it was normal. But I want a mathematical prove. The link above is helpful.
Comment: @Glen_b The wikipedia page solved my last confusion. Thank you Glen_b!
Answer: The random variable $Z$ is NOT $0.5X + 0.5Y$.
The expression $0.5X + 0.5Y$ describes averaging the values of $X$ and $Y$, not choosing one of them with probability $\frac12$.
With mixtures, it is instead the density (and cdf) that are averaged:
$$f_Z(z) = 0.5 f_X(z) + 0.5 f_Y(z)\,.$$
See Wikipedia's page on mixture distributions for basic information on this. (For means $\mu_i$ and sd's $\sigma_i$ with probability weights $w_i$, it gives the variance of the mixture as $\sum _{i=1}^n w_i((\mu _i-\mu )^2+\sigma_i^2)$ (where $\mu$ is the mean of the mixture). The results for mean and variance there are pretty easy to show.
If you plot the density of Z correctly you will see that it is not normal.
Comment: This one only has one mode but a larger separation in means (ceteris paribus) will be bimodal.
Comment: @MichaelChernick I simulated this, and it looks normal (granted, I did it once, but with n = 1000): https://gist.github.com/markhwhiteii/201c6bafbec5d54e5081535508bc9c8e If it looks normal, is it still normal, even if we know it comes from a mixture of two similar distributions? Is that too theoretical? If it looks normal, I would say, "It is a normal distribution", but strictly speaking, it is not... since, by definition, it is a mixture.
Comment: @MarkWhite I will draw the density so that you can see how it compares to a normal.
Comment: @Mark It's there now; you can see it's noticeably different.
Comment: @Weiwen This distribution is unimodal, not bimodal.  Modes refer to properties of the distribution, not to how it is expressed.  So although this one is constructed from two distributions that have two separate modes, it nevertheless is unimodal.  You can verify this by finding the zeros of the derivative of its density, which is a positive multiple of $x+1+e^{2x}(x-1)$: it has a unique zero at $x=0$. Whether approximating it with a Normal distribution is "acceptable" will depend on the application.
Comment: Distributions like this have two modes.
Comment: @Glen_b +1, thanks. And I assume the peak is a plateau because it is spreading out evenly across the two means, -1 and 1? And the further away from one another they are, the more bimodal it becomes?
Comment: Imagine we put the centers of the two components at $\pm k$. When $k=0$ you of course have a standard normal. In the neighborhood of the peak the each component is  approximately quadratic, so when you have $k\approx\epsilon$ for some small $\epsilon$ the average of the densities will also be approximately quadratic near the center, but as you move them further apart that become flatter and flatter. Now at 1sd from the mean the normal curve is approximately linear (second derivative is 0 there) and, combined with symmetry tells us that when we get $k=1$ the average of the densities ...ctd
Comment: ctd... will be flat at the center; We can check that it's still actually unimodal by looking at the behaviour of the second derivative. But as soon as $k>1$ it dips down in the center giving a bimodal mixture. We're right at the dividing line between bimodal and unimodal. As $k$ grows further the modes become more distinct and separate.
Comment: @MarkWhite I simulated and plotted this, and it doesn't quite look normal; you can see the rather flat spot at the top if you overlay a normal density function over the histogram. IMO, because we were told the density function, there's no point debating if it's unimodal or bimodal. We know it's bimodal. Maybe a better question is: if we encountered this in practice, without knowing the density function, how would we treat it? A single normal density would probably be acceptable.


Reporting the relationship between variables: correlation or regression?

Question: I'm doing my dissertation in Accounting and I developed a questionnaire to test certain hypotheses on the relationship between independent variables and a dependent variable. All were measured on a 5-point Likert scale. I am using SPSS to analyse the data. The variables are all non-normal (I used Kolmogorov-Smirnov test) and so I will be using Spearman correlation to test the relationships.
I was wondering whether this is enough? Should I use some form of regression as well? And if I do, do I still include the Spearman results? Do studies usually include both?
I have not studied any statistics so this is quite new to me.
Answer: This can't be answered by us, only by you. But I can give you the information you need to make the decision.
In correlation (whether Spearman or Pearson) we are looking at the relationship between two variables. Neither is dependent or independent - they are treated equally.
In regression (of any sort) one variable is the dependent variable and one or more are independent. The measurement of the dependent variable is critical. If it was measured on a 5 point Likert scale, then you  probably need ordinal logistic regression.
Which to choose? Since you say you have a dependent variable, that indicates regression. But if you are new to statistics you might not be able to run and interpret an ordinal logistic regression, so you might have to hire a consultant.
Comment: If I decide to carry out a regression, would I still report the Spearman correlation results? Is it appropriate to have both n a study? Furthermore, if the results are statistically significant in the Spearman test but they are not in the regression, what does that mean exactly? Thank you for help, it is greatly appreciated.
Comment: It might be correct and it might not; it depends on what you want to find out. Substance drives statistics, not the other way 'round.
Answer: To report the relashionship between variables, you may prefer a scatterplot. As part of the Royal Society of Chemistry's Analytical Methods Committee, Prof Brian Ripley used to write short expository notes for ANALYST. The note entitle "Uses (Proper and Improper) of Correlation Coefficients", which appeared in ANALYST, SEPTEMBER 1988, VOL. 113 1469, is pertinent to your questions. In particular, the abstract says:
<code>The statistical concept of a correlation coefficient r is frequently misused in
interpreting analytical data. In particular, a large value of r does not indicate a
linear relationship between two measurements; this is demonstrated graphically. For many
of the problems for which a correlation coefficient is used it would be better to
present a scatterplot.
</code>
While the most useful summary of the relationship between the x and y measurements
is often a scatterplot, many would like a more objective measure of linearity than
visual inspection of a scatterplot. This raises at least two questions: What is the
proper use of a correlation coefficient? and How do we assess linearity?, both of
which are addressed in Ripley's report.


Disable click on last column in each row

Question: I am using bootstrap table. currently when you click on columns you get an alert. What I want is when you click on last column nothing will happen. Will appreciate your help.

$('#students tbody').on('click', 'tr.details-control', function() {
   alert('click');
 });
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  1
  2
  ....
  Last

    First
    Second
    ......
    No Alert

    First
    Second
    ......
    No Alert

Comment: `$('#students tbody').on('click', 'tr.details-control:not(:last)', function() {
 alert('click');
 });`
Comment: When I click on first row I am getting alert, on second not..
Comment: So what you want?
Comment: I dont want alert in all last columns in each row.
Comment: You don't need to append _solved_ to the title. By accepting an answer others will see that the question is solved. Thank you.
Answer: Add this:
$('td:last-child').click(function( event ) {
  event.preventDefault();
});

Answer: You can add the event to the td element like that:
$('#students tbody').on('click', 'tr.details-control td:not(:last)', function() {
    alert('click');
});

Answer: Need to use :not() with :last-child selectors like below:-
$('#students tbody').on('click', 'tr.details-control td:not(:last-child)', function() {
  alert('click');
});

Working example:-

$('#students tbody').on('click', 'tr.details-control td:not(:last-child)', function() {
  alert('click');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  1
  2
  ....
  Last

    First
    Second
    ......
    No Alert

    First
    Second
    ......
    No Alert

Comment: @ShyamShingadiya  glad to help you :):)
Comment: Eventually I was targeting only `tr`, hence the issue occurs.
Answer:

$(function(){
 $('table').on('click','td:not(:last-child)',function(){
 alert('hi')
 })
})
<!DOCTYPE html>

<title>Page Title</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  1
  2
  ....
  Last

    First
    Second
    ......
    No Alert

    First
    Second
    ......
    No Alert

Comment: A short explanation of how you have corrected the answer would be more appreciable.
Answer: You can use
$('#students tr.details-control').click(function(e) {
    if($(this).context.rowIndex == $('#students tr').length -1){
        e.preventDefault();
    }else
        alert('click');
 });


Copiar dados de uma tabela para outra sem precisar digitar campo a campo

Question: Alguém sabe o comando SQL que copio os dados de uma tabela para outra tabela, sem precisar explicitar todos os campos da tabela original? Eu sei que existe uma maneira mas me esqueci como faz e não consegui encontrar na net, se alguém souber, ficaria muito grato se pudesse compartilhar aqui comigo, desde já agradeço a atenção. #SQL
Comment: @rray SQL Server
Comment: para qual banco de dados você esta tentando fazer?
Comment: @PabloVargas SQL
Comment: SQL Server? MySQL? noSQL?
Answer: Você pode fazer de 3 formas.
-- sql tabela volátil só existira em tempo de execução
declare @HIERARQUIA table
(
    [ID_HIERARQUIA] [int]  NOT NULL,
    [MICRO] [int] NOT NULL,
    [DESCR] [varchar](250) NOT NULL,
    [MACRO] [int] NULL,
    [POSICAO] [varchar](250) NOT NULL
)

-- 1ª
-- copia para tabela temporaria ...  ficar no banco tempdb até que finalize o execução.
select * into #HIERARQUIA from HIERARQUIA ;

-- 2ª
-- copia para tabela volátil só existira em tempo de execução
insert into @HIERARQUIA
select * from #HIERARQUIA;

-- 3ª
-- copia para uma tabela da base de dados
insert into HIERARQUIA
select * from HIERARQUIA ;

Resumindo. Você vai precisar criar uma tabela com os mesmo campos ou utilizar uma temporária e usa o * no Select , isso faz o mapeamento dos seus campos para uma outra tabela automaticamente.
Answer: Consegui resolver usando SELECT * INTO, agradeço a todos pela atenção.
Answer: No SQL Server e em outros banco pode usar o select into(com algumas diferenças de sintaxe)
SELECT * INTO nova_tabela FROM outra_tabela

Inserting Rows by Using SELECT INTO


Salt Stack - Best way to get schedule output

Question: I'm using saltstack on my servers. I did a simple schedule:
job1:
  schedule.present:
    - function: state.apply
    - seconds: 1800
    - splay: 5

Now I want to get the output of the schedule back on my master
(or on my minion but I just like to know the best way)
I don't really know how to use salt mine or returners or what is best preferred for my needs.
thank you :)
Comment: I guess you already read [the docs](https://docs.saltstack.com/en/latest/topics/jobs/). Which way to pick depends on your use case. If you decide to tell us about your needs we might give you advice :)
Answer: Job data return and job metadata
By default, data about jobs runs from the Salt scheduler is returned to the master.
It can therefore be useful to include specific data to differentiate a job from other jobs. By using the metadata parameter a value can be associated with a scheduled job, although these metadata values aren't used in the execution of the job they can be used to search for specific job later.
job1:
  schedule.present:
    - function: state.apply
    - seconds: 1800
    - splay: 5
    - metadata:
        foo: bar

An example job search on the salt-master might look similar to this:
salt-run jobs.list_jobs search_metadata='{"foo": "bar"}'

Take a look at the salt.runners.jobs documentation for more examples.
Scheduler with returner
The schedule.present function includes a parameter to set a returner to use to return the results of the scheduled job. You could for example use the pushover returner:
job1:
  schedule.present:
    - function: state.apply
    - seconds: 1800
    - splay: 5
    - returner: pushover

Take a look at the returners documentation for a full list of of builtin returners and usage information.


Unknown indication below upper stave

Question: The number 2, quite large and in italics, appears twice below the notes on the upper stave.
There are some fingering indicators but one quarter the size.
The time signature is 6/8
Comment: @Grace - please do not answer in a comment.
Comment: Alright @DoktorMayhem, I only had a sentence as an answer, which I thought wouldn't be enough for an answer. But thanks for letting me know.
Answer: That is a duplet. It works like a triplet, but instead of playing three notes in the time of two, you play these two in the time of three.
Another way to write this is by using dotted eights. But for example in 6/8 time, it's preferred to use duplets. It helps signifying how foreign the rhythm is in relation to the time signature you're in.
Answer: The dotted minim/half in the lower stave shows that 6 quavers/eights fit. So the "2" means "2 in the time of 3". It indicates an irregular group of notes; usually a higher number of notes have to be played in the time of a lower number, and thus quicker than notated; here we have the less usual situation where a lower number (2) have to be played in the time of a higher number (3), and thus slower than notated.
You can tell numbers that indicate irregular groups from fingerings: the former are italic.
Comment: ... and the fingering would be adjacent to the note or note-heads, I think, not halfway along the beam.

Unknown indication below upper stave


What is the most general form of the Navier-Stokes equation?

Question: From a mathematical standpoint, what is the most general form of the Navier-Stokes tensor equation? I'm looking at this from an abstract perspective, so the equations need not be limited to the standard domain of $\mathbb{R}\times\mathbb{R}^3$. I've also seen references to a form for compressible flow as well as one for incompressible flow. Is one more general than the other, or are they separate entities? If there is a single over-arching equation that describes all possible special cases of the Navier-Stokes equation, what is it?
Answer: First of all, some assumption: the first one is that a fluid is treated as a continuum, that is not made unto discrete particles but rather a continuous substance.
Another assumption: all the fields of interest like pressure, velocity, density, temperature and so on are differentiable, weakly at least.
The equations are derived from the basic principles of conservation of mass, momentum, and energy. For that matter, sometimes it is necessary to consider a finite arbitrary volume, called a control volume, over which these principles can be applied.
We start with the so called material derivative
Changes in properties of a moving fluid can be measured in two different ways. One can measure a given property by either carrying out the measurement on a fixed point in space as particles of the fluid pass by, or by following a parcel of fluid along its streamline. The derivative of a field with respect to a fixed position in space is called the Eulerian derivative while the derivative following a moving parcel is called the convective or material derivative.
It's defined as
$$\frac{D}{Dt} =! \frac{\partial}{\partial t} + v\cdot \nabla$$
where $v$ is the velocity of the fluid.
The first term on the right-hand side of the equation is the ordinary Eulerian derivative (i.e. the derivative on a fixed reference frame, representing changes at a point with respect to time) whereas the second term represents changes of a quantity with respect to position. This "special" derivative is in fact the ordinary derivative of a function of many variables along a path following the fluid motion; it may be derived through application of the chain rule.
For example, the measurement of changes in wind velocity in the atmosphere can be obtained with the help of an anemometer in a weather station or by mounting it on a weather balloon. The anemometer in the first case is measuring the velocity of all the moving particles passing through a fixed point in space, whereas in the second case the instrument is measuring changes in velocity as it moves with the fluid.
Now we need some conservation laws in particular for mass, momentum and energy.
This is done via the Reynolds transport theorem, an integral relation stating that the sum of the changes of some extensive property defined over a control volume $\Omega$ must be equal to what is lost (or gained) through the boundaries of the volume plus what is created/consumed by sources and sinks inside the control volume. This is expressed by the following integral equation:
$$\frac{d}{dt}\int_{\Omega} L\ \text{d}V = -\int_{\partial\Omega} Lv\cdot n\ \text{d}A - \int_{\Omega} Q\ \text{d}V$$
Where $L$ is a set of extensive properties as written above, $Q$ represents the sources and sinks in the fluid.
A straightforward application of the divergence theorem and Leibniz rule lead us to this conclusion:
$$\frac{\partial L}{\partial t}  + \nabla\cdot (Lv) + Q = 0$$
From this valuable relation (a very generic continuity equation), three important concepts may be concisely written: conservation of mass, conservation of momentum, and conservation of energy. Validity is retained if   is a vector, in which case the vector-vector product in the second term will be a dyad.
Conservation of Momentum
The most elemental form of the Navier–Stokes equations is obtained when the conservation relation is applied to momentum. Writing momentum as $\rho v$ gives:
$$\frac{\partial \rho v}{\partial t}  + \nabla\cdot (\rho v v) + Q = 0$$
Where $v v$ is what we called before a dyad: a special case of tensor product, which results in a second rank tensor; the divergence of a second rank tensor is again a vector (also called: a first rank tensor). Noting that a body force (notated $b$) is a source or sink of momentum (per volume) and expanding the derivatives completely:
$$v\frac{\partial\rho}{\partial t} + \rho \frac{\partial v}{\partial t} + v v \cdot \nabla\rho + \rho v\cdot \nabla v = b$$
Note that the gradient of a vector is a special case of the covariant derivative, the operation results in second rank tensors; except in Cartesian coordinates, it's important to understand that this isn't simply an element by element gradient. Rearranging and recognizing that:
$$v \cdot \nabla\rho + \rho v\cdot \nabla v = \nabla\cdot(\rho v)$$
With an easy calculation we can show that we can rewrite the general formulation above as
$$v\left(\frac{\partial\rho}{\partial t} + \nabla\cdot(\rho v)\right) + \rho\left(\frac{\partial v}{\partial t} + v\cdot\nabla v\right) = b$$
The leftmost expression enclosed in parentheses is, by mass continuity (shown in a moment), equal to zero. Noting that what remains on the left side of the equation is the convective derivative:
$$\rho\left(\frac{\partial v}{\partial t} + v\cdot\nabla v\right) = b ~~~~~ \to ~~~~~ \rho\frac{Dv}{Dt} = b$$
Conservation of mass
Mass may be considered also. Taking $Q = 0$  (no sources or sinks of mass) and putting in density:
$$\frac{\partial\rho}{\partial t} + \nabla\cdot(\rho v) = 0$$
where $\rho$ is the mass density (per volume).This equation is called the
mass continuity equation, or simply "the" continuity equation. This equation generally accompanies the Navier–Stokes equation.
In case of an incompressible fluid, $\rho = $ constant and so we gain
$$\nabla\cdot v = 0$$
GENERAL FORM
The generic body force $b$  seen previously is made specific first by breaking it up into two new terms, one to describe forces resulting from stresses and one for "other" forces such as gravity. By examining the forces acting on a small cube in a fluid, it may be shown that
$$\rho \frac{Dv}{Dt} = \nabla\cdot\sigma + f$$
Where $\sigma$ is the stress tensor and $f$ accounts the body force present.
This equation is called the Cauchy momentum equation and describes the non-relativistic momentum conservation of any continuum that conserves mass.   $\sigma$ is a rank two symmetric tensor given by its covariant components:
$$\sigma_{ik} =
\begin{pmatrix}
\sigma_{xx} & \tau_{xy} & \tau_{xz} \\
\tau_{yx} & \sigma_{yy} & \tau_{yz} \\
\tau_{zx} & \tau_{zy} & \tau_{zz}
\end{pmatrix}
$$
$\sigma$ are the normal stresses and $\tau$ are the shear stresses.
The tensor can be split up to two terms like
$$\sigma_{ij} = -p\mathbb{1} + \mathbb{T}$$
where $T$ is the deviator stress components, $1$ is the identity matrix and
$$p = -\frac{1}{3}(\sigma_{xx} + \sigma_{yy} + \sigma_{zz})$$
The motivation for doing this is that pressure is typically a variable of interest, and also this simplifies application to specific fluid families later on since the rightmost tensor $\mathbb{T}$ in the equation above must be zero for a fluid at rest. Note that  $\mathbb{T}$ is traceless. The Navier–Stokes equation may now be written in the most general form:
$$\boxed{\rho\frac{Dv}{Dt} = -\nabla p + \nabla\cdot\mathbb{T} + f}$$
This equation is still incomplete. For completion, one must make hypotheses on the form of $\mathbb{T}$  , that is, one needs a constitutive law for the stress tensor which can be obtained for specific fluid families; additionally, if the flow is assumed compressible an equation of state will be required, which will likely further require a conservation of energy formulation.


Nexus 5 can't connect to peripheral device

Question: I have built an android app that can connect to a peripheral device by bluetooth(Classic Bluetooth) using BluetoothSocket.connect() and do some interaction with it. The app works well on Samsung Galaxy S3(4.3) and Note 3(4.3), but when on Nexus 5, the app can't connect to the device.
I have 2 Nexus 5, and both of them can't connect, what make me think there must be something  wrong with Nexus 5, not me. But when I use the app supported by the manufacturer of the device to connect to the device, the connection always can be established, even using Nexus 5.
So I guess, there must be something wrong with Nexus 5 on classic bluetooth, what make it not very easy to establish a connection, and there might be some way to solve it.
Sorry for my poor English.Thanks for any pointers on how to solve this problem.
Here are 3 blocks of my logcat info:
logcat info of Samsung Galaxy S3(worked):
04-01 17:03:33.340 D/BloodPressureService﹕ connect to: 8C:DE:52:2C:68:6D
04-01 17:03:33.360 D/BluetoothUtils﹕ isSocketAllowedBySecurityPolicy start : device null
04-01 17:03:33.360 W/BluetoothAdapter﹕ getBluetoothService() called with no BluetoothManagerCallback
04-01 17:03:33.360 D/BloodPressureService﹕ setState() 0 -> 1
04-01 17:03:33.365 I/BloodPressureMonitorFragment﹕ MESSAGE_STATE_CHANGE: 1
04-01 17:03:35.095 D/BloodPressureService﹕ connected
04-01 17:03:35.095 D/BloodPressureService$ConnectedThread﹕ create ConnectedThread
04-01 17:03:35.105 I/BloodPressureService$ConnectedThread﹕ BEGIN mConnectedThread
04-01 17:03:35.110 D/BloodPressureService﹕ setState() 1 -> 2
04-01 17:03:35.125 I/BloodPressureMonitorFragment﹕ MESSAGE_STATE_CHANGE: 2

logcat info of Nexus 5 at the first time(worked.Don't know why, I never seen that before. But just one time):
04-01 17:14:37.577 D/BloodPressureService﹕ connect to: 8C:DE:52:2C:68:6D
04-01 17:14:37.577 D/BloodPressureService﹕ setState() 0 -> 1
04-01 17:14:37.577 I/BloodPressureMonitorFragment﹕ MESSAGE_STATE_CHANGE: 1
04-01 17:14:37.587 W/BluetoothAdapter﹕ getBluetoothService() called with no BluetoothManagerCallback
04-01 17:14:37.587 D/BluetoothSocket﹕ connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[47]}
04-01 17:14:39.207 D/BloodPressureService﹕ connected
04-01 17:14:39.207 D/BloodPressureService$ConnectedThread﹕ create ConnectedThread
04-01 17:14:39.207 D/BloodPressureService﹕ setState() 1 -> 2
04-01 17:14:39.207 I/BloodPressureService$ConnectedThread﹕ BEGIN mConnectedThread
04-01 17:14:39.217 I/BloodPressureMonitorFragment﹕ MESSAGE_STATE_CHANGE: 2

logcat info of Nexus 5 at the 2nd time(didn't work. And never work again):
04-01 17:14:59.977 D/BloodPressureService﹕ connect to: 8C:DE:52:2C:68:6D
04-01 17:14:59.977 D/BloodPressureService﹕ setState() 0 -> 1
04-01 17:14:59.977 I/BloodPressureMonitorFragment﹕ MESSAGE_STATE_CHANGE: 1
04-01 17:14:59.977 W/BluetoothAdapter﹕ getBluetoothService() called with no BluetoothManagerCallback
04-01 17:14:59.987 D/BluetoothSocket﹕ connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[56]}

Comment: This question is not related to programming.
Comment: Add some logcat output when you try and use `BluetoothSocket.connect`. Otherwise, your question is probably going to be closed.
Comment: Also worth considering that this is a known issue https://code.google.com/p/android/issues/detail?id=41415
Comment: Odd the question was closed with "general computing hardware and software". You got a re-open vote because the reason was wrong and there is logcat to help identify the issue.
Answer: There is some changes in the Bluetooth Stack with Nexus 5, it is the most annoying thing ever. When you open the socket you could try using an insecure socket and see if that helps. Also make sure all existing sockets are closed and null:-
adapter= BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = adapter.getRemoteDevice(mAddress);
BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(UUID);
socket.connect();

At this point you should try and retrieve the output streams:-
 out = socket.getOutputStream();
 in = socket.getInputStream();

Also make sure you fully close the socket:-
        if (in != null) {
            in.close();
            in = null;
        }
        if (out != null) {
            out.close();
            out = null;
        }
        if (socket != null) {
            socket.close();
            socket = null;
        }

Comment: Taken your advice, and did some optimization in my code. Now my Nexus 5 can connect the device sometimes-but only sometimes. Anyway, thanks.
Comment: I found making sure I fully closed the Bluetooth socket also helped. (added to answer)


Docker: Unable to execute RUN command after ADD when starting from scratch

Question: I'm trying to build a custom Linux Alpine docker for ARM architecture starting from the "scratch" image. I don't understand why I can't execute any RUN command after I execute ADD. This is my Dockerfile:
FROM scratch
ADD rootfs.tar /

MAINTAINER Vittorio_Cozzolino

RUN apk add nodejs

And this is the output that I get when the automated build completes (the last line contains the error):
Client:  Version:      1.8.1  API version:  1.20  Go version:
go1.4.2  Git commit:   d12ea79  Built:        Thu Aug 13 02:49:29 UTC
2015  OS/Arch:      linux/amd64

Server:  Version:      1.8.3-rc1  API version:  1.20  Go version:
go1.4.2  Git commit:   6f21aba  Built:        Mon Sep 28 20:03:03 UTC
2015  OS/Arch:      linux/amd64 Step 0 : FROM scratch
 ---> Step 1 : ADD rootfs.tar /
 ---> dd771ffd56ea702 Step 2 : MAINTAINER Vittorio_Cozzolino
 ---> 825fc4c990c8a33 Step 3 : RUN apk add nodejs [91mexec: "/bin/sh": stat /bin/sh: no such file or directory

Actually /bin/sh exists and, in fact, if I run CMD ["/bin/sh"] I don't get any error. Can anyone help me here?
Comment: try to do first `apk update` and then it should be OK
Comment: @user2915097 Just tried, nothing changed. I got the same error.
Answer: CMD ["/bin/sh"] is a simple declaration of the default command to run, so it will always work.
Check if the tar is indeed unpacked, as there was a similar issue in 9541: limit your Dockerfile to the ADD directive, and use docker exec or a simple ls to see what is in there (and with which owner/permission).
If the Dockerfile complains about a missing /bin/sh, and /bin/sh is in the tar archive... chances are that archive didn't uncompress properly.