text:
Q: Conversion using Buffer is different from base64.fromArrayBuffer(). Why does that happen? TempId looks like this:
new Uint8Array([1, 252, 232, 40, 235, 180, 121, 67, 150, 7, 110, 99, 195, 156, 150, 82, 131, 163, 84, 209, 102, 76, 175, 209, 33, 104, 1, 251, 127, 70, 88, 178, 57, 216, 48, 202, 161, 248, 243, 170, 190, 126, 39, 111, 231, 116, 69, 133, 183, 59, 54, 1, 193, 110, 191, 48, 235, 14, 172, 162, 213, 181, 147, 83, 90])
Buffer.from(tempId).toString('base64'); returns this:
AfzoKOu0eUOWB25jw5yWUoOjVNFmTK/RIWgB+39GWLI52DDKofjzqr5+J2/ndEWFtzs2AcFuvzDrDqyi1bWTU1o=
CredId looks like this:
new Uint8Array([1, 252, 232, 40, 235, 180, 121, 67, 150, 7, 110, 99, 195, 156, 150, 82, 131, 163, 84, 209, 102, 76, 175, 209, 33, 104, 1, 251, 127, 70, 88, 178, 57, 216, 48, 202, 161, 248, 243, 170, 190, 126, 39, 111, 231, 116, 69, 133, 183, 59, 54, 1, 193, 110, 191, 48, 235, 14, 172, 162, 213, 181, 147, 83, 90])
base64.fromArrayBuffer(credId, true); returns this:
 AfzoKOu0eUOWB25jw5yWUoOjVNFmTK_RIWgB-39GWLI52DDKofjzqr5-J2_ndEWFtzs2AcFuvzDrDqyi1bWTU1o
As you can see, the token are very similar, but there are a couple of differences ('=' at the end, '/' instead of '_', and '-' instead of '+'.
Why does that happen?


text:
Q: how to add a new variable to this ajax script through post I need to be able to send a value from my PHP script with a variable called $topid that needs to send that id to getData.php script so i tried like
$(document).ready(function(){

    // Load more data
    $('.load-more').click(function(){
        var topid = Number($('#topid').val());
        var row = Number($('#row').val());
        var allcount = Number($('#all').val());
        row = row + 3;

        if(row <= allcount){
            $("#row").val(row);

            $.ajax({
                url: 'getData.php',
                type: 'post',
                data: {row:row},
                beforeSend:function(){
                    $(".load-more").text("Loading...");
                },
                success: function(response){

                    // Setting little delay while displaying new content
                    setTimeout(function() {
                        // appending posts after last post with class="post"
                        $(".post:last").after(response).show().fadeIn("slow");

                        var rowno = row + 3;

                        // checking row value is greater than allcount or not
                        if(rowno > allcount){

                            // Change the text and background
                            $('.load-more').text("Hide");
                            $('.load-more').css("background","darkorchid");
                        }else{
                            $(".load-more").text("Load more");
                        }
                    }, 2000);

            }
        });
    }else{
        $('.load-more').text("Loading...");

        // Setting little delay while removing contents
        setTimeout(function() {

            // When row is greater than allcount then remove all class='post' element after 3 element
            $('.post:nth-child(3)').nextAll('.post').remove().fadeIn("slow");

            // Reset the value of row
            $("#row").val(0);

            // Change the text and background
            $('.load-more').text("Load more");
            $('.load-more').css("background","#15a9ce");

        }, 2000);

    }

});

});
But somehow it does not seem to be working all I need is the id gets sent to the getData.php script and I then get it through post like $topid = $_POST['topid '];

A: if you need to sent topid to the getData change
data: {row:row}

into something like
data: {topid : topid}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert Screen Point to SP 4326 I am using Esri for .NET. I trap screen coordinates by mouse click using ScreenToLocation function. How can I convert this mappoint to SP of 4326?
MapPoint mapPoint = Mapview.ScreenToLocation(screenPoint);

My mappoint is not where I clicked on the map. I get the coordinates as 5423799.44921864,-267641.097678069

A: Are you using the ArcGIS Runtime for windows store or the runtime for wpf?
Anyway, you are getting a WebMercator point. In order to convert between spatial references you need to use the project method of the GeometryService on wpf or the GeometryEngine on the winstore
Or, if you prefer to do the conversion WebMercator (102100/3857) to WGS84 (4326) synchronously by code, you can do with:
private const double R_MAJOR = 6378137.0;
private const double R_MINOR = 6356752.3142;

public MapPoint PointToWGS84(double x, double y)
{
    double originShift = 2 * Math.PI * R_MAJOR / 2.0;
    double mx = (x / originShift) * 180.0;
    double my = (y / originShift) * 180.0;
    my = (180 / Math.PI) * (2 * Math.Atan(Math.Exp(my * Math.PI / 180.0)) - Math.PI / 2.0);
    return new MapPoint(mx, my, new SpatialReference(WGS84));
}

To go from WGS84 to WM
public MapPoint PointToWM(double x, double y)
{
    double originShift = 2 * Math.PI * R_MAJOR / 2.0;
    double mx = x * originShift / 180.0;
    double my = Math.Log(Math.Tan((90.0 + y) * Math.PI / 360.0)) / (Math.PI / 180.0);
    my = my * originShift / 180.0;
    return new MapPoint(mx, my, new SpatialReference(102100));
}

please note that this code works ONLY for WM to/from WGS. For other conversions you must always use the GeometryService


text:
Q: eslint ignore pattern not works I want to run lint check all the file *.js without node_modules
Here my command: "lint": "eslint **/*.js",, My folder structure look like: app > module_name > module.js but in the app folder still having some files common like helpers.js server.js and I also want to check them.
In .eslint config I added "ignorePatterns": "node_modules" and tried added a file .eslintignore and add node_modules but it's not working.
When I run npm run lint it always throw error:

Oops! Something went wrong! :(

ESLint: 7.32.0

You are linting "node_modules/bignumber.js", but all of the files matching the glob pattern "node_modules/bignumber.js" are ignored.

If you don't want to lint these files, remove the pattern "node_modules/bignumber.js" from the list of arguments passed to ESLint.

If you do want to lint these files, try the following solutions:

* Check your .eslintignore file, or the eslintIgnore property in package.json, to ensure that the files are not configured to be ignored.
* Explicitly list the files from this glob that you'd like to lint on the command-line, rather than providing a glob as an argument.

A: You could add node_modules/ in your .eslintignore file, and update the package.json file with script: "lint": "eslint --ext .js app/", before running npm run lint.

A: You could add node_modules/ in your .eslintignore file, and update the package.json file with script:
if u r using ubuntu/linux
"lint": "eslint '**/*.js'"

if project structure like these folder/file.js
if u r using windows
"lint": "eslint **/*.js"

if project structure like these folder/file.js


text:
Q: Update variable value for each iteration inside a promise I want to update the value of index. In this scenario there is job card with multiple services in it and every service have multiple employees in it. So I want to create a multidimensional object with services an array inside job card object and employees an array inside each service but my index variable is not updating.
Here is the code
await Promise.all(
  services.map(async (service) => {
    const labor = await new Promise((resolve, reject) => {
      connection.query(getLabor, [service?.labors_id], (err, result) => {
        resolve(result);
      });
    });
    rest.services.push(labor[0]);
    laborEmployee = service?.employees_id?.split(",");

    let index = -1;
    index = index + 1;
    rest.services[index].employees = [];
    console.log(index);

    await Promise.all(
      laborEmployee.map(async (emp) => {
        const e = await new Promise(async (resolve, reject) => {
          connection.query(getEmployee, [emp], (err, result) => {
            if (err) throw err;
            rest.services[index]?.employees?.push(result[0]);
            resolve(result);
          });
        });
      })
    );
  })
);

But my index variable remains the same. Currently there are two iterations so index should be 0 and 1 but it remains 0 and 0.

A: I'm not 100% sure just looking at the code, but my hunch would be to try defining the index variable outside of the scope of the initial await Promise.all as the way you have it currently, a new index is being defined for each Promise.


text:
Q: router-flux navbar button this.function is not a function I implemented in my router-flux nav bar a right button like this:
  static renderRightButton = (props) => {
          return (
              <TouchableOpacity onPress={() => this.getCurrentPosition()} style={{bottom: 4, right: 8}}>
                  <Icon name='ios-locate-outline' style={{color: 'white'}} />
              </TouchableOpacity>
          );
    }

But If I click on my button I get this error :this.5.getCurrentPosition is not a function
I declare my function in the constructor with
this.getCurrentPosition = this.getCurrentPosition.bind(this)

A: You're using a static method, which means you don't have access to this, which only works for instances.
So you can either
1) remove static
renderRightButton = () => {
          return (
              <TouchableOpacity onPress={() => this.getCurrentPosition()} style={{bottom: 4, right: 8}}>
                  <Icon name='ios-locate-outline' style={{color: 'white'}} />
              </TouchableOpacity>
          );
    }

2) or pass getCurrentPosition to the render method as a parameter.
static renderRightButton = (props, getCurrentPosition) => {
          return (
              <TouchableOpacity onPress={getCurrentPosition} style={{bottom: 4, right: 8}}>
                  <Icon name='ios-locate-outline' style={{color: 'white'}} />
              </TouchableOpacity>
          );
    }

A: So we have had the same problem using RNRF, our solution is to leverage the Actions.refresh API.
For your case, you can do like this:
class AddEventPage extends Component {
  constructor(props) {
    this.getCurrentPosition = this.getCurrentPosition.bind(this);
    this.renderRightButton = this.renderRightButton.bind(this);
  }
  componentDidMount() {
    Actions.refresh({ renderRightButton: this.renderRightButton });
  }

  renderRightButton = (props) => {
    return (
      <TouchableOpacity onPress={() => this.getCurrentPosition()} style={{bottom: 4, right: 8}}>
        <Icon name='ios-locate-outline' style={{color: 'white'}} />
      </TouchableOpacity>
    );
  }

  getCurrentPosition() {
    //Your implementation
  }
}

A: Assuming that you are using jsx file the return can take html like format but you can't structure it that way. Your transpiler didn't pass this.getCurrentPosition() expression. Take a look at your minified file and search for that.
This is how you embed expressions in jsx

function formatName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = {
  firstName: 'test',
  lastName: 'tesjgg'
};

const element = (

    Hello, {formatName(user)}!

);

ReactDOM.render(
  element,
  document.getElementById('root')
);

A: because renderRightButton static you can try:
import { Actions } from 'react-native-router-flux'
constructor (props) {
  this.handleSave = this.handleSave.bind(this)
}
renderRightButton = () => {
return (
  <TouchableOpacity onPress={this.handleSave}>
    <Text>Save button</Text>
  </TouchableOpacity>
)
}
async componentDidMount () {
  Actions.refresh({renderRightButton: this.renderRightButton})
}
async handleSave () {
  console.log('save action')
}


text:
Q: Cassandra with react, net.socket error I am a  newwbie to react and cassandra. I am just trying to connect to the cassandra db by using "npm i cassandra-driver".
I am having a main.js file where I used the cassandra driver code.
Main.js
import 'babel-polyfill';
import 'whatwg-fetch';

import React from 'react';
import ReactDOM from 'react-dom';
import FastClick from 'fastclick';
import { Provider } from 'react-redux';

import store from './core/store';
import router from './core/router';
import history from './core/history';

const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['127.0.0.1'], keyspace: 'excelsior'});
console.log("client---->",client);
const query = 'SELECT * FROM playlists';

client.execute(query, [], function(err, result) {
    console.log("err----->",err);
    console.log("result----->",result);
  assert.ifError(err);
  //console.log('got user profile with email ' + result.rows[0].email);
});

let routes = require('./routes.json'); // Loaded with utils/routes-loader.js
const container = document.getElementById('container');

function renderComponent(component) {
  ReactDOM.render(<Provider store={store}>{component}</Provider>, container);
}

// Find and render a web page matching the current URL path,
// if such page is not found then render an error page (see routes.json, core/router.js)
function render(location) {
  router.resolve(routes, location)
    .then(renderComponent)
    .catch(error => router.resolve(routes, { ...location, error }).then(renderComponent));
}
 continued code ......

I am getting the client console, But After that i am getting an error like
connection.js:122 Uncaught TypeError: net.Socket is not a constructor(…)

Am I missing something here. or is this piece of code should be written anywhere else. ?
Thanks

A: The cassandra-driver is meant to be run on a Node.js server, not in the client (i.e. browser).
So, you'll need to create a Node.js server of some kind for your client code (using React, Redux, or whatever) to talk to. For example, in a typical web application setup, your client code in the browser will:

*

*make an HTTP call to the server

*the server will process that call and use the cassandra-driver to go get the appropriate data for that call

*then send the appropriate data back to the client in the HTTP response

This is a pretty gross simplification of how things could be setup, but this type of communication is common for many web applications, regardless of whether they're using Cassandra, Postgres, or whatever database on the server.


text:
Q: FindRoot gives the wrong root, but with no warning or error message I am solving an equation set using FindRoot,  as shown in the codes below.
c = 2.99792458*10^8; (*light speed*)

no[λ_] := √(2.240921 + (2.246956 (λ*10^-3)^2)/((λ*10^-3)^2 - 126.9207281) + 0.009676/((λ*10^-3)^2 - 0.01562025)); (*refractive index for o ray*)

ne[λ_] := √(2.126019 + ( 0.784404 (λ*10^-3)^2)/((λ*10^-3)^2 - 123.4034379) +  0.008578/((λ*10^-3)^2 - 0.01199134)); (*refractive index for e ray*)

ne2[θ_, λ_] := Sqrt[1/((Cos[θ])^2/(no[λ])^2 + (Sin[θ])^2/(ne[λ])^2)] ;  (*refractive index at angle θ*)

Vo[λ_] = c/( no[λ] - λ D[no[λ], λ]); (*group velocity for o ray*)

Ve[λ_] = c/( ne[λ] - λ D[ ne[λ], λ]);   (*group velocity for e ray*)

Ve2[θ_, λ_] = c/(ne2[θ, λ] - λ D[ ne2[θ, λ], λ]);    (*group velocity at angle θ*)

λi[λp_, λs_] := 1/(1/λp - 1/λs);(*idler waevelenth*)

λp = 520;
root = FindRoot[{no[λs]/ λs + ne2[θ, λi[λp, λs]]/λi[λp, λs] == ne2[θ, λp]/λp,  1/Ve2[θ, λp] == 1/Vo[λs]}, {{θ, 1}, {λs, 800}}]

FindRoot gives the following root  with no warning.
    {θ -> 0.772903, λs -> 794.375}

When no warning or error message appears, the root should be correct. But when it is verified in the plot, the root is false.
{no[λs]/ λs + ne2[θ, λi[λp, λs]]/λi[λp, λs] == ne2[θ, λp]/λp, 1/Ve2[θ, λp] == 1/Vo[λs]} /. root

fig1 = ContourPlot[  no[λs]/ λs + ne2[θ, λi[λp, λs]]/λi[λp, λs] == ne2[θ, λp]/λp, {λs, 350, 2000}, {θ, 0.1, 1.5}, ContourStyle -> {Red}, ImageSize -> {250, 200}];
fig2 = ContourPlot[ 1/Ve2[θ, λp] == 1/Vo[λs], {λs, 350, 2000}, {θ, 0.1, 1.6}, ContourStyle -> {Blue}];
Show[fig1, fig2]

The result is

My question is : In Mathematica, when no warning appears, the root should be
correct? Is this believe true?
P.S.
If I change    λp = 500, we can obtain a true root, also with no warning.

A: Avoiding machine precision shows that there is no intersection of the two curves for λp = 520. Consequently, FindRoot finds a point near where the two curves are closest.
c = 299792458;(*light speed*)

no[λ_] := √(2.240921 + (2.246956 (λ*10^-3)^2)/((λ*10^-3)^2 - 126.9207281) +
       0.009676/((λ*10^-3)^2 - 0.01562025)) //
    Rationalize[#, 0] & // Simplify // Evaluate;(*refractive index for o ray*)

ne[λ_] := √(2.126019 + (0.784404 (λ*10^-3)^2)/((λ*10^-3)^2 - 123.4034379) +
       0.008578/((λ*10^-3)^2 - 0.01199134)) //
    Rationalize[#, 0] & // Simplify // Evaluate;(*refractive index for e ray*)

ne2[θ_, λ_] := Sqrt[1/(Cos[θ]^2/no[λ]^2 +
     Sin[θ]^2/ne[λ]^2)];(*refractive index at angle θ*)
Vo[λ_] = c/(no[λ] - λ D[no[λ], λ]);(*group velocity for o ray*)
Ve[λ_] = c/(ne[λ] - λ D[ne[λ], λ]);(*group velocity for e ray*)
Ve2[θ_, λ_] = c/(ne2[θ, λ] - λ D[ne2[θ, λ], λ]);(*group velocity at angle θ*)
λi[λp_, λs_] := 1/(1/λp - 1/λs);(*idler wavelength*)

λp = 520;

eqns = {
    no[λs]/λs + ne2[θ, λi[λp, λs]]/λi[λp, λs] == ne2[θ, λp]/λp,
    1/Ve2[θ, λp] == 1/Vo[λs]} //
   Simplify;

root = FindRoot[eqns, {{θ, 1}, {λs, 800}},
  WorkingPrecision -> 16,
  MaxIterations -> 1000]

(* {θ -> 0.7729018777020580, λs -> 794.3739989651066} *)

eqns /. root

(* {False, False} *)

fig1 = ContourPlot[
   no[λs]/λs + ne2[θ, λi[λp, λs]]/λi[λp, λs] == ne2[θ, λp]/λp,
   {λs, 350, 1500}, {θ, 1/10, 6/5},
   ContourStyle -> Red,
   WorkingPrecision -> 16,
   MaxRecursion -> 5];
fig2 = ContourPlot[
   1/Ve2[θ, λp] == 1/Vo[λs],
   {λs, 350, 2000}, {θ, 1/10, 8/5},
   ContourStyle -> Blue,
   WorkingPrecision -> 16];
Show[fig1, fig2,
 Graphics[{AbsolutePointSize[4], Point[{λs, θ} /. root]}],
 ImageSize -> {250, 200}]

For λp=500, there are two roots.
λp = 500;

eqns2 = {
  no[λs]/λs + ne2[θ, λi[λp, λs]]/λi[λp, λs] == ne2[θ, λp]/λp,
    1/Ve2[θ, λp] == 1/Vo[λs]} // Simplify;

roots = FindRoot[eqns2, {{θ, #[[1]]}, {λs, #[[2]]}},
    WorkingPrecision -> 16,
    MaxIterations -> 1000] & /@
  {{7/10, 700}, {9/10, 900}}

(* {{θ -> 0.7287476137541260, λs ->
   693.9615475238889}, {θ -> 0.8693491960341734, λs ->
   868.7277923184990}} *)

eqns2 /. roots

(* {{True, True}, {True, True}} *)

fig3 = ContourPlot[
   no[λs]/λs + ne2[θ, λi[λp, λs]]/λi[λp, λs] == ne2[θ, λp]/λp,
   {λs, 350, 1500}, {θ, 1/10, 6/5},
   ContourStyle -> Red,
   WorkingPrecision -> 16,
   MaxRecursion -> 5];
fig4 = ContourPlot[1/Ve2[θ, λp] == 1/Vo[λs],
   {λs, 350, 2000}, {θ, 1/10, 8/5},
   ContourStyle -> Blue,
   WorkingPrecision -> 16];
Show[fig3, fig4,
 Graphics[{AbsolutePointSize[4], Point[{λs, θ} /. roots]}],
 ImageSize -> {250, 200}]


text:
Q: Using reflection to get each instance of XmlElementAttribute for a single property I'm trying to list the possible types that Item could contain. However I am stuck in that I can't call Item.GetType() to loop through its Attributes as this would just return the attributes of the type that it already contained.
I have tried TypeDescriptor.GetProperties(...) but the Attributes container only contains one instance of XmlElementAttribute which is the last one applied to the property (WindowTemplate in this case)
This must be trivial but I cannot find any solution to my problem online.
    [System.Xml.Serialization.XmlElementAttribute("ChildTemplate", typeof(ChildTmpl), Order = 1)]
    [System.Xml.Serialization.XmlElementAttribute("WindowTmeplate", typeof(WindowTmpl), Order = 1)]
    public object Item
    {
        get
        {
            return this.itemField;
        }
        set
        {
            this.itemField = value;
        }
    }

A: You can't use TypeDescriptor for this, as System.ComponentModel always collapses attributes. You must use PropertyInfo and Attribute.GetCustomAttributes(property, attributeType):
var property = typeof (Program).GetProperty("Item");
Attribute[] attribs = Attribute.GetCustomAttributes(
       property, typeof (XmlElementAttribute));

the array will actually be a XmlElementAttribute[] if it makes it easier:
XmlElementAttribute[] attribs = (XmlElementAttribute[])
     Attribute.GetCustomAttributes(property, typeof (XmlElementAttribute));


text:
Q: Vertex cover of minimum weight in a tree with weighted vertices Given a tree with undirected edges, where the the weight of a vertex is its degree, find the vertex cover of minimum weight.
Here's what I think:
Since the vertex cover will need to include enough vertices to cover all edges, that means that regardless of the vertices in the cover, the sum of the weights of all the vertices will be the same (equal to the number of edges). Therefore, we don't need any special algorithm to find the answer, we only need to find the minimum size vertex cover (cover with minimum vertices).
Is this correct, or am I missing something obvious?

A:
Is this correct, or am I missing something obvious?

Two vertices having the same edge; e.g.,...
A -- B -- C

Weights:
B = 2;
A = 1;
C = 1

{ A, C } and { B } are both weighted minimal vertex covers by your definition.
Only { B } is a standard minimal vertex cover.
EDIT:... a better example showing a different reason:
A -- B -- C -- D

Weights:
B = 2;
C = 2;
A = 1;
D = 1

{ A, C }, { B, D }, { B, C } are all standard minimal vertex covers.
Only { A, C } and { B, D } are weighted minimal vertex covers by your definition. Intuitively, this is because the { B, C } vertex cover counts the B -- C edge twice.

The first counter example disproves that all weighted MVCs (as per your definition) are standard MVCs. The second counter example disproves that all standard MVCs are weighted MVCs.
After some thought... you are correct in that the weighted MVC for a tree is any VC with a cost equal to the number of edges.
Finding a weighted MVC is actually quite simple. If you draw the tree out, and pick all the vertexes from every second level (doesn't matter if you start from the first or second level), you end up with a valid weighted MVC by your definition (since all edges are covered, no edge is counted twice).
...more generally, the set of all weighted MVCs is the set of all VCs not containing neighbours. For example, in a tree where no child is a parent, the set of leaf nodes is also a valid weighted MVC.


text:
Q: vCenter login: An error occurred when processing the metadata during vCenter Single Sign-On setup Recently, I took over management of some servers, and I can no longer connect to our vCenter to manage our VMs. We don't have SSO and as far as I know, we only have one account "admin".
When I go on the web using server name, I get error as below:

A server error occurred.
  [400] An error occurred while sending an authentication request to the vCenter Single Sign-On server - An error occurred when processing the metadata during vCenter Single Sign-On setup - null.

Check the vSphere Web Client server logs for details"
When use IP of the sever, I get following error:

[400] An error occurred while sending a logout request to the vCenter Single Sign-On server - An error occurred when processing the metadata during vCenter Single Sign-On setup - null. Back to login screen

I see a 90 policy enforced, however nothing I do seems to resolve the issue.
Solutions i have tried so far and did not help:
restarting the server, reset password, I have check the logs and nothing to be found of recent. last logs were from 2019. the problem started monday 8/0602020 etc.

A: Probably your problem is caused by the STS certificate and other certificate expired, look at this VMware KB:
https://kb.vmware.com/s/article/76719


text:
Q: Create and send PKCS10 in Windows 10 app I am investigating how to create a PKCS#10 certificate signing request (CSR), send it to a Certificate Autority (CA), and create an X.509 client certificate based on the response from the CA. I want to do this in a Windows 10 application (so, an app built on UWP). Can i do this without an extra server to run the "CertCli 1.0 Type Library"?
The only info I've found is this: MSDN Article
It's for Windows 8.1, and it says that I need to have a server "between" the application and the CA, in order to send the CSR to the CA and create the actual certificate. Then I send this certificate back to the application. Deploying and running an extra server simply to host an API seems wasteful, so I'm trying to find another way.

*

*Is this still necessary in Windows 10?

*Could I package the "CertCli 1.0 Type Library" as a DLL or something along with my application?

*Are there open source alternatives (that will run in a UWP app) that can be used to handle the certificate and CSR instead?


text:
Q: Best way to connect to MongoDB using Node.js I've read a few guides on how to use Mongo with Node, and they all seem to connect to databases differently. One particular way that worked well for me was:
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
  if(err) { return console.dir(err); }

  db.createCollection('users', function(err, collection) {});

  //Do all server/database operations in here

});

However, this seems inefficient/odd to me, I would have to reconnect to the database every time there is an app.get(), like for making a new user or retrieving information.
Another way that seems better suited to me is
var mongoose = require("mongoose")
var db = mongoose.connect("localhost:27107/users");

db.createCollection('users', function(err, collection) {});

I've seen several sites do something along these lines, but I personally can't get the above to work. I keep getting the error TypeError: db.createCollection is not a function server-side. So, my question is why the above code doesn't work, if the first code is a good alternative, and if there are any other ways to do this.

A: You can use a global variable to hold the connection (e.g. db), for example:
var db = null // global variable to hold the connection

MongoClient.connect('mongodb://localhost:27017/', function(err, client) {
    if(err) { console.error(err) }
    db = client.db('test') // once connected, assign the connection to the global variable
})

app.get('/', function(req, res) {
    db.collection('test').find({}).toArray(function(err, docs) {
        if(err) { console.error(err) }
        res.send(JSON.stringify(docs))
    })
})

Or, if you prefer, you can also use the Promise object that is returned by MongoClient if it is called without a callback argument:
var conn = MongoClient.connect('mongodb://localhost:27017/') // returns a Promise

app.get('/', function(req, res) {
    conn.then(client=> client.db('test').collection('test').find({}).toArray(function(err, docs) {
        if(err) { console.error(err) }
        res.send(JSON.stringify(docs))
    }))
})

Please note that I used the ES6 fat arrow function definition in the second example.
You are absolutely correct that you should not call MongoClient every time. Using a global variable or Promises allows the MongoDB node.js driver to create a connection pool, which achieves at least two good things:

*

*Connections are reused in a pool, so there is no multiple expensive setup/teardown process for the lifetime of your application. You connect once, and let the driver take care of the rest for you.

*You can control the amount of connection your application makes into the database, by limiting the size of the connection pool.

Edit 2018-08-24: The MongoClient.connect() method in node.js driver version 3.0 and newer returns a client object instead of a database object. The examples above were modified to keep it up to date with the latest node.js driver version.

A: I've written a tutorial on how to reuse mongodb connection in express. You can see here. Basically, it's a simple module, which you can use with expressjs like that:
var connection = require('./dbconnection');
// url and optional config.
app.use(connection(app, 'mongourl', {});

And here's the code for the connection:
module.exports = function(app, uri, opts) {
    if (typeof uri !== 'string') {
        throw new TypeError('Error: Unexpected mongodb connection url');
    }

    opts = opts || {};
    var property = opts.property || 'db';

    var connection;
    return function expressMongoDb(req, res, next) {
        if (!connection) {
            connection = MongoClient.connect(uri, opts);
        }

        connection
            .then(function (db) {
                req[property] = db;
                app.set('mongodb', db);
                next();
            })
            .catch(function (err) {
                connection = undefined;
                next(err);
            });
    };
};

A: You could use it this way:
that's server.js file:
import path from 'path'
import express from 'express'
import bodyParser from 'body-parser'
import morgan from 'morgan'
import db from './server/database'
import routes from './server/routes'

import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import webpackConfig from './config/webpack'
const app = express()
const port = process.env.PORT || process.env.NODE_PORT
const compiler = webpack(webpackConfig)

db(λ => {
  app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath }))
  app.use(webpackHotMiddleware(compiler))
  app.use(morgan('dev'))
  app.use(bodyParser.json({ limit: '20mb' }))
  app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }))
  app.use('/static', express.static('static'));
  //app.use('/api', jwt)
  app.use('/api', routes())

  app.set('json spaces', 2)

  app.get('*', function(request, response) {
    response.sendFile(path.resolve(__dirname, 'index.html'))
  })

  app.listen(port, (error) => {
    if (error) {
      console.error(error)
      throw error
    } else {
      console.info(`==>   Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`)
    }
  })
})

server/database.js
import mongoose from 'mongoose'

export default callback => {
  const { MONGO_URL, MONGO_PORT, MONGO_DB } = process.env

  mongoose.connect(`mongodb://${MONGO_URL}:${MONGO_PORT}/${MONGO_DB}`, error => {
    if (error) {
      console.error('Please make sure your MongoDB configuration is correct and that service is running')
      throw error
    }
  })

  callback()
}

Then you'll have to define your mongoose models, for instance:
import mongoose, { Schema } from 'mongoose'

const ideaSchema = new Schema({
  title: {
    type: String,
    required: true
  },
  slug: {
    type: String,
    required: true,
    unique: true
  },
  description: {
    type: String,
    required: true
  }
})

export default mongoose.model('Idea', ideaSchema)

And just use controllers this way:
import HttpStatus from 'http-status-codes'
import mongoose from 'mongoose'
import sanitize from 'sanitize-html'
import slug from 'slug'
import Idea from '../models/idea'

const findAllIdeas = (req, res) => {
  Idea.find()
    .select('user title slug createdAt updatedAt')
    .populate({
      path: 'user',
      select: 'firstName lastName'
    })
    .then(data => res.status(HttpStatus.OK).json(data))
    .catch(error => res.status(HttpStatus.BAD_REQUEST).json(error))
}

export default { findAllIdeas, findIdeaBySlug, createIdea, addComment }

You will not have to connect to mongoDB for each get request.
So your route will look like that. Quite straightforward:
import { Router } from 'express'
import controller from '../controllers/idea'

const router = Router()

router.route('/')
  .get(controller.findAllIdeas)
  .post(controller.createIdea)

router.route('/:slug')
  .get(controller.findIdeaBySlug)

router.route('/comment')
  .post(controller.addComment)

export default router

A: My go-to code is as follows:
mongoose.connect(YOUR_URL ,function(err) {
  if (err) {
    console.log(err);
  }else{
    console.log("Connected to DB");
  }
});

Also try connecting to just localhost:27107, that may be your problem.


text:
Q: Sticky animation not working properly in Safari/Chrome If you test this in Firefox, whether by scrolling or clicking the text box, everything works fine, but in the other browsers I've listed the text box jumps to the bottom before the animation starts.
Not sure what's causing this to happen or how to fix it, any ideas?
http://coreytegeler.com/gl/
function stickyStuff(){
var half_height = $(window).height()/2+8;
$('#check1').sticky({
    'offset'  : half_height,
    'mode'   : 'animate',
    'speed' : 500,
    'onStick' : function() {
    $('#front-title-wrap').animate({ 'top': '50px' });
    }
});
$('#check2').sticky({
    'offset'  : 55,
    'onStick' : function() {
    $('#front-nav-wrapper').css({'position' : 'fixed','top': '55px', 'opacity' : '1' });
    }
});

A: Not sure it causes the problem, you are including the same sticky js file twice. normal version and min version.
Remove one and test again?
Your script
<script type="text/javascript" language="javascript" src="http://coreytegeler.com/gl/js/jquery.sticky.js"></script>
<script type="text/javascript" language="javascript" src="http://coreytegeler.com/gl/js/jquery.sticky.min.js"></script>


text:
Q: Increasing memory of Play for Scala/Activator ~run I'm running Play for Scala, and need to increase the heap/memory size as it runs out of memory when compiling.
I see the following in activator.bat:
rem TODO Check if there are existing mem settings in JAVA_OPTS/CFG_OPTS and use those instead of the below
for /f "delims=. tokens=1-3" %%v in ("%JAVA_VERSION%") do (
    set MAJOR=%%v
    set MINOR=%%w
    set BUILD=%%x

    set META_SIZE=-XX:MetaspaceSize=64M -XX:MaxMetaspaceSize=256M
    if "!MINOR!" LSS "8" (
      set META_SIZE=-XX:PermSize=64M -XX:MaxPermSize=256M
    )

    set MEM_OPTS=!META_SIZE!
 )

What is MAJOR, MINOR? Which one should I change? How to verify that Play is actually allocating the extra memory?

A: You don't have to modify activator.bat to increase the memory. Just set anyone of these environment variables
SBT_OPTS
ACTIVATOR_OPTS
JAVA_OPTS

How to set heap size in play/activator?
Once your play application is running, run jconsole (its in the bin directory of your jdk) and monitor the heap size using that.
http://karunsubramanian.com/java/5-not-so-easy-ways-to-monitor-the-heap-usage-of-your-java-application/


text:
Q: How to perform a transformation on a number so that it is between a high and low value? This is probably very simple for some of you, but I can't for the life of me get something that works reliably. Given any positive number, $x$, and a positive high and low value $(h, l)$ what kind of functions $f$ are there such that $l\leq f(x)\leq h$?

A: I guess what you want is actually bijection between $(0,\infty)$ and $(l,h)$. Here's a possible way. For $x\in (0,\infty)$, Clearly $\frac{\arctan x}{\pi/2}(h-l)+l\in (l,h)$ is a bijection.

A: As an easier-to-compute alternative to caozhu's arctan solution:
$$ x\mapsto h - \frac{h-l}{x+1} $$

A: Say $l=0, h=1$ then $0\le \sin^2(x)\le 1$.


text:
Q: Ionic 2 public variable and internal function I'm having an issue with Ionic 2 especially with angular. My problem is that i have a variable named "isConnected" and when I want to access from an internal function of a function, I can't. It says can't define proprety of undefined. How do I access to my variable isConnected from an internal function? I tried with this :    BleProvider.prototype.isConnected but it's not working. Someone can explain to me how this works please?
export class BleProvider {

 public isConnected = false;
 public mDevice;

 constructor(public http: Http) {}

 connectToDevice(device){
  console.log('Connecting to device...');

  this.mDevice = device;
  setTimeout(
   ble.connectToDevice(
    device,
    onConnected,
    onDisconnected,
    onConnectError),
   500);

  function onConnected(device) {
    console.log("Connected to device: " + device.name);
    this.isConnected = true;
    console.log("isConnected variable status: " + this.isConnected);
  }
  function onDisconnected(device) {
    console.log('Disconnected from device: ' + device.name);
  }
  function onConnectError(error) {
    console.log('Connect error: ' + error);
  }
}

A: You should use arrow functions, like this:
export class BleProvider {

    public isConnected = false;
    public mDevice;

    constructor(public http: Http) { }

    connectToDevice(device) {
        console.log('Connecting to device...');

        this.mDevice = device;

        // Create the callbacks by using arrow functions () => {...}
        let onConnected = (device) => {
                console.log("Connected to device: " + device.name);
                this.isConnected = true;
                console.log("isConnected variable status: " + this.isConnected);
            },
            onDisconnected = (device) => {
                console.log('Disconnected from device: ' + device.name);
            },
            onConnectError = (error) => {
                console.log('Connect error: ' + error);
            }

        // You can also use an arrow function in the setTimeout! :)
        setTimeout(() => {
            ble.connectToDevice(device, onConnected, onDisconnected, onConnectError);
        }, 500);

    }
}

When using a regular function, the this keyword references the function itself, but when using arrow functions, the this property is not overwritten and still references the component instance (where you defined the isConnected property).


text:
Q: Combine two facet_wrap extensions (facet_rep_wrap and facet_wrap_paginate) I have found 2 useful ggplot2 extensions:

*

*lemon::facet_rep_wrap() repeats axis lines and labels across all facet panels

*ggforce::facet_wrap_paginate() splits facet panels over multiple plots

Now, I would like to apply both extensions in the same plot (repeat axis labels and split over multiple plots)
Example:
library(ggplot2)

p <- ggplot(data = mpg) +
  geom_point(aes(x = cty, y = hwy))

## Default
p + facet_wrap(~ manufacturer)
## Repeat x-axis labels
p + lemon::facet_rep_wrap(~ manufacturer, repeat.tick.labels = "x")
## Split over multiple plots
p + ggforce::facet_wrap_paginate(~ manufacturer, nrow = 2, ncol = 2, page = 1)

How can I combine facet_rep_wrap and facet_wrap_paginate?
Internally, they call ggproto(NULL, FacetWrapRepeatLabels, ...) and ggproto(NULL, FacetWrapPaginate, ...), respectively. Can I combine the two objects FacetWrapRepeatLabels and FacetWrapPaginate? How can I do this?


text:
Q: GWT: Populating a page from datastore using RPC is too slow Is there a way to speed up the population of a page with GWT's UI elements which are generated from data loaded from the datastore? Can I avoid making the unnecessary RPC call when the page is loaded?
More details about the problem I am experiencing: There is a page on which I generate a table with names and buttons for a list of entities loaded from the datastore. There is an EntryPoint for the page and in its onModuleLoad() I do something like this:
final FlexTable table = new FlexTable();

rpcAsyncService.getAllCandidates(new AsyncCallback<List<Candidate>>() {
    public void onSuccess(List<Candidate> candidates) {
       int row = 0;
       for (Candidate person : candidates) {
          table.setText(row, 0, person.getName());
          table.setWidget(row, 1, new ToggleButton("Yes"));
          table.setWidget(row, 2, new ToggleButton("No"));
          row++;
       }
    }
    ...
});

This works, but takes more than 30 seconds to load the page with buttons for 300 candidates. This is unacceptable.
The app is running on Google App Engine and using the app engine's datastore.

A: You could do a lot of things, I will just list them in order that will give you the best impact.

*

*FlexTable is not meant for 300 rows. Since your table is so simple, you should consider generating the HTML by hand, and then using simple HTML widget. Also, 300 rows is a lot of information - consider using pagination. The DynaTable sample app shows you how to do this.

*It looks like you are using one GWT module per page. That is the wrong approach to GWT. Loading a GWT module has some non-trivial cost. To understand what I mean, compare browser refresh on gmail v/s the refresh link that gmail provides. That is the same cost you pay when every page in your website has a distinct GWT module.

*If the list of candidates is needed across views, you can send it along with the HTML as a JSON object, and then use the Dictionary class in GWT to read it. This saves you the RPC call that you are making. This approach is only recommended if the data is going to be useful across multiple views/screens (like logged in users info)

*Check how long your RPC method call is taking. You can enable stats in GWT to figure out where your application is taking time.

*You can also run Speed Tracer to identify where the bottleneck is. This is last only because it is obvious FlexTable is performing a lot of DOM manipulations. In general, if you don't know where to start, Speed Tracer is a great tool.

A: The significant thing here is how you're retrieving the list of candidates, which you haven't shown. 30 seconds is extremely high, and it's unlikely that it's due to the datastore alone.
Have you tried using appstats to profile your app?

A: Like sri suggested - pagination is easiest and (I think) best solution (along with switching to Grid or just <table>). But in case you wanted for some reason to show/render many rows at once, the GWT Incubator project has a nice wiki page about it - along with some benchmarks showing how FlexTable sucks at large row count. Check out their other tables too ;)

A: Your problem is that everytime you add something to the FlexTable it has to re-render the whole page and repaint. Try creating a new FlexTable, populating it, when it is fully populated, get rid of the old one and put the new one there.


text:
Q: if $x_{1},x_{2} $ is $nx-x^n=a$ two roots, show that $|x_{1}-x_{2}|<\dfrac{a}{1-n}+2$
Assmue that $n$ be postive integers,and $a$is real number,and the equation $$nx-x^n=a$$ has postive real roots $x_{1},x_{2}$,show that
  $$|x_{1}-x_{2}|<\dfrac{a}{1-n}+2$$

By condition, I showed that
$$(x_{1}-x_{2})[n-(x^{n-1}_{1}+x^{n-2}_{1}x_{2}+\cdots+x^{n-1}_{2})]=0$$
But I don't know what to do then. Please help, Thanks.

A: Let's study the function $f(x)=nx-x^n$ for $x>0$. $f'(x)=n(1-x^{n-1})$ so there is a global maximum in $1$. The function is monotonic increasing in $[0,1]$ and decreasing in $[1,\infty]$. The function attains twice the same value $a$ if and only if $a\in [0,n-1]$, that is $x\in [0,\sqrt[n-1]{n}]$. So for any such $x_1,x_2$ we have in fact $$|x_1-x_2|\leq\sqrt[n-1]{n}\leq 2\leq \frac{a}{n-1}+2.$$
Equality case: we must have $a=0$ and $2^{n-1}=n$, that is $n=1,2$. For $n=1$ $f(x)=0$ identically (and the text doesn't really make sense), so we might want to suppose $n\geq 2$ from the beginning, and for $n=2$ we have $f(x)=2x-x^2$: here $x_1=0$ and $x_2=1$ give us equality. In all other cases we have strict inequality.

A: Let $f(x)=nx-x^n-a$. Then by Rolle's theorem we get, $\exists c\in [x_1,x_2]$ such that $f'(c)=0\implies c=1$ assuming $n>1$. Then, $\exists \delta>0$ such that $x_1=1-\delta, x_2=1+\delta$. Now, $$nx_2-x_2^n=a\implies n(1+\delta)-(1+\delta)^n=a\\\implies a=(1+\delta)(n-(1+\delta)^{n-1})\\\implies a<(1+\delta)(n-(1+(n-1)\delta))\\\implies a< (n-1)(1-\delta^2)\\\implies 2(\delta-1)<(\delta^2-1)<\frac{a}{1-n}\\\implies |x_1-x_2|=2\delta<\frac{a}{1-n}+2 $$


text:
Q: How to implement dynamic parameterized search? We have relational db (SQL Server 2014, about 30 tables, very normalized). The application is built using Web.API/AngularJS
We need to implement dynamic search - user may select a few fields from several entities; the resulting search pseudo-code might look like:
SearchConditions
    (
        {Company.Name} <Contains> "Enterprise"
    )
    AND
    (
        {Customer.State} <Equals> "MO"
        OR
        {Customer.State} <Equals> "TX"
    )
    AND
    (
        {Company.AnnualSales} <LessThan> "123456.00"
    )
Return
    Company.Name,Customer.Name
    Group By State, Company

The structure of the search will stay the same - bunch of conditions connected by "AND"; each condition might have a few "OR" items inside.
We are using Entity Framework;
so far I see several ways to implement this functionality:

*

*1) build SQL query and run it against db (quite cumbersome)

*2) create EF IQueryable object and get data by using EF (somewhat
easier, but I am afraid that resulting SQL will be awful)

*3) use Lucene.NET (it will require Solr server, I'd like to avoid it
if possible)

*4) create denormalized OLAP instance of our db and use approach (1) or (2)
I am pretty sure there must be other ways; after all, EF/.NET/SQL combination is not so rare; I don't want to reinvent the wheel if I can avoid it. The ideal solution would parse search string, do the search and get back required fields (paging would be a good plus as well)
Would SSAS/SSRS help?

A: Although all the solutions you have mentioned will probably work, I will recommend Elasticsearch.
Elasticsearch is a document store that is built on top of Lucene (you do not need to run a separate Solr server though) and is really easy to run and install. There is also a nice .Net API for it called Nest. As the name mentions it is specifically built for searching. And it also has paging built in among many other features.
You can quite easily store only your search terms in the db and return the ids that is applicable to your search query. We currently use it to store all our data as documents however there are lots of people using it to just do all their searching.
You literally just copy the exe on your machine and run it. You then have a REST api that allows you to communicate with it. Nest abstracts this.
You can built your dynamic queries using Nest by just adding onto the search object or if you want to you can built a json object that you pass in.


text:
Q: mathematical symbols I'm using multidimensional formulas in my work and to differ it from the onedimensional ones I denote it by \mathbf, but what am I supposed to use in the definition and theorems environment to look samely almost like italic?

A: It's usually a bad idea to make the font used for mathematical symbols depend on the text font used for the surrounding environment. Thus if you are using upright bold for the symbol then best to do so even if your theorem text is italic.
Or you may prefer to use bold math italic instead of \mathbf eg using \bm{A} from the bm package, but use the same version consistently, that is don't switch between \bm and \mathbf depending on the surrounding text font.


text:
Q: Android SOAP request is returning HTTP Response 405 I see a couple of similar questions on here but mine has one big difference. I was able to use my login web client web method for about 9 months and then yesterday afternoon I started getting the 405 response.
Below is my code:
class Login extends AsyncTask<String, String, Integer> {
    StringManipulator stringManipulator = new StringManipulator();
    String result = "";
    ParseSessionId parseSessionId = new ParseSessionId();

    @Override
    protected Integer doInBackground(String... args) {
        int statusCode;

        URLSet urlset = new URLSet();
        SoapLogin login = new SoapLogin();

        String username = "";
        String password = "";

        InputStream instream;
        try {
            HttpPost post = new HttpPost(new URI(urlset.getUrl()));

            post.setHeader("SOAPAction", urlset.getAction());
            post.setHeader("Content-Type", urlset.getContentType());

            Log.e("login string entity", login.getSoapLogin(args[0].trim(), args[1].trim()));

            post.setEntity(new StringEntity(login.getSoapLogin(args[0].trim(), args[1].trim())));

            KeyStore trusted = KeyStore.getInstance("BKS");
            trusted.load(null, "".toCharArray());
            SSLSocketFactory sslf = new SSLSocketFactory(trusted);
            sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("https", sslf, 443));
            SingleClientConnManager cm = new SingleClientConnManager(post.getParams(), schemeRegistry);
            CustomHttpClient customHttpClient = new CustomHttpClient();
            HttpClient client = customHttpClient.getNewHttpClient();

            HttpResponse response = client.execute(post);

            Log.e("response.getStatusLine()", "" + response.getStatusLine());
            statusCode = response.getStatusLine().getStatusCode();

            Header[] headers = response.getAllHeaders();
            for (Header h : headers) {
                Log.e("Reponse Header", h.getName() + ": " + h.getValue());
            }

            HttpEntity entity = response.getEntity();

            if (entity != null) {
                instream = entity.getContent();
                result = stringManipulator.convertStreamToString(instream);

                Log.e("result", result);
                sessionID = parseSessionId.parseSessionId(result);

                instream.close();
            }
            return statusCode;

        } catch (Exception e) {
            return null;
        }
    }

    @Override
    protected void onPostExecute(Integer resultCode) {
        if (resultCode == 200) {
        //  Toast.makeText(context, "Response: OK", Toast.LENGTH_LONG).show();

        } else if (resultCode == 400) {
            Toast.makeText(context, "Server Error: 400", Toast.LENGTH_LONG).show();

        } else if (resultCode == 500) {
            Toast.makeText(context, "Server Error: 500", Toast.LENGTH_LONG).show();

        } else {
            Toast.makeText(context, "Server Error: " + resultCode, Toast.LENGTH_LONG).show();
        }
    }
}

Like I said, this all worked fine until yesterday afternoon. I am using SOAP UI to test on the browser and then building the SOAP message using the StringManipulator class.
The final soap login looks like this:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
    <soapenv:Header/>
    <soapenv:Body>
        <tem:Login>
            <tem:login>username</tem:login>
            <tem:password>password</tem:password>
        </tem:Login>
    </soapenv:Body>
</soapenv:Envelope>

The response status line is:

HTTP/1.1 405 Method Not Allowed

The response body is:
07-16 10:38:01.113: E/result(6877): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
07-16 10:38:01.113: E/result(6877):
07-16 10:38:01.113: E/result(6877):
07-16 10:38:01.113: E/result(6877): <title>IIS 8.5 Detailed Error - 405.0 - Method Not Allowed</title>
07-16 10:38:01.113: E/result(6877):
07-16 10:38:01.113: E/result(6877):
07-16 10:38:01.113: E/result(6877):
07-16 10:38:01.113: E/result(6877):
07-16 10:38:01.113: E/result(6877):

07-16 10:38:01.113: E/result(6877):

07-16 10:38:01.113: E/result(6877):
HTTP Error 405.0 - Method Not Allowed

07-16 10:38:01.113: E/result(6877):
The page you are looking for cannot be displayed because an invalid method (HTTP verb) is being used.

07-16 10:38:01.113: E/result(6877):

07-16 10:38:01.113: E/result(6877):

07-16 10:38:01.113: E/result(6877):  <fieldset>
Most likely causes:

07-16 10:38:01.113: E/result(6877):

The request sent to the Web server used an HTTP verb that is not allowed by the module configured to handle the request.

A request was sent to the server that contained an invalid HTTP verb.

The request is for static content and contains an HTTP verb other than GET or HEAD.

A request was sent to a virtual directory using the HTTP verb POST and the default document is a static file that does not support HTTP verbs other than GET or HEAD.

07-16 10:38:01.113: E/result(6877):  </fieldset>
07-16 10:38:01.113: E/result(6877):

07-16 10:38:01.113: E/result(6877):

07-16 10:38:01.113: E/result(6877):  <fieldset>
Things you can try:

07-16 10:38:01.113: E/result(6877):

Verify the list of verbs enabled for the module handler this request was sent to, and ensure that this verb should be allowed for the Web site.

Check the IIS log file to see which verb is not allowed for the request.

Create a tracing rule to track failed requests for this HTTP status code. For more information about creating a tracing rule for failed requests, click here.

07-16 10:38:01.113: E/result(6877):  </fieldset>
07-16 10:38:01.113: E/result(6877):

07-16 10:38:01.113: E/result(6877):
07-16 10:38:01.113: E/result(6877):

07-16 10:38:01.113: E/result(6877):  <fieldset>
Detailed Error Information:

07-16 10:38:01.113: E/result(6877):

07-16 10:38:01.113: E/result(6877):

07-16 10:38:01.113: E/result(6877):
Module	   StaticFileModule

Like I said, this is strange because between yesterday before lunch and yesterday after lunch, I changed nothing... so why would I be getting a new response from the server?
I am at a loss for things to try.

A: If it worked, you went to lunch, came back and it no longer works (and you really didn't change anything, as you say) then somebody else changed something.
You are doing a POST but for some reason IIS does not allow POST for whatever resource you are accessing (maybe a WCF .svc extension?). Seems the "StaticFileModule" is the one complaining based on the error page you get back.
Maybe someone reconfigured the server and now your request is handled by another handler? I suggest you contact your network administrators or site admins and ask them if something was reconfigured, new software installed, updates applied, etc in the time frame when you noticed your method call is no longer functional.


text:
Q: What direction are the decay particles of muons emitted in? If I were to run an experiment where I could measure the neutrino as well as the positron emitted when a muon decays, what direction should i be looking in?

A: The decay of a (anti-)muon to a positron is
$$ \mu^+ \longrightarrow e^+ + \nu_e + \bar{\nu}_\mu .$$
As there are three light decay products their directions (in the rest frame of the anti-muon) are only weakly correlated.
The usual experimental procedure for dealing with this is to work with a beam of highly relativistic (anti-)muons so that all the decay products go in roughly the direction of the (anti-)muon beam. This also has the advantage of increasing the neutrino interaction cross-section up to a level where it is merely tiny rather than well-nigh-infinitesimal.
All that said, even a very small and basic muon-neutrino measurement requires a considerable accelerator, a custom focusing system called a "horn", and a highly specialized detector system. It's not really suitable for a one-person project, nor for a hobbyist budget.


text:
Q: Disable Tomcat/Jetty ETag or cache in development, not working on IOS Anyone knows if there is a way to disable tomcat etag caching ( in development ) or whatever mechanisms it is using ?
Its not really working well in ios browser.
When I change a file, I refresh the iPhone safari browser, but nothing gets updated. I can do this twenty times and still same results.
However, when I then refresh my chrome browser on my desktop computer, it gets refreshed as usual. I can then go the safari browser and refresh and voila, it refreshes.
It makes me believe that it is communicating with the server each time, ( i can see on the logs as well ) but tomcat and jetty might be responding to use local cache, since it deems nothing has changed.
Which is not really true. I am not sure why tomcat threats Chrome and IOS differently, but it seems to be doing that. Or that IOS is not respecting my cache invalidation on the headers:
response.setDateHeader( "Expires"      , 0                                                                           );
response.setDateHeader( "Last-Modified", new Date().getTime()                                                        );
response.setHeader    ( "Pragma"       , "no-cache"                                                                  );
response.setHeader    ( "Cache-Control", "max-age=0, post-check=0, pre-check=0, no-store, no-cache, must-revalidate" );

But this is not working for either Tomcat or Jetty.

A: Appearantely, Java is to blame once again.
I am serving my contents from a URL and I just discovered that it caches them by default.
To prevent it from caching you need to KNOW to set
   url.openConnection().setUseCaches(false);

Which makes we wonder, what other classes this might be repeating itself.
Really clever Java, do the caching for me. Like I can't deal with that myself if I need to.


text:
Q: How to hide oembed links from wordpress excerpt? the_excerpt() function shows all oembeded links.
In this case is about a youtube video: http://i.stack.imgur.com/MP3EF.png

A: Adding the following code to the functions.php file (backing up the file first just in case you break the page):
function remove_links($text)
{
    if ('' == $text )
    {
        $pattern = '~http://[^\s]*~i'; //what we want to remove, the http link
        $text = get_the_content('');
        $text = preg_replace($pattern, '', $text);
    }
    return $text;
}
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'remove_links');

This will override the default excerpt() function and look for the link and remove it.

A: Building on @Howli's answer, here's a modified version that also trims the excerpt and applies the proper filters:
function tect_excerpt( $text ) {
    if ( '' == $text ) {
        $text = get_the_content('');
        $text = strip_shortcodes( $text );

        $text = preg_replace( '~http(s)?://[^\s]*~i', '', $text ); // removes URLs

        $text = apply_filters( 'the_content', $text );
        $text = str_replace(']]>', ']]>', $text);
        $excerpt_length = apply_filters( 'excerpt_length', 20 ); // default: 55
        $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[…]' );
        $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
    }
    return $text;
}

remove_filter( 'get_the_excerpt', 'wp_trim_excerpt' );
add_filter( 'get_the_excerpt', 'tect_excerpt');

A: You may use wp_filter_nohtml_kses function:
echo wp_filter_nohtml_kses(get_the_excerpt());

which will remove the <a href="http://somelink.com"> and </a> opening and closing tags


text:
Q: GCC - Truncation due to type conversion warning Why is the compiler not throwing a value truncation due to the conversion from a uint32 to a uint8 variable type? Precisely the line result = reg_value;
void read_byte_register(uint32_t u32_address_rd_byte_reg,
        uint8_t *pu8_Data_rd_byte_reg)
{
    uint8_t result;
    uint32_t reg_value;
    uint32_t *reg_ptr;

    reg_ptr = (uint32_t *) u32_address_rd_byte_reg;

    reg_value = *(reg_ptr);

    result = reg_value;

    *(pu8_Data_rd_byte_reg) = result;
}

The build command. You can see it is building for an ARM Cortex M3:
arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -pedantic -Wall -Wextra  -g3 -T "linker_script.ld" -Xlinker --gc-sections -Wl,-Map,"output_map.map" --specs=nano.specs -o "output.elf"

A: Adding the flag -Wconversion as stated in a comment to the question fixed the problem. Apparently it is disabled by default. -Wconversion enables warnings about implicit type conversions. Attaching a screenshot about the warning:

arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -pedantic -Wall -Wextra -Wconversion -g3 -T "linker_script.ld" -Xlinker --gc-sections -Wl,-Map,"output_map.map" --specs=nano.specs -o "output.elf"


text:
Q: Error : 14 UNAVAILABLE : Connect Failed I am getting the below error while deploying the business network using multi org env.
Error : Error trying install business network. Error: No valid responses from any peers.
Responses from attempted peer comms was an error : Error : 14 UNAVAILABLE : Connect Failed.
Quick background of my env:
I have a local ubuntu machine with Composer installed.
I have Multi Org setup installed with Hyperledger Fabric which includes 3 Orgs with 9 peers in 9 physical machines.
The connection profile has been used here to deploy the business network application from my local ubuntu machine.
Cards have been created sucessfully with the given Connection Profile and also imported successfully. Created 3 connection profiles for the 3 organizations. Also used TLS certs in the connection profiles.
Please guide me to resolve the issue.

A: This error is usually seen when the CLI cannot connect to the Fabric using the addresses specified in the connection.json file.  Either the Fabric containers are not started or they are not accessible to the CLI via the addresses specified.
Perhaps the addresses are wrong? If you are using 9 physical machines are the addresses resolving? are there firewall issues?


text:
Q: Google Apps script getFrom is undefined Trying to get all unread emails and save the pdf attachments to google drive. When looping through the threads I get an error saying getFrom is undefined. It used to work but doesn't anymore it gets to the first unread email and spits out the error.
var fileTypesToExtract = ['pdf'];
//Name of the label which will be applied after processing the mail message
var labelName = 'SaveToDrive';
function GmailToDrive(){
  //build query to search emails find if email doesnt have savetodrive label for duplicates
  var query = '';
  //GmailApp.getUserLabelByName('receipts-new')
  //filename:jpg OR filename:tif OR filename:gif OR fileName:png OR filename:bmp OR filename:svg'; //'after:'+getDateNDaysBack_(1)+
  for(var i in fileTypesToExtract){
    query += (query === '' ?('filename:'+fileTypesToExtract[i]) : (' OR filename:'+fileTypesToExtract[i]));
  }
  query = 'is:unread ' + query;
  var threads = GmailApp.search(query);
  console.log(threads);
  var label = getGmailLabel_(labelName);
  var parentFolder;
  var root = DriveApp.getRootFolder();
  if(threads == null){
    exit;
  }
  for(var i in threads){
    var mesgs = threads[i].getMessages;
    console.log(mesgs);
    // console.log(threads[i]);

>! if(mesgs[i] == undefined){
>! console.log("Email Undefined");
>! continue;
>!     }
    var senderAddress = mesgs[i].getFrom();
    var emailSubject = mesgs[i].getSubject();

    console.log("Subject: "+emailSubject);
      console.log("Sender Address: "+senderAddress);
      folderPicker_(emailSubject, senderAddress);
      if(threads.length > 0){
    parentFolder = getFolder_(folderName);
  }
      //get attachments
      var attachments = mesgs[i].getAttachments();

      for(var k in attachments){
        var attachment = attachments[k];
        var isDefinedType = checkIfDefinedType_(attachment);
        if(!isDefinedType) continue;
        var attachmentBlob = attachment.copyBlob();
        var file = DriveApp.createFile(attachmentBlob);
        parentFolder.addFile(file);
        root.removeFile(file);
      }

      threads[i].addLabel(label);
      threads[i].markRead();
      console.log("Sucessfull save to drive and label added");
  }

  }

Error
TypeError: Cannot read property 'getFrom' of undefined
GmailToDrive    @ Code.gs:40`


text:
Q: how to set value in formArray I have got a formgroup named input form, having an formarray of topics. I want to change the value of an inputfield using a dynamically created filtered list.
the filter function works fine:
filtertopic(idx: number) {
  const test = this.topics.value[idx].topic;
  if (test !== "") {
    this.onderdeel = "topics";
    this.queryselector = idx;
    this.filteredList = this.Topics.filter(function(el) {
      return el.toLowerCase().indexOf(test.toLowerCase()) >-1;
    }.bind(this));
     } else { this.filteredList = [];
    }
    }

but the function handleBlur to change the value in the input field does not work
handleBlur() {
    console.log(this.selectedIdx);
    if (this.selectedIdx > -1) {
      if (this.onderdeel =="topics") {
        this.topics.value[this.queryselector].topic.setValue(this.filteredList[this.selectedIdx]);
      } else {
        this.query = this.filteredList[this.selectedIdx];
      }
    }
    this.filteredList = [];
    this.selectedIdx = -1;
}

I think it has to do with the

this.topics.value[this.queryselector].topic.setValue(this.filteredList[this.selectedIdx]);

to set the formcontrol value. Does anybody know the solution?

A:  this.yourdataobject.forEach(task => {
      this.formcontrolname.push(
        this.fb.group({
          name: [task.name, Validators.required]
        })
      );
    });


text:
Q: Javascript singleton accepting arguments So there are a lot of questions and answers about the singleton pattern and JavaScript already. But still I couldn't (easily) find a good answer that showed a singleton that accepts arguments. So let's try and change that.
So this is one I came up with:
Global = {};

Global.Singleton = (function () {
    var instance  = undefined;
    // The returned object (Global.Singleton):
    return {
        getInstance : function (name) {
            if (instance) return instance;
            //===========================================|
            // The 'constructor' function:
            return (function (name) {
                var _name = name;
                instance = {};
                instance.getName = function () {
                    return _name;
                };
                return instance;
            }(name));
            //===========================================|
        }
    };
}());

(function () {
    var instance = Global.Singleton.getInstance("Chuck");
    console.log(instance); //  Object { getName=function() }.
    console.log(instance.getName()); // Chuck.
    console.log(instance === Global.Singleton.getInstance()); // true.
}());

Is this a good design?
(I am not yet a professional, so hopefully some experienced programmers will confirm whether this is good or bad code.)
Perhaps you have an alternative and want to post that too here?
EDIT:
I don't know what i was thinking, but the above code can just be simplified to this (which probably is already on this site a thousand times):
Global = {};

Global.Singleton = (function () {
    var instance  = undefined;
    // The returned object (Global.Singleton):
    return {
        getInstance : function (name) {
            if (instance) return instance;
            //===========================================|
            var _name = name;
            instance = {};
            instance.getName = function () {
                return _name;
            };
            return instance;
            //===========================================|
        }

    };
}());

(function () {
    var instance = Global.Singleton.getInstance("Chuck");
    console.log(instance); //  Object { getName=function() }.
    console.log(instance.getName()); // Chuck.
    console.log(instance === Global.Singleton.getInstance()); // true.
}());


text:
Q: Dividing a square into equal-area rectangles How many ways are there to tile an $n\times n$ square with exactly $n$ rectangles, each of which has integer sides and area $n$?
The sequence $C(n)$ begins 1, 2, 2, 9, 2, 46, 2, 250, 37. Clearly $C(p) = 2$ for prime $p$.  The value $C(8) = 250$ was provided to me by Sjoerd Visscher, but I cannot vouch for it personally, not having seen the details of his enumeration.
OEIS was no help.

A: Sorry to poke a dead post but it was near the top of the "unanswered questions" queue for me and it's a decent problem.
Working locally should provide a good avenue of attack on this problem.
For instance, a relatively straightforward analysis (which I'll post if there is interest) yields:
$$ C(p^2) = 2\left(\sum_{k=0}^{p} {p^2-k(p-1) \choose k}\right)-1 $$


text:
Q: Indexing technique in Ehcache I just went to almost all the documentation of ehcache. They are using indexes to perform queries in cache. What they didn't mentioned is what technique they are using?
Also I want to use EHcache as a cache store and create index on that cache with lucene. Does anyone know how to do that i already did an exhaustive search but didn't find anything is it even possible to with EHcache?

A: Ehcache has different types of storage. If you refer to the most commonly used one (MemoryStore), it uses SelectableConcurrentHashMap which is a somewhat customized version of ConcurrentHashMap. Just to be clear, this is completely different from how Lucene works.
If you want to Lucene-index your cache entries, one of the ways of doing that would be implementing CacheEventListener and calling relevant Lucene APIs on each cache event (remove, put, expired, etc.).


text:
Q: Row Deselection Queries Help me out Excel aficionados, Google has failed me with this one ...
To select a number of non-contiguous rows in Excel I hold down Ctrl when I click on the row headers.  However if I want to unselect a row then holding down Ctrl and clicking on the header again has no effect.
Q1. Is there a way to unselect a row in this way?
In Excel 2013 when I attempt to deselect a row with Ctrl held down, the row remains selected but goes a little bit darker, and increasingly so if I click on it again.  This can leave somebody like me with multiple rows selected, but the appearance that some rows are more selected than others.
Q2. What is happening here?
Cheers

A: Ans 1. The answer to your 1st question is simple. Unfortunately you cant. Out of the box Excel doesn't support deselection via clicking for a second time. (Surprising how M'Soft didn't think about this)
You have some external 3rd party plugins (Kutools for example) which does allow you to achieve it.
A workaround is writing a VBA script for the same, however that is kind of going over the edge.
Ans 2. Well I don't have excel 2013 so I can't help you with that one unfortunately. In 2010 it seemed to work pretty normal.


text:
Q: How to JOIN on different CONCAT expressions? I am attempting to Join tables based on a CONCAT expression containing different text criteria.
I have tried a inefficient method that just takes way too long to query.
SELECT
sf.displayId,
-- tw.displayText,
CASE
        WHEN tw.DisplayText IN ('N/A', 'NotApplicable', 'Not Applicable')
        THEN 'Not Applicable'
        ELSE REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(tw.DisplayText,'client','Client'),'approved','Approved'),'rejected','Rejected'),'review','Review'),'Requirement','Requirement'),'open','Open'),'submitted','Submitted'),'complete','Complete'),'incomplete','Incomplete'),'pending','Pending'),'resubmit','Resubmit'),'Awaiting review','Awaiting Review')
        END AS AuditStatus
FROM Connect.Data.supplier_form sf
JOIN Connect.Data.translation tw
     ON ((CONCAT('workflowStepName' , sf.workflowStatusId) = tw.translationField) OR (CONCAT('workflowStepMessage' , sf.workflowStatusId) = tw.translationField))
     AND tw.language = 'en'
WHERE sf.deleted = 0
AND tw.displayText IN ('Awaiting Review','Awaiting review')
ORDER BY sf.displayId
OFFSET 0 ROWS
FETCH NEXT 100 ROWS ONLY;

I want to JOIN Connect.Data.supplier_form sf based on the CONCAT expression in a far more efficient way.

A: I'm not sure how good the SQL optimizer is in SQL Server, so you may try to flip the order of the join condition to make it easier to use an index. I would do two things:

*

*I would change the JOIN condition to:
JOIN Connect.Data.translation tw
ON tw.language = 'en'
AND tw.translationField in (
  CONCAT('workflowStepName' , sf.workflowStatusId),
  CONCAT('workflowStepMessage' , sf.workflowStatusId)
)

*And I would add the index:
create index ix1 on Connect.Data.translation(language, translationField);

Give it a try and let us know if it improves the performance.


text:
Q: How Batch learning in Pytorch is performed? When you look at how network architecture is built inside the pytorch code, we need to extend the torch.nn.Module and inside __init__, we define the module of networks and pytorch is going to track the gradients of parameters of these modules. Then inside the forward function, we define how the forward pass should be done for our network.
The thing I do not understand here is how the batch learning is going to occur. In none of the definition above including the forward function, we do not care about the dimension of batch of the input to our network. The only thing we need to set to perform batch learning is to add an extra dimension to the input which corresponds to the batch size but nothing inside the network definition is going to be changed if we are working with batch learning. At least, this is the thing I have seen in the codes here.
So, if all the things I have explained so far is correct (I would really appreciate if you let me know if I have misunderstood something), how batch learning is performed if nothing is declared regarding the batch size inside the definition of our network class (the class that inherits torch.nn.Module)? Specifically, I am interested to know how batch gradient descent algorithm is implemented in pytorch when we just set nn.MSELoss with batch dimension.

A: Check this:
import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, x):
        print("Hi ma")
        print(x)
        x = F.relu(x)
        return x

n = Net()
r = n(torch.tensor(-1))
print(r)
r = n.forward(torch.tensor(1)) #not planned to call directly
print(r)

out:
Hi ma
tensor(-1)
tensor(0)
Hi ma
tensor(1)
tensor(1)

Thing to remember is that forward should not be called directly.
The PyTorch made this Module object n callable. They implemented callable like:
 def __call__(self, *input, **kwargs):
    for hook in self._forward_pre_hooks.values():
        hook(self, input)
    if torch._C._get_tracing_state():
        result = self._slow_forward(*input, **kwargs)
    else:
        result = self.forward(*input, **kwargs)
    for hook in self._forward_hooks.values():
        hook_result = hook(self, input, result)
        if hook_result is not None:
            raise RuntimeError(
                "forward hooks should never return any values, but '{}'"
                "didn't return None".format(hook))
    if len(self._backward_hooks) > 0:
        var = result
        while not isinstance(var, torch.Tensor):
            if isinstance(var, dict):
                var = next((v for v in var.values() if isinstance(v, torch.Tensor)))
            else:
                var = var[0]
        grad_fn = var.grad_fn
        if grad_fn is not None:
            for hook in self._backward_hooks.values():
                wrapper = functools.partial(hook, self)
                functools.update_wrapper(wrapper, hook)
                grad_fn.register_hook(wrapper)
    return result

And just n() will call forward automatically.
In general, __init__ defines the module structure and forward() defines operations on a single batch.
That operation may repeat if needed for some structure elements or you may call functions on tensors directly like we did x = F.relu(x).
You got this great, everything in PyTorch will do in batches (mini-batches), since the PyTorch is optimized to work this way.
This means when you read the image, you will not read the single one, but one bs batches of images.


text:
Q: Using a parameterless controller constructor with Ninject? I'm using Ninject for dependency injection in my application. Here's an example of one of my controllers:
public class DepartmentsController : Controller
{
    private IDepartmentsRepository departmentsRepository;

    public DepartmentsController(IDepartmentsRepository departmentsRepository)
    {
        this.departmentsRepository = departmentsRepository;
    }

    ...
}

I'm also trying to follow this tutorial to use ELMAH in an MVC application. The idea is to use a custom controller factory to handle errors from every controller. You then set the controller factory to the custom one in the global.asax.cs file.
The only problem is that it is expecting a parameterless constructor in each controller, which I can't do (that I know of) with dependency injection with Ninject.
How can I get around this?

A: If you are using MVC3, you should ignore the part about the Controller Factory and use Global Filters to apply the custom attribute to each controller.
If you aren't using v3 yet and you can modify their code to inherit from the Ninject Controller factory.


text:
Q: Choose compute node(hypervisor) for instance creation with ansible openstack.cloud.server module I am looking to specify which compute node to reside on when creating an instance with Openstack ansible module openstack.cloud.server, Actually I want to ansiblealize the following command:
$ openstack server create --flavor g2 --image Ubuntu-20.04 --network public2 --security-group default --hypervisor-hostname compute3 --os-compute-api-version 2.74 test
# OR
$ openstack server create --flavor g2 --image Ubuntu-20.04 --network public2 --security-group default --host compute3 --os-compute-api-version 2.74 test

How I can pass --host or --hypervisor-hostname similar to Openstack CLI to openstack.cloud.server module in ansible???

A: Try to use meta.hostname define you hypervisor:
- name: Create a new instance and attaches to a network and passes metadata to the instance
  openstack.cloud.server:
      ......
      meta:
        hostname: test1

meta:

A list of key value pairs that should be provided as a metadata to the new instance

Another way, it could use availability_zone parameter to select hosts:
- name: launch an instance in specific host
  openstack.cloud.server:
    ......
    availability_zone: nova:compute3001

See also this example.


text:
Q: Java Applet Blocked I'm trying to make an applet work on my website but whenever I load it, I get the following message: Your security settings have blocked an untrusted application from running.
I have added the site to exception list, but it still won't work.
What should I do to make it work?

A: You need to sign the applet using the official certificate that only some company involved in code signing can provide. If this is not an option for you, there is basically nothing you can do as Oracle has removed the possibility to run unsigned applets in a sandbox of the browser.


text:
Q: Flask send rendered html template on email I'm using Flask to generate API and passing the data using rendered template to create charts on html page using py-script.
Please let me know how can I send the rendered html page with all charts over email?
At least if I get an idea to store the rendered html page will also work.
def test():
    try:
        df = {'C': 20, 'C++': -15, 'Java': 30,
                'Python': 35}

        cars = ['AUDI', 'BMW', 'FORD', 'TESLA', 'JAGUAR', 'MERCEDES']
        point = [23, 17, 35, 29, 12, 41]

        #df1 = pd.DataFrame(list(zip(cars, point)), columns=['cars', 'point'])
        # showing the prediction results in a UI

        return render_template('test.html',data=df,ct=cars,pt=point)

    except Exception as e:
        print('The Exception message is: ',e)
        logging.debug(e)
        return 'something is wrong'

Test.html
<!DOCTYPE html>
<html>
  <head>
      <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
      <script defer src="https://pyscript.net/alpha/pyscript.js"></script>

      <py-env>
        - pandas
        - numpy
        - matplotlib
      </py-env>
  </head>
  <body>

<py-script>
import matplotlib.pyplot as plt

y = list({{data}}.keys())
x = list({{data}}.values())

plt.barh(y, x, color=['red', 'green', 'blue', 'cyan'])

# setting label of y-axis
plt.ylabel("pen sold")

# setting label of x-axis
plt.xlabel("price")
plt.title("Horizontal bar graph")
plt

</py-script>

  </body>
</html>

Regards,
Rohan

A: From the documentation: flask.render_template(template_name_or_list, **context)

Renders a template from the template folder with the given context.

This means that through the render_template function you are able to generate a string starting from a file (the template) and any parameters passed to the template.
Instead of returning the result of the render_template, save it in a variable and then send the content via email.
def test():
    try:
        df = {'C': 20, 'C++': -15, 'Java': 30,
                'Python': 35}

        cars = ['AUDI', 'BMW', 'FORD', 'TESLA', 'JAGUAR', 'MERCEDES']
        point = [23, 17, 35, 29, 12, 41]

        #df1 = pd.DataFrame(list(zip(cars, point)), columns=['cars', 'point'])
        # showing the prediction results in a UI

        my_html = render_template('test.html',data=df,ct=cars,pt=point)
        send_mail("test@test.com", "subject", my_html)

    except Exception as e:
        print('The Exception message is: ',e)
        logging.debug(e)
        raise e

Note that if the template contains css files served by your own application, for example:
<link rel = "stylesheet" href = "{{url_for ('static', filename = 'style.css')}}">, the email will be displayed correctly only if your application It is running. Otherwise embed the css directly into the template, which I recommend if your purpose is to generate an email.


text:
Q: How to take value from array into integer (PHP) Input :
$sql1 = "SELECT COUNT(*) FROM matchTrip where userTripId = :tripId";

$stmt1 = $this->db->prepare($sql1);

$stmt1->bindParam(':tripId', $trip, PDO::PARAM_INT);

$temp = $stmt1->fetchObject();

echo(json_encode($temp));

Output:
 How to take value from array :

 of which json_encode looks like this: {"COUNT(*)":"7"}

Any help will be appreciated.

A: Why don't you just give the column an alias in the SQL itself?
$sql1 = "SELECT COUNT(*) as myCount FROM matchTrip where userTripId = :tripId";

Makes the rest easier to work with.

A: Do you mean json_decode? You can just put it between quotes and it should work; $array["COUNT(*)"].
But you can also add "AS myCount" to your SQL.

A: if to get rid of all the useless stuff from your code
$sql  = "SELECT COUNT(*) FROM matchTrip where userTripId = ?";
$stmt = $this->db->prepare($sql);
$stmt->execute(array($table_of_user[$i]));
$count = $stmt->fetchColumn();

echo $count;

A: So why not just fecth as array?
$temp = $stmt1->fetch(PDO::FETCH_ASSOC);
echo $temp['COUNT(*)'];

A: Just use like this:
$json = json_encode($temp);

echo $json->{'COUNT(*)'}; // 7


text:
Q: Mathematical expression in Crystal Reports I have two fields in a Crystal Report.  Open and InProgress. Each field is a result of a separate command.
In my report, I have bound {Open} and {InProgress} to a text field. I want to create a third field with an expression like {Open} - {InProgress} that will calculate the difference.
Can I do this with such an expression, if yes how can it be acomplished?

A: I found a decent solution. If there is a better way, I will gladly accept that as the answer.
What I did was create a Formula Field, then put the expression I had above {Open} - {InProgress} into that field. I can now use the formula field in the report.


text:
Q: openpyxl giving memory error while updating sheet I want to update exsting sheet in excel using openpyxl and i am getting below error.
File "src\lxml\xmlerror.pxi", line 87, in lxml.etree._LogEntry._setError
MemoryError:
My excel file is of 27MB size.
please find the code i am using below.
evidenceworkbook = load_workbook("Inforce_Fire_Validation.xlsx")
sheet_data = evidenceworkbook['Source']
poldata_D2 = sheet_data['A7']
poldata_D2.value = "testing D2"
evidenceworkbook.save("Inforce_Fire_Validation.xlsx")

I tried using write_only but as per my analysis this is for creating new excel with large data.

A: I will suggest you to use the Optimized reader (link - https://openpyxl.readthedocs.org/en/latest/optimized.html).
While loading a workbook pass read_only=True
wb = load_workbook(file_path, read_only=True)


text:
Q: prevent submitting form in jQuery I want to add data to a selective cell of a table. I wrote this code in JavaScript.
var rowIndex = 10;
var colIndex = 5;
var dateTable = document.getElementById('timeTable');
dateTable.rows[rowIndex].cells[colIndex].innerHTML = "Su";

I wanted to use the same concept in jQuery as:
$('input[name=add_button]').click(function(e) {
    var dateTable = document.getElementById('timeTable');
    var rowIndex = $('[name=days]').val();
    var colIndex = $('[name=times]').val();
    var text = $('input[name = text]').val();
    dateTable.rows[rowIndex].cells[colIndex].innerHTML = text;
    e.preventDefault();
});

My problem is: preventDefault() method should prevent my form to be submitted. It is not preventing form submission. If I remove the      dateTable.rows[rowIndex].cells[colIndex].innerHTML = text; line, the form is not submitted. I think there is some problem with this particular line. Please help me sorting this. If there is better option available in jQuery please tell me. I shall be able to use the colIndex and rowIndex to find the position of the cell.
Thanks

A: Try this:
Add return false; in your form tag like
<form onsubmit="return false;" ......>

</form>

Also check you indexes that these are starting from 0 or 1, if these are starting from 1 then you have to decrease it by 1 before using it,
like dateTable.rows[rowIndex-1].cells[colIndex-1].innerHTML = text;
Actually when you click on button it will prevent its default behavior, not other elements behavior(form in your case).
So, I think it is not possible to prevent your form here.
Alternative Code you can use:
$('form#myForm').on('submit',function(e){
    e.preventDefault();
    var dateTable = document.getElementById('timeTable');
    var rowIndex = $('[name=days]').val();
    var colIndex = $('[name=times]').val();
    var text = $('input[name = text]').val();
    dateTable.rows[rowIndex].cells[colIndex].innerHTML = text;
    return false;
});


text:
Q: Force change default initial save location of all programs to custom folder Many programs often default the save destination location to the standard Libraries/XYZ folder which is the last place I want to save anything (due to sensible backup reasons).
Some programs go a step further and force you to that location within the same program session (Classic Media Player springs to mind) even if you've saved a file elsewhere just a minute beforehand.
Other programs allow you to define this location, but is there a way to force Windows to change the location of any program to a destination of your choice, regardless of what each program dictates?

A: Probably not what you're looking for, but symbolic links have proven useful to me in the past. For instance, many programs are hardcoded to store things in APPDATA but I generally don't want all of this "data" on my "system" sdd. Here, symbolic links come in handy. It can be quirky, and I wouldn't recommend symlinking your entire appdata folder, do it individually on a program by program basis. Of course I would also suggest letting the developer of said program know of your desire for such things.
In your case of some programs not remembering where you last saved a file, when it opens SaveFileDialog again (even in the same session), I'm not sure you can do much about that.
https://msdn.microsoft.com/en-us/library/windows/desktop/aa365680%28v=vs.85%29.aspx


text:
Q: Signal path switching for effect circuits I'm trying to build a method of switching signal order with three circuits in a rack unit.
I've been researching different methods, using relays, using CMOS etc but I'm getting a bit overwhelmed and lost. I don't have a lot of technical experience with electronics apart from building kits and using an Arduino every now and then.
Say circuits are A, B and C; I would like to order them ABC, CAB, BAC, ACB.
Could anyone point me in the right direction on this? Any recommended reading on CMOS or even a chip recommendation?
Thanks for reading!
Edit: Added a picture to make it clearer, all signals are analog (line-level).

A: If I am understanding the question correctly that is actually a fairly complicated matrix. So correct me if I am wrong.
What you are looking for is this...

If you really only want the four permutations you can do that with a four pole four way switch like this...

simulate this circuit – Schematic created using CircuitLab
However, the permutations are much greater than four, six using all of them and more if you skip one, two, or three effects. If you want all of them then there are many ways to do that, some with micros, but a simple enough solution can be implemented with 13 reed relays, a bunch of diodes, and a rotary switch.

simulate this circuit
View Larger
Note I only showed two switch positions, I am sure you can figure out the rest. I also added a bypass.

A: This will be a continuation of Trevor's answer. So the design will be fairly similar.
I'm not sure how much you like relays, but I prefer transistors to do their job (whenever possible). Because of the physical size, price and energy consumption.
I'm using two N-MOSFETS as a transmission gate, but in order to properly open them and close them you will most likely need 12 V and -12 V, those can easily be made with a charge pump and an oscillator.

I hate seeing negative voltages at the top of the schematic, but since the Falstad Circuit JS doesn't support proper wire dragging I decided that it was not worth my time. Had this been something job related then I'd redesign it with -12 V at bottom and 12 V at the top. I realized my wrong doing very late at the design stage.
Here's the text if you want to interact with the button at the bottom.
If you want to simulate, press the Circuit JS link, when you are at Circuit JS, click file at the upper left. Choose "file > import from text" and copy and paste the text from the text link. This is the first time I've made a schematic with an URL that's too long. Oh well.

EDIT: Realized you don't need the PMOS at the bottom if you connect your switch to 12 V instead of 0 V.
So it should look more like this:

If you look at the output, I changed the pull down resistors so they are correct.
This is the design I'd solder onto a PCB and be happy with. But I'm no audiophile, I can't even tell if someone sings bad or not. Music ain't my thang.
Here's the text for this circuit if you want to test it out.


text:
Q: word press loop slider hello i have been working on a particular theme sports bootstrap theme for my football blog. I tried looping the slider of the theme but the theme keeps scattering, despite all my effort . I would really like any help i get thanks. below is the php code i have been working on

                    <?php
                 $args = array(
            'category_name' => 'latest',
            'posts_per_page'=> 4
            );
            $uk_soccer = new WP_Query($args);

            if ( $uk_soccer->have_posts() ) : while ( $uk_soccer->have_posts() ): $uk_soccer->the_post();

                ?>

    <img class="img-responsive" src="<?php the_post_thumbnail_url(); ?>" alt="<?php the_title(); ?>">

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php echo get_the_date('M, j Y'); ?> at <?php the_time(); ?>, by:<?php echo get_author_name(); ?>

<?php echo excerpt(15); ?>

                        <?php
    endwhile;
    endif;
    wp_reset_postdata();

    ?>

A: Put this code so your slider will work

                    <?php
                 $args = array(
            'category_name' => 'latest',
            'posts_per_page'=> 4
            );
            $uk_soccer = new WP_Query($args);

            if ( $uk_soccer->have_posts() ) :
$index = 0;
while ( $uk_soccer->have_posts() ): $uk_soccer->the_post();

                ?>
                        <div class="<?php echo ($index == 0) ? 'active' : ''; ?>feature_news_item">

    <img class="img-responsive" src="<?php the_post_thumbnail_url(); ?>" alt="<?php the_title(); ?>">

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php echo get_the_date('M, j Y'); ?> at <?php the_time(); ?>, by:<?php echo get_author_name(); ?>

<?php echo excerpt(15); ?>

                        <?php
$index++;
    endwhile;
    endif;
    wp_reset_postdata();

    ?>


text:
Q: How to capture Page Speed of NextJS App when the internal route changes How capture page speed data of NextJS App when the internal route changes? My pages does not refresh on route change. i make api calls to fetch data for that page and render it on the route.
i tried using NextJS reportWebVitals API but it is giving me the wrong data.
Is there any better way to capture the page load time of the NextJS app on internal route change?


text:
Q: find command is picking files of unrelated pattern I have a following find command which I trigger via autosys scheduler. The command is used to delete file older than X days.
find /home/my_home/document -maxdepth 1 -type f -mtime +31 -name "qwer_*" -delete -print

But above command fails is failing.
Weird part is, in logs I can see find is picking up the files which does not even match the qwer_* pattern
eg.
find: `/home/my_home/document/yumn.txt': No such file or directory
find: `/home/my_home/document/ztry.txt': No such file or directory

Am I missing anything in find command.

A: In your previous question you said:

I suspect it is due to some other parallel job is deleting some of the files.

This is exactly what happened in this case. Your find found out there's a file yumn.txt, then the file was deleted, then find tried to do something with the file and failed. The same scenario for ztry.txt.
Note it doesn't mean that if yumn.txt was not simultaneously deleted, then find would delete and print it. It only means yumn.txt unexpectedly disappeared before find was done testing it.

You may expect -name "qwer_*" to reject yumn.txt according to sole directory listing (from which find learns about the existence of the file in the first place), so the tool never needs to query about the file itself (later, when the file doesn't exist). My tests indicate this is not always the case.
In general find may or may not rearrange tests. This means -name "qwer_*" may be tested before or after -mtime +31 etc. E.g. GNU find reorders expressions so that tests based only on the names of files are performed early. See man 1 find, -O and -D options. But in your case maybe what you typed first was tested first, so yumn.txt was meant to be tested against -type f and -mtime +31, and at least one of these tests required the file to exist at the moment the test was performed.
But even with sole find . -name "qwer_*" it's possible to encounter the problem. I tested like this:
while true; do touch yumn.txt; rm yumn.txt; done &

Then ls yumn.txt would find a file or not. You can repeat ls yumn.txt many times and sometimes you will find a file, sometimes not. This is expected.
In my Debian, when yumn.txt keeps being created and destroyed on a Btrfs filesystem, find . -name "qwer_*" doesn't complain about it; or at least it did not when I tested repeatedly more than 4k times.
On the other hand in my OpenWRT router find . -name "qwer_*" sometimes does complain, and the message is almost exactly like yours:
find: ./yumn.txt: No such file or directory

It's find from BusyBox and the filesystem is overlayfs (with ext3 as the upperdir). The conclusion is: in some circumstances it's possible that a file being deleted by another process makes find complain (and return non-zero exit status!), even if -name could in theory reject the file in the first place.

Not a general solution, but in your specific case you can try this approach:
find /home/my_home/document/qwer_* -maxdepth 0 -type f -mtime +31 -delete -print

Now the shell performs pattern matching and runs find with only matching files as starting points. Because of -maxdepth 0 find examines only the given files (relevant if at least one of them happens to be a directory). This way disappearing yumn.txt or such cannot affect find. Possible problems:

*

*If qwer_* files are deleted by other process(es) (like yumn.txt was), it may happen find complains and returns non-zero exit status.

*If there are too many qwer_* files then you will get Argument list too long (or similar).

*If there is no match at all, find will get literal /home/my_home/document/qwer_* starting point and complain about nonexisting file/directory.


text:
Q: Build and run express.js server detached as a Github action Problem
When running tests locally, they all pass since I have a docker container running a fake [express.js] api server.
Locally, I just run docker compose up -d to run the test server and docker compose down to exit.
My ci currently runs the live server but has no way to exit.

# action.yml

name: "Build test container"
description: "Run build test container"
outputs:
  time:
    description: "The time executed"
runs:
  using: "docker"
  image: "Dockerfile"

#!/bin/sh
# entrypoint.sh

npm run start

# .github/workflows/ci.yml

name: ci

on: [push]

jobs:
  hello_world_job:
    runs-on: ubuntu-latest
    name: A job to build test container
    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Test containers action step
        uses: ./ # Root dir action
        id: citest
      - name: Get the output time
        run: echo "The time was ${{ steps.citest.outputs.time }}"

I was thinking maybe just build the container and have the ci's pass in a command to run the server but I am not sure if that would hang


text:
Q: Office 365: Outlook — limit sync to 30 days I have just installed MS Outlook for Mac and am trying to prevent it from downloading my entire inbox with emails dating back to 2008.
I have an IMAP Gmail account and only want Outlook to sync emails from the 30 most recent days. This is quite easy to achieve in Thunderbird but I can't see anything for this for Outlook?

A: As of Outlook 16.23 (February 2019), such a feature to limit the email downloaded by date does not appear to exist. There's a feature request on Outlook's UserVoice forum for this functionality.
For an IMAP account, under the account's Advanced settings, you can configure Outlook to only download headers.

There is nothing similar for Exchange accounts.

A: If you set up your Gmail account as a regular IMAP account (and not as a gmail account) in Outlook, you can limit the download size.  For this, you would also need to change your IMAP settings in Gmail.  There is an option to restrict the number of messages that can be synced. I have set it to 1000.  This does not work by number of days, but close enough if you can guess a number for yourself.