text:
Q: Project 3D point to 2D screen coordinate I'm trying to project a few 3d points to screen coordinates to determine whether a touch occurs in roughly the same area. It should be noted that I'm doing this in Kivy, which is Python and OpenGL. I've seen questions like this, but I still don't have a solution. I've tried the following, but the numbers are not close to screen co-ordinates.
def to2D(self, pos, width, height, modelview, projection):
    p = modelview*[pos[0], pos[1], pos[2], 0])
    p = projection*p
    a = p[0]
    b = p[1]
    c = p[2]
    a /= c
    b /= c
    a = (a+1)*width/2.
    b = (b+1)*height/2.
    return (a, b)

To illustrate that this doesn't produce good results, take the following parameters
modelview = [[-0.831470, 0.553001, 0.053372, 0.000000],
             [0.000000, 0.096068, -0.995375, 0.000000],
             [-0.555570, -0.827624, -0.079878, 0.000000],
             [-0.000000, -0.772988, -2.898705, 1.000000]]
projection = [[ 15.763722, 0.000000, 0.000000, 0.000000],
              [ 0.000000, 15.257052, 0.000000, 0.000000],
              [ 0.000000, 0.000000, -1.002002, -2.002002],
              [ 0.000000, 0.000000, -1.000000, 0.000000]]
pos = [0.523355213060808, -0.528964010275341, -0.668054187020413] #I'm working on a unit sphere, so these are more meaningful in spherical coordinates
width = 800
height = 600

With these parameters, to2D gives screen coordinates of (1383, -274)
I don't think the problem is related to OpenGL and python, rather to the operations involved in getting from 3d to screen coordinates.
What I'm trying to do: When a touch occurs, project a 3d point to 2d screen coordinates.
My idea:
Take the camera's modelview and projection matrices, a point that I'm interested in, and the touch position, and then make a method to get from the point to the touch position. Get the method, by converting this source code for gluProject into Python
How I've done it:

*

*Take all of the mathematical objects into Sage for computational simplicity.

*My touch position is (150, 114.1)

*modelview = matrix([[ -0.862734, 0.503319, 0.048577, 0.000000 ],
                    [ 0.000000, 0.096068, -0.995375, 0.000000 ],
                    [ -0.505657, -0.858744, -0.082881, 0.000000 ],
                    [ 0.000000, -0.772988, -2.898705, 1.000000 ]])

*projection = matrix([[ 15.763722, 0.000000, 0.000000, 0.000000 ],
                     [ 0.000000, 15.257052, 0.000000, 0.000000 ],
                     [ 0.000000, 0.000000, -1.002002, -2.002002 ],
                     [ 0.000000, 0.000000, -1.000000, 0.000000 ]])

*width = 800.

*height = 600.

*v4 = vector(QQ, [0.52324, -0.65021, -0.55086, 1.])

*p = modelview*v4

*p = projection*p

*x = p[0]
 y = p[1]
 z = p[2]
 w = p[3]

*x /= w
 y /= w
 z /= w

*x = x*0.5 + 0.5
 y = y*0.5 + 0.5
 z = z*0.5 + 0.5

*x = x*width
 y = y*height  #There's no term added because the widget is located at (0, 0)
The result:
x = 15362.18
y = -6251.43
z = 10.14

The revision: Since this is not even close, I went back to steps 8 and 9 and switched the order of multiplication to see what would happen. So now 8. is p = v4*modelview, and 9. is p = p*projection. In this case, the vectors are row vectors. Another way of looking at this would be p = modelviewTranspose*v4 and p = projectionTranspose*p, where the vectors are column vectors.
The result Part 2:
x = 150.29
y = 196.15
z = 0.6357

Recall that the goal is (150, 114.1). The x coordinate is very good, but the y coordinate is not. So I looked at y*z, which is 124.69. I could live with this answer, although I'm not sure if looking at y*z is what I should actually be doing

A: The first problem is here:
p = modelview*[pos[0], pos[1], pos[2], 0])

When you multiple vector with matrix as 4component vector, Last component (w) must be 1.0
Another one is here:
c = p[2]
a /= c
b /= c

Instead of dividing x and y by z you should divide x, y AND z by w. w is p[4].
In addition to that:
When in doubt, find source code of gluProject and gluUnproject, tear it apart and convert to python.
As far as I know, when projecting vector manually to screen, you're supposed to do following:

*

*Convert "position" to 4 component vector, with .w component set to one.
v4.x = v3.x
v4.y = v3.y
v4.z = v3.z
v4.w = 1.0

*Multiply 4component by matrices.

*Then divide all components by w.
v4.x /= v4.w
v4.y /= v4.w
v4.z /= v4.w

THEN you'll get screen coordinates within +-1.0 range for x and y. (z will be either within 0.0..1.0 or 0.0..-1.0, I forgot which in case of OpenGL).
The reason why w comes to play is because you can't divide via matrix multiplication, so when you need to divide x/y/z by something, you put it into w component, and division is performed after all the matrix multiplications. w also makes translation matrices possible. Any vector with w == 0 cannot be translated using translation matrices, only rotated around origin and deformed with affine transforms ("origin" means point zero of coordinate space - (0.0, 0.0, 0.0) point)
P.S. Also, I don't know how python handles integer to float conversions, but I'd replace  a = (a+1)*width/2 with a = (a+1.0)*width/2.0 to explicitly specify you're using floating point numbers here.

A: If you have access to it, pyopengl's gluProject(x, y, z) returns screenspace x, y, z coordinates for the current context. (Other implementations might need more arguments and set pointers instead of returning!)


text:
Q: A call for MATLAB link maintenance I recently noticed that the documentation pages for MATLAB on the MathWorks site have been updated to a new format. Unfortunately, this also involves a new format for many of the page URLs, breaking a substantial number of links within MATLAB posts. For example, here's one of my posts that recently needed some TLC. Specifically, one of the old links to documentation on subfunctions:
http://www.mathworks.com/help/matlab/matlab_prog/f4-70666.html
no longer works (it just defaults to the documentation intro page). I had to link here instead:
http://www.mathworks.com/help/matlab/matlab_prog/local-functions.html
This repair was also complicated by a slight change in terminology ("subfunctions" are now called "local functions"). You can see that the jumble of letters and numbers on the end of the old link have been replaced with something that is actually descriptive of the content now.
Fixing the problem...
In general, these fixes may not be easy for potential editors. It may require that they be knowledgeable of MATLAB so that they can deduce what the desired target link is, and even then it may not be clear from the context of the post what the link was supposed to be. The best solution may be to just find posts with these bad links and leave a comment for the owner so that they can fix it themselves.
For anyone interested in helping, here are a few search queries to help find posts that may need attention. The offending URLs contain terms of the form "matlab_prog" and "matlab_oop", among some others. These queries will find these:

*

*url:"*matlab_*"

*url:"*matlab_prog*"  (just the "prog" ones)

*url:"*matlab_oop*" (just the "oop" ones)

However, these queries can also give many false positives since they will match the newer corrected links as well. These sorts of queries may be more specific to the older dead-end links:

*

*url:"*matlab_prog/b*"

*url:"*matlab_prog/f*"

*url:"*matlab_oop/b*"

*url:"*matlab_oop/f*"

*url:"*matlab_oop/u*"
Some easier edits...
Additionally, I had previously been fixing some even older link formats that, while they usually redirected correctly, would occasionally fail or add garbage to the link URL. For example, an old link to the function FLIPDIM might look like this:
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/flipdim.html
when it should be this now (what it should redirect to):
http://www.mathworks.com/help/techdoc/ref/flipdim.html
In other words, just remove the "access/helpdesk/" part. It's often a trivial edit, so I usually did it for posts I was already editing for other reasons anyway. If you want to find these to fix them, here's the search query I used.

redpajama_set_name: RedPajamaStackExchange


text:
Q: A quick question on general mathematics I have the following question that I am currently unable to satisfactorily answer myself.
My question is:
Does the inequality
$$\frac{a}{b} + \frac{b}{a} < \frac{f(a)}{f(b)} + \frac{f(b)}{f(a)}\tag{*}$$
imply that $a < b$, in general (i.e., for ALL functions $f$)?
If the answer to my question is NO, under what conditions on the function $f$ is it true that inequality (*) implies $b < a$?

A: The given inequality is symmetric in $a$ and $b$. So if it holds for some pair $(a,b)$, it also holds for the pair $(b,a)$. Thus it cannot force $a\lt b$.


text:
Q: NoClassDefFoundError for tomcat 8.0.15/jasper/tiles 3.0.5 I'm getting the following exception and not sure if the problem is in tomcat 8.0.15 or if there is some incompatibility of other libraries:
Caused by: java.io.IOException: ServletException including path '/WEB-INF/views/layout/baseLayout.jsp'.
    at org.apache.tiles.request.servlet.ServletUtil.wrapServletException(ServletUtil.java:61) ~[tiles-request-servlet-1.0.6.jar:1.0.6]
    at org.apache.tiles.request.servlet.ServletRequest.doInclude(ServletRequest.java:245) ~[tiles-request-servlet-1.0.6.jar:1.0.6]
    at org.apache.tiles.request.AbstractClientRequest.dispatch(AbstractClientRequest.java:54) ~[tiles-request-api-1.0.6.jar:1.0.6]
    at org.apache.tiles.request.render.DispatchRenderer.render(DispatchRenderer.java:47) ~[tiles-request-api-1.0.6.jar:1.0.6]
    at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:259) ~[tiles-core-3.0.5.jar:3.0.5]
    at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:397) ~[tiles-core-3.0.5.jar:3.0.5]
    ... 37 common frames omitted
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.apache.jasper.el.ELContextImpl
    at org.apache.jasper.compiler.Validator$ValidateVisitor.getJspAttribute(Validator.java:1414) ~[jasper.jar:8.0.15]
    at org.apache.jasper.compiler.Validator$ValidateVisitor.checkXmlAttributes(Validator.java:1231) ~[jasper.jar:8.0.15]
    at org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:879) ~[jasper.jar:8.0.15]
    at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1536) ~[jasper.jar:8.0.15]
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2376) ~[jasper.jar:8.0.15]
    at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2428) ~[jasper.jar:8.0.15]
    at org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2434) ~[jasper.jar:8.0.15]
    at org.apache.jasper.compiler.Node$Root.accept(Node.java:464) ~[jasper.jar:8.0.15]
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2376) ~[jasper.jar:8.0.15]
    at org.apache.jasper.compiler.Validator.validateExDirectives(Validator.java:1846) ~[jasper.jar:8.0.15]
    at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:217) ~[jasper.jar:8.0.15]
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:356) ~[jasper.jar:8.0.15]
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:336) ~[jasper.jar:8.0.15]
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:323) ~[jasper.jar:8.0.15]
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:564) ~[jasper.jar:8.0.15]
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357) ~[jasper.jar:8.0.15]
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396) ~[jasper.jar:8.0.15]
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340) ~[jasper.jar:8.0.15]

Any ideas?

*

*JDK 8u25

*Tomcat 8.0.15

*Spring 4.1.2

*Tiles 3.0.5

A: Problem solved. Another component was including spring boot jar which was as a dependency including tomcat 7.0.54 libraries.

A: Make sure jasper.jar is present in tomcat/lib.
If missing, add it, if not, try Tomcat>Clean... from Eclipse

A: Maybe you are missing el-api.jar as mentioned in HTTP Status 500 - java.lang.NoClassDefFoundError: Could not initialize class org.apache.jasper.el.ELContextImpl
kind regards,
soilworker

A: Add servlet-api.jar, jsp-api.jar,el-api.jar to the JRE system libraries in eclipse
Windows - Preferences - Installed JREs -
select the existing jre and cleck edit to add the jars.


text:
Q: Flutter - ImagePicker does not display the image selected I am trying to use ImagePicker. When an image is selected, it is not displayed on the screen. Value seems to be null. Below, you will find the full source code. I have done some research, but I have not find what mistake I am doing. If you could point me in the right direction, it would be great and appreciated. Many thanks.
class CaptureV2 extends StatefulWidget {
  CaptureV2({Key key}) : super(key: key);
  @override
  _CaptureV2State createState() => _CaptureV2State();
}

class _CaptureV2State extends State<CaptureV2> {
  GlobalKey<FormState> _captureFormKey = GlobalKey<FormState>();

  bool isOn = true;
  String _valueTaskNameChanged = '';
  String _valueTaskNameToValidate ='';
  String _valueTaskNameSaved='';

  File imageFile;
  _openGallery(BuildContext context) async{
    imageFile = await ImagePicker().getImage(source: ImageSource.gallery) as File;
    this.setState(() {
    });
  }
  _openCamera(BuildContext context) async {
    imageFile = await ImagePicker().getImage(source: ImageSource.camera) as File;
    this.setState(() {
    });
  }

  Widget _showImageView(context){ //Even when I am selecting an image I always get null
    if(imageFile ==null) {
      return Text('No attachment');
    }else{
      return Image.file(imageFile, width: 200, height: 200,);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child:   Scaffold(
        drawer: MyMenu(),
        appBar: AppBar(
          centerTitle: true,
          title: Text('CAPTURE'),
          actions: <Widget>[
            Padding(
              padding: const EdgeInsets.fromLTRB(0,22,0,0),
              child: Text("On/Off"),
            ),
            Switch(
              value: isOn,
              onChanged: (value) {
                setState(() {
                  isOn = value;
                });
              },
              activeTrackColor: Colors.green,
              activeColor: Colors.green,
            ),
          ],
        ),

//==================

        body: isOn?
        SingleChildScrollView(
          child: Column(
            // crossAxisAlignment: CrossAxisAlignment.end,
            // mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Form(
                key: _captureFormKey,
                child: Column(
                  // crossAxisAlignment: CrossAxisAlignment.end,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.fromLTRB(8.0, 0.0, 15.0, 1.0),
                        child: TextFormField(
                          decoration: InputDecoration(hintText: "Task Name"),
                          maxLength: 100,
                          maxLines: 3,
                          onChanged: (valProjectName) => setState(() => _valueTaskNameChanged = valProjectName),
                          validator: (valProjectName) {
                            setState(() => _valueTaskNameToValidate = valProjectName);
                            return valProjectName.isEmpty? "Task name cannot be empty" : null;
                          },
                          onSaved: (valProjectName) => setState(() => _valueTaskNameSaved = valProjectName),
                        ),
                      ),

                      SizedBox(
                        height: 50.0,
                      ),

 //########ATTACHEMENT & PHOTOS
                      Card(
                          child:
                          Container(
                            // color: Colors.red,
                            alignment: Alignment.center,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children:[
//Attachement
                                FlatButton(
                                  onPressed: () {
                                    },
                                  child:
                                  InkWell(
                                    child: Container(
                                      //  color: Colors.white,
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: [
                                            Icon(Icons.attach_file),
                                            Text('Attachement'),
                                          ],
                                        )
                                    ),
                                    onTap: () {
                                      _openGallery(context);

                                    },
                                  ),
                                ),

//Photo
                                FlatButton(
                                  onPressed: () {(); },
                                  child:
                                  InkWell(
                                    child: Container(
                                      //   color: Colors.white,
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: [
                                            Icon(Icons.add_a_photo_rounded),
                                            Text('Photo'),
                                          ],
                                        )
                                    ),
                                    onTap: () {

                                    },
                                  ),
                                ),

//Voice Recording
                                FlatButton(
                                  onPressed: () {  },
                                  child:
                                  InkWell(
                                    child: Container(
                                      //   color: Colors.white,
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: [
                                            ConstrainedBox(
                                              constraints: BoxConstraints(
                                                minWidth: iconSize,
                                                minHeight: iconSize,
                                                maxWidth: iconSize,
                                                maxHeight: iconSize,
                                              ),

                                              child: Image.asset('assets/icons/microphone.png', fit: BoxFit.cover),
                                            ),
                                            Text('Recording'),
                                          ],
                                        )
                                    ),
                                    onTap: () {
                                      MyApp_AZERTY();
                                    },
                                  ),
                                ),
                              ],
                            ),
                          )
                      ),
                    ]
                ),
              ),
            Container(
                child:
                 _showImageView(context)
            ),
              SizedBox(
                height: 150.0,
              ),

//CANCEL & SAVE
              Container(
                decoration: const BoxDecoration(
                  border: Border(
                    top: BorderSide(width: 1.0, color: Colors.grey),

                  ),
                ),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      Container(
                        child:

                        FlatButton(
                          child: Text("Cancel",style: TextStyle(
                              fontSize: 18.0,fontWeight: FontWeight.bold,color: Colors.grey
                          )
                          ),
                          onPressed: (){
                            final loForm = _captureFormKey.currentState;
                            loForm.reset();

                          },
                        ),
                      ),
                      Container(
                        child: FlatButton(
                          child: Text("Save",style: TextStyle(
                              fontSize: 18.0,fontWeight: FontWeight.bold,color: Colors.blue
                          )),
                          //   Border.all(width: 1.0, color: Colors.black),
                          onPressed: (){}

                              loForm.reset();
                              showSimpleFlushbar(context, 'Task Saved',_valueTaskNameSaved, Icons.mode_comment);
                            }
                            loForm.reset();
                          },
                        ),
                      ),
                    ]
                ),
              ),
            ],
          ),
        ) :

A: The problem is getImage does not return a type of file, but a type of
Future<PickedFile>

So you need to do the following.
final image =  await ImagePicker().getImage(source: ImageSource.gallery);
 this.setState(() {
imageFile = File(image.path);
    });


text:
Q: Fabric.io Beta Distribution via Gradle - Emails Sending Issue I need some assistance with regards to Beta distribution, and am at a loss for where to look or how to troubleshoot this.
I have already posted a question but I believe it to be in the wrong area, and perhaps posting here will have better results.
With that said here is the link regarding the question, relating to the title.
Fabric.io Beta Distribution via Gralde - Group Alias - Invitation Email
Thanks kindly


text:
Q: How to let ImageView dictate size of custom Drawable? Im working on a initials drawable, sort of like gmail has.
I want this drawable to scale automatically to image view size (which will be hardcoded in xml, but multiple variants), therefore I dont want the initials drawable to have hardcoded size as well, which is to me seems is what getIntrinsicWidth() does.
Is there a way to do this? Is there way then for drawable to get the image view size, to do its calculations for rendering?
Thanks

A: Vector drawables can scale automatically by default. Setting android:width="24dp" for example in your drawable xml doesn't force it to be this size, it's just a default value.
Set the ImageView to the size you want, and set your drawable as the image resource. It will fill the available space.
In layout xml:
<ImageView
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:src="@drawable/your_drawable"/>

Or in java:
ImageView iv = findViewById(R.id.your_image_view);
iv.setImageResource(R.drawable.your_drawable);

Mess with android:scaleType if you want different crop behavior.


text:
Q: Does a predefined abbreviation imply the meaning of another undefined (but fundamentally similar) abbreviation? I've defined abbreviation UDES representing untimed discrete-event systems. Now, I need to talk about the larger class of discrete-event systems, which includes the former one.
I'm wondering whether I can directly use DES abbreviation (because I've already defined UDES) or I have to first define DES as discrete-event systems then using its abbreviated form (because it's an independent concept whose abbreviation must be firstly defined).

A: As a reader, I'd personally find it confusing if DES were not defined in its own right, although I'll grant that this could depend on context. If readers are likely to already be familiar with DES as an acronym for discrete-event systems, then it might be appropriate to omit the definition where space is limited.
If DES is likely to be unfamiliar, one option is to only introduce the acronym DES for discrete-event systems, and to refer to untimed distrete-event systems as untimed DES. Another option is to first introduce discrete-event systems, and then to subsequently introduce the acronym UDES for untimed DES.


text:
Q: How to move to another page onclick and still maintain the principle of the SPA In the Angular Project, I defined the main component to display data about companies in the table.
Below the table a button when a button is clicked is moved to a page with inputs to add a new company.
After filling in the fields click Submit and the new company is added to the DB.
Problem: Stay on the same page and do not see if the new company has been added to the DB.
How to move the user back to the main componette while maintaining the SPA principle?
public addCompany(newCompanyName:String, newCompanyPassword:String, newCompanyEmail:String ){
    let newP:any ={
      "name": newCompanyName,
      "password": newCompanyPassword,
      "email": newCompanyEmail,
      "coupons": []
      }

     this.myHttpClient.post<any>("http://localhost:8080/CouponSystemJersey/couponsystem/admin/insertCompany", newP).subscribe(
       (res)=>{
         console.log("new company");
         // How to redirect to adminComponent ?
        },
       (err)=>{console.log(err)}
     );
  }

I use angular routes:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { AdminComponent } from './admin/admin.component';
import { AddCompanyComponent } from './add-company/add-company.component';

const routes: Routes = [
{path:"login", component:LoginComponent},
{path:"admin", component:AdminComponent},
{path:"addCompany", component:AddCompanyComponent}];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Want to switch from addCompany to Admin from addCompany.
The addCompany function is not activated as soon as the button is pressed, but another function is activated (found in the addCmpany's TS) and runs addCompany (after checking that the fields are not null)
the error message :
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/CouponSystemJersey/couponsystem/admin/insertCompany", ok: false, …}
error: {error: SyntaxError: Unexpected token A in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "A new customer was inserted"}
headers: HttpHeaders
lazyInit: ƒ ()
lazyUpdate: null
normalizedNames: Map(0) {}
__proto__: Object
message: "Http failure during parsing for http://localhost:8080/CouponSystemJersey/couponsystem/admin/insertCompany"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/CouponSystemJersey/couponsystem/admin/insertCompany"
__proto__: HttpResponseBase

A: You can use this approach this.router.navigate(["/anotherComponent"]).
import
import { Router } from "@angular/router";

then

constructor(private router: Router) {}

public addCompany(newCompanyName:String, newCompanyPassword:String, newCompanyEmail:String ){
    let newP:any ={
      "name": newCompanyName,
      "password": newCompanyPassword,
      "email": newCompanyEmail,
      "coupons": []
      }

     this.myHttpClient.post<any>("http://localhost:8080/CouponSystemJersey/couponsystem/admin/insertCompany", newP).subscribe(
       (res)=>{
         console.log("new company");
         this.router.navigate(["/admin"]);
        },
       (err)=>{console.log(err)}
     );
  }

A: You are getting the error because your request object doesn't fit with the expected of your DB, please try:
....
this.myHttpClient.post<any>("http://localhost:8080/CouponSystemJersey/couponsystem/admin/insertCompany", JSON.stringify(newP)).subscribe(
.....

Then when you get the correct response:
 (res)=>{
     console.log("new company");
     this.router.navigate(["/admin"]);
    }

I suggest you make an atomic test, try to navigate to other page without make the request.


text:
Q: How to import non-comma/tab separated ASCII numerical data and render into vector (in matlab) I want to import 100,000 digits of pi into matlab and manipulate it as a vector.  I've copied and pasted these digits from here and saved them in a text file.  I'm now having a lot of trouble importing these digits and rendering them as a vector.
I've found this function which calculates the digits within matlab.  However, even with this I'm having trouble turning the output into a vector which I could then, for example, plot.  (Plus it's rather slow for 100,000 digits, at least on my computer.)

A: Use textscan for that:
fid = fopen('100000.txt','r');
PiT = textscan(fid,'%c',Inf);
fclose(fid);

PiT is a cell array, so convert it to a vector of chars:
PiT = cell2mat(PiT(1));

Now, you want a vector of int, but you have to discard the decimal period to use the standard function:
Pi = cell2mat(textscan(PiT([1,3:end]),'%1d', Inf));

Note: if you delete (manually) the period, you can do that all in once:
fid = fopen('100000.txt','r');
Pi = cell2mat(textscan(fid,'%1d',Inf));
fclose(fid);

EDIT
Here is another solution, using fscanf, as textscan may not return a cell-type result.
Read the file with fscanf:
fid = fopen('100000.txt','r');
Pi = fscanf(fid,'%c');
fclose(fid);

Then take only the digits and convert the string as digits:
Pi = int32(Pi((Pi>='0')&(Pi<='9')))-int32('0');

Function int32 may be replaced by other conversion functions (e.g. double).

A: It can be done in one line.
When you modify your text file to just include the post-comma digits 14... you can use fscanf to get the vector you want.
pi = fscanf( fopen('pi.txt'), '%1d' );  fclose all

or without modifying the file:
pi = str2double( regexp( fscanf( fopen('pi.txt') ,'%1c'), '[0-9]', 'match'));


text:
Q: Decode an array of messages in protobuf.js In our node.js application we need to deserialize a Buffer which we know contains multiple objects. With protobuf-net this was done like so:
var stream = new MemoryStream(byteData);
List<Schema.Object> objects = ProtoBuf.Serializer.Deserialize<List<Schema.Object>>(stream);

I am now trying to do the same with protobuf.js. I haven't found an example where it creates an array of the model objects, only a single model object, like so:
const Object = root.lookupType('model.Object');
const message = Object.decode(byteData); //this creates one object but the buffer contains multiple objects

How do you create an array of objects, rather than a single object using protobuf.js?
Here's how the data is being serialized:
try
    {
        using (var stream = new MemoryStream())
        {
            ProtoBuf.Serializer.Serialize(stream, objects);
            Stream.Position = 0;

            // Return the serialized byte array.
            return stream.ToArray();
        }
    }
    finally {}
}

A: Found a solution. You can wrap the Object with another message containing a repeated entry. Then when it's decoded, it will be an array of Objects.
In the .proto file:
message ObjectCollection {
  repeated Object objects = 1;
}


text:
Q: How to log Application Errors when customErros is set to On? I have setup an MVC application to log errors with log4net. In my global.asax I catch Application errors using the Application_Error method (s_log is my logging manager which is a wrapper around Log4net).
protected void Application_Error(Object sender, EventArgs e)
{
    Exception ex = Server.GetLastError().GetBaseException();
    s_log.LogException(true, ex, "Application Error");
}

When customErrors is set to "Off" I get the yellow screen of death and can see the error in my log file. When customErrors is set to "On" I see my Error page (and the detailed error) but nothing is written in the log file (debugging doesn't hit the Application_Error).
Can someone enlighten me on why this happens?
Error.aspx

Sorry, an error occurred while processing your request.

Controller:  <%= Model.ControllerName %>

Action:  <%= Model.ActionName %>
<% if (Model.Exception != null) { %>

    Exception Details:

    <%= Model.Exception.ToString() %>

<% } %>

customErrors section in web.config
<customErrors mode="On" defaultRedirect="~/error">
    <error statusCode="403" redirect="~/error"/>
    <error statusCode="404" redirect="~/error"/>
</customErrors>

A: The customerrors function is just taking care of it before the Application_Error method can.  You should just keep customErrors off and use mvc's response redirect to send user's to the appropriate error page.
See ASP.NET MVC Custom Error Handling Application_Error Global.asax?


text:
Q: Getting total count of column values looking backwards in yearly/n intervals based on composite groupby operation I have a table where each user has an unique enrollment date as shown in the table below. The user also has a service date associated with each line which contains multiple diagnosis codes (including but not limited to a finite set of string values for example, dx_A, dx_B, dx_C,...dx_N; only dx_{A,B,C} shown here for clarity) in columns associated with each service date.

user_id
enroll_date
service_date
Code_1
Code_2
Code_3

A
2019-01-30
2018-06-15
dx_A
dx_B
dx_C

A
2019-01-30
2017-05-20
dx_B
dx_B
dx_A

A
2019-01-30
2017-01-15
dx_B
dx_B
dx_B

A
2019-01-30
2018-02-10
dx_A
dx_C
dx_A

A
2019-01-30
2017-12-14
dx_C
dx_B
dx_B

B
2018-03-07
2017-02-01
dx_A
dx_C
dx_B

B
2018-03-07
2016-10-25
dx_C
dx_A
dx_C

B
2018-03-07
2016-05-25
dx_B
dx_C
dx_A

B
2018-03-07
2018-01-30
dx_A
dx_A
dx_B

Now, using pandas, I want to find out total count of each code that occur for each user looking back at 1 year, 2 year and 3 year intervals from the enroll date so the resulting table looking something like the one given below.

user_id
dx_A_1_yr
dx_A_2_yr
dx_A_3_yr
dx_B_1yr
dx_B_2yr
dx_B_3yr
dx_C_1yr
dx_C_2yr
dx_C_3yr

A
3
1
0
1
4
3
2
1
0

B
2
3
0
1
2
0
0
4
0

In particular, I am having trouble fetching relevant rows which is based on service date for each each user, enroll_date combination for yearly intervals looking back in time.
Example from table above, for user A looking at interval for the first year between 2018-01-30 to 2019-01-30, the condition is satisfied by rows 1 and 4 and the count for codes is hence populated accordingly from these two rows for the first year for user A. For the same user, for the 2nd year interval 2018-01-30 to 2017-01-30 the condition is satisfied by rows 2 and 5 and so on for all the users.

A: Here is what I did :

*

*I create new columns 'dx_A', 'dx_B' and 'dx_C' with the number of times the code is present in each row.

*For each year, I use .loc to filter the service_dates where the delay is in the asked year.

*Then I use groupby to have one row of A and another of B

*I rename the columns with a suffix according to the year

*Finally, I concatenate all the yearly dataframes and write 0 value where there is none.
The table is named 'table'
for code in ['dx_A', 'dx_B', 'dx_C']:
    table[code] = (table == code).sum(axis=1)
table = table.drop(['Code_1', 'Code_2', 'Code_3'], axis=1)

result = pd.DataFrame()
for year in [1, 2, 3]:
    df_year = table.loc[(table.enroll_date < table.service_date + pd.DateOffset(years=year)) &
                       (table.enroll_date >= table.service_date + pd.DateOffset(years=year-1))]
    result_tmp = df_year.groupby('user_id').sum().add_suffix('_' + str(year) + '_yr')
    result = pd.concat([result, result_tmp], axis=1, sort=False)

result = result.fillna(0).astype(int)

Here is the result I got


text:
Q: Where can I find a good JavaScript/HTML AutoSuggest example I am looking for a good example implementation of a JavaScript/HTML AutoSuggest input box to get me started. What I am trying to implement will behave "Exactly" like the Tags input box here on stackoverflow.
If it helps I am using jQuery to perform Ajax request.
I am finding examples to help me implement this however I am concerned what about best practices in the area and would love to get opinions also.

A: Er, jQuery Autocomplete?  And another example.

A: Antonio Lupetti has just posted a review of Javascript based auto suggest scripts in his article Useful Ajax Auto Suggest scripts collection.
You might find some interesting links there?

A: Try the YUI Auto complete. Works great!! http://developer.yahoo.com/yui/autocomplete/

A: I used brandspankingnew's AutoSuggest (and happy of it) -> http://www.brandspankingnew.net


text:
Q: How can I fix mouse lag in Skyrim? I have insane mouse lag in Skyrim. I have changed
iPresentInterval=0

in Skyrim.ini file and
bMouseAcceleration=0

in Skyrimprefs.ini
But I still have mouse lag and the game is unplayable. What can I do?

A: There are two fixes for mouse lag. There's the one you mentioned, which you should use. There's also this one:

Disable mouse smoothing

*

*Go to your Steam Directory, then steamapps, common, skyrim and select Skyrim again.

*Create a backup of the SkyrimPrefs.ini file.

*Open the file, then scroll down to where it says [Controls] and find bMouseAcceleration=1.

*Change to bMouseAcceleration=0.

*Save, exit, and play.

  This fix and the two below are from Skyrim Reddit, and are credited to "Dead man posting" on the Something Awful Forums.

Using both of these worked well for me.
source: http://www.pcgamer.com/2011/11/11/the-elder-scrolls-v-skyrim-tweaks-improve-graphics-disable-vsync-change-fov-and-more/

A: I had the same problem that you are experiencing and determined that the source of the problem lies with the mouse (for me anyhow). I have the razor naga, and after turning off acceleration in skyrim and also turning off vsync I experienced the same lag. When i would move the mouse rapidly the game could not keep up. After thinking about it I found that the razor naga had an acceleration of its own and after turning off the mouse acceleration directly at the source of the mouse (razer naga control panel "downloadable driver") the game ran perfectly.


text:
Q: Creating a Wheel of Fortune-esque puzzle board using JPanel/JFrame Java I was assigned a free-form Java coding assignment in my computer science class in which my group and I decided to make a Wheel of Fortune type game. I've been working on the GUI using JPaneland JFrame, which our online academy goes into some detail on, so I know most of the absolute basics. I managed to get a non-aesthetic but functioning box that displays individual player money and name in a class named playerPlate, as well as a button panel for all the buttons we will need at some point during the game in a class called buttonPanel.
When it came to making the letter/puzzle board where the puzzle is displayed on a 12-14-14-12 grid, I experienced a slew of problems. Here is my code for the letterBoard class which I'm using to try to make the puzzle board.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class letterBoard extends JPanel
                            implements ActionListener
{
private JTextField a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,
a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22,a23,
a24,a25,a26,a27,a28,a29,a30,a31,a32,a33,a34,a35,a36,
a37,a38,a39,a40,a41,a42,a43,a44,a45,a46,a47,a48,a49,
a50,a51,a52;
    JTextField board[] = new JTextField[52];
    public letterBoard()
    {
    setBackground(Color.GREEN);
    JTextField a1 = new JTextField(" ");
    JTextField a2 = new JTextField(" ");
    JTextField a3 = new JTextField(" ");
    JTextField a4 = new JTextField(" ");
    JTextField a5 = new JTextField(" ");
    JTextField a6 = new JTextField(" ");
    JTextField a7 = new JTextField(" ");
    JTextField a8 = new JTextField(" ");
    JTextField a9 = new JTextField(" ");
    JTextField a10 = new JTextField(" ");
    JTextField a11 = new JTextField(" ");
    JTextField a12 = new JTextField(" ");
    JTextField a13 = new JTextField(" ");
    JTextField a14 = new JTextField(" ");
    JTextField a15 = new JTextField(" ");
    JTextField a16 = new JTextField(" ");
    JTextField a17 = new JTextField(" ");
    JTextField a18 = new JTextField(" ");
    JTextField a19 = new JTextField(" ");
    JTextField a20 = new JTextField(" ");
    JTextField a21 = new JTextField(" ");
    JTextField a22 = new JTextField(" ");
    JTextField a23 = new JTextField(" ");
    JTextField a24 = new JTextField(" ");
    JTextField a25 = new JTextField(" ");
    JTextField a26 = new JTextField(" ");
    JTextField a27 = new JTextField(" ");
    JTextField a28 = new JTextField(" ");
    JTextField a29 = new JTextField(" ");
    JTextField a30 = new JTextField(" ");
    JTextField a31 = new JTextField(" ");
    JTextField a32 = new JTextField(" ");
    JTextField a33 = new JTextField(" ");
    JTextField a34 = new JTextField(" ");
    JTextField a35 = new JTextField(" ");
    JTextField a36 = new JTextField(" ");
    JTextField a37 = new JTextField(" ");
    JTextField a38 = new JTextField(" ");
    JTextField a39 = new JTextField(" ");
    JTextField a40 = new JTextField(" ");
    JTextField a41 = new JTextField(" ");
    JTextField a42 = new JTextField(" ");
    JTextField a43 = new JTextField(" ");
    JTextField a44 = new JTextField(" ");
    JTextField a45 = new JTextField(" ");
    JTextField a46 = new JTextField(" ");
    JTextField a47 = new JTextField(" ");
    JTextField a48 = new JTextField(" ");
    JTextField a49 = new JTextField(" ");
    JTextField a50 = new JTextField(" ");
    JTextField a51 = new JTextField(" ");
    JTextField a52 = new JTextField(" ");
    Box b1 = Box.createHorizontalBox();
    b1.add(Box.createHorizontalGlue());
    b1.add(Box.createHorizontalStrut(5));
    b1.add(a1);
    b1.add(Box.createHorizontalStrut(5));
    b1.add(a2);
    b1.add(Box.createHorizontalStrut(5));
    b1.add(a3);
    b1.add(Box.createHorizontalStrut(5));
    b1.add(a4);
    b1.add(Box.createHorizontalStrut(5));
    b1.add(a5);
    b1.add(Box.createHorizontalStrut(5));
    b1.add(a6);
    b1.add(Box.createHorizontalStrut(5));
    b1.add(a7);
    b1.add(Box.createHorizontalStrut(5));
    b1.add(a8);
    b1.add(Box.createHorizontalStrut(5));
    b1.add(a9);
    b1.add(Box.createHorizontalStrut(5));
    b1.add(a10);
    b1.add(Box.createHorizontalStrut(5));
    b1.add(a11);
    b1.add(Box.createHorizontalStrut(5));
    b1.add(a12);
    b1.add(Box.createHorizontalStrut(5));
    b1.add(Box.createHorizontalGlue());
    Box b2 = Box.createHorizontalBox();
    b2.add(Box.createVerticalStrut(5));
    b2.add(a13);
    b2.add(Box.createVerticalStrut(5));
    b2.add(a14);
    b2.add(Box.createVerticalStrut(5));
    b2.add(a15);
    b2.add(Box.createVerticalStrut(5));
    b2.add(a16);
    b2.add(Box.createVerticalStrut(5));
    b2.add(a17);
    b2.add(Box.createVerticalStrut(5));
    b2.add(a18);
    b2.add(Box.createVerticalStrut(5));
    b2.add(a19);
    b2.add(Box.createVerticalStrut(5));
    b2.add(a20);
    b2.add(Box.createVerticalStrut(5));
    b2.add(a21);
    b2.add(Box.createVerticalStrut(5));
    b2.add(a22);
    b2.add(Box.createVerticalStrut(5));
    b2.add(a23);
    b2.add(Box.createVerticalStrut(5));
    b2.add(a24);
    b2.add(Box.createVerticalStrut(5));
    b2.add(a25);
    b2.add(Box.createVerticalStrut(5));
    b2.add(a26);
    b2.add(Box.createVerticalStrut(5));
    Box b3 = Box.createHorizontalBox();
    b3.add(Box.createVerticalStrut(5));
    b3.add(a27);
    b3.add(Box.createVerticalStrut(5));
    b3.add(a28);
    b3.add(Box.createVerticalStrut(5));
    b3.add(a29);
    b3.add(Box.createVerticalStrut(5));
    b3.add(a30);
    b3.add(Box.createVerticalStrut(5));
    b3.add(a31);
    b3.add(Box.createVerticalStrut(5));
    b3.add(a32);
    b3.add(Box.createVerticalStrut(5));
    b3.add(a33);
    b3.add(Box.createVerticalStrut(5));
    b3.add(a34);
    b3.add(Box.createVerticalStrut(5));
    b3.add(a35);
    b3.add(Box.createVerticalStrut(5));
    b3.add(a36);
    b3.add(Box.createVerticalStrut(5));
    b3.add(a37);
    b3.add(Box.createVerticalStrut(5));
    b3.add(a38);
    b3.add(Box.createVerticalStrut(5));
    b3.add(a39);
    b3.add(Box.createVerticalStrut(5));
    b3.add(a40);
    b3.add(Box.createVerticalStrut(5));
    Box b4 = Box.createHorizontalBox();
    b4.add(Box.createVerticalStrut(5));
    b4.add(a41);
    b4.add(Box.createVerticalStrut(5));
    b4.add(a42);
    b4.add(Box.createVerticalStrut(5));
    b4.add(a43);
    b4.add(Box.createVerticalStrut(5));
    b4.add(a44);
    b4.add(Box.createVerticalStrut(5));
    b4.add(a45);
    b4.add(Box.createVerticalStrut(5));
    b4.add(a46);
    b4.add(Box.createVerticalStrut(5));
    b4.add(a47);
    b4.add(Box.createVerticalStrut(5));
    b4.add(a48);
    b4.add(Box.createVerticalStrut(5));
    b4.add(a49);
    b4.add(Box.createVerticalStrut(5));
    b4.add(a50);
    b4.add(Box.createVerticalStrut(5));
    b4.add(a51);
    b4.add(Box.createVerticalStrut(5));
    b4.add(a52);
    b4.add(Box.createVerticalStrut(5));
    add(b1);
    add(b2);
    add(b3);
    add(b4);
    }
    public void actionPerformed(ActionEvent e)
    {
    //logic to be added later
    }
   }

Sorry about the sloppy code. First time posting and was having a bit pf trouble getting it to format correctly. When the above code is run through the wheelGUI class, it essentially creates 4 separate horizontal segments that are much smaller than I would like, editable, and not stacking correctly. I played around with different boxes, struts, and border layouts but could never get it to work properly. And while the code does compile and run (I'm aware of some consistency errors between the separate boxes, forgot to re-do that segment) it is extremely inefficient, as any changes must be done to ~52 different lines of code. I experimented with an iterate method I made:
public void iterate(JTextField[] foo)
{
    board = foo;
    for(int i=0; i<foo.length; i++)
    {
        foo[i] = new JTextField(" ");
    }
}

However, this resulted in a NullPointerException error and did not properly instantiate the a1-52 variables to be used in the boxes. Any help I could get would be great. I apologize if my post and my code are a mess.

A: You should have an array of JTextFields and an array of Box or JPanel containers if that is what you need. Combine them in a for loop.
private JTextField[] fields = new JTextField[TEXT_FIELD_COUNT]; // const = 52
private Box[] boxes = new Box[SUIT_COUNT];  // suit count = 4

for (int i = 0; i < boxes.length; i++) {
  boxes[i] = Box.createHorizontalBox();
  for (int j = 0; j < TEXT_FIELD_COUNT/SUIT_COUNT; j++) {
    int index = i * (TEXT_FIELD_COUNT / SUIT_COUNT) + j;
    fields[index] = new JTextField(COLS); // COLS = some const, possibly 10
    boxes[i].add(fields[index]);
    // add your strut if desired
  }
}


text:
Q: Getting System.NullReferenceException at Xamarin.Forms.Platform.Android.AppCompat.NavigationPageRenderer.OnLayout Getting Exception when set the App.Main Page in ViewModel.
Application.Current.MainPage = new NavigationPage(new HomeView());

HomeView is a MasterDetailPage.
in a Detail Page i have a Content page that have Custom horizontal scrollView, and Content View that have itemSource Bindable Property.

System.NullReferenceException
  at Xamarin.Forms.Platform.Android.AppCompat.NavigationPageRenderer.OnLayout (System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32 r, System.Int32 b) [0×00007] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\NavigationPageRenderer.cs:292
  at mySMARTSMobile.Droid.Renderers.Droid_NavigationRenderer.OnLayout (System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32 r, System.Int32 b) [0×00002] in /Users/Ankit/Desktop/Himanshu/SMARTS/mySMARTSMobile.Droid/Renderers/Droid_NavigationRenderer.cs:45

Xamarin.Forms Version: 2.3.4.247
Please guild me why i am getting this Exception, I am beginner for Xamarin Forms.
public partial class HomeView : MasterDetailPage
{
    public HomeView()
    {
        InitializeComponent();
        NavigationPage.SetHasNavigationBar(this, false);

        var vm = new MainViewModel();
        vm.GetData();
        Detail = new NavigationPage(new MainView(vm));
        //System.GC.Collect();
    }

    protected async override void OnAppearing()
    {
        base.OnAppearing();
        //await Task.Delay(10);
    }
}

In LoginViewModel
Application.Current.MainPage = new NavigationPage(new HomeView());


text:
Q: WordPress Simplified Chinese language code As part of localization for our WordPress website we need to support Chinese simplified script. Not knowing anything about Chinese we did some research and used zh-CN (also known as zh-Hans).
Our client states this is incorrect and we should use:
ch-cn (also known as ch-hans).  We checked several language plugins and did some research on the internet but this code ch-cn seems pretty rare. Is my client wrong? He wants to use simplified script, chinese PRC
Many thanks!

A: The client is wrong, and  zh-CN and zh-Hans are correct (their meanings are different in principle, but they boil down to the same language form). In HTML, on the Internet, and in most other contexts that might be imaginable here, a two-letter code as the first part of a language code must be an ISO 639-1 code. The authoritative registry assigns  "ch" to the Chamorro language, whereas "zh" is assigned to Chinese.


text:
Q: Pandas DataFrame Display Without Dimensions When I print a DataFrame it displays the dimensions of the object (n rows by k columns) at the bottom of the printout. So, for example:
import pandas as pd
df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})

print(df)

will display:
    A   B      C
0  10  20     32
1  20  30    234
2  30  10     23
3  40  40     23
4  50  50  42523

[5 rows x 3 columns]

Is there a way to turn off the display of that final line [5 rows x 3 columns]?

A: Yes! Use pd.options.display.show_dimensions = False:
Here is the original repr:
In [118]: df
Out[118]:
    A   B      C
0  10  20     32
1  20  30    234
2  30  10     23
3  40  40     23
4  50  50  42523

[5 rows x 3 columns]

After setting show_dimensions = False:
In [119]: pd.options.display.show_dimensions = False

In [120]: df
Out[120]:
    A   B      C
0  10  20     32
1  20  30    234
2  30  10     23
3  40  40     23
4  50  50  42523

See the pd.get_option docstring (print(pd.get_option.__doc__) for more on all the options.


text:
Q: Is there a way to manually set the ApplicationSession network timeout for Android Chromecasting? I'm sending a MediaProtocolMessageStream.loadMedia command to my receiver.  After a few seconds my session ends with a "network I/O timeout" with channel=SessionError.CATEGORY_DISCONNECT_CHANNEL and code=SessionError.CODE_TIMEOUT.  This only happens for longer videos in the range of over 200 minutes so I'm assuming there's a legitimate timeout going on.  Is there anyway to tweak the timeout time in a session so I can load larger movies?  I see there's a final DEFAULT_TIMEOUT in the underlying NetworkRequest, but I have no way of accessing it.

A: Timeout value cannot be adjusted by application. It would help us to understand what is causing the timeout in your case. Timeout happens when either the sender does not reply to the receiver's ping requests in a timely manner, or when the sender has not received a ping from the receiver for a certain length of time. It might be the case that the media you are trying to load is tying up the CPU on the receiver so that it can't send its ping request to the sender. Do you see anything in the sender's log similar to "timeout waiting for ping" or so?


text:
Q: Getting details of added place from Google Places API Right now I'm working on a project in which I need to use the Google Places API and I'm too novice in using the Google Places API. The scenario which I want to ask is that how can I get details of a place using place_id which I got in response of place add?
I have searched through all the places but most of them said that you have to use reference attribute in request parameters. So, can I get a solution of this?
I read this information from these lines in Google Places API docs:-
Place Add Responses

Place add responses are returned in the format indicated by the output flag within the request's URL path.

The API returns a status code, and if the request was successful the response includes the following properties for the new place:

    place_id: A unique identifier for a place. To retrieve information about the place, pass this identifier in the placeId field of a Places API request.

A: There is an entire library that someone has built for the Places API for development in java or android. Please see this link: https://github.com/windy1/google-places-api-java


text:
Q: Retrieve the filtered data from HTML table and format it into array I've been working on a function in a PHP system where I can filter the records and then export it to Excel that has a template using PHPSpreadSheet. My problem is that I don't know how to retrieve the filtered records as said in the title above. I think I'm missing something here in my code. This is my code in fetching the records from database into table.
<?php
    $conn = mysqli_connect("localhost", "root", "", "db_ims");
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM tbl_par";
$result = mysqli_query($conn, $sql);

      echo "
";
      echo "

Article
      Description
      Property Number

";
      echo "
";
      while ($row = mysqli_fetch_assoc($result)) {
      echo "
";
      echo "" . $row['article'] . "	";
      echo "" . $row['description'] . "	";
      echo "" . $row['propertyNumber'] . "	";
      echo "
";
      }
      echo "
";
      echo "
";

// Close the database connection
mysqli_close($conn);
?>
    <form action="" method="POST">
    <input type="text" id="myInput" onkeyup="filterTable()" placeholder="Search...">
    <input type="submit" id="generate" name="generate" value="Submit">
    </form>

This is my code in filtering the records:

Lastly, this is the code in exporting the filtered table into excel using PHPSpreadSheet:
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

if (isset($_POST['generate'])) {

$spreadsheet = IOFactory::load('Template.xls');

//This is the part where I don't know what to put.
$data = array();

$worksheet = $spreadsheet->getActiveSheet();
$row = 10; // Start inserting data from row 10
foreach ($data as $item) {
    $worksheet->setCellValue('A'.$row, $item['article']);
    $worksheet->setCellValue('B'.$row, $item['description']);
    $worksheet->setCellValue('C'.$row, $item['propertyNumber']);
    // ...
    $row++;
}

$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('exported_file.xlsx');
}
?>

I tried every possible way that I know but still didn't got my expected result.

A: If you want to submit the values you need to echo the table inside the form and have something to submit - a hidden field for example - then you can add disabled to the fields you do not want to submit
const hide = txtValue.toUpperCase().indexOf(filter) === -1 : true : false;
tr[i].style.display = hide ? "none" : "";
tr[i].querySelector("[type=hidden]").disabled = hide;

I strongly suggest you use AJAX here instead.


text:
Q: What browser / browser engine do Office Add-ins use? So I am trying to get started developing Office 365 Add-ins (previously Apps for Office), and I was wondering what browser or browser engine Office uses when it renders your app. I tried using JavaScript's navigator.appCodeName and navigator.appName, but due to the problem described here renders that method useless. What browser or engine do Office Add-ins use to render apps?

A: It depends on where Office is being used. If it's on Windows Desktop, Office Add-ins use an Internet Explorer to load the hosted webpage in Office.  For iOS, it will rely on the native WebView control.  If on Office Online, it will use a sandboxed iframe, in which ever browser you open Office Online with.
If you're trying to determine the browser Office is running in, I believe sniffing the user agent string will work for you.


text:
Q: Invalid protected resource url Exception while trying to access Magento REST API using OAuth? I'm getting the below error when trying to access Magento REST API in post method in live server.

Invalid protected resource url, unable to generate signature base
  string

In my localhost its working fine with same code. I'm using oauth authentication for REST API in magento. Also GET and PUT methods working fine in same server. Can anybody help me on this issue?


text:
Q: Debian server can't connect to outside world and vice versa At some point within the past 48 hours my KVM server, which had been running without issue for 6 months, went down completely and was unreachable. Using the control panel to my server, I saw that the server was in fact offline. I got in touch with my host and they weren't able to provide me with any information at all. I rebooted the server, and tried to connect to the IP address and other sites hosted, and wasn't able to. Whether using a browser or nslookup, the connection would time out.
I accessed the virtualization via VNC, and gained access to the machine. All my files and everything else seem to be in order, and the machine doesn't seem to have been accessed by anyone else but me.
Pinging the server IP and domain names alike, result in a timed out connection. From the server's terminal, I am getting servfail errors when I try to nslookup or dig an outside IP.
nslookup google.com
;; GOT SERVFAIL reply from 127.0.0.1, trying next server
Server:         ::1
Address:        ::1#53

** server can't find google.com: SERVFAIL

dig google.com
; <<>> DiG 9.9.5-9+deb8u3-Debian <<>> google.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: Query, status: SERVFAIL, id: 40939
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp:4096
;; QUESTION SECTION:
;google.com

;; Query time: 53 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Thu Jan 21 16:54:54 EST 2016
;; MSG SIZE rcvd: 39

I also can't access the internet via the virtualization on a browser.
I can lookup 127.0.0.1 just fine though. So I think it might be a networking issue, but frankly, I'm at a loss, and I don't know what to do.
Any help at all would be appreciated.
EDIT:
ifconfig -a
eth0    Link encap:Ethernet HWadder 00:16:3c:46:e9b0
        inet6 addr: fe80::216:3cff:fe46:e9b0/64 Scope:Link
        UP BROADCASTING RUNNING MULTICAST  MTU:1500  Metric:1
        RX packets:1054844 errors:0 dropped:0 overruns:0 carrier:0
        collisions:0 txqueuelen:1000
        RX bytes:65592375 (62.5MiB)  TX bytes:80043 (78.1 KiB)

lo      Link encap:Local Loopback
        inet addr:127.0.0.1 Mask:255.0.0.0
        inet6 addr: ::1/128 Scope:Host
        UP LOOPBACK RUNNING  MTU:65536  Metric:1
        RX packets:996 errors:0 dropped:0 overruns:0 frame:0
        TX packets:996 errors:0 dropped:0 overruns:0 carrier:0
        collisions:0 txqueuelen:0
        RX bytes:85328 (83.3 KiB)  TX bytes:85328 (83.3 KiB)

route -n
`Destination    Gateway    Genmask    Flags Metric Ref    Use Iface
arp -n returns no result.
EDIT 2:
/etc/network/interfaces

source /etc/network/interfaces.d/*
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp

A: as Michael Hampton your eth0 interface is configured to get IP address information via DHCP.
Normally you would need to configure your network interface manually or static.
An example would look like this in you /etc/network/interfaces config file
auto eth0
iface eth0 inet static
    address 192.0.2.7
    netmask 255.255.255.0
    gateway 192.0.2.254

More information could be found in the debian documentation.2
So check with your server hoster what IP address, netmask and gateway your server should have. Sometimes you can get the information out of the customer portal.
As soon as you have this data configure your network interface accordingly.
Regards
-- arl


text:
Q: Prevent IIS from using SSL certificate for other localhost website I'm trying to set up a different website on IIS but it keeps wanting to use an SSL certifcate that is configured for a different website within the same IIS.
e.g. https://localhost:443 has a security certificate but i want to create http://localhost:98/
Steps I've done:

*

*Created a new application pool

*Created the website within IIS

*Edited bindings to point to a specific IP address and port: e.g: http://123.456.789.10:98/

*Edited binding for localhost to use a different port: 98 e.g: localhost:98/

What's happening is that now whenever I go to localhost:98 or the ip address, it keeps redirecting the site back to the website that has the SSL certificate for it
eg. I click localhost:98/ but it redirects to https://localhost/
What can possibly be incorrect with this setup? I had it working before but then when i tried to apply a different SSL certificate, it didn't work, i re-set up everything and it's constantly pointing to this situation.


text:
Q: PostBackUrl doesn't set Page.IsCrossPagePostBack to true I have a legacy application at my hand which uses ASP.NET WebForms.
My problem here is that, LinkButton controls doesn't set the Page.IsCrossPagePostBack to true. In this application, there are 6 LinkButton controls which are used to create related entities (they post back to a different page than the action of the form element). This MSDN Article claims that PostBackUrl causes Page.IsCrossPagePostBack to become true. But in my code, this is not the case. It always returns false.
Any idea?

A: It's a bit counterintuitive, but you have to read very carefully:

In either case, the PreviousPage page property will contain an object that represents the previous or originator page. If, for example, Page A posts to Page B, Page A's IsCrossPagePostBack property (accessible through the PreviousPage property) will be true and Page B's PreviousPage property will have the name of Page A.

So the solution is:
    if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
        // do stuff


text:
Q: Saving data in React Native Link to the File Structure Photo
So I'm currently learning React Native and assuming a file structure shown in the photo. I would like the user to click a button such that the button saves some text to a txt file under resources. How would I go about doing that?
I have tried AsyncStorage, fn-fetch-blob, react-native-filesystem but they have failed (not sure if those libraries are meant to be for specific file directories on your phone device)
What I have so far is a code shown below where if the user clicks the "Create file" button, then it saves to a text file called "my-file.txt" under the same directory as where the current .js file is, which well doesn't work
import FileSystem from 'react-native-filesystem'

export default class SaveData extends React.Component {
    render() {
        return (
            <View style={styles.container}>
                <TouchableOpacity onPress={this.createFile}>
                    <Text>Save to file</Text>
                </TouchableOpacity>
            </View>
        );
    }

    createFile = async () => {
        const fileContents = 'This is some content.';
        await FileSystem.writeToFile('./my-file.txt', fileContents);
    }
}

A: What you are trying to do here is not possible. There is no way of accessing these directories when your app is running. This is not the same as when you are running on a computer (a node.js app for example). This file structure will not be available when you are running in a native environment.
Async storage is not used to save files. It is used to save values, so it will never work for what you are trying to accomplish here.
The closest thing to what you are trying to do would be to use react-native-fetch-blob and store the file in the file system of the device, which is also the correct way of storing a file on a mobile device.


text:
Q: How to read csv file from resources dir in JUnit Test using FileUtils Have a csv file inside a standard maven project's resources dir as follows:
src/main/resources/fruits.csv
src/test/resources/fruits.csv

fruits.csv
Type, Quantity
apple, 50
banana, 60
orange, 70

Using the following libraries
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.0</version>
</dependency>

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

Fruit (standard POJO)
public class Fruit {

    private String type
    private int quantity;

    public Fruit(String type, int quantity) {
        this.type = type;
        this.quantity = quantity;
    }

    // Getters & Setters
}

CsvFileReader
public class CsvFileReader {

    private static final String [] FILE_HEADER = {""};

    private static final String TYPE = "Type";
    private static final String QUANTITY + "Quantity";

    public static List<Candidate> readCsvFile(File fileName) {
        FileReader fileReader = null;
        CSVParser csvFileParser = null;

        CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER);
        List<Candidate> fruits = null;
        try {
            fruits = new ArrayList<>();
            String file = FileUtils.readFileToString(fileName);
            fileReader = new FileReader(file);
            csvFileParser = new CSVParser(fileReader, csvFormat);
            List<CSVRecord> records = csvFileParser.getRecords();

            for (int i = 1; i < records.size(); i++) {
                CSVRecord record = records.get(i);
                Fruit fruit = new Fruit(record.get(TYPE), Integer.parseInt(QUANTITY));
                fruits.add(fruit);
            }
        }
        catch(Throwable t) {
            t.printStackTrace();
        }
        finally {
            try {
                fileReader.close();
                csvFileParser.close();
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
        return fruits;
    }
}

CsvFileReaderTest (JUnit 4 Test Case):
public class CsvFileReaderTest {

    File csvFile = null;

    @Before
    public void setUp() throws Exception {
        String userDir = System.getProperty("user.dir");
        String filePath = userDir + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator;
        csvFile = FileUtils.getFile(filePath + "fruits.csv");
    }
}

When I run the JUnit Test Case inside Eclipse:
java.io.FileNotFoundException: Type, Quantity
apple, 50
banana, 60
orange, 70
(File name too long)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:146)
    at java.io.FileInputStream.<init>(FileInputStream.java:101)
    at java.io.FileReader.<init>(FileReader.java:58)

It seems to reading the file but the problem is that the FileName is too long?
What am I doing wrong?

A: FileReader constructor expects a path to file where you pass a content of the file. You may use directly CSVParser constructor which takes CSV String.
csvFileParser = new CSVParser(file /*This is already file content*/, csvFormat);

** Edit **
Even better would be to obtain reader for the resource and pass it to CSVParser constructor:
reader = new BufferedReader(new InputStreamReader(
                       this.getClass().getResourceAsStream("fruits.csv")));
csvFileParser = new CSVParser(reader, csvFormat);


text:
Q: Why do photons and gluons not interact with the Higgs field? I'm looking for a non-mathematic answer as I am yet to begin studying physics or calculus, still half a year away. Just a simple explanation in layman's terms.
As i understood it, electrons for example are massless before interacting with the field, like photons. so why do electrons interact with the higgs field and not photons and gluons?

A: This is a difficult question to answer in layman's terms without simply saying "that's how the universe works".
You might be familiar with an expression called the "Standard Model Lagrangian" that appears on things like mugs and T-shirts, like the ones here. This details all of the fields and interactions in the universe that we know of, save for gravity, dark matter and dark energy. The Higgs field is often referred to using the symbol $\phi$. The Lagrangian, when fully expanded contains terms that look like
$$\sim \phi^2 W^2 \qquad \text{or} \qquad \sim \phi \psi_\mathrm{e}^\dagger \psi_\mathrm{e}.$$
In simple terms, this basically says that the Higgs field interacts with the $\mathrm{W}$-boson field, and the electron field $\psi_\mathrm{e}$.
However, there are no similar terms for the photon, the gluon field, or neutrinos. For the photons this is by definition: the photon field is defined as the part of the electroweak interaction that doesn't couple to the Higgs field. For the other fields this is because these terms do not match observations. Neutrinos have a bit of a caveat, because they have a very small mass, that cannot be included in the Standard Mode by interaction with the Higgs field, whilst keeping in line with other observations (i.e. no right-handed neutrinos).
Hopefully this helps make things a little clearer.


text:
Q: Sending objects between GDScript and Rust using TCP I want to connect my game to a rust server and have an event based communication.
The enum on the rust side looks somewhat like this:
enum Event {
    Login(String),
    LoadChunk(Chunk),
    ChunkUpdate(Chunk),
}

I already got a very simple Client and Server using StreamPeerTCP and std::net::TcpListener working and I can already send utf8 encoded strings between them.
Now I want to send an event from the server to the client.
To do so I serialize the event on the server into JSON and then send the bytes from this string to the client using as_bytes().
This is the function on the client which processes the data received from StreamPeerTCP:
func _handle_client_data(data: PoolByteArray) -> void:
    var string_data: String = data.get_string_from_utf8();

    var parsed_data: Object = JSON.parse(string_data);

But now due to loose typing I do not know how I should access any fields from the object.
I think I am doing something fundamentally wrong but I do not know any better solution.
Can anyone help me on how to approach such a problem?

A: I moved the whole TCP-client to rust and tokio using GDNative.
The interface between the rust and GDscript languages is still JSON.
the client emits a Event signal which gets handled in this function by the TcpClientWrapper:
func handle_event(event: String):
    var type: String = event.split('"', true, 2)[1];
    match type:
        "Error":
            var kind: String = JSON.parse(event).result.Error;
            self.emit_signal("Error", kind);
        "Token":
            var token: Array = JSON.parse(event).result.Token;
            self.emit_signal("Token", token);
        _:
            # ChunkUpdate not yet implemented
            print("invalid event type");

The original Event in rust:
pub enum ServerToClient {
    Error(ClientError),
    Token(Token),
    ChunkUpdate(Chunk),
}

To interface With the client I have this script in ClientTcpWrapper:
extends Node;

# position and string
signal ChunkUpdate(position, chunk);
# array
signal Token(token);
# string
signal Error(kind);

export var host: String = "0.0.0.0:8000";

onready var client: Node = self.get_node("TcpClient");

func _ready():
    client.establish_connection(host);

    client.connect("Event", self, "handle_event");

func connection_established() -> bool:
    return client.connection_established();

func register(name: String):
    var string = '{"Register":{"name":"' + name + '"}}';
    client.send(string);

func move(pos: Vector3):
    var x = str(pos.x).pad_decimals(10);
    var y = str(pos.y).pad_decimals(10);
    var z = str(pos.z).pad_decimals(10);
    var string = '{"Move":{"coord":[' + x + "," + y + "," + z + ']}}';

    client.send(string);

func handle_event(event: String):
    var type: String = event.split('"', true, 2)[1];
    match type:
        "Error":
            var kind: String = JSON.parse(event).result.Error;
            self.emit_signal("Error", kind);
        "Token":
            var token: Array = JSON.parse(event).result.Token;
            self.emit_signal("Token", token);
        _:
            print("invalid event type");


text:
Q: Multiplying two conditional probabilities? I have now tried for hours and concluded I need someone to show me how it is done. Can anyone show that $p(t, \mathbf{w} | x, \mathbf{x}, \mathbf{t}) = p(t | x, \mathbf{w}) p(\mathbf{w} | \mathbf{x}, \mathbf{t})$?
If relevant, $x$ and $t$ are not dependent on $\mathbf{x}$ and $\mathbf{t}$. You can assume any additional independence if you think it is necessary.

A: If you assume that $\textbf{w}$ is independent of $x$ and that $t$ is independent of $(\textbf{x}, \textbf{t})$, then you have
$$\begin{align*}p(t,\textbf{w}|x, \textbf{x}, \textbf{t}) &= p(t|\textbf{w}, x, \textbf{x}, \textbf{t})\cdot p(\textbf{w}|x, \textbf{x}, \textbf{t})\\&= p(t|\textbf{w}, x)\cdot p(\textbf{w}|\textbf{x}, \textbf{t}),\end{align*}$$
where the first equality follows from the definition of conditional probability.


text:
Q: How to access GUI from TTY mode? I am using Ubuntu 13.10 32-bit. I am using terminal mode to test a  Window Manager.
I know I can use Ctrl+Alt+F1 to go to terminal mode from the GUI mode. But there is still graphical desktop running in background.
Is there a command to move from CLI to GUI mode so that I can access that GUI?

A: To check your default display manager (DM):
cat /etc/X11/default-display-manager

To check if the display manager is running:
ps cax | grep display_manager

e.g.: if it's lightdm:
ps cax | grep lightdm

(you can then follow up with echo $? command, an output 0(zero) indicate its running or otherwise.)
To start a DM:
sudo start display_manager

e.g.:
sudo start lightdm

To stop a DM:
sudo stop display_manager

e.g.:
sudo stop lightdm

To restart a DM:
sudo restart display_manager

e.g.:
sudo restart lightdm

A: Try this command on virtual console,
sudo service $(cat /etc/X11/default-display-manager | awk '{print substr($1,11)}' ) restart

A: You can either:
Press Ctrl+Alt+F7 *
Or
Run the command startx

If your desktop environment is using Wayland
Press Ctrl+Alt+F8 instead.

* From the 17.10 Release Notes:

*

*GDM has replaced LightDM as the default display manager. The login screen now uses virtual terminal 1 instead of virtual terminal 7.

Also see Why is my GDM at a different TTY than my desktop environment? for more about the origin of this change.

A: the best way to test window manager safely is to use Xephyr. see man pages for more details.
I assume you use gnome-terminal here.

*

*start Xephyr
$ Xephyr :1

*Ctrl+Shitf+T open a new tab
$ export DISPLAY=:1
$ type_your_window_manager_command_here

Now you can play with your window manager in the Xephyr window.

A: You can use sudo chvt 1 if you normally do Ctrl+Alt+F1.


text:
Q: draw triangle shaped program in python This is the question i am working on, its a python Website:

Modify the previous program in two ways. First, instead of a square,
  make it draw a triangle shaped like this: ◤. Second, instead of
  always having 5 lines, it should take the desired size as input from
  input(). For example, if the input is 3, then the output should be
111
11
1

I have solved this so far, it has a predefined input() as told in the question.
my solving so far:
n=int(input())
for i in range(0, 3):
  X = 0-1
  for j in range(0, 3-i):
    X = (X*10)+1
  print(X)

A: I'm not sure exactly what your question is. If you're asking how to do it n times. then range(0, n) or range(n) will do that (If you are starting from 0 then you can omit the 0 from range.
n=int(input())
for i in range(n):
    X = 1
    for j in range(n-1-i): # -1 to reduce by factor of 10
        X = (X*10)+1
    print(X)


text:
Q: Use class member as WNDPROC/DLGPROC with or without global I'll go ahead and give a summary to this, how can I use a dialog procedure that is a member of a class? I am creating a window wrapper class, but CreateDialogParam needs a global dialog procedure, so I tried this workaround:
I have done a bit of searching on this topic. I am making a Dialog class which I am subclassing to make a CMainWnd and then instantiating that. In the Dialog class I have a member function defined as INT_PTR CALLBACK Dialog::cb_proc(HWND,UINT,WPARAM,LPARAM). Now, I know that windows must have a global function as a callback procedure.
So I made a std::map<HWND,Dialog*> DlgProcs map to associate the dialogs window handle with its Dialog class pointer.
And a INT_PTR CALLBACK DlgMainProc(HWND,UINT,WPARAM,LPARAM) so I could pass that to CreateDialogParam(). In the body of DlgMainProc(...) I search the map for using the hWnd parameter to find the Dialog* and return its cb_proc(..) member.
My problem is that none of the messages get processed, this is because the member procedure in my Dialog class never gets called. Even though when I put a MessageBox() in DlgMainProc inside a if (DlgProcs.find(hWnd) != DlgProcs.end()) { statement, the messagebox is displayed, over and over again until I have to abort the program from Visual Studio 2008. Which tells me that it is finding the hWnd in my map. The weird thing is it also does this if I put it in the else statement after that, which contradictingly tells me it is NOT finding the hWnd in the map.
If I put a messagebox in the cb_proc member function it does not get displayed at all. But during this I never get any compiler, linker, or runtime errors. When I remove the messagebox from it (as to not have to abort the program, it was just for debugging purposes) the program runs but no messages get processed, the X button does not close the program, button clicks do nothing.

Here is the PasteBin code: http://pastebin.com/GsGUBpZU
Btw, I have no problem subclassing this, my window is created fine, just no messages are processed, cb_proc just never gets called.
EDIT: Here is the relevant parts of the code
map<HWND,Dialog*> g_DlgProcs;

INT_PTR CALLBACK g_MainDlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
        if (g_DlgProcs.find(hWnd) != g_DlgProcs.end()) {
                Alert("blah"); // Gets executed repeatedly
                return g_DlgProcs[hWnd]->cb_proc(hWnd, msg, wParam, lParam);
        } else {
                Alert("blah"); // Removing the above alert, this gets
                               // executed repeatedly, erm, as well.. O.o strange
                return FALSE;
        }
}

Dialog::Dialog(int id, HWND parent /* = HWND_DESKTOP */) {
        _id = id;
        _parent = parent;

        // Tried this before CreateDialogParam
        g_DlgProcs.insert(make_pair(_handle, this));

        _handle = CreateDialogParam(
                (HINSTANCE)GetModuleHandle(NULL),
                MAKEINTRESOURCE(id), _parent,
                (DLGPROC)g_MainDlgProc, NULL
        );

        // Then tried it after CreateDialogParam
        g_DlgProcs.insert(make_pair(_handle, this));
}

INT_PTR CALLBACK Dialog::cb_proc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
        Alert("blah"); // Never gets executed

        bool handled = true;

        switch (msg)
        {
        case WM_INITDIALOG:
                OnInitialize();
                break;
        case WM_COMMAND:
                if (HIWORD(wParam) == 0 || HIWORD(wParam) == 1) {
                        OnMenuCommand((HIWORD(wParam) == 1), (int)LOWORD(wParam));
                } else {
                        OnCtrlCommand((int)HIWORD(wParam), (int)LOWORD(wParam), (HWND)lParam);
                }
                break;
        case WM_NOTIFY:
                {
                        LPNMHDR head = (LPNMHDR)lParam;
                        OnNotification(head->code, head->idFrom, head->hwndFrom);
                }
                break;
        case WM_CLOSE:
                OnClose(); // DestroyWindow(_handle)
                break;
        case WM_DESTROY:
                OnDestroy(); // PostQuitMessage(0)
        default:
                handled = ProcessMsg(msg, wParam, lParam);
        }

        // Convert bool to Windows BOOL enum
        return ((handled == true) ? TRUE : FALSE);
}

Does anybody know why it never gets called? Or maybe just guide me to another way to use a member function as a DLGPROC?

A: The standard solution is to pass your this pointer as the last parameter to Create,DialogParam, stash it in DWLP_USER in your WM_INITDIALOG handler, and retrieve it from DWLP_USER thereafter. Basically you use DWLP_USER as your map.

A: I tried your code and it worked: cb_proc gets called.  You will miss any messages (e.g. WM_INITDIALOG) that get sent before CreateDialogParam returns.
You can fix the latter problem by adding the window handle and the object to the map in g_MainDlgProc.  If you get a message for an unknown window, you know it belongs to the window you're creating; put the object in a global and you can add the handle/object to the map.

A: I'm just adding this here in case someone finds it useful; using the magic of C++11 lambdas and templates you can have a simple wrapper template that means you don't have to continually rewrite the boiler-plate code for saving and loading userdata in window and dialog box procedures.
Here's an example for the DialogBoxParam function, but the same technique can be applied to CreateDialogParam and CreateWindowEx as well.
template <typename T, INT_PTR (T::*P)(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)>
INT_PTR DialogBoxThis(T* pThis, HINSTANCE hInstance, LPCWSTR lpTemplateName, HWND hWndParent)
{
    return ::DialogBoxParam(hInstance, lpTemplateName, hWndParent, [](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -> INT_PTR {
        if (uMsg == WM_INITDIALOG) SetWindowLongPtr(hWnd, DWLP_USER, lParam);
        T* pThis = reinterpret_cast<T*>(GetWindowLongPtr(hWnd, DWLP_USER));
        return pThis ? (pThis->*P)(hWnd, uMsg, wParam, lParam) : FALSE;
    }, reinterpret_cast<LPARAM>(pThis));
}

You would use it like this:
class MyClass
{
    INT_PTR MyDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
};

// from inside MyClass, we can show a dialog that uses member function MyDlgProc as the dialog procedure
// note it is NOT a static function

DialogBoxThis<MyClass, &MyClass::MyDlgProc>(this, hInstance,
    MAKEINTRESOURCE(IDD_MYDIALOG), hWndParent);


text:
Q: React - Key press and move to component As a title: there is a way moving to components when pressed a key ?
For example:

*

*Click "Tab" and go to first row of my table;

*Click "Enter" and go to input.

I've tried use React reference but I have not succeeded.

A: Yes you can use react-use library it gives you some hooks to perform actions. you can import useKey from form it like this
import useKey from 'react-use/esm/useKey'

And then later in functional component can write
useKey('Escape', ()=>{})

Now when you will press escape it will run the callback function. In that function you can write focus logic.
Remember to use useKey, Component must be a functional component as we can only use hooks in functional components


text:
Q: highlight paragraph in docx file using python-docx I am trying to highlight a paragraph in a .docx file using python-docx.
from docx import Document
from docx.enum.text import WD_COLOR_INDEX

source_folder = 'D:/project/data2/'
f = source_folder+'test.docx'
document = Document(f)

for para in document.paragraphs:
    font1 = para.add_run().font
    font1.highlight_color = WD_COLOR_INDEX.RED
document.save(source_folder+'new.docx')

This code should highlight all the paragraphs in the document but it is not.

A: from docx import Document
from docx.enum.text import WD_COLOR_INDEX

source_folder = 'D:/project/data2/'
f = source_folder+'test.docx'
document = Document(f)

for para in document.paragraphs:
    for run in para.runs:
        run.font.highlight_color = WD_COLOR_INDEX.RED
document.save(source_folder+'new.docx')


text:
Q: Google Earth Engine: reproject images to the same projection Below, I have clipped the same region from 2 google earth images. However, the two clips are at different projections (the crs argument in reproject determines the projection). The reason I am reprojecting is to decrease the resolution of the images, via the scale argument, so that they can be imported with sampleRectangle.  How would I clip the images at the same projection such that they overlap?
import ee
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
import numpy as np

# Load images
pH = ee.Image("OpenLandMap/SOL/SOL_PH-H2O_USDA-4C1A2A_M/v02")
AAFC = ee.ImageCollection('AAFC/ACI')
AAFC = AAFC.filter(ee.Filter.date('2016-01-01', '2016-12-31')).first()

# Get geometry/polygon of interest
geometry = CAR.getInfo()['features'][15]['geometry']['coordinates']
region = ee.Geometry.Polygon(geometry)

# Clip AAFC and plot
AAFC_crs = AAFC.clip(region).projection().wkt()

AAFC_region = AAFC.clip(region)
AAFC_region = AAFC_region.resample('bilinear').reproject(crs=AAFC_crs, scale=1000)
AAFC_img = AAFC_region.sampleRectangle(defaultValue=0)
AAFC_img = np.array(AAFC_img.getInfo()['properties']['landcover'])
AAFC_img = AAFC_img.reshape(len(AAFC_img), -1)

plt.imshow(AAFC_img)
plt.colorbar()
plt.show()

# Clip pH and plot
pH_crs = pH.clip(region).projection().wkt()

pH_region = pH.clip(region)
pH_region = pH_region.resample('bilinear').reproject(crs=pH_crs, scale=1000)
pH_img = pH_region.sampleRectangle(defaultValue=0)
pH_img = np.array(pH_img.getInfo()['properties']['b30'])
pH_img = pH_img.reshape(len(pH_img), -1)

plt.imshow(pH_img)
plt.colorbar()
plt.show()

A: You should be able to set a common crs in both reproject() calls. Since I don't know where exactly your study area is you can use a global coordinate reference system like WGS84 with the EPSG Code 4326.
Alternatively you can look up the UTM Zone of your study area and get a more local EPSG code.
# Clip AAFC and plot
AAFC_region = AAFC.clip(region)
AAFC_region = AAFC_region.resample('bilinear').reproject(crs='EPSG:4326', scale=1000)

# Clip pH and plot

pH_region = pH.clip(region)
pH_region = pH_region.resample('bilinear').reproject(crs='EPSG:4326', scale=1000)


text:
Q: error with classifier.score() python-weka I'm trying to do a weka classifier for python to use python libraries with weka models, like @fracpete do on https://github.com/fracpete/sklearn-weka-plugin, but by my own.
Right now I have that and it works for predictions, use the SHAP library, etc.
from sklearn.base import BaseEstimator
from weka.classifiers import Classifier
from weka.core.dataset import Attribute, Instance, Instances
from sklearn.metrics import accuracy_score

class weka_classifier(BaseEstimator):

    def __init__(self, classifier = None, dataset = None, index = None):
        #Classifier: es el pww3/weka model
        #Dataset: Data for fit the model
        if classifier is not None:
            self.classifier = classifier

        elif dataset is not None:
            self.dataset = dataset
            self.dataset.class_is_last()

    def fit(self, X, y):
        return self.fit()

    def fit(self):
        return self.classifier.build_classifier(self.dataset)

    def predict_instance(self,x):
        x.append(0.0)
        inst = Instance.create_instance(x,classname='weka.core.DenseInstance', weight=1.0)
        inst.dataset = self.dataset
        return self.classifier.classify_instance(inst)

    def predict_proba_instance(self,x):
        x.append(0.0)
        inst = Instance.create_instance(x,classname='weka.core.DenseInstance', weight=1.0)
        inst.dataset = self.dataset
        return self.classifier.distribution_for_instance(inst)

    def predict_proba(self,X):
        prediction = []

        for i in range(X.shape[0]):
            instance = []
            for j in range(X.shape[1]):
                instance.append(X[i][j])
            instance.append(0.0)
            instance = Instance.create_instance(instance,classname='weka.core.DenseInstance', weight=1.0)
            instance.dataset=self.dataset

            prediction.append(self.classifier.distribution_for_instance(instance))

        return np.asarray(prediction)

    def predict(self,X):
        prediction = []
        for i in range(X.shape[0]):
            instance = []
            for j in range(X.shape[1]):
                instance.append(X[i][j])
            instance.append(0.0)
            instance = Instance.create_instance(instance,classname='weka.core.DenseInstance', weight=1.0)
            instance.dataset=self.dataset
            prediction.append(self.classifier.classify_instance(instance))

        return np.asarray(prediction)

    def set_data(self,dataset):
        self.dataset = dataset
        self.dataset.class_is_last()

    def score(self,X,y):
        y_pred = self.predict(X)
        score = accuracy_score(y, y_pred)

        return score

But when I try to evaluate the classifier with this funcion
evaluate_models_cv(sci_Model_1,X,y,10)
from sklearn.model_selection import cross_validate

def evaluate_models_cv(weka_model, X, y, cv, scoring = None):
    return_train_score = True
    n_jobs = -1

    scores = cross_validate(weka_model, X, y, cv = cv, n_jobs = n_jobs, scoring = scoring, return_train_score = return_train_score)

    scores = pd.DataFrame(scores)
    means = scores.mean(axis = 0)
    sds = scores.std(axis = 0)

    results = dict(mean = means, sd = sds)
    results = pd.DataFrame(results)

    return results

I'm getting this error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_2608/4224958314.py in <module>
----> 1 evaluate_models_cv(sci_Model_1,X,y,10)

/tmp/ipykernel_2608/3738102976.py in evaluate_models_cv(weka_model, X, y, cv, scoring)
      5     n_jobs = -1
      6
----> 7     scores = cross_validate(weka_model, X, y, cv = cv, n_jobs = n_jobs, scoring = scoring, return_train_score = return_train_score)
      8
      9     scores = pd.DataFrame(scores)

/usr/local/lib/python3.8/dist-packages/sklearn/model_selection/_validation.py in cross_validate(estimator, X, y, groups, scoring, cv, n_jobs, verbose, fit_params, pre_dispatch, return_train_score, return_estimator, error_score)
    258         scorers = scoring
    259     elif scoring is None or isinstance(scoring, str):
--> 260         scorers = check_scoring(estimator, scoring)
    261     else:
    262         scorers = _check_multimetric_scoring(estimator, scoring)

/usr/local/lib/python3.8/dist-packages/sklearn/metrics/_scorer.py in check_scoring(estimator, scoring, allow_none)
    475             return None
    476         else:
--> 477             raise TypeError(
    478                 "If no scoring is specified, the estimator passed should "
    479                 "have a 'score' method. The estimator %r does not." % estimator

TypeError: If no scoring is specified, the estimator passed should have a 'score' method. The estimator weka_classifier(classifier=AttributeSelectedClassifier:

So I tried to solve it makeing the score() function on the class, but that didn't work.
I'm doing something wrong?

A: Ok it works, I didn't extends the ClassifierMixin class like:
class weka_classifier(BaseEstimator, ClassifierMixin):


text:
Q: Create routing graph (as software objects) from roads Shapefile using pgRouting Intro: It's easy with OSM XML to run my software algorithm converting the XML to my custom software objects representing routing graph: You have ways with easy links to the (ordered) nodes constructing the segment with lat/lon.
Problem: Usually one starts with data as Shapefile, so the easy solution is to use Shape->OSM converter. I want to work directly with the Shapefiles.
Question: It's easy to import Shapefile to PostgreSql and using PostGis to query bounding boxes of the coverage based on geospatial logic. The next step is to use pgRouting in order to parse the raw Shapefile data (roads) to software objects representing the routing graph, for example in Java something like:
class Node() {
    double lat;
    double lon;
    int nodeId;
}

class Segment() {
    LinkedList byOrderNodes;  //of type class Node above
    int segmentId;
    boolean oneWay;
}

class graph() {
    ArrayList segments;  //of type Segment above
}

How to achieve this with pgRouting - What queries and functions to use?
Note - I don't mind between Python/Java/etc.

A: For pgRouting, use pgr_CreateTopology function. http://docs.pgrouting.org/2.3/en/src/topology/doc/pgr_createTopology.html#pgr-create-topology
Basic steps:
1) Load your shapefile into PostgreSQL/PostGIS with shp2pgsql or shp2pgsql-gui or ogr2ogr or any other tool like QGIS
2) Add two columns to the table source / target
ALTER TABLE your_table ADD COLUMN "source" integer;
ALTER TABLE your_table ADD COLUMN "target" integer;

3)
SELECT pgr_createTopology('your_table', 0.00001, 'geom', 'gid');

gid may be different depending on which tool you used to load the shapefile, but should be integer that is unique for the table.
0.00001 is the tolerance at which two nodes are considered the same.  This will vary depending on projection of your data.  For example for a meter projection,you may want to make this higher like 0.5 (1/2 meter)
The function will populate the source and target fields with nodes ids and also create a table your_table_vertices_pgr  which is basically like your Node table.
From there use the pgRouting routing functions.
This and many other topics are covered in our book currently in draft form - http://locatepress.com/pgrouting


text:
Q: Retrieve JSON Payload in Server Response from a Post Request with Ember Data I must be really missing something but I can't find a way to retrieve the json payload from a post request using ember data.  For example:
  var onSuccess = function(data) {
    //Want to get json payload from data
  };

  var onFail = function(data) {
    //Want to get json payload from data
  };

  // save model which sends a post request to the server
  model.save().then(onSuccess, onFail);

Any help much appreciated!

A: Ember Data automatically processes the response from a POST and inserts and/or replaces any objects with matching IDs.  Objects are extracted from the payload automatically and placed in the store.  Read about Ember Data's REST adapter and the conventions expected of your server


text:
Q: For a System Transfer funcition What is the condition that the degree of denominator and numerator will always be same?
If the impulse response begins at n=0,then is it true that the degree of denominator and numerator will always be same? How can we justify this condition?

A: Let $h[n]$ be an impulse response with $h[n]=0, \ \forall n<0$, such that $H(z)=\mathcal{Z}\{h[n]\}$ also exists.
The transfer function is $$H(z)=h[0]+h[1]z^{-1}+h[2]z^{-2}+\cdots$$
Combining the above terms, the numerator and denomerator have equal degrees. For example when $h[n]$ has $N+1$ nonzero terms:
$$H(z)=\frac{h[0]z^{N}+h[1]z^{N-1}+h[2]z^{N-2}+\cdots +h[N]}{z^N}$$


text:
Q: Windows.open automatically adds 'Index' to the url I have a button which opens a new pop up window.
HTML Code :
  <input type="button"
         id="TestRegex"
         name="TestRegex"
         value="Test Regex"
         class="btn btn-default" />

Jquery code:
   $("#TestRegex").click(function () {
            window.open("RegularExpressionTest",
                        '',
                        'height=500,
                        width=600,
                        left=-150,
                        top=10,
                        status=no,
                        toolbar=no,
                        resizable=yes,
                        scrollbars=yes');
        });

The problem is, when I click the link, it opens a new window however the link of the URL is http://localhost:00000/FileTypeDetails/Index/RegularExpressionTest.cshtml however, I wanted it to be http://localhost:00000/FileTypeDetails/RegularExpressionTest.cshtml. Index.cshtml is the page which has the button.

A: The URL of the current page is http://localhost:00000/FileTypeDetails/Index, so the browser thinks that the Index part is a folder. When you open RegularExpressionTest the browser thinks that it is a file or folder inside the Index folder.
You can use .. to get out of the "folder" Index:
window.open("../RegularExpressionTest", '', 'height=500,width=600,left=-150,top=10,status=no,toolbar=no,resizable=yes,scrollbars=yes');

A: For above problem you have to use "URL.Action" for manipulation of URL
Try following script :

window.open('@Url.Action("RegularExpressionTest", "FileTypeDetails")', '', 'height=500,width=600,left=-150,top=10,status=no,toolbar=no,resizable=yes,scrollbars=yes');


text:
Q: How to show image in stimulsoft I store image path in database and use BeforePrintEvent event to show image in stimulsoft report and specify following code in the event:
Image2.Image = Image.FromFile(my Procedure Name.path column name);

My problem:
There are many text box and an image in my report.
my store procedure return many row and every row information show correctly in every report but first row path column in query show in image for every report.(image control in all reports show one image while it show differnt image)
my query return different path for every row.
How can I resolve it?

A: Which Stimulsoft product do you use?
It's necessary to see your report to help you.
You don't need to use BeforePrint event. You could just set the Data Column property of the Image.