text:
Q: not enough arguments in call to (_C2func_bcc_func_load) I am getting an error not enough arguments in call to (_C2func_bcc_func_load)
when compiling Go.
Go Version used: go version go1.19.1
How can I resolve this error?  Would appreciate if anyone could help.
Error Message:
github.com/iovisor/gobpf/bcc
/home/jeremy/go/pkg/mod/github.com/iovisor/gobpf@v0.2.0/bcc/module.go:230:132: not enough arguments in call to (_C2func_bcc_func_load)
    have (unsafe.Pointer, _Ctype_int, *_Ctype_char, *_Ctype_struct_bpf_insn, _Ctype_int, *_Ctype_char, _Ctype_uint, _Ctype_int, *_Ctype_char, _Ctype_uint, nil)
    want (unsafe.Pointer, _Ctype_int, *_Ctype_char, *_Ctype_struct_bpf_insn, _Ctype_int, *_Ctype_char, _Ctype_uint, _Ctype_int, *_Ctype_char, _Ctype_uint, *_Ctype_char, _Ctype_int)

A: It seems that your dependency library github.com/iovisor was broken. Try to check out their github to see if there are any issues, or just do something like go get -u to update your project dependencies to the latest versions (probably some new version have been already released and the problem is fixed). The version can also be restricted in your go.mod file, so you may want to change it there.

A: gobpf@v0.2.0 is not compatible with bcc-0.25.0, but it works with bcc-0.24.0.
I checked out the code at the desired version:
git clone --branch v0.24.0 https://github.com/iovisor/bcc.git

Then I followed the instructions to build it from source:
mkdir bcc/build; cd bcc/build
cmake ..
make
sudo make install
cmake -DPYTHON_CMD=python3 .. # build python3 binding
pushd src/python/
make
sudo make install
popd

This issue has more information. There was a PR merged 12 days ago with a potential fix - it will be available in the next release of gobpf.

A: I used latest recent commit which is compatible with bcc-0.25.0:
$ go list -m github.com/iovisor/gobpf@master
github.com/iovisor/gobpf v0.2.1-0.20221005153822-16120a1bf4d4

Then in your go.mod, use:
require github.com/iovisor/gobpf v0.2.1-0.20221005153822-16120a1bf4d4


text:
Q: How can I pass props to individual  with React Navigation? I have the following stack navigator code in my React Native app using @react-navigation/bottom-tabs:
const Tab = createBottomTabNavigator();

const TabNavigator = () => (
  <Tab.Navigator tabBar={(props) => <BottomNavBar {...props} />}>
    <Tab.Screen name={routes.app.search} component={Search} />
    <Tab.Screen name={routes.app.connections} component={Connections} />
    <Tab.Screen name={routes.app.filters} component={Filters} />
    <Tab.Screen name={routes.app.profile} component={Profile} />
  </Tab.Navigator>
);

How do I pass a prop to an individual screen in this navigator? For example, the Search screen?

A: the component property take a react component as a value to be shown on that screen, and to pass props to that component, instead of calling the screen directly, you can pass am arrow function as a wrapper to that component and in the arrow function return the invoke of the react component that you want to show plus now you can pass the props or even implement some logic before returning!
so lets try this
<Tab.Screen name={routes.app.search} component={() => <Search showProps={true} {...props} />} />

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to fix connection close issue in synchronised method? In our application, we are using grails framework and SQL server for database. We have multiple sites and those  sites can have multiple users (a few users) and if they are accessing the same method via AJAX that can cause issue so we made the that method as synchronized method and to minimize the database interaction we are storing data in map on site basis since all the user from one site will get the same data, and if the data is older than 10 seconds we get the data from database and update the map object. Here we are getting a lot of database connection close issues on the very first line of synchronized method where we are getting site object from database. What is the issue here and how we can resolve the issue?
def synchronized getData(params){
  Site site = Site.get(params.siteId)
  // Here we are checking whether site data does not exists in map
  // or the data expired (10 second older data) then we get data from
  // database and update the map object

  // Then here we create new list object from the data in map object

  return list
}

A: Difficult to figure out the exact problem without more information here.  Several things stand out...
I'm not especially familiar with using the synchronized keyword in front of a service method, I would recommend trying the synchronized annotation with a static object key:
private static final myLock = new Object()

@Synchronized("myLock")
void getData() {
  //do stuff
}

or synchronizing explicitly within the method
void getData() {
  synchronized(myLock) {
    //do stuff
  }
}

I don't know if that's related to your connection closing issues, but worth a try.
But also notably, grails and hibernate provide caching of database retrieves, so if you're loading the same data that's been loaded into hibernate cache, you don't need to cache this in a Map locally...  grails is already doing that for you.  Site site = Site.get(params.siteId) will NOT make a database call if it's been called recently and is already cached by the framework.
I would strongly suggest running some performance checks just making that call vs. caching in a Map object, especially if you're expiring in ~10s anyway.


text:
Q: Infinite loop(?) created in Firebase cloud function I am new to web development (or programming in general) and I am writing codes for my personal project. I am writing Firebase cloud function code in Javascript to auto-rotate,compress, and transform into Progressive JPEG once an image is uploaded, using ImageMagick. But the below part of the code is creating an infinite loop in the backend once an image is uploaded and the function is triggered.
Any advice on what went wrong? I guess it has to do something with Javascript Promise and I probably will have to return something at the end of each if/else case, but not sure where to look at...can someone help out?
if (metadata.autoOrient) { //Check if the image is already rotated and skip auto-rotation
    console.log('This is already rotated');
    return mkdirp(tempLocalDir).then(() => {
        // Download file from bucket.
        return bucket.file(filePath).download({destination: tempLocalFile})
    }).then(() => {
        // Convert the image using ImageMagick.
        return spawn('convert', [tempLocalFile, '-quality', '85', '-interlace', 'plane', tempLocalFile])
    }).then(() => {
        metadata.autoOrient = true
        return bucket.upload(tempLocalFile, {
        destination: filePath,
        metadata: {metadata: metadata}
        })
    }).then(() => {
        // Once the image has been converted delete the local files to free up disk space.
        fs.unlinkSync(tempLocalFile)
        console.log('Compression and PJPEG convsersion successful');
     })
}
else { //Image is not  rotated, thus do all the operations
    return mkdirp(tempLocalDir).then(() => {
        // Download file from bucket.
        return bucket.file(filePath).download({destination: tempLocalFile})
    }).then(() => {
        // Convert the image using ImageMagick.
        return spawn('convert', [tempLocalFile, '-auto-orient', '-quality', '85', '-interlace', 'plane', tempLocalFile])
    }).then(() => {
        metadata.autoOrient = true
        return bucket.upload(tempLocalFile, {
        destination: filePath,
        metadata: {metadata: metadata}
        })
    }).then(() => {
        // Once the image has been converted delete the local files to free up disk space.
        fs.unlinkSync(tempLocalFile)
        console.log('Auto rotation, compression and PJPEG convsersion successful')
    })
}


text:
Q: sbt-assembly tasks don't display in sbt interactive mode I'm using sbt 1.0.1 and I've configured the sbt-assembly plugin (0.14.5) as per its GitHub README.
When I run $ sbt (interactive mode) and run > tasks, none of the assembly tasks are displayed.
However, when I run > help assembly , I see its description (Builds a deployable fat jar.).
What am I doing wrong?
Is this a bug?
Am I missing an import statement in my build.sbt? (Not according to the Setup instructions in the current sbt-assembly README.)
Is there another command I have to run in order to see the sbt-assembly tasks?

A: I eventually found the answer using > help tasks. (Ergo, boneheaded question!)
Adding the flag -V to tasks displays all tasks. (That's simple enough.)
Enigmatically, the flag -v apparently Displays additional tasks. More 'v's increase the number of tasks displayed. Okay, fine, but using what logic? And how did sbt determine its original (apparently) arbitrarily restricted list of tasks?
I suppose I could simply delete this question as an embarrassing 'newbie' thing to ask. But I find that despite a considerable amount of documentation on sbt that exists (as of 2017), very little of it succeeds at communicating a either a conception of the entire system, or notion of how to use its various pieces to orchestrate your own build task.
So if this saves anyone any time at all learning sbt, I'll be pleased.


text:
Q: Why aren't my images from local folder loading? I am trying to load some images in my React App from a local folder called images. It's in the src folder. Right now there are only 2 images in there for testing purposes, but eventually there's going to be many.
First what I do is define an images array:
  const [loadImages, setLoadImages] = React.useState([{image:'images/kitten.jpg'}, {image:'images/penguin.jpg'}]);

Since I'm working with konva I define Image:
  const URLImage = ({image}) => {
    const [img] = useImage(image.src);
    return (
      <Image
        image = {img}
        x = {image.x}
        y = {image.y}

        offsetX = {img ? img.width / 2 : 0}
        offsetY = {img ? img.height / 2 : 0}
        draggable
      />
    );
  };

Then I try to load them all like this:
 {loadImages.map(image => (
   {
    dragUrl.current = e.target.src;}}
/>
))}

Then I also tried to see if an image from the images folder would load up if I simply did this:

But I still get the image is missing symbol:
missing image symbol
What am I doing wrong & how can I fix it? Thanks in advance.

A: You should import images from the images folder
import imageone from './images/3.JPG'

then you can

Without importing image then you can do some think like this


text:
Q: Solutions to $x^2 + y^2 -1 = 0$ over projective space What I would like to do is find the solutions of $p_1(x,y) = x^2 + y^2 - 1 = 0$, after passing to the projective plane.
Step 1, of course, is to homogenize $p_1$. Then we have
 $\tilde{p_1}(x,y,z) = x^2 + y^2 - z^2$.
Now I have proven two things already that simplify my work. I have proved that if a point $(x,y,z) \in \mathbb{C}^3 - (0,0,0)$ satisfies the homogeneous polynomial, then $(x : y : z)$ (all the points in the equivalence class of $(x,y,z)$) satisfy the homogeneous polynomial. It has also been shown that if $(x,y)$ is in the $V(p_1)$, then $(x,y,1)$ is in $V(\tilde{p_1})$. From this I believe we can conclude that the only points left to find, are the points at infinity?
(this is the part where I am confused)
So to find the points at infinity in $V({\tilde{p_1}})$ do we just set $z = 0$ and solve
$$x^2 + y^2 = 0?$$
This would yield $|x| = i|y|$? This makes sense looking at the equation but it feels weird expressing this as a point of $\mathbb{P}^2_{\mathbb{C}}$. How could I write it in the form $(a : b : 0 ) \in \mathbb{P}^2_{\mathbb{C}}$? How can I visualize the line that the point represents? Any geometric intuition?

A: You are more or less correct. The line at infinity is given by $z=0$ and so
$$x^2 + y^2 = 0 \Rightarrow x = \pm iy $$
So there are actually two more points $[i,1,0], [-i,1,0]$ at infinity.
For geometric intuition, note that
$$x^2 +y^2  =1 \Rightarrow (x+iy)(x-iy) =1.$$
So under the change of coordinate $z= x+iy, w = x-iy$, the equation becomes
$$ zw=1$$
and one can think of this as a graph $\{(z, 1/z) :z\in \mathbb C\setminus \{0\}\}$. Thus the equation represents something like $\mathbb C\setminus  \{0\}.$ Since the object in $\mathbb{CP}^2$ is like compactifying the original object in $\mathbb C^2$, so in this situation the two points added are "$z=0$ and $z = \infty$ (which is $w=0$)" The first one is $x-iy = 0$ and the second one is $x+iy = 0$.
Note also that the closure in $\mathbb{CP}^2$ actually looks like a $2$-sphere (or $\mathbb{CP}^1$).


text:
Q: Textarea - Limit content per line Is there anyway I can limit the content of a text area per line?
For instance, in case an user paste a text which overflow that "predefined" number of line, the textarea will just display the content until the limited value previously set up. Keep in mind that empty lines should be take in count.
Any help will be welcome.
Thank you very much

A: Try this out:
<?xml version="1.0" encoding="utf-8"?>
<s:Application name="Spark_TextArea_limit_lines"
               xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx">

    <fx:Script>
        <![CDATA[

            private const MAX_LINES:uint = 5;

            private function textChangeHandler(event:Event):void {
                //Split the string into an array of lines
                var lines:Array = textArea.text.split("\n");
                //If there are too many lines...
                if (lines.length > MAX_LINES) {
                    //Clear the existing text
                    textArea.text = "";
                    //Then insert MAX_LINES of the previous text
                    for (var i:uint=0; i<MAX_LINES; i++) {
                        textArea.text += lines[i] + "\n";
                    }
                    //Finally, move the cursor to the end of input, as
                    //it is reset to position 0 when the text is modified.
                    textArea.selectRange(textArea.text.length, textArea.text.length);
                }
            }

        ]]>
    </fx:Script>

    <s:TextArea id="textArea" change="textChangeHandler(event)"/>

</s:Application>

A: it works with \r
var lines:Array = textArea.text.split("\r");


text:
Q: How to handle failing migrations on reset because of deleted models/methods An old one of my ruby on rails migrations contains both the actual migration but also an action to modify data:
class AddTypeFlagToGroup < ActiveRecord::Migration
  def self.up
    add_column :groups, :selection_type, :string

    Group.reset_column_information
    Group.transaction do
    Group.all.each do |group|
      group.selection_type = group.calculate_selection_type
      group.save
    end
  end
  end

  def self.down
    remove_column :groups, :selection_type
  end
end

In this migration there are the usual add_column and remove_column migration statements. But there are also some model specific method calls.
I wrote this a couple of weeks ago. Since then, I have removed my Group model, which gives an error when I do a full migration with :reset.
rake db:migrate:reset
(in /Users/jesper/src/pet_project)

[...]

==  AddTypeFlagToGroup: migrating =============================================
-- add_column(:groups, :selection_type, :string)
   -> 0.0012s
rake aborted!
An error has occurred, this and all later migrations canceled:

uninitialized constant AddTypeFlagToGroup::Group

The thing is that in the current revision of my code, Group does not exist. How should I handle this "the rails way"??
I am thinking I could modify the migration by commenting out the Group.xxx stuff, but is this a wise way to go?

A: There is no value in leaving the group stuff in your migration now that it is gone from your project.  I'd just edit the migration, drop everything from the db and migrate from scratch.  There isn't even a reason to comment it out (you are using version control right?)
Also, I believe the "rails way" with migrations is spelled "Arrrrgh!"


text:
Q: How do I start Edge from the command line with an argument for URL but open it in a new window? I'm using start microsoft-edge:https://www.myURL.ca to open an Edge browser from CMD. The problem is that I'd like to open it in a new window.
I found the "--new-window" argument which can be used from a structure passed in via C#, but I'm not able to figure out how to get that argument to Edge from CMD.

A: You could use the command below will help you launch the MS Edge browser new windows from CMD.
start msedge www.microsoft.com --new-window

Output:

In the test result, you could notice that there is an existing Edge window. when we run the command it opens a new Edge window.


text:
Q: Github action nothing to commit, working tree clean I have a git action, I have to make sure if there is nothing to add then not commit or push.
but how can I check if there is something to add and commit if necessary.
Here is an example of how I do at the moment:

on:
  push:
    branches:
      - testing

name: Build
jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        name: Check out current commit

      - name: Install
        run: npm install

      - name: Build
        run: npm run build

      - name: Commit
        run: |
          git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git config --local user.name "github-actions[bot]"
          git add .
          git commit -m "Build" -a

      - name: Push
        uses: ad-m/github-push-action@master
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          branch: ${{ github.ref }}

A: Here is what I would recommend:

*

*you can add a separate step to do the diff check

*use the diff check outputs to do the add/commit

It would be like something as follows (the follow example is how we extract the new translations and checkin the changes):
      - name: Check if there is any new translations
        id: verify_diff
        run: |
          npx prettier -w packages/trn/transifex
          git diff --quiet packages/trn/transifex/en_US.json || echo "::set-output name=new_translations_exist::true"

      - name: Commit files
        if: steps.verify_diff.outputs.new_translations_exist == 'true'
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
          git add packages/trn/transifex
          git commit -m "bot: extract the latest transactions"
          git push

A: While the previous answer from @chenrui may still work, it will produce a warning like the following:

Warning: The set-output command is deprecated and will be disabled soon. Please upgrade to using Environment Files. For more information see: https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/

As of October 11, 2022, GitHub has deprecated the save-state and set-output commands. Here is an updated snippet according to GitHub's recommendations:
on:
  push:
    branches:
      - testing

name: Build
jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        name: Check out current commit

      - name: Install
        run: npm install

      - name: Build
        run: npm run build

      - name: Check if there are any changes
        id: verify_diff
        run: |
          git diff --quiet . || echo "changed=true" >> $GITHUB_OUTPUT

      - name: Commit
        if: steps.verify_diff.outputs.changed == 'true'
        run: |
          git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git config --local user.name "github-actions[bot]"
          git add .
          git commit -m "Build" -a

      - name: Push
        if: steps.verify_diff.outputs.changed == 'true'
        uses: ad-m/github-push-action@master
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          branch: ${{ github.ref }}


text:
Q: Trying to make sense of this TypeScript compiler error I'm upgrading to MUI5 and this TS error came up. If I remove backgroundFill then the error goes away. I just don't know how to satisfy the compiler right now.
import React from "react";

import SvgIcon, { SvgIconProps } from "@mui/material/SvgIcon";

const MyIcon = ({
  backgroundFill,
  ...props
}: SvgIconProps & { backgroundFill: string }) => (

TS compiler message:
const MyIcon: ({ backgroundFill, ...props }: {
    children?: React.ReactNode;
    classes?: Partial<SvgIconClasses> | undefined;
    color?: "inherit" | "action" | "disabled" | "primary" | "secondary" | ... 4 more ... | undefined;
    ... 5 more ...;
    viewBox?: string | undefined;
} & CommonProps & Omit<...> & {
    ...;
}) => JSX.Element
The inferred type of 'MyIcon' cannot be named without a reference to '@mui/material/node_modules/@mui/system'. This is likely not portable. A type annotation is necessary.

A: This is difficult to debug without a reproducible example, but it seems like you simply need a return type annotation for your component.
I suggest using React.ReactElement when you're rendering JSX or a component that ultimately renders JSX:
TS Playground
import {default as React, ReactElement} from "react";
import { SvgIcon, type SvgIconProps } from "@mui/material";

const MyIcon = ({
  backgroundFill,
  ...props
}: SvgIconProps & { backgroundFill: string }): ReactElement => <SvgIcon />;


text:
Q: How to commit to Github through their API in Javascript? I'm trying to commit a new file to a Github repo through a put request, but receive a 422 Unprocessable Entity Error.
Here is the the code with which I am trying to commit:
    $http.put('https://api.github.com/repos/<userName>/<repoName>/contents/main.js?access_token='+$scope.authObj.access_token, {
            path: '/main.js',
            message: 'testing',
            content: Base64.encode($scope.contents),
            branch: 'master'
            }).then(function(response) {
        console.log(stuff);
    }).then(null, function(error) {
                console.error(error);
            });

Where <userName> is my Github name and <repoName> is the repo to which I am trying to commit.


text:
Q: Define the antiderivative of a linear map? I'm currently taking a complex analysis course, and upon seeing my professor's proof of Goursat's Theorem, I noticed that it didn't inherently rely on the function we were integrating over being holomorphic.
I've been having a somewhat heated discussion for the last 5 hours with other students/my professor, and none of us know if

would hold for a general $$L :\mathbb{R}^2 \mapsto \mathbb{R}^2$$
linear map, or at least a linear map that does not satisfy the Cauchy Riemann Equations.

A: user8469759 is correct that the question as posed doesn't make a whole lot of sense because it has an underlying arithmatic confusion. However, there is an analog to Goursat's theorem for functions from $\mathbb{R}^n\to\mathbb{R}$ which is known as the of the Gradient Theorem. The Gradient Theorem says that if $\varphi:U\subseteq\mathbb{R}^n\to\mathbb{R}$ and $\gamma$ is a curve from $u$ to $v$ then
$$\varphi(q)-\varphi(p)=\int_\gamma \nabla\varphi(r)\cdot dr $$
The converse of the gradient theorem is also true, and it says that if $F$ is a path-independent vector field, then $F$ is the gradient of some scalar-valued function. This gives a precise criterion for when a function from $\mathbb{R}^n\to\mathbb{R}$ has a path-independent integral.


text:
Q: Is a Patronus an accurate recreation of an animal as it lived, or a depiction of the summoner's conception of that animal? According to this answer, it is possible to have an extinct animal Patronus. But, nobody has a completely accurate scientific understanding of the appearance, behavior, sounds, etc. of long-extinct animals like the woolly mammoth or dinosaurs. So, is a Patronus like this accurate to how it was when it was actually alive? Or is it accurate to what the summoner thinks it was like when it was alive?
This extends to extant animals too. If for example the summoner didn't know something important about the animal but really liked that animal anyway. Like I probably couldn't tell you exactly how many toes any animal (except human) has off the top of my head; so if it was my Patronus would it have too many/too few toes?


text:
Q: Is it possible to iterate through several enum classes? I have three enum classes. I want to somehow put these in an array, loop through the array and call the same method in each enum class. Is this possible in Java?
It seems to me you can't place enum types in an array structure (unless i've missed how).
Thank you.

A: Let each enum type implement a common interface that has the common method that you want into invoke. You can now cast each enum, while iterating, to this common interface and call the method. Also look at EnumSet

A: Here is an example with 2 enums and using reflection:
enum Colour{
    RED,
    BLUE,
    GREEN;

    public void foo(){
        System.out.println("COLOUR");
    }
}

enum Fruit {
    APPLE,
    BANANA,
    PEAR;

    public void foo(){
        System.out.println("FRUIT");
    }
}

You can put the classes into an array and use reflection to call a method for each enum constant:
//create an array
Class[] arr = new Class[2];
arr[0] = Colour.class;
arr[1] = Fruit.class;

//call the foo method
for(Class c : arr){
    Method m = c.getMethod("foo", null);
    for(Object o : c.getEnumConstants()){
        System.out.println("Invoking foo on:" + o);
        m.invoke(o, null);
    }
}

A: If, by enum classes, you mean three different enums, each with their own elements, then you can use an array of type Enum[]. If you mean three items from a single enum, let's call it enum X, then you would put them in an array of type X[].
If you are trying to call a standard Enum function on each one, then you should be all set. If you need to call your own function on them, and are going with an array of Enum[], you'll either need to use reflection or have them all implement the same interface.


text:
Q: Sqlalchemy select issue with related table I have model 'User' who belongs to model 'Role'. One 'Role' has many 'User' and one 'User' has one 'Role'.
If I want to select all users where 'Role' is hidden lets say (this is purely an example) I must do something like this:
User.query.join(Role).filter(roles_table.c.hidden==1).all()

Just by using join in this query i get the following message:

Select statement 'SELECT role.hidden FROM role, user WHERE role.id =
  user.role_id' returned no FROM clauses due to auto-correlation;
  specify correlate() to control correlation manually.

Can anyone point me to the right direction of having this query working?

A: What if you try following instead:
User.query.join(Role).filter(Role.hidden==1).all()

A: Having User class has a relationship to Role, the simplest way would be:
User.query.filter(User.role.has(hidden=1))


text:
Q: Import font awesome with webpack and postcss-loader I am trying to update my webpack build to take advantage fo postcss and postcss-loader.  However I am having problems loading fonts, images, etc.
For example trying to get font awesome imported.
This is my setup before postcss which works:
css:
@import "~font-awesome/css/font-awesome.min.css";

webpack.config:
  ...
  module: {
    rules: [{
      test: /\.css$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: 'css-loader'
      })
    },{
      test: /\.(eot|svg|ttf|woff|woff2)$/,
      loader: 'file-loader?name=fonts/[name].[ext]'
    },{
      test: /\.(png|jpg)$/,
      loader: 'file-loader?name=images/[name].[ext]'
    },{
      test: /\.html$/, loader: 'raw-loader'
    }]
  }
  ...

Trying to move to this:
@import 'font-awesome'

webpack w/ postcss:
  ...
  module: {
    rules: [{
      test: /\.css$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [{
          loader: 'css-loader',
          options: {
            importLoaders: 1
          }
        },{
          loader: 'postcss-loader',
          options: {
            ident: 'postcss',
            sourceMap: true,
            plugins: [require('postcss-import')()]
          }
        }]
      })
    },{
      test: /\.(eot|svg|ttf|woff|woff2)$/,
      loader: 'file-loader?name=fonts/[name].[ext]'
    },{
      test: /\.(png|jpg)$/,
      loader: 'file-loader?name=images/[name].[ext]'
    },{
      test: /\.html$/, loader: 'raw-loader'
    }]
  }
  ...

However when I do I get errors like this:

ERROR in ./style.css Module build failed: ModuleNotFoundError: Module
  not found: Error: Can't resolve '../fonts/fontawesome-webfont.eot' in
  '/test-project/public'

I have tried a few other libraries as well (ie bootstrap, leaflet) and am running into the same problem with those.

A: It appears that the css-loader is having trouble resolving the relative url path to the font-awesome/fonts directory.
You need an alias in your css-loader options like so.
use: [{
  loader: 'css-loader',
  options: {
    importLoaders: 1,
    alias: {
      "../fonts": "font-awesome/fonts"
    }
  }
}

I tested this in an example project and it appeared to compile successfully.
$ ./node_modules/.bin/webpack
Hash: 05687ac67950e58e8485
Version: webpack 3.10.0
Time: 996ms
                          Asset     Size  Chunks                    Chunk Names
  fonts/fontawesome-webfont.eot   166 kB          [emitted]
fonts/fontawesome-webfont.woff2  77.2 kB          [emitted]
 fonts/fontawesome-webfont.woff    98 kB          [emitted]
  fonts/fontawesome-webfont.ttf   166 kB          [emitted]
  fonts/fontawesome-webfont.svg   444 kB          [emitted]  [big]
                 ./dist/main.js  2.63 kB       0  [emitted]         main
                     styles.css  38.1 kB       0  [emitted]         main
   [0] ./main.js 43 bytes {0} [built]
   [1] ./main.css 41 bytes {0} [built]
   [2] ../node_modules/css-loader?{"importLoaders":1,"alias":{"../fonts":"font-awesome/fonts"}}!../node_modules/resolve-url-loader!../node_modules/postcss-loader/lib?{"ident":"postcss"}!./main.css 43.7 kB [built]
    + 10 hidden modules
Child extract-text-webpack-plugin ../../../../Joshua Barnett\Projects\blah\node_modules\extract-text-webpack-plugin\dist ../../../../Joshua Barnett\Projects\blah\node_modules\css-loader\index.js??ref--0-2!../../../../Joshua Barnett\Projects\blah\node_modules\resolve-url-loader\index.js!../../../../Joshua Barnett\Projects\blah\node_modules\postcss-loader\lib\index.js??postcss!../../../../Joshua Barnett\Projects\blah\js\main.css:
     5 assets
       [0] ../node_modules/css-loader?{"importLoaders":1,"alias":{"../fonts":"font-awesome/fonts"}}!../node_modules/resolve-url-loader!../node_modules/postcss-loader/lib?{"ident":"postcss"}!./main.css 43.7 kB {0} [built]
        + 8 hidden modules

Also you may need to be more specific with the alias if you are also using projects that use the ../fonts relative path.

A: This webpack config resolved issue for me:
const rules = [{
  test: /\.css$/,
  use: [
    'style-loader',
    {
      loader: 'css-loader',
      options: {
        importLoaders: 1,
        sourceMap: true,
      }
    },
   'resolve-url-loader',
    {
      loader: 'postcss-loader',
      options: {
        sourceMap: true,
        ident: 'postcss',
        plugins: () => [],
      }
    }
  ]
}, {
  test: /\.(png|woff|woff2|eot|ttf|svg)$/,
  loader: 'url-loader?limit=100000',
}]


text:
Q: Background image above a border I would like to make this textbox

As you can see, there are two parts to the div - the background image in the bottom and the border, that I have already done:
HTML:

Text Text Text

CSS:
.person {
    background: url('../images/results_title.png') repeat-x bottom;
    border: 1px solid #000000;
    min-height: 32px;
}

The problem is that the border is above the background image. The background in the bottom should be above the border (= in the bottom should be just an image without any borders).
IMPORTANT:
There is a text on the image.

A: how about adding the border to the
? You can have a border-right and border-left on the p, with inside padding to keep the text away from the box. If the
's have other layout that would hinder this, wrap them in a div.
See this fiddle, for example:
http://jsfiddle.net/56TqY/1/
The red and cyan are just to examplify, and obviously I use your background with the text, but I think you get the idea.

A: I always hate adding more markup, but I think this should be what you're looking for.
I just added a wrapper so that you can add a padding between the border and the background-image


text:
Q: google app engine deploy a custom vm app takes a long time to deploy Here is my worker.yaml
runtime: custom #python27
api_version: 1
threadsafe: false
vm: true
service: worker
env_variables:
  PYTHON_ENV: lab
network:
  instance_tag: testing123
  name: dev

handlers:
- url: /.*
  script: Framework.Workers.PushQueues.worker.app
  login: admin

Dockerfile
FROM us.gcr.io/smiling-diode-638/basic-algo-docker-v2

and the console output:
gcloud app deploy worker.yaml  --verbosity='debug'                              ✱
DEBUG: Running gcloud.app.deploy with Namespace(__calliope_internal_deepest_parser=ArgumentParser(prog='gcloud.app.deploy', usage=None, description='Deploy the local code and/or configuration of your app to App Engine.', version=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=False), account=None, authority_selector=None, authorization_token_file=None, bucket=None, calliope_command=<googlecloudsdk.calliope.backend.Command object at 0x108770290>, command_path=['gcloud', 'app', 'deploy'], configuration=None, credential_file_override=None, deployables=['worker.yaml'], docker_build=None, document=None, flatten=None, format=None, h=None, help=None, http_timeout=None, ignore_bad_certs=False, image_url=None, log_http=None, project=None, promote=None, quiet=None, server=None, skip_image_url_validation=False, skip_staging=False, stop_previous_version=None, trace_email=None, trace_log=None, trace_token=None, user_output_enabled=None, verbosity='debug', version=None).
DEBUG: API endpoint: [https://appengine.googleapis.com/], API version: [v1beta5]
You are about to deploy the following services:
 - smiling-diode-638/worker/20161109t165841 (from [/Volumes/ownhealth_dev/Backend/worker.yaml])
     Deploying to URL: [https://worker-dot-smiling-diode-638.appspot.com]

Do you want to continue (Y/n)?  Y

DEBUG: No bucket specified, retrieving default bucket.
DEBUG: Using bucket [gs://staging.smiling-diode-638.appspot.com/].
If this is your first deployment, this may take a while...DEBUG: Host: appengine.google.com
DEBUG: _Authenticate configuring auth; needs_auth=False
DEBUG: Sending request to https://appengine.google.com/api/vms/prepare?app_id=smiling-diode-638 headers={'X-appcfg-api-version': '1', 'content-length': '0', 'Content-Type': 'application/octet-stream'} body=
INFO: Attempting refresh to obtain initial access_token
INFO: Refreshing access_token
If this is your first deployment, this may take a while...\DEBUG: Got response: {bucket: vm-containers.smiling-diode-638.appspot.com, path: /containers}

If this is your first deployment, this may take a while...done.

Beginning deployment of service [worker]...
DEBUG: No staging command found for runtime [custom] and environment [MANAGED_VMS].
WARNING: Deployment of App Engine Flexible Environment apps is currently in Beta
INFO: Using Dockerfile found in /Volumes/ownhealth_dev/Backend
Building and pushing image for service [worker]

INFO: Refreshing access_token
INFO: Uploading [/var/folders/d1/lgf326px48s8w6cvj2f7ng200000gp/T/tmplQDUjR/src.tgz] to [us.gcr.io/smiling-diode-638/appengine/worker.20161109t165841:latest]

The image is 3.5GB

it's been more than an hour and it's still deploying.
Edit:
I tried deploying from a local network machine and it's indeed faster to download the image but the deploy is endless and i'm getting Error Response: [4] DEADLINE_EXCEEDED
all the errors I see on that are attached
ERROR: build step "gcr.io/cloud-builders/docker@sha256:1b5a8642d04ef785f7dd2dbb0296f837895f50442fdfe5ebd0b04c206ab0b1b5" failed: exit status 2

where can I check logs for that?
Edit # 2:
I ran it like this
gcloud preview app deploy worker.yaml --image-url=us.gcr.io/smiling-diode-638/basic-algo-docker-v2 --verbosity='debug'

getting
Error Response: [13] Timed out when starting VMs.  It's possible that the application code is unhealthy
But I've added this to the worker.yaml
health_check:
  enable_health_check: False

so how do I disable the health check ??

A: A good chunk of the deployment time is often spent uploading the docker image, largely depending on the image size (in your case pretty big - 3.5GB),  your internet connection upload speed and your server's "closeness" to the GAE region datacenter.
You might get a significant upload speed boost by performing the deployment from a cloud-hosted VM (ideally a GCE machine hosted in the same region as your GAE app).
Building the image also takes time, some of it unavoidable. You might be able to speed it up a bit, see How can I speed up Rails Docker deployments on Google Cloud Platform?
Also, when re-deploying the app some unavoidable additional steps are required compared to the first app deployment, see why does google appengine deployment take several minutes to update service


text:
Q: upgrading database in android studio not working I am trying to updgrade the sqlite version number from 1 to 2 but onupgrade method is not getting called.
do i have to delete application in the device and then install the application to test it ?
Only method which get called is DatabaseHelper and onCreate
No other method get called.
In DatabaseHelper.java file
    private static final int DBVersion = 1; // I had change this value to 2.but it is not working.
    public DatabaseHelper(Context context, CursorFactory cf) {
        super(context, DBName, cf, DBVersion);
    }

 @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TABLE_CREATE_Table);
}
@Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
}
@Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
//This is not called.If it called i will add the changed here
}

another class for dataprovider.java
@Override
    public boolean onCreate() {
        dbHelper = new DatabaseHelper(getContext(), null);
        return true;
    }

A: using :-
@Override
public boolean onCreate() {
    dbHelper = new DatabaseHelper(getContext(), null);
    SqliteDatabase db = dbHelper.getWritableDatabase(); //<<<<<<<<<<<
    return true;
}

attempts to open the database and thus onCreate/onUpgrade would be called.
- onCreate only if the database does not exist.
- onUpgrade only if the database exists AND the specified version number is greater than the database version stored in the database.
That is when instantiating the Database Helper (subclass of SQLiteOpenHelper) no attempt is made to open the database.
The attempt to open the database is only made when the SQLiteDatabase's getWritableDatabase (or getReadableDatabase) are called. Both attempt to open the database. Noting that getWritableDatabase or getReadableDatabase may well be called implicitly.

*

*Note the above does not include directly using the SQliteDatabase's OPEN methods.

Alternative Fix
I personally tend to force the open when constructing the database helper by using :-
public DatabaseHelper(Context context, CursorFactory cf) {
    super(context, DBName, cf, DBVersion);
    this.getWritableDatabase();
}

*

*I tend to save the returned SQLiteDatabase into a class variable and then use that rather than using this.getWritableDatabase() in the underlying methods.


text:
Q: LISTAGG fails with sqlcode=-433 How to overcome from length issue on ListAGG function.

A: Try the XMLAGG function instead:
select
--length (
substr(xmlserialize(
xmlquery('$L/text()' passing XMLAGG(xmlelement(name "a", ','||colname)) as "L") as clob(2M)
), 2)
--)
from syscat.columns;


text:
Q: Replacing String in javascript I have this string
var str="abc test test abc";

How can i replace only second occurence of "abc" string with str.replace()?

A: Here is a more generic version. This will work on the nth occurrence of any query string to be searched and replaced in any input string.
var result, query = 'hello', replacement = 'good', string = 'hello hello world';

var startIndex = 0, index = 0, occurrence = 2, matches = [];

while ((index = string.indexOf(query, startIndex)) > -1) {
    matches.push(index);
    startIndex = index + query.length;
    if (matches.length === occurrence) {
        break;
    }
}

result = string.substring(0, matches[occurrence - 1]) + replacement + string.substring(matches[occurrence - 1] + query.length);

console.log(result);

http://jsfiddle.net/ze6xw8mq/

A: If you just need to replace the second one, you can use below code:
var secondStart = str.indexOf("abc")+"abc".length;
str.substring(0,secondStart)+str.substring(secondStart).replace("abc","new")

The idea is splitting the string into two parts using indexOf.
One generic way is using the callback function in replace method:
 function replaceNthMatch(originalString, searchvalue , newvalue, matchNumber)
{
   var match = 0;
   return originalString.replace(new RegExp(searchvalue, "g"), function(found){
                      match++;
                      return (match===matchNumber)?newvalue:found;
       });
}

var str = "abc test abc test abc"
console.log(replaceNthMatch(str,"abc","new",1))
console.log(replaceNthMatch(str,"abc","new",2))
console.log(replaceNthMatch(str,"abc","new",3))

See : http://jsfiddle.net/wbinglee/h09zt69x/

A: If you want to replace the second occurrence of abc,
var str = "abc test test abc test abc";
str.replace(/\sabc/," ABC");

This would return,
`abc test test ABC test abc`

If you want to replace the last occurrence of abc, you could use,
var str = "abc test test abc test abc";
str.replace(/(.*)abc(.*)/,"$1ABC$2");

Which would return:
abc test test abc test ABC


text:
Q: What is the goal symbol that looks like a book? In Dead by Daylight, sometimes a symbol that looks like a book will be shown in the goal area, next to where the Generator symbol and the number of remaining generators you need to open the gate.
What does this symbol mean?

A: A trapdoor is placed semi-randomly on the map.  It opens when you're the last person alive.
That symbol appears when the trapdoor is open and you can escape using it.
Edit: As of the game's final release, a new requirement is also in place:  At least two generators must be powered before the trapdoor will open.
You can also open the trapdoor early if you have the very rare Skeleton Key item.  This item may only be obtainable through the Bloodweb.


text:
Q: Code too large on Ant in Linux but compiles on Eclipse in Windows I have a java file containing an Enum which is very large. the code compiles on Eclipse with JDK 1.8 but fails to do so on Linux when I do an ant build with the same JDK. It is really weird. But, more importantly, is there a fix for compiling codes that are really huge? My friends told me that from Java 1.7, the compilers do not throw that error. Is it true? Can anybody let me know? Thanks in advance!

A:
A single method in a Java class may be at most 64KB of bytecode.

This is probably a sign that you should refactor your code ...


text:
Q: Network Monitoring on Linux (RHEL/CentOS) I am trying to monitor outgoing network traffic on a Virtual Machine running CentOS (Guest) on a Windows Machine (Host).
I installed Fiddler on the Host Machine (Windows) and allowed remote connections on it so that I can use it as a proxy on the Guest Machine (CentOS).
I am trying to install tableau-server on the Guest Machine (CentOS), and interested in checking the outgoing traffic or the endpoints it uses for it's activation process.
So, while activating tableau-server I pass the proxy, setup via Fiddler to monitor all the traffic.
But the problem is, when I activate tableau-server, I do not get any outgoing traffic, which I think is not possible.
To be sure, I disabled internet connectivity on the Guest Machine (CentOS) thinking it's an offline process, but the activation fails and complains about internet connectivity.
That means, it needs to connect to some endpoints.
But then, why am I not getting anything in Fiddler logs ?
Is it possible that the activation process uses a different protocol instead of http/https ?
If yes, is it possible to whitelist such requests via proxy ?
Can anyone help on this ?
Thanks in advance.

Network Configuration for the VM:

(I can surf the internet on the VM)

A: Here's some pre requisites to activate Tableau with proxy use https://help.tableau.com/current/server-linux/fr-fr/activate.htm
Maybe you missed those requirements.


text:
Q: C#: printing only LAST line in .txt file while file is updating IRTime I manage to write code in C++ that works what is needed. Ill paste it down. But its console application and i need windows form application. So i tried to do it in the  visual studio 2017 and C#.
I need an application that will post on screen, only last line from .txt file but that .txt file needs to be editable while app is running. So when i add new line in .txt and hit ctrl+s it will automaticly update results in app and it will not show me
"NOTEPAD: The process cannot access the file becouse it is being used by another process."
This is the C++ code that works perfect:
std::ifstream ifs("test.log");

if (ifs.is_open())

{std::string line;

    while (true)

    {while (std::getline(ifs, line)) std::cout << line << "\n";
        if (!ifs.eof())
break;
        ifs.clear();
    }
}
return 0;}

it returns last line from test.log file and when i paste new one in test file it automaticly change after saving the changes in test.txt file.
And here is the code that i write in C# and it works BUT after i run it it wont allow me to save changes in file that i ame making changes.
CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text;
using System.IO;

namespace lastone
{
    public partial class last : Form
    {
        public last()
        {
            InitializeComponent();
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Stream myStream;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

                if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {

                    {
                        if ((myStream = openFileDialog1.OpenFile()) != null)
                        {

                            string strfilename = openFileDialog1.FileName;

                        richTextBox1.Text = File.ReadLines(strfilename).Last();

                        }
                    }
                }

        }
    }
}

In this case i load test.txt file with button and openfiledialog... and then just printout last line in richTextbox.
Can anyone give me advice how to make test.txt file editable while my app is working?
And eaven if i manage to bypass that problem how can i make the app that i dont need to open file all over again to finde changes in test.txt? i need it to "refresh" automaticly...
P.S. i am literally NEW to programing so dont judge me :) and i am not native eng speaker so sorry for mistakes. I googled so much stuff that i am only confused... TY for any help.

A: Here's an example console app of how to watch a file for changes with a FileSystemWatcher:
FileSystemWatcher watcher = new FileSystemWatcher();

void Main()
{
    // get file from OFD etc
    watcher.Path = @"c:\temp";
    watcher.Filter = "myfile.txt";
    watcher.Changed += OnChanged;
    watcher.EnableRaisingEvents = true;

    // needed for this example as a console app doesn't have an
    // event loop unlike Windows Forms
    while (true) {
        Thread.Sleep(100);
    }
}

private static void OnChanged(object source, FileSystemEventArgs e)
{
    string line = null;
    using (FileStream logFileStream = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (StreamReader logFileReader = new StreamReader(logFileStream))
    {

        while (!logFileReader.EndOfStream)
        {
            line = logFileReader.ReadLine();
        }
    }

    // Event fires twice unders some circumstances
    // https://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice
    // so ignore the value if it is empty
    if (!string.IsNullOrEmpty(line))
    {
        // do what you want with the line here
        Console.WriteLine("last line: " + line);
    }

}


text:
Q: Is "shop " a CVC word or a CCVC word? Is shop a CVC word?
Or, to rephrase the question, in the CVC structure, do C and V each refer to a single sound or to a single letter?
As I see it, a C or a V means a sound, and a sound could be 1 or 2 letters, so I thought a word like sh-o-p or b-a-th is a CVC word.
Just now someone told me that in CVC, C or V refer to a letter, so shop is a CCVC word.
Is that right or wrong?

A: C and V here only ever refer to sounds, never to letters. The word shop is pronounced either [ʃɒp] or [ʃɑp] depending on your accent, so it's a CVC word: one consonant sound, one vowel sound, and one consonant sound. Letters never matter.

A: English orthography and phonology are very different. And syllable structure has nothing to do with orthography, it's about sounds. So it's CVC word.


text:
Q: component hierarchy and onChange functions in React I am trying to make a system to help standardize form inputs and validation for our app and I'm not sure how to handle change events properly.
I am setting up components in the following structure, Starting at the bottom and working up:

*

*NumberInput: a managed <input> field that makes sure only numeric values and has settings to allow/disallow decimals, max/min values etc. This is like type="number" except I can make it behave the way I want. It is the initial source of all the onChange events. and controls which characters can be entered, etc.

*YearInput. Invokes a NumberInput and automatically adds maxLength 4 and other specific things to it.

*Form Field component. looks like <YearinputField label="Birth Day" name="">. Used to standardize error reporting, labels and form wrapper divs. Will have <inputField component and pass the actual inputs in this.props.children. Would need to get validation messages from children and from parent potentially (parent knows if field is invalid based on external logic, child knows if a year isn't valid for instance.

*Form level component: knows business logic, handles updating state or making calls to store, etc. Needs to be able to respond to value changes in the inputs. I would like not to need to change much about how these components work. Right now they have a pattern where I call onChange={this.handleChange.bind(this, 'field-name')} and it would be awesome to be able to keep those intact. I would like for whether I'm using a regular input, a YearInput, or NumberInput not to affect how this component works.

One thing that's catching me is if the NumberInput component knows its invalid, how does it tell the FieldInput to add the error class to its containing div? I think the parent passing in restrictions can be covered by either passing in a function or props like 'maximum', and 'minimum'.
The main thing though, is I'm not sure what passing down of business I have to set up for the parent component to fire an onChange and know the value of the input at the end of the change.
I want every component except the very top one to be 'dumb' and have no knowledge of any of the application architecture. Are there any patterns or examples I could use to help me figure this out?


text:
Q: Angular NGXS TypeError: Cannot freeze
The code that dispatches the action
  constructor(auth: AuthService, private store: Store) {
    this.userAuth = auth.signedIn.subscribe({ next: (user) => {
      this.user = user;
      this.store.dispatch(new SetUser(user));
    }});
  }

The actions definition
import firebase from 'firebase/app';

export class SetUser {
  static readonly type = '[firebase.User | null] Add';

  constructor(public payload: firebase.User | null) {}
}

And my store implementation:
    @Action(SetUser)
    add({ patchState }: StateContext<UserStateModel>, { payload }: SetUser): void {
        patchState({
            user: payload
        });
    }
@State<UserStateModel>({
    name: 'user',
    defaults: {
        user: null
    }
})

A: Make static readonly type = '[firebase.User | null] Add'; non-static, like so:
static type = '[firebase.User | null] Add';
Since we can't see your whole code (e.g. you post some constructor without any class around) and you won't let us (see comments), that's my best guess following the error-message complaining about some readonly property.
Otherwise there might be some readonly properties in firebase.User, how about that?
You insert something in the store that NGXS is trying to freeze. "Freezing" involves some kind of overwriting which is not allowed on readonly properties. Now it's on you to find what's readonly in there in case my two hints above didn't help.


text:
Q: Server sent events and browser limits I have a web application that listens for Server Sent Events. While I was working and testing with multiple windows open, things were not working and I banged my head for several times looking in the wrong direction: eventually, I realized that the problem was concurrent connections.
However I was testing a very limited number and even if I am running the test on Apache (I know, I should use node).
I then, switched browser and noticed something really interesting: apparently Chrome limits Server Sent Events connections to 4-5, while Opera doesn't. Firefox, on the other hand, after 4-5 simultaneous connections, refuses to load any other page.
What is the reason behind this? Does the limit only apply to SSE connections from the same source, or would it be the same if I were to test open them from a different domain? Is there any chance that I am misusing SSE and this is actually blocking the browsers, or this is a known behaviour? Is there any way around it?

A: One way to get around this issue is to shut down the connections on all the hidden tabs, and reconnect when the user visits a hidden tab.
I'm working with an application that uniquely identifies users which allowed me to implement this simple work-around:

*

*When users connect to sse, store their identifier, along with a timestamp of when their tab loaded. If you are not currently identifying users in your app, consider using sessions & cookies.

*When a new tab opens and connects to sse, in your server-side code, send a message to all other connections associated with that identifier (that do not have the current timestamp) telling the front-end to close down the EventSource. The front-end handler would look something like this:
myEventSourceObject.addEventListener('close', () => {
  myEventSourceObject.close();
  myEventSourceObject = null;
});

*Use the javascript page visibility api to check to see if an old tab is visible again, and re-connect that tab to the sse if it is.
document.addEventListener('visibilitychange', () => {
  if (!document.hidden && myEventSourceObject === null) {
    // reconnect your eventsource here
  }
});

*If you set up your server code like step 2 describes, on re-connect, the server-side code will remove all the other connections to the sse. Hence, you can click between your tabs and the EventSource for each tab will only be connected when you are viewing the page.
Note that the page visibility api isn't available on some legacy browsers:
https://caniuse.com/#feat=pagevisibility

A: The way this works in all browsers are that each domain gets a limited amount of connections and the limits are global for your whole application. That means if you have one connection open for realtime communication you have one less for loading images, CSS and other pages. On top of that you don't get new connections for new tabs or windows, all of them needs to share the same amount of connections. This is very frustrating but there are good reasons for limiting the connections. A few years back, this limit was 2 in all browsers (based on the rules in (http://www.ietf.org/rfc/rfc2616.txt) HTTP1.1 spec) but now most browsers use 4-10 connections in general. Mobile browsers on the other hand still needs to limit the amount of connections for battery saving purposes.
These tricks are available:

*

*Use more host names. By assigning ex. www1.example.com, www2.example.com you get new connections for each host name. This trick works in all browsers. Don't forget to change the cookie domain to include the whole domain (example.com, not www.example.com)

*Use web sockets. Web sockets are not limited by these restrictions and more importantly they are not competing with the rest of your websites content.

*Reuse the same connection when you open new tabs/windows. If you have gathered all realtime communication logic to an object call Hub you can recall that object on all opened windows like this:

window.hub = window.opener ? window.opener.hub || new Hub()
4. or use flash - not quite the best advice these days but it might still be an option if websockets aren't an option.
5. Remember to add a few seconds of time between each SSE request to let queued requests to be cleared before starting a new one. Also add a little more waiting time for each second the user is inactive, that way you can concentrate your server resources on those users that are active. Also add a random number of delay to avoid the Thundering Herd Problem
Another thing to remember when using a multithreaded and blocking language such as Java or C# you risk using resources in your long polling request that are needed for the rest of your application. For example in C# each request locks the Session object which means that the whole application is unresponsive during the time a SSE request is active.
NodeJs is great for these things for many reasons as you have already figured out and if you were using NodeJS you would have used socket.io or engine.io that takes care of all these problems for you by using websockets, flashsockets and XHR-polling and also because it is non blocking and single threaded which means it will consume very little resources on the server when it is waiting for things to send. A C# application consumes one thread per waiting request which takes at least 2MB of memory just for the thread.

A: 2022 Update
This problem has been fixed in HTTP/2.
According to mozilla docs:-
When not used over HTTP/2, SSE suffers from a limitation to the maximum number of open connections, which can be especially painful when opening multiple tabs, as the limit is per browser and is set to a very low number (6).
The issue has been marked as "Won't fix" in Chrome and Firefox.
This limit is per browser + domain, which means that you can open 6 SSE connections across all of the tabs to www.1.example and another 6 SSE connections to www.2.example (per Stackoverflow).
When using HTTP/2, the maximum number of simultaneous HTTP streams is negotiated between the server and the client (defaults to 100).
Spring Boot 2.1+ ships by default with Tomcat 9.0.x which supports HTTP/2 out of the box when using JDK 9 or later.
If you are using any other backend, please enable http/2 to fix this issue.

A: You are right about the number of simultaneous connections.
You can check this list for max values: http://www.browserscope.org/?category=network
And unfortunately, I never found any work around, except multiplexing and/or using different hostnames.


text:
Q: share ssh session/key with remote user Assume the following setup:

*

*User bob is working locally on his workstation foo.

*User alice is working locally on her workstation bar.

*User bob has ssh access to server baz:22 via a key stored at bob@foo:.ssh/id_rsa.

*User alice has ssh access to bob's workstation foo:22 but not to server baz.

Is there a way for bob to ssh to baz sharing his session (via port forwarding?) or key (via ssh-agent forwarding?) such that alice can access baz from bar via foo (assuming bob's identity on foo)?

Addendum:
There are a few more thinks that I should have clarified:

*

*bob doesn't want alice to know his password

*bob doesn't want alice to be able to run rm -rf /home/bob on foo (on baz however that would be fine obviously).

As suggested by @mukesh-sai-kumar,
one could have alice login to foo (as bob?) and ssh with the shared key from there.
The best approach I can see so far would be to create a new key-pair for alice on bar, allow the public key on foo and automatically run the ssh bob@baz via the command="ssh [...]" option in the authorized_keys file.
This would allow to setup ssh baz on bar to actually ssh bob@foo using the new key-pair via alice@bar:.ssh/config with the forwarding of bob@foo logins using this specific key to bob@baz via bob@foo:.ssh/authorized_keys (authorizing alice's key but restricting command to the ssh baz call).
This way, the two new constraints would be met and alice wouldn't even see anything as this hypothetical interactive session shows:
[alice@foo:~] (1) $ hostname
foo
[alice@foo:~] (2) $ whoami
alice
[alice@foo:~] (3) $ ssh baz
[bob@baz:~] (1) $ hostname
baz
[bob@baz:~] (2) $ whoami
bob
[bob@baz:~] (3) $ exit
[alice@foo:~] (4) $ hostname
foo
[alice@foo:~] (5) $ whoami
alice
[alice@foo:~] (6) $

The only remaining problem is that bob's ssh key on foo needs to be shared with bob's session initiated by the ssh from alice (via ssh-agent?) .

A: Solution: Nested SSH session.
alice may log into bob's workstation (foo:22) via SSH with the identity of bob, and then log into baz via SSH with bob's identity (and his key, as they both are now accessible to alice).
A command-based representation of this:
alice@bar:~$ ssh bob@foo
bob@foo's password:
---snip----
bob@foo:~$ ssh -i /home/bob/.ssh/id_rsa (your-user)@baz
----RSA ID based authentication----
your-user@baz:~$

Diagrammatical representation:
alice@bar -> Log into foo as user bob -> use bob's stored key to log into baz -> Achieved!

A: Alice can give Bob her public key, and Bob can add a line to his own .ssh/authorized_keys file that will allow Alice to start a ssh session (as Bob) on Bob's workstation foo. Using the command= option, Bob can restrict Alice's key to not grant an interactive shell, but a nested ssh connection to baz as Bob, and using a key locally accessible to Bob on bar.
command="ssh -I .ssh/id_rsa bob@baz:22" ssh-rsa AAA...== alice@whatever
Optionally, you can include further constraint options (no-port-forwarding, from=, etc. - see sshd man page section on AUTHORIZED_KEYS FILE FORMAT).
When Alice runs ssh bob@bar and authenticates with her private key, she will be connected through bar to a ssh session on baz, without having any control over the intermediate session on Bob's workstation.
Note that from the perspective of baz (logging, security audit), there is no distinction between this tunneled connection initiated by Alice, and a "normal" connection by Bob from his own workstation. This may be what you asked for, but not what you want.
For making the protected key available to Alice for her session, you can explicitly set the environment variable SSH_AUTH_SOCK to be the path that Bob uses for his session (change the authorized_keys entry to command="SSH_AUTH_SOCK=/path/to/bobs/agent_socket ssh bob@baz:22" ssh-rsa AAA...) To avoid having to update the path when it changes (logoff/login typically), Bob can run a dedicated agent on Alice's behalf with an explicit path specified (ssh-agent -a ~/.ssh/agent_for_alice and add only the specific key with SSH_AUTH_SOCK=~/.ssh/agent_for_alice ssh-add ~/.ssh/id_rsa and entering the passphrase.


text:
Q: Docker image problem when running "sam invoke" on the AWS Quick Start "Hello World Example" I'm trying to run sam local invoke HelloWorldFunction
after a simple sam init choosing the template 1 - AWS Quick Start Templates 1 - Hello World Example on Mac OS Ventura 13.1 (22C65) using Apple Silicon M2 CPU.
It doesn't manage to download / build the Docker image :
Bad Gateway for url: http+docker://localhost/v1.35/build?t=public.ecr.aws%2Fsam%2Femulation-python3.9%3Arapid-1.70.0-x86_64&q=False&nocache=False&rm=True&forcerm=False&pull=True&platform=linux%2Famd64

docker.errors.APIError: 502 Server Error: Bad Gateway ("b'Bad response from Docker engine'")

Here's the install output :
sam init

You can preselect a particular runtime or package type when using the `sam init` experience.
Call `sam init --help` to learn more.

Which template source would you like to use?
        1 - AWS Quick Start Templates
        2 - Custom Template Location
Choice: 1

Choose an AWS Quick Start application template
        1 - Hello World Example
        2 - Multi-step workflow
        3 - Serverless API
        4 - Scheduled task
        5 - Standalone function
        6 - Data processing
        7 - Infrastructure event management
        8 - Serverless Connector Hello World Example
        9 - Multi-step workflow with Connectors
        10 - Lambda EFS example
        11 - Machine Learning
Template: 1

Use the most popular runtime and package type? (Python and zip) [y/N]: y

Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]:

Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]:

Project name [sam-app]:

Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)

    -----------------------
    Generating application:
    -----------------------
    Name: sam-app
    Runtime: python3.9
    Architectures: x86_64
    Dependency Manager: pip
    Application Template: hello-world
    Output Directory: .

    Next steps can be found in the README file at ./sam-app/README.md

Commands you can use next
=========================
[*] Create pipeline: cd sam-app && sam pipeline init --bootstrap
[*] Validate SAM template: cd sam-app && sam validate
[*] Test Function in the Cloud: cd sam-app && sam sync --stack-name {stack-name} --watch

Here's the output when running sam local invoke HelloWorldFunction
Invoking app.lambda_handler (python3.9)
Image was not found.
Removing rapid images for repo public.ecr.aws/sam/emulation-python3.9
Building image...
Failed to build Docker Image
Traceback (most recent call last):
  File "/opt/homebrew/Cellar/aws-sam-cli/1.70.0/libexec/lib/python3.11/site-packages/docker/api/client.py", line 261, in _raise_for_status
    response.raise_for_status()
  File "/opt/homebrew/Cellar/aws-sam-cli/1.70.0/libexec/lib/python3.11/site-packages/requests/models.py", line 943, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 502 Server Error: Bad Gateway for url: http+docker://localhost/v1.35/build?t=public.ecr.aws%2Fsam%2Femulation-python3.9%3Arapid-1.70.0-x86_64&q=False&nocache=False&rm=True&forcerm=False&pull=True&platform=linux%2Famd64

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/homebrew/Cellar/aws-sam-cli/1.70.0/libexec/lib/python3.11/site-packages/samcli/local/docker/lambda_image.py", line 273, in _build_image
    for log in resp_stream:
  File "/opt/homebrew/Cellar/aws-sam-cli/1.70.0/libexec/lib/python3.11/site-packages/docker/api/client.py", line 354, in _stream_helper
    yield self._result(response, json=decode)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/aws-sam-cli/1.70.0/libexec/lib/python3.11/site-packages/docker/api/client.py", line 267, in _result
    self._raise_for_status(response)
  File "/opt/homebrew/Cellar/aws-sam-cli/1.70.0/libexec/lib/python3.11/site-packages/docker/api/client.py", line 263, in _raise_for_status
    raise create_api_error_from_http_exception(e)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/aws-sam-cli/1.70.0/libexec/lib/python3.11/site-packages/docker/errors.py", line 31, in create_api_error_from_http_exception
    raise cls(e, response=response, explanation=explanation)
docker.errors.APIError: 502 Server Error: Bad Gateway ("b'Bad response from Docker engine'")
Error: Building Image failed.

And with the --debug option :
sam local invoke HelloWorldFunction --debug
2023-01-22 11:29:05,782 | Config file location: /Users/frog/test_sam_init/sam-app/samconfig.toml
2023-01-22 11:29:05,782 | Config file '/Users/frog/test_sam_init/sam-app/samconfig.toml' does not exist
2023-01-22 11:29:05,784 | Using SAM Template at /Users/frog/test_sam_init/sam-app/template.yaml
2023-01-22 11:29:05,798 | Using config file: samconfig.toml, config environment: default
2023-01-22 11:29:05,798 | Expand command line arguments to:
2023-01-22 11:29:05,798 | --template_file=/Users/frog/test_sam_init/sam-app/template.yaml --function_logical_id=HelloWorldFunction --no_event --layer_cache_basedir=/Users/marc/.aws-sam/layers-pkg --container_host=localhost --container_host_interface=127.0.0.1
2023-01-22 11:29:05,798 | local invoke command is called
2023-01-22 11:29:05,800 | No Parameters detected in the template
2023-01-22 11:29:05,809 | There is no customer defined id or cdk path defined for resource HelloWorldFunction, so we will use the resource logical id as the resource id
2023-01-22 11:29:05,809 | There is no customer defined id or cdk path defined for resource ServerlessRestApi, so we will use the resource logical id as the resource id
2023-01-22 11:29:05,809 | 0 stacks found in the template
2023-01-22 11:29:05,809 | No Parameters detected in the template
2023-01-22 11:29:05,815 | There is no customer defined id or cdk path defined for resource HelloWorldFunction, so we will use the resource logical id as the resource id
2023-01-22 11:29:05,815 | There is no customer defined id or cdk path defined for resource ServerlessRestApi, so we will use the resource logical id as the resource id
2023-01-22 11:29:05,815 | 2 resources found in the stack
2023-01-22 11:29:05,815 | Found Serverless function with name='HelloWorldFunction' and CodeUri='hello_world/'
2023-01-22 11:29:05,815 | --base-dir is not presented, adjusting uri hello_world/ relative to /Users/frog/test_sam_init/sam-app/template.yaml
2023-01-22 11:29:05,829 | Found one Lambda function with name 'HelloWorldFunction'
2023-01-22 11:29:05,829 | Invoking app.lambda_handler (python3.9)
2023-01-22 11:29:05,829 | No environment variables found for function 'HelloWorldFunction'
2023-01-22 11:29:05,829 | Loading AWS credentials from session with profile 'None'
2023-01-22 11:29:05,834 | Resolving code path. Cwd=/Users/frog/test_sam_init/sam-app, CodeUri=/Users/frog/test_sam_init/sam-app/hello_world
2023-01-22 11:29:05,834 | Resolved absolute path to code is /Users/frog/test_sam_init/sam-app/hello_world
2023-01-22 11:29:05,834 | Code /Users/frog/test_sam_init/sam-app/hello_world is not a zip/jar file
2023-01-22 11:29:05,839 | Image was not found.
2023-01-22 11:29:05,839 | Removing rapid images for repo public.ecr.aws/sam/emulation-python3.9
Building image...
2023-01-22 11:29:06,495 | Failed to build Docker Image
Traceback (most recent call last):
  File "/opt/homebrew/Cellar/aws-sam-cli/1.70.0/libexec/lib/python3.11/site-packages/docker/api/client.py", line 261, in _raise_for_status
    response.raise_for_status()
  File "/opt/homebrew/Cellar/aws-sam-cli/1.70.0/libexec/lib/python3.11/site-packages/requests/models.py", line 943, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 502 Server Error: Bad Gateway for url: http+docker://localhost/v1.35/build?t=public.ecr.aws%2Fsam%2Femulation-python3.9%3Arapid-1.70.0-x86_64&q=False&nocache=False&rm=True&forcerm=False&pull=True&platform=linux%2Famd64

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/homebrew/Cellar/aws-sam-cli/1.70.0/libexec/lib/python3.11/site-packages/samcli/local/docker/lambda_image.py", line 273, in _build_image
    for log in resp_stream:
  File "/opt/homebrew/Cellar/aws-sam-cli/1.70.0/libexec/lib/python3.11/site-packages/docker/api/client.py", line 354, in _stream_helper
    yield self._result(response, json=decode)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/aws-sam-cli/1.70.0/libexec/lib/python3.11/site-packages/docker/api/client.py", line 267, in _result
    self._raise_for_status(response)
  File "/opt/homebrew/Cellar/aws-sam-cli/1.70.0/libexec/lib/python3.11/site-packages/docker/api/client.py", line 263, in _raise_for_status
    raise create_api_error_from_http_exception(e)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/aws-sam-cli/1.70.0/libexec/lib/python3.11/site-packages/docker/errors.py", line 31, in create_api_error_from_http_exception
    raise cls(e, response=response, explanation=explanation)
docker.errors.APIError: 502 Server Error: Bad Gateway ("b'Bad response from Docker engine'")
2023-01-22 11:29:06,498 | Cleaning all decompressed code dirs
2023-01-22 11:29:06,498 | Telemetry endpoint configured to be https://aws-serverless-tools-telemetry.us-west-2.amazonaws.com/metrics
Error: Building Image failed.


text:
Q: How to make a custom button provide haptic feedback I've got a custom round button that is derived from Ubuntu.Components.AbstractButton. Looking at the documentation, it states that:

All components deriving from this class support haptic feedback out of the box.

However, my button does not provide haptic feedback when pressed. How exactly can it be enabled for custom buttons?

A: Abstract Buttons do indeed come with haptic feedback out of the box and does not require any special properties to enable it. It sounds like you are experiencing a bug. Perhaps if you can add the code of your custom round button, one can confirm and check if it works on our end or not.


text:
Q: Hacer aparecer el reCaptcha a partir despues del 3º intento El código siguiente muestra un recaptcha a los 3 intentos de login.
Realiza todas las consultas, inserta y elimina datos de la tabla. Lo que deseo es utilizar bien la variable del formulario del recaptcha por que me deja pasar si no presiono el recaptcha.
Este es el código:
<?php
  include_once "conexion/clsConexion.php";
  require_once "recaptchalib.php";
  $obj = new clsConexion;
  $ip = $_SERVER['REMOTE_ADDR'];
  $consulta_ip = $obj->consultar("SELECT count(direccion_ip) AS login_intentos_fallidos FROM intentos_fallidos WHERE direccion_ip = '$ip' AND fecha_login_fallido BETWEEN DATE_SUB( NOW() , INTERVAL 1 DAY ) AND NOW()");
  foreach ((array) $consulta_ip as $row) {
    $intentos_fallidos = $row['login_intentos_fallidos'];
  }
?>
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>SANTA MARIA REYNA | Login</title>

<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

<link rel="stylesheet" href="plugins/bootstrap/css/bootstrap.min.css">

            <img src="configuracion/foto/<?php echo $logo ?>" width="150" height="150" />

Por favor ingrese su codigo y clave.

        <form name="form1" method="post" action="">

                <input type="text" class="form-control" name="codigo" id="username" required placeholder="codigo" autocomplete="off" />

                <input type="password" class="form-control" name="clave" id="password" required placeholder="clave" autocomplete="off" />

            <?php if (isset($intentos_fallidos) && $intentos_fallidos >= 3) {?>

            <?php }?>

                <button type="submit" value="Ingresar" class="btn btn-primary btn-block btn-flat">  Entrar</button>

        </form>

            2017 - All rights reserved.

<?php
    session_start();
    if (!empty($_POST['g-recaptcha-response'])) {
        //Asignas la clave secreta a una variable llamada $claveSecreta
        $claveSecreta = "6LfKazQUAAAAAJFGcTeZ4HfwKuRwvXTY3ZF_A3aR";
        // Por default asumimos que tenemos una respuesta vacía
        $respuesta = null;
        //Creamos una instancia de la clase que incluimos
        $captcha = new ReCaptcha($claveSecreta);
        //Validamos que si hayamos recibido por post la respuesta que recibimos de google al validar el captcha
        if ($_POST["g-recaptcha-response"]) {
            //Le pedimos a google que valide la respuesta del captcha para ello enviamos nuestro dominio y la respuesta
            $respuesta = $captcha->verifyResponse
            (
                $_SERVER['REMOTE_ADDR'],
                $_POST["g-recaptcha-response"]
            );
        }
    }
    if (!empty($_POST['codigo']) and !empty($_POST['clave'])) {
        $codigo = trim($obj->real_escape_string(htmlentities(strip_tags($_POST['codigo'], ENT_QUOTES))));
        $clave = trim($obj->real_escape_string(htmlentities(strip_tags($_POST['clave'], ENT_QUOTES))));
        $clavemd5 = md5($clave);
        $resultapo = $obj->consultar("select * from usuario where codigo='" . $obj->real_escape_string($codigo) . "' and clave='" . $obj->real_escape_string($clavemd5) . "'");
        foreach ((array) $resultapo as $row) {
        $valor = $row['codigo'];
        $estado = $row["estado"];
        $tipo = $row["tipo"];
        $obj->ejecutar("DELETE FROM intentos_fallidos WHERE direccion_ip = '$ip'");
    }
    //si el codigo no existe en la bd manda el mensaje de error es como decir $row['codigo']=nulo
    if (isset($valor) == '') {
        echo "";
        if ($intentos_fallidos < 3) {
            $obj->ejecutar("INSERT INTO intentos_fallidos (direccion_ip,fecha_login_fallido) VALUES ('$ip', NOW())");
        }
        } else if ($estado != 'ACTIVO') {
            echo "";
        } else if ($tipo == 'ADMIN') {
            // esta sesion de autentificado lo pongo 1 para seguridad i despues haga la comprobacion si no es igual a 1 se redireccion al inicio
            $_SESSION["autentificado"] = 1;
            $_SESSION["codigo"] = $codigo;
            $_SESSION["clave"] = $clavemd5;
            header('location:inicio/index.php');
        }
    }
?>

A: veo muy innecesario tener que guardar los intentos fallidos en una tabla, lo que podes hacer es almacenar los intentos en una variable de sesion, un contador y cuando llegue a 3 que te aparezca el captcha, no guardarlo en una tabla. Una vez que logre ingresar correctamente entonces eliminas la variable de session.
Saludos


text:
Q: How do I add numbers together using loops? def adding():
    total = 0
    x = 0
    while x != 'done':
        x = int(raw_input('Number to be added: '))
        total = x + total
        if x == 'done':
            break
    print total

I cant figure out how to add numbers that a user is inputing, and then stop and print the total when they input 'done'

A: I'm assuming it's yelling at you with a ValueError when the user inputs "done"? That's because you're trying to cast it as an int before checking if it's a number or the sentinel. Try this instead:
def unknownAmount():
    total = 0
    while True:
        try:
            total += int(raw_input("Number to be added: "))
        except ValueError:
            return total

Alternatively, you can change your own code to work by doing:
def unknownAmount():
    total = 0
    x = 0
    while x != "done":
        x = raw_input("Number to be added: ")
        if x == "done":
            continue
        else:
            total += int(x)
    return total

But beware that if the user enter "foobar", it will still throw a ValueError and not return your total.
EDIT: To address your additional requirement from the comments:
def unknownAmount():
    total = 0
    while True:
        in_ = raw_input("Number to be added: ")
        if in_ == "done":
            return total
        else:
            try:
                total += int(in_)
            except ValueError:
                print "{} is not a valid number".format(in_)

This way you check for the only valid entry that's NOT a number first ("done") then holler at the user if the cast to int fails.

A: There are many similar questions here, but what the hell. Simplest would be:
def adding():
    total = 0
    while True:
        answer = raw_input("Enter an integer: ")
        try:
            total += int(answer)
        except ValueError:
            if answer.strip() == 'done':
                break
            print "This is not an integer, try again."
            continue
    return total

summed = adding()
print summed

More fancy take on problem would be:
def numbers_from_input():
    while True:
        answer = raw_input("Enter an integer (nothing to stop): ")
        try:
            yield int(answer)
        except ValueError:
            if not answer.strip(): # if empty string entered
                break
            print "This is not an integer, try again."
            continue

print sum(numbers_from_input())

but here are some python features you may not know if you are begginer


text:
Q: .add() in java AWT not working after actionPerformed I am fairly new to coding and have encountered this issue within my code.
I create a button using the Java AWT import. I then check for a response using a while loop and wish to create another button after, however .add() seems to no longer function.
import java.awt.*;
import java.awt.event.*;

public class Main1
{
    public static void main(String[] args)
    {
       Frame f = new Frame();
       f.setSize(500, 500);
       f.setVisible(true);
       ButtonPanel bp = new ButtonPanel(f);

       bp.x = null;
       while (bp.x == null)
       {
       }
       System.out.println(bp.x);

       //THE ISSUE- THIS WILL NOT APPEAR AFTER BUTTON PRESS
       f.add("South", new Button("REEE"));
    }
}

class ButtonPanel extends Panel implements ActionListener
{
    volatile String x;
    public ButtonPanel(Frame f)
    {
        Button b = new Button("Hi");
        b.addActionListener(this);
        f.add("North", b);
    }

    public void actionPerformed(ActionEvent e)
    {
        x = e.getActionCommand();
    }
}

I have been trying solutions for this for the last day or so and nothing seems to be working. I've seen in other posts people have said to use Wait/Notify however I am not too sure how those work and I would like to know explicitly what is going wrong in my program (though I am still open to using Wait/Notify in my solution).
Any help would be appreciated, thank you very much

A: So, they're a number of issues at play here.
The first is the fact that layout managers are generally lazy.  This means that you can add and/or remove a number of components quickly and then do a single layout and paint pass.
To do this, you need to revalidate the Container which was updated.
Next, AWT (and Swing by extension) is based on Model-View-Controller concept, one aspect of this is the "observer pattern".  This is basically a callback concept that allows you to be notified when something of interest happens.
Button makes use of an ActionListener to generate events when the button is "actioned".  This is the "observer pattern" in action.
Why is this important?  You really want to think about what information is needed to be passed where and who's actually responsible for doing what.
For example, is it really the ButtonPanel's responsibility to update the frame? Is giving ButtonPanel unfettered control over the frame really a good idea?
Instead, ButtonPanel "should" be providing some kind of notification when some action has occurred and then any interested parties should be able to do what ever they need to.
As a "basic" example...
import java.awt.Button;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.EventListener;
import javax.swing.event.EventListenerList;

public class Test {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test();
            }
        });
    }

    public Test() {
        Frame f = new Frame();
        f.setPreferredSize(new Dimension(500, 500));
        f.pack();

        ButtonPanel bp = new ButtonPanel(f);
        bp.addObsever(new Observer() {
            @Override
            public void hiWasPerformed() {
                f.add("South", new Button("REEE"));
                f.revalidate();
            }
        });

        f.setVisible(true);
    }

    public interface Observer extends EventListener {
        public void hiWasPerformed();
    }

    class ButtonPanel extends Panel  {

        private EventListenerList eventListener = new EventListenerList();

        public ButtonPanel(Frame f) {
            Button b = new Button("Hi");
            b.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Observer[] listeners = eventListener.getListeners(Observer.class);
                    for (Observer observer : listeners) {
                        observer.hiWasPerformed();
                    }
                }
            });
            f.add("North", b);
        }

        public void addObsever(Observer observer) {
            eventListener.add(Observer.class, observer);
        }

        public void removeObsever(Observer observer) {
            eventListener.remove(Observer.class, observer);
        }
    }
}

A: It looks like nothing is happening because the buttons are being added below the bottom of the window. You should consider using a layout manager to solve this issue.
However, in the meantime the simple solution is to move this line f.add("South", new Button("REEE")); inside the action event and to make use of Frame.pack();:
public class Main1
{
    public static void main(String[] args)
    {
       Frame f = new Frame();
       //set minimums rather than a fixed size
       f.setMinimumSize(new Dimension(500, 500));
       f.setVisible(true);
       CustomButton b = new CustomButton(f);

       //Add this line to update/size/show the UI
       f.pack();

       //Don't place any more code inside the main method. Future events should be triggered by interacting with the UI/buttons
    }
}

Then for the button we don't need to extend Panel, we can do something like this:
class CustomButton implements ActionListener
{
    Frame parentFrame;
    public CustomButton(Frame f)
    {
        parentFrame = f;
        Button b = new Button("Hi");
        b.addActionListener(this);
        f.add("North", b);
    }

    public void actionPerformed(ActionEvent e)
    {
        //Add button here instead of the main class
        parentFrame.add("South", new Button("REEE"));
        //The buttons are being added below the bottom of your window, this will force them to be shown.
        //Using a layout manager will solve this ploblem and you will not need to do this:
        parentFrame.pack();
    }
}

Note: clicking on the "Hi" button multiple times will have interesting results of the "REEE" buttons overlapping or doing odd things if you resize the window.


text:
Q: Uniform convergence,quick proof I am trying to prove the uniformly convergence to exp(-x):
$$f_n(t) = \left\{ \begin{array}{ll}
        \left(1-\frac{x}{n}\right)^n & \mbox{if } x\in [0,n] \\
        0 & \mbox{if } x\geq n
    \end{array}
\right.
$$
But my proof is long and ugly so I imagine there is a better demonstration. If anyone knows a quick proof...
Thanks in advance

A: Since $1-x \le e^{-x}$, we have that $(1-\frac xn)^{n} \le (e^{x/n})^n = e^{-x}$.
Given $\epsilon>0$, if $x > \ln(1/\epsilon)$, then $e^{-x} < \epsilon$.  So we need only prove uniform convergence on finite intervals.
So fix $L>0$.  Find $N \ge L$ such that for $y \ge N$, $(1-\frac Ly)^y \ge e^{-L}(1 - \epsilon)$.  Then for $x \in [0,L]$, and $n \ge N$, since $Ln/x \ge N$, we have $(1-\frac xn)^n = ((1-\frac{L}{Ln/x})^{Ln/x})^{x/L} \ge (e^{-L}(1 - \epsilon))^{x/L} \ge e^{-x}(1-\epsilon)$.
Note we use that $(1-x)^\alpha \ge 1-x$ if $0\le x \le 1$ and $0 \le \alpha \le 1$ in the last step.

A: First proof. As noted by Stephen Montgomery-Smith, it is enough to prove the uniform convergence on segments $[0,K]$ for all $K > 0$.
Let us recall that if two sequences $(a_i)$ and $(b_i)$ satisty $|a_i| \leq 1$ and $|b_i|\leq 1$ for all $i$ then $\left|\prod_{i=1}^n a_i - \prod_{i=1}^n b_i\right| \leq \sum_{i=1}^n |a_i-b_i|$. Using this with $a_i = (1-x/n)$ and $b_i = e^{-x/n}$ and the first-order Taylor expansion of $e^{-x}$, we obtain that for all $x \in [0,K]$,
$$
\left|f_n(x) - e^{-x}\right| \leq n \left|e^{-x/n} -1 + \frac{x}{n}\right| \leq n\frac{x^2}{2n^2} \leq \frac{K^2}{2n}
$$
and the uniform converge is now obvious.
Second proof.
Using the inequalities $e^{-u/(1-u)} \leq 1-u \leq e^{-u}$ for $0 \leq u \leq 1$ with $u = \frac{x}{n}$, we obtain again for all $x \in [0,K]$,
$$
0 \leq e^{-x} - f_n(x) \leq e^{-x}\left(1-e^{-\frac{x^2}{n-x}}\right) \leq e^{-0}\frac{K^2}{n-K} \xrightarrow[n\to\infty]{} 0.
$$
Third proof. Apply the following lemma due to George Pólya : given a sequence of functions $f_n \colon [0,\infty] \to \Bbb R$ and $f\colon [0,\infty] \to \Bbb R$ such that

*

*the function $f$ is continuous,

*for all $n$, the function $f_n$ is decreasing,

*for all $x \in [0,\infty]$, the sequence $f_n(x))$ converges to $f(x)$ as $n \to \infty$;

then $f_n$ converges uniformly to $f$ on $[0,\infty]$.


text:
Q: Typescript not inferring types in switch statement when generics and conditionals are used in the type definition I have a type definition for a function. I'm defining the type of the second argument as conditional on the type of the first argument, like so:
const FOO = "FOO";
const BAR = "BAR";

let fooPayload = {
    zip: "zap"
}
let barPayload = {
    cat: "dog"
}

type ActionTypes = typeof FOO | typeof BAR;
interface MyFunction<T extends ActionTypes = ActionTypes> {
  (
    action: {
      type: T;
      payload: T extends typeof FOO
        ? typeof fooPayload
        : typeof barPayload;
    }
  ): boolean;
}

The function that MyFunction interface refers to has a switch statement within it that switches based on action.type and, depending on the case, does something with action.payload. Here's an example:
const myFunction:MyFunction = (action) => {
    switch (action.type) {
        case FOO:
            action.payload.zip = "new zap"
            return true
        case BAR:
            action.payload.cat = "new dog"
            return false
        default:
            return false
    }
}

The issue I'm having is that Typescript isn't correctly inferring what action.payload should be from the switch statement. For example, if action.type is equal to "FOO" then it should infer that action.payload MUST be typeof fooPayload. Instead, it infers that it is typeof fooPayload | typeof barPayload.
This doesn't make any sense as the type definition for action.payload is based on the value of action.type, and since action.payload.zip is being called within a switch statement that can only occur when action.type equals "FOO", it should infer that the only possible type for action.payload is typeof fooPayload.
Here's a code example
What am I doing wrong here?

A: I'm not sure of the exact place this is causing issues but in general the problem is you are trying to reinvent what typescript already does well, narrow type unions.
Conditionals are a really interesting feature but behave a bit unexpectedly sometimes as they leak out of the scope of where they are defined since they are distributive.
I would implement this a different way:
interface Action<T, P> {
    type: T,
    payload: P
}

type Actions
    = Action<typeof FOO, typeof FooPayload>
    | Action<typeof BAR, typeof BarPayload>
    ;

interface MyFunction {
  (action: Actions): boolean;
}

No conditionals needed, and typescript will narrow the unions as expected in the switch.


text:
Q: Bind an array of structures to DataGrid and auto generate columns I am trying to develop a simple testing application that displays a DataGrid comprised of an array of structures.  I have roughly 20 web services that all return arrays of structures, each of a different type of structure, that I would like to bind to the datagrid to verify the data is accurate.
What is the easiest way to generically bind all the columns for each of the various types of structures into the same DataGrid so that it is easy to toggle from one method to the other on the fly?  I know this would be trivial if the structures were classes with public properties, unfortunately, I am stuck with these structs.

A: Use a view model to receive the structs from web services and converts them to classes (These you have to define for each struct). Define DataTemplates for each of your classes in DataGrid.Resources.


text:
Q: How to Solve this task ()=4(/4)+√n? I'm new to Divide and Conquer. I would like to know how to find out the running time of this calculation?
What exactly do I have to pay attention to and how do I proceed?
n=1 runningtime = O(1)

A: so lets see the calculation for this :

T(n) = 4T(n/4) + n * sqrt(n)
  expanding for sum k steps it will be like
T(n) = 4^k[T(n/4^k)] + n * sqrt(n) * {sqrt(1/4)+sqrt(1/16)....}
  here {sqrt(1/4)+sqrt(1/16)....} is Geometric progression
  if we take k=log4(n) //here base is 4
T(n) = n * [T(1)] + n * sqrt(n)*{1-[2/sqrt(n)]}
T(n) = n * [T(1)] + n * sqrt(n) -2 * n

  you still can use
  Master theorem
 T(n) = aT(n/b) + f(n).
If f(n) = Θ(n^d), where d ≥ 0, then
T(n) = Θ(n^d) if a < bd,
T(n) = Θ((n^d)log n) if a = bd,
T(n) = Θ(n^(logba)) if a > bd

yes the ans is O(n^3/2)
{sorry could not comment due to low reputation}


text:
Q: How to get unique short strings from integers? Say, I have a customers with a integer PK. In my web apps I want to have a profile page for them. I do not want a url like /profile/10375/ (For example, I do not want others to know how many customers I have). I also do not want a slug base url like, /profile/acme_corp/.
What is a good way to convert unique integers to unique random short strings? (For example, earlier Reddit used to have this type of urls, but it was a conversion from decimal to base 36, skipping some ids). But that too is not useful for me as it si easy to guess number of entities in DB with this scheme.
I cant use UUID etc, as they would make the url too large.

A: If the primary concern is that one customer can look at another customer's page I wouldn't depend on the method you are proposing.  Ultimately it is "Security Through Obscurity".  I would, instead, tie the display of the page to the customer's authentication credentials (providing you require your users to log in).  If the customer tries to access a profile page other than their own they redirected to the login page or given an access authorization  error message.
In fact you don't even need to have the customerID in the URL.  Just use /profile/

A: There are some hash algorithms which produce short (8 characters, 0-9a-f) output strings, for example adler32 or crc32. You can generate them using PHP function hash() (see hash_algos() for a list of available algorithms), but I'm not sure your DB engine itself can handle it. If that's the case, generating random slugs would be a better solution.
And add salt when hashing, so it's more secure.

A: The easiest and safest way to do this would be to create lookup table with a mapping from the customer id to a unique random string.

A: You could always base64 then url encode the id's.
in php:
urlencode (base64_encode("1234"))
> MTIzNA%3D%3D

base64_decode(urldecode("MTIzNA%3D%3D"))
> 1234

A: maybe you could asociate a random pair of letters of the alphabet to each digit...


text:
Q: Assign each instance of an object a number from a static int to give a unique name C# I have a class Foo in C# that has a string name and I want each one to have a unique name. What I wanted to do is get the name from creating a static int variable and then assigning it to a local instance int variable to which I add to the end of the string. This does not work though, how would I be able to get my desired result.
class Foo
{
    static int count = 0;
    int fooNum;
    string name;

    public Foo
    {
        ++count;
        fooNum = count;
        name = "Foo" + fooNum;
        Console.WriteLine(name);
    }
}

int main()
{
   for(int i = 0; i < 5; i++)
   {
      Foo test = new Foo();
   }
}

Actual Output:
Foo5
Foo5
Foo5
Foo5
Foo5
Desired Output:
Foo0
Foo1
Foo2
Foo3
Foo4
Any help would be greatly appreciated
Thanks

A: Your code doesn't compile. Correcting it to:
class Foo
{
    static int count = 0;
    int fooNum;
    string name;

    public Foo()
    {
        ++count;
        fooNum = count;
        name = "Foo" + fooNum;
        Console.WriteLine(name);
    }
}

static void Main(string[] args)
{
    for (int i = 0; i < 5; i++)
    {
        Foo test = new Foo();
    }
}

makes it compile and work like a charm. It prints
Foo1
Foo2
Foo3
Foo4
Foo5

A: Mitch and Tudor have correct examples, but I would still point out why your code doesn't work:
Your code doesn't work because you are missing parentheses on your Foo constructor, which causes the code to not compile. If you are ignoring this compiler error you are probably running a previous build which produces the output you are seeing. Fix the constructor and you'll see that your code will work as expected.

A: This code works as expected:
namespace ConsoleApplication68
{
    class Program
    {
        static void Main(string[] args)
        {
           for (int i = 0; i < 5; i++)
           {
              Foo test = new Foo();
              Console.WriteLine(test.name);
           }
        }
    }

    class Foo
    {
        private static int count = 0;
        public string name;

        public Foo()
        {
            int fooNum = ++count;
            name = "Foo" + fooNum;
        }
    }
}

Please note that I've moved the Console.WriteLine() to a more correct place in your code.

A: Try collecting your Foos into a generic Collection, such as:
List<Foo> myFooList;

Then as you add in more Foos to your List, you can use the index number to identify it.