text:
Q: getting selenium error - disconnected: received Inspector.detached event using chrome driver version 2.20.x When my script is trying to sendkeys for username after opening login page, I am getting disconnected: received Inspector.detached event error.

Console details:

SaveReport FAILED: SaveSearche org.openqa.selenium.WebDriverException:
  disconnected: received Inspector.detached event   (Session info:
  chrome=49.0.2623.110)   (Driver info: chromedriver=2.20.353145
  (343b531d31eeb933ec778dbcf7081628a1396067),platform=Windows NT 6.1 SP1
  x86_64) (WARNING: The server did not provide any stacktrace
  information) Command duration or timeout: 334 milliseconds Build info:
  version: '2.42.2', revision: '6a6995d', time: '2014-06-03 17:42:03'
  System info: host: 'jp-anal-l01', ip: '182.178.5.177', os.name:
  'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version:
  '1.7.0_79' Session ID: b963137ae8a484c47efd3ac0984ea6b3 Driver info:
  org.openqa.selenium.chrome.ChromeDriver Capabilities [{platform=XP,
  acceptSslCerts=true, javascriptEnabled=true, browserName=chrome,
  chrome={userDataDir=C:\Users\ANJH1.NA\Temp\dir10584}, rotatable=false,
  locationContextEnabled=true, mobileEmulationEnabled=false,
  version=49.0.2623.110, takesHeapSnapshot=true,
  cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=true,
  browserConnectionEnabled=false, nativeEvents=true,
  webStorageEnabled=true, hasTouchScreen=false,
  applicationCacheEnabled=false, takesScreenshot=true}]     at
  sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown
  Source)   at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
  Source)   at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at
  org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
    at
  org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
    at
  org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
    at
  org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
    at
  org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:89)
    at com.demoProject.loginAllTime(TestSuiteTestCases.java:99)   at
  com.demoProject.TestCases.SaveSearch(TestSuiteTestCases.java:317)   at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   at
  sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)   at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)   at
  java.lang.reflect.Method.invoke(Unknown Source)   at
  [snip]
    at org.testng.TestRunner.privateRun(TestRunner.java:767)    at org.testng.TestRunner.run(TestRunner.java:617)
  [snip]
  org.testng.TestNG.run(TestNG.java:1057)   at
  com.demoProject.executeTestCase(TestSuiteTestCases.java:99)     at
  com.demoProject.initialize(TestSuiteTestCases.java:56)    at
  com.demoProject.executeModules(TestSuiteTestCases.java:142)   at
  com.demoProject.main(TestSuiteTestCases.java:98)

A: Without having the actual test code, my best guess is that com.demoProject.loginAllTime(), which is calling sendKeys(), must be sending either Ctrl-Shift-I, or Ctrl-Shift-J, or Ctrl-Shift-C, each of which will open the Chrome DevTools on Windows.
As mentioned in the comments, if DevTools is opened during a WebDriver run, ChromeDriver will be automatically disconnected, producing the error:

received Inspector.detached event

It doesn't seem to be possible to get that error any other way.

A: This is about chrome issue(https://bugs.chromium.org/p/chromedriver/issues/detail?id=1194).
When you are running selenium program, you cannot press F12 to open dev tools manually, or it'll throw this exception sometimes.
According to the issue list, it looks like fixed, but I still meet this bug in ChromeDriver 2.29

A: Check if Chrome->Developer Tools are enabled.


text:
Q: Mysql insisting on putting weird non-breaking space characters inside my empty textareas I have an admin that is almost completely ajax driven. When the page loads it will already have the values from the database populated in the textareas with a trim() wrapped around the values for good measure. When you save it, it gets serialized into an array and posted to an ajax handling script—the feedback is returned as JSON and if no other elements have been edited and left unsaved, the page is made to reload. I have UTF-8 enforced on every step of the process. The database and the table and the connection collation are utf8_general_ci, the meta tag enforces UTF-8, the json is returned with a Content-Type: application/json; charset=utf8 header.
If I put a htmlspecialchars() around my output before inserting it into the textarea, those non-breaking space characters are converted into  s.
I have about four or five textareas that look and behave exactly the same, they get the exact same treatment and yet, when I load the page, there is always the same two fields that get that weird non-breaking space injected.
When a new row is added through phpMyAdmin, it doesn't seem to suffer from these extra spaces when viewed in phpMyAdmin, but when I open the same row in my admin, the spaces are there. Rows that have been saved in my admin, in phpMyAdmin will show something like  or a simple, normal space at times. Either way, on the front end, in the final output nothing shows up garbled. If i put any kind of text in the textarea instead of the space and save, everything works as expected, no extra spaces appear, it only seems to happen when there is nothing in the space...
A stopgap method for handling this would be to not output from db into the textarea if the htmlspecialchars($row['Val']) = ' ' but that seems like a hack rather than a solution build upon an understanding of the situation.

A: I AM STUPID. Christ, in convoluted oop structure I had done a stupid thing that caused this to keep happening. Sorry to waste your time! Can we delete this question?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Display:none and DOM if display: none removes element from the DOM, why I am able to see it in dev-tools inspector or access via document.getElementBy? It should be somehow one way road. If we removes element via display: none, it should not be present anywhere. How should I understand "removing from DOM"?

A:
if display: none removes element from the DOM

It doesn't. It causes it to render as if it were not in the DOM.
From MDN:

Turns off the display of an element so that it has no effect on layout (the document is rendered as though the element did not exist). All descendant elements also have their display turned off.

A: If you actually want to remove an element from the DOM, you can use Javascript:
myElementParent.removeChild(myElement);

or:
myElement.remove();

Further Reading:

*

*https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild

*https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove

But, in CSS, the following property-value pairs:

*

*display: none;

*visibility: hidden;

*opacity: 0; pointer-events: none;
all represent approaches to remove visibility and interactivity from an element which remains in the DOM.
The key difference between the first of these and the latter two is that display: none; also removes the space that would otherwise be occupied by the element.

A: display:none does not remove the element from the DOM, it only hides the element but it will still be there
you need to use the remove method in javascript like this yourElement.remove(); to actually remove it from the DOM


text:
Q: Finding the expected value of running time with if statement I was working on a problem to find the average case of a for loop that has a 1 step in it. The each element in the input array has a distribution of {0...i} where i is the index of the element.
What threw me off was that, in the for loop there is an if statement that would prematurely end the for loop and this "if statement" would be executed if the value of the array was 50.
The Psuedocode looks somewhat like this:
for i from 0 to n-1:
     do something
     if L[i] == 50:
         do something, and break

and the input of the array are distributed like this:
L[0] = {0}
L[1] = {0, 1}
L[2] = {0, 1, 2}
L[i] = {0, 1, 2, .., i}

With duplicates being allowed and they're independent.

I already realized that there really was no need to look at the summation before index 50 of the array. Further more, the probability of not getting the value of the array was quite obviously i/i+1, however with this being said I do not know how to fully use the expected value theorem to get the expected running time of the program.
I would just like a little tip to get me on track. I feel like im really close to solving this but yet so far, thank you


text:
Q: How to change color of button text in popover in ionic 4 I am trying to change the text color on the button when the user has made the selection from a popover, so that when the user opens the popover again the previous selection is highlighted...It's for a filter list, user selects filter values desc or asc or by name, etc.
in my html file I have 3 buttons:
<ion-button class="btn1" (click)="sortList('Desc', 'secondary')" fill="clear" [color]="(colorSelect==='secondary')"? 'secondary':'tertiary'">Desc</ion-button>
<ion-button class="btn2" (click)="sortList('Desc', 'secondary')" fill="clear" [color]="(colorSelect==='secondary')"? 'secondary':'tertiary'">Desc</ion-button>
<ion-button class="btn3" (click)="sortList('Desc', 'secondary')" fill="clear" [color]="(colorSelect==='secondary')"? 'secondary':'tertiary'">Desc</ion-button>

in my Component file:
colorSelect: string = '';

public sortList(sortType, item: string){
    this.popoverController.dismiss(sortType);
    this.colorSelect = item;
}

How would you keep that item selected after the popover has closed so that when the popover is opened again, the item would be hightlighted?

A: Since popover uses a component that gets destroyed after popover is closed you need to leverage a service that popover component can import and use as source of truth for the button colors.
Very roughly:
https://stackblitz.com/edit/ionic-angular-v5-xfe357
At a high level:
service.ts:
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class SharedService {

  public filters;

  constructor() {
    this.filters = ["secondary","secondary","secondary"]
  }

}

popover.ts:
import { Component } from '@angular/core';
import { PopoverController } from '@ionic/angular';
import { SharedService } from './shared.service';

@Component({
  selector: 'hello',
  template: `
Hello!

  <ion-list>
      <ion-button class="btn1" (click)="sortList(0, 'Desc', 'secondary')" fill="clear" [color]="sharedService.filters[0]">Desc</ion-button>
      <ion-button class="btn2" (click)="sortList(1, 'Desc', 'secondary')" fill="clear" [color]="sharedService.filters[1]">Desc</ion-button>
      <ion-button class="btn3" (click)="sortList(2, 'Desc', 'secondary')" fill="clear" [color]="sharedService.filters[2]">Desc</ion-button>
  </ion-list>
  `
})
export class HelloComponent  {

  constructor(private sharedService: SharedService, private popoverController: PopoverController) {

  }

  sortList(buttonIndex, sortType, item: string){
    if (this.sharedService.filters[buttonIndex]==="secondary") {
      this.sharedService.filters[buttonIndex]="tertiary";
    } else {
      this.sharedService.filters[buttonIndex]="secondary";
    }
    this.popoverController.dismiss(sortType);
  }
}

So your main component from which you call popover should also import such service (and inject it) and leverage data from it as single source of truth.


text:
Q: C++ Recursive Variadic Lambda In C++ we can have a recursive variadic template function. For example:
template<typename ...H>
void g(){}
template<typename H, typename ...T>
void g(H h,T ...t){
    std::cout << h << "\t";
    g<T...>(t...);
}

However this does not seem possible to be done using lambdas. My two main main concerns are:

*

*How to establish a base-case.

*How to make a lambda be recursive and at the same time variadic.

I know I can have recursive lambdas but can't see a way to make it variadic.
Is this type of feature only available in more high-level kind of languages such as Javascript?
Edit:
So far, this is what I have come up with:
template<typename C,typename H, typename ...T>
std::function<void(C,H,T...)> f=[](auto&&  self,H h,T ...t){
    std::cout << h << "\t";
    if(sizeof...(t)>0)
        self(self,t...);
};

Here the first argument would be the lambda itself.
However, the main issue is that in order to call this method I would to have define the type C, which I'm unsure on how to do (or even if it's possible).
Edit:
A more simplistic approach would be:
auto f = [] (auto&&  self, auto&& h,auto&&... t) {
    std::cout << sizeof...(t) << "\n";
    if( sizeof...(t)>0 ){
        self(self,1);
    }
};

int main()
{
    f(f,1,2,3,4,5,6);
    return 0;
}

However gives the following error:
main.cpp:55:13: error: use of ' [with auto:1 = &; auto:2 = int; auto:3 = {}]' before deduction of 'auto'
     self(self,1);
         ^

A: C++17 solves this problem with Constexpr if:
#include <iostream>

auto f = [](auto&&... t){
    auto f_impl = [](auto& self, auto&& h, auto&&... t) {
      std::cout << sizeof...(t) << "\n";
      if constexpr ( sizeof...(t)>0 ){
        self(self,t...);
      }
    };
    return f_impl(f_impl, t...);
};

int main() {
    f(1,2,3,4,5,6);
}

I also took the liberty of wrapping the first parameter(self) inside a "parent" lambda.
The problem with using if(sizeof...(t)) as a guard is that, even if you will not call the lambda with improper arguments at runtime, the compiler still needs to compile the expression self(self, t...) with sizeof...(t)==0, which fails.
constexpr if solves this by making this check at compile-time, and not even compiling the block when the check yields false. Before C++17, conditional compilation semantics(excluding macros) could only be achieved using SFINAE or template specialization, both of which can't be done using only lambdas.

A: I hate helpers, i think using helpers is a misleading design. That said, i couldn't find a solution to this without using a small helper.
The obstacles encountered here are the following:

*

*You cannot refer to a variable declared with auto within it's own initialisation expression
This is solved by passing the function as a parameter to itself using an inner lambda to provide a clean public interface

*You cannot use if( sizeof... ) as a guard (or any other "runtime" mechanism) for the "base-case" because you would still have a call to a function that cannot accept that number of parameters within that if block, which doesn't compile
This is solved by "overloading the lambda" and actually defining all the needed function overloads (i.e the "base-case" also)

*You cannot "simply" overload a lambda once it is defined
This is solved by using a "small" helper code
All in all, one solution could be this:
#include <iostream>

/////////// Helper

template<class F, class... Fs>
struct overloaded : F, overloaded<Fs...>
{
  using F::operator();
  using overloaded<Fs...>::operator();

  overloaded(F&& f, Fs&&... fs)
    : F(std::move(f))
    , overloaded<Fs...>(std::move(fs)...)
  {}
};

template<class F>
struct overloaded<F> : F
{
  using F::operator();

  overloaded(F&& f)
    : F(std::move(f))
  {}
};

template<class... Ts>
overloaded<Ts...> overload(Ts&&...lambdas)
{ return overloaded<Ts...>{std::move(lambdas)...}; }

///////// Recursive Variadic Lambda

int     main(void)
{
  auto lambda = [](auto... args)
    {
      auto lambda_impl = overload(
        [](auto self)
        {
        },
        [] (auto self, auto first, auto...rest)
        {
          std::cout << first << std::endl;
          self(self, rest...);
        });

      lambda_impl(lambda_impl, args...);
    };

  lambda(4, "lol", 8.3);
}


text:
Q: Excel: Finding row count between two specific values I need to indicate in column B the number of rows between where "Criteria Matched" is found in Col D and where "TRUE" is found in Col C.
Criteria Matched and True can occur multiple times, I am looking for the row count distance between the first True and Criteria matched, then the distance between the next two.. etc.
Any ideas? I am a VBA and Excel noob.

A: If both search terms occur only once in their respective columns, try
=match("Criteria Matched",D:D,0)-match(TRUE,C:C,0)

A: To expand upon the previous answer to account for multiple occurrences, you can put this formula in B1 and copy down as needed: =IF($C1=TRUE,MATCH("Criteria Matched",$D2:$D$300,0)-1,""). This gives a count of rows "between" the two values where  "TRUE" is followed by "Criteria Matched" as you stated. If you really meant rows "until", remove the -1 from the formula.
If you need a count between when any one follows the other, then this in B1: =IFERROR(IF($C1=TRUE,MATCH("Criteria Matched",$D2:$D$300,0)-1,IF($D1="Criteria Matched",MATCH(TRUE,$C2:$C$300,0)-1,"")),"")


text:
Q: How to separate javascript and markup in case of a script line with parameters? Separating javascript and markup is easy when the script doesn't have parameters. But how is it done with inline script lines that do? Example:

    <input type="radio" name="action-type" id="change-add" value="change-add"
    onclick="showSelectTables('none','none','none','table','none','none')">

(....)

.
I've tried all varieties I can think of, but all I'm getting is error reports, 'undefined' or the silent treatment from the browser. Is it possible at all, and if so, how? I would be looking for a vanilla javascript solution.
EDIT: see here for what I'm trying to achieve: http://en.wikipedia.org/wiki/Unobtrusive_JavaScript, section 2.

A: I suggest you to change your HTML generation logic to generate the followings:

    <input type="radio" name="action-type" id="change-add" value="change-add" />

Note: this assumes you use jQuery.

An important note: there is nothing wrong to use inline onclick, but it's a better pattern to separate JS and HTML


text:
Q: web service address for Jenkins on AWS Windows installed as a Windows Service I have just installed Jenkins (as a Windows Service) on AWS Windows (Win Server 2012R2) instance.
I'm able to launch it via browser using http://localhost:8080
What url should I use to access this server from other client? I have tried http://:8080 or without the port number but my client (over the net) is failing to connect. The Public DNS of the AWS is also not working.
I set up another Jekins on AWS Ubuntu server with apache tomcat and it's connecting just fine using the Public DNS of the AWS Ubuntu server.


text:
Q: How can I adjust the Bootstrap column grouping? I have a column of content where I'm trying to stack them one after each each other, and this is happening because of the float, so I've included a clearfix, but it's not working.
Code Example:

Title

sub-title

Information

Title

sub-title

Information

sub-title

Information

Title

sub-title

Information

Title

sub-title

Information

sub-title

Information

This is an image example of what I'm after:

A: When you're nesting columns you still need to use rows with the interior column structure just like at any other time.
Also, this (col-md-6 col-sm-6) type of column structure is redundant. You'll see the same results if you use col-md-6 col-sm-6 or col-sm-6; both will collapse at 768px which means the col-md-6 won't be used. Use one or the other depending on which viewport width you want the columns to collapse at. See this post for additional info.
See examples.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

Standard Columns

Title 1
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College i

Sub-Title 1
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College iContrary to
            popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College i

Information 1
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College iContrary to
            popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College i

Title 2
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
            book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
            with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Sub-Title 2
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
            book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
            with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
            when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the
            1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Information 2
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College iContrary to
            popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College i

Redundant Columns

Title 1
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College i

Sub-Title 1
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College iContrary to
            popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College i

Information 1
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College iContrary to
            popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College i

Title 2
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
            book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
            with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Sub-Title 2
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
            book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
            with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
            when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the
            1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Information 2
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College iContrary to
            popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College i

Mobile, tablet, desktop Columns

.col-xs-12 .col-sm-6 .col-md-8

.col-xs-6 .col-md-4

.col-xs-6 .col-sm-4

.col-xs-6 .col-sm-4

.col-xs-6 .col-sm-4


text:
Q: Understanding Variations of the Genetic Algorithm I am working with the R programming language. I am trying to learn about different optimization algorithms such as the "Genetic Algorithm" (e.g. https://cran.r-project.org/web/packages/GA/vignettes/GA.html, https://cran.r-project.org/web/packages/GA/index.html) vs. the "Evolutionary Grammar Algorithm" (e.g. https://cran.r-project.org/web/packages/gramEvol/gramEvol.pdf , https://www.jstatsoft.org/article/view/v071i01).
For instance, I can use the Genetic Algorithm to optimize the following function ("Rastrigin") :
#PART 1: Optimize Rastrigin Function with the Genetic Algorithm

        library(GA)

    #define function
    Rastrigin <- function(x1, x2)
    {
      20 + x1^2 + x2^2 - 10*(cos(2*pi*x1) + cos(2*pi*x2))
    }

    #plot

    x1 <- x2 <- seq(-5.12, 5.12, by = 0.1)
    f <- outer(x1, x2, Rastrigin)
    persp3D(x1, x2, f, theta = 50, phi = 20, col.palette = bl2gr.colors)

    #run optimization algorithm and plot results

    GA <- ga(type = "real-valued",
             fitness =  function(x) -Rastrigin(x[1], x[2]),
             lower = c(-5.12, -5.12), upper = c(5.12, 5.12),
             popSize = 50, maxiter = 1000, run = 100)

    plot(GA)

    summary(GA)

    Fitness function value = -2.502466e-07
    Solution =
                   x1           x2
    [1,] 3.341508e-05 1.203355e-05

Now, I am using the "Evolutionary Grammar Algorithm" to optimize the same function:
#PART 2: Optimize Rastrigin Function with the Evolutionary Grammar Algorithm:

    library(gramEvol)

    ruleDef <- list(expr     = gsrule("<der.expr><op><der.expr>"),
                    der.expr = grule(func(var), var),
                    func     = grule(log, exp, sin, cos),
                    op       = gsrule("+", "-", "*"),
                    var      = grule(x1, x2, n),
                    n        = grule(1, 2, 3, 4))

    # Creating the grammar object
    grammarDef <- CreateGrammar(ruleDef)

    #redefine the same function in a format acceptable to the
    # "gramEvol" library

    Rastrigin  <- function(expr) {
      # expr: a string containing a symbolic expression
      # returns: Symbolic regression Error
      x1 <- c(5.12, 5.12)
      x2 <- c(5.12, 5.12)

      result <- eval(as.expression(expr))

      err <- 20 + x1^2 + x2^2 - 10*(cos(2*pi*x1) + cos(2*pi*x2))

      return(err)
    }

    #run optimization
    ge <- GrammaticalEvolution(grammarDef, Rastrigin  ,
                  terminationCost = 0.001)

    # print results
    print(ge, sequence = TRUE)

    There were 50 or more warnings (use warnings() to see the first 50)

    Grammatical Evolution Search Results:
      No. Generations:  675
      Best Expression:  log(1) + x2
      Best Cost:        57.8494274515718

Question: Can someone please tell me if I have done PART 2 correctly? For some reason, I don't think that PART 1 and PART 2 produced the same answer, nor did they attempt to even solve the same problem. PART 1 actually returns a coordinate of "x1 and x2" that corresponds to the minimum point of the Rastrigin function, whereas I am not sure what the output of PART 2 corresponds to. Is it possible that the "grammatical evolution algorithm" is not a good choice for this problem? Apparently the "grammatical evolution algorithm" is said to work well when the optimization problem has "logical constraints" that can not be specified in the traditional way that "optimization constraints" are usually specified. Is this true?
Source: https://rdrr.io/cran/gramEvol/man/GrammaticalEvolution.html


text:
Q: Passing variables from js to php using ajax I have this form
<form name="main" id="main" class="form-horizontal" method="post">

      Enter Value

        <input type="text" class="form-control" name="value" id="value" placeholder="Enter value">

      Result

        <input type="text" class="form-control" name="result" id="result" placeholder="result" value="">

        <button type="submit" class="btn btn-default" id="Convert" name="Convert" value="Convert">Submit</button>

</form>

and the jquery file is:
$( document ).ready(function() {
  console.log("ready");
  $('#main').submit(function(e){
    e.preventDefault();

     $.ajax({
        type: "GET",
        url : "index.php",     //your processing page URL instead of ???
        data: "&example=2",
        success: function(){
          alert("success");
          $("#result").html("Example content");
        }
     });
  });
});

I want to display the example content string on the #result field when the form submits. It seems simple but I have tried everything and nothing works. I get no http and console errors and the alert shows "success"

A: You are making a mistake when you are writing $("#result").html("Example content"); because it is a input not an element holder.
Change your code to
$('#result').val("Example Content");


text:
Q: Ubuntu from a flash drive, where do files get stored? I'm a total newb to Ubuntu (Linux in general, tbh) and I'd like to try out Ubuntu by running it from a flash drive. Now my question is: Do my files (both installation and 'personal' files (like texts, for example)) store on my flash drive or on my hard disk?

A: If - when you created the flash drive - you granted space for personal files, Ubuntu will save your personal files up to that limit on the flash drive.
If you didn't, you will have to store them separately.

A: Your personal files will be saved in the USB drive in a file named casper.rw. It will be used by the Live Ubuntu session.

A: you can create a persistence file when you create the live ubuntu disk. Follow this procedure and slide to the right the bar "How much..." until reach the space you want to use. Next time you boot the files will remain where you saved them.


text:
Q: How can i create a new worksheet and save it there whenever the date changes its month in EPPlus I have a column named datein which has dates in it. The question is how can i create a new worksheet and save it there whenever the date changes its month. A new month new worksheet.
all I have right now is my code for saving into excel using epplus.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();

        using (MySqlConnection con = new MySqlConnection(connectionString))
        {
            using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM statusrouted.routed", con))
            {
                cmd.CommandType = CommandType.Text;
                using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
                {
                    using (DataTable dt = new DataTable())
                    {

                        using (ExcelPackage pck = new ExcelPackage())
                        {
                            sda.Fill(dt);

                            ExcelWorksheet ws = pck.Workbook.Worksheets.Add(DateTime.Today.ToString("MMMM-yyyy"));

                            ws.Cells.Style.Font.Size = 11;
                            ws.Cells["B1:K1"].Merge = true;
                            ws.Cells["B1"].Value = "INCOMING AND OUTGOING ROUTED COMMUNICATIONS";
                            ws.Cells["B1"].Style.Font.Size = 12;
                            ws.Cells["B1"].Style.Font.Bold = true;
                            ws.Cells["B1"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                            ws.Cells["B1"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                            ws.Cells["A2"].LoadFromDataTable((this.maindgv.DataSource as DataTable).DefaultView.ToTable(), true);

                            ws.DeleteColumn(1);

                            saveFileDialog1.Title = "Save as Excel";
                            saveFileDialog1.FileName = "";

                            saveFileDialog1.Filter = "Excel files(2007)|*.xlsx";

                            if (saveFileDialog1.ShowDialog() != DialogResult.Cancel)
                            {
                                try
                                {
                                    pck.SaveAs(new FileInfo(@""+ saveFileDialog1.FileName));
                                    recentsToolStripMenuItem1.AddRecentItem(@"" + saveFileDialog1.FileName);
                                }
                                catch (Exception)
                                {
                                    DialogResult reminder = MessageBox.Show("Cannot save file, file opened in another program.\nClose it first! ", "Save Failed", MessageBoxButtons.OK);
                                }
                            }
                        }
                    }
                }
            }
        }

A: How the logic will work is as given below

Follow these steps
var dateGroups  = dt.AsEnumerable().GroupBy(row => row["ColumnName of Date Time"]);
foreach (var group in dateGroups)
{
 // the group.Key will give the Date on the basis of which you can create sheets.
// and then your logic of excel
  foreach (var rows in group)
  {
   // excel filling logic
  }
}


text:
Q: Find Deployment which contains specific image I got an overview about all unique running images in my Kubernetes cluster via https://kubernetes.io/docs/tasks/access-application-cluster/list-all-running-container-images/#list-all-container-images-in-all-namespaces
Now I found one image - for example mysql:5.7 - running in my Cluster.
How can I find out now which Deployment actually deploys this image?


text:
Q: circle in complex plane I'm trying to figure out the following set:
$|z+i| = 2|z|$.
My approach was to use the triangle inequality as follows:
$2|z| = |z+i| \leq |z| + |i| = |z| + 1$.  This should imply that
$|z| \leq 1$, but this is nowhwere near the solution.

A: Hint. The given condition means that the distance from $z$ to $(-i)$ is twice the distance from $z$ to $0$. It is well known that the locus of points having a given ratio of distances to two given points is a circle. Such circles are called Apollonian circles. See e.g. this article at cut-the-knot.org.

A: Observe
\begin{align}
|z+i|^2=4|z|^2.
\end{align}
Since we have that
\begin{align}
|x+iy+i|^2=x^2+(y+1)^2 = 4x^2+4y^2=4|z|^2
\end{align}
which means
\begin{align}
3x^2+3\left(y^2-\frac{2}{3}y+\frac{1}{9}\right)-\frac{1}{3}=3x^2+3y^2-2y=1 \ \ \ \Rightarrow \ \ \ 3x^2+3\left(y-\frac{1}{3} \right)^2 = \frac{4}{3}.
\end{align}

A: Let $z=x+iy$, $|z|=\sqrt{x^2+y^2}$
$$x^2+(y+1)^2 = 4x^2+4y^2$$
$$3x^2+3y^2-2y-1=0$$
$$x^2+(y-\frac{1}{3})^2=(\frac{2}{3})^2$$
$$|z - (0+\frac{1}{3}i )| =|z-\frac{1}{3}i |=\frac{2}{3}$$
It is a circle.

A: $|z+i|^2 = (2|z|)^2$
$z = x + i y$
$x^2 + (y+1)^2 = 4x^2 + 4y^2$
$3x^2 + 3y^2 - 2y -1 =0$
$x^2 + y^2 -\frac{2}{3}y - \frac{1}{3} = 0$
It is form of a circle if we compare it with the general equation $x^2 + y^2 + 2gx + 2fy + c =0$ whose center is $(-g,-f) = (0,\frac{1}{3})$  and radius of $\sqrt{g^2 + f^2 -c} = \sqrt{4/9} = \frac{2}{3}$.
You see that as per your approach too here $|z| < 1$.
More on properties and general equations of circles - http://mathscentre.ac.uk/resources/workbooks/mathcentre/mc-TY-circles-2009-1.pdf

A: Here |z+i|=2|z|.
Let us assume z=x+iy.
thus |x+i(y+1)|=2|x+iy|.
(x^2+(y+1)^2)^(1/2)= 2(x^2+y^2)^(1/2).
x^2 + y^2 +2y +1= 4(x^2+y^2).
3(x^2+y^2)-2y-1=0. Which is an equation of circle in complex plain with centre(0, 1/3) and radius 2/3.


text:
Q: Create and throw exceptions based upon names I have a list of exceptions (with package name path: com.a.b.ExceptionA) and error codes map.
Now, user will call new ApiException(errorcode,"message"), or   new ApiException(errorcode,"message", Throwable t). Then, inside BaseException, I want to create ExceptionA,B based upon errorcode and throw it.
I can look up the map and get the exception type path, but how to create the exception and throw it? So some thing like below? or any better approach?
Class<?> c = Class.forName("com.a.b.ExceptionA");
Constructor<?> cons = c.getConstructor(String.class);
Object object = cons.newInstance("message");
throw object;

Thanks!


text:
Q: max() just checks first value in a list/tuple for multiple lists/tuples? max((12,1),(1,),(2,1,2) : So is it a wrong format to check which tuple is the greatest respective to the number of values in the tuple?
Because only the first value of each tuple is considered in this case.

A: If you want to treat the longest tuple as the maximum, you need to specify a different key function:
>>> max((12,1),(1,),(2,1,2), key=len)
(2, 1, 2)

By default, tuples are compared lexicographically, meaning the second element of two tuples is only considered if the first elements are equal. (The empty tuple is less than or equal to any other tuple.)


text:
Q: Safari on IPad 2 input file strange behavior I have one <input id="foo" type="text"> and one <input type="file"> in a HTML page. I know that the input file is greyed in IPad 2 because it is not supported.
However what I find realy strange is that I can not set the value of "foo" e.g. document.getElementById("foo").value='something';
If I remove the input file, then everything works fine.
Is this a known issue/bug or am I missing something? I really find this a strange behavior.
Thanks in advance.


text:
Q: how to access the Json Responce dict value in the Html script My django views
def contact_otp(request):
        if request.method=="POST":
            data = {
        "data-token":f"{otp.token}"
    }
            #
            return JsonResponse(data)

.then((response) => response.json())
          .then((data) => {
            console.log(data)
            const newVarPass = document.createElement("input")
            newVarPass.setAttribute('id','varPassID')
            newVarPass.setAttribute('value',`${data}`)
            newVarPass.value=`${data}`
            newVarPass.style.display="none"
            document.body.appendChild(newVarPass)
            alert("Check your Email We have send you the otp")
            console.log(data)

          })

    x = document.getElementById("varPassID")
                console.log(x)
                console.log("Lets check")

How to get the values of the json keypair i want to have which is present in the json data i am always getting object object in the value now
updated console.log(data)

A: document.getElementById("varPassID").innerText = data.data-token

Reference: https://www.w3schools.com/jsref/prop_node_innertext.asp


text:
Q: Why UTF-8 fail on this encoding? I'm about to download a page encoded in UTF-8.
So this is my code:
using (WebClient client = new WebClient())
{
    client.Headers.Add("user-agent", Request.UserAgent);

    htmlPage = client.DownloadString(HttpUtility.UrlDecode(resoruce_url));

    var KeysParsed = HttpUtility.ParseQueryString(client.ResponseHeaders["Content-Type"].Replace(" ", "").Replace(";", "&"));
    var charset = ((KeysParsed["charset"] != null) ? KeysParsed["charset"] : "UTF-8");
    Response.Write(client.ResponseHeaders);

    byte[] bytePage = Encoding.GetEncoding(charset).GetBytes(htmlPage);
    using (var reader = new StreamReader(new MemoryStream(bytePage), Encoding.GetEncoding(charset)))
    {
        htmlPage = reader.ReadToEnd();
        Response.Write(htmlPage);
    }
}

so, it set UTF-8 for the encoding. But the downloaded title, for example, show in my screen as:
Sexy cover: 60 e più di "quei dischi" vietati ai minori

and not as:
Sexy cover: 60 e più di "quei dischi" vietati ai minori

somethings is wrong, but I don't find where. Any ideas?

A: The problem is that by the time you get the data it's already been converted.
When WebClient.DownloadString executes, it gets the raw bytes and converts them to a string using the default encoding. The damage is done. You can't take the resulting string, turn it back into bytes, and re-interpret it.
Put another way, this is what's happening:
// WebClient.DownloadString does, essentially, this.
byte[] rawBytes = DownloadData();
string htmlPage = Encoding.Default.GetString(rawBytes);

// Now you're doing this:
byte[] myBytes = Encoding.Utf8.GetBytes(htmlPage);

But myBytes will not necessarily be the same as rawBytes.
If you know what encoding to use beforehand, you can set the WebClient instance's Encoding property. If you want to interpret the string based on the encoding specified in the Content-Type header, then you have to download the raw bytes, determine the encoding, and use that to interpret the string. For example:
var rawBytes = client.DownloadData(HttpUtility.UrlDecode(resoruce_url));
var KeysParsed = HttpUtility.ParseQueryString(client.ResponseHeaders["Content-Type"].Replace(" ", "").Replace(";", "&"));
var charset = ((KeysParsed["charset"] != null) ? KeysParsed["charset"] : "UTF-8");

var theEncoding = Encoding.GetEncoding(charset);
htmlPage = theEncoding.GetString(rawBytes);


text:
Q: Is long polling possible in Google App Engine? I need to make application that needs to poll server often, but GAE has limitations on requests, so making a lot of requests could be very costly. Is it possible to use long polling and make requests wait for the maxium 30 seconds for changes?

A: We've tried implementing a Comet-like long-polling solution on App Engine, with mixed results.
def wait_for_update(request, blob):
    """
    Wait for blob update, if wait option specified in query string.
    Otherwise, return 304 Not Modified.
    """
    wait = request.GET.get('wait', '')
    if not wait.isdigit():
        return blob
    start = time.time()
    deadline = start + int(wait)
    original_sha1 = blob.sha1
    try:
        while time.time() < deadline:
            # Sleep one or two seconds.
            elapsed = time.time() - start
            time.sleep(1 if elapsed < 7 else 2)
            # Try to read updated blob from memcache.
            logging.info("Checking memcache for blob update after %.1fs",
                         elapsed)
            blob = Blob.cache_get_by_key_name(request.key_name)
            # Detect changes.
            if blob is None or blob.sha1 != original_sha1:
                break
    except DeadlineExceededError:
        logging.info("Caught DeadlineExceededError after %.1fs",
                     time.time() - start)
    return blob

The problem I'm seeing is that requests following a long-polling one, are getting serialize (synchronized) behind the long-polling request.  I can look at a trace in Chrome and see a timeline like this:

*

*Request 1 sent. GET (un-modified) blob (wait until changed).

*Request 2 sent. Modify the blob.

*After full time-out, Request 1 returns (data unmodified).

*Request 2 gets processed on server, and returns success.

I've used wireshark and Chrome/timeline to confirm that I AM sending the modification request to the server on a distinct TCP connection from the long-polling one.  So this snychronization must be happing on the App Engine production server.  Google doesn't document this detail of the server behavior, as far as I know.
I think waiting for the channel API is the best hope we have of getting good real-time behavior from App Engine.

A: Google AppEngine has a new feature Channel API, with that you have
a possibility to build a good realtime application.
Another solution is to use a third part comet server like mochiweb
or twisted with a iframe pattern.
Client1, waiting a event:
client1 --Iframe Pattern--> Erlang/Mochiweb(HttpLongPolling):

Client2, sending a message:
client2 --XhrIo--> AppEngine --UrlFetch--> Erlang/Mochiweb

To use mochiweb with comet pattern, Richard Jones has written a good
topic (on google: Richard Jones A Million-user Comet Application).

A: I don't think long polling is possible. The default request timeout for google appengine is 30 seconds.
In long polling if the message takes more than 30 secs to generate, then it will fail.
You are probably better off using short polling.
Another approach is to "simulate" long polling withing the 30 sec limit. To do this if a message does not arrive within, say 20 sec, the server can send a "token" message instead of a normal message, requiring the client to consume it and connect again.
There seems to be feature request (and its accepted) on google appengine for long polling


text:
Q: What are the grounds for refunding of Symmetra's teleporter? I have noticed for a while now that sometimes my teleporter will close on its own, and refund a portion of the meter to me.
What factors determine the refunding of a teleporter? What determines how much ultimate charge I receive from the refund?

A: It might require further testing but from my experience there are 2 things to take into account :

*

*As @Lyrion said when you have placed a teleporter while defending point A, and the point is taken, you get the refund. This is likely to prevent your teammates from being teleported on the wrong location (and you getting yelled at by them ^^).

*The ultimate percent you receive seems to be based on the number of people who have used the teleporter. I had a game where 3 people had used my teleporter and I was refunded with 50% ultimate bar. This seems logical to me as the teleporter has 6 charges.
The only thing I don't know is if the proximity of the teleporter with the taken point is taken into account. It might need to be tested by placing a teleporter near point B, let point A be taken and see if the teleporter is refunded.

A: Teleporters are refunded when either team's active spawn room changes. This is why you do not get a refund when the first point of Gibraltar is capped (neither team has spawn room changed), but you do for the subsequent checkpoints.
The amount of ultimate charge refunded is equal to [uses left]/6.


text:
Q: What does "beyond" mean? Sometimes it's really hard for me to understand what does a word of "beyond" mean.
In the movie Arrival the character of Amy Addams says:

I'm not so sure I believe in beginnings and endings. There are days
  that define your story beyond your life. Like the day they arrived.

The only guess I have is the second sentence means something like: There are days that affect your story even though you life hasn't began yet.

A: Google Dictionary

be·yond preposition & adverb

*

*at or to the further side of. "he pointed to a spot beyond the trees" synonyms:    on the far side of, on the other side of, further
  away than, behind, past, after, over More

*happening or continuing after (a specified time or event). "we can manage another two years, but beyond that the system is not viable"
synonyms: on the far side of, on the other side of, further away than,
  behind, past, after, over "beyond the trees" noun

*

*the unknown after death. "messages from the beyond"

I'd say "days that define your story beyond your life", means, outside of your life as if it could be viewed in its entirety from outside and examined. This examination would help you to understand and define your life.


text:
Q: AudioBufferSourceNode.start() fails on Safari ONLY when started with an offset I am trying to start playing a buffer at a particular offset sometimes. I have an object that I create like this:
var directSource = AudioContext.createBufferSource();

Later on, after initializing it, I call:
directSource.start();

That works on all browsers.
The user can skip around, so I might stop that sound, and reinitialize everything (it runs the exact same code as the first time, except that it is passed an offset) and call start with:
directSource.start(0, offset);

This works on Chrome and Firefox, but that particular line causes an InvalidStateError on Safari, both on my MacBookPro and on an iPhone.
If I replace that line with:
directSource.start();

Then I DO NOT get the error.
I tested the AudioContext and it is definitely in the "running" state.
I put a console.log() just before calling start() to make sure I am not inadvertently calling it twice.
Can anyone help diagnose why Safari won't start at an offset? Is there somewhere else I can look for a clue about what it doesn't like.
Thanks!

A: I think the problem you encounter is that Safari is extremely picky in this case. The offset parameter needs to be less than or equal to the duration of the AudioBuffer in Safari.
The Web Audio spec says "offset is silently clamped to [0, duration]". (https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-start-when-offset-duration-offset) But Safari is throwing an error instead.
You can avoid that by making sure that you clamp the value yourself.
bufferSource.start(
    0,
    Math.min(bufferSource.buffer.duration, offset)
);

I'm the author of a package called standardized-audio-context. It does not yet have a fix for this but I already created an issue for it. The goal of this package is to provide a version of the AudioContext which works almost the same in every browser in this little bug should definitely be handled as well.


text:
Q: Building a custom API--needing a logic check I am in the planning and early coding stages of writing my first full-fledged API for a large scale we application.  I have used several APIs over the years but this is the first time I have been asked to construct something that will allow programmatic interaction on this level.
I have done quite a bit of research looking for best practices and such and have identified what I THINK will offer a fairly flexible response communication system.
My questions are:
Is this what you expect to see as API interaction?
Did I miss anything important?
Explanation of API:
I am going to be using HTTP Type 1 protocol for communication and a unique API key for authentication.
I am expecting this to come through CURL requests over an SSL connection.
Example of Successful (200 OK) XML Response (rate limit request):
<?xml version="1.0" encoding="UTF-8"?>
<node>
    <short_message>Request Complete</short_message>
    <long_message>Rate Limit Status Response</long_message>
    <response_data>
        <rate_limit>40</rate_limit>
        <rate_used>31</rate_used>
    </response_data>
</node>

Example of Failed XML Response (Will be sent under appropriate 400/500 Header);
<?xml version="1.0" encoding="UTF-8"?>
<node>
    <error_code>1201</error_code>
    <short_message>API Error</short_message>
    <long_message>The requested API version (1.5) is invalid</long_message>
</node>

Additionally I am setting up the error codes to be used in search-able documentation for easing the migraines of other developers.  Pass/Fail of request will be given through appropriate HTTP codes--Success (200), bad requests (400), method not found (404), authentication failed (403), etc...
I am also using version based endpoints so that any code changes will not require external code changes.
Finally devs will be able to request all responses in either XML, JSON, or PHP serialized arrays.
The internals of my code are very simple.  All data is passed through POST (probably using CURL or some alternative) including a unique API key.  That API key is linked to a user in the system which will then allow the internal methods to execute a limited set of functions that are enabled for that specific user.
I am following the API 'Golden Rule'--"Always add, never delete".
So..  what else should I consider and what have I missed?

A: Shane,
I am assuming your goal is to build a RESTful API - is that true?
My answer applies only if this assumption is true - I am not trying to criticize your design, just its RESTfulness.
REST defines 4 interface constraints which your design must adhere to in order to be RESTful. Your design violates at least three of them and hence is not RESTful. This is not necessarily a bad thing in itself but it is important that you understand that your system will probably not have the properties you expect it to have.
I'll try to get you started with a short answer below, but please have a look at http://nordsc.com/ext/classification_of_http_based_apis.html where I discuss this issue a bit more. You can then probably break all this down to smaller questions and come back here or visit rest-discuss on Yahoo groups: http://tech.groups.yahoo.com/group/rest-discuss/
Now short comments to your design:

*

*You should not use your own response codes but only use the ones provided by HTTP. You could make up your own ones, but those must be generally applicable and not be specific to your application or interaction.

*You should use a specific media type, not only application/xml. If none of the existing types match your need (or can be extended to do so), you can develop your own. In fact, the major design activity should be spend on the media type. It is where your domain semantics live.

*You must adhere to the hypermedia constraint to be truly RESTful. This means that the client should be provided with links and/or forms to discover what it can do next.
Using the classification referenced above, you API seems like a HTTP-based Type I ( http://nordsc.com/ext/classification_of_http_based_apis.html#http-type-one ) assuming you do not put actions in your URIs, which would make it RPC URI-Tunneling ( http://nordsc.com/ext/classification_of_http_based_apis.html#uri-rpc )
I hope that helps you with your overall goal.
Jan

A: A few things:
1) Putting response headers into different places - HTTP header AND response_code - will definitely cause confusion. Some developers will check it in one place, some in the other. If you want to go with that route, absolutely make sure that the response codes are identical between HTTP headers and the returned XML.
2) Your server does NOT have to return the API version with every response. You're wasting bits on the wire. If the client wants a specific version of the API, have them send it up in the request. You don't have to send it back to them.
3) Combine response_code and request_status. Look at how HTTP does it: 200-299 means success. 400-499 means client is dumb. 500-599 means server is screwed up.

A: If you're really building REST services, consider this:

*

*request_status, should be drop in favor of html response code (at least 200: OK, 400: Bad Request, 401: Unauthorized, 403: Forbidden and 500: Internal Error), response_code may be needed to find in your documentation an explanation of the problem.

*You want to provide different format, the format of the response should not depend of the url but of the Accept header

A: The XML looks nice.
But to say more about the inner Logic we need more Details than just the XML.

A: The best API you can use as an example is the API your coding in. Use the same naming conventions and casing.
Also, try to build sample applications using your API and you'll quickly discover its shortcomings.

A: Have you considered using versioned endpoints? They may require a bit more planning and maintenance on your part, but your users will love not having to rewrite their code every time you decide to change parameters / return values.
If you come up with a plan to deprecate and then remove old versions, this shouldn't prove too painful.

A: About you "single URL/endpoint" idea - keep in mind that with Apache you can serve a potentially unlimited number of URLs from a single script via URL rewriting rules. This means that with a properly defined .htaccess file in the directory of your "endpoint" script you can have your web server automatically "map" incoming requests like this, for example:

/foo/slice/1234 => /foo/?action=slice&oid=1234
/foo/dice/3456  => /foo/?action=dice&oid=3456
/foo/chop/4567  => /foo/?action=chop&oid=4567

This can be very helpful if you decide that you want to serve "RESTful" URLs after all (and can be made to work with HTTP request modes GET, POST, PUT, DELETE, HEAD).


text:
Q: Check if all letters of string are contained in list of letters in Python I am trying to write a Scrabble valid word checker function in Python. I need to see if the list contains all the letters in the word, but once I match a letter I cannot use it again. So if my word is 'test' and my list is ['t', 'a', 'e', 's'] that should return False since I need 2 t's.
Here is my idea:
def validWord(word, letterList):
  for x in word:
    if x in letterList:
      letterList = letterList.remove(x)
    else:
      return False
  return True

However I get this error when I compile it:
TypeError: arument of type 'NoneType' is not iterable
Now I am guessing that the "if x in letterList" only can run once and not iterate. So now I was hoping someone could give me a push in the right direction. This is just for fun on my part, I was going to use this to create a "Words with Friends Cheater" and show my friends.
Thanks!

A: list.remove returns None and you are assigning it to letterList. On the next iteration, it becomes if x in None, where in operator tries to iterate None and fails with that error. So, change
letterList = letterList.remove(x)

to
letterList.remove(x)

You can solve this problem like this
from collections import Counter

def validWord(word, letterList):
    word2, word1 = Counter(word), Counter(letterList)
    return all(word2[k] <= word1.get(k, 0) for k in word2)

print validWord("test", ["t", "a", "e", "s"])  # False
print validWord("test", ["t", "e", "t", "s"])  # True


text:
Q: "Run all cells" command in Google Colab programmatically I need to run certain command "Run all" from Google Colab menu "Runtime" programmatically. It does not have any obvious "onclick" eventHandler which I could call from javascript code on that page.
Other "divs" on the page are OK to be called from js, for exapmle, I can connect to runtime using js code:
document.querySelector('#top-toolbar > colab-connect-button').shadowRoot.querySelector('#connect').click();

Runtime menu is a dropdown menu and I tried to .click() every
 item inside it but no effect.
Also "Run all" command has a hotkey Ctrl + F9 but dispatching event to the document element has no effect. But I can send Enter command to any input field inside the notebook with this code:
document.querySelector('input.raw_input').dispatchEvent(new KeyboardEvent('keydown', {key: 'Enter'}))

Using Chrome code inspector Ctrl + Shift + I I looked inside "Run all" command and it looks like:

Run allCtrl+F9

So I searched inside Sources tab of inspector code on the page and found occurrences of "runall" in https://colab.research.google.com/v2/external/external_polymer_binary.js file:
, Eja = X(new W({
        id: "runall",
        description: "Run all cells in notebook",
        shortcut: IG(120)

120 - is a keycode of F9 button by the way. Also I found I think exact place where needed menu item is called:
        case "runall":
            d.runAll();
            break;

but it's almost impossible for me to understand what is d. and where its reference!
Also I found many other interesting and useful commands like this.notebook.getKernel().isRunning() or c.notebook.getKernel().restart() but the question is the same all the time: what is the root object for those commands? I tried document. and window. but the result is "undefined" or "is not a function". I think that I could call runall() command in a string like:
document.**SOMETHING I DONT KNOW**.runAll()

I am very bad with frontend/js and its very difficult to find something in obfuscated code but if we have such function as .runAll() in javascript code which is connected to required menu item I thick it is possible to run it programmatically from console or javascript injection
Or maybe it is possible to dispatch a keyboard event Ctrl + F9 to some element in order to run this command thus the question is WHAT is the required object to dispatch the keyboard event

A: I spent a while combing through that javascript file for a similar reason, and finally figured out how to make this work.
Here's a function to programmatically run all cells:
function runAll() {
  const F9Event = {key: "F9", code: "F9", metaKey: true, keyCode: 120};
  document.dispatchEvent(new KeyboardEvent("keydown", F9Event));
}

Note that KeyboardEvent.keyCode is deprecated in favor of KeyboardEvent.code, but you still need to provide it here (as of 5/18/21) since it's the property Colab uses to check keyboard inputs.
You can also use metaKey: true and ctrlKey: true interchangeably, regardless of platform, since Colab just checks whether either KeyboardEvent.metaKey or KeyboardEvent.ctrlKey is present for shortcuts that require them.

Also I found many other interesting and useful commands like this.notebook.getKernel().isRunning() or c.notebook.getKernel().restart() but the question is the same all the time: what is the root object for those commands?

There's a global colab object that provides access to some (but not all) functionality.  Most things are accessible through colab.global, e.g. to restart the kernel, you can use:
colab.global.notebook.kernel.restart()


text:
Q: two or three dots I have a more general question to ask:
about using the $\cdots$ symbol.
As far as I have heard three dots will represent that it continues up to infinity.
And I have found (mostly in computer programming) that two dots will be used in a case to indicate the terms between two specific points.
So my question is what is suitable to write in a case where finite number of terms are used.
For example Consider the set with $n$ number of elements. Let them be
$$x_1,x_2, \cdot \cdot x_n \;\text{ two dots. }$$  Or is it $$x_1,x_2, \cdots  x_n\;\;?$$

A: You'll need to use three dots:
$\{1, 2, 3, \ldots \}$
$\{1, 2, \ldots, 10\}$
You can also use three dots to indicate an infinite sum, or to abbreviate the sum of many numbers, provided you've made the pattern clear.
$\sum_{k = 1}^{k=119} k = 1 + 2+ 3+ \cdots + 119\\$
$\sum_{k=1}^\infty k =1 + 2 + 3 + \cdots$


text:
Q: Tap and Drag gesture in Windows Phone without XNA I want to know if there's some kind of gesture for Windows Phone that allow me to tap on a Button and then drag to another and tap it, of course without XNA framework because this is not a game and I don't want use it.
For example, I have two buttons "A" and "B", if tap on A then I drag my finger (still on the screen) on B then B should be selected with A.
I hope everybody understand my problem, Of course I'm doing all this with C# and XAML for Windows Phone 8.
Thanks for the answers. Cheers.

A: You can use the DragStarted and DragCompleted events from Microsoft.Phone.Controls.GestureListener available in Phone Toolkit. Sample code: http://www.scottlogic.co.uk/blog/colin/2012/06/a-gesture-driven-windows-phone-todo-application-part-two-drag-re-ordering/

A: I also prefer using the already implemented gestures that Microsoft provides with the windpwsphone toolkit. It's probably the best implementation of standard gestures you can get.
And as @Arun already showed, there are already drag and drop implementations done.
But if this is not sufficient for you, you can always create your own gestures based on the raw event, that ever UIElement has. See:
http://msdn.microsoft.com/en-us/library/ms604577%28v=vs.95%29.aspx


text:
Q: PHP - Searching for records in a database whilst simultaneously ordering them and paginating them Right, day 8 learning php and I feel that I have tried to do things in the wrong order.... I was fine up until yesterday. I have set myselft the task of creating a fake online book shop (seems popuar with all learn php books). First I created my products and listed them all on a page from the database.. easy, then I used a dropdown box to order the results... hard but did it eventually. Then tried to paginate, easy, then tried to join my ordering code and pagination code: most painful few hours of my life but complete. The I utilised a search bar.. easier then thought, an now I am trying to mix this search bar with my pagination and ordering code and my hair is falling out by the handful! I really wish I had attempted to learn all three at once but would have been a bit of a handful/headful.
So my problem is... It paginates... yay, it orders... yay however when I first see the results from a search... It paginates ok (shows me how many pages there are which is always the correct value) however when I click to view the 2nd page it the stops showing me the results of the search, instead takes me to page 2 of ALL products in the database. The same also happens if I try and order the list, it changes to an ordered list of all the products and tells me the search criteria is empty!
Sorry for such a long winded question, I just cant work out where I have slipped up!
Thank you soo much for anybody who can help!
Heres the code:
booksearch.php:
(have taken out all the irrelevent code!)
<?php $query1 = "SELECT *
      FROM booktable";

// execute the query

$results1 = mysql_query($query1)
                or die(mysql_error());

// count the number of rows that are selected from the table

$field = mysql_num_fields( $results1 );

// echo $field;

        for ( $i = 0; $i < $field; $i++ )
    {
         $names[$i] = mysql_field_name( $results1, $i );
        }
?>
<form name="searchbook" action="productssearch.php" method="get">

    Got For It:<input type="text" id="searchbar" name="searchterm" value="Enter anything and we will search on title, author, publisher and ISBN"></input>

    <input type="submit" name="Search" value=" - Search - "></input>
  </form>

productssearch.php:
require "dbconn.php";
$term = $_GET['searchterm'];
$records_per_page = 10;
//If user set the sort order, save to session var - else set default
if(@$_POST['order'])
{
$_SESSION['order'] = trim($_POST['order']);
}

elseif(!isset($_SESSION['order']))
{
$_SESSION['order'] = 'bookname';
}

//Determine the total records and pages
$query = mysql_query ("SELECT COUNT(bookname)
          FROM booktable
          WHERE bookname LIKE '%".$term."%'
          OR bookisbn LIKE '%".$term."%'
          OR bookpub LIKE '%".$term."%'
          OR bookauthor LIKE '%".$term."%'");

$total_records = mysql_result($query, 0);
$total_pages = ceil($total_records / $records_per_page);

//Set the page to load
$page = (isset($_GET['page'])) ? (int) $_GET['page'] : 1;
if($page<1 || $page>$total_pages)
{
$page = 1;
}

//Create limit var for query
$limit_start = ($page-1) * $records_per_page;

//Create and run query for records on current page
$query = mysql_query ("SELECT bookname, bookauthor, bookpub, bookisbn
          FROM booktable
          WHERE bookname LIKE '%".$term."%'
          OR bookisbn LIKE '%".$term."%'
          OR bookpub LIKE '%".$term."%'
          OR bookauthor LIKE '%".$term."%'
          ORDER BY ".mysql_real_escape_string($_SESSION['order'])." ASC
          LIMIT $limit_start, $records_per_page");

//Prepare output
//**************************************************************
$numrow = mysql_num_rows($query);
//Create pagination links
$navLinks = '';

//Prev page
if($page > 1)
{
$prevPage = $page - 1;
$navLinks .= "Prev ";
}
else
{
$navLinks .= "Prev ";
}

//Individual pages
for($p=1; $p<=$total_pages; $p++)
{
$pageNo = ($p == $page) ? "{$p}" : $p;
$navLinks .= "$pageNo ";
}

//next page
if($page < $total_pages)
{
$nextPage = $page + 1;
$navLinks .= "Next";
}
else
{
$navLinks .= "Next";
}
?>

(IRRELEVANT STUFF FROM MIDDLE REMOVED)

<?php

echo "
";
echo "
";
echo "";

echo "	";
echo "";
echo "Book Title";
echo "	";
echo "";
echo "Book Author";
echo "	";
echo "";
echo "Book Publisher";
echo "	";
echo "";
echo "Book ISBN";
echo "	";
echo "";

echo "	";
echo "
";
while ($row = mysql_fetch_assoc($query))
{
 $bookname = $row['bookname'];
 $bookauthor = $row['bookauthor'];
 $bookpub = $row['bookpub'];
 $bookisbn = $row['bookisbn'];
  // send the values to the browser as a row in a html table
  echo "
";

  echo "
";
  echo "";
  echo "Add to basket";

  echo "	";

 echo "";
  echo $bookname;
  echo "	";

  echo "";
  echo $bookauthor;
  echo "	";

  echo "";
  echo $bookpub;
  echo "	";

  echo "";
  echo $bookisbn;
  echo "	";

  echo "
";

}
?>

<?php
echo "
";
echo $navLinks; ?>

Please note I am a real beginner so I am not learning how to make secure or safe code.,.. I havnt even encrypted user and admin passwords yet... just trying to learn the mechanics of the script!
Thank you all again for taking the time to read my "windy" question!

A: It's becuase you are not carrying your:
$term = $_GET['searchterm'];

to the next page.
So when you search a blank string you are getting returned back the results for everything.
Your pagination links should contain the search term used in your POST.

A: To all who are reading this: I'm keeping it SIMPLE, as Phil has commented he's a beginner.  We all know there are considerations that are NOT being taken into account in this answer!
Phil, the answer lies in the construction of your navlinks code.
When you click one of the navlinks, it passes the limits for your pagination, but does NOT pass the search term.
You would need to modify your navlinks to be along the lines of:
$navLinks .= "Prev ";

and
$navLinks .= "$pageNo ";

and
$navLinks .= "Next";

etc.


text:
Q: Dormant black holes vs feeding black holes Why do they refer to black holes as if they are conscious beings?
Here are two examples :
http://www.techtimes.com/articles/166814/20160624/heres-what-happens-when-a-sleeping-black-hole-wakes-up-to-devour-a-star.htm
https://phys.org/news/2013-04-black-hole-snack.html
I've never heard of the earth feeding on asteroids... Or the sun feeding on matter. Does a black hole really go dormant and ignore matter around it? Or does it mean that there isn't any matter close enough to pull in so it just sits there... Until something does get too close. Then gravity pulls it in just like any other object would...just like the earth would.
It makes it seem like an object orbits a black hole for eons and then some day the black hole decides to wake up and eat it.
I find the constant personification of black holes to be confusing. Making an already tricky subject more confusing.
Am I missing something here?

A: While I do see some real chance of legitimate confusion arising from the articles you posted, it is very much so that popular science websites/articles tends to sensationalise things. It might even be that human beings like to frame things in a decidedly human perspective, whether to understand them better or for any other reason. You might even get ideas or be able to draw ideas about consciousness from the usage and choice of these words, I don't know. But what I do know is that whatever it is, it isn't good physics.
As far as I know, all of this "feeding", "waking up" and "sleeping" are just words being tossed around with no real connotation to the "personhood" of the black hole. The terms have some applicable meaning but are mostly vague generalisations for things physicists don't have a specific name for/have much more specific names for (like spaghettification, event horizon, matter accretion, etc.).
In essence, all of it just means that the black hole has run out of matter around it to "spin" and "crush" and ceases to radiate strong EM waves. See this answer for more details. Also, the wikipedia page contains a wealth of information on black holes that is a good deal more accurate, a lot more detailed, a lot less sensationalist and not unnecessarily anthropomorphised like the articles you have linked.


text:
Q: Laravel foreach loop in HTML Blade Table Cells that Span Many Columns I'm trying to show a table in laravel blade same as the image below

In the HTML Blade table To make a cell span more than one row, I use the rowspan attribute. But when I try to do it with foreach in blade view it not working perfectly. foreach loop return the team raw three times.
here is my blade code
@foreach($datas as $data)

  {{$data->team_name}}
{{$data->name}}
{{$data->email}}
{{$data->phone}}

@endforeach

Please help.

A: Team row returning three times, because it's in the foreach, if rowspan is a static value you can try below code:
@foreach($datas as $key => $data)

     @if ($key == 0 || $key % 3 == 0)
         {{$data->team_name}}
     @endif
     {{$data->name}}
     {{$data->email}}
     {{$data->phone}}

@endforeach

Laravel 5.2 and up
For dynamic rowsapn, try below code:
@php
   $rowid = 0;
   $rowspan = 0;
@endphp
@foreach($datas as $key => $data)
  @php
     $rowid += 1
  @endphp

     @if ($key == 0 || $rowspan == $rowid)
         @php
             $rowid = 0;
             $rowspan = $data->how_many_members;
         @endphp
         {{$data->team_name}}
     @endif
     {{$data->name}}
     {{$data->email}}
     {{$data->phone}}

@endforeach

change how_many_members property fits to your model field name.


text:
Q: Disable "These files might be harmful to your computer" message for home server (Win10) I've just set up a small home server, and I'm getting a "These files might be harmful to your computer" message whenever accessing files on it. The solution I've found is to edit my internet options and add the server's IP to a trusted list, but the "Sites" button is grayed out, so I'm unable to edit it:
Disable "These files might be harmful to your computer" warning?

Any suggestions would be appreciated. Thank you

A: Found the solution on this site:
http://www.winhelponline.com/xp/ie/flags.htm
open regedit, go to
HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1
find the "Flags" item, and whatever value is there, add "3" to it (i.e. if it's 0, change to 3; if it's 8, change to 11, etc) -- this enables both the "Sites" and "Custom settings" buttons
Then you can simply follow the steps in this solution to disable the notification for your server:
Disable "These files might be harmful to your computer" warning?


text:
Q: Print statement in if, switch and while condition of c Can someone explain why the code prints "HelloWorld" and not "HelloWorldThere" ? Also why does it print anything at all as there are no conditions in if or switch statements ? Here is the code:
#include <stdio.h>

int main()
{
    int a, b;

    if(printf("Hello"))
        switch(printf("World"))
            while(printf("There"))
            {
                return 0;
            }
}

A: Pretty straightforward: printf("Hello") returns 5 (the number of characters written). 5 is not 0, so it's considered "true" for the purposes of the if, so then printf("World") also returns 5, the switch looks for a case 5:, doesn't find one, and stops there.

A: For starters, let's consider what the function printf returns. From the C Standard

3 The printf function returns the number of characters transmitted, or
  a negative value if an output or encoding error occurred.

So the condition of this if statement
if(printf("Hello"))

evaluates to true because printf() returns a non-zero value.
Then this switch statement
switch(printf("World"))

is evaluated.
Now let's consider how the switch statement works. From the C Standard

4 A switch statement causes control to jump to, into, or past the
  statement that is the switch body, depending on the value of a
  controlling expression, and on the presence of a default label and the
  values of any case labels on or in the switch body. A case or default
  label is accessible only within the closest enclosing switch
  statement.

As the body statement of the switch statement does not have a label (including the default label) then the control is passed past the body statement. That is, the while statement (that is a body statement of the switch statement) is not executed.
If you want to get the expected by you result then for example insert the label default.
#include <stdio.h>

int main()
{
    if(printf("Hello"))
        switch(printf("World"))
            default: while(printf("There"))
            {
                return 0;
            }
}

In this case the program output is
HelloWorldThere

Or use a null-statement as the body statement of the switch statement.
#include <stdio.h>

int main()
{
    if(printf("Hello"))
        switch(printf("World")); // <==
            while(printf("There"))
            {
                return 0;
            }
}


text:
Q: Feature Request: relaxed spam rules for established users
Possible Duplicate:
Increase captcha threshold for post editing

It would be nice to have slightly relaxed spam rules for established users. In my experience (on SO), all it takes for me to see Bret and Jermaine is a couple of fast edits even though I've got a 3.5k+ reputation. Of course it's not like it happens often, but when it does, it feels like an unnecessary bother. So here's my suggestion: relax the spam detection a little, reserved for established users with 2k+ or 3k+ reputation. Not so much that it would allow a compromised account to have a free spam buffet (or is it really a buffet when you're bringing the spam?) but just enough that it becomes nearly impossible for a normal user to trigger the spam detection.
Sorry for the block of text :)


text:
Q: How do I connect Kubernetes Engine on GCP to an external Google Cloud Storage Bucket? I have deployed a pod on a Kubernetes Cluster on GCP. I have used a Persistent volume using a PVC as the volume mount.
I need to input data(.doc files) residing in Google Cloud Storage buckets into the the pod's data path.
How do I mount this external storage or injest the data into the pod?
And I require this this to be a live connection or for the injestion to happen at regular intervals.

A: I found a way to mount google cloud storage buckets into Kubernetes-
GCS Fuse has to be built into the image and then the cloud storage buckets can be mounted as directories. I referred to these links to implement this-
https://karlstoney.com/2017/03/01/fuse-mount-in-kubernetes/
https://github.com/maciekrb/gcs-fuse-sample

A: As mentioned by Ahmet and Patrick, it is not possible to mount Google Cloud Storage (GCS) buckets as PV/PVCs at Google Kubernetes Engine (GKE).


text:
Q: Tensorflow with Keras fit and tensors in dataset input result in list index out of range I encountered a strange error when using tf.keras in python with a dataset that consists out of tensors.
What I do is create a dataset from a csv file and modify it as it contains a time series. In the end, I end up with a dataset that has tuples of input and output tensor.
These are fed into a tf.keras model and here is where it becomes interesting. Fit calls a function in training.py of the keras enginge which is called _standardize_user_data. This should return the input, targets, and so on for fit_loop, which in turn checks something on it and crashes with
if issparse is not None and issparse(ins[i]) and not
K.is_sparse(feed[i]):
    IndexError: list index out of range

in line 187 of training_arrays.py. This is due to the fact _standardize_user_data returns empty lists, with the reasoning that if tensors are the input, then it everything should be set up already, which it apparently isn't. that Here is some small MWE.
#!/usr/bin/env python3
import argparse
import glob
import logging
import numpy as np
import tensorflow as tf
from tensorflow import keras

def read_dataset(filename, columns, field_defaults, input_size, output_size, stride, input_features):
    def decode_csv(row):
        fields = tf.decode_csv(row, record_defaults=field_defaults, field_delim=',')
        all_columns = dict(zip(columns, fields))
        return all_columns

    def split_window(window):
        inputs = tf.reshape(tf.concat(window['value'][0:input_size], axis=1), [input_size, input_features])
        outputs = tf.reshape(tf.concat(window['value'][input_size:input_size + output_size], axis=1),
                             [output_size, input_features])

        return inputs, outputs

    dataset = tf.data.TextLineDataset(filenames=filename)
    dataset = dataset.map(decode_csv)
    dataset = dataset.apply(tf.contrib.data.sliding_window_batch(window_size=input_size + output_size, stride=stride))
    dataset = dataset.map(split_window)
    dataset = dataset.repeat()

    return dataset

if __name__ == "__main__":
    COLUMNS = ['value']
    FIELD_DEFAULTS = [[0.0]]
    INPUT_FEATURES = 1

    epochs = 1
    steps = 1
    INPUT_SIZE = 4
    OUTPUT_SIZE = 2
    STRIDE = 1
    input_train = "./data/"

    input_train_list = glob.glob(input_train + "*")

    model = keras.Sequential()
    model.add(tf.keras.layers.Dense(OUTPUT_SIZE, activation=None))
    set = read_dataset(input_train_list, COLUMNS, FIELD_DEFAULTS, INPUT_SIZE, OUTPUT_SIZE, STRIDE, INPUT_FEATURES)

    model.compile(optimizer=tf.train.AdamOptimizer(0.01), loss='mse', metrics=['mse'])
    model.fit(set, epochs=epochs, steps_per_epoch=steps)

The data is in the form of:
0.047910000000000785
3.0999999999892225e-05
0.0160979999999995
2.9000000000500847e-05
0.01716599999999957
2.800000000036107e-05
2.9999999999752447e-05
0.019235000000000113

Does anybody know if this is intended or if something goes wrong? Does my data generation give the wrong output? Or could it be that there is a bug?
I'm thankful for any help!


text:
Q: Multilayer Perceptron works fine with sigmoid activations, but not with hyperbolic tangent I have written a simple MLP with one single layer. When learning the XOR function using sigmoid activations, the loss reduced consistently. However, if I change the labels of the XOR data from [0, 1] to [-1, 1] and use the tanh activation instead, the loss doesn't reduce. It should still work by simply changing the labels and using tanh, shouldn't it? And if so, where is my implementation going wrong with tanh?
import sys

import numpy as np

class DataSet:

    def __init__(self, data):
        self.size = len(data)
        self.inputs, self.labels = [], []
        for i in range(len(data)):
            self.inputs.append(data[i][0])
            self.labels.append(data[i][1])
        try:
            self.numInputs = len(self.inputs[0])
        except TypeError:
            self.numInputs = 1
        try:
            self.numOutputs = len(self.labels[0])
        except TypeError:
            self.numOutputs = 1

class MLP:

    def __init__(self, numInputs, numHidden, numOutputs, activationFunction):
        # MLP architecture sizes
        self.numInputs = numInputs
        self.numHidden = numHidden
        self.numOutputs = numOutputs
        self.activationFunction = activationFunction.lower()

        # MLP weights
        self.IH_weights = np.random.rand(numInputs, numHidden)      # Input -> Hidden
        self.HO_weights = np.random.rand(numHidden, numOutputs)     # Hidden -> Output

        # Gradients corresponding to weight matrices computed during backprop
        self.IH_gradients = np.zeros_like(self.IH_weights)
        self.HO_gradients = np.zeros_like(self.HO_weights)

        # Input, hidden and output neuron values
        self.I = np.zeros(numInputs)    # Inputs
        self.L = np.zeros(numOutputs)   # Labels
        self.H = np.zeros(numHidden)    # Hidden
        self.O = np.zeros(numOutputs)   # Output

    # ADD BIAS FOR RELU ########################################################
    # ADD SOFTMAX ##############################################################
    def activation(self, x, derivative=False):
        if self.activationFunction == 'sigmoid':
            if derivative:
                return x * (1 - x)
            return 1 / (1 + np.exp(-x))

        if self.activationFunction == 'tanh':
            if derivative:
                return 1. - np.tanh(x) ** 2
            return np.tanh(x)

        # if self.activationFunction == 'softmax':
        #     if derivative:
        #         return ########
        #     return np.exp(x) / np.sum(np.exp(x))

        if self.activationFunction == 'relu':
            if derivative:
                return (x > 0).astype(float)
            return np.maximum(0, x)

        print("ERROR: Activation function not found.")
        sys.exit()

    def forward(self, inputs):
        # Ensure that inputs is a list
        try:
            len(inputs)
        except TypeError:
            inputs = [inputs]

        self.I = np.array(inputs).reshape(1, self.numInputs)
        self.H = self.I.dot(self.IH_weights)
        self.H = self.activation(self.H)
        self.O = self.H.dot(self.HO_weights)
        self.O = self.activation(self.O)
        return self.O, self.L

    def backwards(self, labels):
        # Ensure that labels is a list
        try:
            len(labels)
        except TypeError:
            labels = [labels]

        self.L = np.array(labels)
        self.O_error = self.L - self.O
        self.O_delta = self.O_error * self.activation(self.O, derivative=True)

        self.H_error = self.O_delta.dot(self.HO_weights.T)
        self.H_delta = self.H_error * self.activation(self.H, derivative=True)

        self.IH_gradients += self.I.T.dot(self.H_delta)
        self.HO_gradients += self.H.T.dot(self.O_delta)

        return np.sum(self.O_error ** 2)

    def updateWeights(self, learningRate):
        self.IH_weights += self.IH_gradients
        self.HO_weights += self.HO_gradients
        self.IH_gradients = np.zeros_like(self.IH_weights)
        self.HO_gradients = np.zeros_like(self.HO_weights)

# data = DataSet([
#     [[0, 0], 0],
#     [[0, 1], 1],
#     [[1, 0], 1],
#     [[1, 1], 0]
# ])
#
# mlp = MLP(data.numInputs, 20, data.numOutputs, 'sigmoid')

data = DataSet([
    [[0, 0], -1],
    [[0, 1], 1],
    [[1, 0], 1],
    [[1, 1], -1]
])

mlp = MLP(data.numInputs, 20, data.numOutputs, 'tanh')

numEpochs = 10000
learningRate = 0.01

losses = []
for epoch in range(numEpochs):
    errors = []
    correct = []
    for i in range(data.size):
        mlp.forward(data.inputs[i])
        errors.append(mlp.backwards(data.labels[i]))
    mlp.updateWeights(learningRate)
    epochLoss = np.mean(errors)
    losses.append(epochLoss)
    if epoch % 100 == 0 or epoch == numEpochs - 1:
        print("EPOCH:", epoch)
        print("LOSS: ", epochLoss, "\n")

A: Your code for derivatives is erroneous.
You don't calculate derivatives evaluated at input, but on output (for example you take $x(1-x)$ for sigmoid derivative, but it's actually $\sigma(x) (1 - \sigma(x))$.
Because of that your evaluation of $tanh'(x)$ is wrong, in your implementation it should be ($1 - x^2$).
It seems to be a good idea though to leave this one, fix sigmoid derivative instead, and actually evaluate derivatives right.


text:
Q: How to collect the syslog in openwrt? I want to collect the whole log file of the openwrt in raspberry pi-3 system,as it will be available in /var/log/syslog in normal system.Please help me to collect the whole syslog of the raspberry pi-3 openwrt OS.

A: uci default using the logread to get the log. You can see more detail in openwrt webside.
https://openwrt.org/docs/guide-user/base-system/log.essentials

A: using dmesg command to collect kernel log


text:
Q: How to reduce dex files in APK How to reduce dex files to minimal in my project?
It has more than 20 dex files

Some files only have 1 class, 1 method.

============
Update: For more info, this is my problem about debug apk

============
Update 2: I don't use Instant Run in my project.

Thanks in advance!


text:
Q: How to combine multiple input datasets (dataframe)? I have multiple datasets and want to union the rows into one dataset in order to fit a classifier. Is there a good way to combine the input datasets?
My data consists of historical values of the stock market - and I want to use the complete data to fit only one classifier.
If I will create one big table - I will have problems with the end and start of each dataset.
For example - the last days of the first stock on the list will be used to train the classifier with the start of the second stock in the list.
Maybe I should normalize each data set before concatenating all to one data set?
Answered by usr: all the historical data that is related to training the classifier is already in the columns - so - appending all rows will be ok and will not cause problem with the first and the last days of different stocks/datasets

A: If you're looking to union data frames into one, you have several options using Pandas.

*

*You can use .append()
e.g. df = df1.append(df2, ignore_index=True)

*

*You can also use .concat(). With concat you can join more than two data frames

e.g. df = pd.concat([df1, df2], ignore_index=True)
Here's some more information with examples: https://pandas.pydata.org/pandas-docs/stable/merging.html


text:
Q: Save the mysql queries(Insert, Delete, Update) to database in cakephp 3 I want to log/save all the mysql queries(insert ,delete,update) and there duration respectively in a log table.
Please let me know how this can be done in cakephp 3


text:
Q: which client side js library can I use for file upload where file size can be restricted Which js library can I use to upload files from any browser and will allow client-side restriction of the file size

A: dropzone.js can. dropzone website
their example:
Dropzone.options.myAwesomeDropzone = {
  paramName: "file", // The name that will be used to transfer the file
  maxFilesize: 2, // MB
  accept: function(file, done) {
    if (file.name == "justinbieber.jpg") {
      done("Naha, you don't.");
    }
    else { done(); }
  }
};

A: Try jquery File Uploader
it has option

maxFileSize
The maximum allowed file size in bytes.
Type: integer Default: undefined Example: 10000000 // 10 MB Note: This
  option has only an effect for browsers supporting the File API.

But old browsers don't support this feature. And unlikely there are any way to fix it

A: Try https://github.com/mailru/FileAPI
We using this library in our web projects, works fine in any browsers except android default browser.


text:
Q: Loading binary data with FixedLengthRecordDataset in TensorFlow I'm trying to figure out how to load binary data file using FixedLengthRecordDataset:
import tensorflow as tf
import struct
import numpy as np

RAW_N = 2 + 20*20 + 1

def convert_binary_to_float_array(register):
    return struct.unpack('f'*RAW_N, register.numpy())

raw_dataset = tf.data.FixedLengthRecordDataset(filenames=['mydata.bin'],record_bytes=RAW_N*4)
float_ds = raw_dataset.map(map_func=convert_binary_to_float_array)

This code throws:
AttributeError: in user code:

tf-load-data.py:14 convert_binary_to_float_array  *
    return struct.unpack('f'*RAW_N, register.numpy())

AttributeError: 'Tensor' object has no attribute 'numpy'

numpy() is available if I try to iterate over the dataset:
raw_dataset = tf.data.FixedLengthRecordDataset(filenames=['mydata.bin'],record_bytes=RAW_N*4)

for register in raw_dataset:
    print(struct.unpack('f'*RAW_N, register.numpy()))

By reading the Tensor type description, I realized that numpy() is available only during eager execution. Thus, I can deduce that during the map() call the elements are not provided as EagerTensor.
How to load this data into a dataset?
I'm using TensorFlow 2.4.1

A: I would suggest working with tf.io.decode_raw. I unfortunately do not know what mydata.bin looks like so I created some dummy data:
import random
import struct
import tensorflow as tf
import numpy as np

RAW_N = 2 + 20*20 + 1

bytess = random.sample(range(1, 5000), RAW_N*4)
with open('mydata.bin', 'wb') as f:
  f.write(struct.pack('1612i', *bytess))

def convert_binary_to_float_array(register):
    return tf.io.decode_raw(register, out_type=tf.float32)

raw_dataset = tf.data.FixedLengthRecordDataset(filenames=['/content/mydata.bin'], record_bytes=RAW_N*4)
raw_dataset = raw_dataset.map(convert_binary_to_float_array)

for register in raw_dataset:
  print(register)

You could also try first decoding your data into integers with tf.io.decode_raw and then casting to float with tf.cast, but I am not sure if it will make a difference.


text:
Q: Data Center Optimalization in AMPL I have such task:
Given are: set of nodes N (each with its power consumption) set of data servers D ⊂ N (each with available storage),
set of computation servers C ⊂ N (each with available computational power), set of edges (each with its capacity), set of
requests D (each with needed CPU power and requested storage).
Demands are served by a pair of servers (storage + computation), traffic of size proportional to storage is generated
between them. A node consumes energy if there is any traffic starting, ending, or passing through it. The task is to assign
demands to servers in such a way that all constraints are met.
Having a power budget B, design a configuration that maximizes the number of served demands.
I need to write the AMPL model to solve this by cplex. Can someone  help me with expressions?