text:
Q: How to use amplify sign-in only? In my angular application, I just want to use Amplify Sign-in function only. I don't want to use Amplify UI Angular since I have created my own login form. I want to pass the username and password to do authentication. I followed the example, but not sure how to get it working.
I think that the code is simple.
async onSubmit() {
   try {
    const user = await Auth.signIn(this.loginForm['username'].value,
    this.loginForm['password'].value);
   } catch (error) {
       console.log('error signing in', error);
   }
 }

Here is my DEMO, however it says that I miss some packages such http and https.

A: make sure you are calling Amplify.configure to configure which User Pool you are connecting to - https://docs.amplify.aws/lib/auth/start/q/platform/js#re-use-existing-authentication-resource
you are using Auth.signIn correctly, but it needs to be configure with Amplify.configure before you can use it,
for example (no-angular specific):
// ./index.js
import { Amplify } from "aws-amplify";

Amplify.configure({
  aws_cognito_region: "us-east-1",
  aws_user_pools_id: "xxxxxxx",
  aws_user_pools_web_client_id: "xxxxxxx",
  aws_mandatory_sign_in: "enable",
});

// ./components/sign-in.js
try {
  await Auth.signIn(username, password);
  let user = Auth.currentUserInfo();
  console.log(user);
  // {
  //   "username": "...",
  //   "attributes": {
  //     "sub": "...",
  //     "email_verified": true,
  //     "phone_number_verified": true,
  //     "phone_number": "...",
  //     "email": "..."
  //   }
  // }
} catch (error) {
  console.log("error signing in", error);
}

A: You simply don't implement the front-end functionality to add a new user. Then, in your Cognito user pool config, there is an option User sign ups allowed? which you would set to Only administrators can create users.
Edit: Also, consider using the hosted UI, it may save you some front-end work.


text:
Q: Should StackOverflow have a discussion module? My question is down to the fact that I have one closed topic, and one about to be closed.
Closed:
Perls Of Wisdom For a .Net Programmer
About To Be:
Is MVVM killing silverlight development?
Both are down to being "of a discussion nature" or not technically questions in the SO sense. I agree with that as they are not of the same ilk as standard programming questions. I have also noticed that SO has a large number of closed topics that are good discussion material and get some up votes before being closed.
Rather than spending time on closed topics that do not fit with the SO structure, it would be nice to see a place where this sort of discussion could be fostered. I feel both of my questions where interesting and so have others but I also understand the reason for people voting for closing.
Is this something that is being discussed or is this something members would prefer not to see?

A: Our engine is very poor at pure "there is no correct-ish answer" discussion.
We are planning a third place for more real time discussion.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Filter parent based on child parameters in JPA 2 I have a few unidirectional @OneToMany relationships as this :
@Entity
@Table(name = "Parent")
public class Parent {

    @OneToMany
    @JoinColumn(name = "ParentID")
    private List<Child1> childList1;

    @OneToMany
    @JoinColumn(name = "ParentID")
    private List<Child2> childList2;
}

@Entity
@Table(name = "Child1")
public class Child1 {
    private int someProperty;
    // other properties
}

@Entity
@Table(name = "Child2")
public class Child2 {
    private int someProperty;
    // other properties
}

I'm trying to get all Parents with child1.someProperty=10 and child2.someProperty=20. Could anyone please help ?
I tried using Join :
Root<Parent> root = criteria.from(Parent.class);
ListJoin<Parent, Child1> join = root.join(Parent_.childList1);
criteriaBuilder.equal(join.get(Child1_.someProperty), 10);

However, this returns a Parent for every Child1:
Parent----Child1(someProperty=10)
Parent----Child1(someProperty=10)

I would like the result to be :
        /Child1(someProperty=10)
       /
Parent/---Child1(someProperty=10)
      \
       \
        \Child2(someProperty=20)

Could anyone please help with this? I would prefer JPA Criteria, JPQL is fine though .
 I'm prepared to make minor changes in my entity structure, if it helps (minor changes, like making the relationship bidirectional ?)
Thanks.
I'm using hibernate as the JPA implementation, by the way.

A: You have to use setDistinct(true) on your query.
Results you are getting are valid join results mapped row by row to entities. Adding distinct will enable root aggregation resulting i parent having N children as what I belive is what you expect.


text:
Q: How do you maintain the previous scroll position after post using asp.net core 3.1 MVC and razor views? How do you maintain the previous scroll position after a post using asp.net core 3.1 MVC (web application) and razor views?
How do you do this across the site?
I saw this: ASP.NET MVC3 Razor - Maintain scroll position on postback - but those did not work for me.

A: First, Create a base view model that all other models will inherit
public class BaseViewModel
{
   public int ScrollPosition { get; set; }
}

All view models that are bound that will need to remember the previous scroll position will inherit from this BaseViewModel
Second, Add a hidden input to your form used for posting:
   @using(Html.BeginForm("SomeAction", "SomeController", FormMethod.Post)
   {
      @Html.HiddenFor(x => Model.ScrollPosition)
      ....
   }

Third, inside your post method on the backend set a value to TempData:
   TempData["ScrollPosition"] = Model.ScrollPosition;

Fourth, when redirect after post, set this value to your Model for binding in your view:
   MyModel.ScrollPosition = (int)TempData["ScrollPosition"];

Fifth, use javascript to scroll to previous position after page load:
   <script type="text/javascript">
       window.addEventListener("DOMContentLoaded", function(){
           //add event listener for the scroll event and set hidden input value for posts
           document.addEventListener('scroll', function(){
              const scrollPosY = window.scrollY;
              document.querySelector('input[name="ScrollPosition"]').value = scrollPosY;
           });
           const scrollpos = document.querySelector('input[name="ScrollPosition"]').value;
           window.scrollTo(0, scrollpos); //y-axis scroll
       });
   </script>

If you would need to track x axis scroll as well as y axis, you'd need two hidden inputs
for each x and y axis scroll position and change model to hold both x and y

A: Another way to do this is to submit the form with AJAX and, after a successful POST, call window.location.reload(); which will restore the scroll position.
function CreateItem() {
    var serializedForm = $('#formId').serialize();

    $.ajax({
        url: "item/create",
        type: "POST",
        data: serializedForm
    })
    .done(function () {
        window.location.reload();
    });
}

A: First add the following jquery function to your page in the script tag:
$(document).scroll(function () {
    // Note scroll position.
    localStorage['pageIdentifier'] = $(document).scrollTop();
});

And then add:
$(document).ready(function () {
    // Maintain scroll position.
    $(document).scrollTop(localStorage['healthPage']);
});


text:
Q: swift 3 can't update markerinfowindow content after call API I am using this code to return an GoogleMarkerInfoWindow, and it works fine!
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
        let customInfoWindow = Bundle.main.loadNibNamed("customInfoWindown", owner: self, options: nil)?[0] as! CustomInfoWindowns
        customInfoWindow.title = "This is title"
        return customInfoWindow
}

but when I update the title after call an API, then I can't update this label
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
        let customInfoWindow = Bundle.main.loadNibNamed("customInfoWindown", owner: self, options: nil)?[0] as! CustomInfoWindowns
        let id = marker.userData as? String
        UserManager.sharedInstance.getUserInfo(id, onComplete: {(content, error) in
            let userModel = UserModel.convertStringToUserModel(content!)
            DispatchQueue.main.async {
                 customInfoWindow.title = userModel.name // this code didn't work
            }
        } )
        return customInfoWindow
}

How can I do to update this label after call API?
Thank you!

A: Because you are using async try to reload map view
self.map.reloadInputViews()


text:
Q: Equivalent of e.ReturnValue in EntityDataSource I'm using EntityDataSource with DetailsView in my ASP.NET application. I want to get identity column value after inserting the record. ObjectDataSource has e.ReturnValue property I want to know its equivalent in EntityDataSource?

A: You can subscribe to the Inserted event, which is an EventHandler<EntityDataSourceChangedEventArgs>.
The EntityDataSourceChangedEventArgs instance has an Entity property, representing the newly inserted entity.
void EntityDataSource1_Inserted(object sender, EntityDataSourceChangedEventArgs e) {
    YourEntityType newlyAdded = (YourEntityType)e.Entity;
    int newId = newlyAdded.Id;
}


text:
Q: Best way to ensure Item can only be used by 1 user I have a web application with two main table (All tasks) and (In progress). When you open a task from (All tasks) the item gets moved into (In progress). Now if users on different pc's open the task at the same time it will duplicate.
In your guys opinions what is the best way to make sure duplicates don't happen.
I currently have a column thats 0 if not processed and 1 if processed but this still gives a 2-3 second period where the task can be opened from two pcs at the same time.
I have looked into guid's and using sql transactions although ive read this slows things down abit
I hope this makes sense my dudes
Thanks in advance
a junior devi

A: This isn't meant to be a solution, just a quick framework to get you started:
CREATE TABLE #tasks (task_id INT, other_stuff VARCHAR(50), held BIT);
INSERT INTO #tasks SELECT 1, 'My Test Task', 0;
CREATE TABLE #work_queue (task_id INT);

--User #1 puts a task onto the work queue
BEGIN TRANSACTION;
    UPDATE #tasks SET held = 1 WHERE task_id = 1 AND held = 0;
    --Did we get it?
    IF @@ROWCOUNT = 1
        INSERT INTO #work_queue SELECT 1;
COMMIT TRANSACTION;

--User #2 fails to get a handle to the task so nothing is put onto the work queue
--Note that this can be run asynch from a second session
BEGIN TRANSACTION;
    UPDATE #tasks SET held = 1 WHERE task_id = 1 AND held = 0;
    --Did we get it?
    IF @@ROWCOUNT = 1
        INSERT INTO #work_queue SELECT 1;
COMMIT TRANSACTION;

--Task completes
BEGIN TRANSACTION;
    DELETE FROM #work_queue WHERE task_id = 1;
    UPDATE #tasks SET held = 0 WHERE task_id = 1;
COMMIT TRANSACTION;

If a user comes along to "book out" a task then one of these results will occur:

*

*they get a "lock" by setting the held flag to 1 where it was previously zero.  So the task is booked out and added to the in progress table (work queue in my example);

*they can't book out the task, as it's already been booked out by someone else.  So nothing happens.

If you were to run the "book out stage" from multiple users simultaneously then only one user would get the task, but there would be little in the way of "slow down".

Another (better?) way of handling this would be to store the user_id of the user who has a job running instead of a BIT flag.  Now you know who has the job rather than simply knowing that someone has it "booked out" so you can't get it?

A: Give the destination table a column that will contain the primary key from the source table, and put a uniqueness constraint on it. Or, if possible, simply give them the same primary key.
For example, if your AllTasks table has a primary key of TaskID, put a TaskID column in your InProgress table too, and put a uniqueness constraint on it. If two users try to copy the same record, the second record will violate the constraint and the insert will fail.


text:
Q: Mysterious MATLAB error using ./ in a for loop I need to make a for loop in MATLAB to divide each column in a matrix by a separate column vector. I only want to do this for a selection of the columns in the matrix, not all the columns.
This is what I'd like to do, where Indexes is a 19x1 vector of integers (not all consecutive numbers), big_matrix is 82x24, and other_column is 82x1:
matrix_to_fill = zeros(82,length(Indexes));
for x = Indexes
    new_column = big_matrix(:,x)./other_column;
    new_index = find(Indexes==x);
    matrix_to_fill(:,new_index) = new_column;
end

When I run this I get the following error:
Error using  ./
Matrix dimensions must agree.

I can run each iteration separately without getting errors, so I know that the matrix dimensions agree. What's more, if I type out the Indexes as a vector it works fine:
matrix_to_fill = zeros(82,length(Indexes));
for x = [1,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23]
    new_column = big_matrix(:,x)./other_column;
    new_index = find(Indexes==x);
    matrix_to_fill(:,new_index) = new_column;
end

And I think the "x=Indexes" syntax is fine because I've tested that using just:
for x = Indexes
    disp(x)
end

So I'm completely stumped. Any help would be much appreciated!

A: The problem is in your definition of the for loop.  When you say that you think the "x=Indexes" syntax is correct you haven't been observant enough to see that it is not correct.
What you need is
for x = Indexes'
% Do your looping
end

Note the transpose in the above.
If you do
for x = Indexes
    disp(x)
end

Then the loop is executed once, with x taking on the value of the whole vector.
If you do
for x = Indexes'
    disp(x)
end

then x will take on the individual elements of the matrix and you'll have 19 scalars displayed, once each time through the loop.


text:
Q: Google Chrome refused to display GoogleMaps Frame because X-Frame-Options is set to deny I'm working on a website for a shop and I'm using the GooleMaps Engine Lite to show his location. It works on IE9 and 10, Safari for Windows, iOS and MacOs and Mozilla Firefox, but it's not working on Chrome. If I use the Javascript Console I can see the following error:
Refused to display 'https://accounts.google.com/ServiceLogin?service=mapsengine&passive=1209600…up=https://mapsengine.google.com/map/embed?mid%3DzehbkDaSW5QM.kyKZHGifzxMc' in a frame because it set 'X-Frame-Options' to 'DENY'.

Could anybody help me?

A: First time I had the problem it disappeared when I rebooted my computer, but today the problem appeared again. I've read on Google forums that the conflict comes when you are semi-logged with your Google account. If I log out completely my account or log in the map re-starts to work. In Safari you will find the same issue.
A temporary solution is sandbox the map iframe to forbid it to access the cookies.

A: https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options

The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame> or <iframe>. Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.

The counter-question I have to you is why are you implementing that URL in an iframe, when it specifically tells the browser it does not want to be loaded in an iframe?
Did you follow the instructions at https://support.google.com/mapsenginelite/answer/3024935?hl=en when embedding the map?

*

*Make sure you have your desired map open and that it is set to be accessible by the Public.

*Click the folder button.

*Select Embed on my site.

*In the box that appears, copy the HTML under 'Embed on the web,' and paste it into the source code of your website or blog.

A: You're linking to the Google Account login page for the maps generator, not to a map. The link is probably not what you want.
To make an embeddable map from Google Maps Engine,

*

*click on the green "Share" button on the top right and set you map to public

*click on the folder icon on the top left (next to "Add layer") and choose "Embed on my site"

A: 1) in the left bottom corner click on 6 teeth wheel , 'Share and integration of map'
2) In opened dialog press on 'integrate map'
3) you got iframe line with correct src .


text:
Q: analyze program models that induce threads Thread is a single stream of control in the flow of a program. Which programming models it induces, and what are possible advantages and disadvantages of such models? (OpenMP, MPI, PThread, Cuda are these the one that induces threads? what are some pros and cons for each program model? )  Thank you

A: You can't both initialize a variable and declare it as extern. They are two different things.
When you declare a global variable, you can initialize it:
// trace_logger.c
int inst_cout= 0;

When the global variable may be used by other modules, you name it in a .h file (or define it directly in the other c/cpp source file) that the other modules can include:
// trace_logger.h
extern int int_cout;

And if you need a global variable but don't want to share it with other modules, you declare it as:
// trace_logger.c
static int counter= 0;


text:
Q: Adobe Air native extension - drawable resources are packaged into APK but values resources are not I have a multiplatform Adobe Air Native Extension (ANE) that I have created.  The Android portion of the ANE includes resources (i.e. res/drawable, res/drawable-hdpi, res/layout, res/values).
When I create the ANE, the resources are included in the ANE properly.
(I have determined this by pulling apart the ANE and I see all my resources in the proper directories)
However, when I create the APK, it includes all my resources EXCEPT the res/values directory.
That whole directory and it's resources are not included.
(I have determined this by pulling apart the APK and looking at the res directory)
Does anyone know if there is something special in Adobe packaging of APK's that prevents res/values folder from ANE's being included in the final APK?

A: What is happening in this situation is that the resources are being compiled into a binary format (in the resources.arsc file) so the original source files are not packaged into the APK.
If you dump the resources in the apk using aapt you can see that the resources are there:
 aapt dump --values resources your_app.apk


text:
Q: Is there a better way to make setter non primitive user defined type property? Hi I am new to typescript. I summarized my use case in the following example.
class Movie {
    private crew: Crew;
    private cast: Cast;
    private locations: Location;
    private movieId;

    constructor(public id: string) {
        this.movieId = id;
    }
    public getMovieId() {
        return this.moveId;
    }
    public setCrew(value: Crew){
        this.crew = value;
    }
    public getCrew() {
        return this.crew;
    }
    ...
    //other getter and setters.
};

type Crew = {
    crew_varA: string,
    crew_varB: boolean,
    crew_varC: string,
    crew_varD: boolean,
}

type Cast = {
    cast_varE: string,
    cast_varF: string,
    cast_varG: string,
}
type Location = {
    loc_varX: string,
    loc_varY: string,
    loc_varZ: string,
}

when I create an object of Movie, I need to call setCrew() method. But only 'crew_varA' variable has value by that time. I am not able to make a call to setCrew() method with only one variable. I need to initialize all variables with some default value which is not appropriate something like this.
let mv = new Movie("SpiderMan");
mv.setCrew({crew_varA: "Peter Parker", crew_varB:false, crew_varC:null, crew_varD:null}; //is there a way to set only one property of Crew and add other properties one by one based on some logic??

I am not sure my approach is correct or not. I appreciate your help.


text:
Q: Qual a diferença entre usar Object.toString() e String.valueOf()? Estava fazendo uns testes e percebi que utilizar um ou outro, o resultado acaba sendo o mesmo. Fiz este código para exemplificar:
public class ParseToStringTest {

    public static void main(String[] args) {
        new ParseToStringTest().parseTest();
    }

    public void parseTest() {

        SomeObj o = new SomeObj();
        System.out.println(o.toString());
        System.out.println(String.valueOf(o));

    }

    class SomeObj {}
}

Rodando no ideone, o resultado que obtive foi:
Ideone$SomeObj@677327b6
Ideone$SomeObj@677327b6

Ou seja, o resultado foi idêntico.
Teria alguma diferença entre usar String#valueOf()  ou Object#toString() para exibir uma representação do objeto em forma de String?

A: Documentação da Oracle

if the argument is null, then a string equal to "null"; otherwise, the
value of obj.toString() is returned.

Tradução:

Se o argumento é null, então temos uma string igual a "null"; Caso
contrário, o valor de obj.toString() é retornado.

Traduzido em código seria:
public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

No caso de um Object#toString, se a instância é null um NullPointerException será lançado. Não deve haver  uma diferença exceto para uma invocação de método adicional, ou seja, são praticamente a mesma coisa.

A: Quase nenhuma. Existe uma indireção adicional no String.valueOf, que é a checagem se o parâmetro é nulo ou não.
Parafraseando a documentação de String.valueOf:
O método vai checar se o objeto é nulo e, se ele for, é retornada a string "null", caso contrário será feita a chamada de .toString() do objeto.
Em código, o valueOf é, basicamente:
public static String valueOf(Object obj) {
    return obj == null ? "null" : obj.toString();
}

Ainda existem classes que implementam uma versão estática de toString() (como a Integer ou Arrays, por exemplo), isso serve, principalmente, para que estas classes possam trabalhar numa versão alternativa da representação do objeto como string, permitindo parâmetros adicionais ou uma implementação personalizada independente do .toString() original.
Isso fica bem claro na classe Integer, onde existe um overload que é possível definir qual a base que o número será mostrado.
Integer number = 15;

System.out.println(Integer.toString(number, 10)); // 15   (decimal, base 10)
System.out.println(Integer.toString(number, 2));  // 1111 (binário, base 2)
System.out.println(Integer.toString(number, 16)); // f    (hexadecimal, base 16)

Veja este exemplo funcionando no repl.it.
Então, o mais indicado é usar String.valueOf quando o objeto pode ser nulo, noutros casos, pode-se usar tranquilamente o .toString().

A: Na documentação diz que "se o argumento é nulo é retornado null, caso contrário o valor retorna .toString". Segundo essa lágica, o String.valueOf(Object) imprime null enquanto o Object.toString() pode gerar um NullPointerException.
Um outro detalhe importante é que o valueOf é um método estático, já o toString é um método de instância e só pode ser chamado em um tipo de referência. No entanto, o valueOf talvez, digo talvez, seja mais flexível em relação ao toString(). Veja os tipos básicos do método estático valueOf, que pode ser invocado:
String   valueOf(boolean b)
String   valueOf(char c)
String   valueOf(char[] data)
String   valueOf(char[] data, int offset, int count)
String   valueOf(double d)
String   valueOf(float f)
String   valueOf(int i)
String   valueOf(long l)
String   valueOf(Object obj)

Se tratando do toString(), sempre será necessário fazer a chamada de sua classe específica. Veja um exemplo:
Integer.toString(int i)   // inteiros
Float.toString(float f);  // flutuantes

Veja estes exemplos:
Exemplo 1:
public String doIt(float number) {

  return String.valueOf(number);
}

Exemplo 2:
public String doIt(float number) {

  return Float.toString(number);
}


text:
Q: Calculating this $\int_{|z|=1}\frac{z^a(1+z)^m}{(c-\ln z)^b}dz$ complex integral Solving a problem related with series, it appear this integral in the complex plane
$$\int_{|z|=1}\frac{z^a(1+z)^m}{(c-\ln z)^b}dz$$
where $a\in\mathbb{R}$ ,$b,c>0$ and $m=0,1,2,...$ which I'm not able to solve.
I try to use the standar parametrization of $|z|=1$ or even expand $(1+z)^m$ but it seems not right.
Any help is welcomed.

A: I think I have reached an interesting form for this integral in terms of a finite sum of special functions at least for $a>-1$. I do hope it doesn't revert back to the series you have been considering directly somehow!
I will prove that for $a,b >-1$

$$\begin{align}I&=\int_{|z|=1}\frac{z^a(1+z)^m}{(c-\ln z)^b}dz\\&\\&=\sum_{n=0}^m(-1)^n {m\choose n}\frac{e^{c(a+n+1)}}{(a+n+1)^{1-b}}\Big[\Gamma(1-b,(c+i\pi)(a+n+1))-\Gamma(1-b,(c-i\pi)(a+n+1))\Big]\end{align}\tag{1}$$

where $\Gamma(z,x)$ is the upper incomplete gamma function.
It is possible for this integral to be evaluated using it's branch cuts in the complex plane, but I think it's way more facile to consider the elementary identity
$$\frac{1}{(c-\ln z)^b}=
\frac{1}{\Gamma(b)}\int_{0}^{\infty}dy ~y^{b-1}e^{-(c-\ln z)y}$$
to rewrite the integral as
$$I=\int_{0}^{\infty}\frac{dy}{\Gamma(b)}y^{b-1}e^{-cy}\int_{|z|=1}z^{a+y}(1+z)^mdz$$
The interchange of integration and summation seems to be justified by Fubini's theorem, since the absolute value of this integral is definitely finite. For $a+y\in \mathbb{R}\setminus\mathbb{N}$ one can use a keyhole contour to show that
$$\int_{|z|=1}dz~z^{a+y}(1+z)^m+\lim_{\epsilon\to 0}\Bigg[2i\sin(\pi(a+y))\int_{\epsilon}^1dr~r^{a+y}(1-r)^m-i\int_{-\pi}^{\pi}d\theta~\epsilon ^{a+y+1}e^{i\theta(a+y+1)}(1+\epsilon e^{i\theta})^m\Bigg]=0$$
Now here's the tricky part: We are integrating over the variable $y$, which is positive. If $a+y>a>-1$ then the two summands enclosed in the limit below converge separately and the second one obviously converges to zero. We thus conclude that

$$\int_{|z|=1}dz~z^{a+y}(1+z)^m=-2i\sin(\pi(a+y))B(a+y+1,m+1)\tag{2}$$

However we note that $B(a+y+1,m+1)$ is a rational function of $y$ because
$$B(a+y+1,m+1)=\frac{\Gamma(m+1)\Gamma(a+y+1)}{\Gamma(m+a+y+2)}=\frac{m!}{(a+y+1)(a+y+2)...(a+y+m)(a+y+m+1)}$$
Keeping in mind that we can perform a partial fraction decomposition on this rational function, we seek to perform the integral
$$J(c,x)=\int_{0}^{\infty}dy\frac{y^{b-1}e^{-cy}}{y+x}$$
Taking a derivative with respect to $c$ we can easily show that
$$\frac{\partial J}{\partial c}=-\frac{\Gamma(b)}{c^b}+xJ\iff J(c,x)=\Gamma(b)\frac{e^{cx}}{x^{1-b}}\Gamma(1-b,cx)$$
where we used the fact that $\lim_{c\to\infty}J(c,x)=0$ which can be easily shown by an appropriate bound.
Now performing the partial fraction decomposition
$$\frac{m!}{(a+y+1)...(a+y+m+1)}=\sum_{n=0}^{m}\frac{A_n}{y+a+n+1}~~,~~ A_n=(-1)^n{m\choose n}$$
and substituting the value of the integral term by term and handling the sine appropriately we obtain the result.
EDIT:
Despite the limitations of the above proof it can actually be shown that the formula is general enough for all $a\in\mathbb{R}$. It's of key importance to note in order to generalize that eq. $(2)$ holds for all $a,y\in\mathbb{R}$ since it is an entire function in both:

$$\int_{|z|=1}dz~z^{a+y}(1+z)^m=\frac{2\pi i}{(m+1)B(a+y+m+2, -a-y)}\tag{2a}$$

Form $(2a)$ is not good for integration, however. To perform the integration it suffices to notice that the resulting poles coming from the partial fraction decomposition are annihilated by $\sin(\pi(a+y))$ because it has zeros precisely at $a+y=n\in \mathbb{Z}$. Then establish the following result
$$\begin{align}J(\lambda;b,c,x)&=\int_{0}^{\infty}dy\frac{y^{b-1}e^{-cy}\sin(\lambda(y+x))}{y+x}\\&=\frac{1}{2i}\frac{e^{cx}}{x^{1-b}}\Gamma(b)\Big[\Gamma(1-b,(c+i\lambda)x))-\Gamma(1-b,(c-i\lambda)x))\Big]\end{align}$$
Done!


text:
Q: Redux Actions No Longer Work after Converting to TypeScript I tried my best to convert existing code to TS.  But now for some reason, my calls to get initial data are no longer working after porting my code to TS.
HomePageContainer.tsx
class HomePageContainer extends Component<{
    featuredCompanies: Array<Company>,
    companies: Array<Company>,
    countries: Array<Country>
}, any> {
    async componentDidMount() {
        console.log('got here');
        await fetchFeaturedCompanies();
        console.log('got here');
        await fetchCompanies();
        await fetchCountries();
    }

    render() {
        return (
            <HomePage
                className="ft-homepage"
                companies={this.props.companies}
                countries={this.props.countries}
                featuredCompanies={this.props.featuredCompanies} />
        );
    }
}

const mapStateToProps = (state: any) => ({
    countries: state.country.countries,
    companies: state.company.companies,
    featuredCompanies: state.company.featuredCompanies,
});

const mapDispatchToProps = {
    fetchCountries,
    fetchCompanies,
    fetchFeaturedCompanies,
};

export default connect(mapStateToProps, mapDispatchToProps)(HomePageContainer);

It get the console.logs for 'got here' and also fetchFeaturedCompanies but that's it.
CompanyAsyncActions.ts
So it gets here and logs 'fetchFeaturedCompanies'.  But if I try to add a console.log inside async (dispatch: any) => { it doesn't hit it
export function fetchFeaturedCompanies() {
 console.log('fetchFeaturedCompanies');
 return async (dispatch: any) => {
  const response: any = await findFeatured();
  if (response && response.body) {
   const featuredCompanies = response.body;
   dispatch(featuredCompaniesReceived(featuredCompanies));
  }
 };
}

I don't know if there's something TS'ish for redux I need to do, or I messed up my TS definitions or what...there's really no errors either.
The expressjs server is definitely running.
api.ts (also was converted to using TS)
const _ = require('lodash'),
 companyTable = require('../shared/data/companies.json'),
 countryTable = require('../shared/data/countries.json'),
 compression = require('compression'),
 express = require('express'),
 historyApi = require('connect-history-api-fallback'),
 oneYear = 31536000;

module.exports = express()
 .use(compression())
 .on('error', (err: string) => {
  console.log(err);
 })
 .get('/api/v1/countries', (_req: any, res: any) => {
  res.json(countryTable.map((country: any) => _.pick(country, ['id', 'name', 'images'])));
 })
 .get('/api/v1/companies', (_req: any, res: any) => {
  res.json(
   companyTable.map((company: any) =>
    _.pick(company, [
     'id',
     'active',
     'images',
     'locations',
     'name',
     'new',
     'notInterviewed',
     'interview.apprenticeships.hasApprenticeship',
    ])
   )
  );
 })
 .get('/api/v1/companies/featured', (_req: any, res: any) => {
  console.log('get /api/v1/companies/featured');
  const companies = companyTable.filter((company: any) => company.featured.active);

  if (companies) {
   console.log('requesting companies from json');
   res.json(companies);
  } else {
   res.status(404).send('requested featured companies do not exist.');
  }
 })
 .get('/api/v1/companies/:companyId', (req: any, res: any) => {
  const company = companyTable.filter((company: any) => company.id === parseInt(req.params.companyId, 10))[0];

  if (company) {
   res.json(company);
  } else {
   res.status(404).send('The requested company does not exist.');
  }
 })
 .use(historyApi())
 .use(
  express.static('dist', {
   maxage: oneYear,
  })
 )
 .use((_req: any, res: any) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET,OPTIONS');
  res.header(
   'Access-Control-Allow-Headers',
   'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json'
  );
  res.send('Sorry, Page Not Found');
 });

UPDATE - per Michal's suggestion
lass HomePageContainer extends Component<{
    featuredCompanies: Array<Company>,
    companies: Array<Company>,
    countries: Array<Country>,
    fetchFeaturedCompanies: any,
    fetchCompanies: any,
    fetchCountries: any
}, any> {
    async componentDidMount() {
        console.log('got here');
        await this.props.fetchFeaturedCompanies();
        console.log('got here');
        await this.props.fetchCompanies();
        await this.props.fetchCountries();
    }

A: You still have to dispatch Redux actions in React components using this.props
  async componentDidMount() {
        console.log('got here');
        await this.props.fetchFeaturedCompanies();
        console.log('got here');
        await this.props.fetchCompanies();
        await this.props.fetchCountries();
    }

And put them in prop types, so that Typescript will compile.


text:
Q: Generate bytecode from .class file Error I've been trying to generate a bytecode from a class file via
Python27 and whenever I enter the full path of the .class file I always get this error:

A: Based on matching up the stacktrace with the github repo, it looks like the line where you're getting the error is
Bytecode = subprocess.Popen(['javap', '-c', Java_Class],\
                    stdout=subprocess.PIPE, stderr=subprocess.PIPE)

So Windows can't find javap. Can you make sure that you have the jdk installed? What happens when you try to run it on the command line?
Also, please post the text of the error instead of a screenshot.


text:
Q: Using charts in web application (negative value in bar chart) I want to use bar chart in web application.
I have searched many libraries including google code, and many but many do not support negative values for bar charts.

A: There are a couple of "hacks" to display negative values with the Google Charts API:

The above chart was generated using: http://chart.apis.google.com/chart?cht=bvs&chd=t:50,50,50,30,50|0,0,0,20,0|20,10,30,0,30&chco=00000000,ff0000,0000ff&chs=200x125&chg=0,51,1,0&chxt=y&chxl=0%3a|-50|0|50

You may want to check the following article for further reading about this workaround:

*

*Negative numbers in the Google Chart API

A: Flot is more than capable of displaying negative values. Have a look at this example I whipped up.

A: Open Flash Chart supports them as long as you set the graph scale accordingly, I think.
gRaphaël is also supposed to support them but there was a bug at some point and I don't know if it's fixed.


text:
Q: Create an SVG circle's drop shadow without the circle itself I want to create the shadow of an circle, while leaving the centre of the circle transparent.

I can't work out how to do it. I've tried using masks and filters, but they seem to cancel each other out. The mask cuts off the filter.
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
  width="200" height="200" viewBox="0 0 200 200" >
  <defs>
    <filter id="blur">
      <feDropShadow dx="0" dy="0" stdDeviation="4.5"
          flood-color="black"/>
    </filter>
    <mask id="circle-mask" x="0" y="0" width="1" height="1">
      <circle cx="75" cy="75" r="50" />
    </mask>
  </defs>
  <circle cx="75" cy="75" r="50" style="mask: url(#circle-mask) filter: url(#blur)"/>
</svg>

I've tried used a circle as a clipPath, but that clips everything outside the circle (I want to clip the inside). I've tried messing the groups, putting the mask on the group and the filter on the circle (and the other way round). I've tried putting the mask and the filter into a style.
I'm not getting anywhere. How do I make the inside of the circle transparent?

A: You can do this in a compact way by extending your filter. The additional feComposite/out  will remove anything that overlaps with the original shape (assuming your shape is always fully opaque).

body {
background: grey;
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
  width="200" height="200" viewBox="0 0 200 200" >
  <defs>
    <filter id="blur-out">
      <feDropShadow dx="0" dy="0" stdDeviation="4.5"
          flood-color="black"/>
      <feComposite operator="out" in2="SourceGraphic"/>
    </filter>
  </defs>
  <circle cx="75" cy="75" r="50" filter= "url(#blur-out)"/>
</svg>

A: Just make the mask bigger. You'll need to make the bits you don't want to mask white and the bits you do black.

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
  width="200" height="200" viewBox="0 0 200 200" >
  <defs>
    <filter id="blur">
      <feDropShadow dx="0" dy="0" stdDeviation="4.5"
          flood-color="black"/>
    </filter>
    <mask id="circle-mask" x="-0.2" y="-0.2" width="1.4" height="1.4">
      <rect width="100%" height="100%" fill="white"/>
      <circle cx="75" cy="75" r="50" fill="black"/>
    </mask>
  </defs>
  <circle cx="75" cy="75" r="50" style="mask: url(#circle-mask); filter: url(#blur)"/>
</svg>


text:
Q: Overriding Option in Base Web Menu breaks keyboard bindings Update August 20:
@mark_reeder and I had a follow up chat on the Base Web Slack. Mark explained to me that you can pass a component to the label prop (as opposed to passing a string). So now, instead of overriding Option with my own custom component, I just pass a custom label component with an icon to label. Much easier!Thanks again, @mark_reeder.
Update August 16:
I accepted the answer of @mark_reeder. This fixed the issue of getting the focus states to work. However, clicking "Enter" to select the focused element still did not work, I ended up adding an event listener to the body and doing some kludegy logic. I'm hoping someone out there has a better way.

I'm new to Base Web. I built a custom "more options" menu (aka "kebab" menu). I wanted the options to have icons so I did an override on the Option in the Menu component. It looks good, but the keyboard bindings no longer work. If I comment out the override, the keyboard bindings work (but then I lose the icons).
Here is my code:
//MoreOptionsMenu.js

import React from 'react'
import { StatefulPopover, PLACEMENT } from 'baseui/popover'
import Overflow from 'baseui/icon/overflow'
import { StatefulMenu } from 'baseui/menu'
import IconOption from 'Components/Shared/IconOption/IconOption'
import InvisibleButtonWrapper from 'Components/Shared/InvisibleButtonWrapper/InvisibleButtonWrapper'

const MoreOptionsMenu = ({ items, placement = PLACEMENT.bottom, ariaLabel, id }) => {
  return (
    <StatefulPopover
      content={({ close }) => (
        <StatefulMenu
          items={items}
          overrides={{
            Option: {
              component: IconOption,
              props: {
                close,
                ariaLabel,
                id
              }
            },
            List: {
              style: ({ $theme }) => ({
                borderTopLeftRadius: '6px',
                borderTopRightRadius: '6px',
                borderBottomLeftRadius: '6px',
                borderBottomRightRadius: '6px',
                border: `1px solid ${$theme.colors.lightGray}`,
              })
            }
          }}
        />
      )}

      accessibilityType={'tooltip'}
      placement={placement}
    >
      <InvisibleButtonWrapper>
        <Overflow size={24} aria-label={ariaLabel} style={{ marginLeft: 'auto', cursor: 'pointer' }}/>
      </InvisibleButtonWrapper>
    </StatefulPopover>
  )
}

export default MoreOptionsMenu

//IconOptions
import React, { forwardRef } from 'react'
import { useStyletron } from 'baseui'
import { stringToKebabCase } from 'Shared/Utilities'
import InvisibleButtonWrapper from 'Components/Shared/InvisibleButtonWrapper/InvisibleButtonWrapper'

const IconOption = forwardRef(( { close, item, ariaLabel, id }, ref) => {
  const [css, theme] = useStyletron()
  return (
    <li
      role='option'
      aria-disabled='false'
      aria-selected='false'
      id={stringToKebabCase(`${id}-${item.label}`)}
      className={css({
        display: 'flex',
        alignItems: 'center',
        padding: '10px',
        cursor: 'pointer',
        ':hover': {
          outline: `${theme.colors.accent} solid 3px`
        },
        ':focus': {
          outline: `${theme.colors.accent} solid 3px`
        },
        ':active': {
          outline: `${theme.colors.accent} solid 3px`
        },
        ':nth-child(even)': {
          backgroundColor: theme.colors.lighterGray
        }
      })}
      aria-labelledby={ariaLabel}
      ref={ref}
      onClick={() => {
        typeof item.callback === 'function' && item.callback()
        close()
      }}>
      <InvisibleButtonWrapper>
        {item.icon}
        {item.label}
      </InvisibleButtonWrapper>

  )
})

export default IconOption

// InvisibleButtonWrapper.js

import { withStyle } from 'baseui'
import { StyledBaseButton } from 'baseui/button'

const InvisibleButtonWrapper = withStyle(StyledBaseButton, ({$theme}) => ({
  paddingTop: 0,
  paddingBottom: 0,
  paddingLeft: 0,
  paddingRight: 0,
  color: `${$theme.colors.primaryA}`,
  backgroundColor: 'inherit',
  ':hover': {
    color: `${$theme.colors.primaryA}`,
    backgroundColor: 'inherit',
  }
}))

export default InvisibleButtonWrapper

Here is a sandbox so you can see / play with the code
A few more notes in anticipation of questions that people may have. The reason I use forwardRef is that I was getting an error about function components not being able to receive refs. The keyboard bindings do not work regardless of whether I use forwardRef. The InvisibleButtonWrapper is intended to make the component more accessible without breaking the styles. Removing it does not seem to affect the keyboard bindings.
Also, is there an idiomatic Base Web way to do this that I am missing? The docs say "Each menu item has an option to include an icon by default, but this can be removed." However, there is not example of how to make that work. Before I created my own custom component, I tried simply adding an icon property to the items but it did not render.

Latest file update with fixes from mark_reeder and aforementioned event listener on document:
import React, { forwardRef, useEffect } from 'react'
import { useStyletron } from 'baseui'
import { stringToKebabCase } from 'Shared/Utilities'
import InvisibleButtonWrapper from 'Components/Shared/InvisibleButtonWrapper/InvisibleButtonWrapper'

const IconOption = forwardRef((props, ref) => {
  const [css, theme] = useStyletron()
  const { close, item, ariaLabel, id, $isHighlighted, $isFocused } = props

  const handleKeyDown = ({ code }) => {
    if (code === 'Enter') {
      document.querySelector("[data-iconoption='true'][aria-selected='true']").click()
    }
  }

  useEffect(() => {
    document.addEventListener('keydown', handleKeyDown)
      return () => {
        document.removeEventListener('keydown', handleKeyDown)
      }
  }, [])

  return (
    <li
      data-iconoption={'true'}
      tabIndex={0}
      role='option'
      aria-selected={props['aria-selected'] ? 'true' : 'false'}
      id={stringToKebabCase(`${id}-${item.label}`)}
      className={css({
        backgroundColor: $isHighlighted ? theme.colors.lighterGray : theme.colors.white,
        display: 'flex',
        alignItems: 'center',
        padding: '10px',
        cursor: 'pointer',
        ':hover': {
          backgroundColor: theme.colors.lighterGray
        },
        ':focus': {
          backgroundColor: theme.colors.lighterGray
        },
      })}
      aria-labelledby={ariaLabel}
      ref={ref}
      onClick={() => {
        typeof item.callback === 'function' && item.callback()
        close()
      }}>
      <InvisibleButtonWrapper>
        {item.icon}
        {item.label}
      </InvisibleButtonWrapper>

  )
})

export default IconOption

A: The base menu components rely on props to display the highlighted menu item: https://github.com/uber/baseweb/blob/master/src/menu/styled-components.tsx#L50
Two changes to your IconOption will get your outlines showing up:
First, add $isHighlighted to your props list for IconOption -
const IconOption = forwardRef(({ $isHighlighted, close, item, ariaLabel, id }, ref) => {

Second, modify your outline in the style of your li in IconOption based on the value of $isHighlighted:
outline: $isHighlighted ? `${theme.colors.accent} solid 3px` : 'none',

As far as more Idiomatic Base Web ways of doing this, there are some examples that include images that might work for you like https://baseweb.design/components/menu/#menu-with-profile-menu


text:
Q: Web browser find anchor and autoclick in c# I am creating one tool in which i have used C# browser control, which automatically logs in IRCTC and book the ticket. everything is working fine, except one page. i am not able to click through browser, how can i find the anchor and click through C# browser.Below is the HTML:

            <colgroup span="16">
            </colgroup>

                        Train No.

                        Train Name

                        From

                        Departure

                        To

                        Arrival

                        Dist.(Km)

                        Travel Time

                        M

                        T

                        W

                        T

                        F

                        S

                        S

                        Class

                        12141

                        RAJENDRA NGR EXP

                        CSTM

                        23:25

                        JBP

                        14:15

                        997

                        14:50

                        Y

                        Y

                        Y

                        Y

                        Y

                        Y

                        Y

                            1A
                                2A
                                    3A
                                        SL O,

here i want to click on below through browser. i am not able to find below anchor: Please help me:
 SL.

A: You could inject html into the page that is loaded in the browser control and load jquery, then inject javascript the same way that uses jquery to find the anchor tag and click it.
HtmlElement head = idOfBrowserControl.Document.GetElementsByTagName("head")[0];

HtmlElement script1 = idOfBrowserControl.Document.CreateElement("script");
script.SetAttribute("type", "text/javascript");
script.SetAttribute("src", "//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js");

HtmlElement script2 = idOfBrowserControl.Document.CreateElement("script");
script.SetAttribute("type", "text/javascript");
script.InnerHtml = "function clickAnchor() { $($('a', '#avlAndFareForm:trainbtwnstns:6:j_idt311')[0]).click();}}";

head.AppendChild(script1);
head.AppendChild(script2);

Then when you want to click it, do
idOfBrowserControl.Document.InvokeScript("clickAnchor");

You don't have to inject jQuery, I just do that because I use jQuery for everything...  It's easier.


text:
Q: Why is the cutoff for AUC (area under ROC curve) to be considered an acceptable classfier at .7 and what is it acceptable for? From reading about interpreting the area under a ROC curve, it seems the general consensus is that anything from .7 - .8 is considered an acceptable classifier. What is it considered "acceptable" for? It seems like a quite vague interpretation. I was also wondering why anything above .7 is considered good. For example, some classifiers need high accuracy to be used (like using face recognition as a password on phones) while others don't need nearly that high of accuracy.

A: The area under an ROC curve

is equal to the probability that a classifier will rank a randomly chosen positive instance higher than a randomly chosen negative one (assuming 'positive' ranks higher than 'negative').

So if a 70% or 80% probability of getting the case ordering correct is good enough, then those AUC values are "acceptable."  As you note, whether that's actually good enough depends on the field of application. My guess is that whatever you read that led you to your sense of a "consensus" about the quality of those AUC values might have been based more on the difficulty of getting models in practice to do much better than that, at least in fields like clinical medicine.


text:
Q: Can Xbox One S and DualShock 4 controllers work over bluetooth at the same time? I just bought a Xbox One S controller and a Bluetooth 4.0 CSR dongle for my PC.
It works great.
Now I want to play games (mostly FIFA) with my brother and I need to buy another controller. I listed my preferred ways but I don't know if they work.
If anyone has tried these scenarios or is %100 sure that one way works please let me know.

*

*Xbox One S controller and DS4 over BT

*Two Xbox One S controllers over BT (as far as I searched this one is not possible)

*Xbox One S controller over BT and another controller (whatever it may be) over USB cable

I know that Microsoft and Sony each have their official dongle for connecting their controllers to PC (and this will be my last option if above ways wont work) but since I have Bluetooth I was wondering If the two can work together.

A: You should be able to pair all of them to the same PC with one Bluetooth dongle. I just tested with two Xbox One S controllers and two Dualshock 4 controllers and it worked fine. You may need third party drivers for the Dualshock 4 depending on the software you're trying to use it with.
Don't buy the official dongles. The Xbox One dongle is only for the OLD pre-S gamepads that do not support Bluetooth. The dongle does nothing for Xbox One S controllers. The Dualshock 4 dongle will work but it can only handle one controller at a time and isn't necessary if you already have a working Bluetooth dongle.
Both controllers work well with a micro USB cable.

A: Xbox website states - "We recommend connecting only one controller at a time using Bluetooth." You can freely connect PS4 DualShock 4 controller via USB as long as cable length is enough.


text:
Q: HTML Root Links I have a hello.css in 100-days-of-code folder as follows :
Refer here
can anyone help me for the href tag to navigate from Day-5 hello-css.html-->hello.css in parent directory?

A: ../../100-days-of-code/hello.css should be the path you are looking for.

A: <link rel="stylesheet" type="text/css" href="../../100-days-of-code/hello.css">


text:
Q: Databinding to property is working, but not updating I have property in model:
private EditorSelectionTool SelectionTool { get; set; }

Binding:
 <DataTemplate DataType="{x:Type viewModels:EditorSelectionTool}">
                    <Rectangle Stroke="White" StrokeThickness="1" StrokeDashArray="4 4" Width="{Binding Width}" Height="{Binding Height}" Visibility="{Binding Visibility}"/>
                </DataTemplate>

Model is derivated from PropertyChangedBase class (Caliburn.Micro)
And method which change the property fields:
 public void StartSelecting(Point point)
    {
        SelectionTool.X = point.X;
        SelectionTool.Y = point.Y;
        NotifyOfPropertyChange(() => SelectionTool);
    }

Debug shows that method was called. But change in UI is not happening.
SelectionTool class:
   public class EditorSelectionTool
{
    public double X { get; set; }
    public double Y { get; set; }
    public double Width { get; set; }
    public double Height { get; set; }
    public Visibility Visibility { get; set; }
}

A: You're firing the property changed event on a property called SelectionTool. However you've never fired the property changed event on Height and Visibility.
In some cases this would work--it depends on if something is actually bound to SelectionTool. In such a case it would force the bindings further "down the chain" to also reload. But since you're having problems, I assume that doesn't apply to your specific binding scenario.
In Visual Studio, the output window often has information about binding failures.

A: Seeing you are using Caliburn.Micro, you will need to update your EditorSelectionTool to implement PropertyChangedBase and as Paul K mentioned, add property change notifications to each property.
public class EditorSelectionTool : PropertyChangedBase
{
    private double _x;
    private double _y;
    private double _width;
    private double _height;
    private Visibility _visibility;

    public double X
    {
        get { return _x; }
        set
        {
            _x = value;
            NotifyOfPropertyChange(()=> X);
        }
    }

    public double Y
    {
        get { return _y; }
        set
        {
            _y = value;
            NotifyOfPropertyChange(() => Y);
        }
    }

    public double Width
    {
        get { return _width; }
        set
        {
            _width = value;
            NotifyOfPropertyChange(() => Width);
        }
    }

    public double Height
    {
        get { return _height; }
        set
        {
            _height = value;
            NotifyOfPropertyChange(() => Height);
        }
    }

    public Visibility Visibility
    {
        get { return _visibility; }
        set
        {
            _visibility = value;
            NotifyOfPropertyChange(() => Visibility);
        }
    }
}

A: You notify a change on SettingTool, but that property has not changed at all. It is the same instance and therefore there is no change.
And even if you notify a change, WPF will check, if there is really a change by comparing the old with the current value (here the instance of SettingTool).

*

*Create a new instance of EditorSelectionTool, assign this to the property and notify the change

or

*Implement a change notification on each property in EditorSelectionTool


text:
Q: What is the best way to host node.js app on Windows? I have a RESTful API implemented on nodejs which I have to host on Windows. Now app is just simple RESTful service, maybe in future I will implement the backoffice for it to manage users, display statistic etc. So for now app is just an API, but maybe in future it will be extended to serve few pages with dynamic content, I am not going to provide access to the static content (except regular content for web apps: favicon, images, css, js files etc).
After research I see few options to host my app on Windows:

*

*Use windows service to run the node server.

*Use IIS and IISNode module as a front server.

*Use Nginx on Windows as a front server (I didn't work with Nginx, but it seems that it can be used to host node and can be used on Windows).

My questions:

*

*As I understood it is better to use some front server. This approach has a lot of benefits: you can manage app state, logs, domain names etc. What are the benefits of using windows service to host the app?

*How to choose between IIS and Nginx. Is it wise to use Nginx on Windows, does it have some advantages?

A: IISNode has a number of benefits which are outlined on the project page. https://github.com/tjanczuk/iisnode/wiki
I would lean that direction primarily because if you have to host it on Windows, that indicates there is someone who knows how to manage Windows servers and that would typically include IIS. If you set up your own Windows service, you become responsible for scalability and recovering the process if it crashes.


text:
Q: Why the index of a v-for used as a method parameter in another component doesn't equal to the initial index value? My problem is the following one: I have a list of bank accounts, they are looped in a v-for. For each bank account, I have a button to be able to delete it. When a user delete a bank account, I want to display a confirmation modal with a confirm method. I have to pass the index of the v-for to the method to know which element I have to delete from the original array. When I passed that index, it doesn't match to the index of the current element.
Here is a visual support:

  <ModalConfirm @close="showModal = false" @confirmDelete="deleteBA(index)" v-if="showModal" />

{{ bankAccount.name }}

      <button @click="showModal = true">
        Delete bank account
      </button>

So here, the index value in the method deleteBA is not the same than the original index of the v-for. I can't understand why !
I created a live example:
https://codesandbox.io/s/6jo79vr1lk
Thanks for any help !

A: The issues is in the following code:
<template>

{{ index }}

          <button @click="showModal = true;">Delete bank account {{element}}</button>

        <ModalConfirm
          @close="showModal = false;"
          @confirmDelete="deleteBA(index);"
          v-if="showModal"
        />

</template>

you have one modal for each account , but use a single boolean value to toggle all. @click="showModal = true;"
While there are ways to handle that by adding a modal boolean for each item, it's unnecessary to have a modal for each item, and better to reuse the same modal.
you can use a modal index instead of a boolean, so @click="showModal = index"
<template>

{{ index }}

          <button @click="showModal = index;">Delete bank account {{element}}</button>

    <ModalConfirm
      @close="showModal = -1"
      @confirmDelete="deleteBA(showModal);"
      v-if="showModal >= 0"
    />

</template>


text:
Q: how to store value in session in asp.net core? I want to hold input data in session in the view and later send it to the controller. how can I do that?
I have two textboxes in view and I want to store those data in session .then post it with ajax to the controller.
how can I achieve that?

A:
I want to hold input data in session in the view and later send it to the controller. how can I do that? I have two textboxes in view and I want to store those data in session .then post it with ajax to the controller. how can I achieve that?

Please note you can not directly set Session variable on client side JavaScript.
For more information about Session state and accessing Session values in ASP.NET Core, please check the following doc:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-5.0#set-and-get-session-values
Besides, sessionStorage could help maintain a separate storage area for each given origin that's available for the duration of the page session. You can try to store input data in sessionStorage while textboxes/input fields' change event is triggered, so that you can get stored data from sessionStorage and make AJAX request with data to your controller action.
For more information about sessionStorage, please check:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API

A: In asp.net Controller is backside, so you want to store data fronside in for example js?
In the browser with js and other frontside frameworks you can store data literally ANYWHERE, try window.localStorage, window.sessionStorage or in a SPA app try a global variable.
I would like to see an answer for backside in asp.net session.


text:
Q: Restful APIs: readonly / writeonly fields I have a conceptual question with restful apis. In my data model, I have countries and companies.
Users of the api won't be able to create country objects. There are constant entries in the database for countries. They will be creating company objects, which have country as a field. So when creating a company, api expects a json like:
{
    'name': 'company name',
    'country': 5, // country id
    ...
}

On the client side, when displaying a company, we also want to display its country. One approach to this is, after getting a company resource, we issue another get request to get the country object. But this approach is problematic performance-wise, especially on the pages we list multiple companies.
Another approach would be to include country details in another field on get requests, like:
{
    'name': 'company name',
    'country': 5, // country id
    'country_details': {
        'name': 'USA',
        'phone_code': 1,
        'id': 5
    }
    ...
}

I do not think that this is the correct approach either, as data representation is different for post and get requests for the same resource. Have any suggestions for this case?

A:
...as data representation is different for post and get requests for the same resource.

POST from RFC 7231:

The POST method requests that the target resource process the
representation enclosed in the request...

Whereas PUT:

The PUT method requests that the state of the target resource be
created or replaced with the state defined by the representation
enclosed in the request message payload.  A successful PUT of a given
representation would suggest that a subsequent GET on that same
target resource will result in an equivalent representation being
sent in a 200 (OK) response.

And:

The fundamental difference between the POST and PUT methods is
highlighted by the different intent for the enclosed representation.
The target resource in a POST request is intended to handle the
enclosed representation according to the resource's own semantics,
whereas the enclosed representation in a PUT request is defined as
replacing the state of the target resource.

So POST and GET bodies differing is not a problem, but it would be for PUT and GET. I would make the distinction clearer by not using the same URL for POST and GET. Which makes sense anyway as the GET would include a company identifier, whereas the POST won't.
For example, maybe it makes sense for companies to be posted to a country URL, this way we don't need to include the country id in the body:
POST: /usa/company

BODY: { 'name': 'company name' }

RESPONSE: 200 with Content-Location header: /companies/1

Then the subsequent GET of that Content-Location:
GET: /companies/1

RESPONSE: { 'name': 'company name', 'country': 'USA' }


text:
Q: Find all local maxima of a geom_smooth curve in R ggplot? I need to find all local maxima of a geom_smooth() curve in R. This has been asked in Stack Overflow before:
How can I get the peak and valleys of a geom_smooth line in ggplot2?
But the answer related to finding a single maximum. What if there are multiple local maxima we want to find?
Here's some sample data:
library(tidyverse)

set.seed(404)
df <- data.frame(x = seq(0,4*pi,length.out=1000),
                 y = sin(seq(0,4*pi,length.out=1000))+rnorm(100,0,1))

df %>% ggplot(aes(x=x,y=y)) +
  geom_point() +
  geom_smooth()

To find a single maximum, we use the function underlying geom_smooth() in order to get the y values of the curve. This would be either gam() for 1000+ data points or loess() for fewer than 1000. In this case, it's gam() from library(mgcv). To find our maximum is a simple matter of subsetting with which.max(). We can plot the modeled y values over geom_smooth() to confirm they're the same, with our maximum represented by a vertical line:
library(mgcv)

df <- df %>%
  mutate(smooth_y = predict(gam(y ~ s(x,bs="cs"),data=df)))

maximum <- df$x[which.max(df$smooth_y)]

df %>% ggplot() +
  geom_point(aes(x=x,y=y)) +
  geom_smooth(aes(x=x,y=y)) +
  geom_line(aes(x=x,y=smooth_y),size = 1.5, linetype = 2, col = "red")  +
  geom_vline(xintercept = maximum,color="green")

So far, so good. But, there is more than one maximum here. Maybe we're trying to find the periodicity of the sine wave, measured as the average distance between maxima. How do we make sure we find all maxima in the series?
I am posting my answer below, but I am wondering if there's a more elegant solution than the brute-force method I used.

A: You can find the points where the difference between subsequent points flips sign using run-length encoding. Note that this method is approximate and relies on x being ordered. You can refine the locations by predicting more closely spaced x-values.
library(tidyverse)
library(mgcv)

set.seed(404)
df <- data.frame(x = seq(0,4*pi,length.out=1000),
                 y = sin(seq(0,4*pi,length.out=1000))+rnorm(100,0,1))

df <- df %>%
  mutate(smooth_y = predict(gam(y ~ s(x,bs="cs"),data=df)))

# Run length encode the sign of difference
rle <- rle(diff(as.vector(df$smooth_y)) > 0)
# Calculate startpoints of runs
starts <- cumsum(rle$lengths) - rle$lengths + 1
# Take the points where the rle is FALSE (so difference goes from positive to negative)
maxima_id <- starts[!rle$values]

# Also convenient, but not in the question:
# minima_id <- starts[rle$values]

maximum <- df$x[maxima_id]

df %>% ggplot() +
  geom_point(aes(x=x,y=y)) +
  geom_smooth(aes(x=x,y=y)) +
  geom_line(aes(x=x,y=smooth_y),size = 1.5, linetype = 2, col = "red")  +
  geom_vline(xintercept = maximum,color="green")
#> `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

Created on 2020-12-24 by the reprex package (v0.3.0)

A: I went with a brute force, Monte Carlo method to solve the problem. Using replicate(), we try out 100 random ranges of x and find the maximum y value within each range. We reject maxima that occur at either end of the range. Then we find all unique values of the output vector:
maxima <- replicate(100,{
  x_range <- sample(df$x,size=2,replace=FALSE) %>% sort()
  max_loc <- df %>%
    filter(x >= x_range[1] & x <= x_range[2]) %>%
    filter(smooth_y == max(smooth_y)) %>%
    pull(x)
  if(max_loc == min(x_range)|max_loc == max(x_range)){NA}else{max_loc}
})
unique_maxima <- unique(maxima[!is.na(maxima)])

df %>% ggplot() +
  geom_point(aes(x=x,y=y)) +
  geom_smooth(aes(x=x,y=y)) +
  geom_line(aes(x=x,y=smooth_y),size = 1.5, linetype = 2, col = "red")  +
  geom_vline(xintercept = unique_maxima,color="green")


text:
Q: Setting lsp-dart indentation The Flutter/Dart project
recommends
using the lsp-dart package.
I'm quite partial to an indentation of 4 spaces. What's the appropriate way to set it in ~/.emacs?
Curiously, flutter format  itself doesn't offer such an option, making for a rather heavy-handed set of tools.

A: flutter format uses the heavily road-tested values from the home office. And yes, it's highly opinionated, and ensures whitespace or rewrapping doesn't needlessly occur when editing someone else's code and submitting a pull request. Considering the hoarde of people working on Dart at Google, this is a wise choice.


text:
Q: How can I speed up the query? How can I speed up this query?
 l_string varchar2(200);
 /* parameter string */
 l_string := ':27.07.2015:10.07.2015:23.07.2015:01.08.2015:';

 select  t3.*
  from  table1 t1, table2 t2, table3 t3
 where  t1.col1 = t2.col2
   and  t2.col3 = t3.col4
   and  (instr(l_string, ':' || to_char(t3.col1, 'dd.mm.yyyy') || ':') > 0 OR
         instr(l_string, ':' || to_char(t3.col2, 'dd.mm.yyyy') || ':') > 0 OR
         instr(l_string, ':' || to_char(t3.col3, 'dd.mm.yyyy') || ':') > 0 OR
         instr(l_string, ':' || to_char(t3.col4, 'dd.mm.yyyy') || ':') > 0 OR
         instr(l_string, ':' || to_char(t3.col5, 'dd.mm.yyyy') || ':') > 0 OR
         instr(l_string, ':' || to_char(t3.col6, 'dd.mm.yyyy') || ':') > 0 OR
         instr(l_string, ':' || to_char(t3.col7, 'dd.mm.yyyy') || ':') > 0 OR
         instr(l_string, ':' || to_char(t3.col8, 'dd.mm.yyyy') || ':') > 0 OR
         instr(l_string, ':' || to_char(t3.col9, 'dd.mm.yyyy') || ':') > 0 );

A: Your predicate with instr doesn't allow index access. So you are ending with full table scan of T3.
You may formulate the predicate diferently as:
 where col1 in (to_date('27.07.2015','dd.mm.yyyy'),
           to_date('10.07.2015','dd.mm.yyyy'),
           to_date('23.07.2015','dd.mm.yyyy'),
           to_date('01.08.2015','dd.mm.yyyy')) or
  col2 in (to_date('27.07.2015','dd.mm.yyyy'),
           to_date('10.07.2015','dd.mm.yyyy'),
           to_date('23.07.2015','dd.mm.yyyy'),
           to_date('01.08.2015','dd.mm.yyyy')) or
  col3 in (to_date('27.07.2015','dd.mm.yyyy'),
           to_date('10.07.2015','dd.mm.yyyy'),
           to_date('23.07.2015','dd.mm.yyyy'),
           to_date('01.08.2015','dd.mm.yyyy')) or
 .... -- etc for columns col3 - col9

If the table T3 is large and the predicate above selectes only few records, you may profite with defining indexes on col1 to col9
 create index t3_ix1 on t3(col1);
 create index t3_ix2 on t3(col2);
 ....

The possible execution plan will perform 9 * 3 (columns * values) INDEX RANGE SCAN and BITMAP CONVERSION to get the OR result. So for realy huge T3 the 27 index range scan will be better that FULL SCAN an dyou will speed up; but it depends on your data...

A: I do not have an Oracle instance to test, but OR conditions almost always slow down execution as does calling instr multiple times.  Try doing one large concatenation and searching for the value in there.  You'll notice I added a '~' to make sure you didn't get a match from data due to the concatenation:
select  t3.*
  from  table1 t1, table2 t2, table3 t3
 where  t1.col1 = t2.col2
   and  t2.col3 = t3.col4
   and  instr(l_string,
         (':' || to_char(t3.col1, 'dd.mm.yyyy') || ':' ||
         '~:' || to_char(t3.col2, 'dd.mm.yyyy') || ':' ||
         '~:' || to_char(t3.col3, 'dd.mm.yyyy') || ':' ||
         '~:' || to_char(t3.col4, 'dd.mm.yyyy') || ':' ||
         '~:' || to_char(t3.col5, 'dd.mm.yyyy') || ':' ||
         '~:' || to_char(t3.col6, 'dd.mm.yyyy') || ':' ||
         '~:' || to_char(t3.col7, 'dd.mm.yyyy') || ':' ||
         '~:' || to_char(t3.col8, 'dd.mm.yyyy') || ':' ||
         '~:' || to_char(t3.col9, 'dd.mm.yyyy') || ':') > 0

I would explore other options, but without more information that's all I can offer.


text:
Q: Button script wasn't updated from the change set Some time ago I deployed change set to the production - 1 button and 4 validation rules. Now I have noticed that despite deployment status was "Deploy: Succeeded", button code wasn't updated (but validation rules was).
How can it be possible, that button script wasn't updated from the change set?


text:
Q: FitSharp and x86 .Net dll I have an ActionFixture that is compiled into a x86 dll.  When I run the test from fitnesse test starts but never finishes.  Is there any way to get fitnesse to run a dll compiled as x86?

A: If you compile your dll's as 32 bit (x86) you may encounter problems when running fitnesse tests using the fsharp runner.exe.  The solution I have used to resolve the problem is to run corflags.exe against the runner.exe.  This will effectively change the runner to a 32 bit application. corflags comes as part of the Windows Development SDK which can be downloaded off the Microsoft website.
corflags runner.exe /32BIT+

A: Not sure what's happening. Run with the GUI runner and see if you get an exception. See http://www.asoftwarecraft.com/2010/01/troubleshooting-with-fitsharp-and.html


text:
Q: drive_auth() function not creating gargle-oauth token on password submission R v3.6.2
RStudio Desktop v1.2.5033
R package 'googledrive' v1.0.0
I have written an R script that uploads csv files to a googlesheets account. In order to avoid having to automate this, I have used the drive_auth() function to refresh the OAuth token. Code is simply:
drive_auth(
 email = "email@gmail.com",
 path = NULL,
 scopes = "https://www.googleapis.com/auth/drive",
 cache = gargle::gargle_oauth_cache(),
 use_oob = gargle::gargle_oob_default(),
 token = NULL
)

drive_upload(file, overwrite=TRUE, type="spreadsheet")

On both a mac and a Windows OS machine, this then opens a default browser that asks for login details. When these are correctly entered, the script now has permissions to upload / edit files and googledrive functions subsequently work. It creates an authority token in the file path:
Home/Users/.R/garle/gargle-oauth
However, when attempting to do this on a new laptop that will be used as a server, I am met with the following error messages:
Error: can't get Google credentials.
Are you running googlesheets in a non-interactive session? Consider:
* sheets_deauth() to prevent the attempt to get credentials.
* call 'sheets_auth()' directly with all necessary specifics.

On inspection of the gargle-oauth folder, it has not created an OAuth token, as it did automatically with other machines on the entering of google login details.
I re-ran the programme on the other windows machine after deleting the OAuth token and it worked fine, creating the token again from scratch. I cannot pinpoint the reason why this token is not being created in this instance.

A: I've since solved this and I'm going to post an answer in case anyone is in a similar problem and comes across this post during a google search.
When initialising a connection with googledrive, the package uses the default port of 1410. It was unable to establish a connection with google because a zombie process was using this port.
To kill this process, open up the windows command prompt (or command line on a mac) as admin and enter the netstat command:
C:\Users>netstat -ano|findstr "PID :1410"

This will (if anything is running on this port) return:
Proto Local Address Foreign Address State PID
TCP 0.0.0.0:1410.0.0.0:0 LISTENING 18264

That number at the bottom right is the process PID, enter that into the following command to kill the process:
taskkill /pid 18264 /f

When running any R googledrive functions, you should now be able to authorise your code to interact with your google account and it will create an OAuth token to save you having to go through this again.

A: I confirm that this problem also got me on Ubuntu. I resolved it by finding and killing the process on port 1410 (which was also listening on 40167):
me@me:/internal$ netstat -tulpn
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
PID/Program name
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:3000            0.0.0.0:*               LISTEN      894/node
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:25              0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:1410          0.0.0.0:*               LISTEN      21011/R
tcp        0      0 127.0.0.1:40197         0.0.0.0:*               LISTEN      21011/R
tcp        0      0 127.0.0.1:9000          0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      -
tcp6       0      0 :::22                   :::*                    LISTEN      -
tcp6       0      0 :::25                   :::*                    LISTEN      -
tcp6       0      0 :::443                  :::*                    LISTEN      -
tcp6       0      0 :::1917                 :::*                    LISTEN      1277/node /home/ult
tcp6       0      0 :::3838                 :::*                    LISTEN      -
tcp6       0      0 ::1:6379                :::*                    LISTEN      -
tcp6       0      0 :::80                   :::*                    LISTEN      -
udp        0      0 127.0.0.53:53           0.0.0.0:*                           -

me@me:/internal$ kill -HUP 21011


text:
Q: User control "ascx" file with C# I have a user control, basically consists of a tree view and also a drop down list..
The user control shows something like
(For the tree view)
  Books
    Learn Algebra in 24hrs (30)
    Learn Calculus in 1 week (16)

(For the Drop Down)
--- Books ----
Learn Algebra in 24hrs (30)
Learn Calculus in 1 week (16)

the designer wants to be able to set a property to "true" or "false" in the ascx file that will hide the count on the right (if true shows, if false hides). The count comes from a database along with the product name.
How can I achieve this?, the do not want to deal with C#, but want to be able to deal with the "ascx" file.
Thank you in advance

A: Create a public property in your User Control, which can be set in the HTML when you use the control.
using System;

namespace RohmPortal.Portal.Controls
{
    public partial class WebUserControl1 : System.Web.UI.UserControl
    {
        public bool DisplayTitle { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}

Used like.
<uc2:WebUserControl1 ID="WebUserControl11" DisplayTitle="false" runat="server" />


text:
Q: Of all probability matrix $P$ having stationary distribution $\pi$, find the one having smallest diagonal I am requesting your help today trying to solve a somewhat odd problem. Is there a way to find through some numerical algorithm such as Newton's method the stochastic matrix $\boldsymbol{P}$ having stationary distribution $\boldsymbol{\pi}$ (column vector, given as an input) and lowest diagonal (whose elements are closest to 0)?
I initially thought about minimizing the following loss function:
$$L(\boldsymbol{P}) = {(\mathrm{diag}(\boldsymbol{P}))}^\mathsf{T} \mathrm{diag}(\boldsymbol{P}) + \lambda_1 {||\boldsymbol{P}^\mathsf{T}\boldsymbol{\pi} - \boldsymbol{\pi}||}^2 + \lambda_2 {||\boldsymbol{P}\boldsymbol{e} - \boldsymbol{e}||}^2,$$
where $\mathrm{diag}$ returns the diagonal of its argument, $\lambda_1$ and $\lambda_2$ are both Lagrange multipliers, and $\boldsymbol{e}$ is a vector filled with 1 (same dimensions as $\boldsymbol{\pi}$).
As far as I know, this is a case of differentiating a scalar ($L$) with respect to a matrix ($\boldsymbol{P}$). I think it may involve something called tensors, but to be honest I have little to zero experience with this, and even less once you throw in Lagrange multipliers.
I did some calculations, and it would appear the differential is given by
$$\tfrac{\partial{}L}{\partial{}\boldsymbol{P}} = 2\mathrm{\boldsymbol{D}}(\boldsymbol{P}) - 2\lambda_1\boldsymbol{\pi}\boldsymbol{\pi}^\mathsf{T}(\boldsymbol{I} - \boldsymbol{P}) - 2\lambda_2 \boldsymbol{e} \boldsymbol{e}^\mathsf{T} (\boldsymbol{I} - \boldsymbol{P}^\mathsf{T}),$$
which at some point involved an "outer product" or "Kronecker product", but could be simplified to that. The $D$ function outputs a diagonal matrix having same diagonal as its argument. In turn, the Hessian matrix (matrix of second order derivatives) would be given by
$$\tfrac{\partial{}^2L}{\partial{}\boldsymbol{P}\partial{}\boldsymbol{P}^\mathsf{T}} = 2\boldsymbol{I} + 2\lambda_1\boldsymbol{\pi}\boldsymbol{\pi}^\mathsf{T} + 2\lambda_2 \boldsymbol{e} \boldsymbol{e}^\mathsf{T}.$$
I tried inputting these in a "Newton's method-like" program, but all it outputted was gibberish.
All of this is a bit out of my league, but I really tried to make it work by myself before running here. I would be so grateful if someone could help me out. I know a solution exists, because Excel's solver is able to find solutions (don't ask why I use Excel, in this case I don't have a choice).
Thanks,
RSMax
P.S. Just in case there would be multiple definitions around, by "stochastic matrix" I mean a square matrix whose elements are probabilities, and whose rows all sum to 1.
P.P.S. By stationary distribution, I am referring to "long terms odds", as given by:
$$\boldsymbol{\pi} = {(\boldsymbol{I} + \boldsymbol{E} - \boldsymbol{P}^\mathsf{T})}^{-1} \boldsymbol{e},$$
where $\boldsymbol{E}$ is a square matrix filled with ones (same dimensions as $\boldsymbol{P}$).
EDIT No1: Fixed some typos and added some clarifications regarding what is an input.
EDIT No2: Substituting the sum of the squares of the diagonal elements for the trace indeed made this a linear problem which I was then able to solve using the simplex's "Big M" method. Works like a charm, even on Excel! My VBA code:
Public Const MAXVALUE As Double = 1.79769313486231E+308 'Arbitrary large value
Public Const EPSILON As Double = 0.0001 'Tolerance parameter for the Simplex method
Public Const BIGM As Double = 100# 'Big M constant for the Simplex method

Public Function Simplex(odds As Range) As Variant
'///////////////////////////////////////////////////////////////////////
'/// :function:    Simplex
'/// :scope:       Public
'/// :description: For odds.Cells.Count > 10, there can be instability issues.
'/// :return:      Wrapper (data validation) for the Simplex_ function.
'/// :odds:        An array of long-term odds (Range).
'///////////////////////////////////////////////////////////////////////
   Dim n As Long
   n = odds.Cells.Count

   With WorksheetFunction
      If .Count(odds) <> n Then
         Simplex = CVErr(xlErrNum)
      ElseIf .CountIf(odds, ">1") > 0 Then
         Simplex = CVErr(xlErrValue)
      ElseIf .CountIf(odds, "<0") > 0 Then
         Simplex = CVErr(xlErrValue)
      ElseIf Abs(.Sum(odds) - 1) > EPSILON Then
         Simplex = CVErr(xlErrValue)
      Else
         Simplex = Simplex_(odds)
      End If
   End With
End Function

Private Function Simplex_(pi As Range) As Double()
'///////////////////////////////////////////////////////////////////////
'/// :function:    Simplex_
'/// :scope:       Public
'/// :description: Implements the "Big M" variant of the Simplex method.
'/// :return:      The lowest trace probability matrix having stationary distribution Odds.
'/// :pi:          An array of long-term odds.
'///////////////////////////////////////////////////////////////////////
   Dim StopFlag As Boolean
   Dim output() As Double
   Dim MinRatio As Double
   Dim MaxCost As Double
   Dim factor As Double
   Dim Ratio As Double
   Dim Pivot As Double
   Dim x() As Variant
   Dim Row As Long
   Dim Col As Long
   Dim n As Long
   Dim i As Long
   Dim j As Long
   Dim k As Long

   n = pi.Cells.Count
   'As we're looking for a matrix, the number of unknowns is n^2 + others for the constraints
   ReDim x(0 To 2 * n + 1, 0 To n * n + 2 * n + 2) As Variant
   ReDim output(1 To n, 1 To n) As Double
   x(0, 0) = "BASIS"
   x(0, 1) = "Z"

   For i = 1 To n * n
      Row = 1 + (i - 1) \ n
      Col = 1 + (i - 1) Mod n
      x(0, i + 1) = "p" & Row & Col
   Next

   For i = 1 To n
      Col = 1 + (i - 1) Mod n
      x(0, i + n * n + 1) = "c.r" & Col
      x(0, i + n * n + n + 1) = "c.pi" & Col
      x(i, 0) = "c.r" & Col
      x(i + n, 0) = "c.pi" & Col
   Next

   x(0, n * n + 2 * n + 2) = "RHS" 'Right-hand side
   x(2 * n + 1, 0) = "COST"

   For i = 1 To n
      For j = 1 To n * n
         Row = 1 + (j - 1) \ n
         x(i, j + 1) = IIf(Row = i, 1, 0)
      Next

      x(i, n * n + 2 * n + 2) = 1

      For j = 1 To n * n
         Row = 1 + (j - 1) \ n
         Col = 1 + (j - 1) Mod n
         x(i + n, j + 1) = IIf(Col = i, pi(Row).Value, 0)
      Next

      x(i + n, n * n + 2 * n + 2) = pi(i).Value
   Next

   For i = 1 To n * n
      Row = 1 + (i - 1) \ n
      Col = 1 + (i - 1) Mod n
      x(2 * n + 1, i + 1) = IIf(Row = Col, -1, 0)
   Next

   For i = 1 To 2 * n
      For j = i + 1 To 2 * n
         x(i, n * n + 1 + j) = 0
         x(j, n * n + 1 + i) = 0
      Next

      x(i, 1) = 0
      x(i, n * n + 1 + i) = 1
      x(2 * n + 1, n * n + 1 + i) = -BIGM
   Next

   x(2 * n + 1, 1) = 1
   x(2 * n + 1, n * n + 2 * n + 2) = 0

   For k = 1 To 2 * n
      Col = n * n + 1 + k
      MinRatio = MAXVALUE

      For i = 1 To 2 * n
         If x(i, Col) > 0 Then
            Ratio = x(i, n * n + 2 * n + 2) / x(i, Col)

            If Ratio < MinRatio Then
               MinRatio = Ratio
               Row = i
            End If
         End If
      Next

      Pivot = x(Row, Col)

      For i = 1 To 2 * n + 1
         If i <> Row Then
            factor = -x(i, Col) / Pivot

            For j = 1 To n * n + 2 * n + 2
               x(i, j) = x(i, j) + factor * x(Row, j)
            Next
         End If
      Next

      For j = 1 To n * n + 2 * n + 2
         x(Row, j) = x(Row, j) / Pivot
      Next
   Next

   Do
      MaxCost = -MAXVALUE

      For i = 1 To n * n
         If x(2 * n + 1, i + 1) > MaxCost Then
            MaxCost = x(2 * n + 1, i + 1)
            Col = i + 1
         End If
      Next

      If MaxCost <= 0 Then
         Exit Do
      Else
         MinRatio = MAXVALUE

         For i = 1 To 2 * n
            If x(i, Col) > 0 Then
               Ratio = x(i, n * n + 2 * n + 2) / x(i, Col)

               If Ratio < MinRatio Then
                  MinRatio = Ratio
                  Row = i
               End If
            End If
         Next

         Pivot = x(Row, Col)

         For i = 1 To 2 * n + 1
            If i <> Row Then
               factor = -x(i, Col) / Pivot

               For j = 1 To n * n + 2 * n + 2
                  x(i, j) = x(i, j) + factor * x(Row, j)
               Next
            End If
         Next

         For j = 1 To n * n + 2 * n + 2
            x(Row, j) = x(Row, j) / Pivot
         Next

         x(Row, 0) = x(0, Col)
      End If
   Loop

   For i = 1 To n * n
      Row = 1 + (i - 1) \ n
      Col = 1 + (i - 1) Mod n

      For j = 1 To 2 * n
         If x(j, 0) = "p" & Row & Col Then
            output(Row, Col) = x(j, n * n + 2 * n + 2)
            Exit For
         End If
      Next
   Next

   Simplex_ = output
End Function

A: If you make the objective to minimize the sum of the diagonal entries (i.e. the trace), your problem becomes a linear programming problem, solvable with readily available software (I think even Excel).  In many cases the optimal solution will have all diagonal entries $0$.
EDIT: It may help to think of the problem this way.  There are $n$ people, numbered from $1$ to $n$.  Each person $i$ has a nonnegative  amount $\pi_i$ of money, and we want to move all the money around so that everyone ends up with the same amount they started with.   $P_{ij}$ is the fraction of person $i$'s money that goes to person $j$.  Of course this will not be possible if one person has more than half the total amount of money.  Otherwise it will be possible, by the following algorithm.  We arrange the people in order clockwise from richest to poorest around a circular table, and everyone puts their money on the table in front of them (let's say in coins of a given denomination).  The richest persion (#1) takes the amount $\pi_1$ off the table, starting with #2's coins, which come after his own coins.  Each person then continues, taking the correct number of coins starting where the previous one left off.  By induction, for $k$ from $2$ to $n$, when #k's turn comes, all his coins have already been taken.
EDIT: Here is a more explicit version of the algorithm I alluded to above.
We may assume that $\pi_1 \ge \pi_2 \ge \ldots \pi_n > 0$.  If necessary, we reorder the rows and columns to make them decrease.  If some $\pi_i$ are $0$, we make the corresponding columns all $0$ and put a $1$ arbitrarily (off the diagonal) in each of the corresponding rows, and follow the following algorithm for the rows and columns where $\pi > 0$.
If $\pi_1 > 1/2$, we let  $P_{11} = 2 - 1/\pi_1$, $P_{i1}=1$ and $P_{1i} = \pi_i/\pi_1$ for $ i > 1$, and all other $P_{ij} = 0$.  It is easy to check that this works, and no solution can have $P_{11} < 2 - 1/\pi_1$.
Now suppose $\pi_1 \le 1/2$.  Let $S_k = \sum_{i=1}^k \pi_i$ be the partial [[sums of $\pi$, so $S_0 = 0$ and $S_n = 1$.  Let $r_{ij}$ be the length of the intersection of the intervals $[S_{i-1}, S_i]$ and $[S_{j-1}+\pi_1, S_j + \pi_1] \mod 1$.  Then $P_{ij} = r_{ij}/\pi_i$.
For example, suppose $\pi = [0.3, 0.24, 0.24, 0.16, 0.06]$.  The partial sums are $[0, 0.3, 0.54, 0.78, 0.94, 1]$.  The shifted partial sums $S_i + \pi_1$ are $[.3, .0.6, 0.84, 1.08, 1.24, 1.30]$.  Then, for example, the intersection of $[S_{2} + \pi_1, S_3 + \pi_1] \mod 1 = [.84, 1] \cup [0, .08]$ and $[S_0, S_1]=[0,0.3]$ has length $0.08$, so $P_{13} = 0.08/0.3 = 4/15$, while the intersection of $[S_2+\pi_1, S_3 + \pi_1] \mod 1$ with $[S_3, S_4] =[.78, .94]$ has length $.1$ so $P_{43} = .1/.16 = 5/8$ and
the intersection of $[S_2+\pi_1, S_3 + \pi_1] \mod 1$ with $[S_4, S_5] = [.94, 1]$ has length $.06$ so $P_{53} = .06/.06 = 1$.  The resulting matrix is
$$ \pmatrix{ 0 & 0 & 4/15 & 8/15 & 1/5\cr 1 & 0 & 0 & 0 & 0\cr
1/4 & 3/4 & 0 & 0 & 0\cr 0 & 3/8 & 5/8 & 0 & 0\cr 0 & 0 & 1 & 0 & 0\cr} $$

A: The following is too large for a comment and definitely not an answer.
Fix $n \in \mathbb{N}$ and let $\cal{P}$ be the set of stochastic $n \times n$-matrices with $\text{diag}(P) = 0$. Let further
$$\mathcal{E} := \left\{\pi \in \mathbb{R}^n \colon \pi_i \geq 0, \sum \pi_i = 1, \exists P \in \mathcal{P} \text{ with } \pi \cdot P = \pi\right\},$$
each $\pi$ being a row vector. Then both $\mathcal{P}$ and $\mathcal{E}$ are compact convex subsets of $\mathbb{R}^{n \times n}$ resp. $\mathbb{R}^n$ and not empty if $n \geq 2$ and for $n = 2$ we have $\mathcal{E} = \{(0.5,0.5\}$. The problem is that $(1,0,\ldots,0), \ldots, (0,0,\ldots,1) \not\in \mathcal{E}$.
But for large $n$ it seems (I have no proof) it seems that almost any random stochastic $\pi$ is in $\mathcal{E}$. For this case your original problem is equivalent to "Find a $P \in \mathcal{P}$ with $\pi \cdot P = \pi$". Here the explicit construction of a homogeneous Markov chain with transition probability matrix $P$ (appropriately chosen) may be helpful to get a "feeling" for the solution. Of course this is impossible to formalize.
It seems to me that for $n$ large using numerical methods may be too heavy for this sort of problem. Edit (I've just seen the answer of Robert Israel) A reformulation as a linear programm with criterion
$$\sum P_{ii} = \min!$$
and variables $P_{ij}$ is possible.


text:
Q: Stratified random sample when setting training and testing dataset I am trying to divide my dataset into a training dataset  to fit a linear model and a testing dataset to carry out prediction using the model. Proportion or 80%-20%.
My issue is that my original dataset has a variable with a 90%-10% split between its two possible factors.
I am trying to keep that proportion constant across both the training and testing dataset so the model created and the prediction are carried out on datasets similar to the original dataset as the 80%-20% split risks the posibility of having too much or too little of one factor in the testing dataset.
I am not giving too much detail as this is part of my dissertation project.
I simply want to get an idea on how to keep the proportion working.
Thank you.


text:
Q: Base64 encoding for SAS.Planet SAS.Planet is a Russian soft, written in Delphi, to download Satellite images from many servers (sasgis.org). It is great and I use it a lot, but it would be better if I could insert my own data to it. It stores data in a file named marks.sml, which is basically a xml file. An example of it goes:
<?xml version="1.0" standalone="yes"?>
<DATAPACKET Version="2.0"><METADATA><FIELDS>
<FIELD attrname="id" fieldtype="i4" readonly="true" SUBTYPE="Autoinc"/>
<FIELD attrname="name" fieldtype="string" WIDTH="255"/>
<FIELD attrname="descr" fieldtype="bin.hex" SUBTYPE="Text"/>
<FIELD attrname="scale1" fieldtype="i4"/><FIELD attrname="scale2" fieldtype="i4"/>
<FIELD attrname="lonlatarr" fieldtype="bin.hex" SUBTYPE="Binary"/>
<FIELD attrname="lonL" fieldtype="r8"/>
<FIELD attrname="latT" fieldtype="r8"/>
<FIELD attrname="LonR" fieldtype="r8"/>
<FIELD attrname="LatB" fieldtype="r8"/>
<FIELD attrname="color1" fieldtype="i4"/>
<FIELD attrname="color2" fieldtype="i4"/>
<FIELD attrname="visible" fieldtype="boolean"/>
<FIELD attrname="picname" fieldtype="string" WIDTH="255"/>
<FIELD attrname="categoryid" fieldtype="i4"/></FIELDS>
<PARAMS AUTOINCVALUE="3"/></METADATA><ROWDATA>
<ROW id="1" name="Prueba1" descr="06/04/2015 9:48:56" scale1="2" scale2="0" lonlatarr="ANBXOtFZZY8FwABITxpq702zBMAgSCcJANBXOlGCU48FwABA1S48rk+zBMAgSCcJANBXOlEvPY8FwACo0VkXqlWzBMAgSCcJANBXOtGRPI8FwADYDRHFYGKzBMAgSCcJ" lonL="-71.69795087659068" latT="-44.826108606201" LonR="-71.61829999768443" LatB="-44.84607227245893" color1="-1493237760" color2="0" visible="TRUE" picname="" categoryid="1"/>
<ROW id="2" name="Prueba Polygon" descr="06/04/2015 10:16:25" scale1="2" scale2="0" lonlatarr="ANBXOtEeN48FwABAFiGe6lSzBMD89hIAANBXOlGPN48FwAAoQlXdQGKzBMD89hIAANBXOtELLI8FwACAC5X1IGKzBMD89hIAANBXOlEUK48FwACA1erKqlSzBMD89hIAANBXOtEeN48FwABAFiGe6lSzBMD89hIAANBXOtEeN48FwABAFiGe6lSzBMD89hIA" lonL="-71.6085152991981" latT="-44.83268277223885" LonR="-71.58413938367076" LatB="-44.84595056374432" color1="-1509949440" color2="872415231" visible="TRUE" picname="" categoryid="1"/>
</ROWDATA></DATAPACKET>

As you can see there is a tag named "ROW" in which are the "shapes". I tried to rewrite it for my own data, but the actual array of points is codified. Searching in the web I found that it is a Base64 encoding (Delphi). And I don't have a clue about it. I read a little about it, but is quit complex. My specific questions are:
- Could I make the Base64 encoding in any language? or have to use Delphi only?
- If so, does anyone have the code in python?
Thank you!

A: Decoding base64 data is quite simple.
In [1]: import base64

In [2]: lonlatarr = base64.b64decode("ANBXOtFZZY8FwABITxpq702zBMAgSCcJANBXOlGCU48FwABA1S48rk+zBMAgSCcJANBXOlEvPY8FwACo0VkXqlWzBMAgSCcJANBXOtGRPI8FwADYDRHFYGKzBMAgSCcJ")

In [3]: len(lonlatarr)
Out[3]: 96

In [4]: lonlatarr[0:9]
Out[4]: b'\x00\xd0W:\xd1Ye\x8f\x05'

Interpreting what is means is more difficult.
Notice the regularity in the data:
In [18]: lonlatarr[0:4], lonlatarr[24:28], lonlatarr[48:52]
Out[18]: (b'\x00\xd0W:', b'\x00\xd0W:', b'\x00\xd0W:')

In [19]: len(lonlatarr)
Out[19]: 96

In [20]: lonlatarr[41:48], lonlatarr[89:96]
Out[20]: (b"\xb3\x04\xc0 H'\t", b"\xb3\x04\xc0 H'\t")

In [21]: lonlatarr[17:24], lonlatarr[41:48], lonlatarr[89:96]
Out[21]: (b"\xb3\x04\xc0 H'\t", b"\xb3\x04\xc0 H'\t", b"\xb3\x04\xc0 H'\t")

A sequence begins with b'\x00\xd0W:' and ends with b"\xb3\x04\xc0 H'\t".
The data inbetween varies.
It could be that these mark the beginning and end of a longitude or latitude.
Or it could be that the beginning and end of the numbers are always the same because of their range and encoding.
Fortunately, the code for this program seems to be available.
Your file might have something to do with the MarksDB? It's hard to tell.
It might be a good idea to contact the developers.


text:
Q: how to make disabled select box to clickable (in webkit browsers) i need to set my disabled input select box to clickable in webkit browsers (under IE is working, under chrome,opera,safari not).
My page structure is the next:
<select id="...">(its disabled by jquery)</select>(its a custom jquery select box)

my page do the next steps:
/1. add new href to

/2. set new color for custom jquery select box then set is to disabled
In IE i can click to disabled select box but in webkit browsers
(chrome,safari) and in firefox i cant :(
I try to add pointer-events:none to my disabled select box (all way: by jquery, by css) but the custom jquery select box (span) is inherit the pointer-evenets:none setting too. Its working only when i manualy disable (in chrome developer tools) the second pointer-events setting (from span).
Please help :{


text:
Q: In Python what could cause a for loop to randomly go backwards in value? What can cause an iterator to go forwards in a loop, and then backwards?
This is the code I'm using to loop through the table's primary key field. The primary key is being used to populate initial values in a separate table.
For loop:
for row in sampleDB.select_fromTable():
    print row[0]
    sampleDB.insert_toTable(row[0], 2.0)

sqllite insert statement:
def insert_toTable(self, primaryKey, initial):
    c = self.conn.cursor()
    c.execute('insert into insert_toTable VALUES(?, ?)', (primaryKey, initial))
    if c.rowcount == 1:
        print "Updated row.\n"
    else:
        print "Row does not exist.\n"

    self.conn.commit()
    c.close()

The select statement that creates the tuple to loop through:
def select_fromTable(self):
    c = self.conn.cursor()
    c.execute('select * from sampleTable')

    c.close

    return c

Here is an example table:
Primary Key     Text
0               John
1               Sue
2               Bill
3               Tyler

Running the loop without the insert statement prints each unique key once, but if I add the call to the insert function (insert_toTable) I get this phenomenon:
0
Updated row.

1
Updated row.

0
Traceback (most recent call last):
sqlite3.IntegrityError: column urlid is not unique

The next iteration of the loop should be to the unique value "2" not back to "0"....
I can provide more sections of code if needed.

A: I suspect the results of this code may change depending on exactly which versions of sqlite and python are used.
Notice that your call to c.close in the select_fromTable method should be c.close(). This is a fortunate error, since you cannot iterate over the results of the query after the cursor is closed. However, the result is that you have two open cursors in the loop.
Try changing your select_fromTable method to:
def select_fromTable(self):
    c = self.conn.cursor()
    c.execute('select * from sampleTable')
    results = c.fetchall()
    c.close()
    return results

and see what happens. I believe it will fix your problem.


text:
Q: get cod 500 internal server error when try to display in ReportViewer I'm trying to generate server report as pdf from web api. I used Microsoft ReportViewer 11.0. And I get errors below. The report page show blank and nothing error show in VS. But In Fiddler, Its respond internal server(500 code).
it completely write to local pdf file
I get error like this when try to display report. Plz help me guys
and here is my code
re.ServerReport.ReportServerUrl = new System.Uri(pReportURL);
        re.ServerReport.ReportPath = ReportPath;

        re.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
        IReportServerCredentials irc = new ReportServerCredentials(pReportUserName, ReportPAssword, pReportURL);
        re.ServerReport.ReportServerCredentials = irc;
        Int32 i = 0;
        ReportParameter[] rptParm = new ReportParameter[hdParam.Count];
        if (rptParm != null)
        {
            foreach (DictionaryEntry index in hdParam)
            {
                if (i <= hdParam.Count)
                {
                    rptParm[i] = new ReportParameter(index.Key.ToString(), index.Value.ToString());
                    i = i + 1;
                }

            }
            re.ServerReport.SetParameters(rptParm);
        }
        Warning[] warnings;
        string[] streamids;
        string mimeType;
        string encoding;
        string extension;
        re.ServerReport.DisplayName = ReportPath;
        byte[] data = re.ServerReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);
        System.Web.HttpContext.Current.Response.Clear();
        System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
        System.Web.HttpContext.Current.Response.Write(data);
        System.Web.HttpContext.Current.Response.Flush();
        System.Web.HttpContext.Current.Response.End();
        Stream ms = new MemoryStream(data);
        System.Web.HttpContext.Current.Response.Buffer = true;
        //ms.WriteTo(System.Web.HttpContext.Current.Response.OutputStream);

        File.WriteAllBytes(@"C:\testpdf.pdf", data);
        var result = Request.CreateResponse(HttpStatusCode.OK);
        result.Content = new StreamContent(ms);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("PrintOut_Finance_Inv/pdf");
        return result;