text:
Q: Preventing inappropriate imports and enforcing project hierarchy in Typescript In a TS project I'd like the following to be blocked:

*

*A file from folder common importing from folder projectA

*A file from folder projectB importing from folder projectA
I'd like the following to be allowed:

*

*A file from folder projectA importing from folder common.

I'm aware of References. However, as I understand, they require a build for type checking (If such a separation is made, one must build to create d.ts files first) which I'd rather avoid.
What options do I have? Is it possible to achieve simply via separate tsconfig files for each of those projects/folders?

A: TLDR; You really should just use References. It is exactly what they are for.
But let's address some of your specific thoughts first:

*

*Is it possible to achieve simply via separate tsconfig files for each of those projects/folders?
Yes, but it's not very flexible. You could isolate common by setting its rootDir to .. You would then get an '/path/to/projectA' is not under 'rootDir' error if you tried to import projectA into common.  But to be able to import common into projectA, its rootDir would have to be more global, but then that would allow you to import projectB.
Not only that, according to the Project References documentation:

Previously, this structure was rather awkward to work with if you used a single tsconfig file:

*

*It was possible for the implementation files to import the test files

*It wasn't possible to build test and src at the same time without having src appear in the output folder name, which you probably don't want

*Changing just the internals in the implementation files required typechecking the tests again, even though this wouldn't ever cause new errors

*Changing just the tests required typechecking the implementation again, even if nothing changed
You could use multiple tsconfig files to solve some of those problems, but new ones would appear:

*

*There's no built-in up-to-date checking, so you end up always running tsc twice

*Invoking tsc twice incurs more startup time overhead

*tsc -w can't run on multiple config files at once

*I'm aware of References. However, as I understand, they require a build for type checking (If such a separation is made, one must build to create d.ts files first) which I'd rather avoid.
What's the reason for this aversion?

*

*If it's the upfront cost of building a fresh project clone, that will be more than made up for by the improved build times (see arguments for below). The benefits of the latter for developer productivity will far outweigh the costs of the former.
Ironically, the larger you concern about the upfront cost, the larger the benefit from the improved build times!

*If it's that you want to be able to navigate a fresh clone in a type and linkage aware editor like VS Code or WebStorm without having to build, you can achieve this by checking the .d.ts files into source control.

Here's what the docs say specifically:

Because dependent projects make use of .d.ts files that are built from their dependencies, you'll either have to check in certain build outputs or build a project after cloning it before you can navigate the project in an editor without seeing spurious errors. We're working on a behind-the-scenes .d.ts generation process that should be able to mitigate this, but for now we recommend informing developers that they should build after cloning.

The argument for Project References
From the docs:

*

*you can greatly improve build times

A long-awaited feature is smart incremental builds for TypeScript projects. In 3.0 you can use the --buildflag with tsc. This is effectively a new entry point for tsc that behaves more like a build orchestrator than a simple compiler.
Running tsc --build (tsc -b for short) will do the following:

*

*Find all referenced projects

*Detect if they are up-to-date

*Build out-of-date projects in the correct order
Don't worry about ordering the files you pass on the commandline - tsc will re-order them if needed so that dependencies are always built first.

*enforce logical separation between components

*organize your code in new and better ways.
There's some more useful benefits / features in the Project References doc.
Example setup

*

*src/tsconfig.json
Even if you have no code at the root, this tsconfig can be where
all the common settings go (the others will inherit from it), and
it will enable a simple tsc --build src to build the whole
project (and with --force to build it from scratch).
{
  "compilerOptions": {
    "outDir": ".", // prevents this tsconfig from compiling any files

    // we want subprojects to inherit these options:
    "target": "ES2019",
    "module": "es2020",
    "strict": true,
    ...
  },

  // building this project will build all of the following:
  "references": [
    { "path": "./common" }
    { "path": "./projectA" }
    { "path": "./projectB" }
  ]
}

*

*src/common/tsconfig.json
Because common has no references, imports are limited to targets within its directory and npm_modules. You could even restrict the latter, I believe, by giving it its own package.json.
{
  "extends": "../tsconfig.json", //inherit from root tsconfig

  "compilerOptions": {
  "rootDir": ".",
  "outDir": "../../build/common",
  "composite": true
  }
}

*src/projectA/tsconfig.json
projectA can import common because of the declared reference.
{
  "extends": "../tsconfig.json", //inherit from root tsconfig

  "compilerOptions": {
  "rootDir": ".",
  "outDir": "../../build/projectA",
  "composite": true
  },
  "references": [
    { "path": "../common" }
  ]
}

*src/projectB/tsconfig.json
projectB can import common AND projectA because of the declared references.
{
  "extends": "../tsconfig.json", //inherit from root tsconfig

  "compilerOptions": {
  "rootDir": ".",
  "outDir": "../../build/projectB",
  "composite": true
  },
  "references": [
    { "path": "../common" }
    { "path": "../projectA" }
  ]
}

Builds
These are just some examples. I use the abbreviate forms of tsc switches below, e.g. -b instead of --build. All commands executed from the repo root.
tsc -b src - builds the entire tree.
tsc -p src/projectA/ compiles just projectA.
tsc -b src/projectA/ builds projectA and any dependencies that are out of date.
tsc -b -w src - build & watch the entire tree.
tsc -b --clean src - delete the output for the entire tree.
tsc -b -f src- force a rebuild of the entire tree.
Use the  -d or -dry  switch to get a preview of what tsc -b will do.

A: I suggest to use a linter for that job, no need to adjust the build step or use Project References.
eslint-plugin-import is a quite popular ESLint plugin, compatible to TS and can do what you want. After having configured typescript-eslint (if not already done), you can play around with these rules:

*

*import/no-restricted-paths - Restrict which files can be imported in a given folder

*import/no-relative-parent-imports - Prevent imports to folders in relative parent paths

*import/no-internal-modules - Prevent importing the submodules of other modules

Let's try with following project structure:
|   .eslintrc.js
|   package.json
|   tsconfig.json
\---src
    +---common
    |       common.ts
    |
    +---projectA
    |       a.ts
    |
    \---projectB
            b.ts

.eslintrc.js:
module.exports = {
  extends: ["plugin:import/typescript"],
  parser: "@typescript-eslint/parser",
  parserOptions: {
    sourceType: "module",
    project: "./tsconfig.json",
  },
  plugins: ["@typescript-eslint", "import"],
  rules: {
    "import/no-restricted-paths": [
      "error",
      {
        basePath: "./src",
        zones: [
          // disallow import from projectB in common
          { target: "./common", from: "./projectB" },
          // disallow import from projectB in projectA
          { target: "./projectA", from: "./projectB" },
        ],
      },
    ],
    "import/no-relative-parent-imports": "error",
  },
};

Each zone consists of the target path and a from path. The target is the path where the restricted imports should be applied. The from path defines the folder that is not allowed to be used in an import.

Looking into file ./src/common/common.ts:
import { a } from "../projectA/a"; // works
// Error: Unexpected path "../projectB/b" imported in restricted zone.
import { b } from "../projectB/b";

The import/no-relative-parent-imports rule also complains for both imports, like for a.ts:

Relative imports from parent directories are not allowed. Please either pass what you're importing through at runtime (dependency injection), move common.ts to same directory as ../projectA/a or consider making ../projectA/a a package.

The third rule import/no-internal-modules wasn't used, but I also list it here, as it can be very useful to restrict access to child folders/modules and emulate (at least) some kind of package internal modifier in TS.


text:
Q: MobileFirst SAP Adapter http HEAD requests We are working with MobileFirst 6.3, mobilefirst server running on RHEL linux. We connect to SAP and have used Discovery to generate adapter code and used those generated adapter calls except for custom authentication. If we do a create in toward SAP, that results in http POST request, but adapter always generates one http HEAD request before that actual request. I've had SAP backend people complain about these (not that I personally think they would cause much harm). I've also confirmed these when inspecting other things using wireshark. I can imagine that they would relate to some type of connectivity check by the adapters, but have not been able to find any evidence of this. Searching for similar questions is also challencing since HTTP and HEAD strings are so common in urls and html code.

*

*Can anyone verify my guess of the purpose of these HEAD requests ?

*Is there any documentation on these ?

*Are they in any way configurable (and in that case what would be the disadvantages for opting out) ?

Adapter definitions:
..
    <connectivity>
            <connectionPolicy xsi:type="nwgateway:NWGatewayHTTPConnectionPolicyType">
                    <protocol>HTTP</protocol>
                    <domain>our.complex.host</domain>
                    <port>10084</port>
                    <connectionTimeoutInMilliseconds>30000</connectionTimeoutInMilliseconds>
                    <socketTimeoutInMilliseconds>30000</socketTimeoutInMilliseconds>
                    <serviceRootUrl>/sap/opu/odata/sap/OUR_CUSTOM_REQS/</serviceRootUrl>
                    <!-- Following properties used by adapter's key manager for choosing specific certificate from key store
                    <sslCertificateAlias></sslCertificateAlias>
                    <sslCertificatePassword></sslCertificatePassword>-->
                    <maxConcurrentConnectionsPerNode>50</maxConcurrentConnectionsPerNode>
            </connectionPolicy>
    </connectivity>

..
    <procedure name="createOurCustomObjectHeader" securityTest="OurCustomSecurityTest" connectAs="endUser"/>
..

Adapter code:
function createOurCustomObjectHeader(content) {
    var request = {
            CollectionName: "OurCustomObjectHeaderSet",
            Content : content
    };
    return WL.Server.createNWBusinessObject(request);
}

Security test code:
    <customSecurityTest name="OurCustomSecurityTest">
        <test realm="wl_antiXSRFRealm" />
        <!--  test realm="wl_authenticityRealm"/ -->
        <test realm="wl_remoteDisableRealm" />
        <test realm="OurCustomRealm" isInternalUserID="true" />
        <test realm="wl_deviceNoProvisioningRealm" isInternalDeviceID ="true" />
    </customSecurityTest>

A: After looking at the code, it appears we use HEAD request to fetch a CSRF-Token from the Gateway and then we insert that token into the header of the actual create request. If you refer to SAP's documentation, all modifying operations require a CSRF token header for security purposes.
In 6.3 or even later versions of MobileFirst, I'm afraid there's no way around this configuration due to the provisions of the SAP Gateway infrastructure.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apple Pay - Interac Payment Method we are trying to add interac as an acceptable payment method for apple pay, but when ever we open the apple pay sheet : it says not accepted and is disabled for selection.
we verified before opening the sheet the accepted payment in array and it had the below reference
static let interac: PKPaymentNetwork
any idea what are we missing?
Checked the array of paymentTypes to ensure static let interac: PKPaymentNetwork is available


text:
Q: Install Tahoma font in Ubuntu When I tried to install the font Tahoma with these commands, I got two errors (permissions denied):
$ cabextract -F 'tahoma*ttf' IELPKTH.CAB
IELPKTH.CAB: WARNING; possible 5592 extra bytes at end of file.
Extracting cabinet: IELPKTH.CAB
  extracting tahoma.ttf
tahoma.ttf: Permission denied
  extracting tahomabd.ttf
tahomabd.ttf: Permission denied

$ wget http://download.microsoft.com/download/ie6sp1/finrel/6_sp1/W98NT42KMeXP/EN-US/IELPKTH.CAB
cabextract -F 'tahoma*ttf' IELPKTH.CAB
mkdir -p /usr/share/fonts/truetype/msttcorefonts/
mv -f tahoma*ttf /usr/share/fonts/truetype/msttcorefonts/
chmod 644 /usr/share/fonts/truetype/msttcorefonts/tahoma*
fc-cache -v
rm -f IELPKTH.CAB

A: You can give try with script:
#!/bin/bash
[ ! -f /usr/share/fonts/truetype/msttcorefonts/tahoma.ttf -o ! -f /usr/share/fonts/truetype/msttcorefonts/tahomabd.ttf ] &&
wget https://sourceforge.net/projects/corefonts/files/OldFiles/IELPKTH.CAB &&
cabextract -F 'tahoma*ttf' IELPKTH.CAB &&
mkdir -p /usr/share/fonts/truetype/msttcorefonts/ &&
mv -f tahoma*ttf /usr/share/fonts/truetype/msttcorefonts/ &&
chmod 644 /usr/share/fonts/truetype/msttcorefonts/tahoma* &&
fc-cache -v &&
rm -f IELPKTH.CAB &&
echo "Installed Tahoma"

A: what you can do is a simple method.

*

*download tahoma font.

*Then copy that downloaded font and all you have to do is paste it in this folder:

/usr/share/fonts/truetype

But since this folder is protected, you will have to open this folder as root. i.e right click and OPEN AS ROOT. provide your password and paste it there. THATS ALL...!!!

A: I had the same error. You have to do a "sudo" and issue the command one by one :
$ wget http://download.microsoft.com/download/ie6sp1/finrel/
$ cabextract -F 'tahoma*ttf' IELPKTH.CAB
$ sudo mv -f tahoma*ttf /usr/share/fonts/truetype/msttcorefonts/
$ chmod 644 /usr/share/fonts/truetype/msttcorefonts/tahoma*
$ fc-cache -v
$ rm -f IELPKTH.CAB

A: Download Tahoma.
Right click and "Open With Fonts".

When it opens click on Install.

Done.


text:
Q: Why shared library is linked by absolute path? I create an application by linking the libociei.so and libcustome.so
CC -o main main.cpp ../lib/libociei.so ../lib/libcustome.so
and copy libociei.so libcustome.so to /usr/lib
then I use ldd to check library, it shows:
   main .....
   libcustome.so  ===>   /usr/lib/libcustome.so
   ../lib/libociei.so

why libociei.so is not relocated to /usr/lib/libociei.so ?
ps : ld library path is /lib:/usr/lib and I do not add ../lib to ld library path

A: If you are on linux (say Ubuntu) then it is probably because you did not run:
sudo ldconfig

On other systems I am not so sure.

A: When you use readelf -d main does the NEEDED entries have the full path?
My guess is that ldd is seeking the libraries in the default path.


text:
Q: How to handle multiple user type in Django I'm trying to make a small website which has three types of users ["client" , "volunteer" , "coordinator"]. Each type of user has restrictions on what views it can access. All three users have different login pages.
Approach 1 : To achieve this, I've added a key to the session category, assign one of the above given userTypes during login and, whenever a view is called, check whether that user can access that view.
login.html:
{% extends "base.html" %}
{% block content %}

{% if form.errors %}

 Sorry , invalid

{% endif %}

    <form action="/login_volunteer/authenticate/" method="post">{% csrf_token %}
     Username :
    <input type="text" name="username" value="" id="username">
     Password :
    <input type="password" name="password" value="" id="password">
    <input type="hidden" name="category" value="volunteer" id="category">
    <input type="submit" value="login" />
    </form>

{% endblock %}

view.py:
def hello(request):
    name = "abhishek"
    if request.session.session_key is None:
        html = 'Session is expired'
        return HttpResponse(html)
    try:
        if not request.POST.get('category') == 'volunteer
            html = 'You are Not allowed here'
            return HttpResponse(html)
    except :
        print "error"
    html = 'Hi this is awesome'
    return HttpResponse(html)

Approach 2 : I thought I could create a custom User class rather than just using the default User provided by Django and assign the CustomUser to the request.user during login. Then when the view is called, I check is_Client or is_Volunteer.
customUser.py:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser

class VolunteerUser(AbstractBaseUser):
    """
    Custom user class.
    """
    email = models.EmailField('email address', unique=True, db_index=True)
    joined = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)
    is_volunteer = models.BooleanField(default=False)

class ClientUser(AbstractBaseUser):
    """
    Custom user class.
    """
    email = models.EmailField('email address', unique=True, db_index=True)
    joined = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)
    is_Client = models.BooleanField(default=False)

So my question is, which of these approaches is the best way to accomplish the task at hand? Is there any other method that solves this?
I'm also concerned about security and I feel that the first method is more insecure than the second.

A: The better approach for achieving your requirement is to use the inbuilt Group and Permissions model in Django. But since Permissions can be a little tricky, an alternative approach is to create a UserProfile model like below:
from django.contrib.auth.models import User
class UserProfile(models.Model):
    user = models.ForeignKey(User)
    type = models.CharField(max_length=15)

Then use the @user_passes_test decorator for controlling access to the views like this:
from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u: u.get_profile().type == 'client')
def view_for_client(request):
    ...

The UserProfile model will also be useful to save all of the preferences of your user. Also you would need to set the following setting:
AUTH_PROFILE_MODULE = 'accounts.UserProfile'


text:
Q: pulling ranom index array from a different class Trying to make a mad lib that will pull a random Verb from an array in my other class, tried creating an object of other class and calling the getRandomVerb() method inserting the array list, works normally for the main class and arrays in main but having trouble with other class.
Example 01
Example 02


text:
Q: JVM for different windows operating system As we know that the JVM implementation is OS specific (Windows / Linux / Solaris etc). I wanted to dig into deeper i.e., do we have different JVM implementations for different Windows OS versions?
Example:
Is JVM-Implementation-For-Win-XP same as JVM-Implementation-For-Win-8 ??

A:
Is JVM-Implementation-For-Win-XP same as JVM-Implementation-For-Win-8 ??

Yes and no. They mostly use the same codebase, but there are some differences here and there. For example windows XP did not have a proper dualmode ipv4/ipv6 sockets, so there was - if I recall correctly - some special handling to use two native sockets per java NIO socket under XP, which is not necessary on newer windows versions.
But those differences are relatively small, they can be detected at runtime and the appropriate code paths can be used.
Your view of "implementations" is too monolithic, there may be separate implementations for some components without having separate implementations of the JVM as a whole.
There are many parts of the JVM shared across platforms.
There even is a project to have an easy-to-port subset of the JVM that's basically portable C/C++ and zero assembly, hence the name: Project Zero
Also note that the Oracle/OpenJDK Hotspot JVM is not the only player in town.

A: Quoting from Oracle , The JVM is same for all version of Windows, only the difference is architecture
i.e 32-bit or 64-bit.But they stopped providing guarantees for Windows-XP as
Microsoft stopped providing updates to it from  April 8, 2014.

A: JVM is platform-independent. So that, the answer is yes. But as Arunesh's saying, the architecture is a little bit different.


text:
Q: How to read from Windows Named Pipe with timeout? I'm trying to port something that is very easy in Unix to Windows: reading from a named pipe (fifo) with timeout when nothing happened.
I'm trying to do it in a simple way (using PeekNamedPipe), without using overlapped IO. Is this possible?
Below is a complete example. It doesn't work for the moment: The written string is not received, and the reader gets

ERROR_NO_DATA    232 (0xE8)    The pipe is being closed

after the first read, and the writer gets this after some tries

ERROR_SEM_TIMEOUT    121 (0x79)    The semaphore timeout period has expired

The test writer (pipe client):
#include "Windows.h"
#include <iostream>
#include <stdio.h>
#include <errno.h>

int main()
{
    HANDLE hpipe;
    DWORD written;
    const char *pname = "\\\\.\\pipe\\isp-control";
    char msg[] = "play asdf.wav";

    printf("waiting for pipe %s\n", pname);
    bool stat = WaitNamedPipeA(pname, 4000);
    printf("  --> %d, error %d\n", stat, GetLastError());

    if (stat)
    {
        hpipe = CreateFileA(pname, GENERIC_WRITE | GENERIC_READ,
            0, NULL, OPEN_EXISTING, 0, NULL);

        if (hpipe != INVALID_HANDLE_VALUE)
        {
            bool stat = WriteFile(hpipe, msg, strlen(msg) + 1, &written, NULL);
            printf("  wrote %d bytes of %d: '%s'\n", written, strlen(msg) + 1, msg);
            printf("  --> %d, error %d\n", stat, GetLastError());

            CloseHandle(hpipe);
        }
        else
        {
            printf("error %d opening pipe (handle %d)\n", GetLastError(), (int) hpipe);
            return 1;
        }
    }
    return 0;
}

The test reader (pipe server and client):
#include <stdio.h>
#include <iostream>
#include <string>
#include "pipeio.hpp"

int main (int argc, char *argv[])
{
  std::string pipename = "\\\\.\\pipe\\isp-control";    // command input filename
  ISP::WindowsPipeIO io(pipename, 2);

  while (true)
  {
    // wait for pipe input in command string or timeout
    std::string cmdstr = io.wait();
    printf("got response: '%s'\n", cmdstr.c_str());
  }
}

and the pipeio.hpp class, in the first #ifdef I left the Unix version to show what I'm trying to achieve:
#ifndef _PIPEIO_HPP_
#define _PIPEIO_HPP_

namespace ISP {

/// interface for wrapper around named pipe
class PipeIO
{
public:
  //virtual ~PipeIO ();
  virtual std::string wait () = 0;
};

#ifndef WIN32  /////////// Unix version
#include <errno.h>

/// MacOS/Linux wrapper around named pipe
class UnixPipeIO : public PipeIO
{
public:
  UnixPipeIO (std::string name, double timeout)
  : name_(name)
  {
    // open control and status pipes
    filedes_ = open(name_.c_str(), O_RDWR | O_NONBLOCK);
    if (filedes_ < 0)
      throw std::runtime_error("can't open pipe");

    timeout_.tv_sec  = timeout; // todo: use fractional
    timeout_.tv_usec = 0;
  }

  std::string wait ()
  {
    FD_ZERO(&input_);
    FD_SET(filedes_, &input_);

    // wait for commands
    //db printf("waiting for fd %d...\n", filedes_);
    int ready = select(filedes_ + 1, &input_, NULL, NULL, &timeout_);

    if (ready > 0  &&  FD_ISSET(filedes_, &input_))
    { // ctl input has data, read and parse
      //db printf("fd %d is ready.\n", filedes_);
      int nread = read(filedes_, command_, CTL_INPUT_SIZE);
      command_[nread] = 0;  // null-terminate
      //db printf("read command (nread %d): '%s'\n", nread, nread > 0 ? command_ : "");

      //todo: continue reading when more than CTL_INPUT_SIZE chars are available
      //todo: stop at \0? continue when called again
      return std::string(command_);
    }
    else if (ready == 0)
    {
      //db printf("timeout\n");
      return "timeout";
    }
    else
    {
      fprintf(stderr, "error %d in select: %s\n", errno, strerror(errno));
      return "ioerror";
    }
  }

private:
  std::string name_;    //< name of pipe
  int filedes_;
  struct timeval timeout_;
  fd_set input_;
  static const long CTL_INPUT_SIZE = 65535;
  char command_[CTL_INPUT_SIZE];
};

#else   /////////////////////// Windows

#define NOMINMAX
#include "Windows.h"
#include <errno.h>

/// Windows wrapper around named pipe
class WindowsPipeIO : public PipeIO
{
public:
  WindowsPipeIO (std::string name, double timeout)
  : name_(name), timeout_((int) (timeout * 1000.))
  {
    printf("windowspipeio %s timeout %d ms\n", name_.c_str(), timeout_);

    // open control and status pipes
    hpipe_ = CreateNamedPipeA(name_.c_str(),
                 PIPE_ACCESS_DUPLEX,
                 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_NOWAIT,
                 4, // num. instances
                 1024 * 16, // output buffer size
                 CTL_INPUT_SIZE,  // input size
                 timeout_, // default timeout ms
                 NULL);
    if (hpipe_ == INVALID_HANDLE_VALUE)
      throw std::runtime_error("can't create pipe " + name);

    // open read handle
    hread_ = CreateFileA(name_.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);

    if (hread_ == INVALID_HANDLE_VALUE)
      throw std::runtime_error("can't open read handle " + name);

    printf("  windowspipeio created pipe %d, read %d\n", (int) hpipe_, (int) hread_);
  }

  ~WindowsPipeIO()
  {
    CloseHandle(hread_);

    printf("~windowspipeio disconnect %s\n", name_.c_str());
    DisconnectNamedPipe(hpipe_);
    printf("~windowspipeio close %s\n", name_.c_str());
    CloseHandle(hpipe_);
  }

  std::string wait ()
  {
    DWORD dwRead;

    // wait for commands
    if (hpipe_ != INVALID_HANDLE_VALUE  &&  hread_ != INVALID_HANDLE_VALUE)
    {
      //db
      printf("waiting for connection for pipe %s handle %d\n", name_.c_str(), (int) hpipe_);
      bool stat   = ConnectNamedPipe(hpipe_, NULL);
      int  winerr = GetLastError();
      printf("  --> status %d error %d\n", stat, winerr);

      if (winerr == ERROR_PIPE_CONNECTED)
      { // connection is good

    // instead of going through implementing "overlapped i/o", we simply peek into the pipe to see if data is available
    DWORD nready = 0;
    if (PeekNamedPipe(hpipe_, NULL, 0, NULL, &nready, NULL) == 0)
      fprintf(stderr, "error %d peeking into pipe: %s\n", GetLastError(), strerror(errno));

    printf("pipe connected and peeked at %d bytes\n", nready);

    if (nready > 0)
    { // data available
      printf("  pipe %s has available %d bytes\n", name_.c_str(), nready);

      while (ReadFile(hread_, command_, CTL_INPUT_SIZE - 1, &dwRead, NULL) != FALSE)
      {
        /* add terminating zero */
        command_[dwRead] = '\0';
        //db
        printf("  read command (%d bytes): '%s'\n", dwRead, dwRead > 0 ? command_ : "");

        //todo: continue reading when more than CTL_INPUT_SIZE chars are available
        //todo: stop at \0? continue when called again
        return std::string(command_);
      }

      printf("  hmmm, read %d, but there should have been %d bytes (error %d)\n", dwRead, nready, GetLastError());
    }
    // else: no data available: timeout

    DisconnectNamedPipe(hpipe_);
    printf("disconnected from pipe (error %d)\n", GetLastError());
      }
      // else: no client connected: timeout

      //db
      printf("timeout\n");
      Sleep(timeout_);
      return "timeout";
    }
    else
    {
      fprintf(stderr, "error %d (invalid pipe handle): %s\n", errno, strerror(errno));
      return "ioerror";
    }
  }

private:
  std::string name_;    //< name of pipe
  int timeout_; //ms
  HANDLE hpipe_;
  HANDLE hread_;
  static const long CTL_INPUT_SIZE = 65535;
  char command_[CTL_INPUT_SIZE];
};

#endif

} // end namespace ISP

#endif // _PIPEIO_HPP_


text:
Q: Does the value of std::chrono::system_clock.now().time_since_epoch().count() increase monotonically? I'm aware of steady_clock and that it is the only clock that is specified to be monotonic. And I understand that system_clock can jump forward or backward due to daylight savings and leap years. But doesn't count() give you the number of ticks of the system clock since the Unix epoch, which is an always increasing number, regardless of how that integer number of ticks is parsed into a "calendar date + wall clock" interpretation? i.e. Even if the "calendar date + wall clock" jumps from 2am from 3am on a given day in March, hasn't the integer count of ticks only increased by one tick?
In short, doesn't it stand to reason that the value of std::chrono::system_clock.now().time_since_epoch().count() should be expected to, in the short term, increase monotonically (barring updates to the system clock, which of course are a very real event), even if the date+time it refers to jumps around?
EDIT
As pointed out by @SergeyA, if the system clock is changed, then of course the value will jump around. But I think the change in wall clock time due to daylight savings is not an NTP update event or a manual change by a user. If it helps clarify the question, I'm interested in uptimes of an hour or two, which could cross the DST boundary, as opposed to uptimes of weeks or months, in which the clock could drift.

A: Short answer - no, it does not. System clock can be (and will be in practice!) adjusted outside, as a result of manual action or source (NTP, PTP) synchronization.

A: system_clock tracks Unix Time.  Unix Time has no UTC offset adjustments (daylight saving).  It is just a linear count of non-leap seconds.  It is possible that an implementation could jump backwards during a leap second insertion.  Though in practice the leap second is "smeared" with many tiny adjustments over a span of hours.
In theory it is possible for a system_clock to be monotonic.  In practice, no clock keeps perfect time, and must be adjusted, (potentially backwards) to stay in sync with Unix Time.
In C++11/14/17, the Unix Time measure is not specified for system_clock, but it is the existing practice.  In C++20, it will be specified.


text:
Q: AWS Serverless Environment setup with API Gateway, Lambda and Aurora Its a kind of GYM fitness IoT/Serverless project.
Work Flow
Each Member is wearing a fitness band on hands and it sends the data to the fitness mobile app every 30min via Bluetooth. Every day(7 am to 8 am) or when the user connects the mobile app to the internet, it will execute a Json call on the mobile app backend and send data to AWS API gateway, with the help of Lambda we will write the data to AWS Aurora. After that, each member can able to see the daily workout details in their fitness app.

Need to setup an AWS serverless environment to handle n number of
requests to the API Gateway. I've some doubts about setup the
serverless environment

Questions:

*

*How to handle a large number of queries comes to API Gateway (more
than 10000/sec)

*Did the lambda can handle the request? How to handle the data write to DB?

*What kind of AWS Aurora is Suitable to handle the request.

Looking at your valuable suggestion to implement with highly scalable infrastructure.

A:
How to handle a large number of queries comes to API Gateway (more than 10000/sec)

API GW has limit of 10k requests/s with burstable capacity. This is a lot, so are you sure do you really need so much?
You may use SQS or  Kinesis for handling much higher throughput. (each option would have its pros and cons)

Did the lambda can handle the request? How to handle the data write to DB?

The default concurrency limit for lambda is 1000 (increasable on request) , however using SQS or Kinesis could help to "smooth" the peaks and allow using more reasonable infrastructure.

What kind of AWS Aurora is Suitable to handle the request.

As soon as you're using queueing of write events, you could select your instance types based on total throughput rather than be afraid of the peaks.


text:
Q: How to control Rstudio switching between windows? Although I find Rstudio excellent, I have some problems with automatic switching back to the source pane. A typical example would be that I am creating a script, lets say it contains (from ?lm):
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group <- gl(2, 10, 20, labels = c("Ctl","Trt"))
weight <- c(ctl, trt)
lm.D9 <- lm(weight ~ group)

Then I want to check something inside the lm function with debug from console:
debug(lm)
lm.D9 <- lm(weight ~ group)
...
Browse[2]> Q

After I finish browsing with Q, the focus automatically changes back to the source, even if I have already been working in the console for a while. This can be quite annoying as selected text in the source pane will be deleted when I touch any key. And this might go unnoticed if I am concentrated on what I wanted to do in the console and I switch back without checking what happened with the source.
After some googling, I thought this might be changed with
Options/Code Editing/Focus console after executing from source

However, the focus did still switch back to the source after ending the browser!
Any ideas how to turn off this behavior? I think (could be wrong) that this was different in the earlier version I had of Rstudio. My current is 0.98.978.


text:
Q: How do I get Zen Cart to server XML, JSON (without html headers) I am attempting to write a module that uses ajax requests to another page within zen cart.  I would like to mark the page that is to serve the data as "Simple": that is, there will be no headers, footers, or additional characters added to the served page (save the XML, JSON).
Is there a setting within Zen Cart that would allow me to mark this page as "Simple"?

A: You'll want to create a separate .php script which returns just the data you want (without the extraneous information).  Don't use the Zen Cart page infrastructure (i.e. don't put the module under includes/modules/pages, etc.) - just create a file for the purpose you need.


text:
Q: probability P(A and B) I have difficult to understand the following rule. Can anyone use a simple example to explain the rule to me? Thanks.

If A and B are any two events, then $P(A \cap B) = P(B)\cdot P(A| B)=P(A)\cdot P(B|A)$, where P(B|A) is the probability of B happening under the condition of event A.

A: The Kolmogorov definition of conditional probability is
$$ P(B|A) = \frac{P(B \cap A)}{P(A)}
$$
so rearranging gives $P(B|A) P(A) = P(B \cap A)$.

A: Conditional probabilities are especially useful when it comes to things that involve having to pick things without replacement.
Consider a game of blackjack and you want to calculate the probability that you're dealt two aces. (We can assume for simplicity that we are only dealing with a single deck of 52 cards and that the first two cards in the deck are dealt to us). If we let $A$ be the event that the first card is an ace and let $B$ be the event that the second card is an ace, then it is clear that we want to find $P(A \text{ and } B)$.
Using the definition of conditional probability, we find,
$$P(A \text{ and } B) = P(A)P(B|A) = P(\text{first card is an ace})P(\text{second card is an ace given the first card is an ace)} $$$$= \frac{4}{52}\cdot \frac{3}{51} = \frac{1}{221}.$$
We have that $P(A)$ is $\frac{4}{52}$ since there are 4 aces in a 52 card deck and $P(B|A) = \frac{3}{51}$ because after the first ace is drawn, there are 3 aces amongst the 51 cards remaining.

A: If $\mathbb{P}[A]=0$ then clearly we would like $\mathbb{P}[A \cap B]=0$ and this is the case.
Now if $\mathbb{P}[A]\neq0$ then this is equivalent to
$$
\mathbb{P}[B|A] = \frac{\mathbb{P}[A \cap B]}{\mathbb{P}[A]}
$$
The right-hand side is a definition of $\mathbb{P}[B|A]$, that is, the probability of $B$ knowing $A$. It makes sense because it basically restricts the sample space to $A$.
Simple example: We throw a dice twice.
There are $36$ possible equiprobable outcomes, say $(a,b)$ with $1\leq a,b\leq 6$.

What is the probability of obtaining at least one $6$ knowing that the sum of the two throws is $8$ ?

Answer: There are $5$ outcomes for which the sum of the two throws is $8$. They are
$$
(2,6),(3,5),(4,4),(5,3),(6,2)
$$
Of those $5$ outcomes, there are $2$ for which there is a $6$ : $(2,6)$ and $(6,2)$. Hence, reasonably, the probability should be $2/5$.

This example motivates the above definition.

Indeed, if you call $B$ the event "obtaining at least one $6$" and $A$ the event "the sum of the two throws is $8$" then we see that
$$
A \cap B = \{(2,6),(6,2)\}
$$
and our answer $2/5$ can be written in the form
$$
\frac{2}{5} = \frac{2/36}{5/36} = \frac{\mathbb{P}[A\cap B]}{\mathbb{P}[A]}
$$

A: Firstly, suppose that A and B are independent events, then the probability that they both occur is just the product of their individual probabilities:
$P(A \cap B) = P(A)P(B)$.
Inthis situation, $P(A|B) = P(A)$ and $P(B|A) = P(B)$.  This means that the probability of A occurring is the same whether or not B occurs, or vice versa.
Conditional probability lets us conceptualize dependent events. When there is some relationship between A and B, like A causes B or vice versa, or they have some common cause, then $P(A) \neq P(A|B)$ and $P(B) \neq P(B|A)$.
Example:
Suppose we have a jar of 100 marbles. 70 are red and 30 are green. Moreover, 65 have white stripes, and 35 are plain.
Thus: $P(R) = 70/100$, $P(G) = 30/100$, $P(S) = 65/100$ and $P(N) = 35/100$.
Now suppose there is a bias: suppose that most green marbles, 29 in fact, have a white stripe.
If we take all 30 green marbles out of the jar and put them into their own jar, the "green jar", and draw marbles from just the green jar, the probability is 29/30 that we get a striped one. This is obvious: we have 30 marbles, and 29 have stripes.  This 29/30 probability is $P(S|G)$: probability of a stripe, when green is taken for granted.
Since 29 of the 65 striped marbles are green, it means that 36 are red. If we put all 70 red marbles into a jar, and choose from just that red jar, the probability of getting a striped marble is 36/70. This is $P(S|R)$.
Now we know that 29 green marbles have a stripe. So the probability of a striped green marble being chosen from the original red-green jar is precisely 29/100.  That is $P(G \cap S)$.
If we plug in the numbers:
$$P(G \cap S) = P(S|G)P(G)$$
we see that it works out:
$$29/100 = 29/30 \times 30/100$$
The 30 and 30 cancel, leaving $29/10$.
It works with S and G reversed also. $P(G|S)$ is the probability of a marble being green, if it has a stripe. If we make a "striped jar" with just the striped marbles, it contains 65 marbles. 29 of them are a green. So $P(G|S)$ is $29/65$:
$$P(G \cap S) = P(G|S)P(S)$$
$$29/100 = 29/65 \times 65/100$$
Now the 65's cancel, leaving $29/100$.


text:
Q: Dependency issues using com.google.android.gms:play-services-ads:20.5.0 and com.google.firebase:firebase-analytics:18.0.0 While updating my app to the latest library versions, I have encountered the following issue:
Duplicate class com.google.android.gms.internal.measurement.zzfu found in modules jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3) and jetified-play-services-measurement-impl-18.0.0-runtime (com.google.android.gms:play-services-measurement-impl:18.0.0)
Duplicate class com.google.android.gms.internal.measurement.zzfv found in modules jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3) and jetified-play-services-measurement-impl-18.0.0-runtime (com.google.android.gms:play-services-measurement-impl:18.0.0)
Duplicate class com.google.android.gms.internal.measurement.zzfw found in modules jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3) and jetified-play-services-measurement-impl-18.0.0-runtime (com.google.android.gms:play-services-measurement-impl:18.0.0)
Duplicate class com.google.android.gms.internal.measurement.zzfx found in modules jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3) and jetified-play-services-measurement-impl-18.0.0-runtime (com.google.android.gms:play-services-measurement-impl:18.0.0)
Duplicate class com.google.android.gms.internal.measurement.zzfy found in modules jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3) and jetified-play-services-measurement-impl-18.0.0-runtime (com.google.android.gms:play-services-measurement-impl:18.0.0)
Duplicate class com.google.android.gms.internal.measurement.zzfz found in modules jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3) and jetified-play-services-measurement-impl-18.0.0-runtime (com.google.android.gms:play-services-measurement-impl:18.0.0)
Duplicate class com.google.android.gms.internal.measurement.zzq found in modules jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3) and jetified-play-services-measurement-impl-18.0.0-runtime (com.google.android.gms:play-services-measurement-impl:18.0.0)
Duplicate class com.google.android.gms.internal.measurement.zzs found in modules jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3) and jetified-play-services-measurement-impl-18.0.0-runtime (com.google.android.gms:play-services-measurement-impl:18.0.0)
Duplicate class com.google.android.gms.measurement.internal.zzfh found in modules jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3) and jetified-play-services-measurement-impl-18.0.0-runtime (com.google.android.gms:play-services-measurement-impl:18.0.0)
Duplicate class com.google.android.gms.measurement.internal.zzgl found in modules jetified-play-services-measurement-18.0.0-runtime (com.google.android.gms:play-services-measurement:18.0.0) and jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3)
Duplicate class com.google.android.gms.measurement.internal.zzgm found in modules jetified-play-services-measurement-18.0.0-runtime (com.google.android.gms:play-services-measurement:18.0.0) and jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3)
Duplicate class com.google.android.gms.measurement.internal.zzgn found in modules jetified-play-services-measurement-18.0.0-runtime (com.google.android.gms:play-services-measurement:18.0.0) and jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3)
Duplicate class com.google.android.gms.measurement.internal.zzgo found in modules jetified-play-services-measurement-18.0.0-runtime (com.google.android.gms:play-services-measurement:18.0.0) and jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3)
Duplicate class com.google.android.gms.measurement.internal.zzgp found in modules jetified-play-services-measurement-18.0.0-runtime (com.google.android.gms:play-services-measurement:18.0.0) and jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3)
Duplicate class com.google.android.gms.measurement.internal.zzgq found in modules jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3) and jetified-play-services-measurement-impl-18.0.0-runtime (com.google.android.gms:play-services-measurement-impl:18.0.0)
Duplicate class com.google.android.gms.measurement.internal.zzhs found in modules jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3) and jetified-play-services-measurement-impl-18.0.0-runtime (com.google.android.gms:play-services-measurement-impl:18.0.0)
Duplicate class com.google.android.gms.measurement.internal.zzhx found in modules jetified-play-services-measurement-base-18.0.3-runtime (com.google.android.gms:play-services-measurement-base:18.0.3) and jetified-play-services-measurement-impl-18.0.0-runtime (com.google.android.gms:play-services-measurement-impl:18.0.0)

Go to the documentation to learn how to Fix dependency resolution errors.

After checking the dependencies, I was able to fix the build errors using the following in my build.gradle file:
 resolutionStrategy {
        force("com.google.android.gms:play-services-measurement-base:18.0.0")
        force("com.google.android.gms:play-services-measurement-sdk-api:18.0.0")
    }

Although the app builds fine and ads are showing, I am worried that overriding the the default dependency versions for google play ads library will cause some issue with impression tracking, etc.
Is there any official solution here? I need analytics and ads. Is there something I'm missing here?
Thanks!


text:
Q: Snowflake cumulative sum for multiple entry in same date for a given partition I have a table with below data set. I want to get the cumulative sum based on PK1 and PK2 as on TXN_DATE. I have tried with cumulative window frame functions and its giving the expected result. But I want the output to be in desired format which needs to be grouped by TXN_DATE.

SELECT
    PK1
    ,PK2
    ,TXN_DATE
    ,QTY
    ,SUM(QTY) OVER (PARTITION BY PK1,PK2 ORDER BY TXN_DATE ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) SUM_QTY
FROM MY_TABLE
ORDER BY TXN_DATE;

Above query is giving the result as below,

I want the result as shown below in either one of the format, Can someone help to get the desired result based on this.

OR

A: Just get rid of rows between unbounded preceding and current row in your window function. The sum() window function will make the daily total the same for all rows on the same day that way.
with SOURCE_DATA as
(
select   COLUMN1::string as PK1
        ,COLUMN2::string as PK2
        ,COLUMN3::date   as TXN_DATE
        ,COLUMN4::int    as QTY
from (values
('P001', 'XYZ', '2022-11-03', 15),
('P001', 'XYZ', '2022-11-08', -1),
('P001', 'XYZ', '2022-11-12', -4),
('P002', 'ABZ', '2022-11-03', 10),
('P002', 'ABZ', '2022-11-03', 1),       -- This was listed as ABC in the photo
('P002', 'ABZ', '2022-11-05', -5),
('P002', 'ABZ', '2022-11-10', -1),
('P002', 'ABZ', '2022-11-10', -1),
('P002', 'ABZ', '2022-11-10', 1)
     )
)
select   *
        ,sum(QTY) over (partition by PK1, PK2 order by TXN_DATE) QUANTITY
from SOURCE_DATA
order by PK1, TXN_DATE
;

Output:

PK1
PK2
TXN_DATE
QTY
QUANTITY

P001
XYZ
2022-11-03
15
15

P001
XYZ
2022-11-08
-1
14

P001
XYZ
2022-11-12
-4
10

P002
ABZ
2022-11-03
10
11

P002
ABZ
2022-11-03
1
11

P002
ABZ
2022-11-05
-5
6

P002
ABZ
2022-11-10
-1
5

P002
ABZ
2022-11-10
-1
5

P002
ABZ
2022-11-10
1
5


text:
Q: Cucumber Selenium webdriver tests not execute with Jenkins I have try to execute the tests which are integrate with cucumber and selenium via jenkins. Console shows that build is successful but I cannot see execution of tests(opening the browser and continue the user actions).
This automation project use cucumber and selenium webdriver. When I execute feature files though Intellij IDEA, its successfully executes. But not working with jenkins.
I have set the relevant settings(pom file path, Maven path, jdk path, cucumber report plugin enabled).


text:
Q: How to install open-vm-toolbox on Kali Linux? I try to install open-vm-toolbox on my virtual machine.
I tried apt-get updateand apt-get install open-vm-toolboxafterwards, but i get: 'Package open-vm-toolbox not found'
How can i solve this?

A: New Kali versions
Type the following command:
   apt-get update
   apt-get install open-vm-tools-desktop fuse
   reboot

If this install is failed , you need to istall linux-headers.
apt-get install -y linux-headers-$(uname -r)

Old Kali versions:
install vmware-tool patche
cd ~
apt-get install git gcc make linux-headers-$(uname -r)
git clone https://github.com/rasa/vmware-tools-patches.git
cd vmware-tools-patches

Mount the VMware tools ISO by clicking "Install VMware Tools"
copy the installer to the downloads directory and then run the installer script :
Example:
   cd ~/vmware-tools-patches
   cp /media/cdrom/VMwareTools-9.9.0-2304977.tar.gz downloads/
 ./untar-and-patch-and-compile.sh

Change VMwareTools-9.9.0-2304977.tar.gz with your current version


text:
Q: Require extended permissions in FBML pyfacebook app I'm trying to get my FBML canvas page to automatically prompt new app users for permission to publish_stream.  Following Facebook's documentation I tried using the required_permissions argument to require_login.  That is, I tried to use the pyfacebook require_login decorator like this:
@facebook.require_login(required_permissions='publish_stream')

as in:
@decorator_from_middleware(FacebookMiddleware)
@facebook.require_login(required_permissions='publish_stream')
def canvas(request, template):
   ...

Requesting extended permissions in a pyfacebook-based Facebook iFrame app has been discussed.  Requesting extended permissions in an FBML app too.  My objective is to require extended permissions in an FBML app.  Am I missing something or can anyone suggest a workaround?
Thanks.

A: Right, pyfacebook does not yet support required_permissions for login, but you can call (or rather, redirect to) authorize manually. I've just written the following decorator for my purposes:
def require_permissions(*names):
    """Require extended permissions.
    XXX: in theory, the facebook.require_login() decorator should support
    this, but doesn't in pyfacebook yet."""
    def decorator(fn):
        required_perms = set(names)
        def wrapper(request, *args, **kwargs):
            fb = request.facebook
            perms = set() if fb.ext_perms is None \
                    else set(fb.ext_perms.split(','))
            if not required_perms.issubset(perms):
                missing = required_perms.difference(perms)
                url = fb.get_ext_perm_url(','.join(missing),
                            next='%s%s' % (fb.get_app_url(), request.path[1:]))
                print url
                return fb.redirect(url)
            return fn(request, *args, **kwargs)
        return wrapper
    return decorator

You may have to tweak the value of next as it is passed to get_ext_perm_url, but this should otherwise be fine (works for me). Usage example:
@facebook.require_login()
@facebook.require_add()
@require_permissions('email', 'offline_access')
def index(request):
   # ...


text:
Q: How to use code to affect the quantity of something? 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;

namespace ChocolateProgramByGhassan
{
public partial class Form1 : Form
{
    String quantityString;
    double quantity;
    double price = 3.00;
    double tax = 0.75;

    public Form1()
    {
        InitializeComponent();
    }

    private void buttonTotal_Click(object sender, EventArgs e)
    {
        price = 3.00 * quantity;
        MessageBox.Show(price.ToString());
    }

    private void domainUpDown1_SelectedItemChanged(object sender, EventArgs e)
    {
        quantityString = this.domainUpDown1.SelectedItem.ToString();
        quantity = Double.Parse(quantityString);
    }

    private void buttonTax_Click(object sender, EventArgs e)
    {
        tax = 0.75 * quantity;
        MessageBox.Show(tax.ToString());
    }
   }
}
}

I wasn't being specific enough in my previous question. I just want to to know how to get quantity to affect a set number in code. I have 2 set numbers 3 and 0.75, and a button for each. For the first button I get System.Windows.Forms.TextBox, Text: and for the second I get the desired message but the quantity does not affect the original number. What I am trying to do is enter a number and have it affect the original number stated in the code.

A: Not sure if this will solve the issue, but in the domainUpDown1_SelectedItemChanged event handler try setting the quantity variable with the value currently set in the DomainUpDown property. (I am assuming here that it is the quantity variable you wish to change)

A: In your SelectItemChanged event try this code:
quantityString = domainUpDown1.SelectedItem.ToString();
quantity = Double.Parse(quantityString);

Istead of DomainUpDown = quantity, use String quantityString and double quantity.
Now you should have a quantity variable that changes anytime you change the index of your DomainUpDown. I don't know how you get the other variables, but if your problem lays here you may use this approach.


text:
Q: Selecting text between two strings by matching using regex I know there are similar posts to get the text between two strings but I couldn't figure out what's wrong with my code even after multiple tries, so I decided to post a question. The text data I am trying to use regex upon looks as follows:
* * *

level a20. heading1 random

paragraph 1
paragraph 2

paragraph 3

* * *

paragraph 4

paragraph 5

* * *

level b22. random-heading2

someparagraphs...

I aim to get all the text between level a20. heading1 random to * * * level b22. randomheading2. I was able to find the start of the text using
regex = r"^\* \* \*[ \t\n\r\f]+level \S+ heading random"

but when I try to add the rest of the regex, the code fails to grab the text
regex_full = r"^\* \* \*[ \t\n\r\f]+level \S+ heading random(.*?)\* \* \*[ \t\n\r\f]+level \S+ [a-z]+"
re.finditer(regex_full, above_text_data, re.MULTILINE | re.DOTALL)

because I am sure of 'heading random' but in different documents the other heading ('random-heading2') changes, it could even be one word or two works. Can someone please highlight what's the error with the regex_full expression to obtain all the text between level a20. heading1 random to * * * level b22. randomheading2 ? On regex101.com it shows the error as "Your regular expression does not match the subject string."
* * *

level a20. heading1 random

TEXT OF INTEREST
* * *

level b22. random-heading2

A: Could be this
r"\* \* \*\s*level a20\. heading1 random\s*(.*?)\s*\* \* \*\s*level b22\. random-heading2"
capture group 1 contains trimmed content.

A: If you want to select text(including newlines) between two Strings:
(?<=level a20. heading1 random)[\s\S]*?(?=level b22. random-heading2)

May work


text:
Q: Toggle treating warnings as errors when deploying a shiny app on Heroku via Docker How do I tell either R or Docker or Heroku to not treat warnings as errors when deploying a shiny/golem app?
I think last week I already found the answer - something along the lines of ENV WARNINGS_ARE_ERRORS=false in my Dockerfile - but I seem to be unable to "re-find" it as my Google game is failing me completely today ;-)
Some key resources:

*

*https://cran.r-project.org/web/packages/golem/vignettes/c_deploy.html

*https://github.com/virtualstaticvoid/heroku-buildpack-r
This is what my Dockerfile structurally looks like
FROM rocker/r-ver:4.0.4
ENV WARNINGS_ARE_ERRORS=false
RUN apt-get update && apt-get install -y  git-core libcurl4-openssl-dev libgit2-dev libicu-dev libpq-dev libssl-dev libxml2-dev make pandoc pandoc-citeproc && rm -rf /var/lib/apt/lists/*
RUN echo "options(repos = c(CRAN = 'https://cran.rstudio.com/'), download.file.method = 'libcurl')" >> /usr/local/lib/R/etc/Rprofile.site
RUN R -e 'install.packages("remotes")'
RUN R -e 'remotes::install_github("r-lib/remotes", ref = "97bbf81")'
RUN Rscript -e 'remotes::install_version("shiny",upgrade="never", version = "1.5.0")'
RUN Rscript -e 'remotes::install_version("golem",upgrade="never", version = "0.2.1")'

[...]

RUN Rscript -e 'remotes::install_github("rappster/confx")'
RUN mkdir /build_zone
ADD . /build_zone
WORKDIR /build_zone
RUN R -e 'remotes::install_local(upgrade="never")'
CMD R -e "options('shiny.port'=$PORT,shiny.host='0.0.0.0');mypkg::run_app()"

And this is the warning that is bumped up to an error that I'm getting:
[...]

Step 25/30 : RUN Rscript -e 'remotes::install_github("rappster/confx")'
 ---> Running in f50d3dd800cb
Downloading GitHub repo rappster/confx@master
valid (NA -> 3f09feea8...) [GitHub]
Downloading GitHub repo rappster/valid@master
Running `R CMD build`...
* checking for file '/tmp/RtmpKWNYfH/remotes77dbc946c/rappster-valid-3f09fee/DESCRIPTION' ... OK
* preparing 'valid':
* checking DESCRIPTION meta-information ... OK
* checking for LF line-endings in source and make files and shell scripts
* checking for empty or unneeded directories
* building 'valid_0.0.0.9001.tar.gz'
Installing package into '/usr/local/lib/R/site-library'
(as 'lib' is unspecified)
* installing *source* package 'valid' ...
** using staged installation
** R
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded from temporary location
** testing if installed package can be loaded from final location
** testing if installed package keeps a record of temporary installation path
* DONE (valid)
Running `R CMD build`...
* checking for file '/tmp/RtmpKWNYfH/remotes76bee127a/rappster-confx-e53517f/DESCRIPTION' ... OK
* preparing 'confx':
* checking DESCRIPTION meta-information ... OK
* installing the package to process help pages
* checking for LF line-endings in source and make files and shell scripts
* checking for empty or unneeded directories
* building 'confx_0.0.0.9024.tar.gz'
Installing package into '/usr/local/lib/R/site-library'
(as 'lib' is unspecified)
* installing *source* package 'confx' ...
** using staged installation
** R
** inst
** byte-compile and prepare package for lazy loading
Warning: replacing previous import 'magrittr::set_names' by 'purrr::set_names' when loading 'confx'
** help
Error : (converted from warning) /tmp/RtmpqApPd2/R.INSTALL11445cdd308/confx/man/grapes-not-in-grapes.Rd: \name should not contain !, | or @
ERROR: installing Rd objects failed for package 'confx'
* removing '/usr/local/lib/R/site-library/confx'
Error in i.p(...) :
  (converted from warning) installation of package '/tmp/RtmpKWNYfH/file75a06ee6c/confx_0.0.0.9024.tar.gz' had non-zero exit status
Calls: <Anonymous> ... with_rprofile_user -> with_envvar -> force -> force -> i.p
Execution halted
The command '/bin/sh -c Rscript -e 'remotes::install_github("rappster/confx")'' returned a non-zero code: 1
 ▸    Error: docker build exited with Error: 1

A: After stepping through my search history one page at a time I was able to piece it together again.
Turns out the issue is caused by {remotes} and can be remedied by adding
ENV R_REMOTES_NO_ERRORS_FROM_WARNINGS=true

to your Dockerfile (see related GitHub issue)
Adding the env var
R_REMOTES_NO_ERRORS_FROM_WARNINGS=TRUE

to your .Renviron file might also work, but didn't test yet.


text:
Q: $4$ points in order $A,B,C,D$ lie on a circle with the extension of $AB$ meeting the extension of $DC$ at $E$ and that of $AD$ and $BC$ at $F$.
$4$ points in order $A,B,C,D$ lie on a circle with the extension of $AB$ meeting the extension of $DC$ at $E$ and that of $AD$ and $BC$ at $F$. Let $EP$ and $FQ$ be tangents to this circle with points of tangency $P$ and $Q$ respectively. Suppose $EP = 60$,$FQ = 63$. Find $EF$.

What I Tried: Here's a picture :-

Used Power of a Point to get :-
$$EA * EB = ED * EC = 3600$$
$$FA * FD = FB * FC = 3969$$
Yet this does not help to proceed and neither finds the value of $EF$ .
I thought of Pythagoras Theorem once. Join OP and OQ and let them be $x$ each . Then we can find $OE$ and $OF$ in terms of $x$ . Not sure if that helps in the problem though.
Can anyone help me? Thank You.

A: As I showed in this post, given a circle $\Gamma$ and two points $X,Y$ such that $Y$ lies on the polar of $X$ w.r.t. $\Gamma$, we have

$$XY^2=\text{Pow}_{\Gamma}(X)+\text{Pow}_{\Gamma}(Y)$$

Back to your case, it is well-known that $E$ lies on the polar of $F$ w.r.t. the circumcircle of $ABCD$ (recall, for example, how to prove Brokard's Theorem) and, hence, $$EF^2=60^2+63^2=7569\iff EF=87$$

A: Hatton's Projective Geometry, pg 156 gives two versions of a theorem:

[T]he square of the distance between a pair of conjugate points with
respect to a circle is equal to the sum of the powers of the points.

and

If a quadrangle be inscribed in a circle, the square of the distance
between two of its diagonal points external to the circle equals the
sum of the square of the tangents from these points.

The second version uses your setup.
Here's a screen capture of the theorems and their proofs.

The proofs should be easy to follow, except for perhaps the last sentence.  A more explicit version would be
$$
\begin{align}
EF^2 &= (EK+KF)^2 \\
     &= EK^2+2EK\cdot FK+FK^2 \\
     &= EK(EK+KF)+(EK+FK)FK \\
     &= EK\cdot EF + EF\cdot FK \\
     &= EC\cdot ED + FB\cdot FC \text{ (using powers of $E,F$ wrt circles $CDF,BCE$)}\\
     &= \text{sum of powers of $E$ and  $F$ wrt original circle $ABCD$}
\end{align}
$$


text:
Q: How to prevent scrolling to top after removing query parameters? I have set up a new application. When a route changes (normally) I want to scroll to the top of the page.
I have setup my app-routing like this:
@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      initialNavigation: "enabled",
      scrollPositionRestoration: "top",
      anchorScrolling: "enabled",
      scrollOffset: [0, 280], // [x, y] - adjust scroll offset
    }),
  ],
  exports: [RouterModule],
})
export class AppRoutingModule {}

But now I have a button that clears route parameters. I want the page to stay where it is, but it keeps scrolling to the top.
I searched how to remove query parameters without activating the route change and found this:
Angular: How to update queryParams without changing route
So I did this:
public reset(e: MouseEvent): void {
  e.preventDefault();
  this.brandFilterService.reset();

  this.router.navigate([], {
    relativeTo: this.activatedRoute,
    queryParams: { query: null, id: null },
    queryParamsHandling: "merge",
  });
}

The problem is, it still scrolls to the top of the page.
Is there anyway I can do this without it trying to scroll?


text:
Q: Simplify some code in Java and Android Studio I am trying to create something like that: After clicking a button, the program should show four random numbers ( between 1 and 9), but with some particularities. Together and after a set of conditions (operations), the final result is 22. I had already written the code, but I think it is too big for the usage, and there are some little things I wanted to change. For example, instead of clicking the button several times until the right set of numbers appear, I would like it to automatically show those four "magic" numbers in the first click. I have no idea how to do it:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }    public void button_action (View v){ int TF = 22;

    Random a = new Random();
    int i1 = a.nextInt(10 - 1) + 1;
    TextView tv = (TextView) findViewById(R.id.textView1);

    Random b = new Random();
    int i2 = b.nextInt(10-1)+1;
    TextView tv2 = (TextView) findViewById(R.id.textView2);

    Random c = new Random();
    int i3 = c.nextInt(10-1)+1;
    TextView tv3 = (TextView) findViewById(R.id.textView3);

    Random d = new Random();
    int i4 = d.nextInt(10-1)+1;
    TextView tv4 = (TextView) findViewById(R.id.textView4);

    int soma = i1 + i2 + i3 + i4;
    int mult0 = i1 * i2 * i3 * i4;
    int mult1 = (i1*i2*i3)+i4;
    int mult2 = (i1*i2)+i3+i4;
    int mult3 = i1 * (i2 + i3 + i4);
    int mult4 = i2 * (i1+i3+i4);
    int mult5 = i3 * (i1+i2+i4);
    int mult6 = i4 * (i1+i2+i3);
    int mult7 = (i1*i3)+i2+i4;
    int mult8 = (i1*i4)+i2+i3;
    int mult9 = (i2*i3)+i1+i4;
    int mult10 = (i2*i4)+i1+i3;
    int mult11 = (i4*i3)+i1+i2;
    int mult12 = (i1*i3*i4)+i2;
    int mult13 = (i1*i2*i4)+i3;
    int mult14 = (i4*i2*i3)+i1;

    if (soma == TF){
        tv.setText(String.valueOf(i1));
        tv2.setText(String.valueOf(i2));
        tv3.setText(String.valueOf(i3));
        tv4.setText(String.valueOf(i4));}

    if (mult0 == TF){
        tv.setText(String.valueOf(i1));
        tv2.setText(String.valueOf(i2));
        tv3.setText(String.valueOf(i3));
        tv4.setText(String.valueOf(i4));}

    if (mult1 == TF){
        tv.setText(String.valueOf(i1));
        tv2.setText(String.valueOf(i2));
        tv3.setText(String.valueOf(i3));
        tv4.setText(String.valueOf(i4));}

    if (mult2 == TF){
        tv.setText(String.valueOf(i1));
        tv2.setText(String.valueOf(i2));
        tv3.setText(String.valueOf(i3));
        tv4.setText(String.valueOf(i4));}

    if (mult3 == TF){
        tv.setText(String.valueOf(i1));
        tv2.setText(String.valueOf(i2));
        tv3.setText(String.valueOf(i3));
        tv4.setText(String.valueOf(i4));}

    if (mult4 == TF){
        tv.setText(String.valueOf(i1));
        tv2.setText(String.valueOf(i2));
        tv3.setText(String.valueOf(i3));
        tv4.setText(String.valueOf(i4));}   ... }
 }

Any suggestions?


text:
Q: Flutter: StreamBuilder gets other firestore documents when updating a single document I have a Stream like this:
@override
  void initState() {
    super.initState();
    rentsStream = FirebaseProfile().getRents(widget.portfolio.id);
  }

Widget _rentsStream() {
    return StreamBuilder<QuerySnapshot>(
      stream: rentsStream,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) return Text('Error: ${snapshot.error}');
        if (!snapshot.hasData) return const Loader();
        if (snapshot.data == null) return const Loader();

        rents = snapshot.data!.docs;
        return _portfolioBuilder(context);
      },
    );
  }

The stream is declared outside in order to not rebuild the stream every time I change the state.
Here I get a list of rents. When I modify one of them, this one gets updated but the problem is that it comes with the rest of rents incrementing the documents reads monthly quota (and also I don't need to get again the non updated ones).
Also it triggers with some state changes inside the page I return from the StreamBuilder. Video: https://youtu.be/RPid3Jn_UYQ
Each rent card has this:
onTap: () {
          Provider.of<MyRents>(context, listen: false)
              .updateCurrentRentIndex(widget.index);
          Navigator.of(context).pushNamed(
            '/rent',
            arguments: {
              'newRent': widget.rent,
              'portfolioId': widget.portfolioId
            },
          ).then((value) => calculateProfitsExpenses());
      }

Is possible to just get the one I updated? Otherwise I'd need to save them locally and update the rents based on what I changed.

A: What platform are you running this on? On native mobile, the Firestore caches documents by default and (while your code will get called with all documents) only the modified ones are actually read from the server. Let me repeat that: while your snapshot listener gets called with all documents in the query, many of those may be coming from the local cache and those won't cause charged reads on the server.
This local persistence caching is also available on Web, but there you have to explicitly enable it.


text:
Q: Javascript/Jquery values pushing more than once I am working on building a Simon Game, similar to the one you can find here: https://codepen.io/Em-Ant/full/QbRyqq/. Relevant code snippet below and the whole of my code written so far can be found here: https://github.com/JamesRiall/Simon-Game/blob/master/js/index.js
Essentially the program is adding "red", "green", "blue" or "yellow" to the array clicksInRound whenever the relevant panel on the game is clicked. I can then use this clicksInRound array to check against the sequence the player should be following to either do nothing (if the selection is right but they haven't completed the round yet), move them onto the next level (if selection is correct and they've completed that round's sequence) or reset the game (if wrong).
My problem is that when I play through the game, the clicksInRound array is having too many values pushed to it. Below is the result of console.log of clicksInRound when I play a game and click on yellow twice (with yellow the first color in the generated sequence):
["yellow"]
["yellow"]
["yellow", "yellow"]
The output I want here is just "yellow" for the first two lines (the first click my selection is yellow in round one, and then second click my selection is yellow only so far in round two). However, I'm getting the third line ["yellow", "yellow"] which is throwing out all of my checks. If I click yellow then blue in the second round, my clicksInRound array will be ["yellow", "yellow", "blue"] when I want my output to be ["yellow", "blue"]
Can anyone diagnose the problem from the code snippet below or from my full code on GitHub? (sorry for the somewhat incomplete code snippet, it's difficult to post the relevant snippets here without just copying in the whole program).
Thanks!
$(".game-button").click(function() {
  if (sequencePlaying === false && running === true) {
    if ($(this).is("#red")) {
      playRedInSequence();
      clicksInRound.push("red");
      whereInRound++;
      checkClickIsCorrect();
    } else if ($(this).is("#blue")) {
      playBlueInSequence();
      clicksInRound.push("blue");
      whereInRound++;
      checkClickIsCorrect();
    } else if ($(this).is("#yellow")) {
      playYellowInSequence();
      clicksInRound.push("yellow");
      whereInRound++;
      checkClickIsCorrect();
    } else if ($(this).is("#green")) {
      playGreenInSequence();
      clicksInRound.push("green");
      whereInRound++;
      checkClickIsCorrect();
    }
  }
});

A: Problem doesn't seem to be in your JavaScript code. In your HTML you haven't closed the div on line 28.

If you close the div and run the code , it seems to work as expected although I don't fully understand the game. Here I have created a jsFiddle out of your github code with the correction. It seems to be working.


text:
Q: Wireguard in a VM I have a setup where on my Ubuntu host, I have a connection to a remote Wireguard server, and where on this host I have VMs where I would like to connect to other remote Wireguard servers.
Also I have no difficulties in connecting to the Wireguard servers from the VMs it gives me no internet connection in the VM.
I'm surprised because this setup used to work with Openvpn (TCP) on the host but not anymore. Did I miss something in the Ubuntu 22.04 bindings with Gnome boxes ?
I'm using Wireguard through wg-quick.


text:
Q: How does The Good Dinosaur fit into the Pixar theory? Earth's history in The Good Dinosaur appears to be different than in the rest of the Pixar films. (The dinosaurs, for one.) If it is in the same universe, then what happened to the dinosaurs? How does The Good Dinosaur fit into the Pixar theory? While I would prefer a WoG answer from Jon Negroni, any explanation would suffice.

A: From Jon Negroni:
Pixar Theory author Jon Negroni posted The Pixar Theory, Part 3: 'The Good Dinosaur' on December 3, 2015.

The Good Dinosaur hammers the point that when left to their own
  devices, animals can become just as intelligent as humans, as we also
  see in A Bug's Life with Flik's inventions and ingenuity ensuring the
  survival of his entire community.
every dino is obsessed with survival [...] There's not much food around [...] If dinosaurs have been evolving for millions of years, then why are they having such a hard time, now? In the opening scene, there are many dinosaurs all eating together without a care in the world, so something big had to happen between those good times and the bleak world we're introduced to countless years later.
Well, I think it's pretty simple. These dinosaurs are living in a "post-apocalypse" of their own civilization. At one point, they probably had plentiful resources to sustain a massive population, much like you'd expect. But what we see is a shifted environment. The lush jungles filled with edible plants that we know existed millions of years ago have vanished by the time we meet Arlo, just as they would have if the asteroid had hit Earth.[...]
mammals (AKA humans) are stealing their food and thriving in this new environment[...]
These storms are a product of this change, as the world gradually corrects the imbalance of reptiles and mammals caused by the lack of an extinction-level event.
And many years later, the same "correction" will happen between man and another new species: machine.
  [...]
If The Good Dinosaur exists in the same timeline as movies like The Incredibles and Finding Nemo, then where's the evidence of those movies being a result of this alternate universe where dinosaurs ruled the Earth much longer than planned?
What about fossils? Certainly, the Pixar movies would exist in a world where the fossil record is drastically different. What about these strange creatures in The Good Dinosaur that don't look like any animals we're aware of, like the dreaded cluckers?
Well, that's where Up comes in.
It's no dinosaur. It's a bird (Kevin). And this is a bird that bears resemblance to the bizarre makeup of the "prehistoric" birds and raptor-hybrids we see in The Good Dinosaur, who have originated from this alternate universe where evolution was never halted.
  [...]
So Kevin's existence, as well as this rare, superhuman ability, finally has an explanation. Somehow, the longer evolution of these strange creatures brought about magic — or at least something that resembles magic — that can eventually be harnessed by humans in various ways. After all, what is it really that makes those dogs in Up talk? And is it any surprise that Muntz comes across Kevin's existence in the 1930s, not long before the sudden rise of supers with strange abilities?
  [...]
Remember: The Incredibles takes place in an alternate version of the 1950s and 60s. Mr. Incredible was very young or even born around the same time Charles Muntz was uncovering what could be "magic" properties. This could even serve as an explanation for why academia suddenly turned on Muntz, shaming him for what we know weren't fraudulent discoveries. Perhaps this was a ploy to keep his research hidden from the world, explaining why only Americans are shown to have powers in The Incredibles.
  [...]
OK, what about the strange animals mentioned earlier? Well, when we explore the dirigible in Up, Muntz shows off his collection of these strange creatures that are so rare, Muntz doesn't expect Carl to know what they are.
They range from giant turtles and other aquatic life to hybrid mammal/dinosaurs that are reminiscent of Forrest from The Good Dinosaur. And we can now deduce that in the Pixar Universe, many of these creatures existed closer together in time, explaining why they're displayed as a group.
  [...]
So the exotic creatures from The Good Dinosaur apparently exist across multiple Pixar movies, and the absence of an extinction-level event seemingly provides an explanation for why animals have become so intelligent by the time we get to movies like Ratatouille.  And the movie even provides some hints as to why magic exists in the Pixar Universe, and we now know why said universe is alternate to our own.
  [...]
In Cars 2, the sentient cars are running out of oil, entirely. And this makes sense for two major reasons:
Mankind has a 200 billion population by 2105 (according to WALL-E)
  There's less oil on Earth because (whoops!) dinosaurs died out more gradually.
  [...]
The absence of other energy options like fossil fuels might provide an explanation for why human energy is so important in the Pixar Universe.

From Pixar:
The Pixar Theory is a complicated fan theory that Pixar has said is baseless. See this article from BusinessInsider.

Last year, Pixar's Jay Ward laughed off the theory to Jalopnik saying,
  "I think somebody had a lot of time on their hands."
"The movies were sort of made in a different order by different
  directors in different times, in different places," he added. "It's
  cool that it all worked out that way, but it probably was not
  intentional."
Recently, Movies.com caught up with "Monsters University" director Dan
  Scanlon and producer Kori Rae to ask once and for all what Pixar
  thinks of the very complex universe.
"It's a funny idea, but we would've had to be insane geniuses to have
  plotted that out." Rae said, "It's nothing that we talk about at
  Pixar, I don't think. Or at least I don't. I'm sure people do,
  though."
So, while the theory is fun and in-depth, it's definitely no more than
  that, a theory.

Fan Speculation:
SuperCarlinBros speculate on this in their video "How The Good Dinosaur fits into The Pixar Theory":


text:
Q: Data mining libraries that easily integrate with Free Pascal? I have been experimenting with different approaches for pattern matching, analyzing, and predicting time-series data.
Since I have no professional experience in data mining or related fields I came up with my own methods from scratch.
After a few months of sporadically skimming data mining articles (the few that I understood) I realized that my methods are very basic.
For example, the way I implemented pattern matching is through a multidimensional k-Nearest Neighbor approach.
I am just now starting to understand that there are common techniques such as Decision Trees, Principal Component analysis, Covarience matricies, etc that I should be utilizing.
I have been experimenting with RapidMiner, which is a GUI data mining tool. RapidMiner lets you drag-and-drop various implementations of sophisticated techniques and connect them together without writing a line of code. It has been an awesome learning tool for me.
It looks like this:

RapidMiner has an API but unfortunately it is in Java, and all of my current code is in Free Pascal and MySQL.
I am looking for some way to integrate RapidMiner into my application, so I could experiment with different data processing methods through the RapidMiner GUI and use them seamlessly with my current code.
If that is not feasible, I would settle for another data mining package, as long as it is easy to integrate into my current Free Pascal code.
I looked into R - and that seems about right, but it does not seem to be easy to integrate with Free Pascal either.
For clarity, my data sets are fairly large (500,000+ rows) and computation must occur in real-time. The software runs on Windows 7.

A: I don't know the package, but a few general options:

*

*Try to get a plain C (native DLL) to this software from the authors.

*Use JNI to communicate with a Java program that calls the API. Delphi and FPC JNI libraries are available.


text:
Q: Recursive Complete Binary Tree in Python - The tree is skewed Here is a recursive implementation of a Complete Binary tree( Not a Binary Search Tree in Python from a list. Need help with the logic to build the balanced tree, the logic i have written generates a skewed tree. I am aware it can be done with Queues but I need a recursive implementation.
Here is the code:
class Node:
    """A simple Binary Node to be used in a Tree"""

    def __init__(self, value=-1, leftNode=None, rightNode=None):
        self.value = value
        self.leftNode = leftNode
        self.rightNode = rightNode

class BinaryTree:
def __init__(self, root=None):
    self.root = root
    self.noOfLeftNodes = 0
    self.noOfRightNodes = 0

def addNode(self, root, node):
    if self.root is None:
        self.root = node
        return
    if root.leftNode is None:
        root.leftNode = node
        self.noOfLeftNodes += 1
        return
    elif root.rightNode is None:
        root.rightNode = node
        self.noOfRightNodes += 1
        return

    else:
        if self.noOfLeftNodes - self.noOfRightNodes < 2:
            self.addNode(root.leftNode, node)
        else:
            self.addNode(root.rightNode, node)

def preorder(self, root):
    if root is None:
        return
    print(root.value)
    self.preorder(root.leftNode)
    self.preorder(root.rightNode)

#Test stub
    bt = BinaryTree()
    nodes = [1, 2, 3, 4, 5, 6, 7]
    for i in range(len(nodes)):
        bt.addNode(bt.root, Node(nodes[i]))
    print('---Binary Tee---')
    bt.preorder(bt.root)

A: Think about what happens, when your algorithm runs:

*

*1 becomes the root. (#left = 0, #right = 0).

*2 becomes the left child of the root (#left = 1, #right = 0).

*3 becomes the right child of the root (#left = 1, #right = 1).

*4 triggers the else and because #left - #right = 0 < 2, it is inserted ...

*... (Do that, until you get to a point where the algorithm does not what you expect.)

Hint: #left and #right not are doing what they should. If you insert something as a left child in the right subtree of the root, #left is incremented. Try to maintain these values for each node, not just once for the whole tree.


text:
Q: Angular JS ng-repeat - track by dynamic collection I'm trying to make ng-repeat over function call result, like

{{item}}

where f is
function f (arr) {
    return arr.map(function (v) {
      return [v]
    })
  }

Here is Plunker with this code
Problem is that in console we can see errors like 10 $digest() iterations reached. Aborting!
This is not because of recreating container array, because if we just modify line 3 like
return [v] -> return v

and remove
track by item[0]

everything works. This is because of recreating items, and track by should handle this. But for some reason it doesn't :(
I was also trying to solve the problem without track by buy putting constant $$hashKey on each item (even on collection itself). Here is Plunker with same error. Hope some one could explain why this is not working
So there is two separate questions: case with track by and case with $$hashKey
BTW Yes, I read
How to Loop through items returned by a function with ng-repeat? and
AngularJS InfDig error (infinite loop) with ng-repeat function that returns array of objects more than a few times, but can't find an answer there
Thanks

A: Is there any reason you can't compute the result and then display it? I.e. have ng-init="a = [0,1,2]; fa = f(a);" and then ng-repeat="item in fa" ?
Working plunkr example
If you need to have that computed result updated when a changes you could just have a $scope.$watch statement watching for changes to a and then updating fa.

A: Ok, here is hack we could use to solve the case without track by or $$hashKey
ng-repeat="item in t = angular.equals(t, f(a)) ? t : f(a)"

But this does answer the question why examples in question are does not work. So, please, if you know the answer - post it - I would be very grateful


text:
Q: Can't get url by QNetworkAccessManager (result differs what I see in my browser) I use QT 4.8.2 for my project.
My problem is what QTNetworkAccess can't get my url (or decode it) correctly.
If I paste my url to browser, I see what result in browser differs what I see in result (QNetworkreply).
This is example url I need to get:
* https://myhost/folder/folder/rss?cn1%5B0%5D=Web%2C+Mobile+%26+Software+Dev&cn2%5B0%5D=Web+Development
or, without urlencode:
** https://myhost/folder/folder/rss?cn1[]=Web%2C+Mobile+%26+Software+Dev&cn2[]=Web+Development
I try to pass QUrl as * and **.
This is my code to get:
networkAccess = new QNetworkAccessManager();
connect (networkAccess, SIGNAL (finished(QNetworkReply*)), this, SLOT (h_networkAccess(QNetworkReply*)));

request = new QNetworkRequest(QUrl(settings->get()->rss_link));
request->setRawHeader("User-Agent",      "Mozilla/5.0 (Windows NT 5.1; rv:37.0) Gecko/20100101 Firefox/37.0");
request->setRawHeader("Accept",          "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
request->setRawHeader("Accept-Encoding", "deflate");
request->setRawHeader("Connection",      "keep-alive");
if (settings->get()->cookie != "")
    request->setRawHeader("Cookie",      settings->get()->cookie.toAscii());

networkAccess->get(*request);

Maybe, my problem is "+" symbol in url ... But I don't know.
I can provide full link what I need to test.
Please, help.

A: If your url is already encoded, use QUrl::fromEncoded
From the doc:

Parses input and returns the corresponding QUrl. input is assumed to
  be in encoded form, containing only ASCII characters.


text:
Q: How to hold data in text field in html? I have created two html pages. One page having name and age text fields and second page having mother name and father name. Whenever i click on next button in first page that goes to second page then if i click on previous button in second page that comes to first page but data is not shown.so i want that data in that fields.

I want to see data inside field before what i entered...

A: You can use localStorage to store value and retrieve it.
HTML
<form name="frm1" method="post">

Enter Your Name:
   <input type="text" id="name" name="name">

                          ^^ id attribute added

Enter Your Age:
   <input type="text" id ="age" name="age">

                          ^^ id attribute added

     <input type="button" id ="nextButton" value="Next">
                          ^^ id attribute added

 </form>

JS
// Check if local storage has previously stored value
// If there are values then populate relevent field with value.
document.addEventListener("DOMContentLoaded", function(event) {
var getStoredName = localStorage.name;
var getStoredAge = localStorage.age;
console.log(getStoredName ,getStoredAge);
      if(getStoredName !==undefined || getStoredAge !== undefined){
      document.getElementById("name").value=getStoredName;
      document.getElementById("age").value=getStoredAge;
      }

})

// Set local storage on click of next button

var getNextButton = document.getElementById("nextButton");

getNextButton.addEventListener("click",function(){
    localStorage.name=document.getElementById("name").value;
    localStorage.age=document.getElementById("age").value;
    })

EXAMPLE

A: Think about your problem:

*

*Do you need to go to the second page? Can you just put all four of the inputs on the same form? Can you change "page" using Javascript instead of actually navigating to a different page? These would both be good workarounds to your problem.

*Does the data that the user entered need to be there when they go back a page? If the form is submitting it to the server, then it would just be confusing to the user that it's still there and they might submit it twice by mistake.

*Finally, if you really need the data to still be there,  you'll have to use persistent data storage such as cookies or localStorage. If you want to learn how to do that, then have a look at this answer which describes the process of using cookies / localStorage and discusses which is the best method.


text:
Q: Why use use "one" rather than 1? In Real Estate there seems to be a trend to use "one" in place 1.
One Madison(NYC), One57(NYC), One WTC(NYC), One Park Drive(NYC), One One One (Brisbane) and many more.
Is there any reason to do this? Where did this trend come from?

A: There are two obvious reasons for using the word rather than the numeral.

*

*The number is being treated as a proper name rather than merely a postal address.  Many high end restaurants like to use its number in this way.  Most particularly this is true of some upmarket commercial properties, such as One Hyde Park in London, England.  This is a combination of luxury apartments and retail in the heart of Mayfair.

*Prestige is the second motivation, and why such addresses are to be found in real estate offices.  The pencil thin One Madison, where all the moneybag residents have a whole floor to themselves, is a case in point:  address as status symbol.


text:
Q: Goldbach's Conjecture: Counterexample of "necessary condition" Definitions:
Divisor Function:
$$\sigma_x(n) = \sum_{d\mid n} d^x$$
Euler's Totient Function:
$$\phi(n) = \# \{m \in \mathbb{Z}^+ \mid (\gcd(m,n)=1) \wedge (1 \le m \le n)\}$$
Conjecture:
The following condition  is necessary: If $n \ge 4$ is any even integer, and $p$ is prime such that $\frac{n}{2} + 1 \le p \le n - 2$ and $(p+1) \sigma_1(n-p) - (p-1)\phi(n-p) = 2n$, then $n-p$ has to be prime.
Note:
If $p$ and $q$ are primes such that $p < q$, define $m = pq$. Then $$\frac{\sigma_1(m) - \phi(m)}{2} = p + q$$
Attempt:
I didn't prove any of this, but I created the following algorithm using Matlab, which may work with any even integer $n \ge 2$ entered by the user:
clc; clear; close all;

n = input("Select a positive integer: ");
n = 2*n;
[p, q] = SumOfPrimes(n);

fprintf("The sum of primes of %d is %d + %d\n", n, p, q)
fprintf("%d is prime: %s", q, num2str(isprime(q)))

function [p1,p2] = SumOfPrimes(n)

    if isprime(n/2)
            p1=n/2;
            p2=n/2;
    else

        for p = prevprime(n-2):-2:n/2 + 1
            x = sum(divisors(n-p));
            y = eulerPhi(n-p);
            if isprime(p) && (p+1)*x - (p-1)*y == 2*n
                break
            end
        end
        p1 = p;
        p2 = n - p;
    end

end

Some of you will trigger something in their heads: Yes, it's part of Goldbach's Conjecture. Unfortunately, my program only outputs two primes, $p$ and $q$, so the sum is $2n$, which uses the condition above in Conjecture.
I only want a counterexample of the "necessary" condition stated above, or if impossible, to prove that this is true.
Thanks.


text:
Q: How Do I Set The Garbage Collector For The AJC Ant Task? I am getting out of memory errors when doing compile time weaving. As you can see, I have already set the Xmx (via maxmem) to 1024m. This could be due to the jar I am trying to weave is ~70MB.
How do I set the Garbage Collector? I tried using the X param but when I connect to the process with JConsole the ConcMarkSweep is not set.
    <echo message="Weaving..."/>
    <aspectj:iajc classpathref="compile.libs" aspectpath="${src.dir}" outJar="${output.jar}" fork="true" maxmem="1024m" X="+UseConcMarkSweepGC">
        <inpath>
            <pathelement path="${classes.dir}"/>
        </inpath>
    </aspectj:iajc>

The error is:
Bugs for exceptions thrown have titles File:line from the top stack,
e.g., "SomeFile.java:243"

If you don't find the exception below in a bug, please add a new bug
at http://bugs.eclipse.org/bugs/enter_bug.cgi?product=AspectJ
To make the bug a priority, please include a test program
that can reproduce this exception.
GC overhead limit exceeded

when weaving classes
when weaving
when batch building BuildConfig[null] #Files=0 AopXmls=#0
GC overhead limit exceeded
java.lang.OutOfMemoryError: GC overhead limit exceeded
    at org.aspectj.apache.bcel.classfile.ConstantPool.copy(ConstantPool.java:69)
    at org.aspectj.apache.bcel.generic.ClassGen.<init>(ClassGen.java:161)
    at org.aspectj.weaver.bcel.LazyClassGen.<init>(LazyClassGen.java:255)
    at org.aspectj.weaver.bcel.BcelObjectType.getLazyClassGen(BcelObjectType.java:523)
    at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1742)
    at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1710)
    at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1472)
    at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1286)
    at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:435)
    at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterCompiling(AjPipeliningCompilerAdapter.java:304)
    at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:73)
    at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:430)
    at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:1003)
    at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:267)
    at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:181)
    at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112)
    at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60)
    at org.aspectj.tools.ajc.Main.run(Main.java:355)
    at org.aspectj.tools.ajc.Main.runMain(Main.java:234)
    at org.aspectj.tools.ajc.Main.main(Main.java:84)

23-Sep-2013 23:58:12 org.aspectj.weaver.tools.Jdk14Trace info
INFO: Dumping to D:\Projects\Delete\AspectjTest\.\ajcore.20130923.234357.932.txt

1 fail|abort

A: a workaround would be to use the <java> ant command, and list the main weaver class as the thing that runs. org.aspectj.tools.ajc.Main, you would also have to set all the args manually that this ant task does automatically.

A: I got it using it via ANTs exec task calling the aspectj1.7/bin/ajc.bat (1.7.3) with args.
Just editing ajc.bat and replacing -Xmx64g by -Xmx3g helped me trying to apply it e.g. on the guava-18.0.jar.
Similarly it was also mentioned here: https://bugs.eclipse.org/bugs/show_bug.cgi?id=36234#c3
if you wan't to use the aspectj:iajc task nevertheless you should run your ant.bat (or sh) with the appropriate JVM args as above.
Within Eclipse (it happens normally within the Eclipse VM and in case it is not appropriately configured and you don't wanna make the JVM arg changes in the eclipse.ini file) you would need to adjust the implicitely created External Tools Configuration for your ANT target and set JRE => Runtime JRE: [x] Separate JRE: ... and adjust its VM arguments: -Xmx3g e.g..