text:
Q: How to show that $M_{2\times 2}(\mathbb{R})=W_1\oplus W_2$ based on the following assumption? Let the subspaces $W_1=\{\begin{pmatrix}a&b\\-b&a \end{pmatrix}|a, b\in \mathbb{R}\}$ and  $W_2=\{\begin{pmatrix}c&d\\d&-c \end{pmatrix}|c, d\in \mathbb{R}\}$ of $M_{2\times 2}(\mathbb{R})$,how to show that $M_{2\times 2}(\mathbb{R})=W_1\oplus W_2$?
By the definition of direct sum, $V= W_1\oplus W_2 \iff V=W_1+W_2 $ and $W_1\cap W_2=\{0\}$ .
Since both $W$ are subspaces of $V$, we can write $v=w_1+w_2$ where $w_1\in W_1$ and $w_2\in W_2$. Because every $v$ can be represented as $e\begin{pmatrix}a&b\\-b&a \end{pmatrix}+ f\begin{pmatrix}c&d\\d&-c \end{pmatrix}$, $V=W_1+W_2$. Since each $w_1\in W_1$ cannot linearly combines to form vectors in $W_2$, $W_1\cap W_2=\{0\}$   .
I think my proof is totally useless and does not show anything, could anyone revise it?

A: $$\begin{align*}&\bullet\;\begin{pmatrix}a&b\\c&d\end{pmatrix}=\begin{pmatrix}\frac{a+d}2&\frac{b-c}2\\-\frac{b-c}2&\frac{a+d}2\end{pmatrix}+\begin{pmatrix}\frac{a-d}2&\frac{b+c}2\\\frac{b+c}2&-\frac{a-d}2\end{pmatrix}\;\implies\;V=W_1+W_2\\{}\\
&\bullet\;\begin{pmatrix}a&b\\c&d\end{pmatrix}\in W_1\cap W_2\implies\begin{cases}a=d=-d\\b=-c=c\\\end{cases}\;\implies a=b=c=d=0\end{align*}$$
and thus $\;V=W_1\oplus W_2\;$


text:
Q: How to make phrase sentence about availability for a meeting I am writing a formal email to inform my availability for a meeting. I want to write that I am available all week except on Monday morning and Friday morning. Which of the following is correct?

*

*I am available all week except on Monday and Friday morning.

*I am available all week except on Monday morning and Friday morning.

*I am available all week except on mornings of Monday and Friday.

For option 1, it sounds like I am not available on entire Monday and morning of Friday.
For option 2, using morning twice is repetition.
I would appreciate if someone can comment on or rephrase these options.

A: [I have been asked by the OP to post my comment as an answer. Initially I decided not to because it had already been posted by Peter, but as I disagree with part of Peter's answer (see my comment below his answer), I thought it may be useful to post my own suggestions.]
In the light of earlier posts and comments, the selection below tries to illustrate the usage of "not", "neither", "nor", "except" and "un-" as negatives.  But be careful not to use two negatives: note that the option using "neither" omits the "not".

I am available all week, except on Monday and Friday mornings.
I am not available on Monday morning nor on Friday morning, but otherwise am free.
I am not available on either Monday morning nor Friday morning, but otherwise am free.
I am available on neither Monday morning nor Friday morning, but am free for the rest of the week.
I am available at any time next week, except on the mornings of Monday & Friday.
I am unavailable on both Monday and Friday mornings, but am available at any other time next week.

A: You could use

I am available all week except on Monday and Friday mornings.

As mentioned in the comments, the "s" is very important to signal it applies to both Monday and Friday.
You might also say

For next week, I am not available on the mornings of Monday and Friday.
  I am not available on Monday nor Friday mornings, but otherwise free.

redpajama_set_name: RedPajamaStackExchange


text: Q: Change templates in a child theme I wanted to edit code in a theme. I have created a child theme. I want to edit a posts-3.php file but the changes are not reflecting. Do I have to create folder paths with the same name as that of the parent theme?


text:
Q: Add/remove class when close to bottom of page I have the below jquery which is adding or removing a class when the user hits the bottom of the page. I'd like to adjust this code to implement the change when the user is close to the bottom, or perhaps when the bottom comes into viewport?
Any help greatly appreciated!
JS
// Add/remove class to/from .logo upon reaching bottom of page
$(window).scroll(function() {
   $(".logo").removeClass("viewport-bottom");
   if($(window).scrollTop() + $(window).height() === $(document).height()) {
       //you are at bottom
       $(".logo").addClass("viewport-bottom");
   }
});

A: $(window).scroll(function() {
   $(".logo").removeClass("viewport-bottom");
   if($(window).scrollTop() + $(window).height() > ($(document).height() - 100) ) {
       //you are at bottom
       $(".logo").addClass("viewport-bottom");
   }
});

Change the subtracted value to suit your needs.
Using === would only work when the scroll bar was at that exact pixel.

A: couldn't you just subtract the number to verify when to add or subtract for instance, wouldn't the below say if it's within 50 pixels of the end, hide and show,
// Add/remove class to/from .logo upon reaching bottom of page
$(window).scroll(function() {
   $(".logo").removeClass("viewport-bottom");
   if($(window).scrollTop() + $(window).height() === $(document).height() - 50) {
       //you are at bottom
       $(".logo").addClass("viewport-bottom");
   }
});


text:
Q: Calculate first week of the month from a particular day in Date picker? For example if 1st June is coming on Thursday than Week-1 of June should be from 5th as it's a Monday.
I want to disable alternate weeks in the calendar but the week should start from Monday for the first month only.
I can use momentJS also

A: Steps

*

*Get the start of month with .startOf('month'), I used .add(1, 'month') for pass to next month

*Check if the date is a Monday using .day() that return you a number from 0 to 6 (Sunday - Saturday), so Monday is the number 1

*If it isn't a Monday add to date a week with .add(1, 'week') and set the day at a Monday using .day() but this time pass at the method the number of week that you want set (1)

const MONDAY = 1;

let nextMonthStartDate = moment().add(1, 'month').startOf('month');

if (nextMonthStartDate.day() !== MONDAY) nextMonthStartDate = moment(nextMonthStartDate).add(1, 'week').day(MONDAY);

console.log(`The first complete date of ${nextMonthStartDate.format('MMMM')} start at the ${nextMonthStartDate.format('LLLL')}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

This code write all first complete week of current year.

const numberOfMonth = 11;

const yearStartDate = moment().startOf('year');

const MONDAY = 1;

for (let i = 0; i <= 11; i++) {
  let monthStartDate = moment(yearStartDate).add(i, 'month').startOf('month');
  if (monthStartDate.day() !== MONDAY) monthStartDate = moment(monthStartDate).add(1, 'week').startOf('week').day(MONDAY);
  console.log(`The first complete date of ${monthStartDate.format('MMMM')} start at the ${monthStartDate.format('LLLL')}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>


text:
Q: Optimistic Concurrency I have an Entity Framework Project with several linked entities. Since it is utilized by multiple users at once I've set up a RowVersion-Field for entities which are likely to be edited by several users at once. Unfortunately I now get an OptimisticConecurrencyException every time I try to save a new entity, which is linked to an already existing entity.

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.

The problem is now that this error doesn't really give any pointers as to where the error really lies. It could either be the underlying model that is modified in the meantime, there could be a validation error on the new model or something else.
The code I use to add the new entity is as follows:
using (ctx = new DbContext())
{
    try
    {
        ctx.Samples.Add(model);
        ctx.SaveChanges();
    }
    catch (DbUpdateConcurrencyException ex)
    {
        LogManager.HandleException(ex.InnerException);
    }
}

model is the model i want to add to the database
Edit: As seen above i modified the code to ignore the update of an underlying model. Furthermore i have verified through:
ctx.Database.log = s => Debug.Write(s);

That only an insert statement is sent to the database and not an additional update statement.
INSERT [dbo].[Samples]([IDSample], [ModificationDate], [IDUser])
VALUES (@0, @1, @2)
SELECT [RowVersion]
FROM [dbo].[Samples]
WHERE @@ROWCOUNT > 0 AND [IDSample] = @0 AND [ModificationDate] = @1

I would understand the exception if i would update an entity and the rowversion column wouldn't match, but in this case it's a completely new entity. Is there a way to see if one of the properties is malformed?
Edit2:
Instead of just trimming the milliseconds i now used DateTime.Today instead of DateTime.Now which works. Seemingly there is some problem with datetime2(4) on ModificationDate. I already made sure that ModificationDate is truncated to 4 milliseconds so there should be no parse error.
Edit3:
After switching back to DateTime.Now and trimming the milliseconds it stopped working and the entities are not longer inserted into the database. Could this be caused by the fact that the sql server has problems matching the entities based on millisecond values. I executed the EF generated SQL as seen above with some fictional values and it went through although on some occasions the query didn't return a rowversion-value. In terms of the entity framework, the client would interpret this as a return value of 0 lines and therefore call an concurrency-exception. (It should also be of note that the ModificationDate together with the IDSample is the primary key of the entity.)
Edit4:
I'm now using DateTime.Today and then add the needed precision, which works for me. This can be flagged as solved. (Altough i would have expected that EF can take care of datetime-format-conversion by itself :/)

A: The question I have is where are/were you adding the DateTime? You are creating too many steps to hammer out this problem. Creating a datetime, modifying it, etc.
If you're entity is inheriting from a base class with mapped properties do your concurrency add/update in the DbContext override of SaveChanges().
Here's an example: (written without optimized syntax)
public abstract class EntityBase
{
   public int Id {get; set;}
   public DateTime CreationDate {get; set;}
   public DateTime? ModifyDate {get; set;}
   public string VersionHash {get; set;}
}
public static class EntityBaseExtensions
{
    public static void MyBaseEntityMapping<T>(this EntityTypeConfiguration<T> configuration) where T : EntityBase
    {
        configuration.HasKey(x => x.Id);
        configuration.Property(x => x.CreationDate)
                                 .IsRequired();
        configuration.Property(x => x.ModifyDate)
                                 .IsOptional();
        configuration.Property(x => x.VersionHash).IsConcurrencyToken();
    }
}
public class MyEntity : EntityBase
{
   public string MyProperty {get; set;}
}
public class MyEntityMapping : EntityTypeConfiguration<MyEntity>
{
    public MyEntityMapping()
    {
       this.MyBaseEntityMapping();
       Property(x=>x.MyProperty).IsRequired();
    }
}

public class MyContext : DbContext
{
    ....
    public override int SaveChanges()
    {
        this.ChangeTracker.DetectChanges(); //this forces EF to compare changes to originals including references and one to many relationships, I'm in the habit of doing this.

        var context = ((IObjectContextAdapter)this).ObjectContext; //grab the underlying context
        var ostateEntries = context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified | EntityState.Added); // grab the entity entries (add/remove, queried) in the current context

        var stateEntries = ostateEntries.Where(x => x.IsRelationship == false && x.Entity is EntityBase); // don't care about relationships, but has to inherit from EntityBase

        var time = DateTime.Now; //getting a date for our auditing dates

        foreach (var entry in stateEntries)
        {
            var entity = entry.Entity as EntityBase;
            if (entity != null) //redundant, but resharper still yells at you :)
            {
                if (entry.State == EntityState.Added) //could also look at Id field > 0, but this is safe enough
                {
                    entity.CreationDate = time;
                }
                entity.ModifyDate = time;
                entity.VersionHash = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10); //this an example of a simple random configuration of letters/numbers..  since the query on sql server is primarily using the primary key index, you can use whatever you want without worrying about query execution.. just don't query on the version itself!
            }
        }
        return base.SaveChanges();
    }
    ....
}


text:
Q: How can I change tab item style as activated by scrolling? Here is a simplified of my code:

#header{
  background-color: #f1f1f1;
  height: 30px;
  border-bottom: 1px solid #ccc;
  padding: 10px 15px;
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
}
#logo{
  float: left;
  font-weight: bold;
  font-size: 18px;
}
ul{
  display: inline;
}
li{
  display: inline-block;
  padding: 0px 30px;
}
.active{
  color: red !important;
}
a{
  color: gray;
  text-decoration: none;
}
#container{
  margin-top: 70px;
}

LOGO

Item 1

Item 2

Item 3

Item 4

Item 1

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text  here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

Item 2

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

Item 3

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text  here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

Item 4

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text  here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

All I'm trying to do is changing the color of items (in the header) by scrolling. I mean I want to add .active class to a[href="i2"] (making it red) element when user scrolls and div#i2 comes in the top of page. How can I do that?
Can I change class property based on the scrolling?

A: WITHOUT JQUERY:

 // To remember the current active tab
 let currentTab = 1 ;

 // Without jQuery, I get the parent items top
 let topContainer = document.getElementById('container').offsetTop;

 // I get the top of each item, in a table
 let stateItems = {};

 for(let i = 1 ; i < 5 ; ++ i)
 {
   stateItems[i] = {
     top: topContainer + document.getElementById('i'+i).offsetTop,
     actived: i == 1
   };
 }

 // To adjust: I want the active class to be applied just
 // when the title reachs the top of the window (under the header)
 const DecFromTop = 120 ;

 // I deal with scroll event
 window.onscroll = function(evt){

    // the current scroll, adjusted
    let wY = window.scrollY + DecFromTop;

    // For convenience (see above)
    let topItem = 0 ;

    // A loop on each tab
    for(let i = 1 ; i < 5 ; ++ i){

      // Can't be this one
      if ( i == currentTab ) { continue } ;

      // I take the item top props
      topItem = stateItems[i];

      // I only apply and remove class on ± 10 px, once

      if ( wY > topItem.top - 10 && wY < topItem.top + 10)
      {
        // <= Scrolling ± 10 px the current checked item
        // => I have to change the current tab

        // Once

        if ( false == topItem.actived )
        {
          // <= Not actived yet
          // => I have to activate it and desactivate the current

          // Remove prev tab class
          document.getElementById('tab'+currentTab).className = '';
          stateItems[currentTab].actived = false ;

          // Add new tab class
          document.getElementById('tab'+i).className = 'active';
          topItem.actived = true ;

          // Remember current tab
          currentTab = i;
        }
      }
    }
  }

   #header{
      background-color: #f1f1f1;
      height: 30px;
      border-bottom: 1px solid #ccc;
      padding: 10px 15px;
      position: fixed;
      width: 100%;
      top: 0;
      left: 0;
    }
    #logo{
      float: left;
      font-weight: bold;
      font-size: 18px;
    }
    ul{
      display: inline;
    }
    li{
      display: inline-block;
      padding: 0px 30px;
    }
    .active{
      color: red !important;
    }
    a{
      color: gray;
      text-decoration: none;
    }
    #container{
      margin-top: 70px;
    }

LOGO

Item 1

Item 2

Item 3

Item 4

Item 1

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text  here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

Item 2

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

Item 3

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text  here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

Item 4

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text  here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

A: You can use scrollTop() to find the current scroll, and offset().top for each block, here is the code.

$(window).scroll(function(){
  var x = $(window).scrollTop();
  var i1 = $('#i1').offset().top;
  var i2 = $('#i2').offset().top;
  var i3 = $('#i3').offset().top;
  var i4 = $('#i4').offset().top;
  var offset = 110; //px
  //console.log(i1,i2,i3,i4,x);
  if(x>i1 - offset && x < i2){
    $('.links').removeClass('active');
    $("a[href='#i1']").addClass('active');
  }
  if(x>i2 - offset && x < i3){
    $('.links').removeClass('active');
    $("a[href='#i2']").addClass('active');
  }
  if(x>i3 - offset && x < i4 ){
    $('.links').removeClass('active');
    $("a[href='#i3']").addClass('active');
  }
  if(x>i4 || ($(window).scrollTop() + $(window).height() == $(document).height())
  ){
    $('.links').removeClass('active');
    $("a[href='#i4']").addClass('active');
  }

});
#header{
  background-color: #f1f1f1;
  height: 30px;
  border-bottom: 1px solid #ccc;
  padding: 10px 15px;
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
}
#logo{
  float: left;
  font-weight: bold;
  font-size: 18px;
}
ul{
  display: inline;
}
li{
  display: inline-block;
  padding: 0px 30px;
}
.active{
  color: red !important;
}
a{
  color: gray;
  text-decoration: none;
}
#container{
  margin-top: 70px;
}

LOGO

Item 1

Item 2

Item 3

Item 4

Item 1

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text  here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

Item 2

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

Item 3

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text  here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

Item 4

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text  here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text

 here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text here is some text


text:
Q: How do I ignore lines to points with y=0 using pst-plot and a logarithmic y-scale? I am using pst-plot to visualize data sets in linear x and logarithmic y scale. The data set should be plotted by connecting all points with a solid line style. This all works fine by using \pstScalePoints(1,1){}{log} as long as there is no point in the data set with (x_i, y_i=0). The behavior I want to achieve is that such points should not be plotted at all and the line connecting all points is then disconnected at that point (that is, there are lines connecting points at x_1 up to x_(i-1), no line from x_(i-1) to x_(i+1), and again lines from x_(i+1) to x_n). This is for example the default behavior in MATLAB. By googling I found the following way to put points with y=0 outside the figure but the connecting lines are still shown: \pstScalePoints(1,1){}{dup 0 eq { pop -1.e30 }{ log } ifelse}. Thanks for you help!
Requested minimal example:
\documentclass{article}
\pagestyle{empty}

\usepackage{pstricks}
\usepackage{pst-plot}
\usepackage{pstricks-add}

\begin{document}

\begin{pspicture}[showgrid=false](0,0)(10,10)
    \savedata{\mydata}[{{0,0.01},{1, 0.02},{2, 0.00},{3, 0.02},{4, 0.02}}]
    \pstScalePoints(1,1){}{dup 0 eq { pop -1.e30 }{ log } ifelse}
    %\pstScalePoints(1,1){}{ dup 0 eq { pop pop }{ log } ifelse}
    \begin{psgraph}(0,-3)(4,0){4.0cm}{4.0cm}%
        \listplot[linestyle=solid, showpoints=false]{\mydata}
    \end{psgraph}%
\end{pspicture}

\end{document}

A: try
\pstScalePoints(1,1){}{ dup 0 eq { pop pop }{ log } ifelse}


text:
Q: Converting json object to json array using org.json.simple I have one org.json.simple.JSONObject i.e {"2016":
obj =  {"12":{"19":{"12":"{\"DonationTime\":11111111111,\"Donation\":10}"}}}}

I want to convert to json array like
org.json.simple.JSONArray arr = obj.toJsonArray(obj); //no such method exists

Is there any method available to convert above object to array.
or do i need to iterate to make it JSONArray.
I am using org.json.simple not org.json.

A: The String is a JSONObject not JSONArray.
String s = {"12":{"19":{"12":"{\"DonationTime\":11111111111,\"Donation\":10}"}}}}

You can use the following code:
Object obj = parser.parse(s);

JSONObject object = (JSONObject)obj;

Creating JSONArray:
JSONArray list = new JSONArray();
list.add(object);


text:
Q: How to array pass to the http post in angular 8? basket=[];
I wan to this  basket array pass the post method
this.data.SaveShipment(this.basket).then(data=>{ });

I pass that array but network showed 400 bad requests How can I pass that
How can I convert that array to Object


text:
Q: Possibly unstable output of linear power supply due to very large current amplfication I'm designing a linear power supply with an op-amp as error amp and a Sziklai pair as output stage as a hobby project (see schematic below).
I'm worried, that the output Vo will be unstable/unpredictable due to the very large current amplification from the output of U1 to the output of the power supply Vo. Maybe leakage and/or noise currents will be enough the turn the output on.
I have simulated the circuit in Orcad Pspice, and there it works fine, but I fear that it will not in practice.
Has anyone an idea how to remedy the potential problem?

A: So as you said, the gain of the 4 BJTs combined is huge and results in a severely unstable circuit, irrespective of the local compensation. Trust me, I have tried. When you simulated the circuit, you must have connected the input of the voltage regulator to a pure DC source, which has absolutely no ripple. Due to this, your op amp just has to maintain a steady output voltage to drive the BJTs to get the desired output voltage. The problem arises in the real world where PSU noise is unavoidable and the op amps have a finite value of PSRR (power supply rejection ratio). Due to this, the op amp must vary its output to compensate for the PSU ripple. But in doing so, even the smallest variations in the op amp's output is amplified greatly by the BJTs and results in severe instability. The following LTspice simulations demonstrate that.
This is a simulation with a pure DC input

As you can see, the output is a clean 5V DC, as you would expect.
Now, I have added 200mVpp 100kHz of input ripple:

As you can see, the output has gone nuts. The output has over 350mVpp of ripple!!
Now you might say, "Let's add some output capacitance to bring down the ripple!"
So here's the result of that:

The o/p ripple has indeed decreased, but look at the collector current of the series pass transistor:

The collector current has a 0.6A swing, which the capacitor absorbs!
Now here's a better voltage regulator scheme:

In this scheme, a current source (which you can easily make using 2 PNP BJTs) feeds the series pass transistor is shunted to control the amount of current going into the base of the pass transistor. By controlling the base current of the pass tranny, the collector current and hence the output voltage can be controlled. This is much more stable and has a good ripple rejection.
And here is the collector current of the pass tranny:

There is only 10mA of swing, compared to last time's 0.6A!

A: There's way too much gain, this will never work.
First rule of designing a regulator is know your load impedance. There will usually be at least one capacitor on the output, most likely several. Some loads are tricky, like DC-DC converters which can have negative input impedance (VCC goes down, current goes up). If there are wires between regulator and load, add some inductance.
If the regulator, the load and the capacitors are part of the same design, then the regulator can be optimized for these parameters. Otherwise, it has to be designed to work with a range of loads and capacitors.
So get an idea of the range of impedance curve vs frequency you want it to work with. If you design a bench power supply, that's quite a wide range.
If the load is connected via something that has low inductance, like power/ground planes, then it's on the same board, so you design it together, that's easier.
If the load is connected via wires (inductance) then the HF output impedance of the power supply is irrelevant for load regulation, it will be dominated by wire inductance anyway. And if you expect ceramic capacitors on the load side, then your power supply can't have low impedance at high frequency (ie, ceramic caps on the output) otherwise you're building a series LC resonator with the wires. So it's safer to have a flat resistive output impedance at HF, say an electrolytic cap with ESR around 1 ohm or above, or a bunch of MLCCs with resistors in series. This has the advantage that the regulator now faces a known load impedance at HF, if the wires are long enough to have enough inductance to isolate it from low HF load impedance.
So, top right we have a load, a bunch of caps stepped through a list of values with ESR and ESL, and on the left, its impedance is in blue. The 50nH inductor and 10mOhm resistor are the wires.
Bottom right we have a regulator which is (for now) just a 350nH inductor. Combined with the various simulated load impedances, this forms some nicely damped combinations if the load capacitors are large, but if they are small, there is ringing.

This needs damping, so let's add some shunt resistive impedance to our regulator, something like a 0.1 Ohm 220µF capacitor with rather irrelevant inductance. I've also stepped the wire inductance.

This is much better damped. So, let's get rid of the load and display the target regulator output impedance. I've added a 1µF, 1 ohm cap too.

Now you can synthetize that any way you want. There will be a pass transistor and an error amp to provide current to the load and to synthetize the inductive (350nH) part of the impedance. The damping can be provided by an output cap, or it can be done by the control loop too, if you want a very fast overcurrent protection. Because if the power supply is set to 40V, 20mA and you plug in a LED thinking "hey it's on current limit what could go wrong", if the output capacitance is implemented with a capacitor it will discharge into the LED and possibly fry it. Otherwise if the damping part of the impedance curve is not implemented with a big cap, but with a smart control loop instead, then there is no charged capacitor to fry your LED.
Designing a competent bench power supply is rather tricky because there are two control loops (current and voltage) and how fast, and how well it switches between the two without anything going wrong sorts out the winners from the losers.
So, ok, I did not answer the question exactly, but this is where you should start.

A: You don't say what U1 is, but it probably is compensated for unity gain or low-gain applications.  However, Q1, Q2, and Q4 are uncompensated voltage gain stages within the U1 feedback loop.  Local degeneration will help tame things, but even if it runs cleanly you still should do a full stability analysis to see how close to the edge you are skating.

A: U1 has some slew-rate limiting, probably, but with Q1 wired as shown,
that doesn't help.   Reduce the voltage gain at Q1 by putting
an emitter resistor into the circuit, such that U1 doesn't have
enough voltage range on its output to saturate the Q1 transistor... which
would be bad for regulation.
An emitter resistor for Q2 might be useful as well, but that will
dissipate some power if it is needed.   The op amp is likely to
work best if its internal voltage gain dominates (rather than
the gain of the added transistors) so that the internal  amplifier
compensation is effective.
A Bode plot with a few sample load impedances would be a very useful
simulation procedure.


text:
Q: How to log scaling applied by \includegraphics? I'm currently working on a large-ish document that contains a lot of screenshots. These range from relatively small dialog boxes or details of the screen to some very large overview pictures. I currently use the option width=\textwidth for the larger screenshots to scale them down to fit the page (somewhat). I also need to apply some scaling to the other screenshots - some larger images need to be scaled down, some details need to be scaled up.
Now I would like to use a small set of scaling factors throughout the document. The screenshots are all taken from a single application, and I'd rather not have the font size and UI details change size from image to image. To achieve that, my current plan is to use only two or three fixed scaling factors throughout the document. I can apply these manually in the source code, but I need to determine the actual values first. For that, I was thinking about setting every image to width=\textwidth, recording the actual scaling applied and then classifying and adjusting the scaling factors.
As far as I can see, the original size and the requested size of each image file is contained in the log file, but on separate lines and in a syntax that is not very parser-friendly. Is there a better way to log the actual scaling factor that is applied to the image?

A: You could try this:
\documentclass{article}
\usepackage{graphicx}
\usepackage{etoolbox}
\makeatletter
\appto\GPT@setup@scale{\wlog{x-scale: \Gin@scalex, y-scale: \Gin@scaley}}
\begin{document}
\includegraphics[width=\textwidth]{example-image-duck}

\includegraphics[width=\textwidth]{example-image-a}

\end{document}

It will log
File: example-image-duck.pdf Graphic file (type pdf)
x-scale: 1.8696, y-scale: 1.8696

and
File: example-image-a.pdf Graphic file (type pdf)
x-scale: 1.07413, y-scale: 1.07413


text:
Q: Unable to create a Pause,Restart,and Home button dialog for swift Spritekit I made a simple game with swift spritekit and I was planning to implement a button that will display a dialog box and was searching around on tutorials on custom dialog but found none that helped me. I know how to make a simple dialog with with a UIView, but the problem is I have no clue how to make a custom dialog box that gives you options to transition to main menu, restart the game and such. I've found How can I pause a game in SpriteKit and SceneKit - SWIFT but still not enough.
I managed to make a dialog box with a UIView but I cannot transition to other gamescene, and I also cannot customize the looks of it that suits my games atomsphere. If there is some tips or samples that are easyto percieve will be great since I started swift just recently. I would love to hear from you!

A: The solution was quite simple, I was able to implement a custom dialog that would transition to the  main menu after using the SKScene parameter that has been passed into the init() within the class that extends the UIView.


text:
Q: IllegalArgumentException: Unsupported value: null while login with twitter I am trying to login with Twitter when i used dependency firebase_auth:^0.6.6 it was working perfactly and i fetch the user's Profile picture and the Code was
final TwitterLoginResult result = await twitterLogin.authorize();
switch (result.status)
{
case TwitterLoginStatus.loggedIn:
var session = result.session;
FirebaseUser user = await _auth.signInWithTwitter(
authToken: session.token, authTokenSecret: session.secret);
img=user.photoUrl;
}

but i migrated the app to AndroidX and this dependency was not compatible so i used firebase_auth: ^0.14.0+5 and this code was not working so i change the code to
final TwitterLoginResult result = await twitterLogin.authorize();

switch (result.status) {
case TwitterLoginStatus.loggedIn:
var session = result.session;

final AuthCredential credential =
TwitterAuthProvider.getCredential(authToken: session.token,
authTokenSecret: session.secret);

FirebaseUser user = (await _auth.signInWithCredential(credential)).user;

and this code is not working app is Crashing and showing the error
W/BiChannelGoogleApi(18829): [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzak@70a4ccf
W/InputMethodManager(18829): startInputReason = 1
D/FirebaseAuth(18829): Notifying id token listeners about user ( D71yiiEX7ubSon4xxcddKlSydn72 ).
D/FirebaseAuth(18829): Notifying auth state listeners about user ( D71yiiEXccccccccKlSydn72 ).
I/zygote64(18829): Do full code cache collection, code=124KB, data=91KB
I/zygote64(18829): After code cache collection, code=123KB, data=68KB
I/zygote64(18829): Do partial code cache collection, code=123KB, data=68KB
I/zygote64(18829): After code cache collection, code=123KB, data=68KB
I/zygote64(18829): Increasing code cache capacity to 512KB
D/AndroidRuntime(18829): Shutting down VM
E/AndroidRuntime(18829): FATAL EXCEPTION: main
E/AndroidRuntime(18829): Process: com.example.login_app, PID: 18829
E/AndroidRuntime(18829): java.lang.IllegalArgumentException: Unsupported value: null
E/AndroidRuntime(18829):    at io.flutter.plugin.common.StandardMessageCodec.writeValue(StandardMessageCodec.java:294)
E/AndroidRuntime(18829):    at io.flutter.plugin.common.StandardMessageCodec.writeValue(StandardMessageCodec.java:291)
E/AndroidRuntime(18829):    at io.flutter.plugin.common.StandardMessageCodec.writeValue(StandardMessageCodec.java:291)
E/AndroidRuntime(18829):    at io.flutter.plugin.common.StandardMessageCodec.writeValue(StandardMessageCodec.java:291)
E/AndroidRuntime(18829):    at io.flutter.plugin.common.StandardMethodCodec.encodeSuccessEnvelope(StandardMethodCodec.java:57)
E/AndroidRuntime(18829):    at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler$1.success(MethodChannel.java:225)
E/AndroidRuntime(18829):    at io.flutter.plugins.firebaseauth.FirebaseAuthPlugin$SignInCompleteListener.onComplete(FirebaseAuthPlugin.java:691)
E/AndroidRuntime(18829):    at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
E/AndroidRuntime(18829):    at android.os.Handler.handleCallback(Handler.java:808)
E/AndroidRuntime(18829):    at android.os.Handler.dispatchMessage(Handler.java:101)
E/AndroidRuntime(18829):    at android.os.Looper.loop(Looper.java:166)
E/AndroidRuntime(18829):    at android.app.ActivityThread.main(ActivityThread.java:7529)
E/AndroidRuntime(18829):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(18829):    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
E/AndroidRuntime(18829):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
I/Process (18829): Sending signal. PID: 18829 SIG: 9
Lost connection to device.

Please can someone explain to me how to resolve this problem?

A: Problem is with login task AND Androidx  twitter_login_issue
Add this dependency in your pubspec.yaml file and let me know this working or not?
flutter_twitter_login:
  git: git://github.com/eudangeld/flutter_twitter_login.git

Same issue (question) login_issue


text:
Q: Insert blob on WebSQL I'm trying to save a blob image into sqlite (Web SQL) on an Apache Cordova App which is run on Android.
I've figured out how to create the blob and obtain it from a local file. The problem is that on the database, instead of being saved the blob, saves an String which states [Object Blob]
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost/image.jpg",true);
xmlhttp.responseType = 'blob';
xmlhttp.onreadystatechange = function(){
  if(xmlhttp.readyState==4){
    var product_image = xmlhttp.response;
    db.transaction(tx.executeSql("INSERT INTO scans(product_image) VALUES (?)",[product_image]), errorCB);
  }
}
xmlhttp.send();

In fact, product_image returns a jpeg blob object. But as stated before, when I do SELECT the result returns [Object Blob]
This is how I create the database:
CREATE TABLE IF NOT EXISTS scans(id INTEGER PRIMARY KEY, product_image BLOB)

A: WebSQL does not support binary data directly.
Typically, binary data is converted into some text format like Base64, and stored as text in the database.
Alternatively, use blob literals and the hex() function to treat blob values as hex strings at the interface between SQL and JavaScript.


text:
Q: Docker plugins for eclipse I have a problem with Dockerfiles on eclipse. I am using eclipse neon and I would like to get rid of error: Unknown instruction: ARG.
It seems to be described in this issue:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=496782
I tried to upgrade eclipse to newest version (Version: Neon.3 Release (4.6.3))
I tried to upgrade all plugins that have something to do with docker; especially the one mentioned in link above.
I tried remove all those plugins.
I started eclipse with clean option.
Now I do not have any editor related to Dockerfiles, but error still exists!
It is little bit frustrating. Can someone suggest what else should be upgraded/removed?

A: Install Docker Tooling in eclipse.In  Help > Install New Softwar , then give below repo url.
http://download.eclipse.org/release/neon

And then select Docker Tooling under Genral Purpose Tools


text:
Q: pytest: how to make dedicated test directory I want the following project structure:
|--folder/
|  |--tests/
|  |--project/

Let's write a simple example:
|--test_pytest/
|  |--tests/
|  |  |--test_sum.py
|  |--t_pytest/
|  |  |--sum.py
|  |  |--__init__.py

sum.py:
def my_sum(a, b):
    return a + b

test_sum.py:
from t_pytest.sum import my_sum
def test_my_sum():
    assert my_sum(2, 2) == 5, "math still works"

Let's run it:
test_pytest$ py.test ./
========== test session starts ===========
platform linux -- Python 3.4.3, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /home/step/test_pytest, inifile:
collected 0 items / 1 errors

================= ERRORS =================
___ ERROR collecting tests/test_sum.py ___
tests/test_sum.py:1: in <module>
    from t_pytest import my_sum
E   ImportError: No module named 't_pytest'
======== 1 error in 0.01 seconds =========

It can't see t_pytest module. It was made like httpie:
https://github.com/jkbrzt/httpie/
https://github.com/jkbrzt/httpie/blob/master/tests/test_errors.py
Why? How can I correct it?

A: An alternative way is making tests a module as well, by adding __init__.py file in folder tests. One of the most popular python lib requests https://github.com/kennethreitz/requests is doing in this way in their unit tests folder tests. You don't have to export PYTHONPATH to your project to execute tests.
The limitation is you have to run py.test command in directory 'test_pytest' in your example project.
One more thing, the import line in your example code is wrong. It should be
from t_pytest.sum import my_sum

A: Thank you, jonrsharpe. Py.test does no magic, I need to make my packages importable myself. There is one of possible solutions:
   $ export PYTHONPATH="${PYTHONPATH}: [Path to folder with my module]"

( PYTHONPATH is one of path sources for sys.path )
If I need to make this change permanently, I need to add this string to ~/.bashrc

A: With pytest:
if __name__ == '__main__':
     import pytest
     pytest.main(['-x', 'tests', '--capture', 'sys'])

# Note: tests is the directory name

This might be helpful for solving your problem with unittest:
Assume we have starter script called run_tests.py
the code in run_tests.py:
import unittest

if __name__ == '__main__':
    # use the default shared TestLoader instance
    test_loader = unittest.defaultTestLoader

    # use the basic test runner that outputs to sys.stderr
    test_runner = unittest.TextTestRunner()

    # automatically discover all tests in the current dir of the form test*.py
    # NOTE: only works for python 2.7 and later
    test_suite = test_loader.discover('./tests')

    # run the test suite
    test_runner.run(test_suite)

you just replace ./tests into your toplevel target dir(absolute path) contains all test scripts
you just run this file like
python run_tests.py
you will be able to see running all the test scripts.

A: Try this:
# in bash/zsh shell
test_pytest$ PYTHONPATH=. pytest

# in fish shell
test_pytest$ env PYTHONPATH=. pytest

It is the same as what @stepuncius points at, and what this answer refers to in a gist. I just wanted to put this in one clean answer. It is a simple solution for small projects, without meddling with the packet-module structure, or setup.py, etc.


text:
Q: Cannot make a static reference to the non-static method int b = new Scanner(System.in).nextInt();

Эклипс мне вот такую штуку выдаёт:

Cannot make a static reference to the non-static method close() from the type Scanner.

A: Статичный метод принадлежит классу, не статичный метод принадлежит инстансу класса.
Когда вы вызываете close(), вы получаете ошибку потому, что этот метод не ассоциирован с инстансом класса.


text:
Q: SVG animation on scroll? I have a small svg:

<svg xmlns="http://www.w3.org/2000/svg" width="164.969" height="195">
        <path d="M164.979 28.97a3.675 3.675 0 0 1-6.19 2.66 90.127 90.127 0 1 0-.99 132.64 3.685 3.685 0 0 1 4.95 5.46 97.5 97.5 0 1 1 1.07-143.48 3.656 3.656 0 0 1 1.16 2.72z" fill="url(#linear-gradient)" fill-rule="evenodd"></path>
        <linearGradient id="linear-gradient">
            <stop offset="0%" stop-color="#e87975"></stop>
            <stop offset="100%" stop-color="#f3c7a1"></stop>
        </linearGradient>
    </svg>

I wonder if it possible to somehow fill the white background with linear gradient on scroll from top start to bottom end? Unfortunately I found only drawing examples on intentet and my small expericence in jQuery doesn't give me a chance to do it by myself. Thank you!

A: For the Background stuff look at this: How to create gradient color in svg background
For scrolling, this could be helpfull: http://cbron.github.io/blog/2013/12/30/draw-svg-path-on-scroll-tutorial/
Anyway: Instead of jQuery you should try Snap.svg for manipulating your SVG.


text:
Q: Четные числа Фибоначчи. Проект Эйлера В чем моя ошибка?
Я пытаюсь создать список из всех четных чисел Фибоначчи, но в моем списке присутствуют и нечетные числа.
Код:
numbers = [1, 2]

# Создаем ряд Фибоначчи
while numbers[-1] < 4000000:
    need = numbers[-2] + numbers[-1]
    numbers.append(need)

def filter():
    '''Эта функция оставляет только четные числа
    в списке numbers
    '''
    for num in numbers:
        if (num % 2) != 0:
            numbers.remove(num)
    print(numbers)
filter()

A: for num in numbers:
    if (num % 2) != 0:
        numbers.remove(num)

Вы удаляете элементы из списка во время итерирования по нему. Весь хвост сдвигается на одну позицию к началу при удалении, и Вы пропускаете элемент, идущий сразу за удаляемым.

A: Все немного проще и менее ресурсоемко.
numbers = [1, 2]
odd_numbers=[]
while numbers[-1] < 4000:
    need = numbers[-2] + numbers[-1]
    numbers[-2],numbers[-1]=numbers[-1],need
    if (need % 2) == 0:
        odd_numbers.append(need)
print (odd_numbers)

Результат:
[8, 34, 144, 610, 2584]

Индексацию numbers оставил исключительно для вашего удобства, что-бы вас не запутать. На самом деле там, конечно, индексы  разумнее использовать 0 и 1.


text:
Q: How can I get an eventListener "keypress" to trigger links of my differents pages (student project)? I"m working on a school project, so I have some limitations (rules).
I can just use basic html css and javascript.
No libraries.
I set up 5 pages (including the index), and i wanted to create some functions on an keyboard event, so the user can navigate between the 5 pages with keyboard 1 to 5 keys.
Here are my html and js code so far, i'm pretty sure the window location href is the problem here. It works, but its failing after 3 or 4 uses.

function touche1(){
    console.log("touche 1 tapée");
    window.location.href = "../index.html";
}

function touche2(){
    console.log("touche 2 tapée");
    window.location.href = "./pages/projets.html";
}

function touche3(){
    console.log("touche 3 tapée");
    window.location.href = "./pages/presentation.html";
}

function touche4(){
    console.log("touche 4 tapée");
    window.location.href = "./pages/medias.html";
}

function touche5(){
    console.log("touche 5 tapée");
    window.location.href = "./pages/contact.html";
}

document.addEventListener("keypress", function(e){
    var touche = String.fromCharCode(e.charCode)
    switch(touche){
        case "1":
            touche1()
            break;
        case "2":
            touche2()
            break;
        case "3":
            touche3()
            break;
        case "4":
            touche4()
            break;
        case "5":
            touche5()
            break;
}})

    Accueil
    Projets
    Présentation
    médias
    Contact

I know it's linked to my pages url / window position href, but cant figure it out.
thanks a lot :)

A: Try (open chrome console, run snippet and push keys 1-5)

document.body.onkeypress = e => {
  let links = [
    'index.html',
    'pages/projets.html',
    'pages/presentation.html',
    'pages/medias.html',
    'pages/contact.html',
    ]
  location = links[e.key-1]||links[0];
}

  Accueil
  Projets
  Présentation
  médias
  Contact

A: Thanks all ! I finally figured it out.
My problem was my index was not in the same folder as my other pages.
I just copied my index to be my home page and put it in the same folder, and kept my index as an enter page. It works fine.
Thanks for all the quick answers :)


text:
Q: Could not unzip uploaded file on creation of Lambda function using python I am trying to create aws lambda function using python.
Error in Lambda Function

Function mentioned below is giving error 'Could not unzip uploaded file'
def upload_lambda_function(zip_file_name):
with open(zip_file_name) as zip_blob:
#"fileb://"+base64.b64encode(zip_blob.read()),
    lambda_execution_role_arn = 'arn:aws:iam::' + \
        aws_account_id + ':role/' + lambda_execution_role
    aws_lambda.upload_function(
        lambda_function_name,
        "file://"+zip_blob.read(),
        "nodejs6.10",
        lambda_execution_role_arn,
        "index.handler",
        "event",
        description=None,
        timeout=60,
        memory_size=128)

aws_lambda.upload_function define inside library boto/awslambda
 def upload_function(self, function_name, function_zip, runtime, role,
                    handler, mode, description=None, timeout=None,
                    memory_size=None):

    uri = '/2014-11-13/functions/{0}'.format(function_name)
    headers = {}
    query_params = {}
    if runtime is not None:
        query_params['Runtime'] = runtime
    if role is not None:
        query_params['Role'] = role
    if handler is not None:
        query_params['Handler'] = handler
    if mode is not None:
        query_params['Mode'] = mode
    if description is not None:
        query_params['Description'] = description
    if timeout is not None:
        query_params['Timeout'] = timeout
    if memory_size is not None:
        query_params['MemorySize'] = memory_size

    try:
        content_length = str(len(function_zip))
    except (TypeError, AttributeError):
        # If a file like object is provided and seekable, try to retrieve
        # the file size via fstat.
        try:
            function_zip.tell()
        except (AttributeError, OSError, IOError):
            raise TypeError(
                "File-like object passed to parameter "
                "``function_zip`` must be seekable."
            )
        content_length = str(os.fstat(function_zip.fileno()).st_size)
    headers['Content-Length'] = content_length
    return self.make_request('PUT', uri, expected_status=201,
                             data=function_zip, headers=headers,
                             params=query_params)

def make_request(self, verb, resource, headers=None, data='',
                 expected_status=None, params=None):
    if headers is None:
        headers = {}
    response = AWSAuthConnection.make_request(
        self, verb, resource, headers=headers, data=data, params=params)
    body = response.read().decode('utf-8')
    if body:
        body = json.loads(body)
    if response.status == expected_status:
        return body
    else:
        error_type = response.getheader('x-amzn-ErrorType').split(':')[0]
        error_class = self._faults.get(error_type, self.ResponseError)
        raise error_class(response.status, response.reason, body)

A: One thing that might be misleading is that boto 2.0 uses an older version of the Lambda API (2014-11-13). The current API (2015-03-31) (which is what you'll see if you consult the docs), uses a JSON dict in the body, which includes the base64 encoded zipfile as one of its values. However, in the API used by boto2, almost everything is passed via query params and the entire body is dedicated to the contents of the zipfile as a binary blob (no encoding).
Your problem appears to be the fact that you are prepending "file://" to the bytes in your zip. In the boto code you posted, the contents of the zip_function argument just get blindly passed through to the eventual HTTP request body. You should open zip_filename with the 'b' flag and just pass zip_blob.read() to upload_lambda_function without modification. (Or, if you notice, the code can handle file-like objects in addition to strings, so you can simply pass zip_blob without reading it).
def upload_lambda_function(zip_file_name):
    with open(zip_file_name, 'rb') as zip_blob:
      aws_lambda.upload_function(
        lambda_function_name,
        zip_blob,
        "nodejs6.10",
        lambda_execution_role_arn,
        "index.handler",
        "event",
        description=None,
        timeout=60,
        memory_size=128)


text:
Q: Show that there do not exist any integer $m,n$ such that $\frac{m}{n}+\frac{n+1}{m}=4$ The question is
Show that there do not exist positive integers $$m,n$$ such that   $\frac{m}{n}+\frac{n+1}{m}=4$ . It is the problem.I tried to make a quadratic equation of m. And I found that we have to show that there do not exist positive integer $n$ such that $\sqrt{3n^2-n}$ .
But how?? Anyone have any idea!

A: Continuing your proof on showing that the discriminant $D$ is not a perfect square:
$D= 3n^2-n = n(3n-1)$
$\gcd(n, 3n-1) =1$ by elementary methods.
So we need both $3n-1$ and $n$ to be perfect squares. But $3n-1$ cannot be a perfect square taking mod 3.


text:
Q: Codesplitting and server-side rendering with redux I'm codesplitting my React+Redux application as described by Dan Abramov here, and everything appears to work fine. However, I'm also rendering the application on the server. This results in console error documented by this answer. However, I'm not attempting to clean up old state—I'm loading the state as the server computed it. The problem is the state from the server gets loaded into the global state before the codesplitted modules are loaded.
If I understand Dan properly, the error is just a warning, and everything appears to function correctly, but it's really not a pleasant development workflow to see errors on nearly every page load.
Is there anything I can/should be doing differently with my codesplitting code to alleviate this? It's nearly verbatim to Dan's example.

A: The answer was kind of obvious when it hit me. Just like you send the redux state to the client, you need to tell the client which optional reducers need to be included into the combined reducer on creation.
Based on Dan Abramov's work in the linked answer in my question, I changed store.asyncReducers into an array of paths instead of a map of objects. Then I was able to serialize this array and send it to the front-end where it was able to require the async reducers that the server-side render used.


text:
Q: How to DISable display sleep on Dell PowerEdge R310 The display on these PowerEdge systems goes to sleep after some period of time. Normally, when you plug in a KVM, you have to press a key to "wake up" the display. I'm connecting these servers to a KVM switch, and I'd like the display to NOT go to sleep -- so when you select a system via the KVM switch you immediately see the console display. OS on these boxes is Linux, Ubuntu Lucid (10.04).

A: With X11 you want to disable DPMS in /etc/X11/xorg.conf.
#In the "Monitor" section, you need a line like:
        Option          "DPMS"
#Then, in the "ServerLayout" section (for Xorg 7.2 and later, make a
#separate ServerFlags section instead), include lines like this:
        Option          "BlankTime"     "0"
        Option          "StandbyTime"   "0"
        Option          "SuspendTime"   "0"
        Option          "OffTime"       "0"

#Alternatively try this in the Monitor section:
        Option          "DPMS"          "False"

Mostly from: http://www.shallowsky.com/linux/x-screen-blanking.html
From outside of X11 with a login sessions you could do the following:
setterm -blank 0
setterm -powersave off

From outside of X11 without a login session you can use the following kernel parameters in your boot loader:
consoleblank=   [KNL] The console blank (screen saver) timeout in
                seconds. Defaults to 10*60 = 10mins. A value of 0
                disables the blank timer.


text:
Q: Using foreach loop to echo array values in PHP I have a html form with the following input tags
<input type="text" name="parcelnumber[]" id="parcelnumber" class="gui-input" placeholder="Parcel Number">
<input type="text" name="section[]" id="section" class="gui-input" placeholder="Section">

The html form looks like so;

The user is given the ability to dynamically add extra parcel numbers.
How can I use a foreach loop to echo each Section for each Parcel numbers?
The below foreach loop is not giving me the results I want. The last section is repeated again for the first parcel loop. That is why it is not giving me the echo result I am after.
$parcels = $_POST['parcelnumber'];
$sections = $_POST['section'];

foreach($parcels as $parcel) {
    foreach ($sections as $section) { }
    echo $parcel . $section . "
";
}

A: If I understand correctly, does this help?
$parcels = $_POST['parcelnumber'];
$sections = $_POST['section'];

foreach($parcels as $key => $parcel) {
    echo $parcel . " - " . $sections[$key] . "
";
}

A: Currently the code will just iterate over all parcels and all sections. You need to define the sections for each parcel,
it should be like this
<input type="text" name="parcelnumber[]" id="parcelnumber" class="gui-input" placeholder="Parcel Number">
<input type="text" name="section[parcelnumber][]" id="section" class="gui-input" placeholder="Section">

Change the name attribute of the section input with js, so that you can map which section belongs to which parcel
and then use,
$parcels = $_POST['parcelnumber'];
$sections = $_POST['section'];

foreach($parcels as $parcel) {
    foreach ($sections[$parcel] as $section) { }
    echo $parcel . $section . "
";
}


text:
Q: how to create object using user input using array and not array list When i compile and execute, I get java.lang.ArrayOutOfBoundsException. How do i fix it? Must use array and not arrayList. This is BlueJ. I'm inheriting the methods from desktop and laptop and those 2 classes are getting the values of parent class in computer.

import java.util.Scanner;

public class testComputer {
    public static void main(String args[]) {
        String a;
        Scanner scanner = new Scanner(System.in);
        Desktop[] desk = new Desktop[5];
        Laptop[] lap = new Laptop[5];
        int Desk = 0;
        int Lap = 0;

        do {
            System.out.println("*************** Artificial Intelligence Co.***************");
            System.out.println("Computer Menu");
            System.out.println("1. Add a new Desktop Information");
            System.out.println("2. Add a new Laptop Information");
            System.out.println("3. Display all Computer Information");
            System.out.println("4. Quit");
            System.out.println("***********************************************************");
            System.out.print("Please enter either 1 to 4: ");
            a = scanner.nextLine();

            if (a.equals("1")) {
                desk[Desk] = new Desktop();
                desk[Desk].setDisplayDesktopInfo();
            } else if (a.equals("2")) {
                lap[Lap] = new Laptop();
                lap[Lap].setDisplayLaptopInfo();
            } else if (a.equals("3")) {
                int i = 0;
                for (i = 0; i <= desk.length; i++) {
                    if (desk.length == i) {
                        System.out.println("================Desktop================");
                        desk[i] = new Desktop();
                        desk[i].getDisplayDeskInfo();
                        System.out.println("");
                    } else {
                        System.out.println("Error!");
                    }
                }

                int j = 0;
                for (j = 0; j <= lap.length; j++) {
                    if (lap.length == j) {
                        System.out.println("================Laptop================");
                        lap[j] = new Laptop();
                        lap[j].getDisplayLapInfo();
                        System.out.println("");
                    } else {
                        System.out.println("Error");
                    }
                }
            } else if (a.equals("4")) {
                System.out.println("Good Bye!");
            }
        } while (!a.equals("4"));

    }
}

import java.util.Scanner;
public class Desktop extends Computer
{
private static final String alphanumeric_regex_pattern = "^[a-zA-Z0-9]*$";
private String Monitor;

public Desktop()
{

}
void setMonitor(String monitor)
{
    Monitor = monitor;
}
String getMonitor()
{
    return Monitor;
}

void setDisplayDesktopInfo()
{
    Scanner scanner = new Scanner(System.in);
    System.out.println("========================================");
    System.out.println("Information for new Desktop");
    System.out.println("========================================");
    System.out.print("What is the Computer ID: " + "");
    setComputerID(scanner.nextLine());
    System.out.print("What is the Processor Speed: " + "");
    setprocessorSpeed(scanner.nextLine());
    System.out.print("What is the RAM: " + "");
    setRAM(scanner.nextLine());
    System.out.print("What is the Harddisk size: " + "");
    setHarddisk(scanner.nextLine());
    System.out.print("What is the Monitor Type: " + "");
    setMonitor(scanner.nextLine());
    System.out.println("");
    System.out.println("Your information has been added successfully.");
    System.out.print("");
}
void getDisplayDeskInfo()
{
    System.out.println("Computer ID: " + getComputerID());
    System.out.println("Processor Speed: " + getprocessorSpeed());
    System.out.println("RAM: " + getRAM());
    System.out.println("Harddisk: " + getHarddisk());
    System.out.println("Monitor: " + getMonitor());
    System.out.print("");
}

}
import java.util.Scanner;
public class Laptop extends Computer
{
private String Weight;

void setWeight(String weight)
{
    Weight = weight;
}
String getWeight()
{
    return Weight;
}

void setDisplayLaptopInfo()
{
    Scanner scanner = new Scanner(System.in);
    System.out.println("========================================");
    System.out.println("Information for new Laptop");
    System.out.println("========================================");
    System.out.print("What is the Computer ID: " + "");
    setComputerID(scanner.nextLine());
    System.out.print("What is the Processor Speed: " + "");
    setprocessorSpeed(scanner.nextLine());
    System.out.print("What is the RAM: " + "");
    setRAM(scanner.nextLine());
    System.out.print("What is the Harddisk size: " + "");
    setHarddisk(scanner.nextLine());
    System.out.print("What is the Weight: " + "");
    setWeight(scanner.nextLine());
    System.out.println("");
    System.out.println("Your information has been added successfully.");
    System.out.print("");
}
void getDisplayLapInfo()
{
    System.out.println("Computer ID: " + getComputerID());
    System.out.println("Processor Speed: " + getprocessorSpeed());
    System.out.println("RAM: " + getRAM());
    System.out.println("Harddisk: " + getHarddisk());
    System.out.println("Weight: " + getWeight());
    System.out.print("");
}

}
*************** Artificial Intelligence Co.***************
Computer Menu
1. Add a new Desktop Information
2. Add a new Laptop Information
3. Display all Computer Information
4. Quit
***********************************************************
Please enter either 1 to 4: 1
========================================
Information for new Desktop
========================================
What is the Computer ID: D001
What is the Processor Speed: 3.3GHZ
What is the RAM: 4GB
What is the Harddisk size: 80GB
What is the Monitor Type: CRT

Your information has been added successfully.
*************** Artificial Intelligence Co.***************
Computer Menu
1. Add a new Desktop Information
2. Add a new Laptop Information
3. Display all Computer Information
4. Quit
***********************************************************
Please enter either 1 to 4: 3
If you see this message means you have not done yet!
If you see this message means you have not done yet!
If you see this message means you have not done yet!
If you see this message means you have not done yet!
If you see this message means you have not done yet!
Error
Error
Error
Error
Error
*************** Artificial Intelligence Co.***************
Computer Menu
1. Add a new Desktop Information
2. Add a new Laptop Information
3. Display all Computer Information
4. Quit
***********************************************************
Please enter either 1 to 4: 4
Good Bye!

A: If the user chooses 3 you are creating a new computer, laptop object before displaying the information, I removed those lines, and your code will obiously generate ArrayIndexOutOfBoundsException, now this code is error-free and the rest is up to you, Enjoy.
import java.util.Scanner;

public class testComputer {
    public static void main(String args[]) {
        String a;
        Scanner scanner = new Scanner(System.in);
        Desktop[] desk = new Desktop[5];
        Laptop[] lap = new Laptop[5];
        int Desk = 0;
        int Lap = 0;

        do {
            System.out.println("*************** Artificial Intelligence Co.***************");
        System.out.println("Computer Menu");
        System.out.println("1. Add a new Desktop Information");
        System.out.println("2. Add a new Laptop Information");
        System.out.println("3. Display all Computer Information");
        System.out.println("4. Quit");
        System.out.println("***********************************************************");
        System.out.print("Please enter either 1 to 4: ");
        a = scanner.nextLine();

        if (a.equals("1")) {
            desk[Desk] = new Desktop();
            desk[Desk].setDisplayDesktopInfo();
            ++Desk;
        } else if (a.equals("2")) {
            lap[Lap] = new Laptop();
            lap[Lap].setDisplayLaptopInfo();
            ++Lap;
        } else if (a.equals("3")) {
            int i = 0;
            for (i = 0; i < desk.length; i++) {

                    System.out.println("================Desktop================");

                    desk[i].getDisplayDeskInfo();
                    System.out.println("");

            }

            int j = 0;
            for (j = 0; j < lap.length; j++) {

                    System.out.println("================Laptop================");

                    lap[j].getDisplayLapInfo();
                    System.out.println("");

            }
        } else if (a.equals("4")) {
            System.out.println("Good Bye!");
        }
    } while (!a.equals("4"));

}

}


text:
Q: Require Logic to avoid "StaleElementReferenceException" after page refresh I am having multiple links on a Webpage. After clicking the link, a popup opens, I Set some values on fields in the popup and click on 'Save'.

On clicking on 'Save', the main web page refreshes to show the updated status of the link. I use a "for" loop to iterate through all the Links one-by-one and update the status. To avoid stale element reference, I have written a utility to check if element is stale still but I am unable to get rid of this exception.
Below is my Utility code:
public static boolean isStale(WebElement e){
    try{
        e.isDisplayed();
        return false;
    }catch(StaleElementReferenceException ex){
        return true;
    }
}

Below is my page Objects code:
public class DocCheckPageObjects {

WebDriver driver = null;

public DocCheckPageObjects(WebDriver driver) {
    this.driver = driver;
    PageFactory.initElements(driver, this);
}

@FindBy(tagName="a")
WebElement tagName_a;
public WebElement tagName_a() { return tagName_a; }

@FindBy(xpath="//input[@name='progress']")
WebElement listBoxDocStatus;
public WebElement listBoxDocStatus() { return listBoxDocStatus; }

@FindBy(xpath="//span[@title='Received Hard Copy']")
WebElement listBoxDocStatusOptionReceivedHardCopy;
public WebElement listBoxDocStatusOptionReceivedHardCopy() { return listBoxDocStatusOptionReceivedHardCopy; }

@FindBy(xpath="//button[@name='update']")
WebElement btnSave;
public WebElement btnSave() { return btnSave; }

@FindBy(xpath="//*[contains(text(),'Saved Successfully')]")
WebElement toastMsg;
public WebElement toastMsg() { return toastMsg; }}

Below is my Class code:
DocCheckPageObjects docCheckObj = new DocCheckPageObjects(driver);
    WebElement docCheckTable = driver.findElement(By.xpath("//div[@class='slds-gutters slds-wrap slds-m-horizontal_xx-small']/table"));

    System.out.println("No of Links: " + docCheckTable.findElements(By.tagName("a")).size());

    int linkCount =  docCheckTable.findElements(By.tagName("a")).size();

    for(int i=0; i<linkCount;i++) {
        wait.until(ExpectedConditions.elementToBeClickable(docCheckTable.findElements(By.tagName("a")).get(i)));
        docCheckTable.findElements(By.tagName("a")).get(i).click();
        docCheckObj.listBoxDocStatus().click();
        docCheckObj.listBoxDocStatusOptionReceivedHardCopy().click();
        docCheckObj.btnSave().click();
        while(util.isStale(docCheckTable.findElements(By.tagName("a")).get(i))) {
            docCheckTable = driver.findElement(By.xpath("//div[@class='slds-gutters slds-wrap slds-m-horizontal_xx-small']/table"));
        }
    }

I think the code inside while loop is executing before the page is refreshed hence I am still getting Stale element exception.
Below is the code which works using thread.sleep:
for(int i=0; i<linkCount;i++) {
        Thread.sleep(1000);
        docCheckTable = driver.findElement(By.xpath("//div[@class='slds-gutters slds-wrap slds-m-horizontal_xx-small']/table"));
        wait.until(ExpectedConditions.elementToBeClickable(docCheckTable.findElements(By.tagName("a")).get(i)));
        docCheckTable.findElements(By.tagName("a")).get(i).click();
        docCheckObj.listBoxDocStatus().click();
        docCheckObj.listBoxDocStatusOptionReceivedHardCopy().click();
        docCheckObj.btnSave().click();
    }

Q1) Above code resolves the state element reference, but i want to avoid using thread.sleep.
Q2) I had to put my locator like "docCheckTable" in my executable class instead of in Page Object factory class.  How do I put all my Locators in Page Object class which returns a list of Webelements and also avoids Stale Element exception.


text:
Q: Fail a grunt build when debug prints exist in source I am working on a PHP/Javascript project where I've nicely set up a build workflow. It involves testing, minifying, compressing into the final zip deliverable, and a whole lot of other nice stuff.
I want to build a task that fails when there are certain patterns in the source code. I would like to look for any print_r(), error_log(), var_dump(), etc functions, and halt the build process if there are any. Perhaps later I would like to check for things in Javascript or CSS so this is not only a PHP question.
I know it can be done with grunt-shell and grep but I'd like to know the following:

*

*Are there any grunt plugins specific to this task? Ideally I would like to be able to specify a list of regexes per file type, and to set whether to continue or fail the build on pattern match.

*How do others tackle the problem of double-checking the packaged source for the most common debug statements or other patterns?

A: Not a complete answer to my question, but I've recently come across this grunt plugin which is somewhat related. It removes console.log statements from JavaScript. Haven't tried it yet. Looks good. I still would like to know if there's something similar for PHP though.
http://grunt-tasks.com/grunt-remove-logging-calls/
Edit: Seeing as there's only tumbleweeds rolling in the wind here, I'm posting my workaround that's based on grunt-shell. However this is not what I was looking for. It's not perfect because it doesn't do proper syntax parsing:
    shell: {
        check_debug_prints: {
            command: '(! (egrep -r "var_dump|print_r|error_log" --include=*.php src || egrep -r "console\.\w+|debugger;" --include=*.js src) ) || (echo "Debug prints in source - build aborted" && false )'
        }
    },

and
grunt.loadNpmTasks( 'grunt-shell' );

Edit 2: I finally found the exact grunt plugin I was looking for. It is grunt-search. There is a failOnMatch boolean option that lets you indicate if a particular regex pattern should cause the build to fail when found.


text:
Q: What compile/linking mechanism is glm using? I'm currently working with OpenGL use glm library, I see each header file (*.hpp) had it own implementation file (*.inl) but how can it auto-compile (or linking) glm each time we compile project? For example:
#include <glm/glm.hpp>
// We actualy dont included any *.inl files
// And in glm.hpp (or any *.hpp files) are not included too!

but when compile, it had no error!

A: From the glm/glm/core/dummy.cpp:
/// GLM is a header only library. There is nothing to compile.
/// dummy.cpp exist only a wordaround for CMake file.

So you have to include the headers in your project and that's it (similar to boost) . You are correct about the .inl files, they are included by headers. Headers have guards, so there will be no duplication.


text:
Q: Can prometheus scrape targets together? I need Prometheus to scrape several mongodb exporters one after another in order to compute a valid replication lag. However, the targets are scraped with a difference of several dozen seconds between them, which makes replication lag impossible to compute.
The job yaml is below:
- job_name: mongo-storage
  honor_timestamps: true
  scrape_interval: 1m
  scrape_timeout: 10s
  metrics_path: /metrics
  scheme: http
  static_configs:
  - targets:
    - mongo-1a-exporter.monitor:9216
    - mongo-2a-exporter.monitor:9216
    - mongo-3a-exporter.monitor:9216
    - mongos-exporter.monitor:9216
    - mongo-1b-exporter.monitor:9216
    - mongo-2b-exporter.monitor:9216
    - mongo-3b-exporter.monitor:9216
    labels:
      cluster: mongo-storage

A: This isn't possible, Prometheus makes no guarantees about the phase of scrapes or rule evaluations. Nor is this something you should depend upon, as it'd be very fragile.
I'd aim for knowing the lag within a scrape interval, rather than trying to get it perfect. You generally care if replication is completely broken, rather than if it's slightly delayed. A heartbeat job could also help.

A: This isn't possible with Prometheus... normally.
However it might be possible to exploit the prometheus/pushgateway to achieve what you want. My thinking is that you write a script/tool to scrape the mongo exporters in a synchronised way, threads/forks/whatever, and then push those metrics into a prometheus/pushgateway instance.
Then configure prometheus to scrape the prometheus/pushgateway instead of the mongo exporters, and since all the metrics are in the one endpoint they will hopefully always be in sync and avoid any lag regarding being up to date.
Hope this helps.


text:
Q: Python rename KML file name wit '(' and ')' I am trying to rename a few KML files with
1) spaces to _
2) - to _
I am running the script in Arcmap. for the first two it works fine.
But for the ( and ) it's going wrong ?
# Rename file
path = "C:\\DATA\\"
files = os.listdir(path)

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace("-", "_")))

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace(" ", "_")))

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace("(", "_")))

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace(")", "_")))

The goals is that I need to import KML files, import them in a Gdb, and then Append them to a excisting layer.
The whole script already works. But I still need to rename the files manually while the gdb will not take in files wit a - minus blancs and ( or ) sign whom are by default in a lot of kml files I have.
Below the whole script that works fine, if i manually rename the - or ( or ) or blanks
# Name: BatchKML_to_GDB.py
# Description: Converts a directory of KMLs and copies the output into a single fGDB.
#              A 2 step process: first convert the KML files, and then copy the featureclases

# Import system models
import arcpy, os

# Rename file
path = "C:\\DATA\\"
files = os.listdir(path)

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace(" ", "_")))

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace("-", "_")))

# Set workspace (where all the KMLs are)
arcpy.env.workspace= (r"C:\DATA")

# Set local variables and location for the consolidated file geodatabase
outLocation = "C:\\WorkingData\\fGDBs"
MasterGDB = 'AllKMLLayers.gdb'
MasterGDBLocation = os.path.join(outLocation, MasterGDB)

# Create the master FileGeodatabase
arcpy.CreateFileGDB_management(outLocation, MasterGDB)

# Convert all KMZ and KML files found in the current workspace
for kml in arcpy.ListFiles('*.kml'):
  print "CONVERTING: " + os.path.join(arcpy.env.workspace,kml)
  arcpy.KMLToLayer_conversion(kml, outLocation)

# Change the workspace to fGDB location
arcpy.env.workspace = outLocation

# Loop through all the FileGeodatabases within the workspace
wks = arcpy.ListWorkspaces('*', 'FileGDB')
# Skip the Master GDB
wks.remove(MasterGDBLocation)

for fgdb in wks:

  # Change the workspace to the current FileGeodatabase
  arcpy.env.workspace = fgdb

  # For every Featureclass inside, copy it to the Master and use the name from the original fGDB
  featureClasses = arcpy.ListFeatureClasses('*', '', 'Placemarks')
  for fc in featureClasses:
    print "COPYING: " + fc + " FROM: " + fgdb
    fcCopy = fgdb + os.sep + 'Placemarks' + os.sep + fc
    arcpy.FeatureClassToFeatureClass_conversion(fcCopy, MasterGDBLocation, fgdb[fgdb.rfind(os.sep)+1:-4])

# Clean up
del kml, wks, fc, featureClasses, fgdb

A: It should be obvious why this doesn't work - once one of your loops has actually renamed a file, the subsequent loops won't be able to find it, because they're still looking for the original name!
You need a SINGLE loop, with all of the .replace() operations chained together so that the file gets renamed directly to its final name.


text:
Q: Wrapfloat and tikzpicture problem I have a problem with tikzpicture inside the environment "wrapfloat". The code works well for the first tikz picture, but for the second and the following figure, the text doesn't wrap the figure. This is my code
\documentclass[10pt,a4paper,openright,oneside]{article}
\usepackage[italian]{babel}
\usepackage[latin1]{inputenc}
\usepackage{graphicx}
\usepackage{newlfont}
\usepackage{amssymb, graphicx, pgfplots, wrapfig}
\pgfplotsset{/pgf/number format/use comma,compat=newest,standard/.style={
    axis x line=middle,
    axis y line=middle,
    enlarge x limits=0.1,
    enlarge y limits=0.15,
    every axis x label/.style={at={(current axis.right of       origin)},anchor=north west},
    every axis y label/.style={at={(current axis.above origin)},anchor=north east}
}}
\usepackage{amsmath}
\usepackage{latexsym, tikz}
\usetikzlibrary{decorations.pathmorphing,patterns, shapes, arrows.meta}
\usepackage{amsthm}

\begin{document}
\section{Risalire all'equazione di una curva partendo dal grafico}
\begin{wrapfloat}{figure}{i}{0.4\textwidth}
\begin{tikzpicture}
\begin{axis}[standard,
ytick={1,2}, yticklabels={$1$,$2$}, xtick={-1}, xticklabels={$-1$},
xlabel=$x$,ylabel=$y$,width=6cm, height=6cm,
xmin=-3,
xmax= 3,
ymin=-1,
ymax=3]
\addplot [domain=-4:4,samples=700,smooth] {(x+1)^2+1};
\draw [dashed] (-1,0)--(-1,1);
\draw [dashed] (0,1)--(-1,1);
\end{axis}
\end{tikzpicture}
\end{wrapfloat}
\textbf{text} text

text text text \\
\begin{wrapfloat}{figure}{i}{0.8\textwidth}
\begin{tikzpicture}
\begin{axis}[standard,
ytick={0,0}, yticklabels={$O$}, xtick={0,0}, xticklabels={$O$},
xlabel=$x$,ylabel=$y$,width=9cm, height=9cm,
xmin=-7,
xmax= 7,
ymin=-3,
ymax=7]
\addplot [domain=-5:5,samples=700,smooth] {0.3*(x)^2};
\addplot [domain=-5:5,samples=700,smooth, green] {0.3*(x)^2+3};
\addplot [domain=-5:5,samples=700,smooth, red] {0.3*(x)^2-3};
\draw [->] (0.5,1)--(0.5,2.5);
\draw [->] (0.5,-0.8)--(0.5,-2.3);
\node [] at (1.2,1.7) {$\tiny{+m}$};
\node [] at (1.2,-1.7) {$\tiny{-m}$};
\end{axis}
\end{tikzpicture}
\end{wrapfloat}
\noindent text text\\
\begin{wrapfloat}{figure}{i}{0.8\textwidth}
\begin{tikzpicture}
\begin{axis}[standard,
ytick={0,0}, yticklabels={$O$}, xtick={0,0}, xticklabels={$O$},
xlabel=$x$,ylabel=$y$,width=9cm, height=9cm,
xmin=-12,
xmax= 12,
ymin=-3,
ymax=7]
\addplot [domain=-12:12,samples=700,smooth] {0.3*(x)^2};
\addplot [domain=-12:12,samples=700,smooth, green] {0.3*(x+6)^2};
\addplot [domain=-12:12,samples=700,smooth, red] {0.3*(x-6)^2};
\draw [->] (0.5,1)--(0.5,2.5);
\draw [->] (0.5,-0.8)--(0.5,-2.3);
\node [] at (1.2,1.7) {$\tiny{+m}$};
\node [] at (1.2,-1.7) {$\tiny{-m}$};
\end{axis}
\end{tikzpicture}
\end{wrapfloat}

\end{document}

Thanks in advance!


text:
Q: Opening a text file to read in Windows from idLE (Python) I want to read a file which is on my drive at location C:\Users\PITA SHIVAYA\Desktop\BIGDATA\test.txt. How can I run so that I can use this .txt file as input for above code.
import sys
for line in sys.stdin:
    line = line.strip()
    items = line.split(' ')
    print((str)(items[2] + "\t" + items[4] + "\t" + items[6] + "\t" + items[9] + "\t1"))

A: Can you change the code ? You can open your file instead of using stdin
file_path = r'C:\Users\PITA SHIVAYA\Desktop\BIGDATA\test.txt'

with open(file_path, 'r') as file:
    for line in file:
        line = line.strip()
        items = line.split(' ')
        print((str)(items[2] + "\t" + items[4] + "\t" + items[6] + "\t" + items[9] + "\t1"))

Not that I use a raw string for file_path (a rbefore the opening quote), to avoid backslashes to be interpreted as special characters
Another solution is to redirect the file to stdin when you execute python:
python my_file.py < C:\Users\PITA SHIVAYA\Desktop\BIGDATA\test.txt


text:
Q: smtplib.SMTPConnectError: (421, b'Service not available') while using my pycharm to send a mail with python i got the above error each time i try sending a mail using python. am somewhat new to this whole smtp thing. below is my code. please help.
import smtplib

my_email ="okoyekennethoptimizer@gmail.com"
password = "nmmrjdphptwfgjgb"

connection = smtplib.SMTP("smtp.gmail.com", 587)
connection.starttls()
connection.login(user=my_email, password=password)
connection.sendmail(from_addr=my_email, to_addrs="okoyek10@yahoomail.com", msg="hello")
connection.close()

please help. its been giving me tough time

A: Try creating an "App password" after enabling 2-step auth in your Gmail. You still need to do some lookup but generally, this should help.

A: The trick is in:

*

*Enabling less secure apps.

*Make sure your account has 2FA.

*Generating an app password under My Google Account>>Security under Signing in to Google.

*Replace the 16-digit password with the password you've placed in the password variable.

*Just before connection.starttls() add connection.ehlo().
A code for  example:
my_email ="okoyekennethoptimizer@gmail.com"
app_password = "16-digit-app-password"

connection = smtplib.SMTP("smtp.gmail.com", 587)
connection.ehlo()
connection.starttls()
connection.login(user=my_email, password=app_password)

*Also you SHOULD create From:, To:, and Subject: message headers, separated from the message body by a blank line.
E.g.
msg = "\r\n".join([
  "From: user_me@gmail.com",
  "To: user_you@gmail.com",
  "Subject: Any subject",
  "",
  "Good Evening, how are you?"
  ])


text:
Q: How can i solve heroku Application error?
*I am having a Heroku Application error. I can not find how can I solve it. or you can say to me how can i remove the whole Heroku application from my project to re-create Heroku app.
thank you.