text:
Q: Get Data for every weeks average of high and low prices I have table named as
FP_BASIC_BD

whose structure is like as follows.
Name           Null?    Type
-------------- -------- ------------
FS_ID          NOT NULL VARCHAR2(20)
DATE           NOT NULL DATE
CURRENCY                CHAR(3)
PRICE                 FLOAT(126)
PRICE_OPEN            FLOAT(126)
PRICE_HIGH            FLOAT(126)
PRICE_LOW             FLOAT(126)
VOLUME                FLOAT(126)

For any value of FS_ID I would like to calculate
weekends date
week start date
average(High of PRICE_HIGH+Low of PRICE_LOW)

for all the weeks.
Weekend is considered as Friday IF Fridays data not available then try to get 1 or any day before but after or equal to Monday of that week.
Week Start is considered as Monday. If Mondays data not available then get 1 or any day ahead but less or equal to to the weekend in above step.
Task of getting weekend and week start dates can be done in different query. But i want to use it as a range in a single query and get the required average.

A: First, please don't use Oracle keywords (e.g. date) as column names.
Second, your description of how you want to calculate the average is ambiguous, so I included a couple of options.
I think this should work to get your week start / end dates.
select
    trunc("DATE", 'IW') as week,
    min(trunc("DATE")) as week_start,
    max(trunc("DATE")) as week_end,
    (max(price_high) + min(price_low)) / 2 as avg_price_weekly,
    avg(price_high+price_low) as avg_price_daily
from fp_basic_bd
where to_char("DATE", 'DY') not in ('SAT','SUN')
group by trunc("DATE", 'IW');

From your description, I'm guessing you don't have any Saturday/Sunday dates in this table. If you do, and you specifically want to exclude them from this query, let me know and I'll update my answer.
Edit: updated to exclude weekend days (sat/sun).


text:
Q: Difficulty deploying Node API because of JWT Hello developer friends!
I already concluded an (academic) e-commerce project a few months ago and did other projects later... including my portfolio... and I was waiting to complete them to deploy it and attach it to the portfolio.
It turns out that in the meantime Heroku withdrew free access in November as you know...but I managed to find a way to do it with Render.
The front-end and back-end are already running ... but I'm having some difficulty configuring the communication between the two.
I've been looking and seeing some tutorials to configure the environments... but it's a little confusing for me to apply them in the code because the course I took didn't teach about the production environment.
The application on my localhost works perfectly but when accessing the API in production I see that the problem is probably a JWT token but I can't configure it.
Does anyone have a solution that could help me?
Here are the links of the deploys if you need to check:
https://e-commerce-burgershop-api.onrender.com/
https://e-commerce-burgershop.onrender.com/
Repositories:
https://github.com/ed-radanovis/Burgershop_fullstack_project-backend
https://github.com/ed-radanovis/Burgershop_fullstack_project-frontend
[when accessing the API this message appears.]
(https://i.stack.imgur.com/niAwY.png)
If anyone can help me, I'll be immensely grateful because that's all I need to complete my portfolio and try to apply for a vacancy as a Dev.
I tried to configure the environment with dot env files and I also tried to configure it directly on the Render platform without success.  As I mentioned earlier, I'm a beginner and this is my first Full-stack application deployment and I don't know how to proceed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Matrix equation $Z - {}^t Z =c A Z$ I would like to solve the following matrix equation, with $Z$ as the unknown matrix,
$$
Z - {}^t Z = c \, \Gamma G Z
$$
where the matrices $\Gamma$ and $G$ are both symmetric and invertible and c is a constant.
So I wonder if anyone can tell me if it is possible to solve this equation or if i have to do it component by component, that i'd prefer to avoid.
Thank you


text:
Q: Find number of continuous subarray having sum zero You have given a array and You have to give number of continuous subarray which the sum is zero.
example:
1)  0 ,1,-1,0 => 6 {{0},{1,-1},{0,1,-1},{1,-1,0},{0}};
2)  5, 2, -2, 5 ,-5, 9 => 3.

With O(n^2) it can be done.I am trying to find the solution below this complexity.

A: Consider S[0..N] - prefix sums of your array, i.e. S[k] = A[0] + A[1] + ... + A[k-1] for k from 0 to N.
Now sum of elements from L to R-1 is zero if and only if S[R] = S[L]. It means that you have to find number of indices 0 <= L < R <= N such that S[L] = S[R].
This problem can be solved with a hash table. Iterate over elements of S[] while maintaining for each value X number of times it was met in the already processed part of S[]. These counts should be stored in a hash map, where the number X is a key, and the count H[X] is the value. When you meet a new elements S[i], add H[S[i]] to your answer (these account for substrings ending with (i-1)-st element), then increment H[S[i]] by one.
Note that if sum of absolute values of array elements is small, you can use a simple array instead of hash table. The complexity is linear on average.
Here is the code:
long long CountZeroSubstrings(vector<int> A) {
    int n = A.size();

    vector<long long> S(n+1, 0);
    for (int i = 0; i < n; i++)
        S[i+1] = S[i] + A[i];

    long long answer = 0;
    unordered_map<long long, int> H;
    for (int i = 0; i <= n; i++) {
        if (H.count(S[i]))
            answer += H[S[i]];
        H[S[i]]++;
    }

    return answer;
}

A: This can be solved in linear time by keeping a hash table of sums reached during the array traversal. The number of subsets can then be directly calculated from the counts of revisited sums.
Haskell version:
import qualified Data.Map as M
import Data.List (foldl')

f = foldl' (\b a -> b + div (a * (a + 1)) 2) 0 . M.elems . snd
  . foldl' (\(s,m) x -> let s' = s + x in case M.lookup s' m of
                          Nothing   -> (s',M.insert s' 0 m)
                          otherwise -> (s',M.adjust (+1) s' m)) (0,M.fromList[(0,0)])

Output:
*Main> f [0,1,-1,0]
6

*Main> f [5,2,-2,5,-5,9]
3

*Main> f [0,0,0,0]
10

*Main> f [0,1,0,0]
4

*Main> f [0,1,0,0,2,3,-3]
5

*Main> f [0,1,-1,0,0,2,3,-3]
11

A: C# version of @stgatilov answer https://stackoverflow.com/a/31489960/3087417 with readable variables:
        int[] sums = new int[arr.Count() + 1];
        for (int i = 0; i < arr.Count(); i++)
            sums[i + 1] = sums[i] + arr[i];

        int numberOfFragments = 0;
        Dictionary<int, int> sumToNumberOfRepetitions = new Dictionary<int, int>();

        foreach (int item in sums)
        {
            if (sumToNumberOfRepetitions.ContainsKey(item))
                numberOfFragments += sumToNumberOfRepetitions[item];
            else
                sumToNumberOfRepetitions.Add(item, 0);

            sumToNumberOfRepetitions[item]++;
        }

        return numberOfFragments;

If you want to have sum not only zero but any number k, here is the hint:
            int numToFind = currentSum - k;
            if (sumToNumberOfRepetitions.ContainsKey(numToFind))
                numberOfFragments += sumToNumberOfRepetitions[numToFind];

A: I feel it can be solved using DP:
Let the state be :
DP[i][j]  represents the number of ways j can be formed using all the subarrays ending at i!
Transitions:
for every element in the initial step ,
Increase the number of ways to form Element[i] using i elements by 1 i.e. using the subarray of length 1 starting from i and ending with i i.e
DP[i][Element[i]]++;

then for every j in Range [ -Mod(highest Magnitude of any element ) , Mod(highest Magnitude of any element) ]
DP[i][j]+=DP[i-1][j-Element[i]];

Then your answer will be the sum of all the DP[i][0] (Number of ways to form 0 using subarrays ending at i ) where i varies from 1 to Number of elements
Complexity is O(MOD highest magnitude of any element * Number of Elements)

A: https://www.techiedelight.com/find-sub-array-with-0-sum/
This would be an exact solution.
# Utility function to insert <key, value> into the dict
def insert(dict, key, value):

    # if the key is seen for the first time, initialize the list
    dict.setdefault(key, []).append(value)

# Function to print all sub-lists with 0 sum present
# in the given list
def printallSublists(A):

    # create an empty -dict to store ending index of all
    # sub-lists having same sum
    dict = {}

    # insert (0, -1) pair into the dict to handle the case when
    # sub-list with 0 sum starts from index 0
    insert(dict, 0, -1)

    result = 0
    sum = 0

    # traverse the given list
    for i in range(len(A)):

        # sum of elements so far
        sum += A[i]

        # if sum is seen before, there exists at-least one
        # sub-list with 0 sum
        if sum in dict:

            list = dict.get(sum)
            result += len(list)
            # find all sub-lists with same sum
            for value in list:
                print("Sublist is", (value + 1, i))

        # insert (sum so far, current index) pair into the -dict
        insert(dict, sum, i)

    print("length :", result)

if __name__ == '__main__':

    A = [0, 1, 2, -3, 0, 2, -2]

    printallSublists(A)

A: I don't know what the complexity of my suggestion would be but i have an idea :)
What you can do is try to reduce element from main array which are not able to contribute for you solution
suppose elements are -10, 5, 2, -2, 5,7 ,-5, 9,11,19
so you can see that -10,9,11 and 19 are element
that are never gone be useful to make sum 0 in your case
so try to remove -10,9,11, and 19 from your main array
to do this what you can do is
1) create two sub array from your main array
`positive {5,7,2,9,11,19}` and `negative {-10,-2,-5}`
2) remove element from positive array which does not satisfy condition
   condition -> value should be construct from negative arrays element
   or sum of  its elements
   ie.
       5 = -5 //so keep it //don't consider the sign
       7 = (-5 + -2 ) // keep
       2 = -2 // keep
       9 // cannot be construct using -10,-2,-5
       same for all 11 and 19
3) remove element form negative array which does not satisfy condition
      condition -> value should be construct from positive arrays element
       or sum of  its elements
  i.e. -10 // cannot be construct so discard
       -2 = 2 // keep
       -5 = 5 // keep

so finally you got an array which contains -2,-5,5,7,2 create all possible sub array form it and check for sum = 0
(Note if your input array contains 0 add all 0's in final array)


text:
Q: How to allign 2x2 radio buttons into a group in android I'm new to android please let me know what I have made wrong, I have added a radio group and next added Gridlayout to align radio buttons in 2x2 form of matrix, it aligned good, but problem is that it is not deselecting previously selected options when I select any radio button. How can I achieve this ?
All radio buttons are getting selected. None of them are deselecting upon changing selection of radio button. Please suggest me any approach.

Thanks

<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radOption1"
                android:layout_row="0"
                android:layout_column="0"
                android:padding="5dp" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radOption2"
                android:layout_row="0"
                android:layout_column="1"
                android:padding="5dp" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radOption3"
                android:layout_row="1"
                android:layout_column="0"
                android:padding="5dp" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radOption4"
                android:layout_row="1"
                android:layout_column="1"
                android:padding="5dp" />

    </GridLayout>
</RadioGroup>

A: RadioGroup is basically a LinearLayout within which you can align your RadioButtons. It's not like a generic layout that can store anything (GridLayout in your example) and it will handle any RadioButtons that you will put down in the hierarchy.
TLDR: RadioGroup lets you align your RadioButtons horizontally or vertically - it's a LinearLayout.
The thing you need to do is described in this question.


text:
Q: How to get interactive html output from JasperReports? I am using JasperReports to generate various high end reports. But my requirement is for web based dynamic reports. The output is in html format and I want it to be interactive and not static. The functionalities similar to Jquery DataTables (like column hiding, sorting, filtering, etc ).
But for applying Jquery DataTables to the generated html , "thead" tag and "table-'id' " is required which is not there in JR html template by default.
Can I edit the html template from where JR generate html? If yes how?
Is there any alternative to Jquery DataTables provided by JR Server as I have heard of JasperReports Server?


text:
Q: HTML not getting changed after jQuery call is made successfully I have a voting mechanism on the site. When people vote up or down, this code is called:
// Called right away after someone clicks on the vote up link
$('.vote_up').click(function()
{

var problem_id = $(this).attr("data-problem_id");

queue.voteUp = $(this).attr('problem_id');

var span = $(this).closest('span').find('span.votes');

queue.span = span;

vote(problem_id , 1);

//Return false to prevent page navigation
return false;
});

and the vote function that it calls looks like this:
var vote = function(problem_id , vote)
{
    if ( vote == 1 )
    {
        queue.voteUp = problem_id;
    }
    else
    if ( vote == -1 )
    {
        queue.voteDown = problem_id;
    }

    var dataString = 'problem_id=' + problem_id + '&vote=' + vote;

// The person is actually logged in so lets have him vote
        $.ajax({
                type: "POST",
                url: "/problems/vote.php",
                dataType: "json",
                data: dataString,
                success: function(data)
                {
                    text = queue.span.text ();

                    if ( vote == -1 )
                    {
                        if ( data == "update_success" )
                        {
                            incrementedText = parseInt(text ,10) - 2;
                        }
                        else
                        {
                            incrementedText = parseInt(text ,10) - 1;
                        }
                    }
                    else
                    if ( vote == 1 )
                    {
                        if ( data == "update_success" )
                        {
                            incrementedText = parseInt(text ,10) + 2;
                        }
                        else
                        {
                            incrementedText = parseInt(text ,10) + 1;
                        }
                    }

                    queue.span.text(incrementedText + " ");
                },
                error : function(data)
                {
                    errorMessage = data.responseText;

                    if ( errorMessage == "not_logged_in" )
                    {
                        queue.login = false;

                        //set the current problem id to the one within the dialog
                        $problemId.val(problem_id);

                        // Try to create the popup that asks user to log in.
                        //  $dialog.dialog('open');
                        $("#loginpopup").dialog();

                        errorMessage = "";

                        // prevent the default action, e.g., following a link
                        return false;
                    }
                    else
                    if ( errorMessage == "already_voted" )
                    {
                        // Display a dialog box saying that the user already voted
                        $('
').html('You already voted this way on this problem.').dialog();
                    }
                    else
                    if (  errorMessage == "error_getting_vote" )
                    {

                        $('
').html('Error getting existing votes.').dialog();
                    }
                    else
                    {
                        // ? :)
                    }
                } // End of error case
            }); // Closing AJAX call.
    };

and here is the PHP that made the HTML for the vote button.  The link is called "important" or "not important" :
echo ''.$problem_date.'
'.$vote.'
 Important
|
Not Important';

When a user votes, the AJAX gets called, and everything works ok.  The only problem is that the HTML does not get updated with the new vote count.  Any idea how I can accomplish that?

A: In your JavaScript you attempt to select the  using the votes class ($(this).closest('span').find('span.votes');). So I recommend changing:

To:

I recommend using a parent element to make your selector work properly:
$('.vote_up').click(function() {
   console.log($(this).parents('div:first').children('.votes'));
});
//this requires there to be a div element that is the ancestor of the code you posted

Here is a jsfiddle of the above solution: http://jsfiddle.net/jasper/DzZCY/1/


text:
Q: jquery validate form.submit() acting oddly I am using JQuery's validate plugin to validate a form.  Validation occurs and the submitHandler is triggered. But then I get this error (from IE8):

Webpage error details
User Agent: Mozilla/4.0 (compatible;
  MSIE 8.0; Windows NT 5.1; Trident/4.0;
  .NET CLR 1.1.4322; .NET CLR 2.0.50727;
  .NET CLR 3.0.04506.30; .NET CLR
  3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C;
  .NET4.0E) Timestamp: Fri, 20 May 2011
  16:30:56 UTC
Message: Object doesn't support this
  property or method

It works as it should in Firefox- no errors at all. Any ideas why the form.submit() method doesn't work?
JQuery
$(document).ready(function() {
    $.validator.addClassRules('valcount',{digits: true, min: 1});

    //Fish Form
    $("form[name='fish']").validate({
        debug: true,
        ignore: ":hidden,[name='']", // do not validate form fields in invisible sections
        errorPlacement: function(error, element) {
            if ( element.is(":radio") ) {
                error.appendTo( element.parent().next().next() );
            }else if(element.is(":checkbox") && element.parent().is('li')){
                error.insertBefore(element.closest("ul.horiz"));
            }else{
                error.appendTo(element.parent());
            };
        },
        rules: {
            fish_name: {required:true, minlength:5},
            care_id: {required: true, digits: true, min: 1},
            strain_id: {required: true, digits: true, min: 1},
            transgene_id: {digits: true, min: 0}
        },
        // set this class to error-labels to indicate valid fields
        success: function(label) { // set   as text for IE
            label.html(" ").addClass("checked");
        },
        submitHandler: function(form){
            if(confirm('Are you sure?'))form.submit(); //PROBLEM var has no such method
        }
    });

});// end $(document).ready(function(){

Form HTML
<form action='http://example.com' method='post' name='fish' id='fish'>
        <input name='fish_id' type="hidden" value="39" >

Fish Name<input name='fish_name' id='fish_name' type='text' value='110208'>

Notes<textarea name='notes' id=fishnotes></textarea>

Animal Care Protocol<select name='care_id' id='care_id'><option value='1' selected="selected">Breeding Colony</option>
</select>

Strain<select name='strain_id' id='strain_id'><option value='1' selected="selected">AB wt</option>
<option value='2' >Tub wt</option>
<option value='14' >AB/Tub</option>
<option value='15' >AB/Tub deadhead</option>
<option value='16' >Casper</option>
</select>

Transgene<select name='transgene_id' id='transgene_id'><option value=0>None</options><option value='1' >Ztag</option>
<option value='2' >KDR-eGFP</option>
<option value='3' >BTIAR-eGFP</option>
<option value='4' >BTIA-eGFP</option>
<option value='5' >BTTP3.1-eGFP</option>
<option value='6' >BTTP6.2-eGFP</option>
<option value='7' >BTIAR-Luc</option>
<option value='8' >BTIA-Luc</option>
<option value='9' >BTTP3.1-Luc</option>
<option value='10' >BTTP6.2-Luc</option>
<option value='11' >Tg(hsp70tolgfp)v28</option>
<option value='16' >blither</option>
</select>

<input value='Edit' type='submit' >

</form>

Edited: removed submit name and id, added info about FF. Tried with $(form).submit() instead of form.submit(). Still no joy.

A: <input name='submit' id='submitfish' value='Edit' type='submit' >
You can't name a submit button "submit". When you do this and call form.submit() in MSIE, MSIE thinks that you're trying to reference the input object, which "doesn't support this property or method."
Remember that in jQuery, $(this) is a jQuery object and this is the actual DOM element. So
submitHandler: function(form){
The submit handler is passing the form as a DOM element, which is why form.submit() fails here.

A: It turns out the problem is a conflict between jquery 1.6.x and validate plug-in 1.8.x.  When I reverted to jquery 1.5, the issue went away.  It's not a very good fix, but hopefully it will save someone some head scratching.
ETA: it appears that validate version 1.8.1, recently released, will fix this problem too.  Note that as of May 24th, 1.8.0 is the version hosted at http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js


text:
Q: Facebook login works in chrome but not in Firefox I have an asp.net website - www.domain.com
I've used the built in OAuth in VS2012 to allow users to register on my site using facebook. Unforutnately, I recently discovered that this has not been working for users on Firefox. What makes this even more strange is that, in the facebook app settings, if I change the site url from http://www.domain.com to http://domain.com, it starts working in firefox and stops working in chrome.
How can I fix this so it will work in both browsers???

A: Problem:
As stated you have to allow Facebook to use the two domains for your website.
Solution:
To do this, go to your Facebook Account: > Apps > Settings > Basic.
In this page set both www.domain.com and domain.com for "App Domains".
That will fix the problem for all browsers and future browser updates.


text:
Q: R shiny: Change "height" attribute of rectangle in gvisTimeline I use gvisTimeline in a R Shiny-App:
library(shiny)
library(googleVis)

ui <-fluidRow(
  tags$head(
    tags$script(src="https://d3js.org/d3.v3.min.js", {{ suppressDependencies("d3") }})
  ),
  htmlOutput("timeline")
  )

server <- function(input, output) {

dat <- data.frame(Term=c("1","2","3"),
                  President=c("Whashington", "Adams", "Jefferson"),
                  start=as.Date(x=c("1789-03-29", "1797-02-03", "1801-02-03")),
                  end=as.Date(x=c("1797-02-03", "1801-02-03", "1809-02-03")))

output$timeline <-renderGvis({
                    gvisTimeline(data=dat[,-1], rowlabel="President",
                    start="start", end="end")
          })
    }

shinyApp(ui, server)

I would like to change the height of the middle rectangle. I achieve this by selecting the appropriate svg element in JavaScript Console:
d3.select('svg:nth-child(1) g:nth-child(5) rect:nth-child(2)')
.attr('height', 42)
.attr('y', 40);

How can I intergrate this code into the Shiny-App in order to get this one rectangle in desired height and y-coordinate from the beginning? Thank you for your help!

A: The problem here is that the timeline is transferred from the Google Server a few milliseconds after the page is loaded. You need to execute your JavaScript code after this transfer happened, i.e. 50 or 500 ms after the page is initialized. The following code will execute it every 50 ms, which works but is far from perfect.

*

*In UI, you need a dummy output "uiOutput("timelineAdjustment")":
uiOutput("timelineAdjustment")

*In Server, you need to define it as follows:
autoInvalidate50msec <- reactiveTimer(50, session)
output$timelineAdjustment <- renderUI({
   autoInvalidate50msec()
   HTML("<script type='text/javascript'>d3.select('#timeline svg:nth-child(1) g:nth-child(5) rect:nth-child(2)').attr('height', 42).attr('y', 40);</script>")
})

Alternatively, the equivalent definition if you just execute it once (1000ms) after the page is loaded:
output$timelineAdjustment <- renderUI({
    HTML("<script type='text/javascript'>setTimeout(function() { d3.select('#timeline svg:nth-child(1) g:nth-child(5) rect:nth-child(11)').attr('height', 41).attr('y', 41); },1000);</script>")
})

If there is a better way of achieving this, I'd be glad to hear!


text:
Q: How to set the Return-Path to an email address other than Sender address using JavaMail? How to set the Return-Path to an email address other than Sender address using JavaMail?

A: I've experienced the same issue and found the only solution discussed putting property  "mail.smtp.from" props.put("mail.smtp.from", "replyto@example.com");
Still this solution was not suitable for me because I'm sending lot's of e-mails from different users, so recreating session for each e-mail would be horrible for prodictivity.
So I found another solution after reading JavaMail sources:
1) Use SMTPMessage(extends MimeMessage) instead of MimeMessage.
2) Use setEnvelopeFrom(String) method.
3) Use SMTPTransport to send e-mail (I didn't try with others).
Here is a code example:
SMTPMessage message = new SMTPMessage(session);
message.setEnvelopeFrom("returnpath@hotmail.com");
...
transport.sendMessage(message, message.getAllRecipients());

A: The code below does what you want, and does it in the correct way. Reread what you yourself posted in the comment

From: RFC2821: 4.4 Trace Information
When the delivery SMTP server makes
the "final delivery" of a message, it
inserts a return-path line at the
beginning of the mail data.  This use
of return-path is required; mail
systems MUST support it.  The
return-path line preserves the
information in the
from the MAIL command.  Here, final
delivery means the message has left
the SMTP environment.  Normally, this
would mean it had been delivered to
the destination user or an associated
mail drop, but in some cases it may be
further processed and transmitted by
another mail system.

and a few lines later.

A message-originating SMTP system
SHOULD NOT send a message that already
contains a Return-path header.

If you carefully read this you will understand that only the final smtp-server/delivery agent is supposed to add the Return-Path header. It is not something you as client (trying to send a mail) should do. The final smtp-server will base the Return-Path header on the sender address of the envelope (SMTP MAIL FROM part).
So setting mail.smtp.from is the correct way to tell java that the envelope sender address should be different from the from part.
If you have troubles understanding what the different from's are just take a look at a telnet smtp-session. Where replyto@example.com should correspond to mail.smtp.from and from@example.com to m.addFrom(...);
telnet smtp.example.com 25
220 smtp.example.com ESMTP .....

helo computername
250 smtp.example.com Hello computername [123.123.123.123]

mail from:<replyto@example.com>
250 <replyto@example.com> is syntactically correct

rcpt to:<rcpt@foo.com>
250 <rcpt@foo.com> verified

data
354 Enter message, ending with "." on a line by itself
To: Joey <to@joey.com>
From: Joey <from@example.com>
Subject: Joey

Hey Joey!

.
250 OK id=....

Quit

props.put("mail.smtp.from", "replyto@example.com");
Session session = Session.getDefaultInstance(props, null);
MimeMessage m = new MimeMessage(session);
m.addFrom(InternetAddress.parse("from@example.com"));

A: I found that if the 'mail.protocol' property is set to something other than 'smtp' (like 'smtps'), then only the following would work:
props.put("mail.smtps.from", "replyto@example.com");

This allowed me to avoid using the SMTPMessage class as described in GiorgosDev's answer (classes in the 'com.sun' package aren't intended to be public API).


text:
Q: Call a Django python function from tag script in the template This is some content of my Django template.
...
Do operation with database.
...

...

The function is for example(we can imagine the function is in views.py):
def performtask():
#do my operation with the database
My question is, how it is possibile to call performtask() function from the script tag in my template?

A: you should go through with ajax
   $.ajax({
        url: "http://abc,com/app/",
        type: "POST",
        data :{},
        success:function(result){
            //your code
        },
        error:function(error){
            //error handal
        }
    });

you can get more details here :
https://realpython.com/blog/python/django-and-ajax-form-submissions/
https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html


text:
Q: TikZ - Style for arrow with midpoint decorator I am creating a kind of commutative diagram with different types of arrows. So far, I have defined different line styles for my different types of map, like this:
\tikzstyle{map}=[->,>=stealth',semithick]
\tikzstyle{incmap}=[semithick, right hook-latex]
\tikzstyle{typemap}=[->,>=latex',thin, dashed]

This way, I declare all my nodes in the layout that I want, and then I can declare maps between them easily using \draw[<style>]. In addition, I can easily switch the style of a map (e.g. from a inclusion map to a normal one) if I decide that it is not the correct one.
Now, I want to create an arrow style for partial maps that looks like a normal arrow with a circle in the midpoint (no matter the length of the arrow). I know that I can do this in a one-by-one fashion, but I would like to be able to define that in a style, in a similar way to the others. To clarify, the arrows should look like this:
-o->
--o-->
---o--->

Any suggestions?
I am not using TikZ's cd library, but I have checked it and there is nothing that solves the problem.
Thanks in advance!
EDIT: As suggested, I add here the MWE with my initial status.
\documentclass{standalone}
\usepackage{tikz}

\usetikzlibrary{arrows,positioning,shapes}

\begin{document}
\begin{tikzpicture}[on grid,node distance=20mm]

\tikzstyle{element}=[inner sep=2pt,minimum height=1.3em,font=\itshape]
\tikzstyle{label}=[auto,midway,font=\itshape,inner sep=2pt]
\tikzstyle{map}=[->,>=stealth',semithick]
\tikzstyle{incmap}=[semithick, left hook-latex]
\tikzstyle{typemap}=[->,>=latex',thin, dashed]

\node[element] (l)  []  {L};
\node[element] (i)  [right of=l]    {I};
\node[element] (r)  [right of=i]    {R};

\draw[map]      (l) to node [label,above]   (lm)    {l}     (i);
\draw[incmap]   (r) to node [label,above]   (rm)    {r}     (i);

\end{tikzpicture}
\end{document}

A: Using markings worked perfectly. Here is how I solved it:
\documentclass{standalone}
\usepackage{tikz}

\usetikzlibrary{arrows,positioning,shapes,decorations.markings}

\begin{document}
\begin{tikzpicture}[on grid,node distance=20mm,
  decoration={markings,mark=at position 0.5 with {\draw circle [radius=.4ex];}}]

\tikzset{element/.style={inner sep=2pt,minimum height=1.3em,font=\itshape}}
\tikzset{label/.style={auto,midway,font=\itshape,inner sep=2pt}}
\tikzset{map/.style={->,>=stealth',semithick}}
\tikzset{incmap/.style={semithick, left hook-latex}}
\tikzset{partmap/.style={->,>=latex,semithick,postaction={decorate}}}

\node[element] (l)  []  {L};
\node[element] (i)  [right of=l]    {I};
\node[element] (r)  [right of=i]    {R};

\draw[partmap]  (l) to node [label,above]   (lm)    {l}     (i);
\draw[incmap]   (r) to node [label,above]   (rm)    {r}     (i);

\end{tikzpicture}
\end{document}

Thanks again to the people who answered!


text:
Q: Python/Tornado error on app launch I am repeatedly getting this error with my Tornado app on launch:
  File "/Library/Python/2.7/site-packages/tornado/database.py", line 59, in __init__
    args = dict(conv=CONVERSIONS, use_unicode=True, charset="utf8",
NameError: global name 'CONVERSIONS' is not defined

I have installed Tornado and MySQLdb with pip. I have uninstalled and re-installed both. I am running against a remote MySQL instance.
I am baffled and not sure how to troubleshoot. Any advice?

A: Ultimately this was masking this error:
ImportError: dlopen(/Library/Python/2.7/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
  Referenced from: /Library/Python/2.7/site-packages/_mysql.so
  Reason: image not found

I was able to resolve this by setting DYLD_LIBRARY_PATH:
export DYLD_LIBRARY_PATH=/usr/local/mysql/lib:$DYLD_LIBRARY_PATH

A: if you run it within MAC OS and Eclipse, you should add DYLD_LIBRARY_PATH into eclipse' environment setting.


text:
Q: Python:The process cannot access the file because it is being used by another process try:
    masterpath = os.path.join(path, "master.txt")
    with open(masterpath, 'r') as f:
        s = f.read()
    f.close()
    exec(s)
    with open(masterpath, 'w') as g:
        g.truncate()
    g.close()
    os.remove(masterpath)

Here I want to read something in a .txt file and then erase content and delete it. But it always shows it cannot delete it as 'The process cannot access the file because it is being used by another process'.
Actually what I need is to delete the .txt file, but it cannot delete immediately sometimes, so I erase the content at first in case that it will be read again. So is there any good way to read something in a .txt file and then delete this file as soon and stable as possible?

A: You should NOT call f.close() nor g.close(). It is called automatically by with statement.

A: remove the unnecessary close() statements to start - like @grapes mentioned - why are you truncating what you are deleting? just delete it...
try:
    masterpath = os.path.join(path, "master.txt")
    with open(masterpath, 'r') as f:
        s = f.read()
    exec(s)
except Error as e:
    print(e)
else:
    os.remove(masterpath)

FYI, it is bad form to execute the contents of a file if you do not control the contents of said file.
another option:
masterpath = os.path.join(path, "master.txt")
with open(masterpath, 'r') as f:
    try:
        s = f.read()
    except Error as e:
        print(e)
    else:
        exec(s)
os.remove(masterpath)

A: Try to use short sleep in exception part:
    try:
        masterpath = os.path.join(path, "master.txt")
        with open(masterpath, 'r') as f:
            s = f.read()
        f.close()
        exec(s)
        with open(masterpath, 'w') as g:
            g.truncate()
        g.close()
        os.remove(masterpath)
   except WindowsError:
            time.sleep(sleep)
        else:
            break

Another way is to use:
os.remove(masterpath)


text:
Q: Finding the difference image between multiple images I've taken multiple screenshots from a webcam on my campus and I have taken the average of the 300 screenshots and it gives me an image with many ghostly people. I am trying to figure out how to get the difference image between the images so that I can change the differences to red to show is more clearly. I just need some help getting an idea of where to start. I know I need to subtract the first image by the second, and then that image by the third, but I'm not sure of a way to do that in Python.
import os, os.path, time
import matplotlib.pyplot as mplot
from PIL import Image
import numpy as np

files=os.listdir('./images')
print files

image=[]

for file in files:
    img=Image.open('./images/'+file)
    img=np.float32(img)
    image.append(img)

avg_img=[]

for img in image:
    try:
        avg_img+=img
    except:
        avg_img=img

avg_img/=len(image)
avg_img=np.clip(avg_img, 0, 255)
avg_img=np.uint8(avg_img)
mplot.imshow(avg_img)
mplot.show()

A: There are tons of ways to do this, but I will first keep closest to what you currently have. Then I will show a more compact way.
import os, os.path, time
import matplotlib.pyplot as mplot
from PIL import Image
import numpy as np

files=os.listdir('./images')
print files

image=[]

for file in files:
    img=Image.open('./images/'+file)
    img=np.float32(img)
    image.append(img)

avg_img=np.zeros_like(image[0])

for img in image:
    avg_img += img

avg_img/=len(image)
avg_img=np.clip(avg_img, 0, 255)
avg_img=np.uint8(avg_img)
mplot.imshow(avg_img)
mplot.show()

# get series of differences
differences = []
for img0, img1 in zip(image[:-1], image[1:]):
    differences.append(img1 - img0)

Here is an easier way using numpy.
import os, os.path, time
import matplotlib.pyplot as mplot
from PIL import Image
import numpy as np

files = os.listdir('./images')
print files

img = Image.open(os.path.join('./images', files[0])

image_stack = np.ndarray((len(files), img.shape[0], img.shape[1], 3), dtype=np.float32)

for i, file in enumerate(files):
    img = Image.open('./images/'+file)
    img = np.float32(img)
    image_stack[i] = img

avg_img = np.mean(image_stack, axis=0)
avg_img = np.clip(avg_img, 0, 255)
avg_img = avg_img.astype(np.uint8)

mplot.imshow(avg_img)
mplot.show()

difference_stack = image_stack[1:] - image_stack[:-1]

I doubt your webcam image stores floats, but maybe that is the case.


text:
Q: SQL Error: ORA-04091 while executing Trigger I am trying to execute my trigger:
CREATE OR REPLACE TRIGGER Trg_video_bfr_delete
    AFTER DELETE ON CMS_VIDEO
    FOR EACH ROW
DECLARE
    CODE varchar2(60);
BEGIN
    SELECT CODE INTO CODE
    from CMS_VIDEO
    WHERE CODE = :OLD.CODE;
    IF CODE IS NOT NULL THEN
        INSERT INTO ASSET_DELETE_INDEX(CODE,ASSET_TYPE,IW_VPATH,LANGUAGE,MODIFIED_DTE)
        VALUES (CODE,'Video',:old.IW_VPATH,:old.CONTENT_LANGUAGE,sysdate);
    END IF;
EXCEPTION
    WHEN NO_DATA_FOUND THEN
        INSERT INTO ASSET_DELETE_INDEX (CODE,ASSET_TYPE,IW_VPATH,LANGUAGE,MODIFIED_DTE)
        VALUES (CODE,'Video',null,:old.CONTENT_LANGUAGE,sysdate);
        COMMIT;
END Trg_video_bfr_delete;
/

But I am getting the following error while executing a delete command on the table
Error report -

SQL Error: ORA-04091: table LSDS.CMS_VIDEO is mutating, trigger/function may not see it
  ORA-06512: at "LSDS.TRG_VIDEO_BFR_DELETE", line 6
  ORA-04088: error during execution of trigger 'LSDS.TRG_VIDEO_BFR_DELETE'
  04091. 00000 -  "table %s.%s is mutating, trigger/function may not see it"
  *Cause:    A trigger (or a user defined plsql function that is referenced in
             this statement) attempted to look at (or modify) a table that was
             in the middle of being modified by the statement which fired it.
  *Action:   Rewrite the trigger (or function) so it does not read that table.

Could anyone please help?

A: You have written trigger AFTER DELETE ON CMS_VIDEO. This trigger will fire when DELETE is performed from CMS_VIDEO table. So when CMS_VIDEO table is being modified, you cannot modify or query the same table in any of your triggers, procedures or functions.
CREATE OR REPLACE TRIGGER Trg_video_bfr_delete
AFTER DELETE ON CMS_VIDEO
FOR EACH ROW

BEGIN
  IF :old.CODE IS NOT NULL THEN
    INSERT INTO ASSET_DELETE_INDEX(CODE, ASSET_TYPE, IW_VPATH, LANGUAGE, MODIFIED_DTE)
    VALUES (:old.CODE, 'Video', :old.IW_VPATH, :old.CONTENT_LANGUAGE, sysdate);
  END IF;
END Trg_video_bfr_delete;
/

A: This is because you are deleting record from table and same table is used as reference inside trigger. This is case of "Mutating Error". You should switch to statement level trigger is it fits your requirement or you can use compound trigger which has multiple entry point and are capable of handling such scenarios.
Please refer https://oracle-base.com/articles/9i/mutating-table-exceptions

A: As per the snippet provided, I dont see any point in doing a SELECT on mutating TABLE.
We can easily ise :OLD.CODE to fetch the value. Hope below snippet helps.
CREATE OR REPLACE TRIGGER Trg_video_bfr_delete AFTER
  DELETE ON CMS_VIDEO FOR EACH ROW
--  DECLARE CODE VARCHAR2(60);
  BEGIN
--    SELECT CODE INTO CODE FROM CMS_VIDEO WHERE CODE = :OLD.CODE;
    IF CODE IS NOT NULL THEN
      INSERT
      INTO ASSET_DELETE_INDEX
        (
          CODE,
          ASSET_TYPE,
          IW_VPATH,
          LANGUAGE,
          MODIFIED_DTE
        )
        VALUES
        (
          :old.code,
          'Video',
          :old.IW_VPATH,
          :old.CONTENT_LANGUAGE,
          sysdate
        );
    END IF;
  EXCEPTION
  WHEN OTHERS THEN
    INSERT
    INTO ASSET_DELETE_INDEX
      (
        CODE,
        ASSET_TYPE,
        IW_VPATH,
        LANGUAGE,
        MODIFIED_DTE
      )
      VALUES
      (
        :old.code,
        'Video',
        NULL,
        :old.CONTENT_LANGUAGE,
        sysdate
      );
    COMMIT;
  END Trg_video_bfr_delete;


text:
Q: node fs not found with snowpack using typescript I'm trying to create a snowpack project, which already fails by the basic start.
I set up a basic snowpack project, but when I try to start my dev server it will fail because of this line:
import * as fs from "fs/promises";

Showing me:
▼ Console

[snowpack] ! building dependencies...
[snowpack] Package "fs/promises" not found. Have you installed it?

But I think node is installed...
How can I use fs with snowpack?
Basically I wanted to build an app with selenium-webdriver but this fails even more, since it imports more libraries that are not loaded. fs is one of them. And I don't understand what rollup is doing and if this will be the right way to 'bundle` (?) fs ?
UPDATE:
Using:
import * as fs from "fs";

will work, when running npx tsc file.ts && node file.js, but it shows in snowpack I still get the error:
▼ Console

[snowpack] ! building dependencies...
[snowpack] Package "fs" not found. Have you installed it?

npm ERR! code 1
npm ERR! path /home/user/snowpackproject/scraper
npm ERR! command failed
npm ERR! command sh -c snowpack dev --polyfill-node


text:
Q: faces/index.xhtml location in java web application In web.xml, I had found the declaration for the initial web page as follows.
<welcome-file-list>
    <welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>

Where is face in Java Web application? I have known that index.xhtml is located in Web Pages folder.

A: if you opened web.xml you will find mapping of /faces/* url to servlet that contain life cycle of JSF and managed by that servlet
as any page goes in JSF life cycle must be under/faces/
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
</servlet-mapping>


text:
Q: Error(10,4): PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: end not pragma final create or replace TRIGGER "VALIDATE_DOA_DOD" BEFORE UPDATE ON IN_PATIENT
FOR EACH ROW
BEGIN
  IF :NEW.DOD < :OLD.DOA THEN

    enter code here

 RAISE EX_INVALID_DOD;
  END IF;

  EXCEPTIION
    WHEN EX_INVALID_DOD THEN
      dbms_output.put_line('Date Of Discharge must be greater or equal to Date of Admition');

END;

A: *

*replace the 'enter code here' with something meaningful, or remove it

*edit EXCEPTIION into EXCEPTION

*declare your exception EX_INVALID_DOD
So:
create or replace TRIGGER "VALIDATE_DOA_DOD" BEFORE UPDATE ON IN_PATIENT
FOR EACH ROW
declare
    EX_INVALID_DOD exception;
BEGIN
  IF :NEW.DOD < :OLD.DOA THEN

     --enter code here

     RAISE EX_INVALID_DOD;
  END IF;

  EXCEPTION
    WHEN EX_INVALID_DOD THEN
      dbms_output.put_line('Date Of Discharge must be greater or equal to Date of Admition');

END;


text:
Q: Get absolute path of android drawable image I need to get the absolute path or the File object of my drawable image in android application. Is there any way to do this?
Drawable is as following
context.getResources().getDrawable(R.drawable.back_button)

A: If you app is insalled on sdcard  try this code :
Bitmap bitMap = BitmapFactory.decodeResource(getResources(),R.id.img1);

File mFile1 = Environment.getExternalStorageDirectory();

String fileName ="img1.jpg";

File mFile2 = new File(mFile1,fileName);
try {
       FileOutputStream outStream;

       outStream = new FileOutputStream(mFile2);

       bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);

       outStream.flush();

       outStream.close();

} catch (FileNotFoundException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
} catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
}

String sdPath = mFile1.getAbsolutePath().toString()+"/"+fileName;

Log.i("hiya", "Your IMAGE ABSOLUTE PATH:-"+sdPath);

File temp=new File(sdPath);

if(!temp.exists()){
       Log.e("file","no image file at location :"+sdPath);
}

A: Uri path = Uri.parse("android.resource://com.nikhil.material/" + R.drawable.image);

OR
Uri otherPath = Uri.parse("android.resource://com.nikhil.material/drawable/image");

OR
Uri path = Uri.parse("android.resource://"+BuildConfig.APPLICATION_ID+"/" + R.drawable.image);

A: drawable resources are added to binary at run time therefore cannot be accessed by path.
you can decode and use drawables instead.
If you need resources you can access at runtime by path, try using assets folder instead.
Hope this is helpful


text:
Q: Runtime Error 6 on Mac OS X When I tried executing the following code on Excel for Mac (OS X), I get a runtime error 6 -stack overflow when it gets to the portion of the code when it's dividing the two resulting numbers (Reward_Over_Risk). This happens even when I change the variable from As Single to As Double or even As Variant. Running the same code on a Windows 10 OS, however produces the required results.
Is there away for me to get this resolved?
The code in question is as below (Note, I've only posted a portion of the code as the runtime error happens at the "Reward_Over_Risk" line:
Sub Trading_Plan_Code()

Dim Support_Line As Currency
Dim ATR As Currency
Dim Target_Entry As Currency
Dim Profit_Target As Currency
Dim Stop_Loss As Currency
Dim Reward_Over_Risk As Single
Dim Reward_Number As Currency
Dim Risk_Number As Currency

If Worksheets(1).Range("E11").Value = "Long" Then

    Support_Line = Worksheets(1).Range("H11").Value
    ATR = Worksheets(1).Range("I11").Value
    Target_Entry = Worksheets(1).Range("J11").Value
    Profit_Target = Worksheets(1).Range("K11").Value

    Stop_Loss = Support_Line - ATR
    Reward_Number = Profit_Target - Target_Entry

'At this point the result for the Reward_Number is 2.2

    Risk_Number = Target_Entry - Stop_Loss

'At this point the result for Risk_Number is 1.5

    Worksheets(1).Range("L11").Value = Stop_Loss

    Reward_Over_Risk = Reward_Number / Risk_Number

    Worksheets(1).Range("M11").Value = Reward_Over_Risk

End If

End Sub

Funny enough, when I replace the "Reward_Number" and "Risk_Number" with whole numbers 2 & 1, the code runs. However, when I add the decimal points 2.2 and 1.5 I get the run time error. Again, I do not get this issue running the same code on a windows machine.
Any pointers would be much appreciated.
Thanks!

A: I had the very same problem that you had had by running some VBA code at Excel 16 through my os x computer. Also, as in your case, I tried to run the code through windows and no problem appeared. As a solution, I found out that by not specifying the type of the variable (Dim Risk_Number instead of Dim Risk_Number As Currency) - so letting it be a variant - the problem disappeared. I hope it is useful for you.


text:
Q: How to design a layout In Android that is suitable for portrait/landscape mode? I've designed a layout ideally for portrait mode. However, when I switch the layout to landscape mode, the layout crashes. How can this be fixed?

A: add this line to your activity tag in AndroidManifest.xml
android:configChanges="orientation|screenSize"

or handle the change in orientation in code because the change in orientation recreates the activity again.


text:
Q: Restarted my server and started getting this error: Forever detected script exited with code: 8 I resized my Digital ocean droplet (Permanently) This required I powered off my droplet and then powered on again. When I visit the webpage I get a typical NGINX page saying that I have succesfully installed NGINX, the web app can no longer be seen
I did a mup logs -f to see what is going on and I am continually getting this error.
I am not sure what is wrong and it looks like something is off with my cron jobs but I am not sure what. Any ideas:
error: Forever detected script exited with code: 8
[xxx.xxx.xxx.xx] error: Script restart attempt #75[xxx.xxx.xxx.xx]
[xxx.xxx.xxx.xx] {"line":"63","file":"synced-cron-server.js","message":"SyncedCron: Scheduled \"Email Weekly Todos for Mentors\" next run @Mon Nov 30 2015 07:00:00 GMT-0500 (EST)","time":{"$date":1448741207434},"level":"info"}[xxx.xxx.xxx.xx]
[xxx.xxx.xxx.xx] {"line":"63","file":"synced-cron-server.js","message":"SyncedCron: Scheduled \"Weekly Push Notifications to students\" next run @Sun Nov 29 2015 10:00:00 GMT-0500 (EST)","time":{"$date":1448741207437},"level":"info"}[xxx.xxx.xxx.xx]
[xxx.xxx.xxx.xx]
[xxx.xxx.xxx.xx] events.js:72[xxx.xxx.xxx.xx]
[xxx.xxx.xxx.xx] throw er; // Unhandled 'error' event
[xxx.xxx.xxx.xx] [xxx.xxx.xxx.xx] ^
Error: listen EADDRINUSE
at errnoException (net.js:905:11)
at Server._listen2 (net.js:1043:14)
at listen (net.js:1065:10)
at net.js:1147:9
at dns.js:72:18
at process._tickCallback (node.js:442:13)
error: Forever detected script exited with code: 8[xxx.xxx.xxx.xx]

Any ideas would help a lot

A: I fixed the issues by setting the app file in sites-enabled folder to listen to port 3000. I think it was listening to 80 by default and conflicting with nginx


text:
Q: Counterexample - Increasing function My intuition says that the statement is false. Anyone out there know of counterexamples?

Suppose $f: R\to R$ and $c\in R$ such that $f'(c) > 0$.  So, $\exists \varepsilon> 0 $ such that $f\mid_{(c-\varepsilon, c+\varepsilon)}$ is increasing.

(Original screenshot)

A: No. Take $$f(x)=\cases{ x+2x^2\sin(1/x), & $x\ne0$\cr 0, &$x=0$}.$$ $f$ is differentiable everywhere and $f'(0)=1$. But $f$ is not monotonic in any neighborhood of $x=0$ (since in any neighborhood of $0$, $f'$ takes both positive and negative values).
This is Example 3.5
 in Gelbaum and Olmsted's Counterexamples in Analysis.

A: $f(x):=\begin{cases}x,&\text{if $x\in\boldsymbol {Q}$}\\
\tan(x),&\text{if $x\in\boldsymbol{R}\setminus\boldsymbol{Q}$}\end{cases}$, for $c=0$ we have $f'(c)=1$.  Here we have a punctal monotony: there exists $\epsilon>0$ such that for all $x_1\in ]-\epsilon,0[$ and $x_2\in ]0,\epsilon[$ we have $f(x_1)<f(x_2)$, but $f$ is not increasing on $]-\epsilon,\epsilon[$ for any $\epsilon>0$: chose an irrational $a\in]0,\epsilon[$ and a rational $b\in]0,\epsilon[$ with $a<b$, then $f(a)>f(b)$.


text:
Q: C++ internal compiler error Since many weeks our compilation server is crashing randomly while compiling our C++ code.
Sometimes the compilation failed and we have the following error :
/usr/include/c++/7/future:429:7: internal compiler error: Segmentation fault

The error is always raised from system libraries (but not always the same) and at different step of the compilation process.
We have tried to increase the size of RAM up to 10 GB and the size of the swap (up to 5GB) but the issue has not been solved. We have also tried multiple version  of the cc compiler but without success.
We have a set a machine but the issue is only reproducible on out compilation server. We have to fix it because this server is part of our continuous integration chain.
The source code is composed of  about 10000-20000 line of codes (not really much) but we use some template.
Does someone knows how to solve or investigate this error ?
System information:
compiler = c++
compiler version = c++ (Ubuntu 7.2.0-1ubuntu1~16.04) 7.2.0
compilation tools = cmake and make
ubuntu-xenial
RAM  = 10G
Swap = 5G
NbCPU = 4

Thank you very much for your help

A: So you've got intermittent errors in (presumably well tested) compiler internals from (presumably also well tested) system libraries, and the problems are reproducible on multiple compiler versions, but only on this single machine. That points towards a hardware issue.
Bad RAM seems like a good candidate. A C++ compiler processing a moderately sized code base is likely to crash from e.g. random bit flips at least some of the time.
You should test your RAM (or just swap it out and see if the failures go away).


text:
Q: LaTeX Compilation & Memory Question Good Day,
I'll explain my situation for reference before I dive into the question.
I am writing a fairly lengthy report in LaTeX.  The report will probably end up being over 60 pages and have multiple sections and lots of figures/tables.
Most of my data is coming from an external program that prints data files with ~ 10,000 data points in each column.  I am currently using PGFplots to downsample in order to prevent an "Out of Memory" error.
My worry is that, when I compile the entire report as one single document (instead of section by section) I will get an "Out of Memory" error because of all the figures and data being processed by PGFplots.  In addition to downsampling, I also have some filters I am applying to the data via PGFplots.
I am not sure how to estimate the amount of memory LaTeX will need when the final document is compiled so I do not know how to estimate how much PGFplots can handle downsampling/filter - wise.
If any of this is unclear please let me know.  Also, this is my first time posting so please feel free to correct me with any customs/best practice when it comes to posting.

A: The memory usage of pgfplots is beyond the default configuration of a tex system, especially for huge data sets.
The pgfplots reference manual contains a section named "Memory and Speed considerations" which is dedicated to the associated problems. Reducing its section to one sentence results in "lualatex is the simplest approach to get around memory limits and, since pgfplots 1.12, to reduce time; image externalization avoids unnecessary recompilations".
Especially the performance has been addressed in pgfplots 1.12, so I suggest to give it a try: parts of the computations have been moved to Lua.
More reading: http://pgfplots.sourceforge.net/pgfplots.pdf


text:
Q: Como trazer um resultado específico de uma consulta SQL acima dos demais? Tenho a seguinte consulta SQL:
SELECT DISTINCT `user_id` AS `id`, `user_name` AS `name` FROM `users` ORDER BY `id` ASC;

Que gera a saída:
+----+--------+
| id | name   |
+----+--------+
|  1 | Calebe |
|  2 | João   |
|  3 | Lucas  |
|  4 | Pedro  |
+----+--------+

No entanto, preciso que determinado user venha nos resultados, antes dos demais.
Exemplo: Quero que o user_id = 3 apareça no topo. Então o resultado deve vir da seguinte forma:
+----+--------+
| id | name   |
+----+--------+
|  3 | Lucas  |
|  1 | Calebe |
|  2 | João   |
|  4 | Pedro  |
+----+--------+

Como posso fazê-lo?

A: Para a sua query específica, funciona algo desse tipo:
SELECT DISTINCT `user_id` AS `id`, `user_name` AS `name` FROM `users`
ORDER BY `id` = 3 DESC, `id` ASC;

Dessa forma, garante-se que o primeiro termo de ordenação obedece o ID desejado.

A: SELECT DISTINCT `user_id` AS `id`, `user_name` AS `name`, if(user_name = `Lucas`,0,1) as `ordem` FROM `users` ORDER BY `ordem` ASC, `id` ASC;

A: Tem uma solução aqui: link
ORDER BY (user_id.id=3) ...

A: Você também pode utilizar uma ordem pelo campo e pelos valores desejados, usando a seguinte regra:

SELECT DISTINCT `user_id` AS `id`, `user_name` AS `name` FROM `users`
ORDER BY FIELD (id, 3, 1, 2, 4 ) ASC, id DESC;


text:
Q: GraphQL type containing a finite set of string values In typescript I can write:
type T = 'some words' | 'some other words' | ...

Is it possible to define such a type in GraphQL schema?
I have a downstream service that returns a set of values, some containing blanks and I would like to have a type restricted to only those values.

A: You can define a custom scalar that only allows your set of values.
In the absence of spaces you could also use an enum.


text:
Q: How To implement the Javascript to elements which has been added to head section of HTML By Jquery prepend()? I have this in my head section.
<script type="text/javascript" src="post.js"></script>

I want this post.js to be also be implemented to the newly created elements.My another js file which is named as main.js have a code that get data from another php file and prepend it in a div with id display.Previous Loaded Div works great with the post.js file but as new elements are prepended, it does not work for new ones. Here is my main.js code which get data from php file and prepend it:
var auto_refresh8 = setInterval(function() {
    var id = "id="+$(".ally:first").attr("id");
    $.ajax({
        type: "POST",
        url: "get_post.php",
        data: id,
        cache: false,
        success:function(html){
            $('#display').prepend(html);
        }
    });
},2000);

this jquery ajax request get data from get_post.php file and prepend it to the div display. but the code in post.js doesn't work with this.The data returned by jquery ajax request contains a div with class comm which have to submitted when keypress function acts.
following is the code of post.js :
$(document).ready( function() {
    $(".comm").keypress(function(e) {
        if(e.which == 13) {
            var id = $(this).attr("id");
            var data = 'id=' + id;
            var post = $(this).val();
            var data1 = 'comment='+post;
            var wholedata = data+'&'+data1;

            $(this).blur();
            $.ajax({
                type: "POST",
                url: "c_insert.php",
                data: wholedata,
                cache: false,
                success:function(html){
                    $('.class_all'+id).append(html);
                }
            });
            return false;
        }
    });
});

A: Use a delegate to handle the event in post.js file instead. See the jQuery documentation for more information.
Something like this should do it:
$('#display').on('keypress', '.comm', function (e) {
  if(e.which == 13) {
    // Do code on event
  }
});

Note that the "on" function should only be used if you are using jQuery version 1.7 or later. Previous versions uses the function "delegate".
edit Changed $(document).on(...) to $('#display').on(...) since all '.comm'-elements are children of '#display'.


text:
Q: Downgrade Ubuntu (18.04 to 16.04) or make php on apach2 work I am new on this forum so sorry if my topic is not on the rules or not at the good place, it's my first post.
I have a little problem, I actualy work on a project for an intership and have a server on ubuntu. I want to make my server using https instead of http. I see on internet than a version of ubuntu 16.04 is recommanded (I was on Ubuntu 14.04 at this moment). I updated my ubuntu with this tutorial :
https://www.digitalocean.com/community/tutorials/how-to-upgrade-to-ubuntu-16-04-lts
The problem is this tutorial don't install me Ubuntu 16.04 but Ubuntu 18.04. When i try go on my phpmyadmin, it don't interpret the php code and show me a page with the php script (I already try to uninstall and re-install Apache2, MySql, php7.2 and phpmyadmin). After some hours of research on internet i don't see where my configuraton of LAMP have a trouble so i've decided to downgrade my Ubuntu and re-install my LAMP server. Apparently it's impossible to downgrade Ubuntu without unistall and re-install it. So i don't know how to do that because the host of my server is in France and I'am on Japan for my internship. I actually work on my project with a ssh connection so can I do it by ssh ?
If it is not possible can you help me to find where my configuration of LAMP have a trouble ?
Thanks a lot for your help and sorry for my horrible inglish and this lllooonnnggg text.

A: I think, you should better understand an error why your server doesn't interpret your PHP code. It's less problem than reinstall full system at all.
Have you checked apache logs? Have you checked if PHP installed OK?
My advice is to install panel, for example, free Vesta and panel install all services for you (instead of LAMPP). IMHO, it's better than LAMP for remote server.

A: I used the Rufus tool to create a bootableUSB flash drive for Ubuntu 16.4 so that I can downgrade my Ubuntu from 18.4 to 16.4. See link.
By following the new install instructions for 16.4, it worked. In terms of options, I checked the following:

*

*Since I didn't want to keep 18.4, I erased it by checking the box for formatting the / partition.

*To keep my data files intact, I unchecked the box for formatting the /home partition.

Below is the output of the "df /dev/sda* -h" command for my 80G HDD after downgrade:
Filesystem      Size  Used Avail Use% Mounted on
udev            1.3G     0  1.3G   0% /dev
udev            1.3G     0  1.3G   0% /dev
/dev/sda2        37G  4.2G   31G  12% /home
/dev/sda5       3.7G   73M  3.4G   3% /boot
/dev/sda6        30G  4.1G   24G  15% /
udev            1.3G     0  1.3G   0% /dev

which has allocated 32G for /, 4G for /boot, 4G for /swap and 40G for /home.
To verify, I issued
"cat /etc/lsb-release" and got:
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.4 LTS"

A: you want to downgrade the Ubuntu 18 to Ubuntu 16, kindly follow the procedures below.

*

*insert Ubuntu 16 CD In a system, choose boot from CD and choose install Ubuntu 16.

*while installing  automatically it comes like uninstall the Ubuntu 18 and reinstall it again.select the option and continue.(follow the same procedure like ubuntu 18)

*same partition it will take it will not erase any data and will downgrade to Ubuntu16.

*same it will applied or dual boot.


text:
Q: Local-only Automator service (not on iCloud) I do not want to have the services on iCloud, but instead just local to Mac. Here's what the Automator dialog displays.

How can it be done?

A: Deselect Automator In iCloud System Preferences

A: Simply click on any of the folder under Recent Places. You can also native to a local directory of your choosing. If you select a local directory, the service won't be saved in iCloud storage.
You need not turn disable iCloud for Automator for saving the service locally.


text:
Q: Proving orthogonality of Hermite polynomials The orthogonality relation for Hermite polynomials is:
$$\int\limits_{-\infty}^\infty e^{-x^2} H_n(x) H_m(x)\ dx = 2^n n! \sqrt{\pi} \delta_{nm}$$
where $\{ n, m \} \in \mathbb{Z}_{\geq 0}$, $H_n(x)$ is the Hermite polynomial of order $n$, and $\delta_{nm}$ is the Kroneker delta indicator, which is $1$ if and only if $n=m$.
The straightforward approach does not work for arbitrary (but unspecified) $n$ and $m$:
Assuming[{n, m} ∈ NonNegativeIntegers,
 Integrate[
  E^(-x^2) HermiteH[n, x] HermiteH[m, x],
  {x, -∞, ∞}]]

but will work for any specified such orders (see related question).
How can I computationally derive the orthogonality relation for arbitrary $n$ and $m$?

A: Since I got a thumbs up, I will present something. To the author of the OP, please let me know whether this is useful or not. If not, I am happy to delete it.
We begin by recording the Rodrigues' formula for the Hermite polynomials
$$
\begin{equation}
H_n (x) = (-1)^n  e^{x^2} \frac{d^n}{dx^n} \left( e^{-x^2} \right)
\end{equation}
$$
Using the above we can re-write the integral of interest as follows:
$$
\begin{equation}
\int^{\infty}_{-\infty} ~ dx ~ e^{-x^2} ~ H_m(x) ~ H_n(x) = (-1)^n \int^{\infty}_{-\infty} ~ dx ~ H_m(x) ~ \frac{d^n}{dx^n} \left( e^{-x^2} \right)
\end{equation}
$$
And now we can separate two cases:
Case 1 We examine $m \neq n$. We will choose $m < n$ without loss of generality and integrate by parts to take all derivatives on the Hermite polynomial.
Assuming[{n, m} ∈ NonNegativeIntegers && m > n,
 Integrate[
  D[HermiteH[m, x], {x, n}] Exp[-x^2], {x, -Infinity, Infinity}]]

Case 2 here we have $m=n$. Here, Mathematica provides us with the following
Assuming[{n} ∈ NonNegativeIntegers && n >= 0,
 Integrate[
  D[HermiteH[n, x], {x, n}] Exp[-x^2], {x, -Infinity, Infinity}]]

The first bit is easy to see that is what we want, since
Factorial[n] == Gamma[1 + n] == FactorialPower[n, n] // FullSimplify

The thing that I have not understood as of yet, is why Mathematica is giving a 0. If I do
Integrate[
 D[HermiteH[0, x], {x, 0}] Exp[-x^2], {x, -Infinity, Infinity}]

I get

Edit thanks to @BobHanlon for reminding me.
With
res = Assuming[{n} ∈ NonNegativeIntegers && n >= 0,
  Integrate[
   D[HermiteH[n, x], {x, n}] Exp[-x^2], {x, -Infinity, Infinity}]]

FunctionExpand will automatically convert FactorialPower to a Gamma.
Then, we can change the ComplexityFunction
gammatofac[expr_, n_] :=
  FullSimplify[expr, n ∈ Integers && n > 0,
   ComplexityFunction -> ((LeafCount@# +
        10 Count[#, _Gamma | _Pochhammer, {0, \[Infinity]}]) &)];

to convert the Gamma to a Factorial. Altogether it reads
gammatofac[Flatten[(res // FunctionExpand)[[1]]][[1]], n]

and returns

To the mathematicians: please do not hunt me down and kill for writing $\int dx ~ \texttt{stuff}$. We do it all the time in Physics.

A: Here us a simple analytical proof of the orthogonality of Hermite polynomials.
Physicists know well, that the Hermite functions are eigenfunctions of the harmonic oscillator. The Hermite function is:
psi[n,x]= Exp[-x^2/2] HermiteH[n,x]

where, for simplicity, I did not write the normalization factor. The Eigen equation reads:
(-d^2/dx^2 + x^2) psi[n,x] == (2n+1) psi[n,x]

Now, it is well know that Eigen functions to different Eigen values are orthogonal (matrix element of 2 different Eigen functions of the Eigen operator must be zero).

A: Surely you know this, and probably not fully addressing your question ...
 p[{n_, m_}] :=  Integrate[Exp[-x^2]
                 HermiteH[n, x] HermiteH[m,x], {x, -\[Infinity], \[Infinity]}];
 Timing[Map[p, Tuples[{Range[10], Range[10]}]]]

returns:

That is, you can calculate the integral for any finite set, but it will take a long time.
It took 17 seconds to compute 100 of them on M1 chip!


text:
Q: SFTP connection from salesforce to Globalscape I need to connect my salesforce instance to Globalscape(file transfer suite) using a SFTP conncetion to extract a flat file.
I am looking for a freeware so that I could automate the same through a batch process.
Can anyone tell me what are my options?
Jitterbit/Filezilla
Since this will be used for marketing cloud solutions , is automation studio a viable option?

A: Yes, you can use Automation Studio for it. The approach is described here.
The key steps are
1) Create a File Transfer Activity
2) Create Import Activity
3) Create "Import Action Settings" and "Import Completion Settings"
4) Create Automation using Automation Studio
There're other 3rd party tools as well e.g. - Put It Forward provides a Free tier which should serve your requirements well enough and


text:
Q: How to remove line break after a tag I use Django template system to do code generation (not only for HTML). I'm somehow troubled by redundant line breaks in django templates.
Here is an example. The template is as below:
// something
    {% for element in elements %}
      Element: {{ element.name }},
    {% endfor %}
// something else

The rendered output will be:
// something

      Element: foo

      Element: bar

// something else

Expected rendered output should be:
// something
      Element: foo
      Element: bar
// something else

After googled a bit, I know I can use {% spaceless %} to remove any white spaces in rendered output. It is quite useful for HTML, but will not work for other languages. My current solution is to add a special string after a tag and replace them with empty string in output.
Is there any better solution to remove line break after a tag?

A: For your production environment you might consider minifying your html to get that little bit more performance. For example using https://pypi.python.org/pypi/django-htmlmin.
If you are only interested in the esthetics, then the .strip function as noted by e-nouri is probably your best answer.

A: You can use .strip on your attributes to strip/trim.
// something
    {% for element in elements %}
      Element: {{ element.name.strip }},
    {% endfor %}
// something else

A: The line breaks in code shouldn't matter, but you can avoid them when you put everything in one line, which doesn't look that good anymore:
{% for element in elements %}Element: {{ element.name.strip }},{% endfor %}


text:
Q: Windows Server 2008 Web Edition Networked Printer Limitations I am told by network admin that windows 2k8 web has a networked/shared printer cap, that is I can only see 10 networked printers but no more, I don't yet have an environment to prove it right or wrong, is that true? where is it documented?
We will setup 100 windows 7 pro or 8 pro work stations in a big WorkGroup. (yup, don't ask me why there is no domain) Each of them is attached to a USB printer, and each of these printers is shared on network. Meaning you can hook up to mine, I can print on yours.
Now, this 2k8 web server is among one of them in this WorkGroup. My question is, can this 2k8 server see and print on the 100 printers shared by each work station on the WorkGroup?

A: I'm gonna go with "probably yes" since Windows doesn't really have a practical hard limit on printers (and I believe we accessed 100+ for a really messed up senior prank one year in high school from a netbook). If a netbook running basic windows 7 can do it, a server can do it.
The bottleneck is going to end up being drivers in all likelihood.


text:
Q: Get Relation of Followed or Public User I am working on a social app.  I have users that can have private accounts.  Users can also follow each other.  What is the fastest way using ActiveRecord or pure SQL to fetch all the records of a has_many on a User that either belong to someone I am following or belong to a public user.  In pseudo code:
User.get_all_posts_for_users_being_followed_by(me) + User.get_all_posts_for_public_users
I have this:
SELECT `posts`.*
FROM   `posts`
WHERE  ( user_id IN (SELECT id
                 FROM   users
                 WHERE  visibility = 'all'
                 UNION
                 SELECT followable_id
                 FROM   follows
                 WHERE  followable_type = "User"
                    AND follower_type = "User"
                    AND follower_id = 4
                    AND follows.status = 1) )

But I was hoping there might be a faster way to handle that, or a way to do it with Rails query methods.

A: You can perform your clear query with ActiveRecord, but I recommend to use this pure version for_now, because it's very easy to modificate it now. You need pay attention on this:

*

*The query might be faster, if you add indexes
add_index :users, :visibility, :name => 'visibility_ix'

*Selecting all columns with the * wildcard will cause the query's meaning and behavior to change if the table's schema changes, and might cause the query to retrieve too much data.

*IN() and NOT IN() subqueries are poorly optimized. MySQL executes the subquery as a dependent subquery for each row in the outer query. This is a frequent cause of serious performance problems in MySQL 5.5 and older versions. The query probably should be rewritten as a JOIN or a LEFT OUTER JOIN, respectively.


text:
Q: Dúvida usando a API Proxy do JavaScript Fiz este código para estudar o Proxy do JavaScript. Ele funciona detectando a alteração da propriedade do objeto porém quando chamo a propriedade no console.log ele não aparece alterada
JS
var f = {nome: "Fulano"}

f = new Proxy (f, {
  set: (target, prop) => {
        if (prop === "nome") {
        alert('Nome alterado')
    }
  }
})

$('#edita').click(() => {
    f.nome = $('input').val()
  console.log(f.nome)
})

HTML
<input type="text">
<button id="edita">EDITAR NOME</button>

Após alterar o nome no evento click do botão o console.log ainda exibe Fulano

A: O objeto Proxy tem um alto grau de flexibilidade, não serve somente para observar mudanças efetuas encima de um objeto, e justamente por esse motivo que quando você escreve um comportamento como set, get, has, você precisa o sobreescrever por inteiro. Foi isso que faltou no seu set, faltou delegar o comportamento de atribuição para o target.
var f = {nome: "Fulano"}

f = new Proxy (f, {
  set(target, prop, value) {
    if (prop === "nome") {
      alert('Nome alterado')
    }

    target[prop] = value;
  }
})


text:
Q: Calling functions on require()d modules in Lua gives me "attempt to index local 'x' (a boolean value)" I've read PIL and the ModulesTutorial on creating modules but I'm having trouble require()ing them correctly.
Here is my setup:
-- File ./lib/3rdparty/set.lua
local ipairs = ipairs
module( "set" )
function newSet (t)
  local set = {}
  for _, l in ipairs(t) do set[l] = true end
  return set
end

And:
-- File ./snowplow.lua
local set = require( "lib.3rdparty.set" )
module( "snowplow" )
local SUPPORTED_PLATFORMS = set.newSet { "pc", "tv", "mob", "con", "iot" }

Then if I run snowplow.lua:
lua: snowplow.lua:4: attempt to index local 'set' (a boolean value)
stack traceback:
  snowplow.lua:4: in main chunk
  [C]: ?

What am I doing wrong in my module definition - what is the boolean exactly? Also, if I append a return _M; at the bottom of my set.lua, then everything starts working - why?

A: true is usually returned by require if module function is not used inside module and module code doesn't return a value.
But anyway it seems strange.
-- file m0.lua
module'm0'

--file dir1\m1.lua
module'm1'

--file test.lua
print(require'm0')
print(m0)

print(require'dir1.m1')
print(m1)

for k,v in pairs(package.loaded) do
   if k:match'm%d' then print(k, v) end
end

--output
table: 0036C8C8
table: 0036C8C8
true
table: 0036B6B0
m0      table: 0036C8C8
m1      table: 0036B6B0
dir1.m1 true

So, you can simply use global variable set instead of local set assigned a value returned by require.

UPD :
It is recommended to avoid using module function and always return your table at the end of your module.  In that case the whole picture is just fine:
-- file m0.lua
return 'string0'

--file dir1\m1.lua
return 'string1'

--file test.lua
print(require'm0')
print(m0)

print(require'dir1.m1')
print(m1)

for k,v in pairs(package.loaded) do
   if k:match'm%d' then print(k, v) end
end

--output
string0
nil
string1
nil
m0      string0
dir1.m1 string1

UPD2 :
Problem disappears if you replace module( "set" ) with module('lib.3rdparty.set').
So, each module must remember its relative path.
Now you could access it either by calling require'lib.3rdparty.set' or by reading global variable lib.3rdparty.set - the result would be the same.

A: require("lib.moduleName")
local moduleName = moduleName

I'm not sure why Lua returns a boolean when you require a module on a different directory, but it seems the module is correctly set on the the global variable. So I simply used that and put it on a local variable with the same name.


text:
Q: Utilizing local variables of a function and setTimeout I have hit a snag in a website I am building. I have a function which adds a specific class to different ids. The end result is to have images fade out one at a time on the home page. I used the local variable a so that I can easily code the different id's without having to write 3 separate functions. However I am having trouble using setTimeout. I cannot seem to get setTimeout to work at all. Any help would be greatly appreciated. The classes get added to the ids with no problem, I am just having trouble with the setTimeout function. I've used multiple methods I've seen on here but I don't really understand them. Any help would be greatly appreciated. Here is my code:

window.onload;

var fetchOne =document.getElementById('picOne');
console.log(fetchOne);

var fetchTwo =document.getElementById('picTwo');
var fetchThree =document.getElementById('picThree');

function AttachClass (a){

    a.className ='opacity';

}

setTimeout(AttachClass.bind(null,a),8000);

AttachClass (fetchOne);

AttachClass (fetchTwo);

AttachClass (fetchThree);
#picOne{

    opacity: 1;

    transition: opacity 2s ease-in-out

}

#picOne.opacity{
    opacity: 0;

}

#picTwo{
    opacity: 1;
    z-index: -1;
    transition: opacity 2s ease-in-out

}

#picTwo.opacity{
    opacity: 0;

}

#picThree{
   opacity: 1;
    z-index: -2;

    transition: opacity 2s ease-in-out
}

#picThree.opacity{
    opacity: 0;

}

A: You're only setting up 1 handler for 1 image with that timeout and a is never defined within the code you've pasted so the setTimeout won't work.
In order for them to fade out separately you'd need to create one setTimeout per image you want faded.
for (var i = 0; i < images.length; i++) {
    setTimeout(AttachClass.bind(null, images[i]), 2000);
}

Secondly, that window.onload seems to be a remnant of something, you can safely remove that.
Thirdly, there's no need to call the function AttachClass after you've setup the setTimeout since it's now handled by setTimeout.
Now you'd just need to stick the images you've queried the DOM for in to an array called images and off you'd go.
It'd look something like this
var fetchOne = document.getElementById('picOne');
var fetchTwo = document.getElementById('picTwo');
var fetchThree = document.getElementById('picThree');

function AttachClass(a) {
    a.classList.add('opacity'); // IE10+ support only
};

let images = [fetchOne, fetchTwo, fetchThree];

for (var i = 0; i < images.length; i++) {
  setTimeout(AttachClass.bind(null, images[i]), 5000);
}

If you'd like to have it further refined, you could stick a class on all images. I chose the class name pic, query the DOM for that class name and then set the above timeouts.
var images = document.getElementsByClassName('pic');

function AttachClass(a) {
  a.classList.add('opacity');
}

for (var i = 0; i < images.length; i++) {
  setTimeout(AttachClass.bind(null, images[i]), 1000);
}

JSBIN here for you to play around with!
Happy hacking!

A: Probably you need something like this:

window.onload = function() {

  AttachClass();

  function AttachClass() {
    setTimeout(function() {
      var a = document.querySelector('.pics img:not(.opacity)');
      if (a) {
        a.className = 'opacity';
        AttachClass();
      }
    }, 1200);
  }
}
.pics img {
  width: 100px;
  opacity: 1;
  transition: opacity 1s ease-in-out
}

img.opacity {
  opacity: 0;
}

A: Thanks everyone for your help. They helped me find my eventual answer. This is how I ended up solving my snag.

window.onload
var fetchOne =document.getElementById('picOne');
console.log(fetchOne);
var fetchTwo =document.getElementById('picTwo');
var fetchThree =document.getElementById('picThree');

setInterval(function() {

    setTimeout(function AttachClass1 (){ fetchOne.className ='opacity';},1000);

    setTimeout(function AttachClass2 (){ fetchTwo.className ='opacity';},8000);

    setTimeout(function AttachClass3 (){ fetchThree.className ='opacity';},14000);

    setTimeout(function RemoveClass2 () { fetchTwo.classList.remove("opacity");},14000)

    setTimeout(function RemoveClass1 () { fetchOne.classList.remove("opacity");},18000)

    setTimeout(function RemoveClass3 () { fetchThree.classList.remove("opacity");},18000)

},24000);

The images flip through one at a time just as I wanted. Then they return with the classlist.remove property. I can also control all the intervals as I like. I'm not familiar at all with JQuery yet so some of the answers above confused me a little. A like to stick to mainly just javascript and this is what I am most comfortable with at the moment. Thanks again for all your help!

A: Here you go

 var imgs = document.querySelectorAll('.fade');
    var delay = 500;
    for (var i = 0; i < imgs.length; i++) {
        (function(i){
        setTimeout(function () {
            imgs[i].classList.add('opacity');
        }, delay * (i + 1))
        })(i)
    }
.fade {
opacity:.2;
transition: 1s all ease-in-out;
}

.fade.opacity {
opacity:1
}


text:
Q: Marking an assembly I am trying to make a multi tenated mvc website where views can be overridden for each tenant.
I'm using RazorGenerator in order to be able to load views from a compiled assembly (with some modifications to allow multiple assemblies).
So now I need to have a way to identify Dlls in the bin that contain views. Currently I'm just creating a dummy class (Class1) and looping through AppDomain.CurrentDomain.GetAssemblies().ToList() to see what asssemblies include that dummy class
I can imagine a few possiblities.

*

*Create an interface IViewPlugin and assign that to my Class1 in each view plugin assembly

*Name each assembly MyCompany.Presentation.Views.Plugins.[ClientName] and include all plugins that match.

Are there any other better ways to mark assemblies as being a 'plugin' assembly when the assemblies themself don't have any actual classes in them (unless I specifically create one for purposes of identifying plugin assemblies)

A: You can create a custom attribute:
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = true)]
public class PluginAssemblyAttribute : Attribute
{
}

And apply it on the assembly:
[assembly: PluginAssembly]

You can then check if the assembly has the attribute:
if (assembly.IsDefined(typeof(PluginAssemblyAttribute), false)
    ...


text:
Q: Distance between points I am wondering how can I solve following problem.
Arrange randomly n points inside a square of the side length a under the condition that the distance between any two points may not be smaller than 1.
I would like to see how can it be solved.

A: If the points really need to be random, then draw random points and place them in the square if there is not already other points at distance less than 1.
Anyway, at some moment the procedure can start looping forever if there is no room left, but this is difficult to establish.
An approximate solution can be implemented by means of a high resolution image of the square. Every time you place a point, erase the disk around it, and then avoid placing points in an erased area.
You can think of an exact solution, by means of a solution to the "Dynamic Planar Nearest Neighbors" problem, but this can be quite arduous.


text:
Q: Installing drivers for a windows 7 guest in virtualbox I am new to ubuntu. I want to know how to install drivers such as lan, wifi, audio, video & graphics, webcam and so in Windows 7 32bit installed as a guest OS inside Ubuntu 10.10 (host) using Virtual Box 3.2.8.
I am using this in a Toshiba Satellite c650 psc 14g. I had downloaded the drivers from the Toshiba website. They work fine when using Windows 7 32 bit as host OS.
Then what are the main differences between dual boot and Virtual Box?

A: System inbuilt components like LAN, Wifi, soundcard,or graphics card will be used from the host OS. They will be virtualized using an emulation for the guest OS. In many cases you are able to choose from different emulation modes in the virtual machine settings.

Therefore you can not install these drivers to your guest OS.

However some external components like USB attached devices (e.g. printer, scanner, Bluetooth dongle) do need an additional driver for the guest OS. In Windows you will be asked for these drivers as soon as you capture the device from the Virtual Box Manager.
Note: for full USB 2.0 support we need to run the PUEL version of Virtual Box that to date is on version 4.1.8.

A: You don't need (and you can't) install your real hardware drivers inside VirtualBox. Windows, while running inside VirtualBox can't access your hardware, it can only interact with a Virtual (false) hardware that VirtualBox will set for it. Virtual Box will translate it to the real hardware. You can get a more complete explanation of how virtual machines work in wikipedia.
That it's the reason that you can't really play the latest games under Virtual Box. Nor the game, nor Windows can access your graphics card to get the most speed. This is also the reason why running windows under a virtual machine is slower than running it on bare metal.
But you will need to install the drivers for the Virtual Hardware to get the best experience possible. They are called Guest Additions in Virtual Box, check this question to install them.
Note that the virtual machine has no direct access to your card, so watching HD videos or playing 3D games can't be accelerated by it and it will be slower than doing it in the host. As you experienced, the speed will be similar to the one that you see while using windows without the drivers (i.e. using no video card acceleration).

A: Most probably you wont need to install any drivers as windows will automatically detect the emulated hardware and install the required drivers. As windows is running on virtual box so it needs the drivers for emulated hardware and not your actual hardware. Mapping emulated hardware to real is the job of VirtualBox and Winodws is not aware that it is running on emulated hardware.

A: You don't have to Install Anything in the Windows guest, Windows installs it automatically.
And the difference between Dual Boot and Emulated Hardware are just...to many, for one it will be slower in the Virtual Machine, you don't have complete 3D hardware acceleration, nor you can't access directly your physical hardware from the Virtual Machine.
The Virtual Machine is as fast as your real hardware can handle it and judging by the Lack of Specs and looking at the Basic Toshiba laptop i would just install Windows side by side with Ubuntu.

A: Ubuntu 14.04 LTS Trusty Tahr host OS
VirtualBox 4.3.10Ubuntu r93012
Windows 7 Home Premium guest
I had the same problem. I first burned the .iso file to a DVD and set up passthrough access to the CD/DVD drive on my Toshiba Satellite C660 laptop. (But you probably don't need to do this; just use the .iso file and mount it as a DVD.) The Windows 7 folder for the VM was created, and the Windows 7 installer started okay. But just after I clicked Start Setup, a dialogue asked "Where do you want to install Windows?, and displays the virtual VDI volume.
After I clicked Next, a dialogue asked me to select drivers, but the list was blank. When I chose either the DVD .iso or the virtual VDI drive, an alert advised that no drivers were found.
The answer is to change the permissions of /home/<~my-home>/VirtualBox VMs/Windows 7/ and its subsidiary files and folders to Read/Write for owner and group (or even for everybody if it's your own computer). The installer hummed along doing its thing happily.


text:
Q: How to Show/hide a select box if a value in another select box is chosen I have two select boxes on a page, coded as follows:

    @Html.LabelFor(model => model.SearchList, htmlAttributes: new {@class = "control-label col-md-2"})

        @Html.DropDownListFor(model => model.SearchListId, Model.SearchList, "Select Search Type", htmlAttributes: new { @class = "control-label input-width-xlarge", id = "SearchList" })
        @Html.ValidationMessageFor(model => model.SearchListId, "", new {@class = "text-danger"})

    @Html.LabelFor(model => model.GroupSortTypes, htmlAttributes: new {@class = "control-label col-md-2"})

        @Html.DropDownListFor(model => model.GroupSortId, Model.GroupSortTypes, "Select Group Sort", htmlAttributes: new { @class = "control-label input-width-xlarge", id = "GroupSortTypes"})
        @Html.ValidationMessageFor(model => model.GroupSortId, "", new {@class = "text-danger"})

How can I make the second select box (GroupSort) visible only when a particular option is chosen in the first? In this case it would be option three out of five options.
Thanks!

A: First add a class hide to your 2nd dropdown and write below code in your js file
$(document).on('change','#SearchList',function(){
       var optionSelected = $("option:selected", this);// Use this if only needed
       var valueSelected = this.value;
       var textSelected = this.text;//Use any of the above either value or text in your if condition
       if(valueSelected=="Your Option")
       {
            $("#GroupSortTypes").removeClass("hide");
       }
       else
       {
            $("#GroupSortTypes").addClass("hide");
       }
});


text:
Q: Append Char To StringBuilder C++/CLI I am trying to use StringBuilder to create the output that is being sent over the serial port for a log file. The output is stored in a byte array, and I am recursing through it.
ref class UART_G {
   public:
     static array<System::Byte>^ message = nullptr;
     static uint8_t message_length = 0;
};

static void logSend ()
{
  StringBuilder^ outputsb = gcnew StringBuilder();
  outputsb->Append("Sent ");
  for (uint8_t i = 0; i < UART_G::message_length; i ++)
  {
    unsigned char mychar = UART_G::message[i];
    if (
      (mychar >= ' ' && mychar <= 'Z') || //Includes 0-9, A-Z.
      (mychar >= '^' && mychar <= '~') || //Includes a-z.
      (mychar >= 128 && mychar <= 254)) //I think these are okay.
    {
      outputsb->Append(L""+mychar);
    }
    else
    {
      outputsb->Append("[");
      outputsb->Append(mychar);
      outputsb->Append("]");
    }
  }
  log_line(outputsb->ToString());
}

I want all plain text characters (eg A, :) to be sent as text, while functional characters (eg BEL, NEWLINE) will be sent like [7][13].
What is happening is that the StringBuilder, in all cases, is outputting the character as a number. For example, A is being sent out as 65.
For example, if I have the string 'APPLE' and a newline in my byte array, I want to see:
Sent APPLE[13]

Instead, I see:
Sent 6580807669[13]

I have tried every way imaginable to get it to display the character properly, including type-casting, concatenating it to a string, changing the variable type, etc... I would really appreciate if anyone knows how to do this. My log files are largely unreadable without this function.

A: You're getting the ASCII values because the compiler is choosing one of the Append overloads that takes an integer of some sort. To fix this, you could do a explicit cast to System::Char, to force the correct overload.
However, that won't necessarily give the proper results for 128-255. You could cast a value in that range from Byte to Char, and it'll give something, but not necessarily what you expect. First off, 0x80 through 0x9F are control characters, and whereever you're getting the bytes from might not intend the same representation for 0xA0 through 0xFF as Unicode has.
In my opinion, the best solution would be to use the "[value]" syntax that you're using for the other control characters for 0x80 through 0xFF as well. However, if you do want to convert those to characters, I'd use Encoding::Default, not Encoding::ASCII. ASCII only defines 0x00 through 0x7F, 0x80 and higher will come out as "?". Encoding::Default is whatever code page is defined for the language you have selected in Windows.
Combine all that, and here's what you'd end up with:
for (uint8_t i = 0; i < UART_G::message_length; i ++)
{
  unsigned char mychar = UART_G::message[i];

  if (mychar >= ' ' && mychar <= '~' && mychar != '[' && mychar != ']')
  {
    // Use the character directly for all ASCII printable characters,
    // except '[' and ']', because those have a special meaning, below.
    outputsb->Append((System::Char)(mychar));
  }
  else if (mychar >= 128)
  {
    // Non-ASCII characters, use the default encoding to convert to Unicode.
    outputsb->Append(Encoding::Default->GetChars(UART_G::message, i, 1));
  }
  else
  {
    // Unprintable characters, use the byte value in brackets.
    // Also do this for bracket characters, so there's no ambiguity
    // what a bracket means in the logs.
    outputsb->Append("[");
    outputsb->Append((unsigned int)mychar);
    outputsb->Append("]");
  }
}

A: You are recieveing ascii value of the string .
See the Ascii chart
 65 = A
 80 = P
 80 = P
 76 = L
 69 = E

Just write a function that converts the ascii value to string

A: Here is the code I came up with which resolved the issue:
static void logSend ()
{
  StringBuilder^ outputsb = gcnew StringBuilder();
  ASCIIEncoding^ ascii = gcnew ASCIIEncoding;
  outputsb->Append("Sent ");
  for (uint8_t i = 0; i < UART_G::message_length; i ++)
  {
    unsigned char mychar = UART_G::message[i];
    if (
      (mychar >= ' ' && mychar <= 'Z') || //Includes 0-9, A-Z.
      (mychar >= '^' && mychar <= '~') || //Includes a-z.
      (mychar >= 128 && mychar <= 254)) //I think these are okay.
    {
      outputsb->Append(ascii->GetString(UART_G::message, i, 1));
    }
    else
    {
      outputsb->Append("[");
      outputsb->Append(mychar);
      outputsb->Append("]");
    }
  }
  log_line(outputsb->ToString());
}

I still appreciate any alternatives which are more efficient or simpler to read.


text:
Q: google script conditional formatting I have put together a google spreadsheet that highlights the first four cells in a row if the value in cell 6 is within 3 days of the current date, but I cannot figure out how to add an if/and statement to exclude all entries that have "East" in row E.
This is the code that I have had success with, minus the exclusion of East not highlighting.
onEdit(e) {
if (e) {
var ss = e.source.getActiveSheet();
var r = e.source.getActiveRange();
if (r.getRow() != 2 && ss.getName() == "Sheet1") {
Days_Remaining = ss.getRange(r.getRow(),6).getValue();
rowRange = ss.getRange(r.getRow(),1,1,4);
if (Days_Remaining < 3.8) {
rowRange.setBackgroundColor("#FF0000");
} else if (Days_Remaining == 'N/A') {
rowRange.setBackgroundColor("#ffffff");
} else if (Days_Remaining > 3.9) {
rowRange.setBackgroundColor("#ffffff");

https://docs.google.com/spreadsheet/ccc?key=0AqtCuK7ex8ZNdGxKLUZpQnZ3UzRCV3VoclVDbFVqQnc#gid=0

A: If you use the new Google Sheets, you can simplify by using Conditional Formatting
If not, you need to get the values in column 5 as well and add an IF block based on that. For example:
Follow_up = ss.getRange(r.getRow(),5).getValue();

And then, before you check Days_Remaining, you should add
If(Follow_up <> "East") {//rest of the checks here }


text:
Q: How to correctly join two tables that each have Start Date and Stop Date columns? This should be easy, maybe even a duplicate, but neither my brain nor my search engine is being very helpful today.
My problem is as below:

Given two tables that both have:

*

*A start date

*A stop date

*A property of an employee. Let's say Desk Number in table A and Team in table B

*The employee's unique ID number.

join together the two tables in some honest way such that you only need one start and stop date per row in the resulting table.

Example input and desired output:
Table A:

Start Date
Stop Date
ID
Desk Number

01/20
05/20
0100
55

03/20
06/20
0100
56

02/22
04/22
0200
91

Table B (notice the overlap in employee 0100's dates):

Start Date
Stop Date
ID
Team Number

01/20
04/20
0100
2

02/20
06/20
0100
3

02/22
04/22
0200
8

Example output:

Start Date
Stop Date
ID
Desk Number
Team Number

01/20
04/20
0100
55
2

02/20
05/20
0100
55
3

02/20
06/20
0100
56
3

02/22
04/22
0200
91
8

I can handle manipulating the resulting dates once the tables are joined correctly, but the join in of itself is causing me issues. I just can't figure out how to make sure that some dates that fall outside of the range don't slip in. My currently solution for the join, which I'm unsure of, was to just join on
[Table A].[Start Date] <= [Table B].[Stop Date]
[Table B].[Start Date] <= [Table A].[Stop Date]

and then take the max/min date as appropriate (don't worry about that part, I only care about the join), but I very much doubt that the solution could really be that simple.

A: Assuming I'm not getting something wrong here, the desired output should be

Start Date
Stop Date
ID
Desk Number
Team Number

01/20
04/20
0100
55
2

02/20
05/20
0100
55
3

03/20
04/20
0100
56
2

03/20
06/20
0100
56
3

02/22
04/22
0200
91
8

Your intuition as to the join is indeed correct, this produces the right result:
SELECT CASE
         WHEN teams.start_date > desks.start_date
         THEN teams.start_date
         ELSE desks.start_date
       END start_date
     , CASE
         WHEN teams.stop_date < desks.stop_date
         THEN teams.stop_date
         ELSE desks.stop_date
       END stop_date
     , desks.id
     , desks.desk_number
     , teams.team_number
  FROM desks
  JOIN teams
    ON desks.start_date < teams.stop_date
   AND teams.start_date < desks.stop_date
   AND teams.id = desks.id

Working demo on dbfiddle