how to cache or preload youtube video in uiwebview

Question: I have a youtube video that plays in a uiwebview in my app.  The cell signal is not very good in most areas I am using the app.
How can I cache the youtube video for better performance when playing the video?
Comment: With a UIWebView you get very little control over what is actually happening with the content. You might look in to the YouTube Data API to see if you could cache video from there, but I doubt that Google wants you doing what you're trying to do.
Answer: Try this
I start downloading the video file with a NSURLConnection
    I then implement the received data delegate method like the following.
<code>- (void)connection:(NSURLConnection *)aConnection didReceiveData:(NSData *)aData
{
    bytesFetched += aData.length;
    if( bytesFetched > kBytesRequiredBeforeStart && !hasCachedData )        // kBytesRequiredBeforeStart = 160000
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kVideoURLCacheHasDataNotification object:self];
        hasCachedData = YES;
    }
    [self.fileHandle writeData:aData];          // this file handle is not closed until after the video has finished downloading
}
</code>
The fileHandle is created like this
<code>- (NSFileHandle *)fileHandle
{
    if( fileHandle == nil )
    {
        NSError             * theError = nil;
        cachedURL = [[NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingFormat:@"/%@", kTempFileName]] retain];
        [[NSFileManager defaultManager] createFileAtPath:[self.cachedURL path] contents:nil attributes:nil];
        fileHandle = [[NSFileHandle fileHandleForWritingToURL:self.cachedURL error:&theError] retain];
        if( fileHandle == nil )
            [[NSNotificationCenter defaultCenter] postNotificationName:kVideoURLCacheErrorOccuredNotification object:self];
    }
    return fileHandle;
}
</code>
*I also have a did finish delegate handling method like this*
<code>- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if( hasCachedData == NO )
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kVideoURLCacheHasDataNotification object:self];
        hasCachedData = YES;
    }
    hasFinishedCaching = YES;
    [[NSNotificationCenter defaultCenter] postNotificationName:kVideoURLCacheDidFinishLoadingNotification object:self];
}
</code>
I then have a method to observer the notification like the following
<code>- (void)videoURLCacheHasDataNotification:(NSNotification *)aNotification
{
    [self.videoController play];
}
</code>
where the videoController is an instance of MPMoviePlayerController created like below, cachedURL is the same one defined above.
<code>- (MPMoviePlayerController *)videoController
{
    if( videoController == nil )
    {
        NSURL       * theURL = self.videoURLCache.cachedURL;
        NSLog( @"Video URL = '%@'", theURL );
        videoController = [[MPMoviePlayerController alloc] initWithContentURL:theURL];
        videoController.shouldAutoplay = NO;
        [videoController setFullscreen:NO animated:NO];
        videoController.view.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleHeight;
        videoController.repeatMode = MPMovieRepeatModeOne;
        videoController.controlStyle = MPMovieControlStyleEmbedded;
        videoController.view.frame = self.videoView.bounds;
        [videoView addSubview:self.videoController.view];
    }
    NSParameterAssert(videoController != nil);
    return videoController;
}
</code>


How much information a Flash program (Flash app) can gather about computer when running?

Question: Does anyone know if a flash web application has access to local hard drive? What about OS information or hardware information?
If I allow webcam and microphone access, how much information can it get about hardware, os and computer?
I'm asking because I'm worried how much information can 3rd party sites gather when I allow running flash applications.
Answer: Flash web apps can access certain information about the device running the browser. If you have a look at the AS3 Capabilities class you will get an idea of what's possible: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/Capabilities.html ... I don't believe you can get any intrusive data from Flash web apps though.


Can I know what rewards I have already unlocked

Question: Is there a way to know what kind of reward giving achievements are already completed on an account?
Answer: There is no such thing as an achievement tracker or achievement screen in Hearthstone. You have to just use your memory as to which ones you've completed already.
Comment: Blizzard has discussed wanting to track achievements with HS but they aren't sure exactly what they want that feature to look like so it seems to be outside of their current development focus.


Php OR operator gives wrong result?

Question: I am surprised with the output of OR operator in php
$a = 5;

echo $b = ((intval($a) == 8 || 2) && intval($a) != 0 ? $a : NULL);

It echo 5 but i expect NULL
Comment: A wife sends her programmer husband to the store: "Get a loaf of bread, and if they have eggs, get a dozen." Back comes the husband with dozen loaves of bread. Seeing his wife's angry face, he innocently responds, "What? They had eggs!" -- Human languages and programming languages don't really work the same. `$a == 8 || 2` means `($a == 8) || 2`, and `false || 2` is `1` (truthy).
Comment: Why do you expect NULL?
Comment: Coz my $a is not 2 and not 8
Comment: use === it will give you null.
Comment: @Dave `===` and `==` in this situation is same, because comparing integers
Answer: It should be like this.
$a = 5;

echo $b = ((intval($a) == 8 || intval($a) == 2) && intval($a) != 0 ? $a : NULL);

Comment: Thanks for answer :)
Answer: As you stated, your $a is not 8 or 2. So assume it's 5.
How your evaluation works:
((intval($a) == 8 || 2) && intval($a) != 0 ? $a : NULL);

Compare intval($a) == 8.
No matter what you get from #1, do || 2 which leads to true (non-zero number is loosely equals true)
Compare intval($a) != 0 - leads to true.
Compare true && true => true
Answer is $a.

Step-by-step:
 (intval($a) == 8 || 2) && intval($a) != 0 ? $a : NULL;
 (false || 2) && intval($a) != 0 ? $a : NULL);
 (false || true) && intval($a) != 0 ? $a : NULL;
 true && intval($a) != 0 ? $a : NULL;
 true && true ? $a : NULL;
 $a;

TL;DR
To get NULL, change || 2 to || intval($a) == 2
Comment: Thanks for answer :)
Answer: change this
intval($a) == 8 || 2

to
intval($a) == 8 || intval($a) == 2

i.e
echo $b = ((intval($a) == 8 || intval($a) == 2) && intval($a) != 0 ? $a : NULL);

Comment: Thanks for answer :)
Answer: The way you write comparison for OR is not possible in PHP. Use below code.
echo $b = ((intval($a) == 8 || intval($a) == 2) && intval($a) != 0 ? $a : NULL);

Comment: Thanks for answer :)

Php OR operator gives wrong result?


Sending email with laravel, but doesn't recognize variable

Question: I'm trying to send an email through Laravel, but I'm getting this error:

Undefined variable: contactEmail

Even though it got defined above it. What is going wrong here?
Controller
$contactName = Input::get('name');
$contactEmail = Input::get('email');
$contactMessage = Input::get('message');

$data = array('name'=>$contactName, 'email'=>$contactEmail, 'message'=>$contactMessage);
Mail::send('template.mail', $data, function($message)
{
    $message->from($contactEmail, $contactName);
    $message->to('email@example.com', 'myName')->subject('Mail via aallouch.com');
});

EDIT:
template.mail
Name: {{$name}}
Email: {{$email}}
Message:{{$message}}

Comment: Ok, got it, just edited my message. You have to pass them using `use ($contactEmail, $contactName)`.
Comment: Please show us your template.mail. You might have more than one problem.
Comment: Did an other Edit, fixed some of it. The template.mail is in the edit (that's all I have in that file). But I'm still getting `Undefined variable: contactEmail` You can also test it out at www.aallouch.com/contact then fill in the form and you'll see the error messages
Comment: Change your template to `this is just a test` and try to send your e-mail. First I think you might have a stmp problem. To be clearer, remove all blade from it.
Comment: Changed it. But same error contactEmail not defined even though it is defined just above it. It's in the controller
Answer: As your $data variable is defined as:
$data = array(
    'name'=>$contactName,
    'email'=>$contactEmail,
    'message'=>$contactMessage
);

You won't have a $data available in your view, but you can use directly:
{{ $name }}
{{ $email }}
{{ $message }}

EDIT:
And your controller should have:
    $contactName = Input::get('name');
    $contactEmail = Input::get('email');
    $contactMessage = Input::get('message');

    $data = array('name'=>$contactName, 'email'=>$contactEmail, 'message'=>$contactMessage);
    Mail::send('template.mail', $data, function($message) use ($contactEmail, $contactName)
    {
        $message->from($contactEmail, $contactName);
        $message->to('firstname.lastname@example.com', 'myName')->subject('Mail via aallouch.com');
    });

You must pass your variables to the closure using
use ($contactEmail, $contactName)

As shown above.
Comment: It was super helpful that you showed  "pass your variables to the closure using `use ($contactEmail, $contactName)`".  I had never known how to pass variables to a closure.  Thanks!
Comment: No, but just did it and getting error: `Object of class Illuminate\Mail\Message could not be converted to string`
Comment: You might need to change your `$message` to something like `$messageBody`. Looks like `function($message)` is being passed to your view in place of your `$message`.
Comment: Okay that is working, but in the email I'm having `Name: {{$name}} Email: {{$email}} Message:{{$message}}` the variables aren't being printed
Comment: Is your template named .blade.php?
Comment: Old post. But solved my problem. I wasn't aware of "Closures" in PHP. Thanks
Answer: I have got this error and I have solved it. I have replace $message keyword with $comment from $data.
Example below :
$data = array('name' => 'vikas', 'message' => 'test message');

view
{{ $name }}
{{ $message }}

It's getting error
$data = array('name' => 'vikas', 'comment' => 'test message');

{{ $name }}
{{ $comment }}

Now it's working fine.
Answer: If you look at source code you'll see this line:
 $data['message'] = $message = $this->createMessage();

So your message field is overwritten by that line. Use other name for the field like text or comment.
Answer: I came here to say that if you get this issue in Laravel 5.* or 6.*, make sure that you have your variables set to public within your Mailable class. By default, PHPStorm will make your properties private and they won't be accessible within the email blade template.


How do I achieve the "GitHub browse repo effect" (update URL without refreshing the page)

Question: When I browse a repo in GitHub (example: https://github.com/sizzlelab/kassi) and click a folder, it loads the folder with a cool javascript animation, moving stuff to the left, instead of reloading the whole page. However, the URL of the page is still updated on every click.
How do I achieve this? To my knowledge, you cannot update the page URL from javascript, so you need to refresh the page. My guess is that they do a partial caching of the page so that it does not seem to reload and then run the javascript animation after reload. Am I on the right track? Any pointers on how this can be achieved? My environment is jQuery and rails, but a general advice will help also.
Comment: Saw this today and was also curious. But not enough to dig in :(
Comment: possible duplicate of [GitHub Slider JQuery Plugin...](http://stackoverflow.com/questions/5419469/github-slider-jquery-plugin)
Comment: Merlyn: yeah, that question is close, but I'm more interested in the method of updating url via refreshing the page than the actual slide effect they have in GitHub, and there seems to be no answers to that in the other question. But thanks for the comment!
Answer: what you want is watch this screencast: http://railscasts.com/episodes/246-ajax-history-state
in combination with jQuery UI effect "slide" - http://docs.jquery.com/UI/Effects/Slide
good luck!
Comment: Hey cool, how didn't I manage to find that before! Thanks a lot, just the directions I wanted!
Answer: You can read about this behaviour in spec — History API and on MDN in section "Adding and modifying history entries".
Comment: Modernizr checks History API something like this: function isHistorySupport() { return !!(window.history && history.pushState); }
Comment: Thanks! So it's HTML5 stuff then? Any ideas on what's the browser support for that currently? And does it gracefully degrade, and if yes, how? To simply refreshing the whole page?

Well, just a few quick questions, I dig in to those links now. :)
Comment: @Kusti the bottom of the MDN link has browser compatibility
Comment: @Kusti: According to [the blog page linked](https://github.com/blog/760-the-tree-slider) from [the dupe question](http://stackoverflow.com/questions/5419469/github-slider-jquery-plugin), HTML5 manages the history changes, and CSS3 handles the sliding.
Comment: There is an nice library that can help emulate new History API via hashbang — https://github.com/balupton/history.js
Comment: Ok, cool! But, is there any way to achieve this also in Internet Explorer? According to the MDN link no version of Internet Explorer, even 9, supports this. I do not (necessarily) need the fancy animation part, just a way to reload new content and change the URL without refreshing the whole page.

Facebook also seems to do something like this: when I click around in the inbox, only then contents of the inbox change so that it seems the whole page is not refreshing even though the URL changes. I have a mac so I'm currently not able to test whether this works also on IE.
Comment: @Kusti: Depending on your requirements, if you can simply hook the link with JS and reroute it to an Ajax call to load the new page into a div, without "refreshing" the whole page.  This won't solve the history problem, tho.


How to get the latest value within a time window

Question: This is what my streaming data looks like:
time | id | group
---- | ---| ---
1    | a1 | b1
2    | a1 | b2
3    | a1 | b3
4    | a2 | b3

Consider all examples above within our window. My use case gets the latest distinct id.
I need the output to be like below:
time | id | group
---- | ---| ---
3    | a1 | b3
4    | a2 | b3

How can I achieve this in Flink?
I am aware of the window function WindowFunction. However, I cannot wrap my head around doing this.
I have tried this just to get the distinct ids. How can I extend this function to my use case?
class DistinctGrid extends WindowFunction[UserMessage, String, Tuple, TimeWindow] {
  override def apply(key: Tuple, window: TimeWindow, input: Iterable[UserMessage], out: Collector[String]): Unit = {
    val distinctGeo = input.map(_.id).toSet
    for (i <- distinctGeo) {
      out.collect(i)
    }
  }
}

Answer: If you key the stream by the id field, then there's no need to think about distinct ids -- you'll have a separate window for each distinct key. Your window function just needs iterate over the window contents to find the UserMessage with the largest timestamp, and output that as the result of the window (for that key). However, there's a built-in function that does just that -- look at the documentation for maxBy() -- so no need for a window function in this case.
Roughly speaking then, this will look like
stream.keyBy("id")
  .timeWindow(Time.minutes(10))
  .maxBy("time")
  .print()


Evaluate $\lim _{n\to \infty }\int_1^2\:\frac{x^n}{x^n+1}dx$

Question: We have $$I_n=\int _1^2\:\frac{x^n}{x^n+1}dx$$ and we need to find $\lim _{n\to \infty }I_n$. Have any ideea how we can evaluate this limit?
Answer: Well, $\frac{x^n}{x^n+1} \leq 1$ for all $x \in [1,2]$, and the constant function $1$ is integrable in $[1,2]$, so by the Dominated Convergence Theorem we have: $$\lim_{n \to +\infty} \int_1^2\frac{x^n}{x^n+1}\,{\rm d}x = \int_1^2 \lim_{n \to +\infty} \frac{x^n}{x^n+1}\,{\rm d}x = \int_{1}^2 1\,{\rm d}x = 1.$$
Comment: It is clear that $x^n/(x^n + 1) \to 1$. If the convergence was uniform, we could swap $\int$ and $\lim$ right off the bat. But as pointed by Alex in a comment in the other answer, the convergence it not uniform. So we must find another way to swap $\int$ and $\lim$. The Dominated Convergence Theorem was the first thing that came to my mind. I don't know if there is another way to do it without using the definition of integral and start swimming in summations.
Comment: are you sure we can use this method?
Comment: what are the conditions that must be satisfy to use "Dominated Convergence Theorem" ?  for instance, in our case, what conditions were put to use DCT ?
Comment: The statement is: If you have a sequence of integrable functions $f_n$ such that $f_n \to f$, and exists $g$ integrable dominating all of the $f_n$, that is, $|f_n| \leq g$ for all $n \geq 0$, then $\lim \int f_n = \int f$.
Comment: and how I could realize if the convergence is uniform or not? what is the difference, because is saw if the convergence is uniform is same like DCT...
Comment: @Lucas: To show that $f_n$ converges uniformly to $f$ one must check that $\lim \limits _n \space \sup \limits _x |f_n(x)-f(x)|=0$. In your problem, though, you get $\frac 1 2$ instead of $0$, so the convergence cannot be uniform. Another way of showing this is the following: the uniform limit of a sequence of continuous functions must itself be continuous. But in your example, the limit is $0$ on $(1,2]$ and $\frac 1 2$ in $1$, which is discontinuous, so again the convergence cannot be uniform.
Comment: but what is the difference between uniform convergence and dominate convergence? **both have the purpose of changing limit with integral**...I see is same thing ... what give in addition the uniform convergence and when we need to use it and not dominated convergence  ?
Comment: "Dominated Convergence" is not a type of convergence - it is the name of the theorem.
Answer: Note that $\frac{x^n}{x^n+1}=1-\frac{1}{x^n+1}$.  Thus,
$$\int_1^2 \frac{x^n}{x^n+1}dx=1-\int_1^2 \frac{1}{1+x^n}dx$$
For $n>1$, the integral on the right-hand side satisfies the inequality
$$\left|\int_1^2 \frac{1}{1+x^n}dx\right|\le \int_1^2 x^{-n}dx=\frac{1-2^{1-n}}{n-1}$$
which clearly goes to zero as $n \to \infty$.
Putting all of this together we see that
$$1\ge \int_1^2 \frac{x^n}{1+x^n}dx=1-\int_1^2 \frac{1}{1+x^n}dx \ge 1-\int_1^2 x^{-n}dx=1-\frac{1-2^{1-n}}{n-1}$$
Therefore, by the "squeeze" theorem
$$\lim_{n \to \infty} \left(\int_1^2 \frac{x^n}{1+x^n}dx\right) =1$$
Comment: @Lucas I added to the answer to provide a proof using the squeeze theorem.  Let me know how I can improve further.  I just want to give you the best answer I can.
Comment: Hi Dr.MV , nice to see you again :D...  about the subject, I think we can prove it with squeeze theorem $\int \:_1^2\:\frac{x^n}{\left(x^n+1\right)}dx\le 1$  but I am thinking to show that $\int \:_1^2\:\frac{x^n}{\left(x^n+1\right)}dx$  is bigger than something goes to 1,have an ideea?
Comment: And you.  Doesn't this development provide the coveted half of such a squeeze?
Comment: what do you mean?
Comment: A lower bound that tends to 1 as $n \to \infty$.
Comment: they don't provide a lower bound who tends to 1...
Comment: $1-\int_1^2 \frac{1}{1+x^n}dx\ge 1-\int_1^2 x^{-n}dx$.
Answer: Divide the numerator and denominator of the integrand by $x^n$:
$$ \frac{1}{1+x^{-n}} $$
For every $x \in (1,2]$, $x^{-n} \to 0$ as $n \to \infty$. Since this is all but one point of the interval of integration, the integral tends to
$$ \int_1^2 \frac{1}{1} \, dx = 1. $$
To do it more thoroughly than this, you can chop up the interval into a small region around $1$ and the rest, and examine the size of the integrand on each.
Comment: The convergence is uniform on intervals $[1+\varepsilon,2]$ for any $\varepsilon>0$, and you can bound the integral on $[1,1+\varepsilon]$ by a constant times $\varepsilon$.
Comment: @Lucas They're very different notions, but happen to coincide for integrating functions over finite intervals. https://terrytao.wordpress.com/2010/10/02/245a-notes-4-modes-of-convergence/ gives an extensive account, but is probably a bit technical. Basically, a sequence of Riemann-integrable functions that converges uniformly on a finite interval converges to a Riemann-integrable function, and the limit and integral can be swapped The DCT is really about the Lebesgue integral. If you want to know more, I suggest you ask a new question - this is not a topic explainable in a few comments.
Comment: I don't see how you commute the limit with the integral other than with the dominated convergence theorem, which is the answer already given by @IvoTerek. (Note that the convergence is not uniform.)
Comment: I totally agree. What I meant is that there is no explicit mention of these facts in your answer. Given that the OP seems to be a beginner, it is important for him to understand that passing to the limit under the integral sign is not a straightforward procedure as it might appear from your answer. It is important to remember that MSE also tries to educate, it is not only a place where problems are solved.
Comment: but what is the difference between uniform convergence and dominate convergence? both have the purpose of changing limit with integral...I see is same thing ... what give in addition the uniform convergence and when we need to use it and not dominated convergence ?


Jtable Hide some columns

Question: How to make a table from some, but not all columns in an object? This is the desired output:
 ID|Author|Messages
 ----------------------------
 2 |Alice | My first message
 5 |Alice | My second message
 6 |Bob   | Hello

This is the object.
      private String[] columnNames
            = {"ID","Author", "HideThis", "Messages"};

    private Object[][] data = {
        {"2", "Alice", "Hide this", "My first message"},
        {"5", "Alice", "Hide this", "My second message"},
        {"6", "Bob", "Hide this", "Hello"}
    };
    private DefaultTableModel model = new DefaultTableModel(data, columnNames);

Do I have to create a new data object and copy only relevant columns or is there a way to say columnSetHidden(2)?
Answer:  DefaultTableModel model = new DefaultTableModel(ProcessArray(data,1),columnNames);

 public Object[][] ProcessArray(Object[][] arr,int colindex) {

            List points = Arrays.asList(arr);
            for (int i = 0; i < arr.length; i++) {
                for (int j = 0; j < arr[i].length; j++) {
                   points.remove(arr[i][colindex]);
                }
             }
             Object[][] returnData = (Object[][]) points.toArray();
             return returnData;

        }

theres no Api specification in DefaultTableModel to remove a column, but you can customize your 2d array and remove the column you need. and then pass the processed array to the constructor of the DefaultTableModel. However you still need to change the column names.

Jtable Hide some columns


Python SMTP Email Message Body Showing

Question: I have been trying to make the content or message body to appear in the emails but it doesn't appear to be working.  It's mentioned that a empty line is needed before the message and with new line after subject.  Also, each time I run the script it runs but gives this error "Task timed out after 3.01 seconds" but I get the email, however, the Lambda function is marked as Failed...not sure why?? Maybe that's not so much of a big deal but if it ran then I'm assuming it was successful which is confusing since it says failed. The biggest thing here is the content not showing up.  Thank you for any assistance.
import smtplib

sender = 'example.org'
recipient = contact

        try:
            subject = str(instance_name) + ' Issues'
            content="Hello World"
            mail = smtplib.SMTP('smtp.office365.com', 587)
            mail.ehlo()
            mail.starttls()
            mail.login('example.org','1234567890')
            header = 'To:' + recipient + '\n' + 'From:' \
            +sender+'\n'+'subject:' + subject  + '\n'
            content=header+content
            mail.sendmail(sender, recipient, content)

        except:
            print ("Error: unable to send email")

Comment: Did you try increasing the timeout? Is your AWS Lambda function connected to a VPC? If so, why did you choose to connect it to a VPC?
Comment: I've been looking for the correct syntax for increasing the timeout but it's not clear but I'm assuming it's "mail = smtplib.SMTP('smtp.office365.com', 587, 600)" the number after the port?  It's not corrected to a VPC.
Comment: I changed this line of code "+sender+'\n'+'subject:' + subject  + '\n\n' " and it appears to be working, it will give me email a simple "hello world" but when I try and email the email body as a string str(email), the body does not show up, what gives?  a string is a string, right?
Answer: I changed this line of code "+sender+'\n'+'subject:' + subject + '\n\n' " and it appears to be working.  As far as the timeout issue.  I increased it to a minute and it works fine now.

Python SMTP Email Message Body Showing


TinyMCE 5.x - highlight custom button

Question: I created a custom link button and want it appear highlighted/selected when you select/click on the link in the text editor, just like clicking on bold text shows the Bold icon as selected. In TinyMCE 4 you could simply use "stateSelector" to have it highlight when that kind of DOM element was selected, like this:
editor.ui.registry.addButton('SpecialLink', {
        icon: 'link',
        onAction: makeSpecialLink(),
        **stateSelector: 'a[href]'**
});

I can't find anything about what stateSelector was replaced with in TinyMCE 5 and so far all I've been able to do is recreate some of that functionality inside tinymce.init:
    init_instance_callback: function(editor) {
            editor.on("SelectionChange", function(e){
                let elem = editor.selection.getNode();
                if( $(elem).is("a") )
                    console.log("Highlight the Special Link button");
                else
                    console.log("Deselect the Special Link button");
            })
        }

I can reference myMCE.plugins.SpecialLink, but I can't call setActive(true) on it.
Any help would be greatly appreciated!
Answer: You can use addToggleButton rather than addButton, then call setActive.
Here's a snippet of my code.
  editor.ui.registry.addToggleButton('my-action', {
    icon: null,
    text: 'My action',
    onAction: function onAction() {
       // ...do stuff
    },
    onSetup: function(api) {
      function nodeChangeHandler(){
        const selectedNode = editor.selection.getNode();
        return api.setActive(selectedNode.id === constants.id);
      }
      editor.on('NodeChange', nodeChangeHandler);
    }
  });
}

https://www.tiny.cloud/docs/ui-components/typesoftoolbarbuttons/#togglebutton
Answer: @Muki's answer is similar to what I did, but I referenced the core code for anchor button from tinymce's git repo here https://github.com/tinymce/tinymce/blob/develop/modules/tinymce/src/plugins/anchor/main/ts/ui/Buttons.ts
I changed editor.ui.registry.addButton to editor.ui.registry.addToggleButton and added onSetup: (buttonApi) => editor.selection.selectorChangedWithUnbind('a:not([href])', buttonApi.setActive).unbind instead of stateSelector after onAction.
Something like below:
editor.ui.registry.addToggleButton('SpecialLink', {
        icon: 'link',
        onAction: makeSpecialLink(),
        onSetup: (buttonApi) => editor.selection.selectorChangedWithUnbind('a:not([href])', buttonApi.setActive).unbind
});

TinyMCE 5.x - highlight custom button


Is complex Abelian variety isogenic to its dual?

Question: Suppose $A$ is a complex Abelian variety and let $A^V$ be the dual Abelian variety. $A^V$ is defined as the moduli space of all line bundles on $A$ with $c_1=0$.
It seems to me that $A$ is isogenic to $A^{V}$.
But I am not sure that this is correct. So I would like to give the following "proof".
Consider the space of all line bundles on $A$ with a fixed ample class $c$ (which exists since $A$ is ableian), let us call this space $A_c$. It is clear that $A_c$ isomorphic to $A^V$. Now, $A$ is acting on intself by translations and so it is acting on $A_c$. I think that the orbit of the action covers whole $A_c$ if $c$ is ample. So we get a  finite covering map $A\to A_c\cong A^{V}$.
Question. Is the above reasoning correct? Are $A$ and $A^V$ isogenious?
Answer: I think your reasoning is correct.
The way I learnt about this isogeny issue is the following. Work over any algebraically closed field. Every invertible sheaf $\mathscr L$ on $A$ induces a homomorphism of Abelian varieties $$\phi_\mathscr L:A\to \textrm{Pic }A$$
sending $a\mapsto \tau_a^\ast\mathscr L\otimes\mathscr L^\vee$, where $\tau_a$ is translation by $a$. Now, if $m:A\times A\to A$ and $q:A\times A\to A$ denote the multiplication and the second projection respectively, then for each $a\in A$ we have an identification in $\textrm{Pic }A$:
$$(m^\ast\mathscr L\otimes q^\ast \mathscr L^\vee)|_{a\times A}\cong \tau_a^\ast\mathscr L\otimes\mathscr L^\vee.$$
There are several things happening:

The locus of $a\in A$ such that the LHS is trivial (by the displayed isomorphism, this is the kernel of $\phi_\mathscr L$) is closed in $A$. This is a good starting point for its possible finiteness!
For any $\mathscr L$, the image of $\phi_\mathscr L$ lands in $A^\vee$. The image is exactly $A^\vee$ when $\mathscr L$ is ample.

If $h^0(A,\mathscr L)>0$, then $\ker\phi_\mathscr L$ is finite if and only if $\mathscr L$ is ample.

So an isogeny $A\to A^\vee$ (called in this case a polarization)  is provided by any ample line bundle. Moreover, those $\mathscr L$ with $h^0(A,\mathscr L)=1$ induce principal polarizations, i.e. polarizations of degree $1$, i.e. isomorphisms $A\to A^\vee$.
Comment: Dear Brenin, did you mean $\chi(L)$ instead of $h^0(L)$ ?
Comment: @Cantlog: I had in mind the following: a principal polarization "is" the choice of a *unimodular* skew symmetric bilinear form $\xi\in H^2(A,\mathbb Z)$. There is a matrix representing this form, and $h^0(A,L)$ is the square root of the determinant of this matrix. But this det must be $1$ because $\xi$ is unimodular. Nevertheless, I checked on *Arithmetic Geometry* (Cornell Silverman ed.) and I only found out that $\deg\phi_L=\chi(L)^2$. Does this imply $h^0(A,L)=1$ when $\deg\phi_L=1$? (If you have that book it is Thm. 13.3, p. 127)
Comment: We have $\chi(L)=h^0(L)$ if $h^0(L)\ne 0$. So what you say is true under the hypothesis of 3. But in general, $L$ ample does not imply $h^0(L)\ne 0$.


Are these corner brackets that hard-to-find?

Question: I was searching for this a particular corner brace/bracket, but it seems that they are impossible to find.
I couldn't them at home depot or at amazon. I'm not sure if they just don't exist or if I'm looking for them incorrectly.
This is it:

I posted a similar question, and it helped because it showed me an alternative, but in this case I want to find this specific bracket that will hold three walls together.
Comment: So search, this is a quick result so they do exist https://www.ebay.co.uk/itm/Pack-50-heavy-duty-enclosed-corner-brace-angle-brackets-fixing-repair-plate-50mm/202654691087?hash=item2f2f292f0f:g:~ZUAAOSwH6lXQ182
Comment: I agree they are easy to find but possibly the op has dimensions that are specific I don't see in the question. Mike turn that into an answer and remember link only tend to change and be worthless or I would have up voted your comment but some folks don't know what corner brackets are. Even it is in the question some may have missed that.
Comment: Agree with Ed. That's an answer. The OP is still trying to make those planters.. lol
Comment: Unfortunately, "shopping" questions are off-topic here.
Comment: how about using steamer trunk corners? https://www.hardwaretree.com/products.php?cat=Corners+for+Trunks
Answer: There is this one on Amazon:
https://smile.amazon.com/dp/B071W4VQPT
You are working with a 20x20 tile and these are 2.25" Roughly
These ones: https://smile.amazon.com/dp/B0195UGD38
They are much larger, though WAY more Expensive.
Though you will see those Brackets. You could use something like this on the Inside with some Galv Bolts or SS Screws to make it look nicer.
https://smile.amazon.com/dp/B07CWMSS79
I'd put two on each adjoining edge. so 2 in each corner and 2 on each side on the bottom.


python sqlalchemy orm one to many bidirectional relation - mapping a json to multiple tables

Question: I am using sqlalchemy orm to map a json to multiple tables.
I have two tables, each for which I have a class.
One of the tables, has a parameter, which is a list of dictionaries and this has to be mapped to different columns of the second table.

from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()

class A(Base):
    __tablename__ = 'a'
    id = Column(primary_key, Interger(10))
    param1 = Column(String(45))
    param2 = Column(String(45))
    atobmap = relationship('B', lazy='subquery', back_populates="a")

class B(Base):
    __tablename__ = 'b'
    bid = Column(primary_key=True, nullable=True, Integer(15))
    bparam1 = Column(ForeignKey('a.id'), nullable=False)
    bparam2 = Column(String(45))
    a = relationship('A', back_populates='b')

sample json:
{
    "id": 1,
    "param1": "Value",
    "param2": "Value",
    "atobmap": [
                 { "bid": 1,
                   "bparam1": 1,
                   "bparam2": "Value"
                 },
                 { "bid": 2,
                   "bparam1": 1,
                   "bparam2": "Value"
                 }
               ]
}

When I manually insert data into the tables and do a GET, its working fine and is returning values as expected, although it adds an _sa_instance_state key with value {} inside my atobmap dictionaries.
{
...
"atobmap": [
                 { "_sa_instance_state": {}
                   "bid": 1,
                   "bparam1": 1,
                   "bparam2": "Value"
                 },
                 { "_sa_instance_state": {}
                   "bid": 2,
                   "bparam1": 1,
                   "bparam2": "Value"
                 }
       ]
}

But when I try to POST the values, it throws an error saying "Unhashable type: dict".
Comment: You should add some more code which actually does the insert or what line throws the error
Answer: You can use a function similar to the one below.
It takes an SQLAlchemy model and a dictionary of field/value pairs and
returns a model instance. Ignores keys that are in the dictionary
that aren't fields on the model. Traverses and instantiates relationships.
Example:
Our models include a Company model with a name field that is a string
and a users field that is a one-to-many relation to a User model.
Our data looks like the following.
{
"company":
{
"name": "Owoga"
"users": [
{
"name": "Eric"
}
]
}
}
We will use SQLAlchemy's class_mapper function to get the "mapper"
for the model. We can then access mapper.attrs.keys() to get a list
of all the mapped fields. Any of those keys that are not relationships, simply
grab them out of the data. For keys that are relationships, get the mapper
of the relationship and then recursively call from_json with that related mapper
and the sub-data. Then, attach that new instance[s] to the parent instance.
def from_json(model, data):
    mapper = class_mapper(model)
    keys = mapper.attrs.keys()
    relationships = inspect(mapper).relationships
    args = {k: v for k, v in data.items() if k in keys and k not in relationships}
    instance = model(**args)
    for attr, relationship in relationships.items():
        if relationship.direction in [MANYTOMANY, ONETOMANY]:
            relationship_instances = [
                from_json(relationship.mapper.class_, el) for el in data[attr]
            ]
            setattr(instance, attr, relationship_instances)
        elif relationship.direction == MANYTOONE:
            try:
                relationship_instance = from_json(
                    relationship.mapper.class_, data[attr]
                )
            except KeyError:
                pass
            else:
                setattr(instance, attr, relationship_instance)
    return instance


3rd level menu pop out being chopped short. CSS query

Question: I'm modifyng a joomla menu to have a horizontal pop out for 3rd level menu items but am struggling getting this to display correctly. I've tried here there and everywhere but can't trace the issue.
The menu in question is at http://bit.ly/13ruR7B
And in particular under Support>Downloads (the rest of the menu is fine)
The resulting 3rd level menu items 'Brochures/catalogues' and 'Pricelists are being chopped off, I've hunted around in Firebug but can't find the cause.
Any suggestions gratefully accepted :-)
C
Comment: Hi, please check out [Something on my web site doesn't work. Can I just paste a link to it?](http://meta.stackexchange.com/q/125997) thanks!
Answer: there are some overflow:hidden declarations you should remove, then just arrange the third level as you wish.
overflow:hidden is added by javascript on div.dropdown.columns1 and the div beneath it.
Comment: Thanks Daniel. pointed me in the right direction. Javascript was the cause.


How to force a groupby/sum when summing on a mismatched value in a column in a Pandas DataFrame?

Question: Say I have a dataframe 'df':

data = {'first':['jack','jack','zeke','zeke','zeke'],
'last':['sparr','sparr','smith','smith','smith'],
'method':['cell','cell','skype','cell','cell'], 'duration':
[5,5,3,1,1]}

first     last     method    duration
 jack    sparr       cell           5
 jack    sparr       cell           5
 zeke    smith       skype          3
 zeke    smith       cell           1
 zeke    smith       cell           1

I want to sum the call durations on first, last, and method. I'd like it so when the 'method' doesn't match, they are 'force summed' and the value is left blank
So far running a something like:

df = df.groupby(['first','last','method'], as_index=False).sum()

will give back:
first     last     method    duration
 jack    sparr       cell          10
 zeke    smith       skype          3
 zeke    smith       cell           2

but I'm going for
first     last     method    duration
 jack    sparr       cell          10
 zeke    smith                      5

How can I modify my sum statement to achieve this, or is this even possible with pandas? Thanks
Answer: Try something like this:
df.groupby(['first', 'last'], as_index=False)[['method', 'duration']]\
  .agg({'method':lambda x: x.iloc[0] if x.nunique() == 1 else '',
        'duration':'sum'})

Output:
  first   last method  duration
0  jack  sparr   cell        10
1  zeke  smith                5

Okay, let's group by only first and last name since you sums appear to at this level.   For method, we are going aggregate to one value, if all the values in the method column the same (nunique == 1), else use '' blank.
We are using dictionary to define the aggregation of each column.
Comment: thanks! can you explain how you knew to chain these things together and what the thought process is? that statement is intimidating haha :0


How to get out of while loop when data is found in swift?

Question: I've written the following code to retrieve data by date inside the while loop. Problem is, it's not getting out of the loop when data is found. I think, I missed some code to make extra checking.
Because print is working multiple times. Please help me how to solve.
while startdate.compare(enddate) != .OrderedDescending {
    let mydate = Config.convertDateTimeFormater(Config.convertDateToString(startdate, fromFormat:

    let test = [
        "date" : mydate
    ]
    JHProgressHUD.sharedHUD.showInView(self.view, withHeader: "Loading", andFooter: "Please wait")
    Alamofire.request(.POST, Config.checkBookingSlot, parameters: test as? [String : AnyObject], headers: headers, encoding: .JSON).responseJSON { (responseData) -> Void in
        if((responseData.result.value) != nil) {
            let swiftyJsonVar = JSON(responseData.result.value!)
            let msg = swiftyJsonVar["message"].stringValue
            if (swiftyJsonVar["success"]) {
                if let slotData = swiftyJsonVar["data"]["detail"].arrayObject {
                    if slotData.count > 0 {
                        isFound = true
                        print("Break")
                        JHProgressHUD.sharedHUD.hide()
                    } else {
                        JHProgressHUD.sharedHUD.hide()
                        self.showPopup(Config.showPopupMsg)
                    }
                } else {
                    JHProgressHUD.sharedHUD.hide()
                    self.showPopup(Config.showPopupMsg)
                }
            } else {
                JHProgressHUD.sharedHUD.hide()
                isFound = true
            }
        } else {
            JHProgressHUD.sharedHUD.hide()
            isFound = true
        }
    }
    if isFound {
        break
    }
    startdate = calendar.dateByAddingUnit(.Day, value: 1, toDate: startdate, options: [])!
}

Comment: see this once u get idea http://stackoverflow.com/questions/9418972/ios-break-nested-loop
Comment: Instead of putting  the network call in loop , use `NStimer` or `Performselector` task so that you will be able to check your condition with response. or else your loop will finish before you get first response itself.
Comment: Are you sure you're receiving and parsing the JSON data correctly?
Answer: You are making asynchronous requests within your loop and your isFound variable is set within the closure, so the loop is not waiting on response for those. It's very likely that your loop will finish before you even get the first response.
Answer: While loop work in sync manner and api calling always work in background means async so you need to change your code like this
func getData(startDate: NSDate) {
    if (startDate.compare(enddate) != .OrderedDescending) {
        let mydate = Config.convertDateTimeFormater(Config.convertDateToString(startdate, fromFormat:

        let test = [
            "date" : mydate
        ]
        JHProgressHUD.sharedHUD.showInView(self.view, withHeader: "Loading", andFooter: "Please wait")
        Alamofire.request(.POST, Config.checkBookingSlot, parameters: test as? [String : AnyObject], headers: headers, encoding: .JSON).responseJSON { (responseData) -> Void in
            if((responseData.result.value) != nil) {
                let swiftyJsonVar = JSON(responseData.result.value!)
                let msg = swiftyJsonVar["message"].stringValue
                if (swiftyJsonVar["success"]) {
                    if let slotData = swiftyJsonVar["data"]["detail"].arrayObject {
                        if slotData.count > 0 {
                            JHProgressHUD.sharedHUD.hide()
                        }
                        else {
                            JHProgressHUD.sharedHUD.hide()
                            self.showPopup(Config.showPopupMsg)
                            startDate = calendar.dateByAddingUnit(.Day, value: 1, toDate: startdate, options: [])!
                            self.getData(startDate)
                        }
                    }
                    else {
                        JHProgressHUD.sharedHUD.hide()
                        self.showPopup(Config.showPopupMsg)
                        startDate = calendar.dateByAddingUnit(.Day, value: 1, toDate: startdate, options: [])!
                        self.getData(startDate)
                    }
                }
                else {
                    JHProgressHUD.sharedHUD.hide()
                }
            }
            else {
                JHProgressHUD.sharedHUD.hide()
            }
        }

    }
}

Comment: how did you call that function then? I want to sync within date range.
Comment: You have startDate right the date you are using in while loop just use that date to call this function like this way `self.getData(startdate)`
Comment: it's not workable because while loop never wait sync result.
Comment: thats why i have not use loop, check my answer properly
Comment: if there is 4 days different between startdate & enddate, how to use your function?
Comment: Don't understand what you asking can you explain briefly?
Comment: exp: start date is 26-July-2016 and end date is 30-July-2016. There is 4 days different between start date & end date. That's why how can I check for all days with your function.
Comment: I am incrementing the startdate `startDate = calendar.dateByAddingUnit(.Day, value: 1, toDate: startdate, options: [])!` just like you did and calling this function again using that date.
Comment: In your question you are setting `isFound` to true for break the loop, in my answer i have not call the function again on that part, I have already give you compete answer. Check properly.


Is this possible in controller test?

Question: In my user controller I have a before_action for the new page/method. This before_action includes:
@organization = Organization.friendly.find(params[:id])

In my user fixtures I have an organization: one for user @admin, and in my organizations fixtures I have a record for this organization "one". Still my controller test fails on the above line with the message:

ActiveRecord::RecordNotFound: Couldn't find Organization without an ID

Why is this? Is it not possible to do this in a controller test and should I use an integration test instead? If I can use a controller test (which I here prefer), what is wrong with my code?

The controller test:
  test "should get new" do
    log_in_as("user", @admin) # Test helper that functions properly
    get :new                  # It fails here on the before_action defined in the users controller.
    assert_response :success
  end

Comment: Shouldn't the `before_action` be `@organisation = @admin.organisation` based on what you've explained?
Comment: It's just one line from the `before_action`. @admin in a variable in the test file, while the before_action exists in the controller.
Answer: You expect to have params[:id], and you don't pass it. Try
test "should get new" do
  log_in_as("user", @admin)
  get :new, id: 1 # or any other
  assert_response :success
end

You either need to change your before_action filter or update your tests.
Comment: Yes, this worked. Included the organization in the `setup` of the test and passed the id.
Answer: As the information you showed, i think the problem is you should limit the before action.
For example
before_action :set_organization, except:[:index,:new] or use only
before_action :set_organization, only:[:show,:edit,:update,:destroy].
If you want set organization for all actions, then you should provide the id params.
eg:
  before_action :set_organization

  def set_organization
     @organization = Organization.friendly.find(params[:organization_id])
  end

  get :new,organization_id: 1

Is this possible in controller test?


`MissingAttributeError` when trying to save after a `select`

Question: This works on rails 3.2:
replies = Reply.select([:id, :reply]).limit 30
replies.first.account # nil
replies.first.account = Account.first
replies.first.save #this works, it updates account on db even when was not included in select

But when i tried to do that on rails 4 I receive:
ActiveModel::MissingAttributeError:

Is not possible to save a attribute if I don't retrieve it using select?
Comment: I take it that a Reply has_one Account?
Answer: From the guides:
"Be careful because this also means you're initializing a model object with only the fields that you've selected. If you attempt to access a field that is not in the initialized record you'll receive: ActiveModel::MissingAttributeError: missing attribute: "
So you are probably referencing the missing attribute in either a validation or a callback.
Eg: if you have an attribute named 'title' on your Reply model with a presence validation, then when you try to save your reply which is initialized to:
#<Reply id: 1, reply: "reply">

you will receive a MissingAttributeError for title because it is not part of your initialized object.
Comment: Is there any way around that? I only want to validate if the attribute has been included in the `select`


Issue with Eclipse Running Android Project

Question: Many times when I run android application using Eclipse. Eclipse stuck on building the project and then I have to restart to fix this. What could be the actual solution for this problem. It wastes a lot of time.
It stucks of Lauching Delegate 27 %
Comment: whats your problem bar is showing @ that time?
Comment: nothing. But Progress Bar is showing Launching Delegate 27%.
Comment: I mean that problem tab like console, logcat...
Comment: nothing because launching is stuck.
Comment: In Eclipse Go to project-> Build Automatically check once and runit.
Comment: A possible cause of this is not having run or debug configurations present. Goto Run/Debug configurations and create a new one to run/debug your app.
Answer: Hmm, were you able to run android applications before? Are you using an emulator or connecting to an actual device?
Comment: Found this over at project pages as Issue #21073, answered by benpar:

Update: This scenario can also be avoided if the AVD emulator is launched from the AVD Manager within Eclipse. The issue happens when launching the first emulator from the Run button in Eclipse.

To avoid:

1.Start Eclipse
2.Window -> AVD Manager
3.Start an emulator
4.Run the project
Comment: same machine and same device. But it is creating problem now. I updated Eclipse and problems has been started is there any way to downgrade it?
Comment: but m not working with emulator. I have an android Device. Does the above scenario applies on Devices?
Answer: your system speed is slow (I think process is slower then 2.0GHZ and ram is less then 2gb).Upgrade them .
Comment: I dont think my system is slow. 2.3 Dual Core 2 GB DDR3 Is it slow? for eclipse?


fading external images in an array

Question: I am trying to take ten images, load them into an array, and then show them one at a time,fading out each one in turn.  I keep getting this error.
ReferenceError: Error #1056: Cannot create property alpha on String.
    at fl.transitions::Tween/setPosition()
    at fl.transitions::Tween/set position()
    at fl.transitions::Tween()
    at images_fla::MainTimeline/goPlay()
my code
import fl.transitions.Tween;
import fl.transitions.easing.*;

play_btn.addEventListener(MouseEvent.CLICK, goPlay)

var images = new Array();

images[0] = "1.jpg";
images[1] = "2.jpg";
images[2] = "3.jpg";
images[3] = "4.jpg";
images[4] = "5.jpg";
images[5] = "6.jpg";
images[6] = "7.jpg";
images[7] = "8.jpg";
images[8] = "9.jpg";
images[9] = "10.jpg";

function goPlay(e:MouseEvent) {
    for (var i:int = 0; i <10; i++) {
    loadWindow.source = images[i];
    var myTween:Tween = new Tween(images[i], "alpha", None.easeOut, 1, 0, 15, true);
}
}

Answer: your problem is all you have is an array of strings, your file names. So when you are trying to target images[i] you are telling the tween to do something to a string which it can't do. You have to load the image into a loader and then apply that tween to the loader.
Loader example
Answer: The first parameter of the Tween object is a string, and fails because strings don't have an alpha property. Try passing the actual loadWindow object instead of the images[i].

fading external images in an array


Is it feasible to add a garbage disposal with this kitchen setup?

Question: Location: US, NYC. I am doing a partial renovation of a small kitchen in a 2-family house, and trying to keep the cost down if possible. Plumbing done, cabinets and backsplash installed, countertop and sink are coming soon. At this late stage, I've discovered that NYC recently allowed garbage disposals (I always thought they were illegal), and I'm wondering how feasible it is to add one.
The setup is on the diagram below. Questions:

There is an approximately 2 foot long approximately horizontal drain pipe run (usual 1.75 inch PVC) between the vertical drain line and the P-trap. Most of this pipe is behind drywall and cabinets and cannot be realistically changed at this stage. Would a garbage disposal be strong enough to push waste through, or would things get stuck in the horizontal pipe?
And what if the pipe is not quite horizontal, but slopes slightly?
Are there height restrictions for where the garbage disposal's output should be in relation to the P-trap and the horizontal drain pipe?
The P-trap is under the center of the sink, but my sink model drains on the right side. Are there any restrictions on the shape or type of the drain connection from the garbage disposal to the P-trap?
There is no dedicated switchable electric outlet under the counter for a garbage disposal, so I thought of plugging a wireless garbage disposal switch into the same double outlet as the dishwasher. Bad idea? Otherwise, the wiring job would be a bit complicated and would require breaking the backsplash.
Generally, does anyone have experience with garbage disposals in NYC?
Comment: One of your questions is about the disposal "pushing" waste through the plumbing. That horizontal bit of pipe _should_ have a slight slope away from the drain. 1/4" per foot of run is the standard. This is what prevents water or other waste from settling in the pipe. The disposal doesn't "push" anything. It just grinds solids so they'll float in the water. It's _always_ recommended to run additional water after you turn off the disposal to ensure that ground solids are washed down the pipes instead of sitting in the disposal and/or any horizontal runs.
Comment: Disposers are not worth the trouble and expense. Many municipalities discourage the installation of disposers because of the extra load on the municipal sewer treatment service.
Comment: Have you located what you would use as a source of power for the disposer?  Installing the garbage disposal itself is fairly trivially easy, but if there isn't a *suitable* circuit already present, you likely need an electrician.  If the area below is unfinished, you may be able to do it with a homeowner's permit instead.  You should check the height of the drain pipe coming from the wall so you know how high the outlet of the disposal unit needs to be.
Comment: @K H, what would make a circuit suitable? I was planning to use the dishwasher power outlet located in the cabinet to the right of the sink. That outlet is not switch-controlled, but I thought that a wireless switch kit designed for garbage disposals would work.
Comment: I'm pretty sure the comments about disposals being banned is outdated. Many studies have shown that the ban was not necessary, and most, if not all, bans have been lifted. This is especially true for modern disposals.
Answer: Prompted by K H's comment, I've looked at the specs of my dishwasher model and garbage disposal, and the sum of their current draw is over 15 A. Not a good idea to plug that into one 15 A circuit.
So irrespective of plumbing questions, a garbage disposal would require adding a new electric circuit in the kitchen, which would be too expensive given my planned renovation budget.
Comment: One question: is the existing circuit wired in conduit, or was it done in cable (BX/AC or MC)?
Comment: I have no idea what's in the ceiling, but the outlets in the wall are on BX.


Empty Trash sound event?

Question: Is there any way to add a sound event every time I empty the trash on my Ubuntu system?
Comment: In Ubuntu 13.04 there is a sound as a hammer blow (that scares me sometimes) that it's warning me about what I intend to do. Also, a warning window appear in this sense. You don't have this behavior?
Comment: i too dont have this behaviour @RaduRădeanu , even no login sounds nothing except drumming one at the start, most of my friends dont have those sounds but some have ..
Comment: @Sushantp606 if you want startup sound, imho i can help you with that and can show you how to add that up. so that it can play on every login.
Comment: no @RaduRădeanu  i am using ubuntu 12.04 lts, and i don't have such behavior. any idea how i might add that event ( read as : even i want to get scared sometimes :P :P )
Comment: @KunalSangwan i knew  that for login , but if its about everything like logout,shutdown, events , caution and please do tell me..
Comment: @Sushantp606 How abt trying copy ubuntu sounds to /usr/share/sounds/ and configure them the same way u did for login ? Makes sense to me. Do share what u got. might as well be helpful in closing this thread up.
Answer:  Empty Trash Sound Workaround
      for Ubuntu 12.04.3
Maybe you will find my idea useful.
   After 2 months of searching for a solution to get a trash-empty sound
   in Ubuntu 12.04.3 I finally was able to put together something that works for me.
If anyone has an improved solution then please share.
You will note in the script below that I have chosen to use the "music123" app
which can be downloaded from the Ubuntu Software Centre and installed to the
/usr/bin folder.  I got the idea from an article on how to set up Ubuntu shutdown sound --> from here.
That one worked great also, I even added the Ubuntu start-up sound.
The following script also uses the commands "trash-empty" and "trash-list".
These commands are part of the "trash-cli" command line utility which was also downloaded from the Ubuntu Software Centre.
Linux Script to Empty Trash with sound of glass breaking.
#!/bin/bash
#
# Name of script: empty-trash.sh
# script to empty trash with confirmation and empty trash sound event
# This script is located in /usr/local/bin

SOUND = "/usr/share/sounds/ubuntu/stereo/trash-empty.ogg"
trash-list > ~/.local/share/Trash/files/trash.lst
file = ~/.local/share/Trash/files/trash.lst

if [ ! -s $file ]; then

        rm -f $file;
        zenity --info --text "TRASH is EMPTY"

else

        zenity --question --title "Confirm Yes/No" --text "EMPTY Trash Bin ?"

           case $? in

                0)
                trash-empty;
                /usr/bin/music123 $SOUND
                ;;

           esac

fi

If you have a trash bin on the desktop or elsewhere, it will continue to work properly and it will still show the full and empty trash bin icons. If you do not want to hear the trash-empty sound then you can right-click on your regular trash bin icon and empty the trash in the usual way.
To empty the trash and hear your chosen sound click on the launcher made for that purpose.  My trash-empty sound is that of breaking glass. You can choose whatever sound file you like, or make your own.
If you click on "Yes" in the zenity confirmation dialogue, then all the trash in all locations, including partitions and USB drives, will be emptied.
                                      ~.~

You can make an "Empty Trash" launcher and put it on your desktop to launch this script whenever you want to empty the trash. Make sure that you have made this script executable.

Attach a unique icon to the launcher.  This is the one I used:

This is the Zenity dialogue question box to confirm emptying of trash:

This is the Zenity dialogue info box that appears if the trash bin is empty
and you have clicked on the "Empty-Trash" launcher.

I added the above edit to provide the images that were not permitted during my initial post. I hope this extra information is useful.
 - walt -wladicus 2013.12.30
Comment: You are welcome ASCIIbetical. I am happy that my little bit of research not only worked for me, but has found a hopeful application for someone else. -_walt_
Comment: FYI - This script throws some errors for me on 14.04 LTS
Answer: For Ubuntu 14.04 and beyond I modified the script by wladicus that I found here to eliminate the errors I was getting due to some unwanted spaces and program flow and made some other minor customizations to insure dependencies are satisfied. You'll need to choose your own sound file and replace  /usr/share/sounds/ubuntu/stereo/GarbageTruckSounds.ogg on the SOUND= line below as that sound is no longer included with Ubuntu.
#!/bin/bash
# Name of script: empty-trash.sh
# script to empty trash with confirmation and empty trash sound event
# This script can be stored in /usr/local/bin or wherever you keep your scripts
# original script created trash.lst in the trash and so never reported "trash is empty"
# modified script to create trash.lst elsewhere and only remove it if the trash was to be emptied.
# utilized mplayer to play the sound rather than the original program as I didn't see the need to install another program.
# I also removed some spaces that were causing the script to throw errors and added a function to get dependencies as required.
function get_dependency
{
   exist="$(dpkg-query -l | grep "ii $@")"
   if [ "$exist" == "" ];
    then echo "$@ is required and not found. Attempt install Y/N"
    read -n 1 solve
    if [ $solve=={Yy} ]
    then sudo apt -y install "$@"
    else echo "Cannot continue as $@ is required."
    exit 1
    fi
    fi
}
get_dependency zenit? #full name zenity on this line caused issues. Used globbing to avoid this.
get_dependency trash-cli
get_dependency mplayer
 SOUND=/usr/share/sounds/ubuntu/stereo/GarbageTruckSounds.ogg
trash-list > ~/.local/share/trash.lst
file=~/.local/share/trash.lst

if [ ! -s $file ]; then
        zenity --info --text "TRASH is EMPTY"

else

        zenity --question --title "Confirm Yes/No" --text "EMPTY Trash Bin ?"

           case $? in

                0)
        rm $file;
                trash-empty;
                mplayer "$SOUND"
        ;;

           esac

fi

Note that this script requires zenity trash-cli and mplayer If they don't exist the script will attempt to install  them. Packages with a dpkg status of rc (removed but configuration files remain) will fail to be reinstalled. I noticed this anomaly in testing with the mplayer package. If you have this issue you can resolve it by removing the configuration files of the offending package with the command sudo apt purge [packagename] which in my case was sudo apt purge mplayer
Also note that 2 of these packages reside in the universe repository and installation of dependancy installation will fail if you don't enable the universe repository first.
Comment: Stumbled across this awesome script purely by accident!
Comment: @WinEunuuchs2Unix I'm pleased you like it!
Answer: First run "sudo apt-get install mpg123"  to play the mp3 files.
Then I created a shell script called "/home/yourname/scripts/check_trash.sh"
#!/bin/bash
cd /home/yourname/.local/share/Trash/files
while true
do
   TOT1="$(ls -1 | wc -l)"
   sleep 2
   TOT2="$(ls -1 | wc -l)"
   if [ "$TOT1" != "$TOT2" ];
   then
     mpg123 -q /home/yourname/trash.mp3
  fi
done

then download a mp3 file and copy it to "/home/yourname/trash.mp3"
Then add the program "/home/yourname/scripts/check_trash.sh" so it runs on bootup:
https://www.howtogeek.com/103640/how-to-make-programs-start-automatically-in-linux-mint-12/
Comment: Mint is not an official Ubuntu variant, so off-topic here.  Better copy-paste the instructions over from the link to here if you can test on Ubuntu.
Comment: That's a neat workaround. If one wanted they could use the `inotifywait` command instead.

Empty Trash sound event?


possible resulting values of shared variable x

Question: If we have two different processes with shared variable x, what are the possible values of x when both processes have completed?
Process A is running the following for-loop:
for (i = 0; i < 5; i++)
    x++

Process B is running:
for (j = 0; j < 5; j++)
    x--

I want to say x can be anywhere from -5 to 5, assuming x is initialized to 0.  Is this true?  Please include an explanation.
Answer: Assuming the compiler will generate a single instruction that will increment x++ or decrement x--, it will have the same value it had before the for loops were executed after both threads are done, which is 0.
Otherwise, let's take the following example:
x++:
1. MOV R1, x     //register R1 receives x
2. INC R1        //register R1 is incremented
3. MOV x, R1     //store decremented x back to the memory

and
x--:
1. MOV R1, x     //register R1 receives x
2. DEC R1        //register R1 is decremented
3. MOV x, R1     //store decremented x back to the memory

It is quite obvious now that if one thread looses the CPU after executing line 1, it will have a value which is not updated, which will lead to a race condition and the variable will then have any value beetwen -5 and +5 after both threads are done with their execution, as you pointed out, depending on the different order of execution that both threads can have.
Answer: You are correct. Imagine this scenario:
Both process A and process B (let's call them thread for clarity), get to the first iteration of the loop. Both threads retrieve the value of x (0), keep a local copy of that, compute their increment/decrement, and then race each other to update the register/memory containing x. Let's say A stores first, and B stores second. The resulting value of x is now -1.
Repeat this four more times and x ends up as -5.
Reverse the race above, and x ends up as 5.


Transparent PNG image with TImageList

Question: I'm using Delphi XE.
I added a TAdvGlowButton on my form and added a TImageList with one transparent PNG image as its source for images. When I view the form in the design mode, the button looks exactly right and the image is transparent. However, when I run the program, the background of the image turns to solid black. If I undestood correctly, this is not a bug of the TAdvGlowButton but TImageList.
Is there a way to fix this without using any 3rd party components?
Comment: Have you set the image list `ColorDepth` property to `cd32bit`? I can see a transparent image for a PNG image, held in an image list, and shown as a toolbar button. So I think `TImageList` can handle such images.
Comment: Yes, ColorDepth is set to cd32bit and DrawingStyle to dsTransparent.
Answer: I solved this by opening the project settings from Project Manager and checked Application -> Enable runtime themes. What kind of silly option is this? When would anyone want to not enable runtime themes?
Comment: It is probably a port from an earlier version of Delphi, where this option was not available. IIRC, the default when upgrading those projects is setting this switch to false.
Comment: Since the default setting for this option is to be checked, you should be asking your self the question, "When would anyone want to **not** enable runtime themes?"  I think you would probably disable runtime themes if you were using other components that did not run when themes were enabled.
Comment: It might be that the previous developers unchecked that. I'm just taking my first steps with this new codebase.

Transparent PNG image with TImageList


Something confusing about cin and >> of C++

Question: //win10 vs2017
#include<iostream>
using namespace std;
typedef unsigned int uint;
uint dis[1002][1002];
uint cost[1002][1002];
uint v, e;
int main()
{
    while (cin >> v, v) {
        cin >> e;
        int start, tmn;
        for (int i = 0; i < e; i++)
            cin >> start >> tmn >> dis[start][tmn] >> cost[start][tmn], dis[tmn][start] = dis[start][tmn], cost[tmn][start] = cost[start][tmn];
        cin >> start >> tmn;
    }

    system("pause");
    return 0;
}

When I run this program I get an exception.

I put a breakpoint and found the source of the problem.
cin >> start >> tmn >> dis[start][tmn] >> cost[start][tmn],

But why cannot I write it like that?
Comment: Maybe your MSVC version is too old to support the [guaranteed evaluation order](https://stackoverflow.com/a/38501596/5376789) in C++17.
Comment: This isn't the issue here, but the `cin >> start >> tmn;` line at the end of the `while` loop doesn't store the values anywhere they'll be used. The `start` and `tmn` variables are re-declared on the next iteration, and might not keep the same value.
Answer: The reason is that, in the partial statement
cin >> start >> tmn >> dis[start][tmn]

the evaluation of expressions start, tmn, and dis[start][tmn] are unsequenced with respect to each other, or to the first call of the stream's operator>>().
One possible sequencing permits dis[start][tmn] to be evaluated (to obtain a reference to an array element) before calling the relevant operator>>() functions that read start and tmn.     In that case start and tmn are uninitialised (since their values have not been read) and accessing their values (necessary to evaluate dis[start][tmn]) gives undefined behaviour.
The solution (which also helps make the code more readable for humans) is to avoid complex expressions that that rely on (or in your case, incorrectly assume) particular orders of evaluation.
Instead of (blech!)
for (int i = 0; i < e; i++)
     cin >> start >> tmn >> dis[start][tmn] >> cost[start][tmn],
         dis[tmn][start] = dis[start][tmn], cost[tmn][start] = cost[start][tmn];

(I've broken the statement into two lines) break the input statement into separate statements - which will be sequenced relative to each other - and avoid using the , operator to achieve other effects in the same statement.
for (int i = 0; i < e; i++)
{
    cin >> start >> tmn;
    cin >> dis[start][tmn] >> cost[start][tmn];

    dis[tmn][start] = dis[start][tmn];
    cost[tmn][start] = cost[start][tmn];
}

It would probably also be a good idea to check that start and tmn are valid, before trying to read dis[start][tmn] and cost[start][tmn].
Although you haven't asked about it, the while (cin >> v, v) probably also does not do what you think it does.
Comment: In C++17 the evaluation order is guaranteed and `cin >> start >> tmn >> dis[start][tmn]` should actually work. Also, I'm not sure what you think the OP thinks `while (cin >> v, v)` does, but I think it reads an unsigned number from `cin` and goes through the loop if the number isn't zero (and a comma does guaranteed sequencing back before even C++11, so it should be guaranteed).
Comment: @Daniel - and before C++17, it gives undefined behaviour in a manner completely consistent with what the OP describes.   There are few compilers at present that compile as C++17 by default, and obvious beginners (like here) are unlikely to have enabled C++17.   I didn't see any point of explaining C++17 to a beginner who probably won't understand the distinction, let alone be using the latest available compiler or know enough about their compiler to enable that mode.   Your interpretation of `cin >> v,v` is also wrong.
Comment: I mention it because I believe the official Stack Overflow policy is to treat the [tag:c++] tag as referring to the latest version unless otherwise stated, and because if somebody comes across this answer while using C++17 it would be helpful to know this isn't the reason.
Comment: And other than potentially not reading a number if `cin >> v` fails (and then having UB or leaving `v` at the same value, depending on if it had ever been successful), what is wrong with my interpretation of the `while` statement? The only other problem I can think of with my interpretation would be if either `unsigned int` or `std::istream` overrode `operator,`, which I'm pretty sure they don't. Saying it doesn't do what it looks like without explaining is less than useful.
Comment: I'm still hoping you answer my question about `while (cin >> v, v)`; it at least [seems to compile to the code I expect](https://godbolt.org/g/5wXJ2s). Maybe there's an edge case I didn't think of, or it's UB and gcc 8.1 with the options I gave happens to interpret it the way I expect, but I honestly cannot think of anything else.
Answer: The input sequence must be >>'start', then >>'dis[start][tmn]', but maybe compiler optimize 'dis[start][tmn]' as int&. So before input, the 'dis[start][tmn]' is regarded as int&, thus leading to error.
here is assembly code.
See in evaluation order in Bjarne Stroustrup's homepage.
Comment: The type of `dis[start][tmn]` is `int`. Maybe you mean lvalue, but what's the relationship with evaluation order? In addition, if you want to share a code in Compiler Explorer, you should click the `Share` menu at the top right corner, and use that link.
Comment: @xskxzr I still believe it's int&, for example, x[2] = *(x+2) is reference. And I mention the order to illustrate 'dis[start][tmn]' is regarded as int& **before** the input operation, thus leading an error(maybe my statement is misleading, I'm sorry). Finally, thanks a lot for your guidance on using StackOverflow (Im a novice here).
Comment: See [here](http://en.cppreference.com/w/cpp/language/operator_member_access#Built-in_subscript_operator), "The result of this expression has the type T". I still don't see why the type affects the evaluation order. Why is `int&` so special that you **infer** the evaluation happens before the input from the fact that it has type `int&`?
Comment: @xskxzr You're right. And I guess the evaluation of parameters is before function call, but the offset 'start' has not been initialized. Is this right? Please correct me if I am wrong. Thanks in advance.
Comment: You can see the other answer.


VS Code not identifying any changes made to the code:

Question: Any changes I make to my code aren't doing anything. I am using three things html, flask and python. Any code change I make to my python or html code is not getting implemented on the browser when I am trying to run it.IT is only running older version of the code.
How can I rectify this error of vscode?
Comment: Did you restart your flask instance?
Comment: How can I restart it ?
Comment: Ctrl+C in the terminal that is running it and then start it again.
Comment: I do this every time I make any changes. But still not showing any difference.
Answer: Make sure you're refreshing the page if you're opening a HTML file. If you're accessing the python server make sure to restart it every time you make changes to the code. The way to do it is ctrl+c in the terminal and running the command again. There are ways to make this happen automatically, refer here for more information
Comment: I do this every time I make any changes. But still not showing any difference.
Comment: Are you saving the files? @RitikaGupta
Comment: Yes. After making changes to my code I always do ctrl + s after that.
Answer: Did you start your flask server in debug mode?
from Python
<code>app.run(debug=True)
</code>
or from terminal
<code>$ export FLASK_DEBUG=1
$ flask run
</code>
Comment: I am doing in debug mode only from the starting.
Answer: Try to run in incognito once. Or try after clearing cache.


UITextField - Next Button (2)

Question: I have used all the suggestions on the forum and still can not go from one uitextfield to the other by hitting the next button. Am i missing something or have something out of place. Any help would be great. Thanks.
Here is all of my code:
//.h file
#import <UIKit/UIKit.h>

@interface IncomeTransactionViewController : UIViewController

@property (strong, nonatomic) IBOutlet UITextField *businessField;
@property (strong, nonatomic) IBOutlet UITextField *memoField;
@property (strong, nonatomic) IBOutlet UITextField *amountField;

@end

//.m file
#import "IncomeTransactionViewController.h"

@interface IncomeTransactionViewController ()

@end

@implementation IncomeTransactionViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

     //Business UITextField
    self.businessField = [[UITextField alloc] initWithFrame:CGRectMake(20, 300, 280, 40)];

    self.businessField.returnKeyType = UIReturnKeyNext;
    self.businessField.placeholder = @"Business";
    self.businessField.autocapitalizationType = UITextAutocapitalizationTypeWords;
    self.businessField.adjustsFontSizeToFitWidth = TRUE;
    self.businessField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.businessField];

    //Memo UITextField
    self.memoField = [[UITextField alloc] initWithFrame:CGRectMake(20, 350, 280, 40)];

    self.memoField.returnKeyType = UIReturnKeyNext;
    self.memoField.placeholder = @"Memo";
    self.memoField.autocapitalizationType = UITextAutocapitalizationTypeWords;
    self.memoField.adjustsFontSizeToFitWidth = TRUE;
    self.memoField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.memoField];

    //Amount UITextField
    self.amountField = [[UITextField alloc] initWithFrame:CGRectMake(20, 400, 280, 40)];

    self.amountField.returnKeyType = UIReturnKeyDone;
    self.amountField.placeholder = @"Amount";
    self.amountField.autocapitalizationType = UITextAutocapitalizationTypeWords;
    self.amountField.adjustsFontSizeToFitWidth = TRUE;
    self.amountField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.amountField];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.amountField) {
        [textField resignFirstResponder];

    } else if (textField == self.businessField) {
        [self.businessField resignFirstResponder];
        [self.memoField becomeFirstResponder];

    } else if (textField == self.memoField) {
        [self.memoField resignFirstResponder];
        [self.amountField becomeFirstResponder];
    }
    return YES;
}

@end

Comment: I don't think you need the resignFirstResponder calls in the business and memo if blocks. Also, have you tried returning NO?
Comment: possible duplicate of [UITextField - Next Button](http://stackoverflow.com/questions/26050306/uitextfield-next-button)
Answer: You have to take the <UITextFieldDelegate> in your .h file
@interface IncomeTransactionViewController : UIViewController  <UITextFieldDelegate>

and in your .m file you need to assign delegate like this
self.businessField = [[UITextField alloc] initWithFrame:CGRectMake(20, 300, 280, 40)];
self.businessField.delegate = self; // add this line
self.businessField.returnKeyType = UIReturnKeyNext;
self.businessField.placeholder = @"Business";
self.businessField.autocapitalizationType = UITextAutocapitalizationTypeWords;
self.businessField.adjustsFontSizeToFitWidth = TRUE;
self.businessField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:self.businessField];

//Memo UITextField
self.memoField = [[UITextField alloc] initWithFrame:CGRectMake(20, 350, 280, 40)];
self.memoField.delegate = self; // add this line
self.memoField.returnKeyType = UIReturnKeyNext;
self.memoField.placeholder = @"Memo";
self.memoField.autocapitalizationType = UITextAutocapitalizationTypeWords;
self.memoField.adjustsFontSizeToFitWidth = TRUE;
self.memoField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:self.memoField];

//Amount UITextField
self.amountField = [[UITextField alloc] initWithFrame:CGRectMake(20, 400, 280, 40)];
self.amountField.delegate = self; // add this line
self.amountField.returnKeyType = UIReturnKeyDone;
self.amountField.placeholder = @"Amount";
self.amountField.autocapitalizationType = UITextAutocapitalizationTypeWords;
self.amountField.adjustsFontSizeToFitWidth = TRUE;
self.amountField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:self.amountField];

This should do it. let me know if it still doesn't work
Comment: Thank you so much. I thought i was missing something. It works great.
Comment: @user3806600 any time.. :)

UITextField - Next Button (2)


java.io.IOException: Incorrect function while runing grails webapp on guest os

Question: I have simple grails app, it works good at my system, but it is hard to share it with other people where everyone has some different settings so i thought it woudl be good to create vagrant box so everyone coudl run it on os with same settings. Ok so let get us down to the business on guest os i can run app also(app is in shared folder) but i recive errors
Exception in thread "main" java.lang.RuntimeException: java.io.IOException: Incorrect function.

at org.grails.io.watch.WatchServiceDirectoryWatcher.addWatchDirectory(WatchServiceDirectoryWatcher.java:183)
at org.grails.io.watch.WatchServiceDirectoryWatcher.addWatchDirectory(WatchServiceDirectoryWatcher.java:153)
at org.grails.io.watch.DirectoryWatcher.addWatchDirectory(DirectoryWatcher.java:111)
at grails.boot.GrailsApp.configureDirectoryWatcher(GrailsApp.groovy:299)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1426)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:174)
at grails.boot.GrailsApp.enableDevelopmentModeWatch(GrailsApp.groovy:110)
at grails.boot.GrailsApp.run(GrailsApp.groovy:65)
at grails.boot.GrailsApp.run(GrailsApp.groovy:347)
at grails.boot.GrailsApp.run(GrailsApp.groovy:336)
at grails.boot.GrailsApp$run.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
at baseapp.Application.main(Application.groovy:8)

Caused by: java.io.IOException: Incorrect function.
at sun.nio.fs.WindowsWatchService$Poller.implRegister(WindowsWatchService.java:420)
at sun.nio.fs.AbstractPoller.processRequests(AbstractPoller.java:260)
at sun.nio.fs.WindowsWatchService$Poller.run(WindowsWatchService.java:580)
at java.lang.Thread.run(Thread.java:745)

I was trying to figure out what is wrong, so my only guess based on WatchServiceDirectoryWatch.java is that grails is trying to set some dir which it will be scanning(i dont know for what?) but because project is in shared folder grails is trying to set dir to which it does not have access(guessing). My question is what  cant i do to do not recive that errors?
Answer: I think you should go deeper and look at grails.boot.GrailsApp at grails.boot.GrailsApp.configureDirectoryWatcher(GrailsApp.groovy:299) which

Creates and returns a file change listener for notifying the plugin manager of changes.

and then at grails.boot.GrailsApp.enableDevelopmentModeWatch(GrailsApp.groovy:110)
which is inside a function named enableDevelopmentModeWatch.
Comment: Thanks for advice, so i think it only appears in development mode when grails `auto-reloading` option is up.


Where should I learn shaders as a vulkan user?

Question: I have no prior experience with any other graphics low level libraries and I have barely any clue how shaders work, any book related to shadings is bloated with opengl code and is demoralizing.
Comment: Is there some reason why you can't simply learn what that "bloated" "opengl code" is doing? Learning Vulkan without any graphics knowledge is a Herculean task; better to start with an API that has training wheels.
Answer: Perhaps you should begin with classic opengl shaders in a more friendly enviroment. ShaderToy is a great community where you'll find tons of tutorials, code examples, masterpieces and great experts that comment everyday.


Galois group of order 2^4

Question: Find the galois group the polynomial
$f(X)=(X^2-2)(X^2-3)(X^2-5)(X^2-7)$ over $\mathbb{Q}$.
A splitting field for $f(X)$ is $K=\mathbb{Q}(\sqrt{2},\sqrt{3},\sqrt{5},\sqrt{7})$.
We must have $[\mathbb{Q}(\sqrt{2},\sqrt{3},\sqrt{5},\sqrt{7}):\mathbb{Q}]=2^4$.
Moreover
$Gal(K/\mathbb{Q})$  is abelian, since if $\sigma\in{Gal(K/\mathbb{Q})}$ then
$\sigma^2=1$, because $\sigma(\sqrt{2})=\pm\sqrt{2}$ (similary $\sigma(\sqrt{3}),\sigma(\sqrt{5}),\sigma(\sqrt{7})$).
By the classification of finite abelian groups; can I conclude that $Gal(K/\mathbb{Q})\approx Z_2\times{Z_2}\times{Z_2}\times{Z_2}$ ?
Thanks you all.
Comment: The most difficult step here is on line four. As a teacher I would want you to elaborate. It is true, but a rigorous proof (in general) requires a useful lemma and its careful use. See [this argument by Bill Dubuque](http://math.stackexchange.com/a/113701/11619) and follow up on the links given there. +1 for the rest of the argument which works as described.
Answer: You've explicitly identified the generators of the Galois group! You don't need to invoke the classification of finite(ly-generated) abelian groups here.
You know that the Galois group must have order $16$, and it's easy to show that the group generated by the maps
$$\sqrt{2} \mapsto -\sqrt{2}, \quad \sqrt{3} \mapsto -\sqrt{3}, \quad \sqrt{5} \mapsto -\sqrt{5}, \quad \sqrt{7} \mapsto -\sqrt{7}$$
is isomorphic to $Z_2 \times Z_2 \times Z_2 \times Z_2$, which has order $16$. Moreover each of these maps must be in the Galois group, so this must actually be the Galois group of your polynomial over $\mathbb{Q}$.

Galois group of order 2^4


The Literature Meta has our logo graphic, and vice-versa

Question: As reported on the Literature Meta, the Literature Meta has our logo.  We have theirs:

Looks like they got switched.  (Reposting here to hopefully spare some confusion.)
Answer: This will be fixed in the next deployment.
Comment: I think we had the correct logo last night, but we lost it again :(


Glassfish warning when i try to open an existing Java Project

Question: the project itself is located in my home-directory, netbeans and glassfish each installed to opt. when i start IDE and open java project i get following warning five times:
/opt/glassfish-3.0.1/glassfish/domains/domain1/config/wss-server-config-2.0.xml (Permission denied)
thanks guys
Answer: What is the permission of the glassfish and netbeans folder in opt? You can verify that with:
ls -l /opt/

Depending on the result you might need to change the ownership of the folder to your username. You can do that with the following commands: (replace username with your username, and press tab to autocomplete versions of the software)
sudo chown username.users /opt/glassfish-<TAB>
sudo chown username.users /opt/netbeans-<TAB>

Answer: I tried renaming the folder nbproject in the project folder, which worked. Simple :-)


Kenmore 96573230 Dryer Heating Element Too Hot? (420° F)

Question: Is it normal for the heating element metal cover to reach 420°F?
https://i.stack.imgur.com/MnpC9.png
I just replaced the upper thermal cut-off fuse and it blew within minutes. The cover location of the cut-off fuse doesn't reach 420°F... closer to 200°F.
Comment: That sounds way hot to me is the vent exhaust blowing air? I would verify there is sufficient air flow across the coil to pushing air into the dryer, I have found the outlet plugged with lint and paper causing the thermal fuse to open.
Comment: All the airflow seems fine. All the coils glow in the heating element... I'm just worried somehow the element is running too hot for some reason. This temperature was after running it for about a couple minutes. Not long at all.
Comment: @FishBulbX - Were you evaluating the airflow when the dryer was pulled away from the wall and disconnected from the vent pipe? If so the point is that the vent pipe may be restricting airflow. If not cleaned on a regular basis this a common problem.
Comment: The flow seemed normal leaving the house, but yes, good point that I should be testing without the vent connected.
Comment: After further testing... seems like partially obstructed vent was the issue. I replaced the vent exhaust and the dryer is now operating correctly.
Answer: After further testing... seems like partially obstructed vent was the issue. I replaced the vent exhaust and the dryer is now operating correctly.


jquery: How do i fade in on load each image in an array of images?

Question: I'm really new to Jquery, however, i've done research and tried hard to do this. I have successfully made one image to do what i want:

preload the image( img = new Image(); $(img).attr('src', someurl);)
append it to a container
fade in the image ( using .hide() and .fadeIn(500) )
on load add some class and hide a .gif image with the loading animation

using this code:

var img = new Image();
$(img).attr('src', 'images/thumbnails/thumb1.png').attr('alt', 'thumbnail' + 1);
$(img).appendTo($('.thumbnail')).hide().fadeIn(400);
$('.thumb img').load(function(){
  $('.loader').fadeOut(300);
  $(this).addClass("thumbimage");
});

where .loader is class added to a div that shows the loading.gif animation.
Now, what i want to achieve is to implement this on an array of image srcs and this is what i have so far:

var imagesrc = [ someurl, someurl, ... ];
$(document).ready(function(){
 var arr = new Array();
 function loadimage() {
  for (i = 0; i < imagesrc.length; i++) {
   arr[i] = new Image();
   $(arr[i]).attr('src', imagesrc[i]);
   $(arr[i]).attr('alt', 'thumbnail' + i);
   $(arr[i]).hide().appendTo($('.thumbnail').eq(i)).fadeIn(300);
  }
 }
 loadimage();
    $('.thumbnail img').load(function(){
  var par = $(this).parent();
  var row = par.parent();
  var indexrow = row.index('.thumbrow');
  var thumbindex = par.index('.thumb') + 3*indexrow;
        //^ this calculates which loading.gif div to fade out
  $('.loader').eq(thumbindex).fadeOut(200);
  $(this).addClass("thumbimage");
 });
});

I've also tried to move the .append() into the .load(..) and failed.
Comment: Possible duplicate of http://stackoverflow.com/questions/29044852/preloading-images-in-html
Answer: ['url1', 'url2'].forEach(function(imageUrl){

    var img = new Image();
    $(img).attr('src', imageUrl).attr('alt', 'thumbnail' + 1);
    $(img).appendTo($('.thumbnail')).hide().fadeIn(400);
    $('.thumb img').load(function(){
      $('.loader').fadeOut(300);
      $(this).addClass("thumbimage");
    });

});

Answer: There may be some confusion with ".thumbnail img", "thumbimage". and "thum img". Are all three separately being used correctly, as you laid them out?
At the end, instead of "thumbimage" in $(this).addClass("thumbimage"); you may want to use "thumb img".


Handle "Cannot access a closed resource set"

Question: I have a website with several languages in a database. From the database I use ResXResourceWriter to create my .resx files. This is working really good but sometimes I get this exception:
<code>MESSAGE: Cannot access a closed resource set.
SOURCE: mscorlib
FORM:
QUERYSTRING:
TARGETSITE: System.Object GetObject(System.String, Boolean, Boolean)
STACKTRACE:    at System.Resources.RuntimeResourceSet.GetObject(String key, Boolean ignoreCase, Boolean isString)
  at System.Resources.RuntimeResourceSet.GetString(String key, Boolean ignoreCase)
  at System.Resources.ResourceManager.GetString(String name, CultureInfo culture)
  at System.Linq.Expressions.Expression.ValidateStaticOrInstanceMethod(Expression instance, MethodInfo method)
  at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable`1 arguments)
  at System.Data.Linq.DataContext.GetMethodCall(Object instance, MethodInfo methodInfo, Object[] parameters)
  at System.Data.Linq.DataContext.ExecuteMethodCall(Object instance, MethodInfo methodInfo, Object[] parameters)
  at Business.DatabaseModelDataContext.Web_GetMostPlayedEvents(String cultureCode)
  at Presentation.Default.Page_Load(Object sender, EventArgs e)
  at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
  at System.Web.UI.Control.LoadRecursive()
  at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
</code>
I don't know why this is happening or how to solve it. Does anyone know anything about this?
Thanks,
Philip
Answer: I suspect you closed your DataSource prematurely or didn't close it at all when your program routine is about to end?
Comment: No it is nothing wong with the DataSource, for that I am sure. It must be something with how the .resx are created or that I miss something. But they are always created succesfully but I am getting the exception when they are used in my website.


why does $\lim_{s\to\infty}(\int^{\infty}_{0^+}e^{-st}\frac{df}{dt}dt) =0$

Question: I am learning Laplace transform and don't understand why does
$$\lim_{s\to\infty}(\int^{\infty}_{0^+}e^{-st}\frac{df}{dt}dt)=0$$
It's in the explanation of initial theorem. Here is what I can get
$$\lim_{s\to\infty}(\int^{\infty}_{0^+}e^{-st}\frac{df}{dt}dt)=\lim_{s\to\infty}(\int^{f(\infty)}_{f(0^+)}e^{-st}df)=\lim_{s\to\infty}(f(0^+))$$
Comment: It's part of the assumptions - the Laplace transform is most effective when it is defined on infinitely differentiable functions whose rate of growth at infinity is not exponential.
Answer: Assume $f$ is well-behaved. Partial integration gives
\begin{eqnarray*}
\int_{0}^{\infty }dt\exp [-st]\partial _{t}f(t) &=&\left\vert \exp
[-st]f(t)\right\vert _{0}^{\infty }+s\int_{0}^{\infty }dt\exp [-st]f(t) \\
&=&f(0^{+})+\int_{0}^{\infty }du\exp [-u]f(\frac{u}{s})
\end{eqnarray*}
Here
\begin{equation*}
\int_{0}^{\infty }du\exp [-u]f(\frac{u}{s})=\int_{0}^{a}du\exp [-u]f(\frac{u%
}{s})+\int_{a}^{\infty }du\exp [-u]f(\frac{u}{s})
\end{equation*}
where both contributions vanish as $s\rightarrow \infty $.


How to modify the pipeline name in gitlab. I am getting the Merge request title as the pipeline title

Question: Hi anyone has any idea how to set the variable name in gitlab pipeline.
I am having an issue where the job title name is always shown as the merge request title.

I already tried finding apis to modify the title of job but to no luck.
I did find GET api/v4/projects/ of gitlab but I find something weird here as well. The title and message is not the commit message but the same MR title.

Can anyone help. Thanks in advance
[EDIT]

The commits have different messsage
The pipeline is not being run on the same commit as shown from SHA of the pipeline
The issue is basically always the MR title is being used as pipeline name
Answer: Pipeline objects don't have a "Title" attribute. What you're seeing on that page is the commit message/title. GitLab displays that so it's easy to differentiate them on the page.
These pseudo-titles will be the same in these two scenarios:

You're running multiple pipelines on the same commit, for example triggers, schedules, etc. that run against the latest commit in a branch. If there aren't new commits between these pipelines, they will run on the same commit.
If you have multiple commits with the same message. You can see this is the case in your screenshot. The commit ID sha's are different, but the commit message is the same.
Comment: The commits have different messsage
    The pipeline is not being run on the same commit as shown from SHA of the pipeline
    The issue is basically always the MR title is being used as pipeline name.
Thats the whole issue here


join in sql query gives column ambigios error

Question: table name - city
columns -city_id,city_name
table - state
column  -state_id,state_name
table name - category
column name - category_id,category_name
table name -  news
column name -  cat_id,state_id,city_id,headline,story ,author etc..
I nedd to select all column from city,state,and category table for inserting id in news table....
for that I create sql query and join all above three table but this shows error ..plz help me...
Column 'state_id' in field list is ambiguous
Column 'city_id' in field list is ambiguous
Column 'category_id' in field list is ambiguous
I need to return all columns from city,state and category table
SELECT city_name,city_id,state_id,category_id,state_name,category_name,headline,author,story,source,photo,date from news left join
 city on news.city_id=city.city_id left join state on news.state_id=state.state_id left join category on news.cat_id=category.category_id;

Answer: You need to specify the tables where the columns come from.  city_id is ambiguous in the select list.  I think this is the right aliases:
SELECT c.city_name, c.city_id, s.state_id, ca.category_id, s.state_name, ca.category_name,
       n.headline, n.author, n.story, n.source, n.photo, n.date
from news n left join
     city c
     on n.city_id= c.city_id left join
     state s
     on n.state_id = s.state_id left join
     category ca
     on n.cat_id = ca.category_id;

Note that I introduced table aliases.  These help make the query easier to write and to read.
Comment: Unknown column 'c.city_name' in 'field list' then also for  Unknown column 'c.city_id' in 'on clause' same for category and state and all
Answer: Reason for the same is, you have state_id both in state and news table (same for city_id which is in City as well as news table) to name few and SQL engine is confused which one to use. Hence i would advice you to use table alias or table name as prefix in the select fields.