text:
Q: SQL Server 2005 Lock Pages in Memory on 32-bit system On a 32-bit Windows Server 2003 Standard Edition SP2, I'm debating the pros and cons of /3gb + AWE + Locked Pages for SQL Server 2005 Standard SP3 CU4.
The system only has 4GB of physical memory, however the developer's IIS service seems to be causing high page-outs for SQL Server.
The solution must be limited to existing hardware and software limitations. (32-bit OS, 32-bit SQL Server, 4GB of physical RAM).  The second challenge is that the server is not domain joined so using local workstation credentials to limit LPIM's scope (A highly recommended configurable option for LPIM) may affect application communication between physical servers.
Thanks to @PaulWhiteNZ's response on #sqlhelp there is some empirical data on the topic.

A: Sorry, if SQL Server and IIS are fighting over memory you need a separate server. Which is always good thing anyway: IIS and SQL Server have different resource requirements and usage patterns.
If you lock memory you'll just make things worse for IIS.


text:
Q: Does TryExecuteTask(task) always block? I'm writing a FIFO queued thread-limited task scheduler.
Does a call to TaskScheduler.TryExecuteTask(task) always block while task is executing?  Testing so far indicates that this is the case, however I can't find this documented anywhere.
Is there ever any reason to call task.Wait() following the above call?  Doing this results in an AggregateException if the task ends in a Faulted state.

A: A call to TryExecuteTask will always block, it runs the task you are providing it on the scheduler on which you are calling the function and returns if the Task has finished successfully.
If you want the task to run in a different thread: on this page there is an example on how to use QueueUserWorkItem to inform the ThreadPool that there's work to be executed. When you call the TryExecuteTask inside there, an available thread will pick it up and executes the task.
task.Wait() is generally used when passing the task to a scheduler to block until the task has completed. Since you are not executing your task in a different thread, the code blocks anyway and calling task.Wait() would be redundant.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Arch linux: set copy/paste/cut shortcuts I would like to set custom keyboard shortcuts for using clipboard. I would like to change it from:

Copy: ctrl + c in programs, ctrl + shift + c in terminal
Paste: ctrl + v in programs, ctrl + shift + v in terminal
Cut: ctrl + x in programs, does not work properly in terminal

To:

Copy: Win + c everywhere
Paste: Win + v everywhere
Cut: Win + x  everywhere

How can I achive this ?
Thank you for your help
PS: I am using: Arch linux, xserver, i3wm, xclip, alacritty

A: Note that bindsym is for associate a key with a command and that $mod is a variable that storages your picked special key (you had to choose between Ctrl and Super).
We don't say Win on Linux, but Super. Its the same key by the way.
So, let we go:

*

*Be sure you have installed wl-clipboard, it works on wayland (which is the default server for i3).
In Arch Linux you can asure its installation with this command:

sudo pacman -S wl-clipboard --needed -y

*Lets edit the i3 config file, default at ~/.config/i3/config

*Add the following lines, for both copy and paste¹:

bindsym $mod+c exec wl-copy
bindsym $mod+v exec wl-paste

*Save it

About the 'cut' function: maybe you could do something like
bindsym $mod+x exec wl-copy ERASE
where erase may be a function which deletes the choosed text after its copying. Of course that last one DOES NOT WORK as it is! We need to think in a way to replace 'ERASE'.
EDIT:
¹ The combo $mod+v is used by default to split vertically, i recommend to use paste with $mode+p or something else.


text:
Q: How do you turn off the repetitive coach in Madden? How do you completely shut off the in game commentary? I'm sick of intercepting the ball and hearing "You're in the shotgun here so use the extra time". I turned off the sound, but I like the crowd/field noise.

A: You can turn off the coordinator through "Game Options" --> "Coordinator Audio" and turn off the announcer through "Volume Control" --> "In-Game Commentary"


text:
Q: Arduino/C++ adjusting Long Millis () in loop So I have made a simple Arduino circuit for practice. I am able to start and stop the loop at any moment via a button. Now I want to make some sick led light sequences.
My initial thought is changing the delay_led1 function at the end of the loop. That way I am able to change the sequence when the loop ends.
I tried to do this with: interval_led1 + 300 (marked in my code with alot of /////////) at the end of the loop, but this doens't work.
How could I add milliseconds to the interval_led1 function via the loop?
const int led1 = 13;
const int led2 = 8;
const int led3 = 5;
const int button = 10;

int ledState_led1 = LOW;             // ledState used to set the LED
int ledState_led2 = LOW;
int ledState_led3 = LOW;

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis_led1 = 0;        // will store last time LED was updated
unsigned long previousMillis_led2 = 0;
unsigned long previousMillis_led3 = 0;

long interval_led1 = 500;           // interval at which to blink (milliseconds)
long interval_led2 = 600;
long interval_led3 = 700;

boolean buttonstate = false;

void setup() {

    pinMode(led1, OUTPUT);
    pinMode(led2, OUTPUT);
    pinMode(led3, OUTPUT);
    pinMode(button, INPUT);
}

void loop() {
    // check to see if it's time to blink the LED; that is, if the difference
    // between the current time and last time you blinked the LED is bigger than
    // the interval at which you want to blink the LED.
    unsigned long currentMillis_led1 = millis();
    unsigned long currentMillis_led2 = millis();
    unsigned long currentMillis_led3 = millis();

    bool current_state = digitalRead(button);
    bool prev_buttonstate= false;

    if(current_state==HIGH && current_state != prev_buttonstate) {
        buttonstate = !buttonstate;    //reverse buttonstate value
    }
    prev_buttonstate = current_state;

    if(buttonstate==true)
        if (currentMillis_led1 - previousMillis_led1 >= interval_led1) {
            previousMillis_led1 = currentMillis_led1;
            if (ledState_led1 == LOW) {
                ledState_led1 = HIGH;
            } else {
                ledState_led1 = LOW;
            }
            digitalWrite(led1, ledState_led1);
            ////////interval_led1 + int(3000); ///////////////////
        }

    if(buttonstate==true)
        if (currentMillis_led2 - previousMillis_led2 >= interval_led2) {
            previousMillis_led2 = currentMillis_led2;
            if (ledState_led2 == LOW) {
                ledState_led2 = HIGH;
            } else {
                ledState_led2 = LOW;
            }
            digitalWrite(led2, ledState_led2);
        }

    if(buttonstate==true)
        if (currentMillis_led3 - previousMillis_led3 >= interval_led3) {
            previousMillis_led3 = currentMillis_led3;
            if (ledState_led3 == LOW) {
                ledState_led3 = HIGH;
            } else {
                ledState_led3 = LOW;
            }
            digitalWrite(led3, ledState_led3);
        }
}

A: Did you mean to have:
Interval_led = interval_led1 + 3000;
Where you actually assign a new value to that variable?


text:
Q: @Html.Action and Controllers with same name While creating a Plugin for a MVC site, I'm facing an issue about controller resolution.
Here are all the routes that concern the current context :
routes.MapRoute("Route1",
    "Admin/Product/{action}/{id}",
    new { controller = "Product", action = "Index", area = "Admin", id = UrlParameter.Optional },
    new[] { "Plugin.Controllers" }
)

routes.MapRoute(
    "Admin_default",
    "Admin/{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", area = "Admin", id = "" },
    new[] { "Admin.Controllers" }
);

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new[] { "Public.Controllers" }
);

There are 3 ProductController classes in the entire solution :

*

*Plugin.Controllers.ProductController (inherits from the Admin one)

*Admin.Controllers.ProductController

*Public.Controllers.ProductController

In my view "/Views/Home/Index.cshtml" (i.e. the "Index" action of the HomeController without any area) I have the following code :
@Html.Action("HomepageProducts", "Product")

It refers to the action "HomepageProducts" of the Public.Controllers.ProductController.
MVC looks for the plugin controller instead of the public one and throws the following exception :

[HttpException (0x80004005): A public action method 'HomepageProducts' was not found on controller 'Plugin.Controllers.ProductController'.]
     System.Web.Mvc.Controller.HandleUnknownAction(String actionName) +291
     System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +31
     System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
     System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
     System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
     System.Web.Mvc.Controller.b__15(IAsyncResult asyncResult, Controller controller) +12
     System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22
     System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
     System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
     System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
     System.Web.Mvc.MvcHandler.b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
     System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
     System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
     System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
     System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
     System.Web.Mvc.<>c__DisplayClassa.b__9() +22
     System.Web.Mvc.<>c__DisplayClass4.b__3() +10
     System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +27
[HttpException (0x80004005): Execution of the child request failed. Please examine the InnerException for more information.]
     System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +102
     System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Action action) +64
     System.Web.Mvc.ServerExecuteHttpHandlerAsyncWrapper.EndProcessRequest(IAsyncResult result) +71
     System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1436
[HttpException (0x80004005): Erreur d'exécution de la demande enfant pour le gestionnaire 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.]
     System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +3428452
     System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +76
     System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +29
     System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +24
     System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +464
     System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) +83
     System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName) +10
     ASP._Page_Views_Home_Index_cshtml.Execute() in c:\Path\To\My\Project\Views\Home\Index.cshtml:14

If this helps, the solution use Autofac.MVC5...
Any help/comment/idea is welcome.
Am I missing something or only the routes are implied in controllers resolution ?
UPDATE
When browsing the "Admin" area all actions are well performed, the plugin and the admin controllers works fine.
If I comment the plugin route, the error is not thrown anymore. Of course my plugin controller is not called anymore.
// routes.MapRoute("Route1",
//     "Admin/Product/{action}/{id}",
//     new { controller = "Product", action = "Index", area = "Admin", id = UrlParameter.Optional },
//     new[] { "Plugin.Controllers" }
// )

So I guess the issue is due to the plugin route, the plugin controller itself or the way the route is resolved by MVC ?
UPDATE 2
I tried to uncomment all my routes and specify area in @Html.Action() as follow:
@Html.Action("HomepageProducts", "Product", new { area = "" })

But MVC ignore the area and try to load the Plugin controller...

[HttpException (0x80004005): A public action method 'HomepageProducts' was not found on controller 'Plugin.Controllers.ProductController'.]

A: I'm definitely sure I miss something but I bypass my issue by register each Plugin.ProductController action routes I've overridden from the Admin one.
routes.MapRoute("Route1",
    "Admin/Product/{action}/{id}",
    new { controller = "Product", action = "Index", area = "Admin", id = UrlParameter.Optional },
    new[] { "Plugin.Controllers" }
)

//...becomes...

routes.MapRoute("Product.Action1",
    "Admin/Product/Action1/{id}",
    new { controller = "Product", action = "Action1", area = "Admin", id = UrlParameter.Optional },
    new[] { "Plugin.Controllers" }
)

routes.MapRoute("Product.Action2",
    "Admin/Product/Action2/{id}",
    new { controller = "Product", action = "Action2", area = "Admin", id = UrlParameter.Optional },
    new[] { "Plugin.Controllers" }
)

//...

All works fine now. With this, I'm able to derive controllers.


text:
Q: Updating tableview view for a chat application I'm implementing real time chat in my app using firebase and and if the keyboard is shown and the user sends me 10 messages in a row, his messages will eventually start hiding behind my keyboard or go out below the tableview view (if the keyboard isn't shown).  I believe this has to do with adjusting the view to adjust to the number of rows within the tableview. Ultimately, I need the latest cell to be right above the textfield (whether the keyboard is shown or not) every time I send a message or receive the latest message.  Any tips?  I took a look at firechat on github and they don't seem to have any code for this: https://github.com/firebase/firechat-ios/blob/master/Firechat/ViewController.m
- (void)viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter]
    addObserver:self selector:@selector(keyboardWillShow:)
    name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(keyboardWillHide:)
     name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification*)notification
{
    [self moveView:[notification userInfo] up:YES];
}

- (void)keyboardWillHide:(NSNotification*)notification
{
    [self moveView:[notification userInfo] up:NO];
}

- (void)moveView:(NSDictionary*)userInfo up:(BOOL)up
{
    CGRect keyboardEndFrame;
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]
     getValue:&keyboardEndFrame];

    UIViewAnimationCurve animationCurve;
    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey]
     getValue:&animationCurve];

    NSTimeInterval animationDuration;
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]
     getValue:&animationDuration];

    // Get the correct keyboard size to we slide the right amount.
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];

    CGRect keyboardFrame = [self.view convertRect:keyboardEndFrame toView:nil];
    int y = keyboardFrame.size.height * (up ? -1 : 1);
    self.view.frame = CGRectOffset(self.view.frame, 0, y);

    [UIView commitAnimations];
}


text:
Q: I want sum of first three count in range "c5:k5" if count is greater than 0 what should i do?
I want sum of the first three counts in the range "c5:k5" if the count is greater than 0 what should i do?

A: If one has Office 365:
=SUM(INDEX(FILTER(C5:K5,C5:K5>0),0,{1,2,3}))

If not:
=SUMPRODUCT(INDEX(C5:K5,N(IF({1},AGGREGATE(15,7,(COLUMN(C5:K5)-MIN(COLUMN(C5:K5))+1)/(C5:K5>0),{1,2,3})))))


text:
Q: Force npm test to make fresh\new copy of input test/
├── TestOne.js
└── TestTwo.js

Say, TestOne.js is :
This test case reads from file InputOne.json and add one record to the object which already has 3 records.
describe('Add Items', function () {
      it('Should add items', function () {
       var input = require('./data/InputOne');
       var obj = new Department();
       var result = obj.AddDept(input);
       result.should.have.length(4);
      });
   });

Say, TestTwo.js is :
This test case reads from file InputOne.json and count the no of elements
describe('Count Items', function () {
      it('Should count items length', function () {
       var input = require('./data/InputOne');
       var obj = new Department();
       var result = obj.CountDept(input);
       result.should.have.length(3);
      });
   });

Problem:
Both the test cases uses same file as input. If I run test cases using mocha both the test cases passes
mocha TestOne   // Passes
mocha TestTwo   // Passes
if I say npm test (which runs all the test cases) I get error as test case in TestOne file has modified the input file. How I can make test case not to cache input file (or force test case to create its own copy of input file)

A: To ensure the file is always loaded in its current form from disk, load it with fs:
var fs = require('fs');

var input = fs.readFileSync('./data/InputOne');
input = JSON.parse(input);

http://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_options


text:
Q: Rails - will paginate not displaying pages correctly Have been following the wiki from the git page but unable to see the problem I am having.
will_paginate is showing the first 10 of the landlords correctly but will not render the next page correctly, the first page 'sticks' no matter which page I visit.
I have tried other threads with the similar issue but did not yield the correct result.
Question: What am I doing wrong? I have copied what I think is the key code to my issue.
I have a landlord class and in that class I have these lines ...
model..
class landlord

 self.per_page = 10
 default_scope order: 'landlords.name ASC'

controller..
class Landlords_controller
 def index
   @landlords = Landlord.paginate(page: params[:landlord]).search(params[:search])
 end

and the view ...
landlords/index.html.erb
 <% @landlords.each ..... %>

 <% end %>

 <%= will_paginate @landlords %>

A: Incorrect symbol in :
@landlords = Landlord.paginate(page: params[:landlord]).search(params[:search])

should be
@landlords = Landlord.paginate(page: params[:page]).search(params[:search])

I love mondays!

A: Or, use:
<%= will_paginate @landlords, param_name: 'landlord' %>

This is useful if you have more than one will_paginate on a page, if not, use the default 'page'


text:
Q: How to add transition to dropdown menu from W3 I'm trying to make a dropdown menu with transition based on the example from W3.  I have it working as a dropdown menu, but can't seem to add the transition.  I want the dropdown to ease in.
I have tried adding transition: all 0.3s; to the .dropdown-content class. I've also researched many other dropdown examples, but none have led to the answer.

function myFunction() {
  var x = document.getElementById("myTopnav");
  if (x.className === "topnav") {
    x.className += " responsive";
  } else {
    x.className = "topnav";
  }
}
.dropbtn:hover {
  transform: scale(1.02);
  color: gray !important;
  transition: all 0.5s ease;
}

.topnav a:hover {
  transform: scale(1.02);
  color: gray;
}

@media screen and (min-width: 769px) {
  .topnav {
    overflow: hidden;
    margin-top: 3em;
    padding-top: 0.5em;
    display: inline;
    float: left;
    margin-right: 3.5%;
    margin-left: 0;
    margin-right: 0;
    float: right;
    text-align: right;
    clear: right;
    margin-top: 3em;
    padding-top: 1em;
    padding-bottom: 0.5em;
  }
  .topnav a {
    float: left;
    padding-bottom: 2em;
  }
  .dropdown:hover .dropdown-content {
    display: flex;
    border-bottom: 2px solid #d51045;
    border-top: 2px solid #d51045;
  }
}

@media screen and (max-width: 769px) {
  .topnav {
    position: relative;
    padding-bottom: 1em;
    padding-top: 1em;
  }
  .topnav .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .topnav a {
    float: none;
    display: block;
    text-align: center;
  }
  .topnav .dropdown {
    float: none;
  }
  .topnav .dropdown-content {
    position: relative;
    float: none;
    text-align: center;
  }
  .topnav .dropdown .dropbtn {
    display: block;
    width: 100%;
    text-align: center;
  }
  .dropdown-content a {
    float: none !important;
    text-align: center !important;
  }
  .dropdown:hover .dropdown-content {
    display: block;
  }
}

.topnav a {
  display: block;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  text-transform: uppercase;
  font-weight: 600;
  font-size: 14px;
  color: #444444;
}

.topnav .icon {
  display: none;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  border: none;
  outline: none;
  padding: 14px 16px;
  background-color: white;
  font-family: inherit;
  margin: 0;
  text-transform: uppercase;
  font-weight: 600;
  font-size: 14px;
  color: #444444;
  transition: color .2s ease-in;
}

.dropdown-content {
  display: none;
  /*box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);*/
  z-index: 1;
  background-color: white;
  position: fixed;
  top: auto;
  right: 0;
  width: 100%;
  border-bottom: 2px solid #d51045;
  border-top: 2px solid #d51045;
}

.dropdown-content a {
  float: right;
  padding: 20px 23px;
  text-decoration: none;
  display: block;
  text-align: left;
  margin: 0 auto;
}

body.home .site-header .container {
  padding-bottom: 1em;
}

img.nav-img {
  display: block;
  margin-left: auto;
  margin-right: auto;
}

   Calendar

    <button class="dropbtn"> About

             </button>

      Musicians
      More

    <button class="dropbtn"> Tickets

        </button>

      Series Subscriptions
      More

    <button class="dropbtn"> Community

        </button>

      Learning Programs

    <button class="dropbtn"> Visit

        </button>

      Seating Charts
      Frequently Asked Questions

    <button class="dropbtn">Give

        </button>

      Ways to Give
      More

  Shop
  ☰

I expect the dropdown to have a smooth transition, similar to the laphil.org menu.

A: The problem is in the CSS display property. You want to animate dropdown appearance but you can't do it with display. Instead I suggest you to use visibility and opacity.
.dropdown-content {
  display: flex;
  visibility: hidden;
  opacity: 0;
}

.dropdown:hover .dropdown-content {
  /*display: flex;*/
  visibility: visible;
  opacity: 1;
  transition: all 0.3s linear;
}


text:
Q: Why am I getting the addresses of the array instead of the values (two-dimensional array)
  5 import java.util.*;
  6
  7 class Matrix {
  8     // declare the member field
  9     private int[][] matrix;
 10
 12     public Matrix(int a, int b, int c, int d) {
 13         matrix = new int[2][2];
 14         matrix[0][0] = a;
 15         matrix[0][1] = b;
 16         matrix[1][0] = c;
 17         matrix[1][1] = d;
 18     }
 19     // identity matrix
 20     public Matrix(char i) {
 21         matrix = new int[2][2];
 22         matrix[0][0] = 1;
 23         matrix[0][1] = 0;
 24         matrix[1][0] = 1;
 25         matrix[1][1] = 0;
 26     }
 27
 29     public int[][] toPow(int n, int[][] matrix) {
 30         if (n == 1)
 31             return matrix;
 32         else {
 33             int[][] temp = matrix;
 34             for (int i = 0; i < 2; i++) {
 35                 for (int j = 0; j < 2; j++) {
 36                     temp[i][j] += matrix[i][j] * this.matrix[j][i];
 37                 }
 38             }
 39             return toPow(n - 1, temp);
 40         }
 41     }
 42     public int[][] toPow(int n) {
 43         return toPow(n, this.matrix);
 44     }
 45 }
 46
 47 class Maths {
 48
 49     public static void main(String[] args) {
 55         Matrix m = new Matrix(1,2,3,4);
 56         System.out.println(Arrays.toString(m.toPow(2)));
 57         System.out.println(Arrays.toString(new int[][] {{1,2},{3,4}}));
 58     }
 59 }

Arrays.toString(Array) should be printing out the contents of the array when called. But when I tried to print the array in the last 2 lines of the code, I get the addresses instead of the content. Can anyone please help me understand why that is?

A: You're seeing the results of calling toString() on each element of your top array. But each element is itself an array. Use Arrays.deepToString() instead:
System.out.println(Arrays.deepToString(m.toPow(2)));

A: Arrays.toString() only works for one-dimensional arrays. Try iterating over the rows of the array and using Arrays.toString() on each row separately.

A: Arrays.toString (int[]) supports array (one-dimension), not matrices (two + dimension)

A: You can call Arrays.toString() for each line of the matrix or Arrays.deepToString().
import java.util.Arrays;

public class Test {

   public static void main(String[] args) {
       new Test().run();
    }

    private void run() {
       int[] v = { 1, 2, 3 };
       int[][] m = { { 1, 1, 1 }, { 2, 2, 2 }, { 3, 3, 3 } };
       System.out.println("Printing the array: ");
       System.out.println(Arrays.toString(v));
       System.out.println("Printing the line addresses: ");
       System.out.println(Arrays.toString(m));

       System.out.println("Priting the matrix: ");
       for (int[] l : m) {
          System.out.println(Arrays.toString(l));
        }

        System.out.println("Priting the matrix (deepToString): ");
        System.out.println(Arrays.deepToString(m));
   }
}

Output:
Printing the array:
[1, 2, 3]
Printing the line addresses:
[[I@3182f0db, [I@b92d342, [I@546b97fd]
Priting the matrix:
[1, 1, 1]
[2, 2, 2]
[3, 3, 3]
Priting the matrix (deepToString):
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]


text:
Q: Prevent overlapping range values on a slider (noUiSlider) I have a set of 3 ranges on a slider consisting of 30 days and beyond (see CodePen). At the moment, the values between the 3 ranges overlap by one day.
var slider = document.getElementById("slider");
var unconstrainedValues = document.getElementById("unconstrained-values");

noUiSlider.create(slider, {
    start: [0, 7],
    padding: [0, 1],
    connect: [true, true, true],
    range: {
        min: 0,
        max: 31
    },
    pips: {
        mode: "values",
        values: [0, 7, 14, 21, 28, 30],
        density: 3
    },
    step: 1,
    range: {
        min: [0],
        max: [31]
    },
    format: wNumb({
        // https://refreshless.com/wnumb/
        decimals: 0,
        mark: ".",
        thousad: ",",
        prefix: ""
        // suffix: ' p.p.'
    }),
    tooltips: true
});

var nodes = [
    document.getElementById("daily-rate-a"), // 0
    document.getElementById("daily-rate-b"), // 0
    document.getElementById("daily-rate-c") // 0
];

slider.noUiSlider.on("update", function (
    values,
    handle,
    unencoded,
    isTap,
    positions
) {
    nodes[handle].innerHTML = values[handle];
});

// var tooltips = document.querySelectorAll('.noUi-tooltip');
// console.log(tooltips);
// tooltips.forEach(tooltip => tooltip.classList.add('tooltips-active'));

var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var input3 = document.getElementById("input3");
var inputs = document.querySelectorAll(".form-control");

var connect = slider.querySelectorAll(".noUi-connect");
var classes = ["c-1-color", "c-2-color", "c-3-color"];

for (var i = 0; i < connect.length; i++) {
    connect[i].classList.add(classes[i]);
}

slider.noUiSlider.on("update", function (values) {
    unconstrainedValues.innerHTML = values.join(" - ");
});

Current result:

*

*0-15

*15-20

*20-Infinity

Desired result:

*

*0-15

*16-20

*21-Infinity

Essentially, the start of the next range should never be the same value as the end of the previous range. (Both 0 in Range A and Infinity in Range C are static and never change.) How do I accomplish this?

A: Use margin option while creating
margin: 1

noUiSlider.create(slider, {
    start: [0, 7],
    ...
    margin: 1 // Newly added
    ...
    tooltips: true
});

Range 3 Implementation

*

*option change

start: [0,16,21]
connect: [true, true, true, true]

*

*Event function change in noUiSlider.on
values[0 ~ 2]

So, a working js/html will be


text:
Q: Induction proof involving prime factor and binomial coefficients The question in my book is:

Use induction on $r$ to prove that if $p$ is a prime integer, then $p$ is a factor $\binom{p}{r}$ for $r=1, 2, . . . , p-1$.

I'm not really sure how to go about proving this statement using induction. Can I not simply do the following:
Expanding the factorials, we see
$\binom{p}{r}=\frac{p!}{(p-r)!(r)!}=\frac{p(p-1)(p-2) . . . (2)(1)}{(p-r)(p-r-1)...(2)(1)(r)(r-1)...(2)(1)}.$
Let $r$ be a positive integer less than $p$. It is given that $p$ is prime, so $p$ cannot be canceled. We know that $\binom{p}{r}$ is a positive integer (from an earlier exercise), so $p$ must be a factor of $\binom{p}{r}$.
If so, induction seems unnecessary. But I assume my instructor would still want me to use induction.

A: The result is true for $r=1$, since $\binom{p}{1}=p$. We now do the  induction step.
Suppose that $p$ divides $\binom{p}{r}$. We show that if $r+1\lt p$ then $p$ divides $\binom{p}{r+1}$.
Note that $\binom{p}{r+1}=\frac{p!}{(r+1)!(p-r-1)!}=\frac{p-r}{r+1}\binom{p}{r}$. Thus
$$(r+1)\binom{p}{r+1}=(p-r)\binom{p}{r}.$$
By the induction hypothesis, $p$ divides the right-hand side, so it divides the left-hand side. Since $r+1\lt p$, $p$ does not divide $r+1$. So $p$ must divide $\binom{p}{r+1}$.
Remark: I agree, induction is certainly not necessary.


text:
Q: Add and Remove class to child and parent element when i click on 'customer-row' it should add class 'open-carrier-tiers' in 'carrier-tiers'. which is working.
but when i click on 'carrier-tiers-close-btn' then it should remove the same class that added before from its parent parent element. which is not working.
and i am using $(this) because this whole code repeating multiple time on page.

close

      <form action="" method="POST">
        <input type="text" name="Customer Name">
        <button type="submit">Submit</button>
      </form>

Jquery
 $(".customer-row").click(function () {
    $(this).find("td.carrier-tiers").addClass('open-carrier-tiers');
});

$(".carrier-tiers-close-btn").click(function () {
    $(this).parent().parent().removeClass('open-carrier-tiers');
});

A: I think it's because the close event is being fired whenever the row is clicked because the event bubbles up. To fix this add an event.stopPropation() to the event handler. This will prevent the row click from also firing close. Try the code snippet below to see if it works for you.

$(".customer-row").click(function(e) {
  $(this).find("td.carrier-tiers").addClass('open-carrier-tiers')
  e.stopPropagation();

  console.log(document.querySelector("td.carrier-tiers").className);

});

$(".carrier-tiers-close-btn").click(function(e) {
  $(this).parent().parent().removeClass('open-carrier-tiers');
  e.stopPropagation();

  console.log(document.querySelector(".carrier-tiers-close-btn").className);

});
td {
  padding: 0.5em;
  border: 1px solid lightgray;
}

      customer-row

close

          <form action="" method="POST">
            <input type="text" name="Customer Name">
            <button type="submit">Submit</button>
          </form>

A: Consider using more precise selectors.

$(function() {
  $(".customer-row td:eq(0)").click(function() {
    $(this).next("td.carrier-tiers").addClass('open-carrier-tiers');
  });
  $(".carrier-tiers-close-btn").click(function() {
    $(this).closest('.open-carrier-tiers').removeClass('open-carrier-tiers');
  });
});
.open-carrier-tiers {
  border: 1px solid black;
}

      customer-row

close

          <form action="" method="POST">
            <input type="text" name="Customer Name">
            <button type="submit">Submit</button>
          </form>

As you targeted the Row, the click event on the child could not bubble up.


text:
Q: iOS 6.0 restrict auto rotation within a navigation controller? What else should I do?
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation) toInterfaceOrientation
{
    return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

-(BOOL)shouldAutoRotate
{
    return NO;
}

My viewController still rotates.

It is embedded in a navigation stack.
If I subclass UINavigationController, and implement the same portrait-only templates there, and I embed my viewController in that tweaked navigationController, than it works, but I have no intention to rewrite my code everywhere a UINavigationController appears.
What is the best practice here?

A: ORIGINAL ANSWER: No need to subclass - just do a category like I described in my solution here:
Top-home button portrait orientation in iOS6 simulator not working
Basically, for iPhone the UINavigationController allows rotation for everything except "top home button portrait", for iPad it allows everything.
So either you do a category forwarding the decision to the currently active view controller or something static like
UINavigationController-Rotation.h:
@interface UINavigationController (Rotation)
@end

UINavigationController-Rotation.m:
#import "UINavigationController-Rotation.h"

@implementation UINavigationController (Rotation)

#pragma From UINavigationController

- (BOOL)shouldAutorotate {

    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {

    return UIInterfaceOrientationMaskPortrait;
}

#pragma -

@end

UPDATE: As Javier Soto pointed out, this might lead to undefined behavior if there is a second category doing the same. In that case,  subclassing might be a better solution.
In a situation where you know there is no other category doing the same I still consider this a working, low effort, local and pragmatic solution. I am not religious about that. Decide yourself.

A: You should inherit from UINavigationController and use your custom one everywhere. It's not that much work (just search for occurrences of UINavigationController in your code). This will turn out to be much more flexible cause you'll be able to customize other things if necessary.
NEVER do it in a category that overrides methods in the main class like that other response suggests.


text:
Q: Rails: How to use i18n with Rails 4 enums Rails 4 Active Record Enums are great, but what is the right pattern for translating with i18n?

A: Starting from Rails 5, all models will inherit from ApplicationRecord.
class User < ApplicationRecord
  enum status: [:active, :pending, :archived]
end

I use this superclass to implement a generic solution for translating enums:
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  def self.human_enum_name(enum_name, enum_value)
    I18n.t("activerecord.attributes.#{model_name.i18n_key}.#{enum_name.to_s.pluralize}.#{enum_value}")
  end
end

Then I add the translations in my .yml file:
en:
  activerecord:
    attributes:
      user:
        statuses:
          active: "Active"
          pending: "Pending"
          archived: "Archived"

Finally, to get the translation I use:
User.human_enum_name(:status, :pending)
=> "Pending"

A: Elaborating on user3647358's answer, you can accomplish that very closely to what you're used to when translating attributes names.
Locale file:
en:
  activerecord:
    attributes:
      profile:
        genders:
          male: Male
          female: Female
          trans: Trans

Translate by calling I18n#t:
profile = Profile.first
I18n.t(profile.gender, scope: [:activerecord, :attributes, :profile, :genders])

A: Model:
enum stage: { starting: 1, course: 2, ending: 3 }

def self.i18n_stages(hash = {})
  stages.keys.each { |key| hash[I18n.t("checkpoint_stages.#{key}")] = key }
  hash
end

Locale:
checkpoint_stages:
    starting: Saída
    course: Percurso
    ending: Chegada

And on the view (.slim):
= f.input_field :stage, collection: Checkpoint.i18n_stages, as: :radio_buttons

A: Combining the answers from Repolês and Aliaksandr, for Rails 5, we can build 2 methods that allow you to translate a single value or a collection of values from an enum attribute.
Set up the translations in your .yml file:
en:
  activerecord:
    attributes:
      user:
        statuses:
          active: "Active"
          pending: "Pending"
          archived: "Archived"

In the ApplicationRecord class, from which all models inherit, we define a method that handles translations for a single value and another one that handles arrays by calling it:
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  def self.translate_enum_name(enum_name, enum_value)
    I18n.t("activerecord.attributes.#{model_name.i18n_key}.#{enum_name.to_s.pluralize}.#{enum_value}")
  end

  def self.translate_enum_collection(enum_name)
    enum_values = self.send(enum_name.to_s.pluralize).keys
    enum_values.map do |enum_value|
      self.translate_enum_name enum_name, enum_value
    end
  end
end

In our views, we can then translate single values:

User Status: <%= User.translate_enum_name :status, @user.status %>

Or the entire collection of enum values:
<%= f.select(:status, User.translate_enum_collection :status) %>

A: I didn't find any specific pattern either, so I simply added:
en:
  user_status:
    active:   Active
    pending:  Pending...
    archived: Archived

to an arbitrary .yml file. Then in my views:
I18n.t :"user_status.#{user.status}"

A: Try using TranslateEnum gem for these purposes
class Post < ActiveRecord::Base
  enum status: { published: 0, archive: 1 }
  translate_enum :status
end

Post.translated_status(:published)
Post.translated_statuses

@post = Post.new(status: :published)
@post.translated_status

A: I've created a gem for this.
http://rubygems.org/gems/translated_attribute_value
Add to your gemfile:
gem 'translated_attribute_value'

If you have a status field for user:
pt-BR:
  activerecord:
    attributes:
      user:
        status_translation:
          value1: 'Translation for value1'
          value2: 'Translation for value2'

And in your view you can call like this:
user.status_translated

It works with active record, mongoid or any other class with getter/setters:
https://github.com/viniciusoyama/translated_attribute_value

A: To keep the internationalization similar as any other attribute I followed the nested attribute way as you can see here.
If you have a class User:
class User < ActiveRecord::Base
  enum role: [ :teacher, :coordinator ]
end

And a yml like this:
pt-BR:
  activerecord:
    attributes:
      user/role: # You need to nest the values under model_name/attribute_name
        coordinator: Coordenador
        teacher: Professor

You can use:
User.human_attribute_name("role.#{@user.role}")

A: Here is a view:
select_tag :gender, options_for_select(Profile.gender_attributes_for_select)

Here is a model (you can move this code into a helper or a decorator actually)
class Profile < ActiveRecord::Base
  enum gender: {male: 1, female: 2, trans: 3}

  # @return [Array<Array>]
  def self.gender_attributes_for_select
    genders.map do |gender, _|
      [I18n.t("activerecord.attributes.#{model_name.i18n_key}.genders.#{gender}"), gender]
    end
  end
end

And here is locale file:
en:
  activerecord:
    attributes:
      profile:
        genders:
          male: Male
          female: Female
          trans: Trans

A: The model:
class User < ActiveRecord::Base
  enum role: [:master, :apprentice]
end

The locale file:
en:
  activerecord:
    attributes:
      user:
        master: Master
        apprentice: Apprentice

Usage:
User.human_attribute_name(:master) # => Master
User.human_attribute_name(:apprentice) # => Apprentice

A: Try the enum_help gem. From its description:

Help ActiveRecord::Enum feature to work fine with I18n and simple_form.

A: Heres a t_enum helper method that I use.
<%= t_enum(@user, :status) %>

enum_helper.rb:
module EnumHelper

  def t_enum(inst, enum)
    value = inst.send(enum);
    t_enum_class(inst.class, enum, value)
  end

  def t_enum_class(klass, enum, value)
    unless value.blank?
      I18n.t("activerecord.enums.#{klass.to_s.demodulize.underscore}.#{enum}.#{value}")
    end
  end

end

user.rb:
class User < ActiveRecord::Base
  enum status: [:active, :pending, :archived]
end

en.yml:
en:
  activerecord:
    enums:
      user:
        status:
          active:   "Active"
          pending:  "Pending..."
          archived: "Archived"

A: Yet another way, I find it a bit more convenient using a concern in models
Concern :
module EnumTranslation
  extend ActiveSupport::Concern

  def t_enum(enum)
    I18n.t "activerecord.attributes.#{self.class.name.underscore}.enums.#{enum}.#{self.send(enum)}"
  end
end

YML:
fr:
    activerecord:
      attributes:
        campaign:
          title: Titre
          short_description: Description courte
          enums:
            status:
              failed: "Echec"

View :
<% @campaigns.each do |c| %>
  <%= c.t_enum("status") %>
<% end %>

Don't forget to add concern in your model :
class Campaign < ActiveRecord::Base
  include EnumTranslation

  enum status: [:designed, :created, :active, :failed, :success]
end

A: I prefer a simple helper in application_helper
  def translate_enum(object, enum_name)
    I18n.t("activerecord.attributes.#{object.model_name.i18n_key}.#{enum_name.to_s.pluralize}.#{object.send(enum_name)}")
  end

Then in my YML file :
fr:
  activerecord:
    attributes:
      my_model:
        my_enum_plural:
          pending:  "En cours"
          accepted: "Accepté"
          refused:  "Refusé"

A: You can simply add a helper:
def my_something_list
  modes = 'activerecord.attributes.mymodel.my_somethings'
  I18n.t(modes).map {|k, v| [v, k]}
end

and set it up as usually:
en:
  activerecord:
    attributes:
      mymodel:
        my_somethings:
           my_enum_value: "My enum Value!"

then use it with your select: my_something_list

A: class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  def self.enum(definitions)
    defind_i18n_text(definitions) if definitions.delete(:_human)
    super(definitions)
  end

  def self.defind_i18n_text(definitions)
    scope = i18n_scope
    definitions.each do |name, values|
      next if name.to_s.start_with?('_')
      define_singleton_method("human_#{name.to_s.tableize}") do
        p values
        values.map { |key, _value| [key, I18n.t("#{scope}.enums.#{model_name.i18n_key}.#{name}.#{key}")] }.to_h
      end

      define_method("human_#{name}") do
        I18n.t("#{scope}.enums.#{model_name.i18n_key}.#{name}.#{send(name)}")
      end
    end
  end
end

en:
  activerecord:
    enums:
      mymodel:
        my_somethings:
           my_enum_value: "My enum Value!"

enum status: [:unread, :down], _human: true

A: Here is the simplest solution I have found.
Model file 'house.rb':
enum status: { unavailable: 0, available: 1 }

In the view, a simple_form select:
<%= simple_form_for(@house) do |f| %>
...
<%= f.input :status,
        collection: House.statuses.keys.map { |s| [t("house_enum_status_#{s}"), s] }
...
<% end %>

The collection creates an array with [key, value] expected for the select, with the correct translation.
And here is both locales yml files used:
'fr.yml'
house_enum_status_unavailable: "Indisponible"
house_enum_status_available: "Disponible"

'en.yml'
house_enum_status_unavailable: "Not available"
house_enum_status_available: "Available"

Here is the result in French
Here is the result in English

A: Model Order:
 enum order_type: {normal: false, security: true}.freeze, _default: :normal

OrdersController
    @order_type = Order.order_types.except(:security) unless secure_present # optional code
    @order_type.transform_keys! { |key| I18n.t("orders.new.order_types.#{key}")}

Locales (Ukrainian)
uk:
  orders:
    new:
      order_types:
        normal: 'Звичайна'
        security: 'Безпечна'


text:
Q: If a non-trivial zero of the zeta function existed off the critical line, would infinitely many zeros exist with the same real part? It is known that there exist infinitely many non-trivial zeros of the Riemann zeta function in the critical strip. Also, we know that infinitely many zeros are on the critical line - more than 1/3 among all, asymptotically - as well as most of the zeros live near the critical line.
In 1984, the theorem of Rademacher and Hlawka showed that the ordinates of the nontrivial zeros of the zeta function are uniformly distributed regardless of the abscissas.
Now, suppose that there exists one non-trivial zero having its real part (say A) other than 1/2. Then, let us call x=A "line A." (the complex plane defined as z=x+iy)
In that case when we take it true,
1) Might infinitely many zeros exist on the line A?
2) If 1) is possible, would they be distributed uniformly?

A: 1) Yes, this is still possible
2) No. We know that they have to distributed with low density, i.e. the number of zeros $z$ with $\Im z < T$ with $\Re z > \sigma >1/2$ is bounded by $T^{4\sigma(1-\sigma) + \epsilon}$ for $\epsilon >0$. So no uniform distribution is possible, since the gaps between consecutive zeros has to grow to infinity.
For sharper results in this direction, I suggest the first chapter of Joern Steuding "Universality of L-functions". This book actually explains pretty good what is going on in the critical stipe off the line $\Re s = 1/2$.


text:
Q: Delphi: GR32 draw a PNG with alpha onto a TBitmap32 without clearing its content After going through several other related questions I couldn't come up with a working code for this, so please spare the "duplicate question" tags.
Given a PNG image with either per-pixel alpha channel or single-color transparency, I need code to draw it onto a TBitmap32 which already contains an image (some drawing goes on before the PNG part). So let's say my TBitmap32 is 200x200, I do some drawing on it, then I want to ~insert a smaller transparent PNG image on top of its current content, transparently according to the PNG's alpha channel data or single-color alpha.
Uses pngimage, GR32;

procedure TForm1.Button1Click(Sender: TObject);
Var b: TBitmap;
    b32: TBitmap32;
    p: TPngImage;
begin
  b   := TBitmap.Create;
  b32 := TBitmap32.Create;
  p   := TPngImage.Create;

  // 50x50 PNG
  p.LoadFromFile('z:\test2.png');

  b.Width    := 200;
  b.Height   := 200;
  b32.Width  := 200;
  b32.Height := 200;
  // some drawing happens on the b32~

  // insert code here to draw the png onto the b32, on top of
  // what's already drawn, and at specific coordinates i.e 10,10

  /////////////////////////////

  b32.DrawTo(b.Canvas.Handle,0,0);
  Canvas.Draw(0,0,b);

  p.Free;
  b32.Free;
  b.Free;
end;

Original PNG:

Results so far:

A: There are two ways of working with transparent PNG files:

*

*Load them into intermediary TBitmap32 bitmaps and then manipulate these TBitmap32 bitmaps.

*Use TPngImage.Draw (implemented in Vcl.Imaging.pngimage with Delphi XE2 and later) directly on target Canvas, as you have pointed out.

The second way is preferable when it comes to transparency, because the code that you may find to load a PNG into TBitmap32 may work incorrectly. Here are the two examples of the incorrect code that is used most frequently:
(1) "LoadPNGintoBitmap32" from http://graphics32.org/wiki/FAQ/ImageFormatRelated
- it applies the transparency twice, so the images with alpha values other than 0 or 255 will look differently than in other software (most noticeable on translucent images with glass effects). This code will first apply alpha to RGB and then sets alpha, so when you pain, alpha will be applied again. You can find more information on this issue here: Delphi, GR32 + PngObject: converting to Bitmap32 doesn't work as expected
. Besides that, it doesn't convert correctly transparency from paletted images into the alpha layer of TBitmap32, for example, all white pixels become transparent.
(2) "LoadBitmap32FromPNG" from gr32ex library: https://code.google.com/archive/p/gr32ex/
- a slightly different implementation of the same algorithm as (1), and has the same issues as (1).
If you still prefer using TBitmap32, make the following sequence of steps:

*

*Make sure your code correctly converts PNG to TBitmap32.

*Do not use TBitmap32 with transparent images to draw directly on HDC, Canvas or TBitmap. Use dmBlend and DrawTo or BlockTransfer() to draw on another TBitmap32. For example, to draw transparently on a TBitmap, create an intermediary cache TBitmap32:

*
*Copy the image from TBitmap to the cache TBitmap32;

*Apply your transparent image to the cache TBitmap32 using DrawTo or BlockTransfer(), avoid using Canvas or HDC to mix two images because they lose alpha layer information;

*Copy the image back from the cache TBitmap32 to your TBitmap.


text:
Q: How to obtain dropdown item value from a form and pass to controller in ASP.NET? Given something like below,
@{
    if (IsPost){
         var someValue = Request.Form["item"];
        }
}

<form class="form-horizontal" method="post" action="@Url.Content("~/Home/Index")">

    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
    Action
    </button>

Items

          @foreach (var item in @Model)
          {

@item

          }

    <input type="submit" name="submit" value="Submit" />

</form>

The problem that occurs is the data is not being passed to the controller for the selectedItem.
For example,
public ActionResult Index(string item){

return View();
}

item returns null, so the value is not being passed it seems. How do I pass information from the View to the Controller in a form that contains a dropdown. Essentially, I would like to have the dropdown item selected passed to a controller.

A:  links trigger GET requests, not POST requests, so your this.Request.Form will always be empty.
Use the querystring. Values are accessed by this.Request.QueryString:
@foreach(var item in @Model) {

@item

}


text:
Q: Convert 4-byte `binary(4)` to an unsigned integer in MySQL I have IPv4 address stored in DB as VARBINARY(4): four bytes of an unsigned integer. Very strange approach, yes :)
How do I convert it to an unsigned integer in MySQL?

A: Bad & slow solution: CONV(HEX(table.ip),16,10)


text:
Q: OpenGL - Easiest way to draw a square with a texture Usually I draw a square with a texture like this:

*

*Create a VBO with 4 coordinates (A,B,C,D for the square)

*Create a EBO with 4 indices (A,C,D and B,C,D) telling that I want to draw a square out of 2 triangles.

*Draw this elements with a texture

Isn't there an easiest way without having a EBO array?
Because it is not very handy to use... If I want to use like this:
VAO = [-0.8f, 0.5f, 0.0f, ...]
EBO = [0, 1, 3, 1, 2, 3, ...]
Then I need to remove a square from my VAO... then I also need to remove the indices from my EBO array and re-arrange it.
Is there a better way to do this?

A: If you really only want to draw a square with a texture on it, you should consider make a new empty VAO, and just call glDrawArrays(GL_TRIANGLE_STRIP, 0,3);
The vertex shader then looks like this:
out vec2 mapping;

void main()
{
    float size = 1.0f;

    vec2 offset;
    switch(gl_VertexID)
    {
    case 0:
        //Bottom-left
        mapping = vec2(0.0f, 0.0f);
        offset = vec2(-size, -size);
        break;
    case 1:
        //Top-left
        mapping = vec2(0.0f, 1.0f);
        offset = vec2(-size, size);
        break;
    case 2:
        //Bottom-right
        mapping = vec2(1.0, 0.0);
        offset = vec2(size, -size);
        break;
    case 3:
        //Top-right
        mapping = vec2(1.0, 1.0);
        offset = vec2(size, size);
        break;
    }

     gl_Position = vec4(offset, 0.0f, 1.0f);
}

The mapping variable tells the fragmentshader what the texture coordinates are.

A:
Isn't there an easiest way without having a EBO array?

Duplicate your vertices & use glDrawArrays().

A: You can use DrawArray to plot the indices.
Something like this:
Vertex2D* vertex = (Vertex2D*) vbo->lock();
        vertex[0].x = x[0]; vertex[0].y = y[0]; vertex[0].u = u[0]; vertex[0].v = v[0]; vertex[0].color = color;
        vertex[1].x = x[0]; vertex[1].y = y[1]; vertex[1].u = u[0]; vertex[1].v = v[1]; vertex[1].color = color;
        vertex[2].x = x[1]; vertex[2].y = y[1]; vertex[2].u = u[1]; vertex[2].v = v[1]; vertex[2].color = color;
        vertex[3].x = x[1]; vertex[3].y = y[0]; vertex[3].u = u[1]; vertex[3].v = v[0]; vertex[3].color = color;
vbo->unlock();

shader->bind();
vbo->bind();
vao->bind();
tex->bind();
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
tex->unbind();
vao->unbind();
vbo->unbind();
shader->unbind();


text:
Q: Need help updating Lua code in Visual Studio 2017 C++ code I have this code that used to work in 2005 but it seems that Lua has changed and I admit I'm stumped.
bool SLua::getValue (const char *table, const char *key, int  *result){

lua_getglobal (state_, table);
lua_pushstring (state_, key);
lua_gettable (state_, -2);

*result = lua_tonumber (state_, -1);
lua_pop (state_, 2);

return true; }

My compiled app crashes every time on lua_gettable (state_, -2);
Is this due to changes in Lua? I already had to swap lua_open() elsewhere with luaL_newstate().
Thanks for any help


text:
Q: How to create split view controller like apple mail I create a Split View Controller with a master and detail. What I am trying to accomplish is to create my split view controller to be similar to apple mail Where I would have my list of mailboxes, then when I tap on one, it shows a list of messages and if you tap on one of those show the message.
Has anyone seen a tutorial on how to do this? After looking at the mail app on iPhone and iPad, I noticed that it first show the master, on iPad the master gets replace with the list of messages and it looks like on iPad it goes from master to table view, then from the list of messages goes into detail view.
Can someone help me and point me in the right direction on accomplishing what I am trying to accomplish?


text:
Q: set timeout in Spring WebFlux webclient I'm using Spring Webflux WebClient to make a REST call from my Spring boot application. And every time getting a timeout in 30 seconds.
Here is some code I tried to set socket timeout in WebClient of Spring webfulx.
 - ReactorClientHttpConnector connector = new ReactorClientHttpConnector(options -> options
           .option(ChannelOption.SO_TIMEOUT, 600000).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 600000));
 - ReactorClientHttpConnector connector = new ReactorClientHttpConnector(
           options -> options.afterChannelInit(chan -> {
                chan.pipeline().addLast(new ReadTimeoutHandler(600000));
            }));
 - ReactorClientHttpConnector connector1 = new ReactorClientHttpConnector(options -> options
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 600000).afterNettyContextInit(ctx -> {
                ctx.addHandlerLast(new ReadTimeoutHandler(600000, TimeUnit.MILLISECONDS));
            }));

And tried to add this above connector setting in "WebClient" by using "clientConnector" method.
And also tried to set timeout as below:
webClient.get().uri(builder -> builder.path("/result/{name}/sets")
                    .queryParam("q", "kind:RECORDS")
                    .queryParam("offset", offset)
                    .queryParam("limit", RECORD_COUNT_LIMIT)
                    .build(name))
            .header(HttpHeaders.AUTHORIZATION, accessToken)
            .exchange().timeout(Duration.ofMillis(600000))
            .flatMap(response -> handleResponse(response, name, offset));

None of the above options is working for me.
I'm using org.springframework.boot:spring-boot-gradle-plugin:2.0.0.M7 which interally have dependecy of org.springframework:spring-webflux:5.0.2.RELEASE.
Please suggest here and let me know if I'm doing anything wrong here.

A: Since HttpClient.from(tcpClient) is now deprecated in the latest netty (v0.9.x and will be removed in v1.1.0). You can use responseTimeout() and ignore too many HTTP connection configurations which you see in other code and this implementation works with the old as well as the new one.
Create HttpClient
HttpClient httpClient = HttpClient.create().responseTimeout(Duration.ofMillis(500)); // 500 -> timeout in millis

Add httpClient to webclient using webClient builder fxn .clientConnector()
WebClient
.builder()
.baseUrl("http://myawesomeurl.com")
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build();

Also, the majority of the implementation available over the website is not deprecated to make sure that you are not using the deprecated one you can check out this link.
FYI: For the older netty versions  (i.e < v0.9.11 version) responseTimeout() uses tcpConfiguration() under the hood, which is deprecated in the new versions. But responseTimeout() uses the new implementation in >=v0.9.11, so even if you change the netty version of your project in the future your code is not going to break.
NOTE: If you are using the old netty version which comes by default with spring sometimes, you probably can use Brian's implementation too. (Not sure though)
If you want to read more about responseTimeout() and how does it work, you can check the source code here and here or the github gist here.

A: I've tried reproducing the issue and couldn't. Using reactor-netty 0.7.5.RELEASE.
I'm not sure about which timeout you're talking about.
Connection timeout can be configured with ChannelOption.CONNECT_TIMEOUT_MILLIS. I'm getting 10 seconds between the "connecting" log message and the actual error:
WebClient webClient = WebClient.builder()
    .clientConnector(new ReactorClientHttpConnector(options -> options
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)))
    .build();

webClient.get().uri("http://10.0.0.1/resource").exchange()
    .doOnSubscribe(subscription -> logger.info("connecting"))
    .then()
    .doOnError(err -> logger.severe(err.getMessage()))
    .block();

If you're talking about read/write timeouts, then you can look at Netty's ReadTimeoutHandler and WriteTimeoutHandler.
A full example could look like this:
ReactorClientHttpConnector connector = new ReactorClientHttpConnector(options ->
        options.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10)
                .onChannelInit(channel -> {
                        channel.pipeline().addLast(new ReadTimeoutHandler(10))
                                .addLast(new WriteTimeoutHandler(10));
                return true;
        }).build());

As of Reactor Netty 0.8 and Spring Framework 5.1, the configuration now looks like this:
TcpClient tcpClient = TcpClient.create()
                 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
                 .doOnConnected(connection ->
                         connection.addHandlerLast(new ReadTimeoutHandler(10))
                                   .addHandlerLast(new WriteTimeoutHandler(10)));
WebClient webClient = WebClient.builder()
    .clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient)))
    .build();

Maybe adding the following to your application.properties will provide more information on what's happening at the HTTP level:
logging.level.reactor.ipc.netty.channel.ContextHandler=debug
logging.level.reactor.ipc.netty.http.client.HttpClient=debug

A: Per HttpClient.from(TcpClient) method, as @im_bhatman mentioned, has been deprecated, here comes a way using the good-old way.
// works for Spring Boot 2.4.0, 2.4.1, and 2.4.2
// doesn't work for Spring Boot 2.3.6, 2.3.7, and 2.3.8
HttpClient httpClient = HttpClient.create()
        //.responseTimeout(Duration.ofSeconds(READ_TIMEOUT_SECONDS))
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIME_MILLIS)
        .doOnConnected(c -> {
                c.addHandlerLast(new ReadTimeoutHandler(READ_TIMEOUT_SECONDS))
                 .addHandlerLast(new WriteTimeoutHandler(WRITE_TIMEOUT_SECONDS));
        });
ClientConnector clientConnector = new ReactorClientHttpConnector(httpClient);
WebClient webClient = WebClient.builder()
        .clientConnector(clientConnector)
        ...
        .build();

I'm not sure about the difference of

*

*HttpClient#responseTimeout(...)

*HttpClient#doOnConnected(c -> c.addHandler(new ReadTimeoutHandler(...)))

A: Refer the below code block to set timeout and retry using webclient
.retrieve()
            .onStatus(
                   (HttpStatus::isError), // or the code that you want
                    (it -> handleError(it.statusCode().getReasonPhrase())) //handling error request
           )
            .bodyToMono(String.class)
            .timeout(Duration.ofSeconds(5))
            .retryWhen(
                    Retry.backoff(retryCount, Duration.ofSeconds(5))
                            .filter(throwable -> throwable instanceof TimeoutException)
           )


text:
Q: Gradient wrt. a Position Vector I found the following equations in a dynamics textbook,
The gravitational potential energy for any two particles in a $n$-particle system is given by,
$$V_{ij} = - \frac {G  m_i  m_j}{r_{ij}}$$
where $r_{ij}$ is the distance between $m_i$ and $m_j$. The total potential energy of the system is,
$$V = \frac{1}{2} \sum_{i = 1}^{n} \sum_{j = 1}^{n}V_{ij} \qquad (i \neq j)$$
If $R_i$ is the postion vector of the $i^{th}$ particle, then
$$\frac{\partial{V}} {\partial {\vec{R_{i}}}} = - \frac{\partial{V}}{\partial{\vec{r_{ji}}}} + \frac{\partial{V}}{\partial{\vec{r_{ij}}}} = -2 \frac{\partial{V}}{\partial{\vec{r_{ij}}}}.$$
What does it mean to take the derivative of a Scalar Function$(V)$ with respect to a vector$(\vec{R_1})$? Is it directional derivative?
I've been trying all day to get the last equation. I would be very grateful if somebody could help me(or mention some reference perhaps). I don't really know which part of math is used to get the last equation.

A: $\frac{\partial V}{\partial \vec R}$ is the vector whose $i^{th}$ component is $\frac{\partial V}{\partial R_i}$.  In other words,
$$\frac{\partial V}{\partial \vec R} = \left<\frac{\partial V}{\partial R_1},\frac{\partial V}{\partial R_2}, \frac{\partial V}{\partial R_3}\right>$$


text:
Q: pydoc injecting python submodules content to main module I have a module dlprim
dlprim/
  __init__.py
  netconfig.py
  _pydlprim.so

its __init__.py incldes:
from ._pydlprim import *
from .netconfig import *

where ._pydlprim is boost.pythom module and .netconfig is submodule.
If I generate a documentation with pydoc -w dlprim - it does not include classes from _pydlprim and netconfig.py so in order to generate them all I need to run pydoc -w dlprim dlprim.netconfig dlprim._pydlprim
But I get 3 separate files each in different namespace I want all of the classes to be found under dlprim module and namespace in pydoc.
How can I do it, or is there an alternative for this?

A: Put the names of those re-exported items in __all__.
from ._pydlprim import *
from .netconfig import *

def _all_of(mod):
    try:
        yield from mod.__all__
        return
    except AttributeError:
        pass
    for item in dir(mod):
        if not item.startswith('_'):
            yield item

__all__ = [*_all_of(_pydlprim), *_all_of(netconfig)]


text:
Q: Should a new screenshot tool automatically set itself to work on pressing the PrtSc key? Having just written my perfect screenshot tool, I've been trying to work out how it should set itself up for use by people who are not me. Screenshots are traditionally taken by pressing the PrtSc key. So, I could do the following things:
As soon as the app is installed, make pressing PrtSc invoke the app
Pros:

*

*works immediately, out of the box, as expected. A user installs the app, hits PrtSc, they get the app they've just installed. Hooray.

Cons:

*

*unconditionally overrides any existing setup you have for PrtSc, which might be annoying

*if you uninstall the app, it won't reset PrtSc to what it was before, which is also annoying

*problematic for multiple users, because app installation runs under sudo, so how does it know which user's PrtSc setup to override? It's certainly possible to add a gconf key as part of installation, but that may be problematic if two different screenshot apps both try?

On first-run of the app, seize the PrtSc key
Pros:

*

*avoids the above problem of wrongly seizing other users' PrtSc keys

Cons:

*

*you have to run the app once manually first, which is annoying (and how do you know how to do that?)

*will still not restore the old setting if the app is uninstalled

Have a configuration dialog in the app where you configure it to seize PrtSc
Pros:

*

*Only seizes PrtSc for people that really want it to

Cons:

*

*you have to run the app once manually first, which is annoying (and how do you know how to do that?)

*you have to go into a configuration dialog to make the app actually do what it's intended to do; take screenshots when you press PrtSc. Ubuntu is past that configure-everything stage now, surely? How irritating. Not doing this!

Something else I haven't thought of
A better cleverer approach that just hasn't dawned on me yet.
Suggestions welcomed!

A: You could perhaps set the keyboard short cut for your app but record what was previously bound to that shortcut. Then on first run (possibly when the user presses prt sc, you could pop up a dialog that asks them something like:

This application has been set as the default screenshot application that will be run whenever you press the 'print screen' key. Do you wish to keep to this behaviour or revert to previous settings?

Enabling them to easily get back to the previous settings if they want.

A: I think scenario A and C are the way to go.
You could plug into the Alternatives system and add the relevant entry to the System → Preferences → Default Applications screen, like this:

I believe that setting yourself as default on install is fine, however. Displaying a notice on first run asking each user if they want to use the previous default instead would be nice.
(Is it even possible to add a new entry in that dialog?)

A: I will go for a configuration dialog in the app, plus a command line script.
Both should read the previous keyboard shortcut value, store it and restore it when the user asks (or delete the value if no one was present).
The dialog should let final users adjust the behaviour. The command line script can be used by packagers to set the default behaviour according to distribution guidelines, and to make it uninstall clean (restoring the keyboard shortcuts that it grabbed).

A:
unconditionally overrides any existing setup you have for PrtSc, which might be annoying

It would. As others have said, I'd make this an option somewhere prominent in the preferences, perhaps a first-run choice-dialogue too.
But importantly, I would have it remember the setting it was changing from and store that somewhere. On uninstallation, I'd have it go through all the users and if enabled reset their print-screen keybind to whatever it was before.
The complicated bit is the post-rm script will run as root and you need to run commands as all the desktop users. I'm sure it's possible and it's by far the best solution.


text:
Q: Software not running in wine 1.7 ubuntu 15.04 Kindly assist with an application from Bridgewood Design. i installed a software called cut list plus on wine 15.04. The software installed perfectly, but not showing in my list of program.
When i browse c. Drive, i cant see the Bridgewood design on my programme files but cant run the software.
Please kindly assist
Henry

A: FAQ : "6.1 How do I run an application once I've installed it?"  at https://wiki.winehq.org/FAQ


text:
Q: How to add tiles in Visual Studio Web application using DevExpress I added and used Tile Control in windows application (WinForms). But i am unable to use tiles in any of the web applications on Visual Studio. Besides using metro css, is there any method to use DevExpress tile control in Visual Studio web applications? Please Help me.

A: From: Mehul Harry's DevExpress Blog Article

Any way to generate a "Tile" feel for Websites using DXTREME...
  ????????

Answer: For websites, you can try the TileView widget.  For Window, DXTREME XAML as it contains a Windows 8 Tile control.

Is there any method to use DevExpress tile control in Visual Studio web applications?
There is not such control for ASP.NET WebForms. At the same time I
  believe that the same behavior can be implemented using
  ASPxDocking. Please refer to our demos starting from this -
  Docking - Forbidden Zones. You can test any demo using a mobile
  tablet device. You can enable any existing theme on a corresponding
  tab on a demo page.

Hope this helps..


text:
Q: Transformar vsix en dll. Quiero añadir un .VSIX en mi código No se si es una locura, pero quiero que el paquete de Visual Studio Installer project este dentro de mi código y no en exe.
Es decir que si yo paso el código de mi programa no tenga que hacer que otra persona tenga que entrar en Tools-- extensions...  y que tenga que descargarlo.
Hay alguna forma de incluir el Installer Projects en mi trabajo?
Gracias!


text:
Q: Regular expression to extract Section Number and Description Am having following data and I would like to extract section number and description in two separate strings.
I am using the following expression - (\d+(?>\.\d+)*)(.\D*). However, in the description I am seeing '. 'value and I want the dot to be in the section identified.
Can someone help me with this?
Here are my sample strings -
1.1.1. ABC
1.1.2. DEF
1.1.2.3. XYZ

Expecting -
No|Description
1.1.1.|ABC
1.1.2.|DEF
1.1.2.3.|XYZ

A: Based on your shown samples, could you please try following.
Online demo of this is: Online demo of regex
(?P<serial>(?:\d+\.)+)\s*(?P<description>\S+)

Explanation: Adding detailed explanation for above.
(?P<serial>           ##Starting a named capturing group named serial here.
(?:\d+\.)+)           ##Starting a non capturing group which is looking for continuous occurrence of digits followed with dot with 1 or more occurrences of this combinations.
\s*                   ##Looking for 1 or more occurrences of spaces here.
(?P<description>\S+)  ##Starting a named capturing group named description here which has all values except spaces occurrences.


text:
Q: Long click to display the content of another activity in the same activity I'm trying to imitate Instagram on long click feature in my application.
I have a list view and when the user clicks an item, it opens a details activity.
what i'm trying to do is to display the details to the user when long pressing an item without moving to the details activity, i need to display it in the center of the screen in the same activity (like when you long press on a picture in Instagram) and disappears when the user release the touch.
I have tired the following:
 view.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        Log.d("LongClick", "Long click");
                        Intent in = new Intent(AppointmentsActivity.this,AppointmentsDetailsActivity.class);
                        startActivity(in);
                        return true;
                    }
                });
                view.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
                            Log.d("TouchTest", "Touch down");
                        } else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
                            Log.d("TouchTest", "Touch up");

                        }
                        return false;
                    }
                });

A: For These you don't need to start new Activity. you have only to have  datas (preferences or a class with variable).  Then  with a simple dialogbox you can do that or with a fragment. Because you can't run 2 Activities in the mean time. And if you want to start detail Activity for resons of memorie, your launch activity may be killed and don't still in backstack.

A: as  user2043602 said, you don't need to start a new activity.,
According to me the best alternative is to use ViewAnimator with two layouts,
and dynamically add a fragment to the second layout[which is not visible, until you move to next view in ViewAnimator].
to add fragment at run-time, you can use the following:
FragmentTransaction transaction;
transaction = getFragmentManager().beginTransaction();
page_1 newFragment1 = page_1.newInstance("one", "two");//here page_1 is my fragment..which you can easily do by adding a new default blank fragment in android studio
transaction.add(R.id.holder, newFragment1);//R.id.holder is the layout id under whihc you wish to add the fragment..

you can you ViewAnimator like this:
ViewAnimator viewAnimator;
viewAnimator = (ViewAnimator)findViewById(R.id.group1);//R.id.group1 is the view animator id
viewAnimator.setInAnimation(AnimationUtils.loadAnimation(page2.this, R.anim.first_try));         viewAnimator.setOutAnimation(AnimationUtils.loadAnimation(page2.this, android.R.anim.slide_out_right));

            viewAnimator.showNext();

A: For this, just open another activity onLongPress as dialog activity.So Content of detail activity will show in current activity.
To open the activity as dialog activity, you need to set activity theme as dialog theme
< activity android:theme="@android:style/Theme.Dialog" />


text:
Q: change url ajax get request i have an ajax call get
$.get('http://tvc.loc/search?searchData='+searchVal, function(returnData) {}

but have my base url stored in a variable
var url = (location.protocol + "//" + location.hostname +
  (location.port && ":" + location.port) + "/");

but now i wan't to do something like this
$.get('"+url/search?searchData='+searchVal, function(returnData) {}

but i don't know if this is possible but i can't seem to get it working

A: You can use + to concatenate:
$.get(url + '/search?searchData='+searchVal, function(returnData) {});


text:
Q: How to use int 13 with AH=03h interrupt in assembly to fill a sector with zeroes? So far i have this:
mov ah,02h
mov cl,11001100001111011101000b ;6,692,584 in dec
mov dl,0
int 13

A: I can see the following issues with your code:

*

*AH should be 3 rather than 2 (2 is for reading).

*CL is only eight bits so is unlikely to be holding that big honkin' value.

*You need to set AH, AL, CH, CL, DH, DL and ES:BX as per the following table:

AH     03h
AL     Number of sectors to write
CH     Track number
CL     Sector number
DH     Head number
DL     Drive number
ES:BX  Buffer to write

And, if you ever need information on interrupts, you should google for "Ralf Brown". This guy created and maintained the definitive interrupt list back in the days before we were insulated from such things. See, for example, the indexed HTML version.
Your specific needs can be met from the Int 13/AH=03h section.
A sample, though untested and written in real mode, would be something along the following lines:
      mov  ax, 0301h           ; cmd 3 (write sector), 1 sector
      mov  cx, 0001h           ; track 0, sector 1
      mov  dx, 0000h           ; head 0, drive 0
      mov  es, segment buff    ; segment and offset of buffer
      mov  bx, offset buff
      int  13h                 ; make the call
      jc   errp                ; detect error
      ret

errp:                          ; process error here
      ret

buff: db   0(256)              ; buffer to write


text:
Q: Golang: Autocomplete missing interface methods I am currently working on a go project where I define an interface to use in another file. My workflow works but I'm confused at either why there doesn't seem to be any "auto-complete" for protocols or why I cannot find it, I am using VSCode.
First of all, I am not fluent in go at all so if I misuse the term "object" for example that's because I don't know any better.
Let's say the interface looks like that:
type TestInterface interface {
    Function1()
}

and my function to pass an object of that interface to looks like that
func Start(obj TestInterface) {
    ...

Now, in order to define a type that I can construct an object of, I do
type TestInterfaceType int

and because I have to conform to the interface defined, I need to apply these functions to my "new" type
func (e TestInterfaceType) Function1() {
    fmt.Println("Test")
}

I am then able to construct an object
var testInterfaceTypeObject TestInterface

testInterfaceTypeObject = TestInterfaceType(1)

and passing that object to my Start() function above which expects a type of that interface works fine since the object of my "new type" has the functions defined that are defined on the interface.

Everything until here works as I have expected, or at least it works for me.
Now if I add another function to the TestInterface but I do not apply that new function to my TestInterfaceType, I see an error coming up that is InvalidIfaceAssign:

InvalidIfaceAssign occurs when a value of type T is used as an
interface, but T does not implement a method of the expected
interface.

I understand why this is happening, I also have to do the func (e TestInterfaceType) ... for my new function but here is my question:
Is there a way to automatically generate empty mock functions for the missing functions? In Java for example, the IDE offers me to add the missing functions (without functionality of course, but at least they are there, ready for me to write logic into them)?
In other words, once I add Function2() to TestInterface, can I make it automatically do
func (e TestInterfaceType) Function2() {

}

wherever I use that interface?


text:
Q: What is the proper way of dealing with navigation to screens located in separate navigators directly in react navigator 5? I have aan app scenario where I have a Bottom tabs navigator as my base navigator tab with Home, Products ... as my tabs:
<Tab.Navigator
    screenOptions={{
      headerShown: true,
    }}
    tabBarOptions={{
      showLabel: false,
      activeTintColor: MyColors.COLOR_ACCENT,
    }}>
    <Tab.Screen
      name="Home"
      component={HomeStack}
      options={{
        tabBarIcon: ({color, size}) => (
          <Icon name="home" color={color} size={size} />
        ),
      }}
    />

    <Tab.Screen
      name="Product"
      component={ProductStack}
      options={{
        tabBarIcon: ({color, size}) => (
          <Icon name="business-center" color={color} size={size} />
        ),
      }}
    />
    <Tab.Screen
      name="Request"
      component={MedRequest}
      options={{
        color: MyColors.COLOR_PRIMARY,
        tabBarIcon: ({color, size}) => (
          <Icon
            name="near-me"
            color={color}
            size={35}
            style={{transform: [{rotateZ: '20deg'}]}}
          />
        ),
      }}
    />
    <Tab.Screen
      name="Reminder"
      component={Reminder}
      options={{
        tabBarIcon: ({color, size}) => (
          <Icon name="alarm" color={color} size={size} />
        ),
      }}
    />
    <Tab.Screen
      name="Location"
      component={LocationStack}
      options={{
        tabBarIcon: ({color, size}) => (
          <Icon name="location-on" color={color} size={size} />
        ),
      }}
    />
  </Tab.Navigator>

Lets consider my first 2 screens from Bottom Tabs.
The first one is Home. It contains a list of top 5 popular products and a "view all" link which navigates it to the second tab products.
Each individual listed products are supposed to navigate to the product detail page.Since, the productDetail navigation is not defined in the bottom tabs navigator, I tried to resolve this by creating a new Stack navigator in home via homeStack which is as:
<Stack.Navigator
    screenOptions={{
      headerShown: false,
    }}>
    <Stack.Screen name="Home" component={Home} />
    <Stack.Screen name="Notifications" component={Notifications} />
    <Stack.Screen name="ProductDetail" component={ProductDetail} />
    <Stack.Screen name="AuthStack" component={AuthStack} />
    <Stack.Screen name="BlogStack" component={BlogStack} />
    <Stack.Screen name="BlogDetail" component={BlogDetail} />
    <Stack.Screen name="Cart" component={CartStack} />
  </Stack.Navigator>

Now that we have the productDetail navigator in handler, I am able to navigate to product detail.
Similarly, the product bottom tab has another stack navigator as ProductStack on top which helps in navigation to its various links. It is as:
<Stack.Navigator
    screenOptions={{
      headerShown: false,
    }}>
    <Stack.Screen name="Product" component={Product} />
    <Stack.Screen name="CartStack" component={CartStack} />
    <Stack.Screen name="ProductDetail" component={ProductDetail} />
  </Stack.Navigator>

My main concern here is that I have been including the ProductDetail and CartStack as an element of navigators in more than one places and I have a feeling that I'm not doing this right.
Also can this multilevel stacking of navigators lead to a performance issue?
Also the cartStack I access when directly navigating to productDetail from home screen causes the disappearance of the bottom tabs.
Am I handling the situation totally wrong here?? Is there an easier way of doing this, that hasn't crossed my mind?

A: So it depends on which tab you want to stay on, if you want to stay on the home tab you can leave it in the home stack. If you want to go to the products tab -> product details page so when they go back/dismiss it will go back to the root screen of the products tab then you can do something like this to navigate to nested screens:
navigation.navigate('Product', { screen: 'ProductDetail' });

A: I think you should put your ProductDetail and CartStack and your BottomTabContainer in a Stack.Navigator, then you can easily navigate to ProductDetail or CartStack from anywhere in your BottomTabNavigator
Something like this:

<Stack.Navigator
  screenOptions={{
    headerShown: false,
  }}>
  <Stack.Screen name="TabNavigator" component={YourTabComponent} />
  <Stack.Screen name="CartStack" component={CartStack} />
  <Stack.Screen name="ProductDetail" component={ProductDetail} />
</Stack.Navigator>

then you can remove your CartStack and ProductDetail out of HomeStack and ProductStack.


text:
Q: iPhone - UIActivityIndicatorView does not hide when stopped I have a custom UIWebView written like this :
.h
@interface MiniWebViewController : UIViewController {
    NSString* destinationURL;

    UIWebView* webView;
    UIActivityIndicatorView* activityIndicatorView;
}

@property (nonatomic, retain) NSString* destinationURL;

@property (nonatomic, retain) IBOutlet UIWebView* webView;
@property (nonatomic, retain) IBOutlet UIActivityIndicatorView* activityIndicatorView;

- (void) run;

@end

.m
@synthesize destinationURL;
@synthesize webView;
@synthesize activityIndicatorView;

- (id) initWithFrame:(CGRect)frame {
    if (self = [super initWithNibName:@"MiniWebView" bundle:nil]) {
        self.destinationURL = @"";

        self.view.frame = frame;
        self.activityIndicatorView.center = self.webView.center;
    }

    return self;
}

- (void) run {
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.destinationURL]]];
}

It is called an initied from another ViewController :
- (void) aFunction {
    MiniWebViewController* oneViewController = [[MiniWebViewController alloc] initWithFrame:CGRectMake(/*Some Rect*/];
            oneViewController.webView.tag = i;
            oneViewController.destinationURL = /*SomeURL*/;
            oneViewController.webView.delegate = self;

            [self.view addSubview:oneViewController.view]; /* the Web view is inside this one */
            [oneViewController run];
    }

    - (void) webViewDidFinishLoad:(UIWebView *)webView {
        int webViewID = webView.tag;
        MiniWebViewController* webViewController = [self.webViews objectAtIndex:webViewID];
        [webViewController.activityIndicatorView stopAnimating];
    }

    - (void)webViewDidStartLoad:(UIWebView *)webView {
        int webViewID = webView.tag;
        MiniWebViewController* webViewController = [self.webViews objectAtIndex:webViewID];
        [webViewController.activityIndicatorView startAnimating];
    }

Into IB hidesWhenStopped is also checked. Everything is linked. The style of the indicator is set to "Large White" into IB.
When running, the indicator is not large, but small.
It is successfully started and stopped (delegate calls are triggered), but it doesn't hide when stopped.
What's the problem ? I don't see...

A: After a careful look in your code, you are modifying the UIActivityView in your init method.  Change those so that they are in your viewDidLoad.  At init, you view is not yet loaded, therefore, there is not an instance of those objects yet created in your controller.
These are the statement that need to be moved:
self.activityIndicatorView.hidesWhenStopped = YES;

self.view.frame = frame;
self.activityIndicatorView.center = self.webView.center;

This goes back to a fundamental of Objective-C:  Sending a message to a nil object...returns nil.  This is an annoying feature at times because there is no compile time warning, nor is there any runtime exception--a feature of the language.

A: Stupid I am, and XCode/cocoa really doesn't help.
I had loaded a wrong XIB name that DOES NOT exist.
So I ask to load something that does not exist, and the app stil works, even showing and using objects that does not exist. Untill one call does not work as expected. No crash...
It's nonsense.


text:
Q: Ada: Writing output numbers in a file separated by a tab Just putting part of some code here where I am writing two values to a text file.
Ada.Long_Float_Text_IO.Put (File => Output_File, Item => Out_2, Fore => 1, Aft => 4, Exp => 0);
Ada.Text_IO.Put (Output_File, "   ");
Ada.Long_Float_Text_IO.Put (File => Output_File, Item => Out_3, Fore => 1, Aft => 4, Exp => 0);

I can separate these numbers Out_2 and Out_3 by a space as shown in the code. The results give (after writing more numbers in the two columns):
-75.2340   421.5700
1256.0000   15.4700
-4568.9800   -118.2800
3784.2100   0.0000

I would like to know if there is a way to specify a tab spacing so that I can have something like this in my text file:
-75.2340     421.5700
1256.0000    15.4700
-4568.9800   -118.2800
3784.2100    0.0000

So which control character produces the above alignment?
Thanks a lot...

A: For a tab, there's the obsolescent ASCII.HT or Ada.Characters.Latin_1.HT.
Or you could use the Width parameter to Ada.Long_Float_Text_IO.Put and friends.
Edit: There is no Width parameter for real output! You could use a large Fore, which would effectively right-justify the output.

A: Instead of that intervening:
Ada.Text_IO.Put (Output_File, "   ");

Call the Set_Col procedure instead, which moves the output line position to the specified column. E.g.
Ada.Text_IO.Set_Col(Output_File, 13);


text:
Q: html5 audio doesn't work in ios safari I have a game in which user clicks start button and after that by setInterval program randomly chooses an audio from an array and plays it. It works fine everywhere but safari.
I've also tried to use a ResponsiveVoice API. None of them works.
It looks as the code below:
var audio = new Audio();
audio.src = 'blabla';

and when user clicks start:
setInterval(function() {
  audio.play();
}, 2000);

How can I solve this problem?

A: If your audio file isn't working AT ALL in safari, (not just with the setInterval js), then it's probably the file type that is the problem.
Currently, flac and ogg audio types are not supported in Safari, but are in other browsers. Likewise with Opus, another open-source file type.
MP3 and AAC are the most widely supported file types, followed by .wav
The use of web audio is pretty widely supported also.
Refer to caniuse for more info.


text:
Q: Check continuity and find norm of linear functional I have to check continuity and find norm of the following linear functional
$$\ell^{2}\ni \{x_n\}^{\infty}_{n=0} \rightarrow \sum^\infty_{n=0}\frac{x_n}{\sqrt{2^n}}\in \mathbb{K}$$
As for continuity, I've found a constant $C=\sqrt{2}$ (derived it from Holder inequality. But I don't know how to find norm of this functional. I can't find a vector from $\ell^{2}$ for which the inequality
$$| \sum^\infty_{n=0}\frac{x_n}{\sqrt{2^n}} | \le \sqrt{2} \cdot(\sum^\infty_{n=0}|x_n|^2)^{1/2} $$
is an equality.
Thanks for any help.

A: If $(X,\langle,\rangle)$ is an inner product space, then for all $x,y\in X$,
$$|\langle x,y\rangle|\leqslant \sqrt{\langle x,x\rangle}\cdot \sqrt{\langle y,y\rangle}$$
and there is equality if and only if $x=\alpha y$ for some scalar $\alpha$.


text:
Q: Writing a program for days in months So I'm trying to write a code where whatever number of the month it is, it returns me the number of days there are in this month. Here is the code I have written at the moment. I got some of the months right but the rest aren't. Can someone point out what I did wrong with the coding?
def get_days_in_month (month):
    if (month == 2):
        return 28
    elif (month == 4 + 6 + 9 + 11):
        return 30
    elif (month == 1 + 3 + 5 + 7 + 8 + 10 +12):
        return 31
    else:
        return 31

A: Better idea:
Use python's built in calculator. Use monthrange and pass in (int) of year and month

monthrange(year,month): Returns weekday of first day of the month and number of days in month,
  for the specified year and month

from calendar import monthrange

def get_days_in_month (year,month):
    month_data= monthrange(year, month)
    # If you only want DAYS, use month_data[1]
get_days_in_month(2018,1)

A: You are adding the numbers 4, 6, 9, 11. You can instead test to see if month equals one of those by using the in keyword and a list:
def get_days_in_month(month):

    if (month == 2):
        return 28
    elif (month in [4, 6, 9, 11]):
        return 30
    else:
        return 31


text:
Q: React cookie integration with spring I have a website, backend is in spring, frontend is in React. I save a cookie on backend using
Cookie cookie = new Cookie("userId", testDTO.getId());
userCookie.setPath("/");
response.addCookie(userCookie);

But when react posts request on the controller, my browser doesnt get that cookie. Storage in firefox is just empty.
Frontend code:
const requestOptions = {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                name: username,
                stayLogged: false
            })
        };

       fetch('http://localhost:8080/health-check/post',requestOptions)
           .then(response => response.json())
           .then(data =>{console.log(data);})

A: I fixed it. Just added to the post mapping in the controller
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")


text:
Q: Triangle and parametric coordinates I'm studying on a book where it says: "A triangle is the set of points

where for some point po, where u and v range over the parametric coordinates (we are talking about barycentric coordinates here) of the triangle"
I don't understand this statement. How come that each point in a triangle surface can be expressed as the expression above?

A: Figured out: p0 is a point inside the triangle, u and v are the barycentric coordinates that are "weights" to use dp/du and dp/dv that represent how much does the surface vary in both directions (they're vectors since p is the barycentric equation for the triangle). u and v are b1 and b2 since b0 = 1 - b1 - b2 (barycentric coords sum to 1)


text:
Q: Update multi nested mongoDB schema This is my model schema
{
"_id" : ObjectId("59999454bad567268f78dc09"),
"chapters" : [
    {
        "_id" : ObjectId("59999454bad567268f78dc0a"),
        "individualChapters" : [
            {
                "_id" : ObjectId("59999454bad567268f78dc0b"),
                "photos" : [
                    {
                        "_id" : ObjectId("59999454bad567268f78dc0c"),
                        image: ObjectId("599993e980c3ba2681639163")
                    },
                    {
                        "_id" : ObjectId("59999595bad567268f78dc12"),
                        image: ObjectId("599993e980c3ba2681639163")
                    }
                ]
            },
            {
                "_id" : ObjectId("5999957dbad567268f78dc10"),
                "photos" : [
                    {
                        "_id" : ObjectId("5999957dbad567268f78dc11"),
                        image: ObjectId("599993e980c3ba2681639163")
                    }
                ]
            }
        ]
    }
]

}
i am trying to push another element in "photos" of second "individualChapters" using the below query, but its always pushing in "photos" of first "individualChapters".
Model.findAndModify(
{
    'chapters.individualChapters._id' : ObjectId("5999957dbad567268f78dc10"),
    'chapters._id' : ObjectId("59999454bad567268f78dc0a"),
    _id: ObjectId("59999454bad567268f78dc09")
},
{
    '$push': {
        'chapters.0.individualChapters.$.photos': {
            image: ObjectId("599993e980c3ba2681639163")
        }
     }
}, { new: false, upsert: false })

Its always updating first individualChapters. Please help!!

A: You are referring to the wrong element. $push should have this
chapters.0.individualChapters.1.photos.0._id like this

A: Here's what works in your specific case.
Model.findAndModify(
{
    'chapters.individualChapters._id' : ObjectId("5999957dbad567268f78dc10"),
    'chapters._id' : ObjectId("59999454bad567268f78dc0a"),
    '_id': ObjectId("59999454bad567268f78dc09")
},
{
    '$push': {
        'chapters.0.individualChapters.1.photos': {
            'image': ObjectId("599993e980c3ba2681639163")
        }
    }
}, { new: false, upsert: false })


text:
Q: How to sum several thrust vector on a single object (like a plane) I'm a developer. I tried (mostly for fun) to create a realistic physic engine.
I try to sum all forces (here thrust) applying to an object in two composantes: an acceleration vector and the angular acceleration.
I read a lot about torque and thrust but there is still some stuff that I can't figure out.
Let's take a exemple: Imagine a plane(or space craft) with two motors each placed at the opposite side with respect to the center of gravity. If they have equals thrust I figure that I can modelise them by a single thrust vector placed on the center of gravity equals to the sum of the thrust provide by the two engines. Is that right?
What's happen if one motor delivered 10% less thrust that the other one, how my thrust decrease, how to compute resulting torque ?
Did I loose or gain efficiency if my thrusters are placed at the back of the plane and why?
I try to find a mathematic model that could work with any number of thruster placed at different position of the air-craft.

A: You need to model total thrust and inertia, as well as angular thrust (torque) about the center of mass and angular inertia.
For example, suppose you have two engines, each five meters left and right of the centerline, and the one on the left exerts a thrust of 90 newtons while the other one has a thrust of 110 newtons.
Then you have a total thrust of 200 newtons,
but the torque from the left engine is 90*5 newton-meters tending to turn to the right, while the other engine has torque of 110*5 newton-meters in the opposite direction,
for a total torque to the left of 20*5 newton-meters.
How fast that makes it turn depends of the angular moment of inertia about the vertical axis.
To model angular inertia, it's easiest if you model a moment of angular inertia about each of the principal axes. For example, a long slender cylinder would have a small moment of angular inertia about it's long axis, but a larger moment about each of the other two axes.
Then, determine the torque about each axis.
If you have an engine whose thrust vector does not go through the center of mass of the vehicle, then it passes it at some distance.
You can determine that distance by dropping a perpendicular line segment from the center of mass to the thrust vector.
The length of that line, times the intensity of the thrust vector, gives you the torque, which is also a vector.
You add these up over all the forces acting on the vehicle.
Then you resolve that torque vector onto each of the principal axes, and together with the angular moment of inertia on each axis, you get an angular acceleration rate on each axis.
Then you use your ordinary differential equation solver (you're probably using Euler) to see how the vehicle motion evolves.
You're going to need to study up on moment of inertia and angular momentum.