text:
Q: ng run project:deploy - Project target does not exist I have a working production build for Angular Web App.
I have an active subscription on my Azure Account (Free Tier) with an AppService Plan, App Service, Resource group, Storage Account, KeyVault, SQL Server & SignalR.

I want to deploy my web App using Azure. My Source control is Azure DevOps.
I have followed tutorials:
https://medium.com/@waelkdouh/deploying-your-angular-application-to-azure-using-azure-devops-f3ba35a0ae4d
https://learn.microsoft.com/en-us/azure/devops/pipelines/apps/cd/deploy-webdeploy-webapps?view=azure-devops
https://learn.microsoft.com/en-us/azure/app-service/deploy-continuous-deployment
https://angular.schule/blog/2019-08-ng-deploy
https://medium.com/@kevinding0218/deploy-angular-8-application-to-azure-app-service-paas-using-azure-devops-repo-cd-c3294cd52193
But basically always fail at the last step:
ng run :deploy
Depending on what I enter for  I get two types of error messages.
If I enter ng run projectName:deploy (this is what I believe to be the correct name), I get
An unhandled exception occurred: Project target does not exist.

If I enger ng run projectname:deploy (this is my projectname with wrong casing), I get
An unhandled exception occurred: Project "projectname" does not exist.

So It seems to trigger some different Error message inside
clientapp\node_modules\@angular\cli\node_modules\@angular-devkit\architect\node\node-modules-architect-host.js

I tried tweaking it as in Angular8 : ng run => 'Project target does not exist.' when using i18n but it didn't make me any wiser.
my angular.json
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "projectName": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "progress": true,
            "extractCss": true,
            "outputPath": "dist/projectName",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [ "src/assets", "src/manifest.webmanifest", "src/web.config" ],
            "styles": [

            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
          "optimization": true,
          "outputHashing": "all",
          "sourceMap": false,
          "extractCss": true,
          "namedChunks": false,
          "aot": true,
          "extractLicenses": true,
          "vendorChunk": false,
          "buildOptimizer": true,
          "serviceWorker": true,
          "ngswConfigPath": "ngsw-config.json"
        }
      }
    },
    "serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "options": {
        "browserTarget": "projectName:build"
      },
      "configurations": {
        "production": {
          "browserTarget": "projectName:build:production"
        }
      }
    },
    "extract-i18n": {
      "builder": "@angular-devkit/build-angular:extract-i18n",
      "options": {
        "browserTarget": "projectName:build"
      }
    },
    "test": {
      "builder": "@angular-devkit/build-angular:karma",
      "options": {
        "main": "src/test.ts",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "src/tsconfig.spec.json",
        "karmaConfig": "src/karma.conf.js",
        "styles": ["styles.css"],
        "scripts": [],
        "assets": [
          "src/assets",
          "src/web.config",
          "src/manifest.webmanifest"
        ]
      }
    },
    "lint": {
      "builder": "@angular-devkit/build-angular:tslint",
      "options": {
        "tsConfig": ["src/tsconfig.app.json", "src/tsconfig.spec.json"],
        "exclude": ["**/node_modules/**"]
      }
    },
    "e2e": {
      "builder": "@angular-devkit/build-angular:protractor",
      "options": {
        "protractorConfig": "e2e/protractor.conf.js",
        "devServerTarget": "projectName:serve"
      }
    },
    "server": {
      "builder": "@angular-devkit/build-angular:server",
      "options": {
        "outputPath": "dist/dogface/server",
        "main": "server.ts",
        "tsConfig": "tsconfig.server.json"
      },
      "configurations": {
        "production": {
          "outputHashing": "media",
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }
          ],
          "sourceMap": false,
          "optimization": true
        }
      }
    },
    "serve-ssr": {
      "builder": "@nguniversal/builders:ssr-dev-server",
      "options": {
        "browserTarget": "projectName:build",
        "serverTarget": "projectName:server"
      },
      "configurations": {
        "production": {
          "browserTarget": "projectName:build:production",
          "serverTarget": "projectName:server:production"
        }
      }
    },
    "prerender": {
      "builder": "@nguniversal/builders:prerender",
      "options": {
        "browserTarget": "projectName:build:production",
        "serverTarget": "projectName:server:production",
        "routes": [
          "/"
        ]
      },

      }
    }

  },
  "defaultProject": "projectName"
}

My web.config
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
    <staticContent>
        <mimeMap fileExtension=".json" mimeType="application/json" />
        <remove fileExtension=".woff"/>
        <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
        <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
    </staticContent>
    <rewrite>
        <rules>
            <rule name="Angular" stopProcessing="true">
                <match url=".*" />
                <conditions logicalGrouping="MatchAll">
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                </conditions>
                <action type="Rewrite" url="/" />
            </rule>
        </rules>
    </rewrite>
    </system.webServer>
</configuration>

My index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8"/>
    <title>DogFace</title>
    <base href="/"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <link rel="manifest" href="/manifest.webmanifest">
    <meta name="theme-color" content="#1976d2">
  </head>
  <body>
  <app-root>
  Loading...
  </app-root>
  <noscript>Please enable JavaScript to continue using this application.</noscript>
</body>
</html>

my tsconfig.json
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "module": "esnext",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "DOM.Iterable",
      "dom"
    ]
  }
}

I've been trying for days now, running in circles. I have updated to Angular 11, did ng add @azure/ng-deploy (which says after logging in: You don't have any active subscriptions, but when I az storage account list in CMD-Shell, I see my actual subscription and when I az login in CMD:  ), I removed & readded node_modules folder, changed es2015 to es5 in tsconfig.json, did npm install before build --prod, authorized my azure account from cmd-shell.
Everything suggested in this thread did not work either angular ng serve command throws error: An unhandled exception occurred: Project does not exist
I did find this bugreport related to , but it's almost a year old and does seem to be resolved.
https://github.com/Azure/ng-deploy-azure/pull/92
My questions:
What else is in play here, that would disrupt me from deploying?
What mistakes did I make in the files presented?
How come angular CLI doesn't find my active subscriptions? One and a half years ago I know it was possible with free subscriptions and documentations doesn't state otherwise?

Half the time when I log into Microsoft with my account it states 'We couldn't find an account with that username. Try another..' But I know for sure this is the good account because when I want to login with another account it says I can't because I'm logged in with the account he can't find (I'm not even joking)
I'd like to get it up and running before I scale up to a bigger/more costly AppServicePlan, just to avoid having all that mess while on paying service :)
Am I asking too much? ))
Thanks for helping

A: My solution to this problem was abandoning the deployment through Angular CLI, add a new subscription, moving everything to that new subscription and deploy though azure deployment center


text:
Q: Pandas: Create New Dataframe That Contains A Column For Total Rows I have the following dataframe: df_Discrep_73L_3 that has a total of 601 rows
I have a second dataframe: df_Discrep_73Y_3 that has a total of 391 rows
I want to create a Dataframe that has the following:
ID  Total Rows
73Y 601
73L 391

I know to use df_Discrep_73L_3.shape to find the number of rows but don't know how to put it in the above dataframe.

A: The .shape method returns a tuple in the form (rows,columns). You can save these by using shape[0] and shape[1] respectively.
rows_73L = df_Discrep_73L_3.shape[0]
rows_73Y = df_Discrep_73Y_3.shape[0]

pd.DataFrame({'ID': ["73Y", "73L"], 'Total Rows': [rows_73Y, rows_73L]})

redpajama_set_name: RedPajamaStackExchange


text:
Q: Understanding the definition of Lie derivative I'm reading Warner. "Foundations of Differentiable Manifolds and Lie Groups." In p. 69, it gives the definition of the Lie derivative as follows:

2.24 Definition (summerized)
  Fix a smooth vector field $X$ on a differentiable manifold $M$. Let $Y$ be another smooth vector field on $M$. The Lie derivative of $Y$ with respect to $X$ at $m$, which is denoted by $(L_XY)_m$, is
  $$(L_XY)_m = \lim_{t\to 0} \frac{dX_{-t}(Y_{X_t(m)}) - Y_m} {t}$$.

Here, $X_t(m) = \gamma_m(t)$, where $\gamma_m$ is an integral curve of $X$ such that $0$ is in the domain of $\gamma_m$ and $\gamma_m(0) = m$. Also, $Y_m = Y(m)$.
I see that the function $t\mapsto\frac{dX_{-t}(Y_{X_t(m)}) - Y_m} {t}$ is a function from the subset of $\mathbb R$ into $M_m$, the tangent space to $M$ at $m$. But to define a limit of such function, there should be a topology on $M_m$, right? But I haven't learned any inner product, norm, metric, or topology given on $M_m$. So what is the topology on $M_m$?


text:
Q: How to use schemas in Django? I whould like to use postgreSQL schemas with django, how can I do this?

A: I just developed a package for this problem: https://github.com/ryannjohnson/django-schemas.
After some configuration, you can simply call set_db() on your models:
model_cls = UserModel.set_db(db='db_alias', schema='schema_name')
user_on_schema = model_cls.objects.get(pk=1)

The package uses techniques described in https://stackoverflow.com/a/1628855/5307109 and https://stackoverflow.com/a/18391525/5307109, then wraps them for use with Django models.

A: Maybe this will help.
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'OPTIONS': {
            'options': '-c search_path=your_schema'
        },
        'NAME': 'your_name',
        'USER': 'your_user',
        'PASSWORD': 'your_password',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

I get the answer from the following link:
http://blog.amvtek.com/posts/2014/Jun/13/accessing-multiple-postgres-schemas-from-django/

A: I've been using:
db_table = '"schema"."tablename"'

in the past without realising that only work for read-only operation. When you try to add new record it would fail because the sequence would be something like "schema.tablename"_column_id_seq.
db_table = 'schema\".\"tablename'

does work so far. Thanks.

A: I've had some success just saying
db_table = 'schema\".\"tablename'

in the Meta class, but that's really ugly. And I've only used it in limited scenarios - it may well break if you try something complicated. And as said earlier, it's not really supported...

A: There is no explicit Django support for postgreSQL schemas.

When using Django (0.95), we had to add a search_path to the Django database connector for PostgreSQL, because Django didn't support specifying the schema that the tables managed by the ORM used.

Taken from:
http://nxsy.org/using-postgresql-schemas-with-sqlalchemy-and-elixir
The general response is to use SQLAlchemy to construct the SQL properly.
Oh, and here's another link with some suggestions about what you can do with the Django base, extending it to try to support your scheme:
http://news.ycombinator.com/item?id=662901

A: I know that this is a rather old question, but a different solution is to alter the SEARCH_PATH.
Example
Lets say you have three tables.

*

*schema1.table_name_a

*schema2.table_name_b

*table_name_c
You could run the command:
SET SEARCH_PATH to public,schema1,schema2;

And refer to the tables by their table names only in django.
See 5.7.3. The Schema Search Path

A: For SQL server database:
db_table = "[your_schema].[your_table]"

A: It's a bit more complicated than tricky escaping. Have a look at Ticket #6148 in Django for perhaps a solution or at least a patch. It makes some minor changes deep in the django.db core but it will hopefully be officially included in django.
After that it's just a matter of saying
db_schema = 'whatever_schema'

in the Meta class or for a global change set
DATABASE_SCHEMA = 'default_schema_name'

in settings.py
UPDATE: 2015-01-08
The corresponding issue in django has been open for 7 years and the patch there will not work any more.
The correct answer to this should be...
At the moment you can't use postgreSQL schemas in django out of the box.

A: As mentioned in the following ticket:
https://code.djangoproject.com/ticket/6148, we could set search_path for the django user.
One way to achieve this is to set search_path via psql client, like
ALTER USER my_user SET SEARCH_PATH TO path;

The other way is to modify the django app, so that if we rebuild the database, django won't spit all the tables in public schema.
To achieve this, you could override the DatabaseWrapper defined in django.db.backends.postgresql_psycopg2.base

*

*Create the following directory:
app/pg/
├── __init__.py
└── base.py

*Here's the content of base.py
from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper

class DatabaseWrapper(DatabaseWrapper):
    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper, self).__init__(*args, **kwargs)

    def _cursor(self):
        cursor = super(DatabaseWrapper, self)._cursor()
        cursor.execute('SET search_path = path')
        return cursor

*In settings.py, add the following database configuration:
DATABASES = {
    'default': {
        'ENGINE': 'app.pg',
        'NAME': 'db',
        'USER': 'user',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}

A: https://docs.djangoproject.com/en/dev/topics/db/multi-db/#using-routers
urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from my_app.my_views import ClientViewSet

router = DefaultRouter(trailing_slash=False)
router.register(r'', ClientViewSet, base_name='clients')

urlpatterns = [
    path('', include(router.urls)),
]


text:
Q: Does a capacitor respond faster than a battery? I grew up with the rule of thumb that you should always put a 47 uF tantalum capacitor wherever power enters a PCB. Perhaps that's a little dated now. I then recently built a battery powered circuit and followed this rule.
Is there any point including the capacitor?  Would you decouple a good alkaline battery?  My understanding is that the electrical power is derived from a redox reaction within it's metals or their oxides. Wikipedia says:-

Redox reactions can occur relatively slowly, as in the formation of rust, or much more rapidly, as in the case of burning fuel.

Rusting and burning (even exploding) fuel doesn't seem to operate at GHz speeds. A capacitor can. Chemicals have mass and volume. And they're gooey. So is a capacitor faster at responding to demand than a chemical battery?

A: I don't know if a capacitor is faster but if I had to guess, I would guess that the electrostatic mechanism in a capacitor is a lot faster than the chemical mechanism in a battery.
But even if batteries were just as fast as capacitors, you would still use capacitors. One thing the capacitor has is a lot less inductance than the battery. Furthermore, there are usually a lot more components that need a low inductance power source in a circuit there are batteries, and it is a lot easier to place a capacitor right next to each component (thus minimizing wiring/trace inductance) than it is to give each one its own battery.


text:
Q: Moving transactional operations away from the controller   def cancel

    begin
      to_bank = @transfer.main_to_bank
      to_bank.with_lock do
        to_bank.locked_balance -= @transfer.amount
        to_bank.available_balance += @transfer.amount
        to_bank.save!
        @transfer.cancel
        @transfer.save!
      end
    rescue ActiveRecord::ActiveRecordError => e
      redirect_to admin_transfer_url(@transfer), alert: "Error while cancelling."
      return
    end

    redirect_to admin_transfer_url(@transfer), notice: 'Transfer was successfully cancelled.'
  end

I would want to refactor the above code to the Transfer model or some other place, because this same code is used elsewhere. However, ActiveRecord does some transaction magic within the model, so I'm worried I might introduce some unexpected side effects by simply moving the code under the model.
Are my worries unfounded and how would the above code typically be refactored to be outside of the controller for reusability?
Update: This seems like the perfect spot for a service object, as described here http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/.

A: 1) As you mention in your update, this is a perfect fit for service objects.  Put them in a directory like app/services since anything in /app is autoloaded.  There are two popular ways of implementing them:
As a static class:
AccountService.transfer(from_account, to_account, amount)

As an object:
service = AccountService.new(from_account, to_account)
service.transfer(amount)

I prefer option one coming from a Java enterprise development background where you would use Java beans similarly.
I would also recommend returning result objects from all services as a rule.  This means you create a small class called "ServiceResult" which contains a boolean flag of whether or not the call was successful, a user friendly message and optionally a result object (which is the method return value if you didn't have service result objects).  In other words checking the result from the controller or any other place would be:
response = AccountService.transfer(from, to, amount)

if response.success?
  flash[:notice] = response.message
else
  flash[:alert] = response.message
end

You can always refactor this into a method:
flash_service_result response

After adding some helper methods to your services, a service method could look like this:
def self.transfer(from_account, to_account, amount)

   ActiveRecord::Base.transaction do
     ..do stuff..
     from_account.save!
     to_account.save!

     service_success("Transfer succesfull...")
   end

 rescue SomeException => error
   service_error("Failed to transfer...")

 rescue ActiveRecord::RecordInvalid => invalid_record_error
   service_validation_error(invalid_record_error)
 end

When using result objects, never raise an exception from the service that you expect to be handled (checked exceptions in other languages).
2) Using the active record transactional methods will behave the same regardless of where it's called from.  It will not add any side effects.  So yes you can call it from a controller or service.


text:
Q: Particular Windows user(s) connecting to samba share as 'nobody' instead of given username? We have an Ubuntu 9.04 server running samba with null passwords and home directory shares, and we have corresponding users that mount said shares on windows machines.  Essentially, each user has an account on the server (with the same username as on their windows machines) and a home directory in /home/USERNAME which is mounted on their local machine as \\SAMBABOX\USERNAME which they then have full access to.
For most users this works without a problem; they can read, write, create, and delete files on their shares without issue.  Following is one such initial connection as seen in the samba logs:
[2009/12/02 10:30:22,  1] smbd/service.c:make_connection_snum(1115)
  somewindowsbox (192.168.2.123) connect to service ekaufman initially as user ekaufman (uid=1002, gid=1002) (pid 22574)

For one user in particular, however, they are unable to - at the very least - create certain files (lock files for an SVN working copy).  This is, mind you, from any windows machine in our AD domain.  Looking at their samba logs, their initial connection is made as the user nobody, and I cannot for the life of me figure out why.
[2009/11/18 10:19:32,  1] smbd/service.c:make_connection_snum(1115)
  somewindowsbox (192.168.2.123) connect to service jdoe initially as user nobody (uid=65534, gid=65534) (pid 15570)

Their user account on the ubuntu server is more or less identical to the others, as indicated in /etc/passwd:
ekaufman:x:1002:1002:,,,:/home/ekaufman:/bin/bash
jdoe:x:1015:1015:,,,:/home/jdoe:/bin/bash

And /etc/group:
ekaufman:x:1002:
jdoe:x:1015:

And even /etc/shadow (with the password hashes removed before being posted here, of course):
ekaufman:!:14580:0:99999:7:::
jdoe:!:14572:0:99999:7:::

I've even deleted their account on the ubuntu box and recreated it, with no change.  According to the admin of the AD domain controller, their account there is more or less identical to everyone elses as well (deleting and recreating it there would be prohibitively complicated).
If I manually mount the share for my own account from a windows machine, forcing the username, it works without incident:
C:\> net use z: \\sambabox.local\ekaufman /user:ekaufman
The command was completed successfully

If I do the same for this particular user, it still connects as nobody, failing silently:
C:\> net use z: \\sambabox.local\jdoe  /user:jdoe
The command was completed successfully

This gives me the impression that, whatever the problem is, it's on the linux side of things.
This is the entire smb configuration in use:
[global]
   null passwords = yes
   guest ok = yes
   security = user
   workgroup = WORKGROUP
   server string = %h server (Samba, Ubuntu)
   dns proxy = no
   log file = /var/log/samba/log.%m
   max log size = 1000
   syslog = 0
   panic action = /usr/share/samba/panic-action %d
   encrypt passwords = true
   passdb backend = tdbsam
   obey pam restrictions = yes
   unix password sync = yes
   passwd program = /usr/bin/passwd %u
   passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
   pam password change = yes
   map to guest = bad user
   usershare allow guests = yes

[homes]
   comment = Home Directories
   browseable = no
   read only = no

[printers]
   comment = All Printers
   browseable = no
   path = /var/spool/samba
   printable = yes
   guest ok = no
   read only = yes
   create mask = 0700

[print$]
   comment = Printer Drivers
   path = /var/lib/samba/printers
   browseable = yes
   read only = yes
   guest ok = no

A: I found the error to be user name mapping in users.map, which I had previously used to correlate NIS usernames to A.D. accounts.  After switching all NIS to the A.D. ServicesForUNIX NIS, I'd forgotten to remove these old username mappings.

A: On my system, there is a group called "sambashare". See if jdoe is a member (along with everybody else).

A: As it turns out, the answer was deceptively simple.  In addition to the user needing an account on the linux machine, they also had to be added to the smbpasswd file.  Additionally, since the connections are being made with null passwords, we need to add them with a null password to said file:
# -a flag adds the new user (must already exist in /etc/passwd)
# -n flag indicates a null password (different from an empty password)
smbpasswd -an jdoe


text:
Q: Read and Write strings via ByteBuf using byte[] array I'm trying to send a string through netty with a ByteBuf.
First of all I convert the string to a byte array like that:
byteBuf.writeInt(this.serverName.length());
byteBuf.writeInt(this.ipAdress.length());

byteBuf.writeBytes(this.serverName.getBytes(StandardCharsets.UTF_8));
byteBuf.writeBytes(this.ipAdress.getBytes(StandardCharsets.UTF_8));

This works well, but I don't know how to read the bytes to convert them back to the string?
I tried something like that:
int snLen = byteBuf.readInt();
int ipLen = byteBuf.readInt();

byte[] bytes = new byte[byteBuf.readableBytes()];

System.out.println(byteBuf.readBytes(bytes).readByte());
this.ipAdress = "";

There must be something to get the bytes back. You can send bytes from a string but can't get the bytes back at the end? Seems like there is a method for that, but I don't have an idea how to do that.
I hope anyone from you can help me.
Thanks in advance! :)

A: In netty 4.1 you can use:
byteBuf.writeCharSequence(...)
byteBuf.readCharSequence(...)

A: Here is an untested answer:
I assume the data order is correct.
Use this, method "readBytes(ByteBuf dst, int length)" : readBytes
Transmit side change to:
byteBuf.writeInt(this.serverName.getBytes().length);
byteBuf.writeInt(this.ipAdress.getBytes().length);

Receiving side:
int snLen = byteBuf.readInt();
int ipLen = byteBuf.readInt();

byte[] bytesServerName = new byte[snLen];
byte[] bytesIp = new byte[ipLen];

byteBuf.readBytes(bytesServerName,snLen);
byteBuf.readBytes(bytesIp, ipLen);

String serverName  = new String(bytesServerName);
String ipAddress   = new String(bytesIp);

System.out.println(bytesServerName);
System.out.println(bytesIp);

A: How about using Netty's own StringEncoder and StringDecoder ? http://netty.io/4.1/api/io/netty/handler/codec/string/StringEncoder.html


text:
Q: Analogy between p-adic and complex numbers Let $p$ be prime. The sequence
$$P_k = 1 + p + p^2 + p^3 + \cdots + p^k$$
goes to $\infty$ for $k\rightarrow\infty$ in the Euclidean norm, but in the p-adic norm it goes to $\frac{1}{1-p}$. It does so by enigmatically going through the "point at infinity" coming from the positive numbers and returning to $\frac{1}{1-p}$ through the negative numbers, which may remind one somehow of the real projective line:

[Note, that the larger $p$ the closer $\frac{1}{1-p}$ to $0$ in the Euclidean norm, but for finite $p$ the number $0$ will not be reached again.]
For the $p$th root of  unity $\omega = e^{i2\pi/p}$ we have $1 + \omega + \omega^2 + \omega^3 + \cdots + \omega^{p-1} = 0$, so one might be inclined to say that the sequence
$$\Omega_k = 1 + \omega + \omega^2 + \omega^3 + \cdots + \omega^{k}$$
approaches a limit cycle for $k\rightarrow\infty$, going through $0$ again and again (the smaller $p$ the more often). So with tongue in cheek one might say, that $\Omega_k$ goes to $0$ for $k\rightarrow\infty$ in the Euclidean norm.

Which deeper connection between p-adic and complex numbers does this reveal (if any)?

[Note, that the closeness of $\frac{1}{1-p}$ to $0$ corresponds to the frequency with which $0$ is passed by $\Omega_k$ — with $\Omega_k$ depending on $p$ via  $\omega = e^{i2\pi/p}$.]
[Note further, that the p-adic numbers $\mathbb{Q}_p$ are an extension of $\mathbb{Q}$ (next to  $\mathbb{R}$) while the complex numbers $\mathbb{C}$ are an extension of $\mathbb{R}$ (and thus of $\mathbb{Q}$).]
[Note further, that $\{\Omega_k\} \cap \mathbb{Q}_p = \{\Omega_k\} \cap \mathbb{Q} = \{0,1\}$ for $p >2$. Or does this statement not make sense?]

Just now I've learned, that Alexander Bogomolny, creator and maintainer of the marvelous web site cut-the-knot, has passed away on the 7th of July. I am very sad about that, I did admire and learn a lot from him.

A:
It does so by enigmatically going through the "point at infinity" coming from the positive numbers and returning to $\frac{1}{1-p}$ through the negative numbers

This is nonsense.  In the $p$-adic numbers there is no "order" and there are no "positive numbers" and no "negative numbers".

A: I strongly agree with the point raised in the other answer.
The not-so-deep connection here is that we have two algebraic structures which 1) are rings which 2) contain an element $x$ such that $1-x$ is invertible, and powers of $x$ exhibit an easily understood structure. To elaborate,

*

*In any ring for any $x$, we have $(1-x)\cdot (1+x+x^2+...+x^{k}) = 1-x^{k+1}$.

*Which, if we can divide by $1-x$, means that your sums are of the general form
$$X_k = \dfrac{1-x^{k+1}}{1-x} $$
Now in one case ($x=p$), we have an extra structure on our ring w.r.t. which $p^n \to 0$, so of course $X_k$ goes to $$\dfrac{1-0}{1-x} = \dfrac{1}{1-x}.$$ In the other case $x=\omega$, periodically $x^n=1$, so with the same period, $X_k$ will be $$\dfrac{1-1}{1-x} = 0.$$
Similarly I can build more examples:

*

*In the ring $\mathbb F_{17} [Z, Y]$ (polynomials in two variables over the field with 17 elements), there exists a primitive $16$-th root of unity, call it $\zeta$. Using it as $x$, we get that $$Z_k = 1+\zeta +... + \zeta^k$$ "cycles through 0 periodically". If we now extend the base field to $\mathbb F_{17^2}, \mathbb F_{17^3}$, and take a $288$-th, ($17^3-1$)-th ... root of unity as $\zeta$, this changes the frequency of the cycle.

*On the field $\mathbb R ((t))$ (Laurent series over $\mathbb R$), there is a natural metric w.r.t. which $t^n \to 0$. So for $$T_k = 1 +t+...+t^k,$$ we have that $T_k$ goes to $\dfrac{1}{1-t}$. Would you say "this enigmatically goes through infinity and comes back from the left hand side"? If we now went to an algebraic closure of this and replaced $t$ by $t^{1/2}, t^{1/3}$, would you say "it comes closer to 0 again"?
Would you say that this shows a deeper connection between these two rings I just made up? Would you say that the powers of $17$ in the first and the roots of $t$ in the second might have a profound connection? (Sorry for teasing.)

Side note 1: Doesn't the "frequency = closeness" correspondence go exactly the wrong way? Namely, for (Euclideanly) big $p$, $1/(1-p)$ comes closer to $0$, whereas $\Omega_k$ hits $0$ less frequently.
Side note 2: To your final small remark: If you define your roots of unity as complex numbers, $\omega = e^{2\pi i /p}$, then of course they are not contained in $\Bbb Q_p$ for any $p \ge 3$. However, the field $\Bbb Q_p$ in general does contain non-trivial roots of unity, namely exactly the $(p-1)$-th ones. With those playing the role of your $\omega$ or my $\zeta$ above, you get the exact same kind of behaviour. My point is, that's because they are roots of unity, and that alone does not tell you something deep about those fields, or let's say: Nothing deeper than that these fields contain certain higher roots of unity.


text:
Q: disabling send button I just a got a requirement to disable the send button in the form until the users enter his data.Can any one guide me?
thanks

A: Have the button initially disabled by having such HTML
<input type="submit" id="btnSubmit" disabled="disabled" value="Send" />

Then in the blur event of your form elements check if user entered all required data and when this happens, enable the button using such code:
document.getElementById("btnSubmit").disabled = false;

A: Normally, I would code it for you, but I'm in a hurry, and you do have to learn how to search for yourself, so here's a hint:
addEventListener(), and you can check the length of the data within an input by calling document.body.getElementById('yourInput').length, and then you can change the button.disabled property to either true (make the default value false in the source code). All you need to do for yourself is find out how to use addEventListener

A: form action="javascript:aNameForAnAjaxSendPostFunction"
function aNameForAnAjaxSendPostFunction()
{
   if ((document.getElementById('your field').value.strlen>0))
  {
      << SEND REQUEST >>
  }
}

A: A simple way of doing what you want using JQuery:
(this works if you have only input texts)
HTML:
<form method='POST' action=''>
<input type='text' name='name' />
<input type='text' name='phone' />
<input type='text' name='email' />
<button type='submit' disabled='disabled'>Send</button>
</form>

Javascript:
$(function() {
     $("input").change(function() {
          if($("input[value='']").length == 0) {
               $("button").removeAttr("disabled");
          } else {
               //disable again if a field is cleared
               $("button").attr("disabled",true);
               alert("Please fill all fields");
               $("input[value='']").eq(0).focus();
          }
     });
});


text:
Q: Is it possible to convert a lottie animation to a GIF? I know Lottie animations are far superior to GIFs in terms of size, control, and quality. I'm looking for a way to convert a single Lottie animated as I don't want to include extra javascript resources in a project. Is there a way to convert a Lottie animation to a GIF or another moving image?

A: As mentioned here: https://github.com/airbnb/lottie-web/issues/1614 there is a javascript library for this.
It's called puppeteer-lottie.
They also provide a command line interface
I used it once and the output was not as good as the original lottie animation but ok. I just used the default settings.

A: You could use https://lottiefiles.com/lottie-to-gif to convert your Lottie animations to GIF.


text:
Q: Can we decompose an increasing net of functions into two increasing nets with prescribed supports? Let $K$ be a compact Hausdorff space and let $U,V\subset K$ be open. Let $\left(f_{i}\right)_{i\in I}$ be an increasing net of continuous non-negative functions such that $f_{i}\le 1$ and $f_{i}$ vanish outside of $U\cup V$. In my specific situation $\sup_{i\in I} f_{i}(x)=1$, for every $x$ in some dense subset of $U\cup V$, but I don't think it is relevant here.

Can we find two increasing nets $\left(g_{p}\right)_{p\in P}$ and $\left(h_{q}\right)_{q\in Q}$ of continuous non-negative functions such that $g_{p}$ and $h_{q}$ vanish outside of $U$ and $V$, respectively, and $g_{p}+h_{q}\le 1$, for every $p,q$, but for every $i$ there are $p,q$ such that  $g_{p}+h_{q}\ge f_{i}$?

In the case when $U\cup V$ happens to be normal, since $U\backslash V$ and $V\backslash U$ are closed in $U\cup V$, there is $e:U\cup V\to [0,1]$ which equals $1$ on $U\backslash V$ and vanishes on $V\backslash U$. Define $e$ to be $0$ on $K\backslash\left(U\cup V\right)$. Then, taking $g_{i}=(1-e)f_{i}$ and $h_{i}=ef_{i}$ accomplishes the goal.


text:
Q: Deleting column using vba takes a huge amount of time Newbie here.
I'm trying to delete a column using vba and it is taking a HUGE amount of time.
Sub Add_Delete()
Application.ScreenUpdating = False
Workbooks("f.xlsx").Sheets("g").Columns("FD:FD").EntireColumn.Delete
End Sub

There are about 20,000 rows with a total of amount 230 columns. There are no calculations being performed. Just data
What am I doing wrong?  Thanks in advance!

A: If it is slow manually also turn off calculation before running it, then turn it back on.
Sub Add_Delete()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Workbooks("f.xlsx").Sheets("g").Columns("FD:FD").EntireColumn.Delete
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub

add screen updating back in also... ;-)


text:
Q: What is the command to display abstract syntax tree for a program using frama-c? I am using frama-c version Phosphorus-20170501. I want to generate abstract syntax tree for the programs using Frama-C. I need to do research on the abstract syntax tree generated from a program using the program analysis tool Frama-C.
I have gone through the manual, where I have read how to calculate Cyclomatic complexity using 'metrics' plugin. Unfortunately, the content doesn't tell anything on how to generate abstract syntax tree. I have gone through other resources also, but it doesn't provide proper answer. I need the command to display abstract syntax tree of a program using the tool Frama-C. Kindly please, help me with this !!


text:
Q: Solr 8.7 configset empty when uploaded with authentication We have enabled authentication in Solr 8.7 and now I want to upload a configset and thereby create a collection based on this configset.
I have followed the below steps:

*

*create config zip
(cd /disk/configsets/my-collection/conf && zip -r - *) > my-collection.zip
The zip file rightly contains all configurations as expected with top level as solrconfig.xml

*upload configset to zookeeper
curl -X POST --header "Content-Type:application/octet-stream" --user userSolr:pwdSolr --data-binary @my-collection.zip "http://host:port/solr/admin/configs?action=UPLOAD&name=my-collection"

*create collection
curl -X POST --header "Content-Type:application/octet-stream" --user userSolr:pwdSolr "http://host:port/solr/admin/collections?action=CREATE&name=my-collection&numShards=1&replicationFactor=1&createNodeSet=localhost:8081_solr&collection.configName=my-collection"
I can see the configset listed in Solr UI as well as the created collection.
However, when I click on files section of collection, its empty. This collection has no configs which means the configset is uploaded empty.
What am I missing?


text:
Q: Python class takes no argument, 3 given (using __init__) I'm trying to create a web crawler from youtube tutorials and such.
I'm facing an issue where I have a class that won't take arguments(other classes do take parameters, structured more or less the same)
The class (crawler.py). I'm using __init__, where I take 3 arguments.
class Crawler:
    # class variables are shared among all crawler instances
    project_name = ''
    home_url = ''
    site_domain = ''
    # use set to speed up read/write process
    file_queue = ''
    queue = set()
    # use set to speed up read/write process
    file_crawled = ''
    crawled = set()

    def __init__(self, project_name, home_url, site_domain):
        Crawler.project_name = project_name
        Crawler.home_url = home_url
        Crawler.site_domain = site_domain
        Crawler.file_queue = Crawler.project_name + '/links_on_queue.txt'
        Crawler.file_crawled = Crawler.project_name + '/links_crawled.txt'
        self.starter(Crawler.site_domain)
        self.crawl_page('first_crawler', Crawler.home_url)

Where it's being called, on the last line (main.py)
import threading
from queue import Queue
# import from files
from crawler import Crawler
from domain_finder import *
from general_crawler_functions import *

# like multiple group members doing different parts, the program
# creates multiple thread that works simultaneously

PROJECT_NAME = 'Demoblaze'
HOME_URL = 'https://www.demoblaze.com/'
DOMAIN_NAME = get_domain(HOME_URL)
FILE_QUEUE = PROJECT_NAME + '/links_on_queue.txt'
FILE_CRAWLED = PROJECT_NAME + '/links_crawled.txt'
THREAD_COUNT = 4
# queue of threads
queue = Queue()
Crawler(PROJECT_NAME, HOME_URL, DOMAIN_NAME)

The error said the class takes no arguments, 3 given
I'm using PyCharm Community on windows, if it helps

A: In main.py you have imported Crawler from crawler
from crawler import Crawler

You should import the Crawler which you have implemented on your own.
Use
import Crawler

instead of
Crawler from crawler


text:
Q: Create a plane that exactly fills the browser window with a perspective camera I want to create a plane with the exact dimensions to fill the browser window.
How can this be done while using a perspective camera?
Using an isometric camera, I think this is pretty simple since I can set the plane's width and height to the window.innerWidth & window.innerHeight values.
Using a perspective camera, I need some equation to go between the desired width (window.innerWidth) and the width assigned to the plane - since perspective will effect it.
Maybe there are some equations I'm not aware of that relate "rendered" size to an objects actual size, distance from the camera, and camera's field of view?
What I've tried:
@westlangley's answer here:
// Convert the field of view to radians
var vFOV = camera.fov * Math.PI / 180;

// Get the visible height
var height = 2 * Math.tan( vFOV / 2 ) * distanceOfPlaneFromCamera;

// If we want a width that follows the aspect ratio of the camera, then get the aspect ratio and multiply by the height.
var aspect = window.innerWidth / window.innerHeight;
var width = height * aspect;

With a field of view = 90, and a distanceOfPlaneFromCamera = 55, the result for height = 109.9999.
I'm not sure what "unit" that value is describing. How would I go from that # to sizing a plane so it fills my screen?


text:
Q: Vulnerability : Password type input with auto-complete enabled
*

*I have added autocomplete="off" and also i tried autocomplete="new-password" to the password texfield

<input type="password" name="login[password]" id="login_password" placeholder="Password" data-validate="not-empty" data-validate-error-message-position="below">

*

*Already saved Password autocomplete is coming in chrome and firefox which should not come and if i use autocomplete="off" or autocomplete="new-password" in input field. I need solution to fix this Vulnerability. Your help will be appreciated.

A: Most of the major browsers now ignore autocomplete=off.
For more info check this
You can add hidden input has type password
  <input type="text" style="display:none">
  <input type="password" style="display:none">

A: We recently faced this issue, to overcome this we did some trick will explain below,
Problem,
We faced issue with save password modal is appearing when doing login (post successful), note we are not using inside
Solution

*

*We keep this <input type="password" autoComplete="off" autoCorrect="off" /> as its

*Using CSS we will apply password type (dot) behaviour

mask the text and will show the password type dot
    font-family: "text-security-disc";
    text-security: disc;
    -webkit-text-security: disc !important;
    -mox-text-security: disc;

*Before submit(first step of submit before making ajax call) we will change the type of the input to "text" so that browser will not understand and wont prompt the user. also as you mapped password using CSS you cant able to see in the UI even if you change the type.


text:
Q: amcharts that have no data in dynamic data provider Gracefully handle amcharts that have no data. I want know if my dataProvider empty. When amcharts draw default null. How can I handle it dynamically?
var chart = AmCharts.makeChart("chartdiv", {
    "theme": "none",
    "type": "serial",
    "dataProvider": data,
    "valueAxes": [{
    "title": "Income in millions, USD"
}]

I want to know how to handle it when the data is empty.

A: Handle it externally by checking if the dataset contains records before even rendering the chart.
if (data && data.length){
  var chart = AmCharts.makeChart("chartdiv", {
    "theme": "none",
    "type": "serial",
    "dataProvider": data,
    "valueAxes": [{
    "title": "Income in millions, USD"
  }]
} else {
   // display a message to the user that there is no data available
}

The AMCharts folks seemed to have neglected handling an empty data set being passed in.
Another option is to create a dummy data point that displays a label on the chart. I haven't personally used this approach because I would rather just hide the graph entirely if it contains no data.


text:
Q: Attemping to Remove Lines from Text File I have created a text file that stores different flight information. I want the admins to be able to remove flights from this page by clicking a 'remove' button associated. I have the following code:
    private void removeButtons()
    {
        for (int x = 0; x < buttons.Count(); x++)
        {
            Button booked = buttons[x];
            booked.Click += new EventHandler(removeFlights);
        }
    }

    private void removeFlights(object sender, EventArgs e)
    {
        string tempFile = Path.GetTempFileName();
        using (var sr = new StreamReader(AppendTexts.flightPathText))//Location of file
        {
            using (var sw = new StreamWriter(tempFile))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    String[] flights = line.Split(',');
                    for (int x = 0; x < buttons.Count(); x++)//If the button clicked matches all the fields, skip it, otherwise write it to temp file
                    {
                        if (airline[0].Text == flights[0] & price[x].Text == flights[1] & cityStartMatch[x].Text == flights[2] & stateStartMatch[x].Text == flights[3] &
                            cityDestMatch[x].Text == flights[4] & stateDestMatch[x].Text == flights[5] & seatsMatch[x].Text == flights[6] & dateMatch[x].Text == flights[7])
                        {

                        }
                        else
                        {
                            sw.WriteLine(flights[0] + "," + flights[1] + "," + flights[2] + "," + flights[3] + "," + flights[4] + "," + flights[5] + "," + flights[6] + "," +  flights[7]);
                        }
                    }
                }
                sr.Close();
            }
        }
        File.Delete(AppendTexts.flightPathText);
        File.Move(tempFile, AppendTexts.flightPathText);
    }

The problem I am having, is that instead of removing the old lines, it just re-adds the other ones to the file. So if I have a flight using the Delta airline and another using Southwest, and I attempt to remove the Delta airline, when I list the flights again, the Delta airline shows up once, but the Southwest airline shows up twice.

A: A. Using a text file as a database in a bad practice.
B. When deleting multiple values from a collection,
either use a temporary collection that you write
good value to.
Then delete original collection and overwrite with temp one.
Or... Delete in-place from end to beginning,
so that current index is not messed up by deleted.
(Use of temp file is more recommended when deleting from large text files,
in the second method you also have to keep reducing file size.)
C. In your solution, you didn't change position
to correct one, calculsted relative to beginning of file, before each write
(and readjust before each read).

A: Databases are great, really useful for this sort of application, and will greatly improve your applications.
I'm a developer by trade, and spend about 20 / 30% of my time writing SQL (database language), and really this is what you should be using for a ASP.NET app or any web app for that matter.
Once you learn it and start using it fully, you'll wonder how you ever did without it.


text:
Q: Uploading file using POST request in Node.js I have problem uploading file using POST request in Node.js. I have to use request module to accomplish that (no external npms). Server needs it to be multipart request with the file field containing file's data. What seems to be easy it's pretty hard to do in Node.js without using any external module.
I've tried using this example but without success:
request.post({
  uri: url,
  method: 'POST',
  multipart: [{
    body: '<FILE_DATA>'
  }]
}, function (err, resp, body) {
  if (err) {
    console.log('Error!');
  } else {
    console.log('URL: ' + body);
  }
});

A: Leonid Beschastny's answer works but I also had to convert ArrayBuffer to Buffer that is used in the Node's request module. After uploading file to the server I had it in the same format that comes from the HTML5 FileAPI (I'm using Meteor). Full code below - maybe it will be helpful for others.
function toBuffer(ab) {
  var buffer = new Buffer(ab.byteLength);
  var view = new Uint8Array(ab);
  for (var i = 0; i < buffer.length; ++i) {
    buffer[i] = view[i];
  }
  return buffer;
}

var req = request.post(url, function (err, resp, body) {
  if (err) {
    console.log('Error!');
  } else {
    console.log('URL: ' + body);
  }
});
var form = req.form();
form.append('file', toBuffer(file.data), {
  filename: file.name,
  contentType: file.type
});

A: You can also use the "custom options" support from the request library. This format allows you to create a multi-part form upload, but with a combined entry for both the file and extra form information, like filename or content-type. I have found that some libraries expect to receive file uploads using this format, specifically libraries like multer.
This approach is officially documented in the forms section of the request docs - https://github.com/request/request#forms
//toUpload is the name of the input file: <input type="file" name="toUpload">

let fileToUpload = req.file;

let formData = {
    toUpload: {
      value: fs.createReadStream(path.join(__dirname, '..', '..','upload', fileToUpload.filename)),
      options: {
        filename: fileToUpload.originalname,
        contentType: fileToUpload.mimeType
      }
    }
  };
let options = {
    url: url,
    method: 'POST',
    formData: formData
  }
request(options, function (err, resp, body) {
    if (err)
      cb(err);

    if (!err && resp.statusCode == 200) {
      cb(null, body);
    }
  });

A: An undocumented feature of the formData field that request implements is the ability to pass options to the form-data module it uses:
request({
  url: 'http://example.com',
  method: 'POST',
  formData: {
    'regularField': 'someValue',
    'regularFile': someFileStream,
    'customBufferFile': {
      value: fileBufferData,
      options: {
        filename: 'myfile.bin'
      }
    }
  }
}, handleResponse);

This is useful if you need to avoid calling requestObj.form() but need to upload a buffer as a file. The form-data module also accepts contentType (the MIME type) and knownLength options.
This change was added in October 2014 (so 2 months after this question was asked), so it should be safe to use now (in 2017+). This equates to version v2.46.0 or above of request.

A: Looks like you're already using request module.
in this case all you need to post multipart/form-data is to use its form feature:
var req = request.post(url, function (err, resp, body) {
  if (err) {
    console.log('Error!');
  } else {
    console.log('URL: ' + body);
  }
});
var form = req.form();
form.append('file', '<FILE_DATA>', {
  filename: 'myfile.txt',
  contentType: 'text/plain'
});

but if you want to post some existing file from your file system, then you may simply pass it as a readable stream:
form.append('file', fs.createReadStream(filepath));

request will extract all related metadata by itself.
For more information on posting multipart/form-data see node-form-data module, which is internally used by request.

A: I did it like this:
// Open file as a readable stream
const fileStream = fs.createReadStream('./my-file.ext');

const form = new FormData();
// Pass file stream directly to form
form.append('my file', fileStream, 'my-file.ext');

A:  const remoteReq = request({
    method: 'POST',
    uri: 'http://host.com/api/upload',
    headers: {
      'Authorization': 'Bearer ' + req.query.token,
      'Content-Type': req.headers['content-type'] || 'multipart/form-data;'
    }
  })
  req.pipe(remoteReq);
  remoteReq.pipe(res);


text:
Q: Trying to multiply specific columns, by a portion of multiple rows in Pandas DataFrame (Python) I am trying to multiply a few specific columns by a portion of multiple rows and creating a new column from every result. I could not really find an answer to my question in previous stackoverflow questions or on google, so maybe one of you can help.
I would like to point out that I am quite the beginner in Python, so apologies ahead for any obvious questions or strange code.
This is how my DataFrame currently looks like:

So, for the column Rank of Hospital by Doctor_1, I want to multiply all its numbers by the values of the first row of column Rank of Doctor by Hospital_1 until column Rank of Doctor by Hospital_10. Which would result in:
1*1
2*1
3*1
4*4
...

and so on.
I want to do this for every Doctor_ column. So for Doctor_2 its values should be multiplied by the second row of all those ten columns (Rank of Doctor by Hospital_. Doctor_3, multiplied by the third row etc.
So far, I have transposed the Rank of Doctor by Hospital_ columns in a new DataFrame:

and tried to multiply this by a DataFrame of the Rank of Hospital by Doctor_ columns. Here the first column of the first df should be multiplied by the first column of the second df. (and second column * second column, etc.):

But my current formula
preferences_of_doctors_and_hospitals_doctors_ranking.mul(preferences_of_doctors_and_hospitals_hospitals_ranking_transposed)

is obviously not working:

Does anybody know what I am doing wrong and how I could fix this? Maybe I could write a for loop so that a new column is created for every multiplication of columns? So Multiplication_column_1 of DF3 = Column 1 of DF1 * Column 1 of DF2 and Multiplication_column_2 of DF3 = Column 2 of DF1 * Column 2 of DF2.
Thank you in advance!
Jeff

A: You can multiple 2d arrays created by filtering column with filter and values first:
arr = df.filter(like='Rank of Hospital by').values * df.filter(like='Rank of Doctor by').values

Or:
arr = (preferences_of_doctors_and_hospitals_doctors_ranking.values *
       preferences_of_doctors_and_hospitals_hospitals_ranking_transposed.values)

Notice - necessary is same ordering of columns, same length of columns names and index in both filtered DataFrames.
Get 2d array, so create DataFrame by constructor and join to original:
df = df.join(pd.DataFrame(arr, index=df.index).add_prefix('Multiplied '))

A: df = pd.DataFrame({"A":[1,2,3,4,5], "B":[6,7,8,9,10]})
df["mul"] = df["A"] * df["B"]

print(df)

Output:
   A   B  mul
0  1   6    6
1  2   7   14
2  3   8   24
3  4   9   36
4  5  10   50

If I understood the question correctly I think you way over complicated it.
You can just create another column telling pandas to give it the value of first column multiplied by second column.
More similar to your specific case with more than 2 columns:
df = pd.DataFrame({"A":[1,2,3,4,5], "B":[6,7,8,9,10], "C":[11,12,13,14,15]})
df["mul"] = df["A"] * df["B"] * df["C"]


text:
Q: Inserting products into Magento stops after x items I am trying to insert products into a Magento Web Shop using the following code:
public static function addProduct($product, $categorieId) {
    $productModel = Mage::getModel('catalog/product');

    $productModel->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE)
            ->setWebsiteIDs(array(1))
            ->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
            ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
            ->setCreatedAt(strtotime('now'))
            ->setName($product->PRODUCT_DETAILS[0]->DESCRIPTION_SHORT)
            ->setCategoryIds(array($categorieId))
            ->setDescription($product->PRODUCT_DETAILS[0]->DESCRIPTION_LONG ? $product->PRODUCT_DETAILS[0]->DESCRIPTION_LONG : $product->PRODUCT_DETAILS[0]->DESCRIPTION_SHORT)
            ->setShortDescription($product->PRODUCT_DETAILS[0]->DESCRIPTION_SHORT)
            ->setPrice($product->PRODUCT_PRICE_DETAILS->PRODUCT_PRICE->PRICE_AMOUNT)
            ->setAttributeSetId($productModel->getResource()->getEntityType()->getDefaultAttributeSetId());

    $productModel->setStockData(array(
        'is_in_stock' => 1,
        'qty' => 99999
    ));

    try {
        $productModel->save();
        return $productModel->getId();
    } catch (Exception $ex) {
        Mage::log($ex->getMessage());
    }
}

Nevertheless, the code inserts items into the right categories. After about 38 items it stops, with no error and nothing. The Ajax call returns no errors, nothing. Any ideas what this can be caused by?
cheers
Wolfgang

A: I would guess that you are hitting the script execution time limit (php.ini max_execution_time)
Assuming you are not running in PHP's "Safe Mode", try inserting the following at the top of your method. (I am assuming this method gets called over and over again.  It will reset the time limit each time)
set_time_limit(30);


text:
Q: Why doesn't Chromium render a web page on one particular computer? I have a strange problem using DCEF3 (last version - c30150c47432 - CEF 3.1650.1562) in a Delphi application.
All seems to be ok on all PC where I install application, except for a PC, where there is the following problem:
when Chromium loads web page with following code:
procedure TMainForm.StartNavigate();
var
  navigateto: String;

begin
  navigateto := 'http://' + URL;

  crm.Load(navigateto);

  crm.Repaint();
end;

the page is not rendered, Chromium's window remains blank.
This situation occurs on a particular PC with video card amd radeon hd 7650m and amd catalyst driver (may be this is relevant ?), on all other systems it's all ok.
Some suggestion ?


text:
Q: Why does my ADC reading not increase when the supply voltage decreases? I am using a 10 bit ADC and 5V supply, so resolution is \$\frac{5}{1023}\$. I decreased my voltage supply to 4V, the resolution now is \$\frac{4}{1023}\$
For both cases, I am reading a constant value of 2.5V from the potentiometer. Shouldn't my LCD screen show a significant increase in voltage value because while the using 5V supply, the number of bit using to represent 2.5V is roughly 511 bits, when voltage decrease to 4V, the same voltage level will be represent by roughly 640 bits. In my original code, I am using (5/1023)*number of bits, hence the reading should increase when the voltage supply decreases but I have not seen significant increase in voltage reading (theoretically, it will be 3.125V.)

A: If you are using VCC as the ADC reference, and using the same VCC as potentiometer reference, then pot output and ADC measurements are both proportional to VCC so the ADC reading stays exactly the same.


text:
Q: Save form v.s submit form in infopath2010 Hi
I am new to Infopath ,SharePoint2010.
I have a form library where user can complete a form. It allows user to save incomplete form. Once they complete the form , it will allow user to submit the form. However, When saving the form , it will create new form and save into the form library ,when submit the form it will create another form in the same form library. How can I make sure that when user submit the form , it will use the current saved form.
Can this achievable or I am asking too much?

A: Best practice is to use submit to Sharepoint rather than save.
That way you can control where and with what name the documents are saved.
Also it is one click for the users.
It sounds like you need to turn off the reminder to save in the form options. That way the users will not be prompted.
To keep the file name from changing you need to only calculate it when the form is initially completed.
Create a file name filed in the form.  If it is blank on open set it to username+date.  That way the first time the form is opened it is set but after that it does not change.  Then in your submit data connection use the filename field as the file name.


text:
Q: How to make track-changes column/range specific I have a table with a number of columns and rows in it and I would like to track the changes made in a specific column. I found the code (see bottom of message) online, and it works perfectly. However, it tracks "all changes". Is there a way to make it range specific. For example I only want to track the changes made in the column with the red numbers. Please see the example:

The code I found online is the following:
Option Explicit

Dim vOldVal 'Must be at top of module

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Dim bBold As Boolean
    If Target.Cells.Count > 1 Then Exit Sub
    If ActiveSheet.Name = "Pricing" Then Exit Sub
    'On Error Resume Next
    With Application
         .ScreenUpdating = False
         .EnableEvents = False
    End With
    If IsEmpty(vOldVal) Then vOldVal = "Empty Cell"
    bBold = Target.HasFormula
        With Sheets("Data")
            '.Unprotect Password:="Secret"
                If .Range("A96") = vbNullString Then
                    .Range("A96:H96") = Array("Cell Changed", "Old Value", _
                        "New Value", "Old Formula", "New Formula", "Time of Change")
                End If
            With .Cells(.Rows.Count, 1).End(xlUp)(2, 1)
                  .Value = ActiveSheet.Name & " : " & Target.Address
                  .Offset(0, 1) = vOldVal
            With .Offset(0, 2)
              If bBold = True Then
                .ClearComments
                .AddComment.Text Text:= _
                     "OzGrid.com:" & Chr(10) & "" & Chr(10) & _
                        "Bold values are the results of formulas"
              End If
                .Value = Target
                .Font.Bold = bBold

            End With
                .Offset(0, 3) = Time
                .Offset(0, 4) = Date
                .Offset(0, 5) = Application.UserName
            End With
            .Cells.Columns.AutoFit
            '.Protect Password:="Secret"
        End With
    vOldVal = vbNullString
    With Application
         .ScreenUpdating = True
         .EnableEvents = True
    End With
    On Error GoTo 0
End Sub

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
        vOldVal = Target
End Sub

Private Sub test()
    Application.EnableEvents = True
End Sub

Please keep in mind that I'm very new to VBA coding.

A: You can do it by adding a single line to your existing code:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Dim bBold As Boolean
    If Target.Cells.Count > 1 Then Exit Sub
    If ActiveSheet.Name = "Pricing" Then Exit Sub
    If Target.Column <> 4 Then Exit Sub

This will just check to see if it is the 4th column of your sheet that has been changed and will ignore changes elsewhere.


text:
Q: List a group of addresses obtained with the Google Maps Geocoder API I can't find a way to properly list a group of addresses obtained from the Google Maps Geocoder API.
What I want to achieve:

*

*Read an object containing longitude and latitude info for a bunch of stores (in production this will come from a WS, right now I'm using a hardcoded object named responseObj)

*Use the Geocoder API to obtain full addresses for each store (the WS only provides lat & lon values)

*Display a list of stores, using information from the responseObj object (the name of the store, distance to current location; both already provided by the WS) as well as the full addresses provided by the Geocoder

My code so far (JS):

    /*
    I'm simulating the response I would obtain from a WS inside this object:
    */
    var responseObj = [{
        "storeName": "Store Number One",
        "lat": "XX.XXXX",
        "lon": "-XX.XXXX",
        "kilometers": 0.10
    }, {
        "storeName": "Two: The Store",
        "lat": "XX.XXXX",
        "lon": "-XX.XXXX",
        "kilometers": 0.50
    }, {
        "storeName": "Three Market",
        "lat": "XX.XXXX",
        "lon": "-XX.XXXX",
        "kilometers": 0.60
    }, {
        "storeName": "Four's",
        "lat": "XX.XXXX",
        "lon": "-XX.XXXX",
        "kilometers": 0.85
    }]

    /*
    /* Getting a list of stores and displaying addresses
    */
    function listStores(stores) {

        for (var key in stores) {
            if (stores.hasOwnProperty(key)) {
                var storeLat = stores[key].lat;
                var storeLon = stores[key].lon;

                var geocoder = new google.maps.Geocoder();
                var storeLatLong = new google.maps.LatLng(storeLat, storeLon);
                var formattedAddress;

                geocoder.geocode({
                    "latLng": storeLatLong
                }, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        if (results) {
                            formattedAddress = results[0].formatted_address;
                            // For debugging:
                            //console.log(results[0].formatted_address);
                        }
                    } else {
                        formattedAddress = "Address unavailable.";
                        // For debugging:
                        // console.log("Address unavailable.");
                    }
                });

                var dataListItem = document.createElement("li");
                dataListItem.innerHTML = "" + stores[key].tienda + "" + " , " + stores[key].kilometers.toFixed(2) + " km away. Address: " + formattedAddress;

                document.getElementById('stores_list').appendChild(dataListItem);
            };
        }
    }

    listStores(responseObj);

Consider the most basic markup structure:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Stores List</title>

Stores:

My problem
I can't manage to properly append the address returned by the geocoder into the list items with the rest of the store info. I'm pretty sure I'm missing something about the asynchronous behaviour of the geocoder, but I'm quite new to JS and can't figure out what.
Please help me understand how to properly display everything as mentioned above.

A: Well, is far as i can see, the problem is that the google geocoder function is asynchronous, to solve this i usually build a recursive function just like this:
//I'm simulating the response I would obtain from a WS inside this object:
    var responseObj = [{
        "storeName": "Store Number One",
        "lat": "XX.XXXX",
        "lon": "-XX.XXXX",
        "kilometers": 0.10
    }, {
        "storeName": "Two: The Store",
        "lat": "XX.XXXX",
        "lon": "-XX.XXXX",
        "kilometers": 0.50
    }, {
        "storeName": "Three Market",
        "lat": "XX.XXXX",
        "lon": "-XX.XXXX",
        "kilometers": 0.60
    }, {
        "storeName": "Four's",
        "lat": "XX.XXXX",
        "lon": "-XX.XXXX",
        "kilometers": 0.85
    }]

    /*
/* Getting a list of stores and displaying addresses
*/
    function listStores(stores, index) {

        // Test for not going on infinite loop
        if (index == stores.length) {
            return;
        }

        var storeLat = stores[index].lat;
        var storeLon = stores[index].lon;
        var geocoder = new google.maps.Geocoder();
        var storeLatLong = new google.maps.LatLng(storeLat, storeLon);
        var formattedAddress;

        geocoder.geocode({
            "latLng": storeLatLong
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results) {
                    formattedAddress = results[0].formatted_address;
                    // For debugging:
                    //console.log(results[0].formatted_address);

                    var dataListItem = document.createElement("li");
                    dataListItem.innerHTML = "" + stores[index].tienda + "" + " , " + stores[index].kilometers.toFixed(2) + " km away. Address: " + formattedAddress;
                    document.getElementById('stores_list').appendChild(dataListItem);

                    // after a success response call it gain with new intex value
                    listStores(stores, (index + 1));
                }

            } else {
                formattedAddress = "Address unavailable.";
                // For debugging:
                // console.log("Address unavailable.");
            }
        });

    }

    listStores(responseObj);

I didn't test id, so give it a try.
Best regards.


text:
Q: How do I reformat text into a different pattern? How can I program my code to change this pattern of BBBBB-AAA to 0AAABBBBB? I'm using asp.net, vb.net, and jQuery.
The format for a Canadian bank account routing number:

A Canadian routing number displayed on a check needs to be reformatted
  differently for electronic payments. If a check displays a routing
  number as BBBBB-AAA (where AAA indicates the Financial Institution and
  BBBBB is the branch), then the routing number must be changed to
  0AAABBBBB to process the payment electronically. For example, if a
  check from an account issued by the Bank of Montreal showed the
  routing number 00011-001, then that number would need to be
  reformatted to 000100011 for the payment to be electronically
  processed.

I get data from the user here on my .aspx page:
<input id="txtBankCode" maxlength="9" required="required" />

And I grab the data here on my jQuery .js page:
var bankCode = $("#txtBankCode").val()

I need to rearrange bankCode to be the format 0AAABBBBB instead of BBBBB-AAA. I am guessing some users will not type the dash while some users will. How can I do this?

A: Given that the hyphen is optional you can't rely on its presence in order to split the string. As such an alternative solution would be to use a regular expression to reorganise the string based on its input format. Try this:
Here's a JS solution:

var bankCode = 'BBBBB-AAA';
bankCode = bankCode.replace(/^(\w{5})-?(\w{3})$/, '0$2$1');

console.log(bankCode);

And here's the same logic in VB:
Dim bankCode As String = "BBBBB-AAA"
bankCode = Regex.Replace(bankCode, "^(\w{5})-?(\w{3})$", "0$2$1")

Console.WriteLine(bankCode)

A: EDIT I think I misunderstood your comment about the optional dash. A split won't work here, then, as it requires the dash to be present. So you'll need to first clean up the string by removing the dash if it's there, then use substring or regex to rearrange it:
bankCode = bankCode.replace(/-/g, '');
const first = bankCode.substring(0,5);
const second = bankCode.substring(5);
bankCode = `0${second}${first}`;

A: Try this.

function show() {
    var bankCode = $("#txtBankCode").val();
    console.log(bankCode.replace(/([a-zA-Z]{5})-?([a-z-A-Z]{3})/, `0$2$1`));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="txtBankCode" maxlength="9" required="required" />
<button type="button" onclick="show()">Show</button>


text:
Q: I want to re-install ubuntu, how to tell which partition to replace? I wanted to re-install because the install didn't work properly the first time, how do I tell which partition is the one automatically created when I last installed it?

A: If you don't want to change the size of the partition, then the Ubuntu installer will ask you if you want to reinstall Ubuntu.


text:
Q: Display specific value for a dropdown list from a value of another dropdown list How to get the scheduleID value from a comboBox within a specific MovieID value from another comboBox?

comboBox Movie
<?php
$query = "select * from ref_movies ORDER BY MovieID";
$result = mysql_query($query) or die (mysql_error());

echo '<select name="MovieID" ><option value="">---Select Movie---</option>';

while ($row = mysql_fetch_assoc($result))
{
    echo "<option value='" . $row['MovieID'] ."'>" . $row['MovieTitle'] ."</option>";
}
echo '</select>';
?>

comboBox Schedule
<?php
$query = "select * from schedule ORDER BY scheduleID";
$result = mysql_query($query) or die (mysql_error());

echo '<select name="ScheduleID" ><option value="">---Select Time---</option>';

while ($row = mysql_fetch_assoc($result))
{
    echo "<option value='" . $row['ScheduleID'] ."'>" . $row['MovieDATETIME'] ."</option>";
}
echo '</select>';
?>

A: Put the two PHP scripts in separate files.
Set the form action in the first one to the URL of the second one.
Read the value from $_GET['MovieID'].


text:
Q: Convergence of $V_n=\prod\limits_{i=1}^n U_i$ I struggle to do this exercise:
Let $U_1,U_2,\dots$ be a sequence of i.i.d. random variables. We define
$$V_n=\prod\limits_{i=1}^n U_i$$
Show that $V_n^{1/n}$ converges almost sure and calculate the limit.
So what I thought so far:
Since I have to show almost sure convergence, I would think that I have to show this with the law of large numbers.
So $$\lim\limits_{n\to \infty}\sum\limits_{i=0}^n\frac{\sqrt{V_n}}{n}=E[\sqrt{V_n}]=nE[\sqrt{U_i}]$$
Now here I'm stucked and I don't know if this is correct. Thanks for help.

A: Assuming that $U_i > 0$, we may define $X_i$ as $\log U_i$. Assuming that $\mathbb{E}[\log U_i]<+\infty$, the law of large numbers gives
$$ \frac{X_1+\ldots+X_n}{n}\to \mathbb{E}[\log U_i] $$
and by exponentiating back
$$ V_n^{1/n} \to \exp\left(\mathbb{E}[\log U_i]\right). $$


text:
Q: Object released too soon using ARC on iOS 5? I created a class AppSettings containing booleans:
#import <Foundation/Foundation.h>

@interface AppSettings : NSObject{

bool bip10secCountdown;
bool jv10secCountdown;
bool jv30secAlert;
bool jv1minAlert;
bool jvp5minAlert;

}

@property bool bip10secCountdown;
@property bool jv10secCountdown;
@property bool jv30secAlert;
@property bool jv1minAlert;
@property bool jv5minAlert;

@end

And the implementation:
#import "AppSettings.h"

@implementation AppSettings

@synthesize bip10secCountdown, jv10secCountdown, jv30secAlert, jv1minAlert, jv5minAlert;

- (id)init
{
    self = [super init];
    if (self){
    }
    return self;

}

@end

Then I'm trying to use this class in my main class but after initializing the object in the viewDidLoad, when I want to use it again it appears as null.. So I guess it's released too early. I'm using ARC so I don't manually manage the memory. Am I doing something wrong ?
The declaration in the main class:
AppSettings *appSettings;

}

@property(nonatomic)bool activated;
@property (nonatomic, strong) AppSettings *appSettings;

And the implementation:
@synthetize appSettings
...
- (void)viewDidLoad
{
    // Initialize the model
    self.appSettings = [[AppSettings alloc]init];

NSLog(@"appSettings = %@",self.appSettings);

The first output is OK.
But then when I try to access appSettings from another method in the Main class, the appSettings is (null)
Thank you for your help.

A: The view has most likely unloaded, or your view controller has been released. Try moving the initialization code to the method where your view controller is initiated(- (id)initWithNibName: bundle:)

A: Instead of:
@property (nonatomic, strong) AppSettings *appSettings;

Try:
@property (nonatomic, retain) AppSettings *appSettings;

And I'd recommend to make your AppSettings as a Singleton-class.

A: When you say you initialise the view contoller in AppDelegate I presume you mean MyViewController *theView = [[MyViewController alloc] init]; or something like that. That will be your first view and you should initialise AppSettings in viewDidLoad of MyViewController, not the AppDelegate.
demon9733 suggestion regarding making AppSettings a singleton is a good one as you will be able to easily access your settings from anywhere in the app.
Also verify whether ARC is being used for MyViewController (or whatever it might be)


text:
Q: Geolocation using global map in ArcGIS Desktop? I want to show my study sites (15 from different countries) using a global map in ArcGIS Desktop.
I'd like to show latitudes and longitudes (perhaps with a map grid).
Is there a way to drop pins to show locations, or at least include map grid?

A: If wizards are enabled, the Grids and Graticules Wizard in the Data Frame Properties > Grids Tab allows you to set up map grids in an layout. In the wizard, choose the graticule option if you want to display lines of latitude and longitude (parallels and meridians). You can choose the type of graticule that you want, change the appearance, symbols, etc. It is also possible to display only markers (point symbols) at the intersections of the grid lines by choosing the "Tick marks and labels" option in the wizard.

Appearance options are also available anytime by clicking the "Properties" button in the Data Frame Properties.


text:
Q: In a GUI, how to change the mouse to Zoom-to-rectangle I am creating a GUI that revolves around looking at a plot. The users are assumed to be very dense, as per instruction. That being said, I have been told that the default Zoom-to-rectangle button needs to have another button in the toolbar at the top of the program (which I would also program to a shortcut for ease of use).
The problem I am having is I don't know how to turn the mouse into the Zoom-to-rectangle. I don't want it to actually zoom, just change the mouse to where if it is then dragged across the plot while clicking, it will then zoom.
This is hard to explain, so if you need more information than what is provided please ask.


text:
Q: Salesforce Marketing Cloud Context:
I'm currently weighing options on project for social media management.
We are currently considering custom build vs product based approach.
The requirements:

*

*Manage content publishing to Facebook (wall post, event) and Twitter.

*plan (workflow & approval process) & schedule the content publishing with a team (manager, seeder, etc)

*Listening to conversation stream on the account profiles being managed

*Engaging with fans and follower to identify influence and lead.

*Performance analytic on the social media campaign

Since this is salesforce group, so obvious it's Salesforce Marketing Cloud which consist of Radian6 & Buddy Media (and Social.com).
Questions:

*

*Which marketing cloud component do I need? My research tells me I just need the Buddy Media.

Thank you.
Note: I can't create the right tags for this topic since my reputation still low, so chose a generic one.

A: While I don't have direct experience in using these products, I've sat through multiple demos of the tools. I agree that to publish your content to Facebook and Twitter, Buddy Media is the right tool. For listening and responding to conversations and monitoring what people are saying about you, Radian 6 is the way to go.


text:
Q: Не работает графика
The method drawLine(int,int,int,int) is undefined for the type Graphics

Раньше работав код)Сейчас нет.Вроде все верно...

A: У вас в проекте уже есть класс Graphics.Соответственно, в нём нет нужного вам метода.В таком случае вам стоит явно указать путь к классу Graphics, то есть прописать java.awt.Graphics.Итого, сигнатура вашего метода должна выглядеть примерно вот так: public void paint(java.awt.Graphics g)

A: Ошибка говорит нам, что у вас в классе Graphics отсутствует метод drawLine(int,int,int,int)
Но я, так же, не вижу в самом верху строки
import Graphics;


text:
Q: Prevent Windows command-interpreter (FOR) from treating list as wildcards? I am trying to write a batch file that takes a couple of arguments, followed by one or more optional filenames (which may include wildcards) and at some point processes each one of the optional filenames, but the for command keeps trying to expand them, so even so much as just printing them won't work.
I checked the help (for /?), but there does not seem to be any switches to prevent this. I tried using single, double, and back-quotes as well as /f, but nothing seems to work.
The following command works as one would expect:
> for %i in (foo bar baz) do @echo %i
foo
bar
baz

The following command does not:
> for %i in (foo bar baz really?) do @echo %i
foo
bar
baz

The following, even less so:
> ren > reallyz
The syntax of the command is incorrect.

> dir /b really*
reallyz

> for %i in (foo bar baz really?) do @echo %i
foo
bar
baz
reallyz

Is there a way to get the Windows command-interpreter to treat the passed list as strings and not try to interpret it as filename wildcards?

A: No - the simple FOR command will always expand the * and ? wild card characters.
You need to use a GOTO loop to do what you want. The SHIFT command enables access to all parameters.
@echo off
:argLoop
if "%~1" neq "" (
  echo %1
  shift /1
  goto :argLoop
)

Most likely you want to do more with the arguments then just print them. Typically you would store them in an "array" of variables for later use.
@echo off
setlocal

set argCnt=1
:argLoop
if "%~1" neq "" (
  set "arg.%argCnt%=%~1"
  set /a argCnt+=1
  shift /1
  goto :argLoop
)
set /a argCnt-=1

:: Show Args
setlocal enableDelayedExpansion
for /l %%N in (1 1 %argCnt%) do echo arg.%%N = !arg.%%N!


text:
Q: Usage of 'just so' There was this dialog in Don Delillo's Cosmopolis which puzzled me:
(A little context, the main character Eric talks to his female bodyguard Kendra, who he had sex with just before, Torval is Eric's chief of security.)

"What's he going to say to you about this?"
"Torval?  Is that who you're talking about?'  She was amused.  "Say
  his name."
"What's he going to say to you?"
"Just so you're safe.  That's his job," she said.

I can't interpret the term 'just so' in this context, I was thinking that maybe she's continuing some speech she began earlier on, but that's surely not the case.
I'd understand the sentence 'just so you're safe' in the sense of
'Why did you do this to me?' - 'Just so you're safe.'
but I can't figure it out here.

A: It's just "shorthand" for "He (Torval) doesn't (or maybe has no right to) care what I do (what we do) just so long as we keep you safe. That's his only job: just to keep you safe."


text:
Q: BASH scripts : whiptail file select I've found a great little program that will allow me to add user friendly GUI's to my Bash Scripts;
whiptail
However the whiptail man page isn't all that helpful and doesn't provide any examples.  After doing some google searches I understand how to create a simple yes/no menu using whiptail:
#! /bin/bash
# http://archives.seul.org/seul/project/Feb-1998/msg00069.html
if (whiptail --title "PPP Configuration" --backtitle "Welcome to SEUL" --yesno "
Do you want to configure your PPP connection?"  10 40 )
then
        echo -e "\nWell, you better get busy!\n"
elif    (whiptail --title "PPP Configuration" --backtitle "Welcome to
SEUL" --yesno "           Are you sure?" 7 40)
        then
                echo -e "\nGood, because I can't do that yet!\n"
        else
                echo -e "\nToo bad, I can't do that yet\n"
fi

But what I would really like to build a file select menu using whiptail to replace some old code I have in a few different backup/restore bash scripts I have:
#!/bin/bash
#This script allows you to select a file ending in the .tgz extension (in the current directory)
echo "Please Select the RESTORE FILE you would like to restore: "
   select RESTOREFILE in *.tgz; do
   break #Nothing
   done
echo "The Restore File you selected was: ${RESTOREFILE}"

I assume this has to be done via the '--menu' option of whiptail, but I am not sure how to go about it?
Any pointers?
Or can you point me in the direction of some whiptail examples?

A: Whiptail is a lightweight reimplementation of the most popular features of dialog, using the Newt library.  I did a quick check, and many features in Whiptail seem to behave like their counterparts in dialog.  So, a dialog tutorial should get you started.  You can find one here but Google is your friend of course.  On the other hand, the extended example probably contains a lot of inspiration for your problem.

A: Build an array of file names and menu select tags:
i=0
s=65    # decimal ASCII "A"
for f in *.tgz
do
    # convert to octal then ASCII character for selection tag
    files[i]=$(echo -en "\0$(( $s / 64 * 100 + $s % 64 / 8 * 10 + $s % 8 ))")
    files[i+1]="$f"    # save file name
    ((i+=2))
    ((s++))
done

A method like this will work even if there are filenames with spaces. If the number of files is large, you may have to devise another tag strategy.
Using alpha characters for the tags lets you press a letter to jump to the item. Numeric tags don't seem to do that. If you don't need that behavior, then you can eliminate some complexity.
Display the menu:
whiptail --backtitle "Welcome to SEUL" --title "Restore Files" \
    --menu "Please select the file to restore" 14 40 6 "${files[@]}"

If the exit code is 255, the dialog was canceled.
if [[ $? == 255 ]]
then
    do cancel stuff
fi

To catch the selection in a variable, use this structure (substitute your whiptail command for "whiptail-command"):
result=$(whiptail-command 2>&1 >/dev/tty)

Or
result=$(whiptail-command 3>&2 2>&1 1>&3-)

The variable $result will contain a letter of the alphabet that corresponds to a file in the array. Unfortunately, Bash prior to version 4 doesn't support associative arrays. You can calculate the index into the array of the file from the letter like this (notice the "extra" single quote):
((index = 2 * ( $( printf "%d" "'$result" ) - 65 ) + 1 ))

Example:
Welcome to SEUL
                ┌──────────┤ Restore Files ├───────────┐
                │ Please select the file to restore    │
                │                                      │
                │            A one.tgz      ↑          │
                │            B two.tgz      ▮          │
                │            C three.tgz    ▒          │
                │            D another.tgz  ▒          │
                │            E more.tgz     ▒          │
                │            F sp ac es.tgz ↓          │
                │                                      │
                │                                      │
                │       <Ok>           <Cancel>        │
                │                                      │
                └──────────────────────────────────────┘

A: This function is part of my function repository for whiptail
# ----------------------------------------------------------------------
#  File selection dialog
#
#  Arguments
#     1  Dialog title
#     2  Source path to list files and directories
#     3  File mask (by default *)
#     4  "yes" to allow go back in the file system.
#
#  Returns
#     0  if a file was selected and loads the FILE_SELECTED variable
#        with the selected file.
#     1  if the user cancels.
# ----------------------------------------------------------------------
function dr_file_select
{
    local TITLE=${1:-$MSG_INFO_TITLE}
    local LOCAL_PATH=${2:-$(pwd)}
    local FILE_MASK=${3:-"*"}
    local ALLOW_BACK=${4:-no}
    local FILES=()

    [ "$ALLOW_BACK" != "no" ] && FILES+=(".." "..")

    # First add folders
    for DIR in $(find $LOCAL_PATH -maxdepth 1 -mindepth 1 -type d -printf "%f " 2> /dev/null)
    do
        FILES+=($DIR "folder")
    done

    # Then add the files
    for FILE in $(find $LOCAL_PATH -maxdepth 1 -type f -name "$FILE_MASK" -printf "%f %s " 2> /dev/null)
    do
        FILES+=($FILE)
    done

    while true
    do
        FILE_SELECTED=$(whiptail --clear --backtitle "$BACK_TITLE" --title "$TITLE" --menu "$LOCAL_PATH" 38 80 30 ${FILES[@]} 3>&1 1>&2 2>&3)

        if [ -z "$FILE_SELECTED" ]; then
            return 1
        else
            if [ "$FILE_SELECTED" = ".." ] && [ "$ALLOW_BACK" != "no" ]; then
                return 0

            elif [ -d "$LOCAL_PATH/$FILE_SELECTED" ] ; then
                if dr_file_select "$TITLE" "$LOCAL_PATH/$FILE_SELECTED" "$FILE_MASK" "yes" ; then
                    if [ "$FILE_SELECTED" != ".." ]; then
                        return 0
                    fi
                else
                    return 1
                fi

            elif [ -f "$LOCAL_PATH/$FILE_SELECTED" ] ; then
                FILE_SELECTED="$LOCAL_PATH/$FILE_SELECTED"
                return 0
            fi
        fi
    done
}

The use is simple
if dr_file_select "Please, select a file" /home/user ; then
        echo "File Selected: \"$FILE_SELECTED\"."
else
        echo "Cancelled!"
fi

A: I've tried following, which worked:
whiptail --title "PPP Config" --backtitle "Welcome to SEUL" --menu YourTitle 20 80 10 `for x in $(ls -1 *.tgz); do echo $x "-"; done`

you might change this into a multiple-liner as well, i've added checking for empty list:
MYLIST=`for x in $(ls -1 *.tgz); do echo $x "-"; done`
WC=`echo $MYLIST | wc -l`

if [[WC -ne 0]]; then
    whiptail --title "PPP Config" --backtitle "Welcome to SEUL" --menu YourTitle 20 80 10 $MYLIST
fi

you need to adjust the numbers in order to get a cleaninterface. And you may replace the "-" by anything else if you want to. But if you don't, you will see 2 entries per line.
By the way: The selected entry is printed onto stderr.
This could need some more improving, but for a basic idea I think it's enough.

A: This seems to be one of the top results when you search for whiptail, and none of the previous results worked for me.  This is what I wound up using:
#! /bin/bash
shopt -s nullglob
dir=`pwd`
cd /path/to/files
arr=(*.tgz)
for ((i=0; i<${#arr[@]}; i++)); do j=$((2*$i+2)); a[j]="${arr[$i]}"; a[j+1]=""; done
a[0]=""
# Next line has extra spaces at right to try to center it:
a[1]="Please make a selection from the files below                                                        "
result=$(whiptail --ok-button "OK button text" --cancel-button "Cancel Button Text" --title "Title Text" --backtitle "Text at upper left corner of page" --menu "Menu Text (not used??)" 30 160 24 "${a[@]}" 2>&1 >/dev/tty)
if [[ $? = 0 ]]
then
# ge 5 in next line should be length of file extension including . character, plus 1
  [ ${#result} -ge 5 ] && outfile="/path/to/files/$result" || echo "Selection not made"
fi
cd "$dir"

$result will be empty if no valid selection was made.  I added a dummy selection at the top of the list that returns an empty string as a result, so that you won't accidentally select the wrong file by accidentally hitting Enter right after the menu comes up.  If you don't want that, then in the "for" line remove the +2 in "do j=$((2*$i+2))" and also the following two lines that set a[0] and a[1] explicitly.
The confusing thing about whiptail is that when reading from an array in a situation like this it expects two data items per line, both of which are displayed, the first being the result you want returned if the line is expected (which in some situations might be a letter or a number) and the second being whatever descriptive text you may want.  That's why for the first line I use a[0] to give an empty string as the result, and a[1] as the descriptive text, but from there on the first item in the pair contains the filename (which is what I actually want returned) and the second is an empty string, since I don't want to display any text other than the filename on those lines.
Also a previous post said whiptail returned an error code of 255 if the cancel button was pressed, but that was not the case for the version I have - it returns 1.  So I just test for an error code of 0 and if it is I assume it may be a valid entry, then I test for a valid string length (more than just the number of characters in the file extension, including the . character) to be sure.


text:
Q: How to filter by a condition on a given level in a Pandas Multiindex Suppose df is the following multi-indexed dataframe:
letter      date        number
x           2021-01-01  0             0
                        1             1
            2021-01-02  0             2
                        1             3
            2021-01-04  0             4
                        1             5
y           2021-02-07  0             6
                        1             7
            2021-02-09  0             8
                        1             9

For each letter, I wish to select only those rows where the date is no more than 2 days after the first.
For x, the first date is 2021-01-01, so all the rows where the date is after 2021-01-03 should be removed.
For y, the first date is 2021-02-07, so all the rows where the date is after 2021-01-09 should be removed.
The desired outcome would be:
letter      date        number
x           2021-01-01  0             0
                        1             1
            2021-01-02  0             2
                        1             3
y           2021-02-07  0             6
                        1             7

What's the best way to do this?

A: That actually looks like a series, so can create a boolean index with groupby transform and filter dates that are less than 2 days from the first value:
df = df[
    df.reset_index('date')
        .groupby('letter')['date']
        .transform(lambda x: x < (x.iat[0] + pd.Timedelta(days=2))).values
]

letter  date        number
x       2021-01-01  0         0
                    1         1
        2021-01-02  0         2
                    1         3
y       2021-02-07  0         6
                    1         7
dtype: int64

For each group, transform date column into boolean values based on the comparison to min date offset by 2 days.
df.reset_index('date')
    .groupby('letter')['date']
    .transform(lambda x: x < (x.iat[0] + pd.Timedelta(days=2)))

Filter:
0     True
1     True
2     True
3     True
4    False
5    False
6     True
7     True
8    False
9    False
Name: date, dtype: bool

Can also use min to get distance from earliest date regardless of order:
df = df[
    df.reset_index('date')
        .groupby('letter')['date']
        .transform(lambda x: x < (x.min() + pd.Timedelta(days=2))).values
]

Series/df creation code:
import pandas as pd

df = pd.DataFrame({
    'letter': ['x', 'x', 'x', 'x', 'x', 'x', 'y', 'y', 'y', 'y'],
    'date': pd.to_datetime(['2021-01-01', '2021-01-01', '2021-01-02',
                            '2021-01-02', '2021-01-04', '2021-01-04',
                            '2021-02-07', '2021-02-07', '2021-02-09',
                            '2021-02-09']),
    'number': [0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
    'value': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}).set_index(['letter', 'date', 'number']).squeeze().rename(None)


text:
Q: SQL expression to select specific month across years What is the ArcGIS SQL expression to select all rows containing the month of May across several years?
Desired records highlighted in Excel:

The source table is in a file geodatabase and I'm using ArcGIS Pro v2.2.4.
Attempts so far
I tried using the wildcard characters for strings listed in the Pro SQL reference but they (unsurprisingly) yield "invalid syntax" error:
SAMPLE_DATE = date '%-05-%'
SAMPLE_DATE = date '__-02-__'

KB article How To: Search for specific parts of a date stored in a Date-Time field offers EXTRACT(MONTH ...) = nn but that returns zero records.
EXTRACT(MONTH FROM SAMPLE_DATE) = 05

A: The KB article is correct, and so is the warning message after a fashion: In the Definition Query box the expression is run against the results of the preceding expression in effect when the tool was opened or last verified.
I had been entering a series of expressions one after the other narrowing in on the right solution. After clearing the expression, closing the dialog and then re-opening Definition Query I get the expected results. (Note: there is a 1 to 3 second pause after closing the dialog to when the table view is updated.)


text:
Q: Angular Firestore Valuechanges get document reference I'm using Angular with google cloud firestore to load data.
I also have a model class, let's call it IMyModel
export interface IMyModel{
    data: any;
    id: string;
}

of which the id is the id of the document on firestore. I can easily load this through
var docs = this.firestore.collection('myCollection').valueChanges({ idField: 'id' }) as Observable<IMyModel[]>; This neatly works.
But now, I also want this functionality with the document reference. Lets's say I alter the model
export interface IMyModel{
    data: any;
    documentReference: DocumentReference;
}

How can I now insert the documentReference field? I already tried
var docs = this.firestore.collection('myCollection').valueChanges({ ref: 'documentReference',  }) as Observable<IMyModel[]>;
But this does not insert the field.

A: valueChanges() gives you an observable. You can do .pipe(map(items => items.map(item => yourFunction(item)))) to transform the data to your liking:
interface IMyModel {
  data: any;
  ref: DocumentReference;
}
const myCollection = this.firestore.collection<{ data: any }>('myCollection');
const itemsWithId$ = myCollection.valueChanges({ idField: 'id' });
const itemsWithRef$: Observable<IMyModel[]> = itemsWithId$.pipe(
  map(itemsWithId => {
    return itemsWithId.map(item => {
      return {
        data: item.data,
        ref: myCollection.doc(item.id).ref,
      };
    });
  }),
);

A: Can you please try with this solution?
export interface Item { id: string; name: string; }
@Component({
  selector: 'app-root',
  template: `
    <ul>
      <li *ngFor="let item of items | async">
        {{ item.name }}
      </li>
    </ul>
  `
})
export class AppComponent {
  private itemsCollection: AngularFirestoreCollection<Item>;
  items: Observable<Item[]>;
  constructor(private readonly afs: AngularFirestore) {
    this.itemsCollection = afs.collection<Item>('items');
    // .valueChanges() is simple. It just returns the
    // JSON data without metadata. If you need the
    // doc.id() in the value you must persist it your self
    // or use .snapshotChanges() instead. See the addItem()
    // method below for how to persist the id with
    // valueChanges()
    this.items = this.itemsCollection.valueChanges();
  }
}

For more reference please refer this link.