text:
Q: Any attempt to access props in MDX component results in failed build, but dev works just fine I'm trying to get a single line of anything from passed by props to render.
If nothing is passed or needed, then the MDX render outs. If props are passed and tried to be used, failure.
The only thing left on this site is getting MDX to actually render on build.
Running [Gatsby Dev] works, and the MDX file renders can use all props passed to it. Any attempt to [Gatsby Build] and it fails saying that it can't read undefined.
I've tried wrapping the render in a MDX provider, in a conditional statement that checks for the specific props first, but nothing works. Gatsby Build pretends like there are no props being passed at all.
POST TEMPLATE
import React from 'react';
import { MDXRenderer } from "gatsby-plugin-mdx"
import {graphql, Link} from 'gatsby'
import { MDXProvider } from '@mdx-js/react';
import Layout from "../components2/Layout";
import Navbar from "../components2/Navbar"

**Styled components**

const Post = ({data}) => {
    const { frontmatter} = data.mdx
    onst result = data.mdx;

    return (
      <Layout>
        <Navbar></Navbar>
        <BlogLayout>
        <Container>
                <Banner>
                <BannerInner>
                  <BannerSubtitle to={`/${frontmatter.tags[0]}`}>{frontmatter.tags[0]}
                  </BannerSubtitle>
                  <BannerTitle>{frontmatter.title}</BannerTitle>
                  <BannerByline>{frontmatter.date}</BannerByline>
                </BannerInner>
              </Banner>
          </Container>
          <GridWrap>
                <MDXProvider>
                <MDXRenderer props={result}>{result.body}</MDXRenderer>
                </MDXProvider>
          </GridWrap>
        </BlogLayout>
      </Layout>
    );
}

export default Post

export const Pagequery = graphql`query PostBySlug($slug: String!) {
  mdx(slug: {eq: $slug}, frontmatter: {templateKey: {eq: "blog-post"}}) {
    frontmatter {
      title
      date(formatString: "MM/DD/YYYY")
      tags
      featuredimage {
        childImageSharp {
          gatsbyImageData(placeholder: DOMINANT_COLOR, layout: FULL_WIDTH)
        }
      }
    }
    body
    excerpt
  }
}
`

MARKDOWN FILE
---
templateKey: blog-post
title: Tables with style
date: 3122-03-08T01:54:06.882Z
description: "Nulla neque sem, gravida nec facilisis eu, interdum a neque. Morbi
  in maximus dui. Morbi tincidunt ultrices nulla quis ullamcorper. Etiam egestas
  id nisi in cursus. In in ex luctus, sodales sapien eu, semper ligula. Fusce
  vitae turpis vel dui interdum eleifend nec nec eros. Praesent sed placerat
  lacus. Aliquam lacinia arcu ut sollicitudin dictum. Aenean gravida commodo
  velit, non accumsan tortor congue et. Duis malesuada nibh et odio finibus, a
  fermentum lacus gravida. "
featuredpost: true
featuredimage: /img/44.jpg
tags:
  - table
metaDescription: "Nulla neque sem, gravida nec facilisis eu, interdum a neque.
  Morbi in maximus dui. Morbi tincidunt ultrices nulla quis ullamcorper. Etiam
  egestas id nisi in cursus. In in ex luctus, sodales sapien eu, semper ligula.
  Fusce vitae turpis vel dui interdum eleifend nec nec eros. Praesent sed
  placerat lacus. Aliquam lacinia arcu ut sollicitudin dictum. Aenean gravida
  commodo velit, non accumsan tortor congue et. Duis malesuada nibh et odio
  finibus, a fermentum lacus gravida. "
---

import { getImage, GatsbyImage } from "gatsby-plugin-image";

## Post Body

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eleifend iaculis nunc ut posuere. Integer mollis interdum nisi eu pellentesque. Quisque euismod ipsum mi, in rutrum nisl malesuada quis. In hac habitasse platea dictumst. Nullam tempor iaculis varius.

## Local Images

{this.props.frontmatter.title}

GATSBY CONFIG
  plugins: [
{
      // keep as first gatsby-source-filesystem plugin for gatsby image support
      resolve: "gatsby-source-filesystem",
      options: {
        path: `${__dirname}/static/img`,
        name: "uploads",
      },
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        path: `${__dirname}/src/pages/blog`,
        name: "pages",
      },
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        path: `${__dirname}/src/images`,
        name: "images",
      },
    },
    {
      resolve: 'gatsby-plugin-local-search',
      options: {
          name: 'pages',
          engine: 'flexsearch',
          query:`
          query {
            allMdx(sort: { fields: [frontmatter___date], order: DESC }, filter: {frontmatter: {templateKey: {eq: "blog-post"}}}) {
              nodes {
                excerpt
                slug
                body
                frontmatter {
                  date(formatString: "MMMM DD, YYYY")
                  title
                  tags
                  featuredimage {
                    publicURL
                    childImageSharp {
                      gatsbyImageData(placeholder: DOMINANT_COLOR, layout: FULL_WIDTH)
                    }
                  }
                }
              }
            }
          }
        `,
          ref:  'slug',
          index: ['title', 'excerpt'],
          store: ['title', 'excerpt', 'slug', 'tags', 'image'],
          normalizer: ({ data }) =>
          data.allMdx.nodes.map(node => ({
              title: node.frontmatter.title,
              excerpt: node.excerpt,
              slug: node.slug,
              tags: node.frontmatter.tags,
              image: node.frontmatter.featuredimage.childImageSharp.gatsbyImageData
          })),
      }
  },
    `gatsby-plugin-react-helmet`,
    "gatsby-plugin-image",
    "gatsby-plugin-sharp",
    "gatsby-transformer-sharp",
    `gatsby-plugin-netlify`,
    `gatsby-plugin-remove-fingerprints`,
    `gatsby-plugin-styled-components`,
    {
      resolve: "gatsby-plugin-netlify-cms",
      options: {
        modulePath: `${__dirname}/src/cms/cms.js`,
      },
    },
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `Matt Site`,
        short_name: `Another site`,
        start_url: `/`,
        background_color: `#6b37bf`,
        theme_color: `#6b37bf`,
        // Enables "Add to Homescreen" prompt and disables browser UI (including back button)
        // see https://developers.google.com/web/fundamentals/web-app-manifest/#display
        display: `standalone`,
        icon: `src/images/icon.png`, // This path is relative to the root of the site.
      },
    },
    {
      resolve: `gatsby-plugin-mdx`,
      options: {
        extensions: [`.mdx`, `.md`],
        gatsbyRemarkPlugins: [
          {
            resolve: "gatsby-remark-autolink-headers",
            options:{
            icon: false
          }
        },
          {
            resolve: "gatsby-remark-relative-images",
            options: {
              staticFolderName: 'static',
            },
          },
          {
            resolve: "gatsby-remark-images",
            options: {
              // It's important to specify the maxWidth (in pixels) of
              // the content container as this plugin uses this as the
              // base for generating different widths of each image.
              maxWidth: 2048,
            },
          },
          {
            resolve: "gatsby-remark-copy-linked-files",
            options: {
              destinationDir: "static",
            },
          },
        ],
      },
    },

  ],

PACKAGE JSON
    "@babel/runtime": "^7.17.8",
    "@fontsource/anton": "^4.5.2",
    "@fontsource/epilogue": "^4.5.4",
    "@mdx-js/mdx": "^1.6.22",
    "@mdx-js/react": "^1.6.22",
    "add": "^2.0.6",
    "babel-plugin-styled-components": "^2.0.6",
    "flexsearch": "^0.7.21",
    "framer-motion": "^6.2.8",
    "gatsby": "^4.1.2",
    "gatsby-awesome-pagination": "^0.3.8",
    "gatsby-image": "^3.11.0",
    "gatsby-plugin-emotion": "^7.9.0",
    "gatsby-plugin-image": "^2.1.0",
    "gatsby-plugin-local-search": "^2.0.1",
    "gatsby-plugin-manifest": "^4.8.1",
    "gatsby-plugin-mdx": "^3.1.1",
    "gatsby-plugin-netlify": "^4.1.0",
    "gatsby-plugin-netlify-cms": "^6.8.0",
    "gatsby-plugin-react-helmet": "^5.8.0",
    "gatsby-plugin-remove-fingerprints": "^0.0.2",
    "gatsby-plugin-sharp": "^4.10.0-next.3",
    "gatsby-plugin-sitemap": "^5.8.0",
    "gatsby-plugin-styled-components": "^5.9.0",
    "gatsby-remark-autolink-headers": "^5.9.0",
    "gatsby-remark-copy-linked-files": "^5.9.0",
    "gatsby-remark-images": "^6.8.1",
    "gatsby-remark-relative-images": "^2.0.2",
    "gatsby-remark-table-of-contents": "^2.0.0",
    "gatsby-source-filesystem": "^4.8.1",
    "gatsby-transformer-remark": "^5.9.0",
    "gatsby-transformer-sharp": "^4.10.0-next.2",
    "hamburger-react": "^2.4.1",
    "netlify-cms-app": "^2.15.66",
    "netlify-cms-media-library-cloudinary": "^1.3.10",
    "netlify-cms-media-library-uploadcare": "^0.5.10",
    "react": "^17.0.1",
    "react-collapsed": "^3.3.0",
    "react-dom": "^17.0.1",
    "react-helmet": "^6.1.0",
    "react-use-flexsearch": "^0.1.1",
    "remark-slug": "^7.0.1",
    "styled-components": "^5.3.3",
    "yarn": "^1.22.17"

A: try adding this line:
const Post = ({data}) => {
    if (!data) return null; //add this

    const { frontmatter} = data.mdx
    const result = data.mdx;

data is undefined until the response of your graphql query comes back, which takes a moment. You can put in a loading screen or some skeleton blocks to render instead of null while you wait for it to load.
if (!data) return <LoadingScreen />;

some other tools that help with this (that you don't need in this case) are:
optional chaining
const result = data?.mdx

conditional rendering
{ data  &&
  return (
      <Layout>
    ...
}

Edit
If you are still struggling after trying that, maybe you should, instead of destructing props, console log all the props,
const Post = (props) => {
    console.log(props)

to inspect whether the shape of the passed props are as you expect.
If that fails too, you can try inspecting the network tab on your browser, and find out whether you are actually receiving the data from gql.


text:
Q: How to eliminate Error when installing web3.py I am attempting to install web3 on my windows machine. I am using the Visual studio code terminal to do this. I have used both commands.

*

*pip install web3

*pip3 install web3

The first error I was getting was around the Visual studios build tools which I was able to install. Now when I run the command I get this error.
ERROR: Command errored out with exit status 1: 'C:\Python310\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\ealvarado\\AppData\\Local\\Temp\\pip-install-nfyoy3t_\\cytoolz_9d52991e4515405886466c30cd8781ec\\setup.py'"'"'; __file__='"'"'C:\\Users\\ealvarado\\AppData\\Local\\Temp\\pip-install-nfyoy3t_\\cytoolz_9d52991e4515405886466c30cd8781ec\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\ealvarado\AppData\Local\Temp\pip-record-g88od3fy\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Python310\Include\cytoolz' Check the logs for full command output.
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
WARNING: You are using pip version 21.2.3; however, version 21.3 is available.
You should consider upgrading via the 'C:\Python310\python.exe -m pip install --upgrade pip' command.

A: the WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) is because at some point in time pip failed to delete some temporary folder that it make while updating or installing or something, to get rip of it just go to the folder listed and delete the folders which name start with ~.
The other warning is for you to upgrade your pip, you should do that.
And for the error, I don't know, maybe that library don't support python 3.10 yet and that is why it fail and/or your outdated pip don't fetch the most current version by virtue of being outdated

redpajama_set_name: RedPajamaStackExchange


text:
Q: Warning before leaving page - but not if route matches I have implemented the following method for warning a visitor before leaving a form:
pending-changes.guard.ts:
import { CanDeactivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

export interface ComponentCanDeactivate {
  canDeactivate: () => boolean | Observable<boolean>;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {

  // if there are no pending changes, just allow deactivation; else confirm first
  return component.canDeactivate() ?
    true :
    // NOTE: this warning message will only be shown when navigating elsewhere within your angular app;
    // when navigating away from your angular app, the browser will show a generic warning message
    // see http://stackoverflow.com/a/42207299/7307355
    confirm('WARNING: You will have to re-choose any images if you go back. Press Cancel to stay on the page, or OK to lose these changes.');
  }
}

And in my component class:
@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
  return false;
  // insert logic to check if there are pending changes here;
  // returning true will navigate without confirmation
  // returning false will show a confirm dialog before navigating away
}

This all works fine! But...
In the component I am using, there is a navigate condition:
this.router.navigate(['/thank-you', 'ads', res.data.slug]);

How can I let my app navigate to "/thank-you" without causing the "Warning" as at this point the form has been submitted.
Thanks

A: You can just insert in the canDeactive hostListener, logic to check if the form is being submitted.
If you have a button for submitting the form, just set some private field formBeingSubmitted to true when it's clicked and then check for it in the logic.
private formBeingSubmitted = false;
@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
  if(this.formBeingSubmitted){
  return true
  }
  return false;
  // insert logic to check if there are pending changes here;
  // returning true will navigate without confirmation
  // returning false will show a confirm dialog before navigating away
}

public onSubmit(){
  this.formBeingSubmitted = true;
}


text:
Q: The name timeLabel does not exist in current context I am using VS 2015 and my coding language is C#. I am trying to create a simple web site in aspx that produces the server time and allows you to change the colors of the clock. Anyways, I have this error that says "The name timeLabel does not exist in the current context" Here is my code so far.
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebTime.aspx.cs" Inherits="Web.WebTime" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Server Time</title>

          Current time on the Web server:

          02:55:28

          New background color:
          <asp:DropDownList ID="backColorDropDownList" runat="server" AutoPostBack="True">
             <asp:ListItem>Black</asp:ListItem>
             <asp:ListItem>White</asp:ListItem>
             <asp:ListItem>Blue</asp:ListItem>
             <asp:ListItem>Red</asp:ListItem>
             <asp:ListItem>Green</asp:ListItem>
             <asp:ListItem>Purple</asp:ListItem>
             <asp:ListItem>Yellow</asp:ListItem>
          </asp:DropDownList>

          New foreground color:
          <asp:DropDownList ID="foreColorDropDownList" runat="server" AutoPostBack="True">
             <asp:ListItem>Yellow</asp:ListItem>
             <asp:ListItem>Black</asp:ListItem>
             <asp:ListItem>White</asp:ListItem>
             <asp:ListItem>Blue</asp:ListItem>
             <asp:ListItem>Red</asp:ListItem>
             <asp:ListItem>Green</asp:ListItem>
             <asp:ListItem>Purple</asp:ListItem>
          </asp:DropDownList>

          New font size:
          <asp:DropDownList ID="fontSizeDropDownList" runat="server" AutoPostBack="True">
             <asp:ListItem>24</asp:ListItem>
             <asp:ListItem>22</asp:ListItem>
             <asp:ListItem>20</asp:ListItem>
             <asp:ListItem>18</asp:ListItem>
             <asp:ListItem>16</asp:ListItem>
          </asp:DropDownList>

Here is my CodeBehind file too:
// Code-behind file for a page that displays the current time
// and updates properties based on user input.
using System;
using System.Drawing;

namespace Web
{
    public partial class WebTime : System.Web.UI.Page
    {
        // initializes the contents of the page
        protected void Page_Init(object sender, EventArgs e)
        {
            // display the server's current time in timeLabel
            timeLabel.Text = DateTime.Now.ToString("hh:mm:ss");
        } // end method Page_Init

        // when loading due to a postback, Page_Load modifies
        // the Label's properties based on user input
        protected void Page_Load(object sender, EventArgs e)
        {
            // if this is a postback, process user input
            if (IsPostBack)
            {
                // retrieve the values submitted by the user
                string backColor = backColorDropDownList.SelectedItem.Text;
                string foreColor = foreColorDropDownList.SelectedItem.Text;
                int fontSize =
                   Convert.ToInt32(fontSizeDropDownList.SelectedItem.Text);

                // modify timeLabel based on the user's selections
                timeLabel.BackColor = Color.FromName(backColor);
                timeLabel.ForeColor = Color.FromName(foreColor);
                timeLabel.Font.Size = fontSize;
            } // end if
        }
    }
}

The errors happen in my CodeBehind file.
"timeLabel", "backColorDropDownList", "foreColorDropDownList", and "fontSizeDropDownList" have the errors.
any help would be much appreciated!

A: You should encapsulate the asp controls inside a form element:

...

  <form runat="server">

          Current time on the Web server:

          02:55:28

          New background color:
          <asp:DropDownList ID="backColorDropDownList" runat="server" AutoPostBack="True">
             <asp:ListItem>Black</asp:ListItem>
             <asp:ListItem>White</asp:ListItem>
             <asp:ListItem>Blue</asp:ListItem>
             <asp:ListItem>Red</asp:ListItem>
             <asp:ListItem>Green</asp:ListItem>
             <asp:ListItem>Purple</asp:ListItem>
             <asp:ListItem>Yellow</asp:ListItem>
          </asp:DropDownList>

          New foreground color:
          <asp:DropDownList ID="foreColorDropDownList" runat="server" AutoPostBack="True">
             <asp:ListItem>Yellow</asp:ListItem>
             <asp:ListItem>Black</asp:ListItem>
             <asp:ListItem>White</asp:ListItem>
             <asp:ListItem>Blue</asp:ListItem>
             <asp:ListItem>Red</asp:ListItem>
             <asp:ListItem>Green</asp:ListItem>
             <asp:ListItem>Purple</asp:ListItem>
          </asp:DropDownList>

          New font size:
          <asp:DropDownList ID="fontSizeDropDownList" runat="server" AutoPostBack="True">
             <asp:ListItem>24</asp:ListItem>
             <asp:ListItem>22</asp:ListItem>
             <asp:ListItem>20</asp:ListItem>
             <asp:ListItem>18</asp:ListItem>
             <asp:ListItem>16</asp:ListItem>
          </asp:DropDownList>

 </form>

...

A: I am not sure why are you getting an error on something as simple as this.Still just paste the below code to display the current time and see

Current time on the Web server:

      <asp:Label ID="timeLabel" runat="server"></asp:Label>

and let me know what error message that comes up


text:
Q: In Android 4.0 Navigation Bar hijack first touch event In Android 4.0 on devices without hardware navigation keys, Android will render navigation bar.
You can hide it, if you want by using setSystemUiVisibility().
If that is done, lets say if you want to get as much screen as possible for playback, when you first touch screen (and yes, on View you implement View.onTouchEvent()), first touch will be hijacked by Android and your API will not be called. Only once navigation bar is visible it will be called.
Now, that can be avoided by also listening to:
http://developer.android.com/reference/android/view/View.OnSystemUiVisibilityChangeListener.html
and when navigation bar is visible just do what you will do on first touch.
Is there any other way to do the same, that will say Android 4.0 to propagate touch event to my app once Navigation bar is done with it?

A: No, the system always consumes the first touch that brings the navigation bar back. You should only hide the navigation bar if your app is in a non-interactive state such as video playback.

A: In ICS you need to use listener.


text:
Q: the meaning of "but neither survived her"? What is the meaning of the following bolded expression? What is the structure of it?

She assembled an all-female company at this time and established a
  school around 1908, but neither survived her.

A: if you are survived by someone, they are still alive after you have died
Santos is survived by his wife of 49 years
What author meant is that both companies did not stay active after her death.


text:
Q: ISSUU change the default 'Click to read' text on a PDF Like in the topic: Is there a way to change this text? When I embed the code on my site the generated structure is flash and I can't access it. The only exception is the Chromium Browser which generates  element and I can change the text via JS. But can I do something with the flash content or change this text somewhere on the issuu account page before publishing the content?

A: You can customize the Issuu viewer, haven't tryed it yet, but have a look at these pages, they should point you in the right direction:
http://developers.issuu.com/customize/
Especially changing language and stuff shouldn't be too hard.


text:
Q: Skip First Column in CSV File with Pandas I have a csv file that is generated that has some information in the first line. I'm trying to skip it but it doesn't seem to work. I tried looking at several suggestions and examples.
I tried using skiprows.
I also looked at several other examples.
Pandas drop first columns after csv read
https://datascientyst.com/pandas-read-csv-file-read_csv-skiprows/
Nothing I tried worked the way I wanted it.
When I got it to work it deleted the entire row.
Here is a sample of the code
# Imports the Pandas Module. It must be installed to run this script.
import pandas as pd

# Gets source file link
source_file = 'Csvfile.csv'

# Gets csv file and encodes it into a format that is compatible.
dataframe = pd.read_csv(source_copy, encoding='latin1')

df = pd.DataFrame({'User': dataframe.User, 'Pages': dataframe.Pages,  'Copies': dataframe.Copies,
                   'Color': dataframe.Grayscale, 'Duplex': dataframe.Duplex, 'Printer': dataframe.Printer})

# Formats data so that it can be used to count Duplex and Color pages.
df.loc[df["Duplex"] == "DUPLEX", "Duplex"] = dataframe.Pages
df.loc[df["Duplex"] == "NOT DUPLEX", "Duplex"] = 0
df.loc[df["Color"] == "NOT GRAYSCALE", "Color"] = dataframe.Pages
df.loc[df["Color"] == "GRAYSCALE", "Color"] = 0
df.sort_values(by=['User', 'Pages'])

file = df.to_csv('PrinterLogData.csv', index=False)

# Opens parsed CSV file.
output_source = "PrinterLogData.csv"
dataframe = pd.read_csv(output_source, encoding='latin1')

# Creates new DataFrame.
df = pd.DataFrame({'User': dataframe.User, 'Pages': dataframe.Pages,  'Copies': dataframe.Copies,
                   'Color': dataframe.Color, 'Duplex': dataframe.Duplex, 'Printer':
dataframe.Printer})

# Groups data by Users and Printer Sums
Report1 = df.groupby(['User'], as_index=False).sum().sort_values('Pages', ascending=False)
Report2 = (df.groupby(['Printer'], as_index=False).sum()).sort_values('Pages', ascending=False)

Sample Data

Sample Output of what I'm looking for.

A: This is an early draft of what you appear to want for your program (based on the simulated print-log.csv):
import csv
import itertools
import operator
import pathlib

CSV_FILE = pathlib.Path('print-log.csv')
EXTRA_COLUMNS = ['Pages', 'Grayscale', 'Color', 'Not Duplex', 'Duplex']

def main():
    with CSV_FILE.open('rt', newline='') as file:
        iterator = iter(file)
        next(iterator)  # skip first line if needed
        reader = csv.DictReader(iterator)
        table = list(reader)
    create_report(table, 'Printer')
    create_report(table, 'User')

def create_report(table, column_name):
    key = operator.itemgetter(column_name)
    table.sort(key=key)
    field_names = [column_name] + EXTRA_COLUMNS
    with pathlib.Path(f'{column_name} Report').with_suffix('.csv').open(
        'wt', newline=''
    ) as file:
        writer = csv.DictWriter(file, field_names)
        writer.writeheader()
        report = []
        for key, group in itertools.groupby(table, key):
            report.append({column_name: key} | analyze_group(group))
        report.sort(key=operator.itemgetter('Pages'), reverse=True)
        writer.writerows(report)

def analyze_group(group):
    summary = dict.fromkeys(EXTRA_COLUMNS, 0)
    for row in group:
        pages = int(row['Pages']) * int(row['Copies'])
        summary['Pages'] += pages
        summary['Grayscale'] += pages if row['Grayscale'] == 'GRAYSCALE' else 0
        summary['Color'] += pages if row['Grayscale'] == 'NOT GRAYSCALE' else 0
        summary['Not Duplex'] += pages if row['Duplex'] == 'NOT DUPLEX' else 0
        summary['Duplex'] += pages if row['Duplex'] == 'DUPLEX' else 0
    return summary

if __name__ == '__main__':
    main()


text:
Q: How i can make this function in javascript i am in a bootcamp and i got stuck here, i tried to do it by myself and it didn't worked, then i copy and paste the code that the mentor wrote, and is not working also for some reason, i should get a random color into the gamePattern variable.. any ideas ?
Thank you.
var buttonColours = ["red", "blue", "green", "yellow"];

var gamePattern = [];

function nextSequence() {

  var randomNumber = Math.floor(Math.random() * 4);
  var randomChosenColour = buttonColours[randomNumber];
  gamePattern.push(randomChosenColour);

A: First of all, in your code nextSequence is missing a closing bracket } and you would need call the function nextSequence() at the end to actually execute your logic.
However, I'd recommend to avoid functions that change values of the global scope because this easily becomes a pitfall for untraceable errors and application behavior. Therefore, I'd recommend to have this helper function randomChoiceFromList that gives you a random item from a list. Furthermore, as it is more abstract it is potentially reusable.

var buttonColours = ["red", "blue", "green", "yellow"];
var gamePattern = [];

function randomChoiceFromList(list) {
  const randomNumber = Math.floor(Math.random() * (list.length));
  return list[randomNumber];
};

gamePattern.push(randomChoiceFromList(buttonColours));
console.log(gamePattern);


text:
Q: CSS overflow issue in Firefox I have a table coded as follows;

Some content ...Some content ...Some content ...Some content ...Some content ...

The CSS is as follows;
    td.weekend_days .blockout_text {
        margin-top: 14px;
    }
    .blockout_text {
        margin-top: 25px;
        padding: 3px;
        text-align: center;
    }

    #c_month_tbl{
        clear: both;
        width: 678px;
    }
    .block_out {
    height: 50px;
}

Now the layout appears fine if the content inside the td is less...But if there is more content, IE kind of expands the cell width/height and displays the content fine.
But in Firefox, the width/height for the content div remains fixed and does not expand as per the content, which makes the layout appear a bit broken..
I tried changing the overflow property for the containing td/div element , but it is not working fine in Firefox.
Please help me. Thank you.

A: Remove the class .blockout, or remove the height restriction on it. If you want it to be at least 50px tall, use min-height instead.


text:
Q: Publish of Database Project fails because deployment script attempts to drop and re-create an unmodified table I'm using Visual Studio 15.8.5 with Sql Server Data Tools 15.1.
I've created an SQL Server database project and imported the schema of an already existing database. I've made several minor changes to a few tables of the database and published the updates to the development database without any problems.
After adding a few SQL scripts to the project, all of them with:
Build Action = None

publish fails, despite no changes have been made in any of the database objects of the project.
This is the part of the auto-generated publish script that causes the problem:
/*
The table [lut].[KAE] is being dropped and re-created since all
non-computed columns within the table have been redefined.
*/

IF EXISTS (select top 1 1 from [lut].[KAE])
    RAISERROR (N'Rows were detected. The schema update is terminating
because data loss might occur.', 16, 127) WITH NOWAIT

GO

Table [lut].[KAE] has not been changed, though. One of the scripts is redefining its schema but this should make no difference since this is a 'No Build' script.
What am I possibly doing wrong here?
Edit:
I've done a schema comparison as @MadBert advised. I originally used my actual database as source and my sql server visual studio project as target. No differences were found.
I then switched source and target databases and compared again. The following 'difference' was detected.

As you can see this is not an actual difference, it looks like a Visual Studio bug in schema comparison. Any ideas on how I could circumvent this behavior?

A: It turned out that a refactor log file was the culprit.
I tried to publish to an empty database, as @Ogglas wisely advised. I noticed that during publish I was getting the following message:

The following operation was generated from a refactoring log file
  8e659d92-10bb-4ce9-xxxx-xxxxxxxxx Rename [lut].[KAE].[xxxxx] to
  $$$$$$$$$ Caution: Changing any part of an object name could
  break scripts and stored procedures.

I then noticed that my SQL Server Database project contained a .refactorlog file

It seems that this log file was generated after I changed the offending table schema. The schema of the table was later reverted to its original state but the log file remained.
I deleted this log file and after that publish finally succeeded!

A: Had a similar problem when a SQL Server Database project was set to the wrong Target platform. Edit this in project properties to match the target server. Initiate a schema compare again by right clicking on the project and select Schema Compare....

Also check if Ignore whitespace is marked in Schema Compare Options. If you still have a difference one way or another try pasting the text in Notepad++ with Show All Characters on and see if you can spot a difference.
If you still can't find any difference, try creating a new database from the project and use SSMS GUI to compare. Does the table have the same Lock Escalation settings etc?


text:
Q: SSH connection from Outside (Dual-Stack lite) I would like to set a SSH connection to my Raspberry Pi via PuTTY while i am not in my local network.
I have:
A: A PC (outside my Network)
B: A virtual Server ubuntu 18.04 with a static IPv4 adress (outside my network)
C: Raspberry Pi 4, Raspbian Buster (home network)
How can I make a SSH Tunnel between:
A->B (I think this would be a IPv4 connection via PuTTY)
B->C (?..I can only adress the IPv6 IP of my Raspberry)
The Port for SSH on RPI is Port 1249.
The Firewall-Settings in my router has been set.
Since my router has only external IPv6 IP-Adress (Dual-Stack), I have rent a vserver with a static IPv4 adress which is outside my network. The vserver is changing the IPv4 requests into IPv6 via 6tunnel (4to6). That makes it possible to reach my cloud server trough my router and I dont need to use a DynDNS service.
I have read the topics about SSH forwarding. But I dont know how
to solve it with the Dual-Stack problem.
If you need more Info pls let know.
Thx for your help.


text:
Q: Limiting rate of requests with Reactor I'm using project reactor to load data from a web service using rest. This is done in parallel with multiple threads. I'm starting to hit rate limits on the web service, so I would like to send at most 10 requests per second to avoid getting these errors. How would I do that using reactor?
Using zipWith(Mono.delayMillis(100))? Or is there some better way?
Thank you

A: You can use delayElements instead of the whole zipwith.

A: One could use Flux.delayElements to process a 10 requests batch at every 1s; be aware though that if the processing takes longer than 1s the next batch will still be started in parallel hence being processed together with the previous one (and potentially many other previous ones)!
That's why I propose another solution where a 10 requests batch is still processed at every 1s but, if its processing takes longer than 1s, the next batch will fail (see overflow IllegalStateException); one could deal with that failure such that to continue the overall processing but I won't show that here because I want to keep the example simple; see onErrorResume useful to handle overflow IllegalStateException.
The code below will do a GET on https://www.google.com/ at a rate of 10 requests per second. You'll have to do additional changes in order to support the situation where your server is not able to process in 1s all your 10 requests; you could just skip sending requests when those asked at previous second are still processed by your server.
@Test
void parallelHttpRequests() {
    // this is just for limiting the test running period otherwise you don't need it
    int COUNT = 2;

    // use whatever (blocking) http client you desire;
    // when using e.g. WebClient (Spring, non blocking client)
    // the example will slightly change for no longer use
    // subscribeOn(Schedulers.elastic())
    RestTemplate client = new RestTemplate();

    // exit, lock, condition are provided to allow one to run
    // all this code in a @Test, otherwise they won't be needed
    var exit = new AtomicBoolean(false);
    var lock = new ReentrantLock();
    var condition = lock.newCondition();

    MessageFormat message = new MessageFormat("#batch: {0}, #req: {1}, resultLength: {2}");
    Flux.interval(Duration.ofSeconds(1L))
            .take(COUNT) // this is just for limiting the test running period otherwise you don't need it
            .doOnNext(batch -> debug("#batch", batch)) // just for debugging
            .flatMap(batch -> Flux.range(1, 10) // 10 requests per 1 second
                            .flatMap(i -> Mono.fromSupplier(() ->
                                    client.getForEntity("https://www.google.com/", String.class).getBody()) // your request goes here (1 of 10)
                                    .map(s -> message.format(new Object[]{batch, i, s.length()})) // here the request's result will be the output of message.format(...)
                                    .doOnSubscribe(s -> debug("doOnSubscribe: #batch = " + batch + ", i = " + i)) // just for debugging
                                    .subscribeOn(Schedulers.elastic()) // one I/O thread per request
                            )
            )
            // consider using onErrorResume to handle overflow IllegalStateException
            .subscribe(
                    s -> debug("received", s) // do something with the above request's result
                    e -> {
                        // pay special attention to overflow IllegalStateException
                        debug("error", e.getMessage());
                        signalAll(exit, condition, lock);
                    },
                    () -> {
                        debug("done");
                        signalAll(exit, condition, lock);
                    }
            );

    await(exit, condition, lock);
}

// you won't need the "await" and "signalAll" methods below which
// I created only to be easier for one to run this in a test class

private void await(AtomicBoolean exit, Condition condition, Lock lock) {
    lock.lock();
    while (!exit.get()) {
        try {
            condition.await();
        } catch (InterruptedException e) {
            // maybe spurious wakeup
            e.printStackTrace();
        }
    }
    lock.unlock();
    debug("exit");
}

private void signalAll(AtomicBoolean exit, Condition condition, Lock lock) {
    exit.set(true);
    try {
        lock.lock();
        condition.signalAll();
    } finally {
        lock.unlock();
    }
}


text:
Q: В чем разница между WHERE и HAVING в PostgreSQL? Какая разница в поведении при использовании в запросе к таблице PostgreSQL ключевых слов WHERE и HAVING?

A:
Основное отличие WHERE от HAVING заключается в том, что WHERE сначала выбирает строки, а затем группирует их и вычисляет агрегатные функции (таким образом, она отбирает строки для вычисления агрегатов), тогда как HAVING отбирает строки групп после группировки и вычисления агрегатных функций. Как следствие, предложение WHERE не должно содержать агрегатных функций; не имеет смысла использовать агрегатные функции для определения строк для вычисления агрегатных функций. Предложение HAVING, напротив, всегда содержит агрегатные функции. (Строго говоря, вы можете написать предложение HAVING, не используя агрегаты, но это редко бывает полезно. То же самое условие может работать более эффективно на стадии WHERE.)

— Документация PostgreSQL 9.6: Aggregate functions (она же на русском)

A: HAVING аналогичен WHERE за исключением того, что строки отбираются не по значениям столбцов, а строятся из значений столбцов, указанных в GROUP BY, и значений агрегатных функций, вычисленных для каждой группы, образованной GROUP BY.


text:
Q: I am getting an error while trying to create a database in Phpmyadmin. (No Privileges) I tried to change my administrator password. But I was not successful. When I try this, I get this error :

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

The operating system I use :
Linux version 4.18.0-parrot10-amd64 (team@parrotsec.org) (gcc version 7.3.0 (Debian 7.3.0-29)) #1 SMP Debian 4.18.10-1parrot10 (2018-10-06)


text:
Q: Quantum Mechanics is $U(1)$ invariant, hence $X$ is isotropic? Since our fundamental laws are invariant under rotations. Hence, we say that spacetime isotropic.
Now Quantum Mechanics is invariant under (global) complex rotations ($U(1)$ transformations. Hence, we say that $X$ is isotropic.
In other words, what is the correct analogous space $X$ here and is "isotropic" the correct term used?

A: First of all, the space $X$ here is the Hilbert space $\mathcal H$ of the system, since the $U(1)$ transformations apply to the state vector $|\psi\rangle \in \mathcal H$ of the system. "Isotropic" is not the correct term to describe the symmetry. The term "isotropic" could maybe be used if $\mathcal H \cong \mathbb C^N$ were symmetric under $SU(N)$ transformations, but I don't think this is a common terminology (also, such a system would be very boring). Instead, this is called a (global) $U(1)$ gauge symmetry.
Let me make two more comments. First, the two symmetries here have an important fundamental difference. The $SO(3)$ symmetry of mechanics compares actual, physically different system states (different rotations of the physical system). However, the $U(1)$ symmetry of quantum mechanics is a gauge symmetry, meaning: The two states $|\psi\rangle$ and $e^{i\varphi} |\psi\rangle$ are the exact same physical state, but our description of the system allows that same state to be described with many different Hilbert space vectors. (This is for convenience only, the actual state space is $\mathcal H / \mathbb C^\ast$, but it is easier to work with $\mathcal H$.)
Second, the Noether theorem states that every symmetry corresponds to a conserved quantity. The conserved quantity corresponding to the $SO(3)$ symmetry of mechanics is angular momentum, but what is that of the $U(1)$ gauge symmetry? Once you learn about QED, you will see that it is the total electrical charge.

A: In analogy with the more common notion "isospin space", I would say the corresponding space for $U(1)$ gauge symmetry is "charge space".
For example, one book which uses this notion is Particle Astrophysics by Donald H. Perkins.


text:
Q: The distance between orthogonal matrices induced by the Frobenius norm An orthogonal matrix is a matrix $A$ over the reals such that $A^t=A^{-1}$ (its transpose is its inverse). The Frobenius norm over $n\times n$ real matrices is given by $\|A\| = \sqrt{trace(A^tA)}$.
I have come across the following claim: The distance (induced by the Frobenius norm) between any two (non equal) orthogonal matrices is $\sqrt{n}$. I can't find a proof for this claim, but no refutation either (of course, if the difference between two orthogonal matrices is itself an orthogonal matrix the claim is clear, but I don't know if that's true either).

A: I don't think this is true. Let $A=I_2$ and $B$ be 2 by 2 matrix with $b_{11}=b_{22}=0$ and $b_{12}=b_{21}=1$. Then both these matrices are orthogonal but
and $||A-B||_F = 2\neq \sqrt{2}$
An even easier counterexample:
Let $A=1$ and $B=-1$ the 1 by 1 orthogonal matrices. Then $A-B=2$ so $||A-B||_F=2\neq 1$.

A: I don't know where you found your claim, but it seems that the distance induced by the Frobenius norm between any two orthogonal matrices can be any real number.
Because:
$$
\begin{align}
\|A - B\|^2 &= \mathrm{tr} \left( (A-B)^t (A-B)    \right) \\
            &= \mathrm{tr} \left( (A^t -B^t) (A-B)  \right)  \\
            &= \mathrm{tr} (A^tA -A^tB - B^tA + B^tB)    \\
            &= \mathrm{tr} (2I) - \mathrm{tr}(2A^tB)  \\
            &= 2n - 2\mathrm{tr}(A^tB)
\end{align}
$$
The last but one equality is due to the fact that $A^tA = B^tB = I$ and $(B^tA)^t = A^tB$ and a matrix and its transpose have the same trace.
Now, take $A = I$ and we've got
$$
\| I - B\|^2 = 2n - 2\mathrm{tr}(B)
$$
for any orthogonal matrix $B$. So, if you take as $B$ the family of orthogonal matrices
$$
\begin{pmatrix}
\cos\theta  &  -\sin\theta \\
\sin\theta  &  \cos\theta
\end{pmatrix} \ ,
$$
$\theta \in [0, 2\pi]$, their traces $\mathrm{tr} (B) = 2\cos\theta$ can be any real number between $-2$ and $2$. So, their Frobenius distances to the unit matrix $I$ can be any real number from $0$ to $\sqrt{8}$.

A: If the distance is defined as $$d(X,Y) = \sqrt{\textrm{trace}(X^{\top}Y)}$$ then it follows from the fact you can write the Frobenius norm as $$\Vert A \Vert_{F}^{2} = \sum_{i,j} |a_{ij}|^{2}$$ since $X^{\top}Y$ is orthogonal if X,Y are and an orthogonal matrix has as its columns (or rows) 3 orthonormal vectors and so their squared norms are each 1 and so their sum is n and so their Frobenius norm is $\sqrt{n}$.
The difference between elements of a group wouldn't be defined by treating them as if they belong to a vector space (or have addition/subtraction defined on them at least). Orthogonal matrices form a group so their combination must be under that binary operation. This is why commutators for abelian groups (well all groups but the abelian ones have the appropriate right hand side for the point I'm making) are written as $$[X,Y] = XYX^{-1}Y^{-1} = e$$ and not $XY - YX = 0$. If X,Y belong to both a group and a separate ring then you can reshuffle $XY-YX=0$ into $XY=YX$ then $XYX^{-1}Y^{-1} = 1 \cong e$ but that's meaningless if X,Y do not have addition/subtraction defined on them. Sure, a matrix representation easily does so but that isn't forming a representation of the underlying group then.


text:
Q: Modifying main Activities grid view in CRM 4.0 using JavaScript I have a task to change envelope icons on the main Activities view page (Work Place, My Work -> Activities) for every row in the grid, depending on the custom status of the row in crm 4.0. I need to do it using JavaScript. Does anybody know if there is a way to do that and where should the JavaScript code be placed?  I am assuming that I need to intercept grid onLoad event, go through the grid, check the condition and flip the url of the icon. But I cannot figure out how to hook into that event...
Thanks very much!
I got several very useful advices and here is what I got so far.
1. I added SiteMap to load a custom page, instead of default one (/workplace/home_activities.aspx)
2. Here is the code of the custom page, placing onreadystatechange in the html was the only way I could get this function to run. Do not know why.

HTML>
HEAD>
TITLE>
script language="javascript" type="text/javascript">
function Run()
{
 var objIframe = getIframe();

   if(objIframe.readyState == "complete")
   {
    var docFrame = objIframe.contentWindow.document;
    var grid = docFrame.getElementById("crmGrid");

    var allRecords = grid.InnerGrid.AllRecords;

    for(var i=0; i

function getIframe()
{
   return document.getElementById("wraperActivitiesFrame");
}

/script>
/HEAD>
body >

  iframe id="wraperActivitiesFrame" src="/workplace/home_activities.aspx" WIDTH="100%" HEIGHT="100%" onreadystatechange="Run()">
/HTML>

The issue I am having now is that the function does not run again when I try to page the grid. I have 2 pages of Activities; when the page loads for the first time - I have my alert boxes, but when I click on "page 2" arrow - nothing happens. Why??? What I am doing wrong?

A: You kinda can hook into that event. You create a "wrapper" HTML page that you load in CRM instead of the default activities grid via Sitemap. This wrapper contains a full-size IFrame in which you load the actual grid, and in the IFrame's onreadystatechange handler (for readyState == 4), you traverse the grid's DOM (jQuery might make this a little easier, but I haven't used jQuery much myself) and do whatever changes you need to do (that means the JavaScript goes within the wrapper HTML page). If you call this via setInterval and put a try-catch around it, this will even be safe against grid refreshes and browsing through the pages.


text:
Q: How to remove the unused constants from the generated Java class file I often use constants in my Java programs, however when taking a look at a decompiled Java class file, I noticed that all the constant's uses throughout the program was replaced by their literal values, while the original declarations and assignments at the top of the class was still present, I'm wondering if these variables are just sitting there wasting memory since they're not being used anywhere in the file. and if there's a way to restrict constants only to compile time and have them removed after the class file is generated.

A: The compiler is smart enough to use memory efficiently in this kind of case. And, even let's suppose that you did have wasted memory per constant, let's do a thought experiment on how much 'space' that may be, realistically.
Let's say we had a mixture of string, int, and other basic types. Each char in a string is 2 bytes in java, and an int is 4 bytes. Let's say we had 75,000 char constants and 25,000 int constants.
That is 75k * 2 so 150k bytes or ~150 kilobytes of memory for the string constants
For the ints that is 25k * 4 or 100k, so ~100 kilobyte of memory.
So a total of ~250kb.
The most basic computer you can buy these days has a minimum of 4gb of ram, more likely 8gb to 16gb.
So 250kb / 4000000kb * 100 = 0.00625% of the lowest spec modern computer.
Now if you are running some microcontroller or other limited hardware, it maaay be something, but even then it is doubtful and you probably aren't using java.
As a general rule of thumb, compilers and interpreters tend to be pretty good at their job, and trusting them to do the right thing most of the time, for most programmers and programs is good enough.
There are times when certain patterns, such as massive creation of new objects, then triggering garbage collection or other issues like that can have large performance impacts.
The key is to know where actual bottlenecks and gotchya's are within a language/computer/use patterns.
It does get more complicated once we move into the distributed space and massive scale - but again unless you are working in that kind of environment, you generally don't need to consider it.
Focus your expectations on your use case, and if you are optimizing for a 10 millisecond gain for something only a few people use, it's probably a waste of time - unless you are doing it for fun.


text:
Q: Why doesn't (*3) `map` (+100) work in Idris? In Haskell, functions are functors and the following code works as expected:
(*3) `fmap` (+100) $ 1

The output is 303 of course. However, in Idris (with fmap -> map), it gives the following error:

Can't find implementation for Functor (\uv => Integer -> uv)

To me this seems like functions aren't implemented as functors in Idris, at least not like they are in Haskell, but why is that?
Furthermore, what exactly does the type signature (\uv => Integer -> uv) mean? It looks like some partially applied function, and that's  what would be expected from a functor implementation, but the syntax is a bit confusing, specifically what \ which is supposed to be used for a lambda/literal is doing there.

A: Functor is an interface.  In Idris, implementations are restricted to data or type constructors, i.e. defined using the data keyword.  I am not an expert in dependent types, but I believe this restriction is required—practically, at least—for a sound interface system.
When you ask for the type of  \a => Integer -> a at the REPL, you get
\a => Integer -> a : Type -> Type

In Haskell we would consider this to be a real type constructor, one that can be made into an instance of type classes such as Functor.  In Idris however, (->) is not a type constructor but a binder.
The closest thing to your example in Idris would be
((*3) `map` Mor (+100)) `applyMor` 1

using the Data.Morphisms module.  Or step by step:
import Data.Morphisms

f : Morphism Integer Integer
f = Mor (+100)

g : Morphism Integer Integer
g = (*3) `map` f

result : Integer
result = g `applyMor` 1

This works because Morphism is a real type constructor, with a Functor implementation defined in the library.


text:
Q: How to connect listbox to table c# winforms I have a table and a form with a listBox1.
I want values from one column from the table will be displayed in the listBox1.
For example:
the table columns: Id , Name , Phone
the table rows:
        1 , abc , 123

        2 , atg , 124

        24 , awt, 155

in the listBox1:
         1

         2

         24

and I also need to know on which one did I clicked from the listBox1.
For example: I clicked on the '24' in the listBox1 and the value '24' will show in textBox1

A: Did you set these properties?
listBox1.DataSource = yourTable;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "ID";

In this way, your listbox will show the column name, but when you click an item you could get the value (ID) associated with that name
    private void ListBox1_SelectedValueChanged(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex != -1)
        {
            int personID = Convert.ToInt32(listBox1.SelectedValue.ToString());
            .......
        }
    }


text:
Q: Java EE 6 annotation @WebServlet is not working with embedded tomcat 8 I m trying to use web application with Embedded tomcat 8 without web.xml.
But I am not able to access the application by hitting the url http://localhost:8085/Servlet_Basic/index.jsp from browser.
Neither I am able to access the servlet by hitting the url http://localhost:8085/Servlet_Basic/hello from browser.
Here is my source code :
pom.xml dependencies
<properties>
    <tomcat.version>8.5.23</tomcat.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>14</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-core</artifactId>
        <version>${tomcat.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <version>${tomcat.version}</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.jdt.core.compiler</groupId>
        <artifactId>ecj</artifactId>
        <version>4.6.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-logging-juli</artifactId>
        <version>8.5.2</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>

</dependencies>

HelloServlet.java
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public HelloServlet() {
        super();
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n";
        out.println(docType + "\n" + "<TITLE>Hello</TITLE>\n" + "\n" + "
My First Servlet
\n" + "");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

App.java
public class App {

    public static void main(String[] args) throws LifecycleException {

        int port = 8085;
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(port);

        StandardServer server = (StandardServer) tomcat.getServer();
        AprLifecycleListener listener = new AprLifecycleListener();
        server.addLifecycleListener(listener);

        String docBase = "D:\\Servlet_Basic\\src\\main\\webapp";
        Context context = tomcat.addWebapp("/Servlet_Basic", docBase);
        context.setAddWebinfClassesResources(true);
        tomcat.start();
        System.out.println("Tomcat server started at port " + port);
        tomcat.getServer().await();
    }
}

src/main/webapp contents :

index.jsp

Hello World

How can I access the application and invoke servlet annotated with @WebServlet
annotation in embedded tomcat without using web.xml  ?
Basically I want to use web application with embedded tomcat without web.xml and without explicitly configuring servlets using tomcat.addServlet() method.
Instead I would like to configure servlet using @WebServlet annotation


text:
Q: How to upgrade package.json or react libraries automatically? How to upgrade packages in react application automatically using commands? I don't want to manually check every library in package.json and check its latest version. I want to upgrade my package.json at one shot.

A: npm i -g npm-check-updates
ncu -u
npm install

Looks like npm-check-updatesis the only way to make this happen now.

A:
Upgrading libraries, frameworks in Javascript project is surely a tiresome and complex process. However, it has much more benefits in the long run and stability .

Here are the main reasons why upgrading libraries are important:

*

* New features: Most dependencies have a clear roadmap for new features.

* Performance improvements: In addition to new features, performance improvements are also made frequently.

* Fixed bugs: Although it is normal to find bugs in libraries that you depend on, patch releases help fix these issues.

* Security patches: Security patches are one of the most important reasons to have your libraries up-to-date.
The manual process is too tiresome as you need to check for the latest version of each package. So make it easier we will be using two separate methods.
Using npm-check-updates

npm-check-updates upgrades your package.json dependencies to the latest versions, ignoring specified versions.

Please follow the steps below -

*

*Install npm-check-updates

*Run npm-check-updates to list what packages are out of date

*Run npm-check-updates -u to update all the versions in your package.json

*Run npm update as usual to install the new versions of your packages based on the updated package.json
If you do not want to install npm-check-updates in machine, you can follow the steps below-

*

*run npx npm-check-updates (This will list down all the outdated packages in package.json)

*Run ncu -u to upgrade package.json

*npm install to install the packages
 Check your project by running the application and verifying the up-gradation. There might be issues in your code that might as part of up-gradation. In such scenario please check the release notes of the package and make the due changes in code.


text:
Q: computing cartesian coordination from image pixel I have a robot arm that moves within a cartesian space. And I have a camera over that space.
I need to compute, given a pixel in the image of the camera, its equivalents in cartesian space.
Do i need calibration of the camera? And how can I use it if yes?


text:
Q: How to declare ES6 iterable callback (delegate) in typescript I'm declaring my delegates/callbacks as:
export interface SomeDelegate {
    (): void;
}

however I have no clue how to declare iterable callback
export interface SomeDelegate {
    function *(): Iterable<any>;
}

Any ideas?
Thank you in advance!

A: Ok, it seems that you can declare ordinary delegate that returns Iterator and have it assigned with generator function...


text:
Q: How to separate a column containing multiple values per row into many columns Goodmorning everyone.
I have a big dataframe, in particular I have a column (a list) containing from 5 to 15 elements. I would like to divide it into many
columns how many are the elements of each row of the column.
    A                  B                 JHON
   GREEN    c("abc", "def", "ghi")       yellow
   RED      c("123", "456", "789")       blue
   JACK     d("rgy", "bob", "pbc")       pink

I would like to achieve such a thing
    A          B       C       D    JHON
  GREEN       abc      def    ghi   yellow
  RED         123      456    789   blue
  JACK        rgy      bob    pbc   pink

ah <- c("A", "B", "C")

separate(df , unlist(df$B), ah )

i tried to set such a thing but i get the error below
Errore: Must extract column with a single valid subscript.
x Subscript `var` has size 5322 but must be size 1.

Thanks in advance to anyone who can help me.
I add the column of my interest
 ProductGallery = list(
    c("http://images.icecat.biz/img/gallery/15656565_3828389912.jpg",
    "http://images.icecat.biz/img/gallery/15656565_0985217712.jpg",
    "http://images.icecat.biz/img/gallery/15656565_2053118492.jpg",
    "http://images.icecat.biz/img/gallery/15656565_3136121979.jpg",
    "http://images.icecat.biz/img/gallery/15656565_3698859043.jpg",
    "http://images.icecat.biz/img/gallery/15656565_7403185164.jpg",
    "http://images.icecat.biz/img/gallery/15656565_5829735672.jpg",
    "http://images.icecat.biz/img/gallery/15656565_1378074619.jpg",
    "http://images.icecat.biz/img/gallery/15656565_9686454727.jpg",

A: Try the following:
df$C <- df$B[2]
df$D <- df$B[3]
df$B <- df$B[1]


text:
Q: Euclid Mullin Sequence Consider the Sequence as follows.
Let $a_1 = 2$, $a_n$ be the largest prime divisor of $P_n = 1 + {\prod_{i = 1}^{n - 1} a_{i}} $
Then we obtain a sequence of prime numbers
How do you show that 5 is never in the sequence?

OK, I am not quite understanding the last paragraph here.
Specifically

*

*I'm not sure what $(P_n, 6)$ mean

*how was $P_{n_0} = 5^k$ reached
The book is The Development of Prime Number Theory by W. Narkiewicz.

A: *

*$(P_n,6)$ is a shorthand for $\gcd(P_n,6)$. So $(P_n,6)=1$ is just saying that neither $2$ nor $3$ divides $P_n$.

*$P_{n_0}=5^k$ is deduced from the fact that $P_{n_0}$ is not divisible by $2$ or $3$, yet its largest prime factor is supposed to be $5$.


text:
Q: I need help on how to get a lower sized string from a bigger string? in C My problem could also translate to stopping a buffer from overflowing;
1st strategy
char first[40];
char g[] = "     Level %d      %d Fruit    %d:%d      ";
char d[41] = {0};
strncpy(d, g, 40);
if(strlen(d) < 40) {
for(i = strlen(d); i < 40; i++) {
d[i] = ' ';
}
}
n = sprintf(first, d, gol, gift, minutes, secs );

I Print my n onto the game's screen, I get my text and some unknown characters following, which means there is a buffer overflow somewhere.
2nd strategy;
char first[40];
char b[40];
strncpy(b, g, sizeof(b));
fgets(b, 40, stdin);            // of b[40] = '\0' also fails
n = sprintf(first, b, gol, gift, minutes, secs );

using " b[40] = '\0' ", I Print my n onto the game's screen, I get my text and some unknown characters following, which means there is a buffer overflow somewhere. using " fgets " crashes the game right away, even if g is 40 characters as of now, yet i want to increase it later
For both strategies, If I actually just put "g" in the " sprintf " statement, it does what I want except when I increase it to more than 40 characters. Sorry that I can't post the whole game code because its 4000 lines long split in 10 files.
I wold appreciate a completely different way of getting a string of only 40 characters from a string of more characters without leaving junk. The string has to be manually typed into the code, not input from user, it doesn't have to be declared like I declared "g".
THANKS

A: what I found was that using " b[40] = '\0' " gives you a correct answer. But if you are using it in for loops, you have to keep track of when you hit a null '\0' to break. which would mean you reached the end. I didn't realize I had a working answer until a day afterwards.
Anyway, my TA ended up telling me that I was doing a lot more than I was asked, i.e I never needed to do this.


text:
Q: Undefined local variable / no method error in Ruby on Rails Can anyone explain to me why I am getting this error?  Rails is about conventions.  Is there a more conventional way of doing what I'm trying to do below?
undefined local variable or method `hello_world' for #<#<Class:...>:...>

Here are my files:
welcome_controller.rb
class WelcomeController < ApplicationController
  def hello_world
    "Hello, World"
  end
end

welcome/index.html.erb
<%= hello_world %>

routes.rb
Rails.application.routes.draw do
  get 'welcome/index'
  root 'welcome#index'
end

A: Or do as :
class WelcomeController < ApplicationController
 helper_method :hello_world
 def hello_world
    "Hello, World"
 end
end

Now call it inside the view :
<%= hello_world %>

Read helper_method

Declare a controller method as a helper, to make the hello_world controller method available to the view.

A: You can use a helper to allow you to write that in your ERB:
module WelcomeHelper

  def hello_world
     "Hello, World"
  end

end

and now, your ERB should work:
<%= hello_world %>

A: hello_world is action defined in controller and routes
You need to define variable(s) in your action. This variable(s) will be accessible in the view
class WelcomeController < ApplicationController

 # this is action
 def index
    # this is variable
    @hello_world = "Hello, World"
 end

end

# view index.html.erb
# this calls variables defined in action
<%= @hello_world %>

Update1:
And if you define your route to welcome#index the action name in controller should be index!

A: This is more Rails-convention for you:
#config/routes.rb
root to: "welcome#index"
resources :welcome

#app/controllers/welcome_controller.rb
Class WelcomeController < ApplicationController
    def index
       #-> will render #app/views/welcome/index.html.erb
    end
end

#app/views/welcome/index.html.erb
Hello World
<%= hello_world %> <!-- Use `@Arup`'s answer to create a helper method -->

A: You can use print 'ff'. it simply work for me :)


text:
Q: add up values from radio buttons onclick without submitting form I saw on a link this ability to add up check boxes, but I need radio buttons added up instantly with any type of coding possible.
http://www.madirish.net/tech.php?section=1&article=7
my form is the following:
    <form action="orders.php" method="post" name="Reservar" target="_self">

        <?php
        foreach ($rows as $row) {
        ?>

         <input name="platofuerte" type="radio" onClick="checkTotal()" value="<?php echo $row['Producto_Precio']; ?>" />

         <input name="platofuerte1" type="hidden" value="<?php echo $row['Producto_ID']; ?>" /><img src='<?php echo htmlspecialchars($row['Producto_Imagen']); ?>' alt='image' name="imagen" id="imagen" />

         <input name="" type="label" value='<?php echo $row['Producto_Nombre']; ?>' />

         <input name="" type="label" value='<?php echo $row['Producto_Descripcion']; ?>' />

        <input name="price" type="label" value='$<?php echo $row['Producto_Precio']; ?>' />

                        <input name="bebida" type="radio" onClick="checkTotal()" value="<?php echo $row['Producto_Precio']; ?>" />

                         <input name="bebida1" type="hidden" value="<?php echo $row['Producto_ID']; ?>" /><img src='<?php echo htmlspecialchars($row['Producto_Imagen']); ?>' alt='image' name="imagen" id="imagen" />

                        <input name="" type="label" value='<?php echo $row['Producto_Nombre']; ?>' />

                        <input name="" type="label" value='<?php echo $row['Producto_Descripcion']; ?>' />

                        <input name="price" type="label" value='$<?php echo $row['Producto_Precio']; ?>' />

                        <?php

                    /*}*/

                   } ?>

                        <input name="postre" type="radio" onClick="checkTotal()" value="<?php echo $row['Producto_Precio']; ?>" />

                         <input name="postre1" type="hidden" value="<?php echo $row['Producto_ID']; ?>" /><img src='<?php echo htmlspecialchars($row['Producto_Imagen']); ?>' alt='image' name="imagen" id="imagen" />

                        <input name="" type="label" value='<?php echo $row['Producto_Nombre']; ?>' />

                        <input name="" type="label" value='<?php echo $row['Producto_Descripcion']; ?>' />

                        <input name="" type="label" value='$<?php echo $row['Producto_Precio']; ?>' />

<input name="aperitivo" type="radio" onClick="checkTotal()" value="<?php echo $row['Producto_Precio']; ?>" />

<input name="aperitivo1" type="hidden" value="<?php echo $row['Producto_ID']; ?>" /><img src='<?php echo htmlspecialchars($row['Producto_Imagen']); ?>' alt='image' name="imagen" id="imagen" />

 <input name="" type="label" value='<?php echo $row['Producto_Nombre']; ?>' />

<input name="" type="label" value='<?php echo $row['Producto_Descripcion']; ?>' />

<input name="" type="label" value='$<?php echo $row['Producto_Precio']; ?>' />

<input type="submit" name="Reservar" id="Reservar" value="Reservar" />

           <input type="text" size="2" name="total" value="0"/>
        </form>

in the last input text box, the totals of the selected radio buttons appear, in theory.  How can I make this work. this propposed  code is for a group of radios with the same name and the radio buttons in adjacent lines of text
my php page runs queries of each group name of radio buttons so I end up with up to 4 items per group. I need to add up totals of those radios sellected from each group.
the suggested script for check boxes is the following:

A: I don't know if I understood your problem, but I think that it can solve that:
In your radio buttons onclick, you can pass the element as a parameter to your function using the this.
<input name="bebida" type="radio" onclick="checkTotal(this)" value="2" />

Now your checkTotal function will receive the element and you can manipulate it as you want.
checkTotal = function (e) {
    console.log(e.value);
}

And depending of what do you want to do, you can user onclick or onchange. The difference is that onclick will still working even if the radio already is selected.
Hope that it solve your problem.

A: I solved it by creating a group per set of radios then adding the groups and displaying the total in an empty text input box.


text:
Q: Dealing with has_many through checkboxes in a nested form I'm trying to add has_many_through relationship through a form nested in a parent model. I can't figure out if this is possible?
The nested form works ok without the checkboxes. And the checkboxes work fine when they're outside the nested form.
= semantic_form_for @raduser do |f|
  %ul
    %li
      = f.text_field :expiration, :placeholder => 'Expiration Date', :id => 'expiration_date'
    - f.fields_for :radcheck do |builder|
      = builder.text_field :username, :placeholder => 'Stuff'
      -Radgroup.all.each do |group|
        %li
          = check_box_tag 'radcheck[radgroup_ids]', group.id, @radcheck.radgroup_ids.include?(group.id)
          = group.groupname

    %li
      = f.submit

This throws an error:
 undefined method `radgroup_ids' for #<ActiveRecord::Relation:0x007faaa24c2468>

I've got the models set up fine I think as all values save perfectly without the checkboxes
--- EDIT ADDED MODELS ---
Radusers have many Radcheck (singular due to legacy db). Radcheck has many radgroups through radusergroup.
class Raduser < ActiveRecord::Base

  has_many :radcheck, :dependent => :destroy
  accepts_nested_attributes_for :radcheck, :reject_if => lambda { |a| a[:value].blank? }, :allow_destroy => true

end

class Radcheck < ActiveRecord::Base
  self.table_name = 'radcheck'

  attr_accessible :attribute_name, :username, :value, :op, :radgroupcheck_id, :radcheck_serial, :radgroup_ids

  belongs_to :raduser

  has_many :radusergroup, :dependent => :destroy
  has_many :radgroup, :through => :radusergroup

end

class Radgroup < ActiveRecord::Base
  self.table_name = 'radgroup'

  has_many :radusergroup, :dependent => :destroy
  has_many :radcheck, :through => :radusergroup

end

class Radusergroup < ActiveRecord::Base

belongs_to :radcheck
belongs_to :radgroup

end

-- UPDATE TWO --
 def new
  @radcheck = Radcheck.new
  ...
 end

 def create
  @radcheck = Radcheck.new(params[:radcheck])
  ...
 end

--- UPDATE 3 ---
My db currently looks like this:
 +----------------+-----------------------+----------+------+
 | radcheck_id    | radgroup_id           | priority | id   |
 +----------------+-----------------------+----------+------+
 | 8              | 3                     |        1 |    1 |
 | 4              | 9                     |        0 |    2 |
 | 22             | 4                     |        1 |    3 |
 | 2              | 6                     |        1 |    4 |

I have the solution suggested below working.
What I was hoping to do was insert the radcheck_username and radgroup_groupname into the db, not the radcheck_id:
+----------------+-----------------------+----------+------+
| ...username    | --groupname           | priority | id   |
+----------------+-----------------------+----------+------+
| user123344     | group88888            |        1 |    1 |
| shushQb        | 30-minutes            |        0 |    2 |
| forty          | gigiig                |        1 |    3 |
| snang          | ps-staff              |        1 |    4 |

Is this possible?

A: The problem appears to be that you're trying to access Radcheck's various Radgroups through a method that isn't defined yet.  I can see a couple of solutions to this.  One would be to add the missing radgroup_ids method to your model.  Alternatively, I think you could call include? on Radchecks radgroups relation.
Solution A
Within your Radcheck class, define:
def radgroup_ids
  radgroups.map(&:id)
end

Solution B
Make a minor change to the way you're checking for included Radgroups
@radcheck.radgroups.include?(group)


text:
Q: Calculating ${(0.9)}^{\left(0.6\right)}$ with an approximation of ${10}^{\left(-4\right)}$ I'm having extreme difficulties understanding how to use Lagrange theorem to find an approximation. So far for my series I have:
$$(1+(-x))^\frac{3}{5}= 1-\frac{3}{5}x-\frac{3}{25}x^2-\frac{7}{125}x^3-\frac{21}{625}x^4...        $$
Knowing that $(0.9)=(1+(-.01) $:
$$(1+x)^\frac{3}{5}= 1-\frac{3}{5}\left(\frac{1}{10}\right)-\frac{3}{25}\left(\frac{1}{10}\right)^2-\frac{7}{125}\left(\frac{1}{10}\right)^3-\frac{21}{625}\left(\frac{1}{10}\right)^4..$$
I've taken a few derivatives of $(1+x)^\frac{3}{5}$:
$f'=\frac{3}{5}(1+x)^\frac{-2}{5}  $
$f''=\frac{-6}{25}(1+x)^\frac{-7}{5}  $
$f'''=\frac{42}{125}(1+x)^\frac{-12}{5}  $
$f''''=\frac{-504}{625}(1+x)^\frac{-17}{5}  $
Now, Lagranges remainder is given by:
$$ \frac{f^\left(n+1\right)(c)}{(n+1)!}(x)^\left(n+1\right)$$
Where c is in-between $a(a=0)$ and our value of $x (-0.1)$.
Now what I don't understand is how to utilize the Lagrange remainder in order to find an error bound of $10^\left(-4\right)$.
I appreciate any help as I just haven't been able to figure out how to use Lagrange! Now keep in mind, this needs to be done without a calculator as well!

A: I'll try my best to get this concept through to you, so let's begin... Taylor's Formula or the Lagrange Form of the error term, denoted by $R_n(x:a)$ is given by the following equation:-$$R_n(x:a)={f^{n+1}(c)(x-a)^{n+1}\over (n+1)! }$$
Simply this gives the error involved in using $T_n(x)$ to approximate $f(x)$ about $x=a$ or $f(x)=T_n(x)+R_n(x:a)$
Considering your problem, we know that,$$(1+(-x))^\frac{3}{5}= 1-\frac{3}{5}x-\frac{3}{25}x^2-\frac{7}{125}x^3-\frac{21}{625}x^4...$$
Let's try to first find out all the variable we can requried for the error term.So we know that $a=0$, but what about $n$ and $c$? Well, often you will have some kind of bound on $c$. I'll show you what that means in a moment. But before that recall that you have to obtain an approximation of $10^{-4}$ . What this means is that you would want your error to be less than this value, so we can write:$$R_n(-0.1:0)<10^{-4}$$
or  $${f^{n+1}(c)(-0.1)^{n+1}\over (n+1)!}<10^{-4}$$
Notice that any $|f^{(n+1)}(c)| \leq |f^{(n+1)}(-0.1)|$ as mentioned @Ian. This is what I meant by finding a bound on $c$. You'll get used to making such observations as you practise more problems. For, instance if you have a trigonometric function(sine or cosine) then $|f^{(n+1)}(c)| \leq 1$ and so on. With this bound we can write that: $${f^{n+1}(c)(-0.1)^{n+1}\over (n+1)!} \leq {f^{n+1}(-0.1)(-0.1)^{n+1}\over (n+1)!}$$ (Multiplying both sides of the above written inequality by the relevant coefficients).
But we don't want this to exceed our desired approximation so we can write:
$${f^{n+1}(-0.1)(-0.1)^{n+1}\over (n+1)!}<10^{-4}$$ Since you are not allowed to use a calculator we'll have to manually try some values of $n$ until we get the answer. So you'll have to try $n=1,2,3...$ and for each of those values calculate this term ${f^{n+1}(-0.1)(-0.1)^{n+1}\over (n+1)!}$ and see the minimum value of $n$ that you must go on till the inequality is finally satisfied. I hope that this helps...


text:
Q: Socket Error: Errno 111 Connection Refused im trying to connect to a locally hosted HiveMQ broker using a RaspberryPi Virtual Machine (Using Oracle VM VirtualBox). im using Mqtt.fx aswell as a second client to look at if the published messages are being recieved.
i was using "iot.eclipse.org" before i tried using the local hivemq broker and it worked fine. so im not too sure what the problem is. maybe im just forgetting something.
im using the paho mqtt module. and my library code is heavily ripped from here: https://pypi.python.org/pypi/paho-mqtt
im using a library/module and then referencing that in another .py file.
This is the code from the library/module:
import paho.mqtt.client as mqtt

client = mqtt.Client()

#Called on connection to server/broker
def on_connect(client, userdata, rc):
    print("connected with result code"+str(rc))

#Called when new message published to subscribed topic
def on_message(client, userdata, msg):
    print("NEW PUBLISH: "+msg.topic+" "+str(msg.payload))

#configure connection to the broker
def setup():
    client.on_connect = on_connect
    client.on_message = on_message

#Subscribe
def subscribe(topic):
    print("subscribing to topic: " +topic)
    client.subscribe(topic)

#Connect to broker
def connect():
    client.connect("127.0.0.1", 1883, 60)

def publish(topic, msg):
    client.publish(topic, msg)

and this is the code im actually running. Just 2 simple publishes:
import mqttLib as owly

owly.setup()
owly.connect()
owly.publish("test/library", "test okay :)")

num1 = input("1st number: ")
num2 = input("2nd number: ")
mult = num1 * num2

owly.publish("test/mult", mult)

This is the message i get after running it:
 Traceback (most recent call last):
  File "mqttTest.py", line 6, in <module>
  owly.connect()
  File "/home/rpi/python/MQTT/mqttLib.py", line 27, in connect
  client.connect("127.0.0.1", 1883, 60)
  File "/usr/local/lib/python2.6/dist-packages/paho/mqtt/client.py", line 612, In connect
  return self.reconnect()
  File "/usr/local/lib/python2.6/dist-packages/paho/mqtt/client.py", line 732, in reconnect
  sock = socket.create_connection((self._host, self._port))
  File "/usr/lib/python2.6/socket.py", line 514, in create_connection
  raise error, msg
  socket.error: [Errno 111] Connection refused

The fact it works on a remotely hosted broker. and not locally confuses me.
i have stripped off most of the plugins on HiveMQ and left the message log plugin on HiveMQ aswell so i dont think its anything to do with authentication.
i think the virtual machine im using is ubuntu if that helps!
Thank you for your time in advance!
EDITED
added ifconfig output:
rpi@RaspberryPi:~$ ifconfig
eth0      Link encap:Ethernet  HWaddr 08:00:27:5b:26:64
      inet addr:192.168.56.101  Bcast:192.168.56.255  Mask:255.255.255.0
      inet6 addr: fe80::a00:27ff:fe5b:2664/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:607 errors:0 dropped:0 overruns:0 frame:0
      TX packets:12 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:82290 (82.2 KB)  TX bytes:1920 (1.9 KB)

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

added netstat -anp output:
rpi@RaspberryPi:~$ netstat -anp
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
 Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State PID/Program name
udp        0      0 0.0.0.0:68              0.0.0.0:*                               -
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node   PID/Program name    Path
unix  2      [ ACC ]     STREAM     LISTENING     5465     1017/lxterminal     /tmp/.lxterminal-socket:0.0-rpi
unix  2      [ ACC ]     STREAM     LISTENING     2354     -                   @/com/ubuntu/upstart
unix  2      [ ACC ]     STREAM     LISTENING     3653     -                   /tmp/.X11-unix/X0
unix  2      [ ACC ]     STREAM     LISTENING     3652     -                   @/tmp/.X11-unix/X0
unix  2      [ ]         DGRAM                    2462     -                   @/org/kernel/udev/udevd
unix  2      [ ACC ]     STREAM     LISTENING     4693     891/dbus-daemon     @/tmp/dbus-DYueHXFGGf
unix  2      [ ACC ]     STREAM     LISTENING     4524     814/gnome-keyring-d /tmp/keyring-OM3Fh4/control
unix  2      [ ACC ]     STREAM     LISTENING     5019     913/gam_server      @/tmp/fam-rpi-
unix  2      [ ]         DGRAM                    5068     -                   @/org/freedesktop/hal/udev_event
unix  2      [ ACC ]     STREAM     LISTENING     4680     -                   /tmp/ssh-ESoUnvu822/agent.822
unix  2      [ ACC ]     STREAM     LISTENING     5037     -                   @/var/run/hald/dbus-ejQUT9OaXl
unix  2      [ ACC ]     STREAM     LISTENING     4832     904/pcmanfm         /tmp/.pcmanfm-socket:0.0-rpi
unix  2      [ ACC ]     STREAM     LISTENING     3497     -                   /var/run/dbus/system_bus_socket
unix  2      [ ACC ]     STREAM     LISTENING     4834     909/menu-cached     /tmp/.menu-cached-:0-rpi
unix  2      [ ACC ]     STREAM     LISTENING     4966     814/gnome-keyring-d /tmp/keyring-OM3Fh4/pkcs11
unix  6      [ ]         DGRAM                    3504     -                   /dev/log
unix  2      [ ACC ]     STREAM     LISTENING     5014     814/gnome-keyring-d /tmp/keyring-OM3Fh4/ssh
unix  2      [ ACC ]     STREAM     LISTENING     5042     -                   @/var/run/hald/dbus-9woYq1KdE9
unix  3      [ ]         STREAM     CONNECTED     5468     -
unix  3      [ ]         STREAM     CONNECTED     5467     1017/lxterminal
unix  3      [ ]         STREAM     CONNECTED     5463     -                   @/tmp/.X11-unix/X0
unix  3      [ ]         STREAM     CONNECTED     5462     1017/lxterminal
unix  2      [ ]         DGRAM                    5365     -
unix  3      [ ]         STREAM     CONNECTED     5288     -                   @/var/run/hald/dbus-ejQUT9OaXl
unix  3      [ ]         STREAM     CONNECTED     5287     -
unix  3      [ ]         STREAM     CONNECTED     5283     -                   @/var/run/hald/dbus-ejQUT9OaXl
unix  3      [ ]         STREAM     CONNECTED     5239     -
unix  3      [ ]         STREAM     CONNECTED     5237     -                   /var/run/dbus/system_bus_socket
unix  3      [ ]         STREAM     CONNECTED     5236     -
unix  3      [ ]         STREAM     CONNECTED     5144     -                   @/var/run/hald/dbus-ejQUT9OaXl
unix  3      [ ]         STREAM     CONNECTED     5134     -
unix  3      [ ]         STREAM     CONNECTED     5063     -                   @/var/run/hald/dbus-9woYq1KdE9
unix  3      [ ]         STREAM     CONNECTED     5062     -
unix  3      [ ]         STREAM     CONNECTED     5039     -                   /var/run/dbus/system_bus_socket
unix  3      [ ]         STREAM     CONNECTED     5038     -
unix  3      [ ]         STREAM     CONNECTED     5025     -                   /var/run/dbus/system_bus_socket
 unix  3      [ ]         STREAM     CONNECTED     5024     904/pcmanfm
 unix  3      [ ]         STREAM     CONNECTED     5022     913/gam_server      @/tmp/fam-rpi-
 unix  3      [ ]         STREAM     CONNECTED     5021     904/pcmanfm
 unix  2      [ ]         DGRAM                    4969     814/gnome-keyring-d
 unix  3      [ ]         STREAM     CONNECTED     4964     891/dbus-daemon     @/tmp/dbus-DYueHXFGGf
 unix  3      [ ]         STREAM     CONNECTED     4963     814/gnome-keyring-d
 unix  3      [ ]         STREAM     CONNECTED     4842     909/menu-cached     /tmp/.menu-cached-:0-rpi
 unix  3      [ ]         STREAM     CONNECTED     4838     902/lxpanel
 unix  3      [ ]         STREAM     CONNECTED     4830     -                   @/tmp/.X11-unix/X0
 unix  3      [ ]         STREAM     CONNECTED     4829     904/pcmanfm
 unix  3      [ ]         STREAM     CONNECTED     4796     -                   @/tmp/.X11-unix/X0
 unix  3      [ ]         STREAM     CONNECTED     4795     901/xscreensaver
 unix  3      [ ]         STREAM     CONNECTED     4788     -                   @/tmp/.X11-unix/X0
 unix  3      [ ]         STREAM     CONNECTED     4787     902/lxpanel
 unix  3      [ ]         STREAM     CONNECTED     4762     -                   @/tmp/.X11-unix/X0
 unix  3      [ ]         STREAM     CONNECTED     4761     897/openbox
 unix  3      [ ]         STREAM     CONNECTED     4701     -                   @/tmp/.X11-unix/X0
 unix  3      [ ]         STREAM     CONNECTED     4700     822/lxsession
 unix  3      [ ]         STREAM     CONNECTED     4697     -                   @/tmp/.X11-unix/X0
 unix  3      [ ]         STREAM     CONNECTED     4696     890/dbus-launch
 unix  3      [ ]         STREAM     CONNECTED     4695     891/dbus-daemon
 unix  3      [ ]         STREAM     CONNECTED     4694     891/dbus-daemon
 unix  3      [ ]         STREAM     CONNECTED     4683     -                   @/tmp/.X11-unix/X0
 unix  3      [ ]         STREAM     CONNECTED     4682     890/dbus-launch
 unix  3      [ ]         STREAM     CONNECTED     4673     -                   @/tmp/.X11-unix/X0
 unix  3      [ ]         STREAM     CONNECTED     4672     882/VBoxClient
 unix  3      [ ]         STREAM     CONNECTED     4671     -                   @/tmp/.X11-unix/X0
 unix  3      [ ]         STREAM     CONNECTED     4670     882/VBoxClient
 unix  3      [ ]         STREAM     CONNECTED     4666     -                   @/tmp/.X11-unix/X0
 unix  3      [ ]         STREAM     CONNECTED     4665     875/VBoxClient
 unix  3      [ ]         STREAM     CONNECTED     4664     -                   @/tmp/.X11-unix/X0
 unix  3      [ ]         STREAM     CONNECTED     4663     875/VBoxClient
 unix  3      [ ]         STREAM     CONNECTED     4656     -                   @/tmp/.X11-unix/X0
 unix  3      [ ]         STREAM     CONNECTED     4655     866/VBoxClient
 unix  3      [ ]         STREAM     CONNECTED     4527     -                   /var/run/dbus/system_bus_socket
 unix  3      [ ]         STREAM     CONNECTED     4526     -
 unix  3      [ ]         STREAM     CONNECTED     4440     -                   /var/run/dbus/system_bus_socket
 unix  3      [ ]         STREAM     CONNECTED     4439     -
 unix  3      [ ]         STREAM     CONNECTED     4415     -                   /var/run/dbus/system_bus_socket
 unix  3      [ ]         STREAM     CONNECTED     4414     -
 unix  3      [ ]         STREAM     CONNECTED     4402     -                   /var/run/dbus/system_bus_socket
 unix  3      [ ]         STREAM     CONNECTED     4401     -
 unix  2      [ ]         DGRAM                    4400     -
 unix  2      [ ]         DGRAM                    4355     -
 unix  3      [ ]         STREAM     CONNECTED     4356     -                   @/tmp/.X11-unix/X0
 unix  3      [ ]         STREAM     CONNECTED     3663     -
 unix  3      [ ]         STREAM     CONNECTED     3517     -                   /var/run/dbus/system_bus_socket
 unix  3      [ ]         STREAM     CONNECTED     3516     -
 unix  3      [ ]         STREAM     CONNECTED     3515     -
 unix  3      [ ]         STREAM     CONNECTED     3514     -
 unix  3      [ ]         DGRAM                    2494     -
 unix  3      [ ]         DGRAM                    2493     -               unix  3      [ ]         STREAM     CONNECTED     2445     -                   @/com/ubuntu/upstart
 unix  3      [ ]         STREAM     CONNECTED     2444     -

r

A: As mentioned in the comments, 127.0.0.1 is the local address of the VM, what you need to use is the IP address of the host where the broker is running.
In this case the broker host is on the VM host, you can get address of the VM host using the ip route command on the VM, it's output it will look something like this:
default via 192.168.56.100 dev eth0
192.168.56.0/24 dev eth0  proto kernel  scope link  src 192.168.56.100

The IP address you want to use for your broker should be the one in the line that starts with default, in the example case 192.168.56.100


text:
Q: What is this functional programming optimization called? Consider the following Haskell code for computing the nth Fibonacci number.
fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)

This code is slow. We can optimize it by refactoring to a helper function that computes "iteratively", by "storing" all the relevant data to compute the recurrence with in its arguments, along with a "counter" that tells us how long to compute for.
fastfib :: Int -> Int
fastfib n = helper 1 0 n
  where
    helper a _ 1 = a
    helper a b i = helper (a + b) a (i - 1)

It seems like this optimization could apply more broadly as well. Does it have a name, in the functional programming community or elsewhere?

A: Yes, it's called accumulating parameter technique. (Here's one of my answers, about it).
It's closely related to monoids, tail-recursion-modulo-cons ("TRMC"), corecursion, hylomorphisms, folding, etc.
Monoids enable the re-parenthesization
a+(b+(c+...)) == (a+b)+(c+...) == ((a+b)+c)+...

which enables the accumulation. TRMC (which came to be explicitly known in the context of Prolog) is the same, just with lists;
[a]++([b]++([c]++...)) == ([a]++[b])++([c]++...) == (([a]++[b])++[c])++...

and corecursion builds lists in top-down manner just like TRMC does.
The answer linked above contains a link to the technical report from 1974 by Friedman and Wise, which essentially talks about accumulation in the context of the + monoid, as an example.
There's no monoids in the Fibonacci example, but there's an accumulation of "knowledge" so to speak, as we go along from one Fibonacci number to the next.


text:
Q: How can I count specific item in sqlite database? How can I count specific items in a SQLite database? Here's what I have tried so far:
 String Query = "SELECT COUNT(*) FROM mytable WHERE date = '" + 2015 + "'";
 ResultSet rs = stmt.executeQuery(Query);
 jtextfield.setText(String.valueOf(rs));

A: Assuming that your query is correct you need to read the result in a proper way:
String Query = "SELECT COUNT(*) FROM mytable WHERE date = '" + 2015 + "'";
ResultSet rs = stmt.executeQuery(Query);
int count    = rs.next() ? rs.getInt(1) : 0;
jtextfield.setText(String.valueOf(count));

A: String query = String.format("SELECT COUNT(*) FROM mytable WHERE date = '%d'", 2015);
ResultSet rs = stmt.executeQuery(query);
int count = 0;
try {
    rs.next();
    count = rs.getInt(1);
} catch (SQLException e) {
    count = 0;
}
String rowCount = String.valueOf(count);
jtextfield.setText(rowCount);

According to the java style guide from Oracle, instance variables should be lowercase and there are a few other stylistic things you'll find you need to change to conform to it. I don't like inner classes or more than one function call in a line, but that's a personal preference, so you'll notice I've changed your code style a little. Feel free to ignore it if you disagree.


text:
Q: Помогите сделать проверку по базе Mysql у меня есть форма, теперь я введу туда john@test.com нажму enter произойдет проверка по базе MySQL на наличие такого email'a if{такого емайла не существует}else{такой емайл существует}. Как реализовать?
A: $res = mysql_query ("SELECT * FROM `user` WHERE `поле`='значение' AND `поле`='значение'  AND `поле`='значение'");
if(mysql_num_rows($res) > 0) {
echo 'OK';
} else {
echo 'NO';
}

A: Или можно делать count:
if ($result = mysqli_query("SELECT COUNT(*) as c FROM user WHERE поле='значение'")) {
    $row = mysqli_fetch_assoc($result);
    if ($row['c'] > 0) {echo 'Ok';}
    else {echo 'No';}
    $result->close();
}
else
{
    echo 'Что-то пошло не так';
}


text:
Q: Resctricting access to only 1 ip address and console connection I havent found an answer to this situation, and I'd like to have an answer before trying it and be stuck !
I would like to restrict connection to my EC2 instance to SSH from one IP address. Also I wonder if connecting to this instance within the console (Amazon website) would be prohibited ?
In other words, suppose I usually connect to this instance through a proxy or a VPN. Would I be able to connect to this instance, change parameters, etc. through the amazon website from any place ? In case the proxy or VPN breaks down ?
This may seems a silly question, but I'm not a specialist and I wouldn't like to be stuck outside :)

A: You can restrict SSH access to an Amazon EC2 instance by creating a Security Group that only permits Inbound SSH (port 22) access from a specific IP address.
The Security Group only limits access to the instance itself. Any activity in the EC2 management console (eg stopping and starting an instance) is not impacted by Security Group settings.
You cannot "connect to an instance from the Amazon EC2 console", but the console does have the ability to launch EC2 Instance Connect, which is a web-based SSH. However, it cannot be restricted to one IP address.


text:
Q: Flutter / Moor getting dynamic function return type error when trying to build my data model I am using MOOR for data persistence in my Flutter app.
dependencies in pub spec.yaml file
path: ^1.8.0
json_annotation: ^4.0.1
moor_flutter: ^4.0.0
intl: ^0.17.0
moor: ^4.4.1

dev_dependencies:
 flutter_test:
  sdk: flutter
moor_generator: ^4.4.1
build_runner: ^2.0.6

My moor_db.dart file
import 'package:moor_flutter/moor_flutter.dart';
part 'moor_db.g.dart';

 class CalendarDayMoor extends Table {
 IntColumn get id => integer().autoIncrement().call();
 DateTimeColumn get date => dateTime()();
 }

I get the following error for both properties
  A value of type 'Column<int>' can't be returned from the function 'id'
 because it has a return type of 'dynamic Function()'.dartreturn_of_invalid_type

Here is a picture of what I see for reference. To the best of my understanding, this should be working.  Any ideas? has anyone run into this? what could be happening? what am I missing?

A: This problem seems to have fixed itself by morning.
Steps I took:

*

*Run flutter upgrade, to make sure you are using the latest DART SDK (that seemed to be part of the issue)

*restart your machine and VSCode

*remember to run flutter pub get so you have added all your dependencies

Best of luck!


text:
Q: On-Demand resource downloading without error on iOS, but not available Our app works every time without a hitch on all iOS devices we've tested with (fresh install or update from xcode/adhoc production/debug, we've tried them all). But it is getting rejected in app review because it appears the ondemand resource never becomes available, even though the download of the resource completes without error.
We are accessing the resource in a blocking region of camera callback. If the resource is available we go ahead and use it, otherwise we do a beginAccessingResourcesWithCompletionHandler() and free callback block only after download is complete. The problem is app reviewer is saying it downloads (there's a progressbar for it) and then keeps asking to redownload over and over. Why would it not be available if it just successfully completed download (note there's no error)?
[request conditionallyBeginAccessingResourcesWithCompletionHandler:^(BOOL resourcesAvailable) {
if (resourcesAvailable)
{
    /* use the resource. */
    /* unblock the callback. done. */
}
else
{
    /* ask to download resource */
    [request beginAccessingResourcesWithCompletionHandler:^(NSError * _Nullable error) {
        if (error)
        {
            NSLog(@"%@", error);
            /* don't unblocked. return. will hang. */
        }
        /* unblock the callback. done. resource should be available next camera frame. */
    }];
} }];

Also it's not an out of storage issue. We have that covered and tested. Moreover the beginAccessingResourcesWithCompletionHandler() returns without error.

A: I'm going to guess that the problem is a failure to heed the warning in big letters in the documentation:

An NSBundleResourceRequest object can only be used for one successful resource request.

You cannot reuse a bundle resource request object. It has only two jobs: to download the resources (once), and to hold them in place (by persisting). Once you have succeeded in downloading the resources once, there are only two things you can do with this bundle resource request object (and you can do both of them):

*

*Call endAccessingResources.

*Throw the object away (or let it go out of scope or die with the termination of the app).
If you want to find out again, in the same run of the app, whether you still have these resources, you need to begin all over again with a new bundle resource request.
However, I would go further. As I've said in the comments, you seem to be misusing conditionallyBegin. There is no need to ask twice during the same run of the app whether you already have these resources, and there is no need to call conditionallyBegin to find that out, because when you say beginAccessing the right thing will happen: either you will start using the resources (if they are present) or you will download them and start using them (if they were not present). The only reason for ever using conditionallyBegin is if your logic would be different from that if it turned out that some resources were not present.

A: After 9 submissions, this issue resolved for us. But unfortunately its not clear which change was essential to it getting resolved. Moreover it was near the 13.2.3 update too.
Overall I'd make sure of these (note there are a lot of examples with up-votes on SO that do not follow these):
1) All beginAccess call are done on main thread.
2) Don't reuse the resourceRequest between conditionallyBeginAcces and beginAccess. (as pointed out by Matt). Redefine them from tag name each time.
3) Make sure resourceRequest are defined such that they do not go out of scope until the whole process is done. Its possible that reviewer devices have a background daemon that instantly deletes resources that are released (due to going out of scope).
4) if the odr is accessed inside a dispatch_sync() block, make sure that there's no path for concurrent beginAccess to be fired.