text:
Q: Collection extends T> means? Why is it throwing compilation error at line 23. 'a' is an object of class Apple and col is a list containing Apple objects, but still, it is throwing a compilation error mentioned below:
The method add(capture#1-of ? extends Fruit) in the type Collection is not applicable for the arguments (Fruit)
public class Basket {
    List<Fruit> list;
    public Basket() {
        list = new ArrayList<>();
    }
    public Basket(List<Fruit> plist) {
        list = plist;
    }

   void addFruit(Collection<? extends Fruit> col) { // this does not work
// void addFruit(Collection<Fruit> col) { // this works
        Fruit a = new Apple();
        Apple a1 = new Apple();
        Fruit f1 = new Fruit();
        col.add(a);// line 23
    }

    int getSize() {
        return list.size();
    }

    public static void main(String[] args) {
        Fruit f1 = new Apple();
        Fruit f2 = new Apple();
        Fruit f3 = new Apple();
        List<Fruit> list = new ArrayList<>();
        list.add(f1);
        list.add(f2);
        list.add(f3);
        Basket b = new Basket(list);
        b.addFruit(list);
        System.out.println(b.getSize());
    }
}

class Fruit {
}

class Apple extends Fruit {
}

A: Collection<? extends Fruit> col means that col is a Collection of Fruit or a Collection of some sub-class of Fruit, such as Collection<Apple> or Collection<Banana>.
You can't add an Apple to a Collection that might be a Collection<Banana>.
If you want to be able to add any Fruit, change the signature to:
void addFruit(Collection<Fruit> col)

A: A collection can only contain entries of some type and its subtypes. For example if you have a Collection<Banana>, it can only contain bananas.
Even though Banana is a sub-class of Fruit, Collection<Banana> is not type-compatible with Collection<Fruit>. It might seem a bit counter-intuitive, but think of it this way: In a Collection<Banana> you only expect a Banana. You don't expect an Apple. But if you have a Collection<Fruit>, you can have all sorts of fruit in it. And you can add any fruit to the collection.
If you cast your Collection<Banana> to Collection<Fruit>, you can add apples in it. Then you try to pull a banana out of your Collection<Banana> and you get an apple. Since you cannot cast Apple to Banana, a ClassCastException is thrown at runtime and your code fails.
So, in your case, you probably want a Collection<Fruit> as suggested by @Eran. However, to answer your question in detail: If you had a Collection<Banana>, you could use the collection as Collection<? extends Fruit>, but you are limited to methods that don't have generic input param.
For example you can mutate the collection using retainAll, remove and a few others, you can as well as use all read-only operations, but you can't add new apples to your collection of bananas.


text:
Q: Asp.Net Core 3.0 Angular SPA template with Identity using Identity server home page User.Identity is null I am using Asp.Net Core 3.0 Angular SPA template using authentication which uses Identity server. However I am using SPA as an external application.
All the identity server page are under Identity Area (Area/Identity). Therefore all the identity server pages follow these routes by convention.
https://localhost:port/Identity/Account/*
Login directly on Identity Server using route Identity/Account/Login works fine. And all the user admin routes detect the user is logged in. The template to display if user is logged in or not is in Pages/Shared/_LoginPartial.cshtml. I have created an Index.cshtml page as shown in following project layout. When navigate to Index page i.e at the root of the website, the User.Identity is not populated and header does not display if user is logged in hence displays Login and Register links. But in same session navigating to user admin pages user is still logged in.
So the issues is why User.Identity isn't populated for root URL?
This is my project structure.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Updating google map markers without reloading map and blinking I am doing a project where I should create a web page that shows Google map with the markers at the specified GPS coordinates.
The project is organized in the following way. At the server side, I have the php script that accepts HTTP request from a GPS device, receives and stores GPS coordinates in the corresponding .txt file. The php file also includes javascript/jquery code that reads the .txt file with the GPS coordinates, create new instance of Google map and put the markers on map for the user that make request in a web browser. As I am electronic hardware engineer, this is pretty new for me. The code I found reloads the map on every 5 second, but that makes the map flashing/blinking for a while on each reload. Also, if I change the zooming manually in the browser, it resets to default on each map reload. Is there any way to avoid map blinking, and update markers smoothly. In the following is the snippet of the javascript/jquery code I have.
function initialize()
    {
        mapProp = {
          center:myCenter,
          zoom:17,
          mapTypeId:google.maps.MapTypeId.ROADMAP
          };
        setInterval('mark()',5000);
    }

    function mark()
    {
            map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
        var file = "gps.txt";
        $.ajaxSetup({cache: false});
                $.get(file, function(txt) {
            var lines = txt.split("\n");

            for (var i=0;i<lines.length;i++){
                console.log(lines[i]);
                var words=lines[i].split(",");
                if ((words[0]!="")&&(words[1]!=""))
                {
                    marker=new google.maps.Marker({
                          position:new google.maps.LatLng(words[0],words[1]),
                          });
                    marker.setMap(map);
                    map.setCenter(new google.maps.LatLng(words[0],words[1]));
                    map.addMarker(new MarkerOptions().position(entry.getValue()).title(entry.getKey()));
                }
            }
            lastLength = lines.length;
            marker.setAnimation(google.maps.Animation.BOUNCE);
        });

    }

    google.maps.event.addDomListener(window, 'load', initialize);

A: What is going on
You keep recreating the map on every update rather than creating it once and add new markers to it.
Fixed code, with comments:
function initialize() {

   // map starting point
   var myCenter = new google.maps.LatLng(0, 0);

   // coordinates file
   var file = "gps.txt";

   // init and keep a reference to last line of coordinates
   var lastLength = 0;

   // init and keep reference to last set marker
   var marker;

   // map options
   var mapProp = {
      center:myCenter,
      zoom:17,
      mapTypeId:google.maps.MapTypeId.ROADMAP
   };

   // create map
   var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);

   // execute once
   mark();

   // set update
   setInterval(mark, 5000);

   // this runs on schedule to add new markers
   function mark() {

      $.ajaxSetup({cache:false});

      $.get(file, function(txt) {

         var lines = txt.split("\n");

         // disable animation on last marker from previous update
         if(marker) {
            marker.setAnimation(null);
         }

         // start from last line + 1 from previous update
         for(var i=lastLength; i<lines.length; ++i) {

            // some debug
            //console.log(lastLength);
            //console.log(lines[i]);

            var words=lines[i].split(",");

            if(words[0] != "" && words[1] != "") {

               // new marker
               marker = new google.maps.Marker({
                  position:new google.maps.LatLng(words[0],words[1]),
               });

               // put marker on map
               marker.setMap(map);

               // center on marker
               map.setCenter(new google.maps.LatLng(words[0],words[1]));

               // I don't know the api enough to fix this part although it seems to work without it
               //map.addMarker(new MarkerOptions().position(entry.getValue()).title(entry.getKey()));
            }
         }

         // update list starting position
         lastLength = lines.length;

         //set animation on current last marker
         marker.setAnimation(google.maps.Animation.BOUNCE);
      }, 'text'); // added datatype:text
   }
}

// init
google.maps.event.addDomListener(window, 'load', initialize);

A: remove this line to get rid of bouncing issue.
marker.setAnimation(google.maps.Animation.BOUNCE);

While you are plotting the markers hold them in an array
marker[j]=new google.maps.Marker({position:new google.maps.LatLng(words[0],words[1])});

and later only add new ones to the map or remove all old one by
marker[j].setMap(null);

and then plot all markers afresh.


text:
Q: StringVar is not working inside the Optionmenu I cannot get the StringVar class to work in my OptionMenu widget, it just appears blank in the OptionMenu. This works on my main window but not this pop-up window here is my code.
def create_new():
    new = tk.Tk()
    new.geometry('300x400')
    new.title('Create New Project')

    l1 = Label(new, text = 'Name of the Project: ', font = ('Arial', 13))
    name = Entry(new)

    menu = StringVar()
    menu.set('Type of Project')
    drop = OptionMenu(new, menu, 'Type of Project', 'Photo Editing', 'lol')

    l1.pack()
    name.pack()
    drop.pack()

Note: I am creating another tkinter window for this.
The optionmenu appears like this
The option menu is just empty


text:
Q: Sort through all attributes in XML tree with PHP XMLReader I have some PHP code to turn an XML file into a CSV file.  During testing, I am not creating a CSV file, just echoing the results in a CSV format.
Whenever XMLReader reaches an empty element, it outputs all the attributes of the element.
1) Is there a way to output the attribute name with it's values i.e. (is there an $xml->AttributeName that goes with the $xml->value)?
2) Is there a way to sort for all attributes in the entire tree and not just those in the empty element?
<?php

ini_set('memory_limit','50M');

$x = file_get_contents('H8_data.xml');

$xml = new XMLReader();
$xml->open('H8_data.xml', null, 1<<19);

$num = 1;
while ($xml->read() && $num <= 2000) {
    if($xml->isEmptyElement) {
        if($xml->hasAttributes)  {
            while($xml->moveToNextAttribute()) {
                echo $xml->value, ', ';
            }
        }
    echo '
';
    $num++;
    }
}

?>

A: $xml->name returns the qualified name of the node. Because attributes are nodes with XMLReader::ATTRIBUTE type, $xml->name will return the name of current attribute in that case.
Below is version of code, which outputs both attribute names and values.

<?php

ini_set('memory_limit','50M');

$x = file_get_contents('H8_data.xml');

$xml = new XMLReader();
$xml->open('H8_data.xml', null, 1<<19);

$num = 1;
while ($xml->read() && $num <= 2000) {
    if($xml->isEmptyElement) {
        if($xml->hasAttributes)  {
            while($xml->moveToNextAttribute()) {
                echo $xml->name, ' = ', $xml->value, ', ';
            }
        }
    echo '
';
    $num++;
    }
}
?>

A: $xml->name ?
http://www.php.net/manual/en/class.xmlreader.php#xmlreader.props.name


text:
Q: Using an MVC model to populate and validate a kendo multiselect? I am trying to bind my kendo multiselect to a property in a model using mvc 5 however all i get is a list of undefined elements. The list is correct at the controller level and looking at the source code the list is correct there but I can not visualize the list.
What is also puzzling is that there are more undefined elements in the list then items the actual list in the model.
Can anyone explain what is going on or show me how to go about debugging and fixing the issues I am having.
Model:
[Required]
public SelectList hierarchy { get; set; }

public virtual IEnumerable<SelectListItem> Hierarchy
{
    get
    {
        var hierarchies = new List<Company>();
        hierarchies = RoleCompanyHelper.GetHierachies();
        var hierarchiesList = new List<SelectListItem>();
        foreach (var hierarchy in hierarchies)
        {
            hierarchiesList.Add(new SelectListItem
            {
                Value = hierarchy.CompanyID.ToString(),
                Text = hierarchy.CompanyName
            });
        }
        return new SelectList(hierarchiesList, "Value", "Text");
    }
}

Controller:
public ActionResult Index()
{
    var vm = new AXCurrentRolesViewModel();
    return View(vm);
}

View:
@model TelerikMvcApp1.Models.AXCurrentRolesViewModel

@(Html.Kendo().MultiSelect()
    .Name("addRoleCompany_hierarchy")
    .BindTo(new SelectList("Value", "Text"))
    .Value(Model.hierarchy)
    .DataTextField("HierarchyName")
    .DataValueField("HierarchyID")
    .Placeholder("Select Hierarchy...")
    .Filter(FilterType.StartsWith)
    .AutoBind(false)
)

On a slightly separate note why does my standard validation using the model always return true??
Thank you for any help and advice on these issues.
EDIT
Source code
<select id="addRoleCompany_hierarchy" multiple="multiple" name="addRoleCompany_hierarchy"></select>
    <script>
        jQuery(function(){jQuery("#addRoleCompany_hierarchy").kendoMultiSelect({"dataSource":[{"Text":"All Companies Inc IFRS \u0026 Consol","Value":"55"},
        {"Text":"All Posting Companies (exc POC \u0026 Investments)","Value":"56"},
        {"Text":"BUUK Group Structure","Value":"57"},
        {"Text":"Cardiff Entities","Value":"58"},
        {"Text":"Department","Value":"59"},
        {"Text":"GTC/GPL/ENC/IPL/QPL/EAM","Value":"60"},
        {"Text":"GTC/GUC/CUL","Value":"61"},
        {"Text":"GTCConsoleAndOperationalCompanies","Value":"62"},
        {"Text":"GTCOperationalCompanies","Value":"63"},
        {"Text":"Inexus Companies","Value":"64"},
        {"Text":"Investment Companies Only","Value":"65"},
        {"Text":"PIL/POL","Value":"66"}],"dataTextField":"HierarchyName","filter":"startswith","autoBind":fal    se,
        "dataValueField":"HierarchyID","placeholder":"Select Hierarchy..."});});
    </script>

A: Change
.DataTextField("HierarchyName")
.DataValueField("HierarchyID")

.DataTextField("Text")
.DataValueField("Value")


text:
Q: Performance about query result of union I have two tables storing user data, one for internal users, another for external users. Both users will buy a book, so I had below sql script
select o.orderid, o.orderdate, u.firstname, u.lastname from OrderTable o inner join
(
  select inneruser_id as uid, firstname, lastname from innerUser where len(firstname) > 0 or len(lastname) > 0
  union
  select external_id as uid, firstname, lastname from externalUser where len(firstname) > 0 or len(lastname) > 0
) u on u.uid = o.userId where o.orderdate > {0}

For table innerUser, innneruser_id is primary key, but external_id is not the primary key of externalUser table,  I want to know, if the result of union still has index on u.uid, because there are over 200,000 internal users and about 100,000 external users.
Do I need to add index to external_id, will this improve the performance of the query.
I appreciate any help.

A: It might, but it looks like adding an index to u.uid, o.userId, and o.orderdate is more likely to improve performance, since those are involved in the join and the filtering.

A: run your query in management studio, with "Include Actual Execution Plan" option turned On.
and do what it suggests to imporove performance.


text:
Q: Python - defining multiple versions of a class I want to define two different versions of a same class:
mail.prod.py
mail.devel.py

only one should be used/imported based on environment type (prod/devel). Can I provide some sort of abstraction that frees the other classes from knowing whether to import prod or devel?

A: You can do this using environment variables. You can do this in Windows via this link and Linux via a command similar to
EXPORT app_env="PROD"

Now, assuming you've set a variable named app_env in your environment, you can do this in your mail module's __init__.py:
import os
if "app_env" in os.environ and os.environ['app_env'] == "PROD":
    import prod as mailcfg
else:
    import devel as mailcfg

At this point, your module should be imported and accessible using mailcfg.variable or mailcfg.DoSomething()
Your mail module needs three files in it:
mail/
    __init__.py
    prod.py
    devel.py


text:
Q: If $f$ is smooth on a ball, does there exist $u$ smooth s.t. $\Delta u =f$? I knew from here that if we have a function $f \in C^{\infty}(\mathbb{R}^{n})$ then we can find a function $u\in C^{\infty}(\mathbb{R}^{n})$ so that $\Delta u = f$.
My question: Assume that I have a function $f\in C^{\infty}(B)$. Here $B$ is the open unit ball in $\mathbb{R}^{n}$. Does there always exist $u\in C^{\infty}(B)$ so that $\Delta u = f$ on $B$?
Note that $f$ may behave badly near $\partial B$, for example $f \equiv d_{B}^{-k}$, where $d_{B}$ is the boundary distance function.


text:
Q: devexpress aspxgridview - setting label with page number I am using devexpress aspxgridview in asp.net 3.5 web application.
on pageload, I have a label control on top of the page whose text for example is "abc".
I am trying to set the value of the label with the page number selected by the user from the grid using onpageindexchanged event.
But the label values is not changing. it is still showing the old value "abc". what may be the problem?

A: To change other controls during the PageIndexChanged event, you might need to disable callbacks (see the ASPxGridView.EnableCallBacks property) and place both the text box and grid control onto the UpdatePanel.
Alternatively, you can do it on the client-side with javascript if you want to keep callbacks enabled. There's a sample project attached here:
http://www.devexpress.com/Support/Center/p/Q201214.aspx


text:
Q: Ошибка в класса после выполнения кода получаю ошибку
batch = [1, 2, 3, 4, 5]
BATCH_FOLDER = 'home/test'

class test:
    def __init__(self, **params):
        if len(batch) > 5:
            BATCH_FOLDER = 'home'
        print(BATCH_FOLDER)

t1 = test()

Без if, это работает подскажите в чем дело? Кажется не логичным влияние условия( которое даже не сработало на выполнение)
По решению это проблемы можно прописать global, но мне интереснее почему это происходит
Кажется, что если есть условие с присвоением, то переменная становится локал, можно ли присваивать так, что бы этого не происходило.

A: Вам надо или так:
batch = [1, 2, 3, 4, 5]
BATCH_FOLDER = 'home/test'

class test:
    def __init__(self, **params):
        global BATCH_FOLDER
        if len(batch) > 5:
            BATCH_FOLDER = 'home'
        print(BATCH_FOLDER)

t1 = test()

или так:
batch = [1, 2, 3, 4, 5]
BATCH_FOLDER = 'home/test'

class test:
    def __init__(self, **params):
        BATCH_FOLDER = ''
        if len(batch) > 5:
            BATCH_FOLDER = 'home'
        print(BATCH_FOLDER)

t1 = test()

вы уж определитесь - в конструкторе BATCH_FOLDER - это глобальная или локальная переменная
в вашем коде как только вы выполняете присваивание в переменную BATCH_FOLDER Питон понимает, что переменная будет локальной, но присваивание у вас происходит не каждый раз, а только в зависимости от выполнения условия, а затем вы выводите значение переменной BATCH_FOLDER (уже каждый раз)
поэтому получается, что переменная то глобальная, то локальная, и Питон от этого офигевает и выдает ошибку
судя по коду вы хотите работать именно с внешней (глобальной) переменной, поэтому в функции __init__ питону надо бы указать, что переменная BATCH_FOLDER - внешняя


text:
Q: Cheapest Way To Export/Import Array Contents To File - AS3/AIR I'm working on a basic editor application. It uses an array of varying size that I want to store to disk. This will eventually be in an AIR application, but for now it's just an AS3 project in Flex.
I want to store the array in a file. The application edits the data, so it doesn't need to be human readable. I want it to be in whatever format will be quickest to store and load back into the array when I need that data again.
Any recommendations?
Edit: It strikes me that importing/exporting in such a way that it can be immediately cast as an Array() would probably be the cheapest thing rather than some sort of iterating - if that's possible. Another obvious option is getting the data as a simple comma delineated string and using the String.split() function to get an array. Though again, the question is what would be cheapest - and I'm not quite convinced that's it.
I'll also add that it needs to be in some sort of permanent file, so a shared object - while possibly the fastest, isn't really a long term solution.

A: I think the fastest and easiest way is to use a shared object. It stores native objects, so there is no serialization / deserialization steps involved. Just assign the value and read it back.
Performance wise, probably the fastest route as well. If you are looking for a large dataset and are sure it's an AIR app, you can use AIR's db, but that will definitely take much more work.

A: First, take a look at this answer.
As for saving the contents of an Array, consider JSON using the export tools provided by Adobe.


text:
Q: Disadvantages of using ternary operator I have the following statments in my source code
int tableField1;
int tableField2;

int propertyField1;
int propertyField2;

if (tableField1 != null)
{
  propertyField1 = tableField1;
}

if (tableField2 != null)
{
  propertyField2 = tableField1;
}

// the above pattern is repeated for 10 tablefields ie tableField3, tableField4... tableField10

I reduced the above statments using the ternary operator as follows
propertyField1 = tableField1 != null ? tableField1 : propertyField1;
propertyField2 = tableField2 != null ? tableField2 : propertyField2;

Following are my questions:
1) Is ternary operator inefficient to use than the if statements.
2) What are the disadvantages (if any) to use ternary operator.

A: 1) No, the compiler will (should) treat the ternary operator in exactly the same manner as an explicit if statement, so there is no difference in efficiency.
2) The only disadvantage is that it can make your code harder to read. On the other hand, it's more concise. Generally avoid ternary statements for readability reasons, except for very simple cases. This probably counts as a very simple case.
I claim this answer is more language-agnostic than Jon Skeet's :)

A: Why not use the null coalescing operator instead?
propertyField1 = tableField1 ?? propertyField1;

Admittedly it looks slightly odd assigning the original value back to the same variable. It's possible that it'll be very slightly less efficient than the if statements, as in theory you're reading the value and assigning it again... but I wouldn't be surprised if the JIT elided that. Anyway, that's definitely at the level of micro-optimization.
Some people consider the conditional operator to be bad for readability - I generally think it's fine for simple statements like this, although it is somewhat obscuring the meaning of "only change the value if we've got a new one".

A: As far as I understand it, the ternary statement is mostly just syntactic sugar, though the compiler can optimize for it.
In this case, I believe it would probably be more efficient, though I'd guess that the compiler would optimize it to be about the same as an if statement.
Disadvantages? Well, it might be harder to read in some cases. It depends on what you're going after.


text:
Q: Почему при другой дате даты дефрагментируются неверно Здравствуйте. Я уже задавал вопрос: Как дефрагментировать даты в базе данных? и там было предложено решение, но, как оказалось, в этом решении есть ошибка.
Вот так выглядит база первоначально. Если применить вот этот код:
    set @today:=date('2016-12-11');
update main M
  join (
   select cid, nomer
     from (
       select A.nomer,
              @cstart:=if(@cnum=A.nomer,@cstart,A.start),
              @cnum:=A.nomer,
              @cid:=(select M.id
                       from main M,allnomer MT
                      where MT.nomer=M.numbernomer and MT.type='lux'
                        and M.datestart>@cstart
                        and find_in_set(M.id,@used)=0
                      order by datestart
                      limit 1
                    ) cid,
              @cstart:=(select dateend from main where id=@cid) dend,
              @used:=coalesce(concat(@used,',',@cid),@used)
         from (
          select A.nomer, A.start
            from (
              select A.nomer,
                     (select coalesce(min(dateend),@today-interval 1 day)
                        from main M
                       where datestart<=@today and M.numbernomer=A.nomer) start
                from allnomer A where type='lux'
            ) A,
            main M, allnomer MT
           where MT.nomer=M.numbernomer and MT.type='lux' and M.datestart>A.start
           order by A.start desc, A.nomer
         ) A,
         (select @cid:=0,@cnum:=0,@cstart:=NULL,@used:='') Y
     ) X where cid is not null
  ) U
  on M.id=U.cid
 set M.numbernomer=U.nomer

То база будет выглядеть так: (так она должна выглядеть после дефрагментации)

Но если изменить set @today:=date('2016-12-11'); на set @today:=date('2016-12-05'); (или любая дата моложе 10), то дефрагментация будет вот такой:

Подскажите, как исправить?


text:
Q: Gmail creating 1pixel line between two images in email I've visited frequently for answers to my HTML problems, but this one has me stumped. I have tested the email backwards and forwards in Litmus, and it looks great in everything, but I had one colleague say that a copy that she received in her personal Gmail (using Chrome) always has a 1 pixel line between slices 2 + 3. I've picked apart the HTML character by character and cannot find a difference that would cause this line to only insert itself between these two slices, and none of the others.
A sample is posted below;

A: please have a look on the snippet i have created , this may help you.
Thanks

 <title></title>


text: Q: Is there a drag and drop function for css, JS and bootstrap in asp.net visual studio 2022? I am trying to drag my css folder and drop into my html code in asp.net visual studio 2022 and it's not working though it works for visual studio 2019. Please I need help


text:
Q: Ternary operator in haskell I often use list comprehension for optional values:
[Parent parent, Destination [DestPage currPage]] ++ [OpenChildren | parent == Bookmark 0]

But i do not know how to do a choice instead of optional value.
A lot of my code looks like this:
let lblTabX         = if isAtBottom then 5 else 3
    lblTabY         = if isAtBottom then 3 else 60
    lblTabPosition  = Position left (if isAtBottom then bottom else top)
    lblTabWidth     = if isAtBottom then lblPageX - 60 else 20
    lblTabHeight    = if isAtBottom then 20 else pageHeight - 80
    lblTabMargin    = if isAtBottom then Margin 0 3 else Margin 3 0

As you see a lot of ifs :)
So i was playing with some operators and came up with this syntax:
iif c l r = if c then l else r

infixl 8 <-/
(<-/) l c = iif c l

infixl 8 /->
(/->) = ($)

And i like how the previous example now looks:
let lblTabX         = 5 <-/ isAtBottom /-> 3
    lblTabY         = 3 <-/ isAtBottom /-> 60
    lblTabPosition  = Position left (bottom <-/ isAtBottom /-> top)
    lblTabWidth     = (lblPageX - 60) <-/ isAtBottom /-> 20
    lblTabHeight    = 20 <-/ isAtBottom /-> (pageHeight - 80)
    lblTabMargin    = Margin 0 3 <-/ isAtBottom /-> Margin 3 0

This is a toy example of course. I have no intention of using it.
But i was just curious, is there a syntax to express the choice besides the if operator? Maybe with list comprehensions?

A: in next(?) GHC at Data.Bool we'll have a bool function:
bool :: a -> a -> Bool -> a
bool f _ False = f
bool _ t True  = t

And your example we could rewrite:
lblTabX = bool 3 5 isAtBottom

A: Whoah, get rid of all those conditionals.  You have a bunch of related settings which in one context will have one set of values, in another context another set.
data TabConfig = TabConfig { tabX, tabY, tabWidth, tabHeight :: Int,
                             tabPosition :: Position,
                             tabMargin :: Margin }

(You don't have to use record syntax; I'm doing it for clarity)
Now you just need to provide your functions with the appropriate TabConfig, from which they can extract the values.  You can provide a defaultConfig function...
defaultConfig :: Context -> TabConfig
defaultConfig c = TabConfig { 5, 3, 20, (pageHeight c) - 80,
                              Position left bottom, Margin 3 0 }

You can also have
bottomConfig :: Context -> TabConfig
bottomConfig c = TabConfig { 3, 60, (pageX c) - 60, 20, Position left top, Margin 0 3 }

Then you just provide the appropriate TabConfig in the appropriate context.  (Hopefull, you worked out that Context is another record-style type and of course you can be playing the same tricks with that).
If there are more parameters to TabConfig and being at bottom only changes some, you can do
bottomConfig c = let def = defaultConfig c
                 in def { tabX = 3, tabY = 60, ...

Just build the right configuration for the current context and make it available to your functions.  Why should your table-drawing functions have to know about the logic you use to decide how their position on the page constrains their dimensions?  What happens when new conditions impose extra constraints?  Mixing them up is horrible.  Separation of concerns is at least as important to functional programming as in OO.  K
Of course, what I'm trying to hint at is that you want the Reader monad.  But the Reader monad is so simple that you don't have to know you're using it, if monads are still daunting to you.

A: ifs in Haskell aren't terribly pretty, but that's not really the reason they're used so seldom. It's more because there's usually a more elegant syntactic alternative! In your example, I would consider
let (                lblTabX, lblTabY, lblTabPosition, lblTabWidth, lblTabHeight,    lblTabMargin )
     | isAtBottom =( 5,       3,       bottom,         lblPageX-60, 20,              Margin 0 3   )
     | otherwise  =( 3,       60,      top,            20,          pageHeight - 80, Margin 3 0   )

Alternatively, you might define an already partially evaluated operator locally:
let bottomCase/|/topCase | isAtBottom = bottomCase
                         | otherwise  = topCase
    lblTabY         =                      3 /|/ 60
    lblTabPosition  = Position left $ bottom /|/ top
    lblTabWidth     =        (lblPageX - 60) /|/ 20
    lblTabHeight    =                     20 /|/ (pageHeight - 80)
    lblTabMargin    =             Margin 0 3 /|/ Margin 3 0

You definitely do not want to do the check on isAtBottom multiple times, redundant code is always bad, regardless of which syntax you use.
But when you do just need a single decision based on a simple boolean value, I would stick to the standard if rather than defining custom operators.

A: Pattern matching is the main syntax for choice, most everything else is expressed in terms of it. (if is defined in terms of an equivalent case expression for example).


text:
Q: Banach-Tarski theorem without axiom of choice Is it possible to prove the infamous Banach-Tarski theorem without using the Axiom of Choice?
I have never seen a proof which refutes this claim.

A: Directly from Wikipedia's page on the Paradox/Theorem

Unlike most theorems in geometry, this result depends in a critical way on the axiom of choice in set theory. This axiom allows for the construction of nonmeasurable sets, collections of points that do not have a volume in the ordinary sense and for their construction would require performing an uncountably infinite number of choices.

A: While I'm aware you did not ask for this I cannot resist to suggest that you have a look at Stan Wagon's book 'The Banach-Tarski Paradox', Cambridge University Press 1985.

A: The Banach-Tarski theorem heavily uses non-measurable sets. It is consistent that without the axiom of choice all sets are measurable and therefore the theorem fails in such universe. The paradox, therefore, relies on this axiom.
It is worth noting, though, that the Hahn-Banach theorem is enough to prove it, and there is no need for the full power of the axiom of choice.
More information can be found through here:

*

*Herrlich, H. Axiom of Choice. Lecture Notes in Mathematics, Springer, 2006.

*Schechter, E. Handbook of Analysis and Its Foundations. Academic Press, 1997.


text:
Q: ¿Mi servicio window no puede acceder a una carpeta compartida? Tengo una consulta y es la siguiente:
He creado un servicio window que debe acceder a la ruta de la carpeta compartida y me sale un mensaje access to the path xxxx is denied
Revisando algunos paginas de ayuda dice que debo agregar permisos a los usuarios IIS_IUSRS y IUSR en otras dice usuario que inicio sesión del servicio windows pero aun así me sale el mensaje de acceso denegado, he agregado todos los usuarios anteriores pero no solucionan el problema.
Servicio Window
private void stLapso_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (FlagTransfirio) return;

            try
            {
                FlagTransfirio = true;
                EventLog.WriteEntry("Se inicio proceso de copiado", EventLogEntryType.Information);

                string stRutaOrigen = ConfigurationManager.AppSettings["stRutaOrigen"].ToString();
                string stRutaDestino = ConfigurationManager.AppSettings["stRutaDestino"].ToString();

                DirectoryInfo di = new DirectoryInfo(stRutaOrigen);
                foreach (var archivo in di.GetFiles("*", SearchOption.AllDirectories))
                {
                    if (File.Exists(stRutaDestino + archivo.Name))
                    {
                        File.SetAttributes(stRutaDestino + archivo.Name, FileAttributes.Normal);
                        File.Delete(stRutaDestino + archivo.Name);
                    }

                    File.Copy(stRutaOrigen + archivo.Name, stRutaDestino + archivo.Name);
                    File.SetAttributes(stRutaDestino + archivo.Name, FileAttributes.Normal);

                    if (File.Exists(stRutaDestino + archivo.Name))
                    {
                        EventLog.WriteEntry("Se copio archivo con éxito", EventLogEntryType.Information);
                    }
                    else
                    {
                        EventLog.WriteEntry("No se copio el archivo con éxito", EventLogEntryType.Information);
                    }
                }

                EventLog.WriteEntry("Se finalizo proceso de copiado", EventLogEntryType.Information);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(ex.Message, EventLogEntryType.Error);
            }

            FlagTransfirio = false;
        }

Mi App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
  <appSettings>
    <add key="stRutaOrigen" value="\\192.168.2.5\Usrdoc\LIQUIDACIONES_LCL_CHARTER\"/>
    <add key="stRutaDestino" value="C:\inetpub\web_15022019\Excel\"/>
  </appSettings>
</configuration>

A: La cuenta LocalSystem tiene amplios permisos, incluida la capacidad para escribir en el registro de eventos. Utilice esta cuenta con precaución porque podría aumentar el riesgo de ataques por parte de software malintencionado. Para otras tareas, considere la posibilidad de usar la cuenta LocalService , que actúa como un usuario sin privilegios en el equipo local y presenta credenciales anónimas a cualquier servidor remoto. En este ejemplo se produce un error si intenta usar la cuenta LocalService , ya que necesita permiso de escritura en el registro de eventos.


text:
Q: New blog created with Wordpress is not crawlable by sitemap software I have a new blog at glowingstart.com (didn't want to add it to the question, but the domain is needed to verify that it can't be crawled by that sitemap-generating site) and I was trying to use this site http://www.xml-sitemaps.com/ to create a sitemap. I have created sitemaps for other sites there and it worked fine.
But with this new site, I got an error. Is there some setting which prevents crawling that Wordpress has? Or what may be the reason for this?
Thank you!


text:
Q: Does ES6 const affect garbage collection? In Kyle Simpson's new title, You don't know JS: ES6 and beyond, I find the following snippet:

WARNING Assigning an object or array as a constant means that value will not be able to be garbage collected until that constant's lexical scope goes away, as the reference to the value can never be unset. That may be desirable, but be careful if it's not your intent!

(Excerpt From: Simpson, Kyle. "You Don't Know JS: ES6 & Beyond." O'Reilly Media, Inc., 2015-06-02. iBooks.
This material may be protected by copyright.)
As far as I can see, he doesn't expand on this, and 10 minutes on Google turns up nothing. Is this true, and if so, what does "the reference to the value can never be unset" mean exactly? I have got into the habit of declaring variables that won't be changed as const, is this a bad habit in real concrete performance/memory terms?

A: The way garbage collectors (GC) work is when something is referenced by nothing ("cannot be reached"), the GC can safely say that something isn't used anymore and reclaim the memory used by that something.
Being able to replace the value of a variable allows one to remove a reference to the value. However, unlike var, const cannot be reassigned a value. Thus, one can't remove that constant from referencing the value.
A constant, like a variable, can be reclaimed when the constant goes "out of scope", like when a function exits, and nothing inside it forms a closure.

A:
WARNING Assigning an object or array as a constant means that value
will not be able to be garbage collected until that constant's lexical
scope goes away, as the reference to the value can never be unset.
That may be desirable, but be careful if it's not your intent!

That note sounds a bit more of a warning than is necessary (perhaps even a bit silly) and tries to make some sort of special case out of this situation.
With a const variable declaration, you can't assign to the variable something little like "" or null to clear its contents.  That's really the only difference in regard to memory management.  Automatic garbage collection is not affected at all by whether it is declared const or not.
So, if you would like to be able to change the contents of the variable in the future for any reason (including to manually remove a reference to something to allow something to be garbage collected sooner), then don't use const.  This is the same as any other reason for using or not using const.   If you want to be able to change what the variable contains at any time in the future (for any reason), then don't use const.  This should be completely obvious to anyone who understand what const is for.
Calling out garbage collection as a special case for when not to use const just seems silly to me.  If you want to be able to clear the contents of a variable, then that means you want to modify the variable so duh, don't use const.  Yes, manually enabling garbage collection on a large data structure that might be caught in a lasting scope/closure is one reason that you might want to change the variable in the future.  But, it's just one of millions of reasons.  So, I repeat one more time.  If you ever want to change the contents of the variable for any reason in the future, then don't declare it as const.
The garbage collector itself doesn't treat a const variable or the contents it points to any different than a var or let variable.  When it goes out of scope and is no longer reachable, its contents will be eligible for garbage collection.
const has a number of advantages.  It allows the developer to state some intent that the contents this variable points to are not to be changed by code and may allow the runtime to make some optimizations because it knows the contents of the variable cannot be changed.  And, it prevents rogue or accidental code from ever changing the contents of that variable.  These are all good things when used in an appropriate case.  In general, you SHOULD use const as much as practical.

I should add the even some const data can still be reduced in size and make the majority of its contents available for garbage collection.  For example, if you had a really large 100,000 element array of objects (that you perhaps received from some external http call) in a const array:
const bigData = [really large number of objects from some API call];

You can still massively reduce the size of that data by simply clearing the array which potentially makes the large number of objects that was in the array eligible for garbage collection if nothing else had a reference to them:
bigData.length = 0;

Remember, that const prevents assignment to that variable name, but does not prevent mutating the contents that the variable points to.
You could do the same thing with other built-in collection types such as map.clear() or set.clear() or even any custom object/class that has methods for reducing its memory usage.

A: That note in my book was referring to cases like this, where you'd like to be able to manually make a value GC'able earlier than the end of life of its parent scope:
var cool = (function(){
   var someCoolNumbers = [2,4,6,8,....1E7]; // a big array

   function printCoolNumber(idx) {
      console.log( someCoolNumbers[idx] );
   }

   function allDone() {
      someCoolNumbers = null;
   }

   return {
      printCoolNumber: printCoolNumber,
      allDone: allDone
   };
})();

cool.printCoolNumber( 10 ); // 22
cool.allDone();

The purpose of the allDone() function in this silly example is to point out that there are times when you can decide you are done with a large data structure (array, object), even though the surrounding scope/behavior may live on (via closure) indefinitely in the app. To allow the GC to pick up that array and reclaim its memory, you unset the reference with someCoolNumbers = null.
If you had declared const someCoolNumbers = [...]; then you would be unable to do so, so that memory would remain used until the parent scope (via the closure that the methods on cool have) goes away when cool is unset or itself GCd.
Update
To make absolutely clear, because there's a lot of confusion/argument in some comment threads here, this is my point:
const absolutely, positively, undeniably has an effect on GC -- specifically, the ability of a value to be GCd manually at an earlier time. If the value is referenced via a const declaration, you cannot unset that reference, which means you cannot get the value GCd earlier. The value will only be able to be GCd when the scope is torn down.
If you'd like to be able to manually make a value eligible for GC earlier, while the parent scope is still surviving, you'll have to be able to unset your reference to that value, and you cannot do that if you used a const.
Some seem to have believed that my claim was const prevents any GC ever. That was never my claim. Only that it prevented earlier manual GC.

A: No, there are no performance implications. This note refers to the practise of helping the garbage collector (which is rarely enough needed) by "unsetting" the variable:
{
    let x = makeHeavyObject();
    window.onclick = function() {
        // this *might* close over `x` even when it doesn't need it
    };
    x = null; // so we better clear it
}

This is obviously not possibly to do if you had declared x as a const.
The lifetime of the variable (when it goes out of scope) is not affected by this. But if the garbage collector screws up, a constant will always hold the value it was initialised with, and prevent that from being garbage-collected as well, while a normal variable might no more hold it.


text:
Q: Validate name1 and name 2 to connection,prov I want to validate two named connections and their connection status and the prov id value from a given text file with Python/Robot Framework. Below is a sample from the text file Test.txt

name..........: uhn3
connection....: Connected (1)
prov id.......: <[1] id:17/IPv6:240bc0ea01e1554e:a01000000000002/128:5551>
connection....: Connected (1)
prov id.......: <[2] id:17/IPv6:240bc0ea01e1554e:a01000000000002/128:5552>
connection....: Connected (1)
name..........: uhn3k
connection....: Connected (145)
prov id.......: <[3] id:16/IPv6:240bc0ea01e1554e:a01000000000001/128:5551>
connection....: Connected (1)
prov id.......: <[4] id:16/IPv6:240bc0ea01e1554e:a01000000000001/128:5552>
connection....: Connected (1)*

and this is the Robot script I have used.
*** Variables ***
@{application_reqfields}  name  connection  prov id

*** Test Case ***
Login SG and check the status
    ${Cmd_Output}=  Get File  Test.txt
    log to console  ${Cmd_Output}
    ${retVal}=  application_validation   ${Cmd_Output}
    ${application_reqfields}
    log to console  ${retVal}

*** Keywords ***
application_validation
    [Arguments]     ${output}   ${reqFields}
    &{retVal}=  Create Dictionary
    FOR     ${field}     IN      @{reqFields}
        @{match}=  Get Regexp Matches   ${output}     .*${field}\\.*\\:\\s*(\\w+)  1
        set to dictionary   ${retVal}   ${field}    ${match}
    END
    [return]  ${retVal}

The keyword application_validation passes and the output looks like

{ 'name': ['uhn3', 'uhn3k'], 'connection': ['Connected', 'Connected', 'Connected', 'Connected', 'Connected'], 'prov id': [] }

I'd need to retrieve the name and related connection status for that connection from the returned value.

A: You seem to have two issues in the script, one is related to not being able to access the correct dictionary value for validation and another is that there is the prov id value which is returned as an empty list.
General Use of Get Regexp Matches
The output you are receiving is actually described in the String Library documentation for keyword Get Regexp Matches. There it is stated that the keyword will return a list of all non-overlapping matches. This means that the output you are receiving is as expected.
You can access dictionary values in Robot Framework simply by using
${VALUE}=    Set Variable    ${DICT[key]}

Because you are having the values behind the keys as lists, you'll need to first get the list out of the dictionary and then access the index in the list you wish to open.
${name1}=    Get From List    ${retVal["name"]}    0

Get From List is from Collections library. But of course this will only return the name and not anything related to it.
Additionally your issue with the prov id is simply due to your regexp call not considering the extra characters in the value. If you change the regexp to consider those instead of simply expecting whitespace it will work fine. This regexp seems to work fine.
${field}\.*\:\s(.*\w+)

Maintaining Item Relation
In order to maintain the relation between items so that the name can be attached to the corresponding entries of prov id/connection you would need to have a set rule on how the entities work here, consider for example

A name field starts a new entity, each connection/prov id is related to the name above it.

Or

Only 3 connection fields may exist for name

Once you have figured that out, you can use following script to capture each field separately and then build from there. I'm assuming that whatever is under the specific name will be assigned to that field, regardless how many entries there are.
application_validation
    [Arguments]     ${output}   ${reqFields}
    &{retVal}=  Create Dictionary
    @{entities}=  Split String    ${output}    name  # Splitting the string on name field
    ${removed}=  Remove From List    ${entities}    0  # Removing empty item on index 0
    FOR  ${item}    IN   @{entities}    # Iterating to get data based on names
        @{name}=    Get Regexp Matches    ${item}    ^\\.*\\:\\s(?P<name>\\w+)    name  # Expecting only single name but the keyword will return a list anyway
        @{connections}=    Get Regexp Matches    ${item}    connection\\.*\\:\\s*(?P<conn>\\w+)  conn
        @{provs}=  Get Regexp Matches    ${item}    prov id\\.*\\:\\s*(?P<prov>.*\\w+)  prov

        # Let's assign the connection status to correct prov id
        &{tempdict}=    Create Dictionary
        FOR    ${conn}  ${prov}    IN ZIP    @{connections}  @{provs}
            Set to Dictionary    ${tempdict}    ${prov}=${conn}
        END
        # Then we need to create an output for each name/value entity
        Set to Dictionary    ${retVal}    ${name}[0]=${tempdict}
    END
    [Return]    ${retVal}

The above script will provide you with a dictionary with nested dictionary for each name where the inner dictionary contains prov id as a key and connection as the value. For example the uhn3 from your example would be returned as
&{retVal}= { "uhn3": {"<[1] id:17/IPv6:240bc0ea01e1554e:a01000000000002/128:5551>": "connected", "<[2] id:17/IPv6:240bc0ea01e1554e:a01000000000002/128:5552>": "connected" }

The weakness of this script will however be if there is a possibility of different number of connection and prov id fields, there will be index error so you'll have to adjust accordingly.
Calling the values from the dictionary can be done by first getting the outer dictionary
FOR    ${name}    IN     @{retVal.keys()}
    Log    ${name}
    FOR    ${conn}    IN   @{name.keys()}
        Log    ${conn}: ${name[${conn}]}
    END
END


text:
Q: how to get started with using version one java script sdk I am looking for a good getting started guide for using version one java Script
SDK.I am using eclipse IDE.Please suggest the project structure for a webapp project using it.
here is a link that i got which has some info.
Also suggest the documentation for the version one java script SDK.

A: I have created a article, http://walkerrandolphsmith.com/blog/v1sdk/, that describes a minimal setup to start using the SDK. In brief the application is a Node app that requires two dependencies: The v1sdk and a AJAX library.
In case the link becomes stale I will condense the article.
npm init --yes
npm install --save v1sdk axios

Create a file server.js
const axios = require('axios');
const v1sdk = require('v1sdk/dist/index');
const sdk = v1sdk.default;
const axiosConnector = v1sdk.axiosConnector;

const axiosConnectedSdk = axiosConnector(axios)(sdk);
const v1 = axiosConnectedSdk('V1Host', 'v1Instance')
            .withCreds('v1User', 'v1Password');
v1.query({
    'from': 'PrimaryWorkitem',
    'select': [
        'Name'
    ]
}).then(assets => {
    console.log(assets);
});

From the command line run, node server.js


text:
Q: How to restrict group visibility rights inside a product in bugzilla Like the person in "separate clients question" I am trying to define "clients" groups within our bugzilla instance. The difference is in the visibility within a particular product. We would like to:

*

*have each group of client only see its project and not the other projects (this is the requirement already answered by the question above),

*have the possibility for each project to have bugs filled either by internal people or by the clients,

*bugs filled by clients are seen by other clients (of the same group of course) and by internals,

*by default bugs filled by internals are also seen by the client group and by internals, but it is possible for the internal accounts to check a box restricting the visibility to only internal.

I tried to google/groups this but the requirements seem a bit unusual. Also I am confident that it should be possible with the MemberControl/OtherControl options explained here. But I can't figure them out. The options I tried were either two restrictive (Mandatory/Mandatory) or not enough (Default/NA for the internal group but then the bug became public, hence the other client groups could see it).
Thanks in advance for your help.
Cheers,
Christophe.

A: The problem is that Bugzilla authorization model is little different. If you want some group to view only one product, on the "Edit group access controls" make him mandatory/mandatory. And only him. And mark the checks to let them edit. Leave all other groups unchecked and NA/NA. Even the administradors. If you have other groups that need access to that product, let`s say the programmers for instance, you have to make their group part of the customer group. Edit the group and mark the programmers group on the "Groups That are members of this group". And so on.
The idea is: if a product is restricted, then it has to belong to group x. Then add all the additional groups that need access under this master group. The customer group is the master on their products.
Got the idea?


text:
Q: PHP encapsulation without class? Is it possible to encapsulate, a variable or function let say, in PHP without wrapping them in a class? What I was doing is:
//Include the file containing the class which contains the variable or function
include('SomePage.php');

//Instantiate the class from "SomePage.php"
$NewObject = new SomeClassFromSomePage();

//Use the function or variable
echo $NewObject->SomeFuncFromSomeClass();
echo $NewObject->SomeVarFromSomeClass;

My intention is to avoid naming conflict. This routine, although it works, makes me tired. If I cannot do it without class, it is possible not to instantiate a class? and just use the variable or function instantly?

A: To use class methods and variables without instantiating, they must be declared static:
class My_Class
{
    public static $var = 123;

    public static function getVar() {
     return self::var;
    }
}

// Call as:
My_Class::getVar();

// or access the variable directly:
My_Class::$var;

With PHP 5.3, you can also use namespaces
namespace YourNamespace;

function yourFunction() {
  // do something...
}

// While in the same namespace, call as
yourFunction();

// From a different namespace, call as
YourNamespace\yourFunction();

A: PHP Namespaces were made to archive the exact same goal:
<?php // foo.php
namespace Foo;
function bar() {}
class baz {
    static $qux;
}
?>

When using call namespaced functions like this:
<?php //bar.php
include 'foo.php';
Foo\bar();
Foo\baz::$qux = 1;
?>

A: This is a way to encapsulate without Class
<?php

(function (){

$xyz = 'XYZ';

})();

echo $xyz; // warning: undefined

Encapsulation Alternative
With this method you can minimize unintentional using array key(uses it instead of variables). Can also use value stored in array anywhere after assigning. Shorter array key area length with variable in keys, inside encapsulation function; outside encapsulation function, variables can be used in keys but otherwise long discriptive keys. Nested encapsulation can also be used.
Example
<?php

define('APP', 'woi49f25gtx');

(function () {

    $pre = 'functions__math__'; // "functions" is main category, "math" is sub.

    $GLOBALS[APP][$pre . 'allowedNumbers'] = [3,5,6];

    $GLOBALS[APP][$pre . 'square'] = function ($num) {
        return $num * $num;
    };

    $GLOBALS[APP][$pre . 'myMathFunction'] = function ($num) use ($pre) {
        if(in_array($num,$GLOBALS[APP][$pre . 'allowedNumbers'])) return 'not allowed';
        return $GLOBALS[APP][$pre . 'square']($num);
    };

})();

echo $GLOBALS[APP]['functions__math__myMathFunction'](4);


text:
Q: fb iframe application: 405 error my application works fine without iframe, returns 405 error at facebook! why is it so?

A: For reference I had this same 405 error. This was because my Facebook app was pointing to a .html file for testing.
I renamed to .aspx and my server stopped sending that error back to Facebook

A: Disable POST for Canvas on the application settings, under the "advanced" tab.

A: When using nginx server, this can be caused by pointing root of the web to .html file... Change it e.g to .php and it will work.
This is probabl because nginx does not allow POST method on static websites.


text:
Q: C++17 class template partial deduction My understanding about the Template argument deduction for class templates proposal was to homogenize the behaviour of template functions and template classes in deduction contexts. But I think that I have misunderstood something.
If we have this template object:
template <std::size_t S, typename T>
struct test
{
    static constexpr auto size = S;
    using type_t = T;

    test(type_t (&input)[size]) : data(input) {}
    type_t (&data)[size]{};
};

I tend to use a helper function as syntactic sugar for creating test objects:
template <std::size_t S, typename T>
test<S, T> helper(T (&input)[S]) { return input; }

Which can be used as shown below:
int main()
{
    int buffer[5];

    auto a = helper<5, int>(buffer); // No deduction
    auto b = helper<5>(buffer);      // Type deduced
    auto c = helper(buffer);         // Type and size deduced

    std::cout << a.size << b.size << c.size;

    return 0;
}

The code above outputs 555 as expected. I've tried the same in Wandbox using the newer compiler setup1:
int main()
{
    int buffer[5];

    test<5, int> a(buffer); // No deduction: Ok.
    test<5> b(buffer);      // Type deduced: FAILS.
    test c(buffer);         // Type and size deduced: Ok.

    std::cout << a.size << b.size << c.size;

    return 0;
}

It looks like template argument deduction for class templates works only deducing all the parameters, I was expecting both behaviours (helper function and class template) to be the same, did I misunderstood something?

1The last compilers availables in Wandbox are gcc HEAD 7.0.1 201701 and clang HEAD 5.0.0 (trunk).

A: From this excellent trip report by Botond Ballo:

The feature as originally proposed included a provision for partial deduction, where you explicitly specify some of the template arguments, and leave the rest to be deduced, but this was pulled over concerns that it can be very confusing in some cases:
// Would have deduced tuple<int, string, float>,
// but tuple<int> is a well-formed type in and of itself!
tuple<int> t(42, "waldo", 2.0f);

A: There appears to be a contradiction here. Looking at P0091R3, it seems clear that partially specifying parameters is supposed to be allowed:

We propose to allow a template name referring to a class template as a simple-type-specifier or with partially supplied explicit template arguments in two contexts:

But the actual standards wording in the same proposal does not provide a way to handle "partially supplied explicit template arguments". template-name as a simple-type-specifier is not allowed to have template arguments.
So following the specification itself, the compiler's behavior appears to be correct.


text:
Q: Asp.Net UpdatePanel error I use UpdatePanel in my aspx page and DropDownList with onselectedindexchanged method.
When run first time onselectedindexchanged method is working. But change selected again it return an error like that;

Uncaught Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException: The state information is invalid for this page and might be corrupted.

 <asp:ScriptManager ID="ScriptManager1" runat="server" EnableViewState="False" EnableScriptGlobalization="true" >
</asp:ScriptManager>

<%@ Page Title="" Language="C#" AutoEventWireup="true"
EnableEventValidation="false" ...  %>

Not : I have to Partial Rendering so i cant add EnablePartialRendering="false" to ScriptManager.
How can i solve this problem?

A: As per @Aristos' comment above, with my Telerik solution, I had to temporarily remove the telerik:RadAjaxManager to see the underlying error. This is similar to temporarily removing the UpdatePanel.
In my case, the error was: TypeLoadException: Could not load type 'System.Data.Entity.DynamicProxies.RepricingApproval_40D472CCAE59DB7A70B40FC6B029B430955A5ED87A7670652AA5B4D9D96A9A38' from assembly 'EntityFrameworkDynamicProxies-Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.]

(BTW, the fix for the above was to set EnableFlattening to false).


text:
Q: Find the $n$ derivative of $y= e^{2x}\sin^2 x$ We have
\begin{align*}
y&= e^{2x}\sin^2 x\\
&= e^{2x}\left(\frac{1-\cos 2x}{2}\right)\\
&= \frac{e^{2x}}{2} - \frac{e^{2x}\cos 2x}{2}
\end{align*}
Then
\begin{align*}
y^{(n)} &= \left(\frac{e^{2x}}{2}\right)^{(n)} - \left(\frac{e^{2x}\cos 2x}{2}\right)^{(n)}\\
&= 2^{n-1}e^{2x} - \left(\frac{e^{2x}\cos 2x}{2}\right)^{(n)}
\end{align*}
I don't know how to proceed with the rightmost term. So far I've been applying the Leibniz Rule whenever I've had to find the $n$ derivative of a function of the form $f(x)g(x)$, because is clear that either $f(x)$ or $g(x)$ has a derivative a $k$ derivative ($1<k<n$) equal to zero, which simplifies the expression nicely.
But here
$$\frac{e^{2x}\cos 2x}{2}$$
both functions are infinitely differentiable on $\mathbb{R}$ which makes things a bit different.
My only attempt was to write its n derivative in this form
\begin{align*}
&=\frac{1}{2}\sum_{k=0}^n{n \choose k} \big(2^k e^{2x}\big)\bigg(2^{n-k}\cos \left[2x + \frac{\pi(n-k)}{2}\right]\bigg)\\
&=\sum_{k=0}^n {n \choose k} 2^{n-1}e^{2x}\cos \left[2x + \frac{\pi(n-k)}{2}\right]
\end{align*}
So
\begin{align*}
y^{(n)} &= 2^{n-1}e^{2x} -\sum_{k=0}^n{n \choose k} 2^{n-1}e^{2x}\cos \left[2x + \frac{\pi(n-k)}{2}\right]\\
&= 2^{n-1}e^{2x}\left(1 -\sum_{k=0}^n{n \choose k} \cos \left[2x + \frac{\pi(n-k)}{2}\right]\right)
\end{align*}
But the textbook's answer is
$$2^{n-1}e^{2x}\left(1 -2^{n/2}\cos \left[2x + \frac{\pi n}{4}\right]\right)$$
For some reason I have the feeling that a little of modular arithmetic has to be applied on $\frac{\pi(n-k)}{2}$

A: You're correct that Leibniz's Rule is a sound way forward.  Note that we have
$$\begin{align}
e^{2x}\sin^2(x)=\frac12 e^{2x}-\frac12 e^{2x}\cos(2x)
\end{align}$$
Then, taking the $n$'th order derivative, we have
$$\begin{align}
\frac{d^n}{dx^n}\left(e^{2x}\sin^2(x)\right)&=\frac{d^n}{dx^n}\left(\frac12 e^{2x}-\frac12 e^{2x}\cos(2x)\right)\\\\
&=2^{n-1}e^{2x}-\frac12 \sum_{k=0}^n\binom{n}{k}\frac{d^{n-k}e^{2x}}{dx^{n-k}}\frac{d^k\cos(2x)}{dx^k}\\\\
&=2^{n-1}e^{2x}\left(1-\sum_{k=0}^n\binom{n}{k}\frac{d^k\cos(2x)}{d(2x)^k}\right)\\\\
\end{align}$$
So, the problem boils down to taking the $k$'th derivative of the cosine function.  But we can express that derivative as $\cos(x+k\pi/2)$.  Hence, we have
$$\begin{align}
\frac{d^n}{dx^n}\left(e^{2x}\sin^2(x)\right)&=2^{n-1}e^{2x}\left(1-\sum_{k=0}^n\binom{n}{k}\cos(x+k\pi/2)\right)\\\\
&=2^{n-1}e^{2x}\left(1-\text{Re}\left(\sum_{k=0}^n\binom{n}{k}e^{i(x+k\pi/2)}\right)\right)\\\\
&=2^{n-1}e^{2x}\left(1-\text{Re}\left(e^{ix}(1+i)^n\right)\right)\\\\
&=2^{n-1}e^{2x}\left(1-\text{Re}\left(2^{n/2}e^{i(x+n\pi/4)}\right)\right)\\\\
&=2^{n-1}e^{2x}\left(1-2^{n/2}\cos(x+n\pi/4)\right)\\\\
\end{align}$$
as was to be shown!

A: We know that $$\sin^2(x) =  \dfrac{1 - \cos(2x)}{2}= \dfrac{1}{2} -\dfrac{1}{2}\Re(\exp(2ix)), $$ where $\Re$ is the real part of a complex number.
It follows that
$$y =\exp(2x)\sin^2(x) = \dfrac{\exp(2x)}{2} - \dfrac{1}{2}\Re(\exp(zx)), $$ with $z = 2+2i.$
Using complex-valued derivatives:
$$\dfrac{dy}{dx} = \exp(2x)- \dfrac{z}{4}\exp(zx)- \dfrac{z^{*}}{4}\exp(z^{*}x),$$ which leads to
$$\dfrac{d^ny}{dx^n} = 2^{n-1}\exp(2x) - \dfrac{z^n}{4}\exp(zx) - \dfrac{z^{*n}}{4}\exp(z^{*}x) = 2^{n-1}\exp(2x) - \dfrac{1}{2}\Re (z^n \exp(zx)).$$

A: Calculate the fist few derivatives and see if a recognizable pattern shows up.
$f(x) = \frac {e^{2x}}{2} + \frac {e^{2x}\cos2x}{2}\\
f'(x) = e^{2x} + e^{2x} \cos 2x - e^{2x}\sin 2x\\
f''(x) = 2e^{2x} - 2e^{2x}\cos 2x - 2e^{2x}\sin 2x - 2e^{2x}\sin 2x - 2e^{2x} \cos 2x = 2e^{2x} - 4e^{2x}\sin 2x\\
f'''(x) = 4e^{2x} - 8 e^{2x}\sin 2x - 8 e^{2x}\cos 2x\\
f^{(4)} = 8e^{2x} - 16\cos 2x$
Do you see a pattern? Can you prove that the pattern will continue?
If you know a little bit about complex exponential you could say:
$f(x) = \frac {e^{2x}}{2} + Re[\frac {e^{(2+2i)x}}{2}]\\
f^{(n)}(x) = 2^n\frac {e^{2x}}{2} + \frac {(2\sqrt2)^n}{2} Re[\frac {e^{(2+2i)x + \frac {n\pi}{4}i}}{4}]\\
f^{(n)}(x) = 2^n\frac {e^{2x}}{2} + \frac {(2\sqrt2)^n}{2} e^{2x} \cos(2x + \frac {n\pi}{4})\\$

A: Taking into consideration just the second part, let's call
$$p(x)=e^{2x}\cos 2x$$
then
\begin{align}
&p^{(1)}(x)=2e^{2x}\cos 2x-2e^{2x}\sin 2x\\
&p^{(1)}(x)=2e^{2x}(\cos 2x-\sin 2x)=2e^{2x}\sqrt{2}\left(\frac{\sqrt{2}}{2}\cos 2x-\frac{\sqrt{2}}{2}\sin 2x\right)\\
&p^{(1)}(x)=2^{3/2}e^{2x}\left(\cos(\pi/4)\cos 2x-\sin(\pi/4)\sin 2x\right)\\
&p^{(1)}(x)=2^{3/2}e^{2x}\cos\left( 2x+\pi/4 \right)
\end{align}
and following the same calculation that we just did we can conclude that
$$p^{(2)}(x)=2^{3/2}2^{3/2}e^{2x}\cos\left( 2x+\pi/4+\pi/4 \right)$$
Now we can see the pattern. So we can prove by finite induction that
$$p^{(n)}(x)=2^{3n/2}e^{2x}\cos\left( 2x+n\pi/4\right)$$
and finaly:
$$\left(\frac{e^{2x}\cos 2x}{2}\right)^{(n)}=2^{3n/2-1}e^{2x}\cos\left( 2x+n\pi/4\right)$$

A: The crux of the problem boils down to computing the $n$th derivative of the function $f(u)=e^u\cos u$.  (Note that if $g(x)=f(2x)$, then $g^{(n)}(x)=2^nf^{(n)}(2x)$.)  Using $\cos u=\Re(e^{iu})$ and $1+i=\sqrt2e^{i\pi/4}$, we find
$$f(u)=\Re(e^{(1+i)u})\implies f^{(n)}(u)=\Re((1+i)^ne^{(1+i)u})=2^{n/2}e^u\Re(e^{(u+n\pi/4)i})=2^{n/2}e^u\cos\left(u+{n\pi\over4}\right)$$
Applied to the OP's problem, we have
$$y(x)={e^{2x}\over2}-{f(2x)\over2}\implies y^{(n)}(x)={2^ne^{2x}\over2}-{2^nf^{(n)}(2x)\over 2}=2^{n-1}e^{2x}\left(1-2^{n/2}\cos\left(2x+{n\pi\over4} \right)\right)$$


text:
Q: Removing and recreating file does not change its creation timestamp on NTFS I've experienced some strange problem with NTFS. The easiest way to reproduce it contains 3 steps.

*

*Creating file foo.txt in arbitrary place, remembering its creation timestamp (it can be found in properties dialog for this file)

*Removing it with shift + delete

*Quickly recreating file with the same name, again looking at properties window. Creation timestamp didn't change since the first file creation (though modified timestamp is other).

This effect causes a great headake in implementing some complex logic in my Qt application. I am simply writing
QFile::remove(file);

but it is pretty clear that file removal must be some kind of flushed. What I want to know is an explanation of this effect and some tips how to aviod it. A way to correctly implement it in Qt (instead of simply writing) will be much appreciated. I have reproduced this effect on Windows 8.1.


text:
Q: Show the identity $\overline{A\setminus B} = \overline{A}∪B$ I've come across this problem in a finals paper.
I've found the right implication, that is $\overline{A\setminus B} \subseteq \overline{A}∪B$, by taking a $\in \overline{A\setminus B} $
Note: $\overline{A}$ denotes the complement of the set A
I need some guidance on finding the leftwards implication. Any tips?
Edit: Solved in comments

A: We wish to show that $\overline{A}\cup{B} \subseteq \overline{A\setminus B}$ holds in general. The approach attempted by the original poster (checking that they are both subsets of each other) is also a valid approach. However, we can solve the problem much quicker than this as follows.
Step 1
Observe that: ${A\setminus B} = {A\cap \overline B}$ and so we can rewrite $\overline{A\setminus B} = \overline{A\cap \overline B}$
Step 2
By de Morgan's law, we know that, in general, $\overline{X\cap Y}=\overline{X}\cup \overline{Y}$ and so if we apply that to our conclusion from step 1, we arrive at final result: $\overline{A\cap \overline B} = \overline{A} \cup B$ as required.
And so this is all we need to complete the proof.


text:
Q: разница между T const& и T Какая разница между типами T const& и T при возвращении/принятии параметров в функцию, где T -- н-ый тип данных?

A: В терминах аргументов функции:
T - означает, что объект передается по значению, т.е. вызывается конструктор копирования объекта (создается новый экземпляр данного типа на стеке). Таким образом, изменение аргумента внутри функции не повлечет на состояние объекта, копию которого мы передали в функцию.
T& - означает, что объект передается по ссылке, т.е. без вызова конструктора копирования (прокидывается ссылка на объект, количество памяти выделяемое под которую зависит от разрядности ОС: в 32-битой - 4 байта, в 64-битной - 8 байт). Изменение состояния объекта, переданного таким образом в функцию, внутри этой функции повлечет его изменение вне её.
Модификатор const означает, что передается константный объект, т.е. объект, который нельзя менять внутри функции.
Если нет необходимости менять объект внутри функции, то объект следует передавать как const T& (все, кроме примитивов), примитивы даже в таком случае выгоднее передавать по значению.
Контрольный пример:
void passByValue(int parm){ parm = 2; }
void passByRef (int& parm){ parm = 2; }

int main()
{
   int parm = 1;

   passByValue(parm);
   cout << boolalpha << (2 == parm); // false

   passByRef(parm);
   cout << boolalpha << (2 == parm); // true
}

При возвращении объекта:
Применимо все тоже, что и для аргументов функции, но существует несколько особенностей.
Если же вы возвращаете ссылку на объект из функции, то будьте уверены в том, что время жизни объекта не истечет за пределами функции.
При возвращании объекта по значению, объект не обязательно будет скопирован, т.к. возможна ситуация с copy elision (частным случаем которой является RVO/NRVO), а также применение конструктора/оператора перемещения.
Контрольный пример:
#include <iostream>

using namespace std;

int global = 1;

int getByValue()              { return global; }
int& getByRef_valid()         { return global; }
const int& getByRef_notValid(){ return 1; }

int main()
{
   int value = getByValue();
   cout << boolalpha << (1 == global); // true
   value = 2;
   cout << boolalpha << (2 == global); // false

   int& validRef = getByRef_valid();
   cout << boolalpha << (1 == global); // true
   validRef = 2;
   cout << boolalpha << (2 == global); // true

   // переменная notValidRef ссылается на память, которая уже помечена как свободная
   // т.е. может быть перезаписана кем угодно в любой момент времени, что невалидно
   const int& notValidRef = getByRef_notValid();
}

A: T const& или const T& - это ссылка на константный объект типа T и передача осуществляется по ссылке (нет полного копирования данных). А если используется просто T, то осуществляется передача по значению и это требует создания копии объекта. Поэтому при передаче в функцию больших объектов, не требующих модификации, следует использовать передачу по ссылке на константу.
При возвращении также можно использовать ссылку. Но главное при этом не забывать, что объект, ссылка на который возвращается из функции, остается живым после завершения функции. Т.е. нельзя например возвращаться ссылки на локальные объекты функции.

A: Если бы это было одно и то же то компилятор не ругался подобным образом:

как видите обе функции одинаковы, только функция ref работает только с постоянными методами переданного ей объекта, которых в классе не объявлено.
что бы убедится в этом раскомментируйте спецификатор const в функции test класса T и ошибки не будет.

Это своеобразный механизм защиты


text:
Q: Model View Controller pattern in REST HTTP client I am a bit confused what should Model consist of in the case of REST client. Let's assume I want to have a client to communicate with server via REST. No database.
Example: I want to send a POST HTTP request with some form data to a server. Where should I put methods like construct_REST_request() or execute_REST_request()? In Controller or in Model? In model theoretically should be business logic objects. Does it mean in Model should be only data that Controller uses?

A: Models are your business objects,  this need not to be database always - but essentially target objects on which controllers will operate.
Controllers executes business logic 'to and from' the models/objects, based on the request from view or other exposure of your REST controllers to the outer world. The example method you given should be part of controller


text:
Q: iPhone: Image gets inverted I'm having a problem with my image on my iPhone app.
When I run my app on my simulator, everything looks good and there's no problem.
But now I've installed the app on my device with TestFlight and the image seems to be inverted. Normally it's a very bright image, and now it's all dark, and some parts are extremely light.
Does anyone know what could be the cause of this?
Thanks
Tjeu

A: I am not sure but I think there must be some problem with the orientation.
Try with face up and face down orientation.


text:
Q: Spring Batch is not exiting when using Spring Integration JAR When I am using Spring integration JAR, my spring application is not exiting. The MBeanExporter is not unregistering the beans and shutting down.
Here are the logs:
Without JAR
2018-09-03 11:03:45 INFO  [main] o.s.b.c.l.support.SimpleJobLauncher - Job: [SimpleJob: [name=resetRegressionDataJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]
2018-09-03 11:03:45 INFO  [main] c.p.c.r.ResetRegressionDataBatchJob - ResetRegressionDataBatchJob exiting with status of exitCode=COMPLETED;exitDescription=
2018-09-03 11:03:45 INFO  [Thread-118] o.s.c.a.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@c6f9085f: startup date [Mon Sep 03 11:02:56 BST 2018]; root of context hierarchy
2018-09-03 11:03:45 INFO  [Thread-118] o.s.jmx.export.MBeanExporter - Unregistering JMX-exposed beans on shutdown
2018-09-03 11:03:45 INFO  [Thread-118] o.s.jmx.export.MBeanExporter - Unregistering JMX-exposed beans
2018-09-03 11:03:45 INFO  [Thread-118] o.s.s.c.ThreadPoolTaskExecutor - Shutting down ExecutorService 'taskExecutor'
2018-09-03 11:03:46 INFO  [Thread-118] o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default'

With JAR
2018-09-03 11:06:55 INFO  [main] c.p.c.r.ResetRegressionDataBatchJob - Started ResetRegressionDataBatchJob in 50.735 seconds (JVM running for 51.906)
2018-09-03 11:06:55 INFO  [main] c.p.c.i.batch.BaseRunnableBatchJob - **************** jobShouldBeRun: True (Default - No Override)
2018-09-03 11:06:55 INFO  [main] o.s.b.c.l.support.SimpleJobLauncher - Job: [SimpleJob: [name=resetRegressionDataJob]] launched with the following parameters: [{}]
2018-09-03 11:06:55 INFO  [main] o.s.batch.core.job.SimpleStepHandler - Executing step: [step1]
2018-09-03 11:06:55 INFO  [main] c.p.c.r.ResetRegressionDataBatchJob - Running the Delete and Update Script for the Regression Reset Batch Job....
2018-09-03 11:06:55 INFO  [main] o.s.jdbc.datasource.init.ScriptUtils - Executing SQL script from class path resource [regression/data/regression.reset.deleteupdatedata.sql]
2018-09-03 11:06:55 INFO  [main] o.s.jdbc.datasource.init.ScriptUtils - Executed SQL script from class path resource [regression/data/regression.reset.deleteupdatedata.sql] in 193 ms.
2018-09-03 11:06:55 INFO  [main] c.p.c.i.b.l.BaseBatchListenerSupport - Start Time is 2018-09-03 11:06:55:282
2018-09-03 11:06:55 INFO  [main] c.p.c.i.b.l.BaseBatchListenerSupport - End Time is 2018-09-03 11:06:55:528
2018-09-03 11:06:55 INFO  [main] c.p.c.i.b.l.BaseBatchListenerSupport - Duration 0:0:0.246
2018-09-03 11:06:55 INFO  [main] c.p.c.i.b.l.BaseBatchListenerSupport - Batch Status is COMPLETED
2018-09-03 11:06:55 INFO  [main] c.p.c.i.b.l.BaseBatchListenerSupport - Exit Status is exitCode=COMPLETED;exitDescription=
2018-09-03 11:06:55 INFO  [main] o.s.b.c.l.support.SimpleJobLauncher - Job: [SimpleJob: [name=resetRegressionDataJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]
2018-09-03 11:06:55 INFO  [main] c.p.c.r.ResetRegressionDataBatchJob - ResetRegressionDataBatchJob exiting with status of exitCode=COMPLETED;exitDescription=

With System.exit(0)
2018-09-03 11:49:50 INFO  [main] c.p.c.i.b.l.BaseBatchListenerSupport - Start Time is 2018-09-03 11:49:50:052
2018-09-03 11:49:50 INFO  [main] c.p.c.i.b.l.BaseBatchListenerSupport - End Time is 2018-09-03 11:49:50:342
2018-09-03 11:49:50 INFO  [main] c.p.c.i.b.l.BaseBatchListenerSupport - Duration 0:0:0.290
2018-09-03 11:49:50 INFO  [main] c.p.c.i.b.l.BaseBatchListenerSupport - Batch Status is COMPLETED
2018-09-03 11:49:50 INFO  [main] c.p.c.i.b.l.BaseBatchListenerSupport - Exit Status is exitCode=COMPLETED;exitDescription=
2018-09-03 11:49:50 INFO  [main] o.s.b.c.l.support.SimpleJobLauncher - Job: [SimpleJob: [name=resetRegressionDataJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]
2018-09-03 11:49:50 INFO  [main] c.p.c.r.ResetRegressionDataBatchJob - ResetRegressionDataBatchJob exiting with status of exitCode=COMPLETED;exitDescription=
2018-09-03 11:49:50 INFO  [Thread-118] o.s.c.a.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@fb5a33e4: startup date [Mon Sep 03 11:48:56 BST 2018]; root of context hierarchy
2018-09-03 11:49:50 INFO  [Thread-118] c.p.c.f.batch.ContextClosedHandler - Inside onApplicationEvent Shutting down ThreadPoolTaskExecutor
2018-09-03 11:49:50 INFO  [Thread-118] o.s.s.c.ThreadPoolTaskExecutor - Shutting down ExecutorService 'taskExecutor'
2018-09-03 11:49:50 INFO  [Thread-118] o.s.c.s.DefaultLifecycleProcessor - Stopping beans in phase 0
2018-09-03 11:49:50 INFO  [Thread-118] o.s.i.endpoint.EventDrivenConsumer - Removing {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2018-09-03 11:49:50 INFO  [Thread-118] o.s.i.c.PublishSubscribeChannel - Channel 'application.errorChannel' has 0 subscriber(s).
2018-09-03 11:49:50 INFO  [Thread-118] o.s.i.endpoint.EventDrivenConsumer - stopped _org.springframework.integration.errorLogger
2018-09-03 11:49:50 INFO  [Thread-118] o.s.c.s.DefaultLifecycleProcessor - Stopping beans in phase -2147483648
2018-09-03 11:49:50 INFO  [Thread-118] o.s.jmx.export.MBeanExporter - Unregistering JMX-exposed beans on shutdown
2018-09-03 11:49:50 INFO  [Thread-118] o.s.jmx.export.MBeanExporter - Unregistering JMX-exposed beans
2018-09-03 11:49:50 INFO  [Thread-118] o.s.s.c.ThreadPoolTaskExecutor - Shutting down ExecutorService 'taskExecutor'
2018-09-03 11:49:51 INFO  [Thread-118] o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default'
2018-09-03 11:49:51 INFO  [Thread-118] o.s.s.c.ThreadPoolTaskScheduler - Shutting down ExecutorService 'taskScheduler'

With context.stop()
2018-09-03 14:49:39 INFO  [main] c.p.c.r.ResetRegressionDataBatchJob - Started ResetRegressionDataBatchJob in 49.884 seconds (JVM running for 50.91)
2018-09-03 14:49:39 INFO  [main] o.s.c.s.DefaultLifecycleProcessor - Starting beans in phase -2147483648
2018-09-03 14:49:39 INFO  [main] o.s.c.s.DefaultLifecycleProcessor - Starting beans in phase 0
2018-09-03 14:49:39 INFO  [main] c.p.c.i.batch.BaseRunnableBatchJob - **************** jobShouldBeRun: True (Default - No Override)
2018-09-03 14:49:39 INFO  [main] o.s.b.c.l.support.SimpleJobLauncher - Job: [SimpleJob: [name=resetRegressionDataJob]] launched with the following parameters: [{}]
2018-09-03 14:49:39 INFO  [main] o.s.batch.core.job.SimpleStepHandler - Executing step: [step1]
2018-09-03 14:49:39 INFO  [main] c.p.c.r.ResetRegressionDataBatchJob - Running the Delete and Update Script for the Regression Reset Batch Job....
2018-09-03 14:49:39 INFO  [main] o.s.jdbc.datasource.init.ScriptUtils - Executing SQL script from class path resource [regression/data/regression.reset.deleteupdatedata.sql]
2018-09-03 14:49:39 INFO  [main] o.s.jdbc.datasource.init.ScriptUtils - Executed SQL script from class path resource [regression/data/regression.reset.deleteupdatedata.sql] in 181 ms.
2018-09-03 14:49:39 INFO  [main] c.p.c.i.b.l.BaseBatchListenerSupport - Start Time is 2018-09-03 14:49:39:363
2018-09-03 14:49:39 INFO  [main] c.p.c.i.b.l.BaseBatchListenerSupport - End Time is 2018-09-03 14:49:39:594
2018-09-03 14:49:39 INFO  [main] c.p.c.i.b.l.BaseBatchListenerSupport - Duration 0:0:0.231
2018-09-03 14:49:39 INFO  [main] c.p.c.i.b.l.BaseBatchListenerSupport - Batch Status is COMPLETED
2018-09-03 14:49:39 INFO  [main] c.p.c.i.b.l.BaseBatchListenerSupport - Exit Status is exitCode=COMPLETED;exitDescription=
2018-09-03 14:49:39 INFO  [main] o.s.b.c.l.support.SimpleJobLauncher - Job: [SimpleJob: [name=resetRegressionDataJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]
2018-09-03 14:49:39 INFO  [main] c.p.c.r.ResetRegressionDataBatchJob - ResetRegressionDataBatchJob exiting with status of exitCode=COMPLETED;exitDescription=
2018-09-03 14:49:39 INFO  [main] o.s.c.s.DefaultLifecycleProcessor - Stopping beans in phase 0
2018-09-03 14:49:39 INFO  [main] o.s.i.endpoint.EventDrivenConsumer - Removing {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2018-09-03 14:49:39 INFO  [main] o.s.i.c.PublishSubscribeChannel - Channel 'application.errorChannel' has 0 subscriber(s).
2018-09-03 14:49:39 INFO  [main] o.s.i.endpoint.EventDrivenConsumer - stopped _org.springframework.integration.errorLogger
2018-09-03 14:49:39 INFO  [main] o.s.c.s.DefaultLifecycleProcessor - Stopping beans in phase -2147483648

Spring Launcher class
public static void main(String [] args)  throws Exception{
        logger.info("Starting Regression Data Reset Batch job......");
        SpringApplication app = new SpringApplication(ResetRegressionDataBatchJob.class);
        app.setWebEnvironment(false);
        app.setBannerMode(Banner.Mode.OFF);
        ExitStatus exitStatus = app.run(args).getBean("resetRegressionDataBatchJob", ResetRegressionDataBatchJob.class).run(args);
        logger.info("ResetRegressionDataBatchJob exiting with status of "+exitStatus);
        if (!ExitStatus.COMPLETED.equals(exitStatus) && !ExitStatus.NOOP.equals(exitStatus))
            System.exit(-1);

    }

I've updated the logs after adding System.exit(0) and ctx.stop(). The context.stop() is not closing all the components as System.exit(0) does. The thread was still running when I used ctx.stop()

A: When you use Spring Integration, it creates several active components as infrastructure beans to support other beans in the application context. One of them is ThreadPoolTaskExecutor.
To properly shutdown the application context with active components you need to use an ConfigurableApplicationContext.close():
/**
 * Close this application context, releasing all resources and locks that the
 * implementation might hold. This includes destroying all cached singleton beans.
 *
Note: Does not invoke {@code close} on a parent context;
 * parent contexts have their own, independent lifecycle.
 *
This method can be called multiple times without side effects: Subsequent
 * {@code close} calls on an already closed context will be ignored.
 */
@Override
void close();

The stop() doesn't deactivate active components, but only stop currently in progress tasks and doesn't allow to start new until the start() back of the application context or that active component.


text:
Q: Change MagicMock return_value instance method callable to PropertyMock I'm trying to change the callable for an instance method on my MagicMock to a PropertyMock as that is how it is accessed (Django model column). But test fails with
 _mock_self = <PropertyMock name='get().my_prop' id='4524632776'>

Given the following code
# view
def get(self request):
    # stuff...
    obj = MyModel.objects.get(id=2)
    # more stuff...
    print(obj.my_prop)
    some_val = MyOtherModel(my_prop=obj.my_prop)

# tests
def test_my_test(mocker):
    other_obj = mocker.patch("app.views.MyOtherModel")
    obj_get = mocker.patch("app.views.MyModel.objects.get")
    obj_prop = mocker.PropertyMock(return_value=1)
    # This should translate to an instance of MyModel i.e. MyModel().my_prop
    obj_get.return_value.my_prop = obj_prop

    # run view

    obj_prop.assert_called_once() # Says never invoked
    # Failed as my_prop was a PropertyMock instead of actual value
    other_obj.assert_called_once_with(my_prop=obj_prop)

The print statement shows
 <PropertyMock name='get().my_prop' id='4524632776'>

So it appears it is the same instance it just is not actually being invoked
I also had attempted directly patching the property off the model but that does not appear to work as the Mocks are not the same.
def test_my_test(mocker):
    other_obj = mocker.patch("app.views.MyOtherModel")
    obj_prop = mocker.patch("app.views.MyModel.my_prop", new_callable=mocker.PropertyMock)
    obj_get = mocker.patch("app.views.MyModel.objects.get")
    obj_get.return_value.my_prop = obj_prop

    # run view
    obj_prop.assert_called_once()
    # Failed as my_prop was a PropertyMock instead of actual value
    other_obj.assert_called_once_with(my_prop=obj_prop)

Which fails with...
_mock_self = <PropertyMock name='my_prop' id='4543022192'>

but prints
 <MagicMock name='get().my_prop' id='4543752232'>

EDIT Added in other patches that more accurately depicted the implementation

A: Overwriting the desired property with a PropertyMock was unnecessary as I could simply assigned the value I wanted to the MagicMock.
def test_my_test(mocker):

    other_obj = mocker.patch("app.views.MyOtherModel")

    obj_get = mocker.patch("app.views.MyModel.objects.get")
    obj_get.return_value.my_prop = 2

    # run view
    other_obj.assert_called_once_with(my_prop=obj_get.return_value.my_prop)

The .assert_called_once was used to check if the attribute was ever invoked and was added when an .assert_called_once_with originally failed.


text:
Q: JavaScript to get all sites i'm follwing? I'm looking for a way to get all the sites I'm following by using JavaScript. What's the best way to do this?

A: You can use REST API to get the followed sites.
Below is the REST endpoint
GET http://<siteCollection>/<site>/_api/social.following/my/followedsitesuri

you can get more details on below MSDN link
https://msdn.microsoft.com/en-us/library/dn194080.aspx

A: This can be achieved using JSOM as well.
function getAllFavorites() {
        var clientContext = SP.ClientContext.get_current();
        var followingManager = new
              SP.Social.SocialFollowingManager(clientContext);
        var documents = new SP.Social.SocialActorInfo();
        documents = followingManager.getFollowed(15);

       /*15 is to get users, documents, sites and tags that the logged
        in user is following. For more details
        https://msdn.microsoft.com/en-us/library/office/jj667835.aspx */

        var actorTypes = ['User', 'Document', 'Site', 'Tag'];

        clientContext.executeQueryAsync(function() {
           documents.forEach(function (doc, i) {
                    var item = {};
                    item.Name = doc.get_name();
                    item.actorType = actorTypes[doc.get_actorType()];
                    item.url = doc.get_uri();
                    $scope.favorites.push(item);
                });
        }, function(sender, args) {
            alert("Error: " + args.get_message());
        });
    }

SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function () {
            SP.SOD.executeFunc('userprofile',
'SP.Social.SocialFollowingManager', function () {
   getAllFavorites();

/*This is to make sure the methods SP.ClientContext and
SP.Social.SocialFollowingManager are loaded for the method
to work */

});
});


text:
Q: queue and flow control with delphi using indy i have a client server application (TCP) that's designed with indy delphi.
i want to have a queue and flow control in my server side application.
my server should not lose any clients data when server traffic is full.
for example , in my server side application i want determine maximum of bandwidth for server is 10Mbps and then if server bandwidth (this 10Mbps) was full the other clients be on queue until bandwidth get free .
so i want to know how can i design this with delphi ?
thanks
best regard

A: The client should not send the message directly to the server. Put the message in a local store (f.i. sqlite-db) and in a thread you read the first message from the local store and try to send it to the server.
If the message was delivered to the server (no exception raised) delete the message from the local store and process the next "first" message in the local store.

A: Within the TIdTCPServer.OnExecute method which receives the client data, it is possible to 'delay' processing of the incoming request with a simple Sleep command. The client data will stay in the TCP socket until the Sleep command finished.
If your server keeps track of the current 'global' bandwidth usage for all clients, it is possible to set the Sleep time dynamically. You could even set different priorities for different clients.
So you would need a simple but thread safe bandwidth usage monitor, an algorithm which calculates sensible Sleep time values, and a way to assign this Sleep time to the individual client connection contexts.
See also:

*

*https://en.wikipedia.org/wiki/Token_bucket

*https://github.com/bandwidth-throttle/token-bucket for an example implementation in PHP

*http://www.nurkiewicz.com/2011/03/tenfold-increase-in-server-throughput.html


text:
Q: Xcode gives 3 syntax errors dealing with Stray '\342' in program I am working on a simple project in Objective-C in Xcode and I'm getting some stray/ errors about the following line of code:
if(celsius < −273.15) {
        NSLog(@"It is impossible to convert temperatures less than −273.15 degrees Celsius, because this is absolute zero, the coldest possible temperature.");
    }

It's actually only about the first line, but I wanted to give some context.
Any suggestions?
I've looked it up here on SO, but everyone else's error hasn't had such simple code like mine, although it appears they have a common problem of having the wrong encoding for certain punctuation, perhaps?
It's got to be just some syntax this on my if statement..
UPDATE:
It looks as though it also displays 2 other stray errors:
Stray '\210'
Stray '\222'

A: − != -
Your minus, isn't a minus.

A: Make sure that your " characters are straight up and down (and not of the left/right slanted variety).


text: Q: Can we change the UI of call kit package in flutter Can we change the UI of the callkit package in a flutter, I want to show a full-screen notification screen for that I am using thecall kit package of flutter, so I have to remove those answer and reject buttons.


text:
Q: Using Firebase auth as provider in custom backend Is there a way to add firebase auth as provider to my custom backend? For my custom backend I am using directus. Directus offers to add auth providers that supports oAuth 2.0 and openID Connect (docs). But I do not know if firebase auth can be used as an oAuth provider, I did not find about it in the firebase docs.
I am using flutter for the frontend part

A: Firebase does not expose OAuth tokens for its user, so you won't be able to use that integration directly. If you're allowing your users to sign in to Firebase with a social provider (Google, Facebook, etc), you can also pass that token to directus, instead of (or in addition to) signing in to Firebase with it.
Otherwise you can take the ID token that Firebase creates for the user, and verify that in your backend code. You won't be using directus' sign-in functionality in that case though.
I also recommend reading: Demystifying Firebase Auth Tokens for an explanation of Firebase's token types.


text:
Q: Read file byte by byte using C I am trying to read a file byte by byte then print it out using C, but the output doesn't match the display of the hex editor.
In hex editor the first 2 lines look like this:
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0111 1111 1000 0000 0000

expected output:
00000000000000000000000000000000
00000000000001111111100000000000

but when my code outputs this:
00000000000000000000001111111100
00000000000000000000000000000000

here's my code:
#include <stdio.h>
#include <string.h>

int main() {
    FILE *fp;
    unsigned char buffer[4900] = "";
    int y;

    y = 0;
    fp = fopen("tugasz.ksa", "rb");

    for (int x = 0; x < 4900; x++) {
        fread(buffer, 1, 4900, fp);
        printf("%x", buffer[x]);
    }
    return (0);
}

A: There a multiple problems in your code:

*

*You do not test for fopen failure, causing undefined behavior if the file does not exist or cannot be open.

*You are not reading the file byte by byte, instead you are reading blocks of 4900 bytes and just print one byte of each block.

*You probably hit the end of file very quickly, but you do not test for end of file, so the output may come from the same part of the file. A classic case of one bug hiding another bug.

*The conversion format %x outputs 1 or 2 characters per byte depending on the byte value. This is a problem is the file contents are 0x00, 0x01, 0x10 and 0x11, which respectively produce 0, 1, 10 and 11, hence the apparent misaligned input.

*For cleanliness, you should fclose the stream.

*From the data posted, it is unclear if the hex editor is displaying data in hexadecimal or binary format and whether the values are word based or byte based.

Here is a simpler approach:
#include <stdio.h>

int main() {
    FILE *fp;
    int c, i, max;

    fp = fopen("tugasz.ksa", "rb");
    if (fp == NULL) {
        fprintf(stderr, "cannot open input file\n");
        return 1;
    }
    for (i = 0, max = 4900; i < max && (c = getc(fp)) != EOF; i++) {
        printf("%02x", c);
        if (i % 16 == 15)
            putchar('\n');  // 16 bytes per line
        else if (i % 2 == 1)
            putchar(' ');   // group bytes in pairs
    }
    if (i % 16 != 0)
        putchar('\n');  // output a newline if needed

    fclose(fp);
    return 0;
}

A:
for(int x = 0; x<4900; x++) {
   fread(buffer, 1, 4900, fp);
   printf("%x", buffer[x]);
}

In the first iteration of the loop, this will print only the first character in buffer at index 0.
In the second iteration, this will print the the second character in buffer at index 1.
So if your file is less than 4900 bytes, it prints only 1 character. The reason you get more output is because the loop doesn't break when you reach end of file. It's printing mostly garbage, not the actual file content.
Given the hex-decimal view of your input file, and the expectation that the output is all 0 and 1, it is unlikely that the source file is a collection of bytes consisting of 0 and 1. Instead, it likely contains bytes from 0 to 256, and each byte is a collection of 0 and 1 bits. Print it as follows:
int main(void)
{
    FILE *fp = fopen("tugasz.ksa", "rb");
    if(fp)
    {
        unsigned char buffer[4096];
        size_t sz;
        int line = 0;
        while ((sz = fread(buffer, 1, sizeof(buffer), fp)) > 0)
        {
            for(int i = 0; i < sz; i++)
            {
                //print the bits of the byte, at buffer[i]:
                for(int j = 0; j < 8; j++)
                {
                    int mask = 1 << (7 - j);
                    int bit = buffer[i] & mask;
                    printf("%d", bit ? 1 : 0);
                }

                //add new line for every 4 byte
                line++;
                if((line % 4) == 0)
                    printf("\n");
            }
        }
    }

    return 0;
}

If bytes are 0 and 1, then simply print it as printf("%d", buffer[i]) or printf("%02X", buffer[i]) for byte values:
int main(void)
{
    FILE *fp = fopen("tugasz.ksa", "rb");
    if(fp)
    {
        unsigned char buffer[4096];
        size_t sz;
        while((sz = fread(buffer, 1, sizeof(buffer), fp)) > 0)
        {
            for(int i = 0; i < sz; i++)
                printf("%d", buffer[i]);
                //or use "%02X" instead, for printing the byte values:
                //printf("%02X ", buffer[i]);
        }
    }
    return 0;
}


text:
Q: Specifying Security Group for EB Load Balancer I spent quite some time finding out that I need to modify the Security Group if I want to enable HTTPS on Elastic Beanstalk. I mean on the frontend, not on the EC2 instance. This is nowhere mentioned in Amazon's documentation. They have this nice switch where you can enable HTTPS and specify the port, but in addition I needed to go to the EC2 console -> Security Groups and find out which Security Group is used by which Load Balancer, and which Load Balancer is used by which EB environment.
Is there a way to specify the Security Group for an Elastic Beanstalk environment? If not, will the load balancer "survive" a rebuilding of the environment or will I need to repeat configuring the ports if the environment is rebuilt?
What's your best practice?
Thanks!

A: To find the name of the security group used in Elastic Load Balancer:
AWS console > Network & Security > Load Balancers

To change the rules for the Elastic Load Balancer you can either create a new security group and then add it to the Load Balancer, or update an existing security group.
To change the security group for Elastic Beanstalk instances:
AWS console > Elastic Beanstalk > Pick environment > Instances > EC2 Security Groups

The field contains the names of the security groups (comma separated) that define firewall access to the launched EC2 instances. It will "survive" a rebuilding. If under "rebuilding" you mean code redeployment. If you stop/terminate Elastic Beanstalk environment, the settings will be lost, unless you create a snapshot.
Update
There's a way to configure Elastic Load Balancer to "survive" a rebuilding. You need to configure your own Elastic Load Balancer -
Customizing Environment Resources
The document has a code snippet for ElastiCache configuration, you can use it as an example to create Elastic Load Balancer resource.
Also, I found a gist with Elastic Load Balancer configuration, although I cannot confirm whether it is a working example or not.
Hope it helps.


text:
Q: autocompletion without dialog Does the prompt-toolkit module supports autocompletion without displaying a dialog box (using tab to autocomplete)? I find the dialog box a bit bulky and overkill when there are a fairly large number of options to autocomplete with.
A-la bash-shell or comparable, using either prompt() or session.prompt()?

Thank you for looking.

A: from prompt_toolkit.shortcuts import CompleteStyle
[...]
session = PromptSession(lexer=PygmentsLexer(...), completer=commands, complete_while_typing=True, complete_style=CompleteStyle.READLINE_LIKE)