问:
How do I work with an array object in PHP?
I have a Laravel site I am modifying, but there are some parts of the PHP code I don't quite understand, which are "array objects" or "object arrays". You see, I don't even know what to call them and so can't find a tutorial or basic data on it. Below is the code that I am dealing with:

```<code> private function parseMetric($result, $view)
    {
        $data = collect([]);

        $result->each(function($item) use ($data, $view) {
            if (isset($item->metric->{$view})) {
                $data->push((object)[
                    'label' => $item->metric->{$view},
                    'value' => $item->metric->count
                ]);
            }
        });
...
</code>```

From what I can tell, this creates an object out of $result. If I json_encode this and echo it out I get this:

```<code> [{"label":"1k-25k","value":14229},
{"label":"1mm+","value":1281},
{"label":"25k-50k","value":398},
{"label":"50k-75k","value":493},
{"label":"75k-100k","value":3848},
{"label":"100k-150k","value":9921},
{"label":"150k-200k","value":4949},
{"label":"200k-250k","value":3883},
{"label":"250k-300k","value":2685},
{"label":"300k-350k","value":2744},
{"label":"350k-500k","value":4526},
{"label":"500k-1mm","value":8690}]

</code>```

Now this is obviously an array of arrays... or is it? Is it an array of objects? Or is it an object containing arrays? But the most important question is, how do I access and move or change the individual objects/arrays in this object? For example, I want to take the second object/array, which is:

```<code>{"label":"1mm+","value":1281}
</code>```

and move it to the end. How do I do that? How do I find it? I used the following piece of code to find it which is pretty clunky:

```<code>$pos = strpos(json_encode($result), '1mm+');
        if($pos){
            Log::debug('Enrich 73, I found it!!!!!!!!!!!!!!!!!!!!!!!!!!!');
        }
</code>```

And once I find it, how do I move that array/object to the end of the whole object?

And finally, where can I find some kind of tutorial, or documentation, that describes this construct and how to work with it?

答:
Acording to Laravel documnentation for Collections, you can try something like this :

To find index of element with name = "1mm+" :

```<code>$index = $datas->search(function ($item, $key) {
    return $item['name'] == "1mm+";
});
</code>```

to get an element at a given index :
$element = $datas->get($index);

to Move element at index 3 to the end :

```<code>$index = 3
$elementToMove = $data->splice($index, 1);
$datas->push($elementToMove);
</code>```

Here is a link to the document used : https://laravel.com/docs/8.x/collections

Body:
I have a Laravel site I am modifying, but there are some parts of the PHP code I don't quite understand, which are "array objects" or "object arrays". You see, I don't even know what to call them and so can't find a tutorial or basic data on it. Below is the code that I am dealing with:

 private function parseMetric($result, $view)
    {
        $data = collect([]);

        $result->each(function($item) use ($data, $view) {
            if (isset($item->metric->{$view})) {
                $data->push((object)[
                    'label' => $item->metric->{$view},
                    'value' => $item->metric->count
                ]);
            }
        });
...

From what I can tell, this creates an object out of $result. If I json_encode this and echo it out I get this:

 [{"label":"1k-25k","value":14229},
{"label":"1mm+","value":1281},
{"label":"25k-50k","value":398},
{"label":"50k-75k","value":493},
{"label":"75k-100k","value":3848},
{"label":"100k-150k","value":9921},
{"label":"150k-200k","value":4949},
{"label":"200k-250k","value":3883},
{"label":"250k-300k","value":2685},
{"label":"300k-350k","value":2744},
{"label":"350k-500k","value":4526},
{"label":"500k-1mm","value":8690}]

Now this is obviously an array of arrays... or is it? Is it an array of objects? Or is it an object containing arrays? But the most important question is, how do I access and move or change the individual objects/arrays in this object? For example, I want to take the second object/array, which is:

{"label":"1mm+","value":1281}

and move it to the end. How do I do that? How do I find it? I used the following piece of code to find it which is pretty clunky:

$pos = strpos(json_encode($result), '1mm+');
        if($pos){
            Log::debug('Enrich 73, I found it!!!!!!!!!!!!!!!!!!!!!!!!!!!');
        }

And once I find it, how do I move that array/object to the end of the whole object?

And finally, where can I find some kind of tutorial, or documentation, that describes this construct and how to work with it?

Body:
Acording to Laravel documnentation for Collections, you can try something like this :

To find index of element with name = "1mm+" :

$index = $datas->search(function ($item, $key) {
    return $item['name'] == "1mm+";
});

to get an element at a given index :
$element = $datas->get($index);

to Move element at index 3 to the end :

$index = 3
$elementToMove = $data->splice($index, 1);
$datas->push($elementToMove);

Here is a link to the document used : https://laravel.com/docs/8.x/collections


来源: stackexchange

问:
Angular Universal trying to open app.component.html
I've recently upgraded my Angular and I've had some problems with server-side rendering. I've had some issues which I've managed to fix but I've gotten stuck on the following error:

```<code>Error: ENOENT: no such file or directory, open 'app.component.html'
</code>```

I wasn't able to find somebody else facing the exact same issue, most of the problems similar to this one I came across were caused by a badly written path. I believe that there might be a problem with my configuration as I don't see app.component.hmtl appear in my compiled dist/app-admin-browsr folder, nor do I see it in the universal example project that I have downloaded.

Has anyone face this issue before?

server.ts

```<code>// generated by @ng-toolkit/serverless
import 'zone.js/node';
import 'reflect-metadata';
import {enableProdMode, ValueProvider} from '@angular/core';
import {ngExpressEngine} from '@nguniversal/express-engine';
import { APP_BASE_HREF } from '@angular/common';

import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as cors from 'cors';
import * as compression from 'compression';

import {join} from 'path';

enableProdMode();

export const app = express();

const DIST_FOLDER = join(process.cwd(), 'dist');

app.use(compression());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

const appServer = process.env.APP === 'admin' ? 'app-admin-server' : 'app-server';
const appBrowser = process.env.APP === 'admin' ? 'app-admin-browser' : 'app-browser';

/*const fs = require("fs");
const path = require("path");
const template = join(appBrowser, 'index.html');
const domino = require("domino");
const templateA = fs
  .readFileSync(path.join(DIST_FOLDER, appBrowser, 'index.html'))
  .toString();
const win = domino.createWindow(templateA);

global["window"] = win;
global["document"] = win.document;
global["branch"] = null;
global["object"] = win.object;
global['UIEvent'] = win.UIEvent;
global['HTMLElement'] = win.HTMLElement;
global['navigator'] = win.navigator;*/

const {ServerAppModuleNgFactory, LAZY_MODULE_MAP} =.
require('./dist/'+appServer+'/main');
// const server = require('./dist/app-server/main');
// console.log(server);
import {ServerAppModule} from './src/app-admin/app/server.app.module';
 app.engine('html', (_, options, callback) => {
  console.log(appBrowser);
  console.log(join(DIST_FOLDER, appBrowser, 'index.html'));
  const engine = ngExpressEngine({
  bootstrap: ServerAppModule,
  });
  engine(_, options, callback);
});
app.set('view engine', 'html');

app.set('views', join(DIST_FOLDER, appBrowser));

app.get('*.*', express.static(join(DIST_FOLDER, appBrowser)));

app.get('*', (req, res) => {
  res.render(join(DIST_FOLDER, appBrowser, 'index.html'), {req, res});
});

// app.get('/api.*', (req, res) => {
//   res.status(404).send('data requests are not supported');
// });
</code>```

答:
I was facing the same issue while upgrading to Angular 9. I got my issue resolved by using command node server/main.js instead of node server.js.

You can modify script in your package.json file.

ContentLicense: CC BY-SA 4.0

Body:
I've recently upgraded my Angular and I've had some problems with server-side rendering. I've had some issues which I've managed to fix but I've gotten stuck on the following error:

Error: ENOENT: no such file or directory, open 'app.component.html'

I wasn't able to find somebody else facing the exact same issue, most of the problems similar to this one I came across were caused by a badly written path. I believe that there might be a problem with my configuration as I don't see app.component.hmtl appear in my compiled dist/app-admin-browsr folder, nor do I see it in the universal example project that I have downloaded.

Has anyone face this issue before?

server.ts

// generated by @ng-toolkit/serverless
import 'zone.js/node';
import 'reflect-metadata';
import {enableProdMode, ValueProvider} from '@angular/core';
import {ngExpressEngine} from '@nguniversal/express-engine';
import { APP_BASE_HREF } from '@angular/common';

import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as cors from 'cors';
import * as compression from 'compression';

import {join} from 'path';

enableProdMode();

export const app = express();

const DIST_FOLDER = join(process.cwd(), 'dist');

app.use(compression());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

const appServer = process.env.APP === 'admin' ? 'app-admin-server' : 'app-server';
const appBrowser = process.env.APP === 'admin' ? 'app-admin-browser' : 'app-browser';

/*const fs = require("fs");
const path = require("path");
const template = join(appBrowser, 'index.html');
const domino = require("domino");
const templateA = fs
  .readFileSync(path.join(DIST_FOLDER, appBrowser, 'index.html'))
  .toString();
const win = domino.createWindow(templateA);

global["window"] = win;
global["document"] = win.document;
global["branch"] = null;
global["object"] = win.object;
global['UIEvent'] = win.UIEvent;
global['HTMLElement'] = win.HTMLElement;
global['navigator'] = win.navigator;*/

const {ServerAppModuleNgFactory, LAZY_MODULE_MAP} =.
require('./dist/'+appServer+'/main');
// const server = require('./dist/app-server/main');
// console.log(server);
import {ServerAppModule} from './src/app-admin/app/server.app.module';
 app.engine('html', (_, options, callback) => {
  console.log(appBrowser);
  console.log(join(DIST_FOLDER, appBrowser, 'index.html'));
  const engine = ngExpressEngine({
  bootstrap: ServerAppModule,
  });
  engine(_, options, callback);
});
app.set('view engine', 'html');

app.set('views', join(DIST_FOLDER, appBrowser));

app.get('*.*', express.static(join(DIST_FOLDER, appBrowser)));

app.get('*', (req, res) => {
  res.render(join(DIST_FOLDER, appBrowser, 'index.html'), {req, res});
});

// app.get('/api.*', (req, res) => {
//   res.status(404).send('data requests are not supported');
// });


问:
Accessing vector of objects C++
Say I store a vector of objects. The object has an attribute such as int age which is private and we need to access it via getAge().

Lets say we call the object "people"

I store the object "people" in a vector...
soo...

```<code> vector<people> vectorOfPeople
</code>```

My question is...
Is it possible to directly access the 'age' via the vector vectorOfPeople?
Maybe something like vectorOfPeople[0].getAge() or something... (I know that doesn't work).

Thanks!

答:
The std::vector has operators:

```<code>reference operator[] ( size_type n );
const_reference operator[] ( size_type n ) const;
</code>```

They,

Return a reference to the element at position n in the vector container.

So, vectorOfPeople[0] would return a reference to the element at 0th position in the vector container and then getAge() will be called on that reference object.

It is nothing different than,

```<code>people obj;
obj.getAge();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Accessing vector of objects C++

Body:
Say I store a vector of objects. The object has an attribute such as int age which is private and we need to access it via getAge().

Lets say we call the object "people"

I store the object "people" in a vector...
soo...

 vector<people> vectorOfPeople

My question is...
Is it possible to directly access the 'age' via the vector vectorOfPeople?
Maybe something like vectorOfPeople[0].getAge() or something... (I know that doesn't work).

Thanks!

Body:
The std::vector has operators:

reference operator[] ( size_type n );
const_reference operator[] ( size_type n ) const;

They,

Return a reference to the element at position n in the vector container.

So, vectorOfPeople[0] would return a reference to the element at 0th position in the vector container and then getAge() will be called on that reference object.

It is nothing different than,

people obj;
obj.getAge();


问:
Aggregate initialization of a derived class with designator
From cppreference we can know:

Since C++17 for derived types:

If the initializer clause is a nested braced-init-list (which is not an expression), the corresponding array element/class member /public base (since C++17) is list-initialized from that clause: aggregate initialization is recursive.

Since C++20 for aggregate types:

Using .designator = arg to specify initialized members is no longer an extension to C, but is supported by the C++ standard.

struct A
{
    int a;
    int b;
};

struct B : A
{
    int c;
};

void test()
{
    A a{.a = 1, .b = 42}; // a.a = 1 && a.b = 42
    B b{{.a = 1, .b = 2}, 42}; // b.a = 1 && b.b = 2 && b.c = 42
}
```
<p>Very simple and intuitive, right?</p>
<p>But let's complicate things a bit.</p>
<pre class="lang-cpp prettyprint-override"><code>constexpr int a_very_very_special_value = 42;

struct A
{
    int a;
    int b;
};

struct B : A
{
    int c = a_very_very_special_value;
    int d;
};

void test()
{
    A a{.a = 1, .b = 42}; // a.a = 1 && a.b = 42
    B b{{.a = 1, .b = 2}, .d = 9}; // Ouch! Mixture of designated and non-designated initializers in the same initializer list is a C99 extension.
}
</code>```

The above situation should be very common, we want a member data to keep its default value, but the standard requires us that .designator = arg must be after all parameters without .designator, but, this is impossible, how do we give our base a name? Like .base_type_name = {.a = 1, .b = 2}?

One might think that things like inheritance are totally unnecessary, we can do it like this.

struct A
{
    int a;
    int b;
};

struct B
{
    A base;
    int c = a_very_very_special_value;
    int d;
};

void test()
{
    A a{.a = 1, .b = 42}; // a.a = 1 && a.b = 42
    B b{.base = {.a = 1, .b = 2}, .d = 9}; // b.base.a = 1 && b.base.b = 2 && b.c = a_very_very_special_value && b.d = 9
}
```
<p>Great, what else is unsatisfactory? Unless we have an interface like this.</p>
<pre class="lang-cpp prettyprint-override"><code>void test(A &a)
{
    if (a.a + a.b > 42) {
        std::cout << "42\n";
    }
    else {
        std::cout << "0\n";
    }
}

void test()
{
    A a{.a = 1, .b = 42};
    B b{.base = {.a = 1, .b = 2}, .d = 9};

    test(a);
    test(b); // No matching function for call to 'test'
}
</code>```

Those who are familiar with the memory model will definitely think that it is very simple, just add a forced type cast, anyway, the data of the original base class is in the head of the data.

void test()
{
    A a{.a = 1, .b = 42};
    B b{.base = {.a = 1, .b = 2}, .d = 9};

    test(a);
//  test(b);
    test((A&)b);
}
```

However, one very important thing is that C++ supports multiple inheritance. If our original design idea is to form a complete type by inheriting multiple structures, what should we do?

Further, if our interface is separate for each inherited type, then we need to give a type cast method for all base classes, and also know the offset of the data in the type, if the data from the base class is not completely placed at the head of the class, the result will absolutely be wrong.

答:
As you've discovered, you can't use both designated initialization and also name the base class. In order to do that, the language needs to be extended to support that case. See P2287R1, which I have not finished yet. Unfortunately, won't make C++23.

Until the language directly supports designated the base class (or directly designated members of the base class), if you want to use designated initializers your best bet is to have the base classes as members, as you've clearly documented.

Body:
From cppreference we can know:

Since C++17 for derived types:

If the initializer clause is a nested braced-init-list (which is not an expression), the corresponding array element/class member /public base (since C++17) is list-initialized from that clause: aggregate initialization is recursive.

Since C++20 for aggregate types:

Using .designator = arg to specify initialized members is no longer an extension to C, but is supported by the C++ standard.

struct A
{
    int a;
    int b;
};

struct B : A
{
    int c;
};

void test()
{
    A a{.a = 1, .b = 42}; // a.a = 1 && a.b = 42
    B b{{.a = 1, .b = 2}, 42}; // b.a = 1 && b.b = 2 && b.c = 42
}

Very simple and intuitive, right?

But let's complicate things a bit.

constexpr int a_very_very_special_value = 42;

struct A
{
    int a;
    int b;
};

struct B : A
{
    int c = a_very_very_special_value;
    int d;
};

void test()
{
    A a{.a = 1, .b = 42}; // a.a = 1 && a.b = 42
    B b{{.a = 1, .b = 2}, .d = 9}; // Ouch! Mixture of designated and non-designated initializers in the same initializer list is a C99 extension.
}

The above situation should be very common, we want a member data to keep its default value, but the standard requires us that .designator = arg must be after all parameters without .designator, but, this is impossible, how do we give our base a name? Like .base_type_name = {.a = 1, .b = 2}?

One might think that things like inheritance are totally unnecessary, we can do it like this.

struct A
{
    int a;
    int b;
};

struct B
{
    A base;
    int c = a_very_very_special_value;
    int d;
};

void test()
{
    A a{.a = 1, .b = 42}; // a.a = 1 && a.b = 42
    B b{.base = {.a = 1, .b = 2}, .d = 9}; // b.base.a = 1 && b.base.b = 2 && b.c = a_very_very_special_value && b.d = 9
}

Great, what else is unsatisfactory? Unless we have an interface like this.

void test(A &a)
{
    if (a.a + a.b > 42) {
        std::cout << "42\n";
    }
    else {
        std::cout << "0\n";
    }
}

void test()
{
    A a{.a = 1, .b = 42};
    B b{.base = {.a = 1, .b = 2}, .d = 9};

    test(a);
    test(b); // No matching function for call to 'test'
}

Those who are familiar with the memory model will definitely think that it is very simple, just add a forced type cast, anyway, the data of the original base class is in the head of the data.

void test()
{
    A a{.a = 1, .b = 42};
    B b{.base = {.a = 1, .b = 2}, .d = 9};

    test(a);
//  test(b);
    test((A&)b);
}

However, one very important thing is that C++ supports multiple inheritance. If our original design idea is to form a complete type by inheriting multiple structures, what should we do?

Further, if our interface is separate for each inherited type, then we need to give a type cast method for all base classes, and also know the offset of the data in the type, if the data from the base class is not completely placed at the head of the class, the result will absolutely be wrong.


问:
Undefined behavior of printf in C?
What should be the output of a single percent sign?

```<code>#include <stdio.h>

void main()
{
    printf("%");
}
</code>```

"Unknown format code" is not like "Unknown escape sequence".

答:
What you're doing is undefined behavior.

Section 7.21.6.1p9 of the C standard regarding format specifiers for fprintf (and by extension printf) states:

If a conversion specification is invalid, the behavior is undefined.  If any argument is
not the correct type for the corresponding conversion specification, the behavior is
undefined.

Also, gcc will generate a warning with -Wall if you do this:

warning: spurious trailing ‘%’ in format [-Wformat=]
```
<p>The correct way to print a <code>%</code> character is with the format specifier <code>%%</code>.</p>
```printf("%%");
```

Title: Undefined behavior of printf in C?

Body:
What should be the output of a single percent sign?

#include <stdio.h>

void main()
{
    printf("%");
}

"Unknown format code" is not like "Unknown escape sequence".

Body:
What you're doing is undefined behavior.

Section 7.21.6.1p9 of the C standard regarding format specifiers for fprintf (and by extension printf) states:

If a conversion specification is invalid, the behavior is undefined.  If any argument is
not the correct type for the corresponding conversion specification, the behavior is
undefined.

Also, gcc will generate a warning with -Wall if you do this:

warning: spurious trailing ‘%’ in format [-Wformat=]

The correct way to print a % character is with the format specifier %%.

printf("%%");


问:
Unrecognized VM option 'MaxPermSize=512m' Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit
I updated my IDE to Android Studio Arctic Fox version and was facing this issue when I tried to sync gradle after the upgrade was complete:

"Unrecognized VM option 'MaxPermSize=512m' Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit."

I checked my java version, which was Java 17. I deleted my .gradle directory which didn't help. Reversed the gradle.properties changes made by the update. It didn't work either. I looked for maxPermSize value in my vm.studiooptions file. It wasn't there as suggested in some stackoverflow already asked questions.

Sharing the fix for this below.

答:
In your Android studio go to File--> settings-->(Build, Execution, Deployment)--->Build Tools---> Gradle.

Inside Gradle settings choose Embedded JDK.

Here's a screenshort


问:
Secure WebApp in Wildfly 25 using OpenID Connect (OIDC) without installing a Keycloak client adapter
My Webapp is deployed in Wildfly 25.0.1.Final and is secured using OpenID Connect (OIDC).
WildFly 25 enables you to secure deployments using OpenID Connect (OIDC) without installing a Keycloak client adapter.

It is configured like this:

web.xml

```<code><login-config>
     <auth-method>OIDC</auth-method>
</login-config>
</code>```

OIDC.json

```<code>{
   "provider-url": "${auth.server.url}",
   "ssl-required": "external",
   "client-id": "myClient",
   "public-client": true,
   "confidential-port": 0
}
</code>```

described here:
http://www.mastertheboss.com/jbossas/jboss-security/secure-wildfly-applications-with-openid-connect/

Everything works fine.
My WebApp is secured, it redirects to keycloak for authorization and keycloak sends the tokens to my webapp.
But, on each request in my Webapp the Wildflyserver sends about 100 requests to the keycloak Server for loading metadata from OpenID provider.

```<code>13:33:38,405 INFO  [org.wildfly.security.http.oidc] (default task-3) ELY23004: Loaded OpenID provider metadata from 'http://keycloakserver:8180/auth/realms/myRealm/.well-known/openid-configuration'
...
...
13:33:39,480 INFO  [org.wildfly.security.http.oidc] (default task-3) ELY23004: Loaded OpenID provider metadata from 'http://keycloakserver:8180/auth/realms/myRealm/.well-known/openid-configuration'
</code>```

This coudn't be correct, the performance couldn't be sufficient.

In Wildfly 23 (with Keycloak adapter) I didn't see this messages!

Anyone with same experience?
Thanks!

答:
This is a known issue and documented here:  https://issues.redhat.com/browse/ELY-2284

If you upgrade to wildfly 26.0.1 it should be resolved.

Body:
My Webapp is deployed in Wildfly 25.0.1.Final and is secured using OpenID Connect (OIDC).
WildFly 25 enables you to secure deployments using OpenID Connect (OIDC) without installing a Keycloak client adapter.

It is configured like this:

web.xml

<login-config>
     <auth-method>OIDC</auth-method>
</login-config>

OIDC.json

{
   "provider-url": "${auth.server.url}",
   "ssl-required": "external",
   "client-id": "myClient",
   "public-client": true,
   "confidential-port": 0
}

described here:
http://www.mastertheboss.com/jbossas/jboss-security/secure-wildfly-applications-with-openid-connect/

Everything works fine.
My WebApp is secured, it redirects to keycloak for authorization and keycloak sends the tokens to my webapp.
But, on each request in my Webapp the Wildflyserver sends about 100 requests to the keycloak Server for loading metadata from OpenID provider.

13:33:38,405 INFO  [org.wildfly.security.http.oidc] (default task-3) ELY23004: Loaded OpenID provider metadata from 'http://keycloakserver:8180/auth/realms/myRealm/.well-known/openid-configuration'
...
...
13:33:39,480 INFO  [org.wildfly.security.http.oidc] (default task-3) ELY23004: Loaded OpenID provider metadata from 'http://keycloakserver:8180/auth/realms/myRealm/.well-known/openid-configuration'

This coudn't be correct, the performance couldn't be sufficient.

In Wildfly 23 (with Keycloak adapter) I didn't see this messages!

Anyone with same experience?
Thanks!


问:
how can I set background to react native animated view

Issue Description

I want to change background color right after rendering component but interpolate but actual output is Error: Style property 'backgroundColor' is not supported by native animated module

Codes

```<code>import React, {useEffect, useRef} from 'react';
import {Animated} from 'react-native';

export default function Welcome(props) {
  const translation = useRef(new Animated.Value(0)).current;
  useEffect(() => {
    Animated.timing(translation, {
      toValue: 0,
      duration: 1000,
      useNativeDriver: true,
    }).start();
  }, []);
  const styles = {
    flex: 1,
    backgroundColor: translation.interpolate({
      inputRange: [0, 100],
      outputRange: ['orange', 'blue'],
    }),
    opacity: translation.interpolate({
      inputRange: [25, 50, 100],
      outputRange: [0, 1, 0],
      extrapolate: 'clamp',
    }),
    transform: [
      {translateX: translation},
      {
        rotate: translation.interpolate({
          inputRange: [0, 100],
          outputRange: ['0deg', '360deg'],
        }),
      },
    ],
  };
  return (
    <Animated.View style={styles}>
      <Animated.Text style={{color:'tomato'}}>Credex</Animated.Text>
    </Animated.View>
  );
}
</code>```

答:
Solution

Firstly, I set useNativeDriver: false

Secondly, within use effect

```<code> Animated.timing(translation, {
     toValue: 100,
     duration: 1000,
     useNativeDriver: false,
   }).start()
</code>```

Finally I set height and width to the view

```<code>  const styles = {
    width: 300,
    height: 300,
    backgroundColor: translation.interpolate({
      inputRange: [0, 100],
      outputRange: ['orange', 'blue'],
    }),
    opacity: translation.interpolate({
      inputRange: [25, 50, 100],
      outputRange: [0, 1, 1],
      extrapolate: 'clamp',
    }),
    transform: [
      {translateY: translation},
      {
        rotate: translation.interpolate({
          inputRange: [0, 100],
          outputRange: ['0deg', '360deg'],
        }),
      },
    ],
  };
</code>```

for more you can refer to this post Here's or watch it at YouTube

Body:
Issue Description

I want to change background color right after rendering component but interpolate but actual output is Error: Style property 'backgroundColor' is not supported by native animated module

Codes

import React, {useEffect, useRef} from 'react';
import {Animated} from 'react-native';

export default function Welcome(props) {
  const translation = useRef(new Animated.Value(0)).current;
  useEffect(() => {
    Animated.timing(translation, {
      toValue: 0,
      duration: 1000,
      useNativeDriver: true,
    }).start();
  }, []);
  const styles = {
    flex: 1,
    backgroundColor: translation.interpolate({
      inputRange: [0, 100],
      outputRange: ['orange', 'blue'],
    }),
    opacity: translation.interpolate({
      inputRange: [25, 50, 100],
      outputRange: [0, 1, 0],
      extrapolate: 'clamp',
    }),
    transform: [
      {translateX: translation},
      {
        rotate: translation.interpolate({
          inputRange: [0, 100],
          outputRange: ['0deg', '360deg'],
        }),
      },
    ],
  };
  return (
    <Animated.View style={styles}>
      <Animated.Text style={{color:'tomato'}}>Credex</Animated.Text>
    </Animated.View>
  );
}

Body:
Solution

Firstly, I set useNativeDriver: false

Secondly, within use effect

 Animated.timing(translation, {
     toValue: 100,
     duration: 1000,
     useNativeDriver: false,
   }).start()

Finally I set height and width to the view

  const styles = {
    width: 300,
    height: 300,
    backgroundColor: translation.interpolate({
      inputRange: [0, 100],
      outputRange: ['orange', 'blue'],
    }),
    opacity: translation.interpolate({
      inputRange: [25, 50, 100],
      outputRange: [0, 1, 1],
      extrapolate: 'clamp',
    }),
    transform: [
      {translateY: translation},
      {
        rotate: translation.interpolate({
          inputRange: [0, 100],
          outputRange: ['0deg', '360deg'],
        }),
      },
    ],
  };

for more you can refer to this post Here's or watch it at YouTube


问:
Using new columns created from PARSENAME
I have split the column PointName using PARSENAME and created 2 new columns and I am needing now to use a WHERE clause to only pull the data for those 6 types.  Is there a way to do this?</p>
```<code>SELECT *, reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),2))as [Type] , reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),3))as [Point]
from RawAnalog RA
Where ra.PointName LIKE '%SKYLINE%'
      and ra.Point IN ('MaTmp', 'OaTmp', 'SaTmp', 'ChwVlv','SaStp', 'SaCFM')
</code>```

答:
Filling in the blanks a bit, but I would guess you could move the PARSENAME to the FROM and then you can filter more easily in the WHERE:

SELECT {Columns you need},
       V.[Type],
       V.Point
FROM dbo.RawAnalog RA
     CROSS APPLY(VALUES(REVERSE(PARSENAME(REPLACE(REVERSE(pointname), '.', '.'), 2)),REVERSE(PARSENAME(REPLACE(REVERSE(pointname), '.', '.'), 3))))V([Type],Point)
WHERE RA.PointName LIKE '%SKYLINE%'
  AND RA.Point IN ('MaTmp', 'OaTmp', 'SaTmp', 'ChwVlv', 'SaStp', 'SaCFM')
  AND V.[Type] IN ({List of acceptable values});
```

Body:
I have split the column PointName using PARSENAME and created 2 new columns and I am needing now to use a WHERE clause to only pull the data for those 6 types.  Is there a way to do this?

SELECT *, reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),2))as [Type] , reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),3))as [Point]
from RawAnalog RA
Where ra.PointName LIKE '%SKYLINE%'
      and ra.Point IN ('MaTmp', 'OaTmp', 'SaTmp', 'ChwVlv','SaStp', 'SaCFM')


问:
replace values by different conditions in a dataframe
I have a dataframe like this:

```<code>df_test = pd.DataFrame({'ID1':['A','B','C','BA','BA','AB','>','>','>','>'],
                       'ID2':['','','','','','','mh','mh','nn','nn']})
df_test
</code>```

I want to obtain a dataframe like this based on the column 'ID1'(1. if len(ID1)>2: then ID1=ID1[-1](for example 'BA', 'AB' will be replaced with 'A', 'B', respectively); 2. if ID1='>': then ID1=ID2(for example: '>' will be replaced with 'mh','nn',respectively)):

```<code>df_result = pd.DataFrame({'ID1':['A','B','C','A','A','B','mh','mh','nn','nn']})
df_result
</code>```

答:
Use str accessor:

```<code>out = df['ID1'].str[-1].replace('>', np.nan).fillna(df['ID2']).to_frame()
print(out)

# Output
  ID1
0   A
1   B
2   C
3   A
4   A
5   B
6  mh
7  mh
8  nn
9  nn
</code>```

Body:
I have a dataframe like this:

df_test = pd.DataFrame({'ID1':['A','B','C','BA','BA','AB','>','>','>','>'],
                       'ID2':['','','','','','','mh','mh','nn','nn']})
df_test

I want to obtain a dataframe like this based on the column 'ID1'(1. if len(ID1)>2: then ID1=ID1[-1](for example 'BA', 'AB' will be replaced with 'A', 'B', respectively); 2. if ID1='>': then ID1=ID2(for example: '>' will be replaced with 'mh','nn',respectively)):

df_result = pd.DataFrame({'ID1':['A','B','C','A','A','B','mh','mh','nn','nn']})
df_result

Body:
Use str accessor:

out = df['ID1'].str[-1].replace('>', np.nan).fillna(df['ID2']).to_frame()
print(out)

# Output
  ID1
0   A
1   B
2   C
3   A
4   A
5   B
6  mh
7  mh
8  nn
9  nn


问:
GKE Kubernetes MySQL Input/output error Ext4Error
I have deployed a MySQL database (statefulset) on Kubernetes zonal cluster, running as a service (GKE) in Google Cloud Platform.

The zonal cluster consist of 3 instances of type e2-medium.

The MySQL container cannot start due to the following error.

```<code>kubectl logs mysql-statefulset-0
2022-02-07 05:55:38+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.35-1debian10 started.
find: '/var/lib/mysql/': Input/output error
</code>```

Last seen events.

```<code>4m57s   Warning   Ext4Error   gke-cluster-default-pool-rnfh   kernel-monitor, gke-cluster-default-pool-rnfh   EXT4-fs error (device sdb): __ext4_find_entry:1532: inode #2: comm mysqld: reading directory lblock 0   40d   8062   gke-cluster-default-pool-rnfh
3m22s   Warning   BackOff     pod/mysql-statefulset-0   spec.containers{mysql}   kubelet, gke-cluster-default-pool-rnfh   Back-off restarting failed container
</code>```

Nodes.

```<code>kubectl get node -owide
gke-cluster-default-pool-ayqo   Ready    <none>   54d   v1.21.5-gke.1302   So.Me.I.P   So.Me.I.P    Container-Optimized OS from Google   5.4.144+         containerd://1.4.8
gke-cluster-default-pool-rnfh   Ready    <none>   54d   v1.21.5-gke.1302   So.Me.I.P   So.Me.I.P   Container-Optimized OS from Google   5.4.144+         containerd://1.4.8
gke-cluster-default-pool-sc3p   Ready    <none>   54d   v1.21.5-gke.1302   So.Me.I.P   So.Me.I.P     Container-Optimized OS from Google   5.4.144+         containerd://1.4.8
</code>```

I also noticed that rnfh node is out of memory.

```<code>kubectl top node
NAME                            CPU(cores)   CPU%   MEMORY(bytes)   MEMORY%
gke-cluster-default-pool-ayqo   117m         12%    992Mi           35%
gke-cluster-default-pool-rnfh   180m         19%    2953Mi          104%
gke-cluster-default-pool-sc3p   179m         19%    1488Mi          52%
</code>```

MySql mainfest

```<code># HEADLESS SERVICE
apiVersion: v1
kind: Service
metadata:
  name: mysql-headless-service
  labels:
    kind: mysql-headless-service
spec:
  clusterIP: None
  selector:
    tier: mysql-db
  ports:
    - name: 'mysql-http'
      protocol: 'TCP'
      port: 3306
---
# STATEFUL SET
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql-statefulset
spec:
  selector:
    matchLabels:
      tier: mysql-db
  serviceName: mysql-statefulset
  replicas: 1
  template:
    metadata:
      labels:
        tier: mysql-db
    spec:
      terminationGracePeriodSeconds: 10
      containers:
        - name: my-mysql
          image: my-mysql:latest
          imagePullPolicy: Always
          args:
            - "--ignore-db-dir=lost+found"
          ports:
            - name: 'http'
              protocol: 'TCP'
              containerPort: 3306
          volumeMounts:
            - name: mysql-pvc
              mountPath: /var/lib/mysql
          env:
            - name: MYSQL_ROOT_USER
              valueFrom:
                secretKeyRef:
                  name: mysql-secret
                  key: mysql-root-username
            - name: MYSQL_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: mysql-secret
                  key: mysql-root-password
            - name: MYSQL_USER
              valueFrom:
                configMapKeyRef:
                  name: mysql-config
                  key: mysql-username
            - name: MYSQL_PASSWORD
              valueFrom:
                configMapKeyRef:
                  name: mysql-config
                  key: mysql-password
            - name: MYSQL_DATABASE
              valueFrom:
                configMapKeyRef:
                  name: mysql-config
                  key: mysql-database
  volumeClaimTemplates:
    - metadata:
        name: mysql-pvc
      spec:
        storageClassName: 'mysql-fast'
        resources:
          requests:
            storage: 120Gi
        accessModes:
          - ReadWriteOnce
          - ReadOnlyMany
</code>```

MySQL storage class manifest:

```<code>apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: mysql-fast
provisioner: kubernetes.io/gce-pd
parameters:
  type: pd-ssd
reclaimPolicy: Retain
allowVolumeExpansion: true
volumeBindingMode: Immediate
</code>```

Why Kubernetes is trying to schedule pod in out of memory node?

UPDATES

I've added requests and limits to MySQL manifest to improve the Qos Class. Now the Qos Class is Guaranteed.

Unfortunately, Kubernetes still trying to schedule to out of memory rnfh node.

```<code>kubectl describe po mysql-statefulset-0 | grep node -i
Node: gke-cluster-default-pool-rnfh/So.Me.I.P

kubectl describe po mysql-statefulset-0 | grep qos -i
QoS Class: Guaranteed
</code>```

答:
I ran a few more tests but I couldn't replicate this.

To answer this one correctly, we would need much more logs. Not sure if you still have them. If I could guess which was the root cause of this issue I would say it was connected with the PersistentVolume.

In one of the Github issue - Volume was remounted as read only after error #752 I found very similar behavior to OP's behavior.

You have created a special storageclass for your MySQL. You've set reclaimPolicy: Retain so PV was not removed. When Statefulset pod (with the same suffix -0) has been recreated (restarted due to error with connectivity, some issues on DB, hard to say) it tried to re-claim this Volume. In the mentioned Github issue, user had very similar situation. Also got inode #262147: comm mysqld: reading directory lblock issue, but in the bellow there was also entry [ +0.003695] EXT4-fs (sda): Remounting filesystem read-only. Maybe it changed permissions when re-mounted?

Another thing that your volumeClaimTemplates contained

```<code>        accessModes:
          - ReadWriteOnce
          - ReadOnlyMany
</code>```

So one PersistentVolume could be used as ReadWriteOnce by one node or only ReadOnlyMany by many nodes. There is a possibility that POD was recreated in different node with Read-Only assessMode.

```<code>[ +35.912075] EXT4-fs warning (device sda): htree_dirblock_to_tree:977: inode #2: lblock 0: comm mysqld: error -5 reading directory block
[  +6.294232] EXT4-fs error (device sda): ext4_find_entry:1436: inode #262147: comm mysqld: reading directory lblock ...
[  +0.005226] EXT4-fs error (device sda): ext4_find_entry:1436: inode #2: comm mysqld: reading directory lblock 0
[  +1.666039] EXT4-fs error (device sda): ext4_journal_check_start:61: Detected aborted journal
[ +0.003695] EXT4-fs (sda): Remounting filesystem read-only
</code>```

It would fit to OP's comment:

Two days ago for reasons unknown to me Kubernetes restarted the container and was keep trying to run it on rnfa machine. The container was probably evicted from another node.

Another thing is that node or cluster might be updated (depending if the auto update option was turned on) which might enforce restart of the pod.

Issue with '/var/lib/mysql/': Input/output error might point to database corruption like mentioned here.

In general, the issue has been resolved by cordoning affected node. Additional information about the difference between cordon and drain can be found here.

Just as an addition, to assign pods to specific node or node with specified label, you can use Affinity

Body:
I have deployed a MySQL database (statefulset) on Kubernetes zonal cluster, running as a service (GKE) in Google Cloud Platform.

The zonal cluster consist of 3 instances of type e2-medium.

The MySQL container cannot start due to the following error.

kubectl logs mysql-statefulset-0
2022-02-07 05:55:38+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.35-1debian10 started.
find: '/var/lib/mysql/': Input/output error

Last seen events.

4m57s   Warning   Ext4Error   gke-cluster-default-pool-rnfh   kernel-monitor, gke-cluster-default-pool-rnfh   EXT4-fs error (device sdb): __ext4_find_entry:1532: inode #2: comm mysqld: reading directory lblock 0   40d   8062   gke-cluster-default-pool-rnfh
3m22s   Warning   BackOff     pod/mysql-statefulset-0   spec.containers{mysql}   kubelet, gke-cluster-default-pool-rnfh   Back-off restarting failed container

Nodes.

kubectl get node -owide
gke-cluster-default-pool-ayqo   Ready    <none>   54d   v1.21.5-gke.1302   So.Me.I.P   So.Me.I.P    Container-Optimized OS from Google   5.4.144+         containerd://1.4.8
gke-cluster-default-pool-rnfh   Ready    <none>   54d   v1.21.5-gke.1302   So.Me.I.P   So.Me.I.P   Container-Optimized OS from Google   5.4.144+         containerd://1.4.8
gke-cluster-default-pool-sc3p   Ready    <none>   54d   v1.21.5-gke.1302   So.Me.I.P   So.Me.I.P     Container-Optimized OS from Google   5.4.144+         containerd://1.4.8

I also noticed that rnfh node is out of memory.

kubectl top node
NAME                            CPU(cores)   CPU%   MEMORY(bytes)   MEMORY%
gke-cluster-default-pool-ayqo   117m         12%    992Mi           35%
gke-cluster-default-pool-rnfh   180m         19%    2953Mi          104%
gke-cluster-default-pool-sc3p   179m         19%    1488Mi          52%

MySql mainfest

# HEADLESS SERVICE
apiVersion: v1
kind: Service
metadata:
  name: mysql-headless-service
  labels:
    kind: mysql-headless-service
spec:
  clusterIP: None
  selector:
    tier: mysql-db
  ports:
    - name: 'mysql-http'
      protocol: 'TCP'
      port: 3306
---
# STATEFUL SET
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql-statefulset
spec:
  selector:
    matchLabels:
      tier: mysql-db
  serviceName: mysql-statefulset
  replicas: 1
  template:
    metadata:
      labels:
        tier: mysql-db
    spec:
      terminationGracePeriodSeconds: 10
      containers:
        - name: my-mysql
          image: my-mysql:latest
          imagePullPolicy: Always
          args:
            - "--ignore-db-dir=lost+found"
          ports:
            - name: 'http'
              protocol: 'TCP'
              containerPort: 3306
          volumeMounts:
            - name: mysql-pvc
              mountPath: /var/lib/mysql
          env:
            - name: MYSQL_ROOT_USER
              valueFrom:
                secretKeyRef:
                  name: mysql-secret
                  key: mysql-root-username
            - name: MYSQL_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: mysql-secret
                  key: mysql-root-password
            - name: MYSQL_USER
              valueFrom:
                configMapKeyRef:
                  name: mysql-config
                  key: mysql-username
            - name: MYSQL_PASSWORD
              valueFrom:
                configMapKeyRef:
                  name: mysql-config
                  key: mysql-password
            - name: MYSQL_DATABASE
              valueFrom:
                configMapKeyRef:
                  name: mysql-config
                  key: mysql-database
  volumeClaimTemplates:
    - metadata:
        name: mysql-pvc
      spec:
        storageClassName: 'mysql-fast'
        resources:
          requests:
            storage: 120Gi
        accessModes:
          - ReadWriteOnce
          - ReadOnlyMany

MySQL storage class manifest:

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: mysql-fast
provisioner: kubernetes.io/gce-pd
parameters:
  type: pd-ssd
reclaimPolicy: Retain
allowVolumeExpansion: true
volumeBindingMode: Immediate

Why Kubernetes is trying to schedule pod in out of memory node?

UPDATES

I've added requests and limits to MySQL manifest to improve the Qos Class. Now the Qos Class is Guaranteed.

Unfortunately, Kubernetes still trying to schedule to out of memory rnfh node.

kubectl describe po mysql-statefulset-0 | grep node -i
Node: gke-cluster-default-pool-rnfh/So.Me.I.P

kubectl describe po mysql-statefulset-0 | grep qos -i
QoS Class: Guaranteed

Body:
I ran a few more tests but I couldn't replicate this.

To answer this one correctly, we would need much more logs. Not sure if you still have them. If I could guess which was the root cause of this issue I would say it was connected with the PersistentVolume.

In one of the Github issue - Volume was remounted as read only after error #752 I found very similar behavior to OP's behavior.

You have created a special storageclass for your MySQL. You've set reclaimPolicy: Retain so PV was not removed. When Statefulset pod (with the same suffix -0) has been recreated (restarted due to error with connectivity, some issues on DB, hard to say) it tried to re-claim this Volume. In the mentioned Github issue, user had very similar situation. Also got inode #262147: comm mysqld: reading directory lblock issue, but in the bellow there was also entry [ +0.003695] EXT4-fs (sda): Remounting filesystem read-only. Maybe it changed permissions when re-mounted?

Another thing that your volumeClaimTemplates contained

        accessModes:
          - ReadWriteOnce
          - ReadOnlyMany

So one PersistentVolume could be used as ReadWriteOnce by one node or only ReadOnlyMany by many nodes. There is a possibility that POD was recreated in different node with Read-Only assessMode.

[ +35.912075] EXT4-fs warning (device sda): htree_dirblock_to_tree:977: inode #2: lblock 0: comm mysqld: error -5 reading directory block
[  +6.294232] EXT4-fs error (device sda): ext4_find_entry:1436: inode #262147: comm mysqld: reading directory lblock ...
[  +0.005226] EXT4-fs error (device sda): ext4_find_entry:1436: inode #2: comm mysqld: reading directory lblock 0
[  +1.666039] EXT4-fs error (device sda): ext4_journal_check_start:61: Detected aborted journal
[ +0.003695] EXT4-fs (sda): Remounting filesystem read-only

It would fit to OP's comment:

Two days ago for reasons unknown to me Kubernetes restarted the container and was keep trying to run it on rnfa machine. The container was probably evicted from another node.

Another thing is that node or cluster might be updated (depending if the auto update option was turned on) which might enforce restart of the pod.

Issue with '/var/lib/mysql/': Input/output error might point to database corruption like mentioned here.

In general, the issue has been resolved by cordoning affected node. Additional information about the difference between cordon and drain can be found here.

Just as an addition, to assign pods to specific node or node with specified label, you can use Affinity


问:
What should be the correct way to send to the front-end the napi_values I receive from the native-addon?
I am trying to communicate this native addon with the front-end. It consists of a prime number generator, when it is executed it writes to the console, I want it to send them via Sockets to the browser console.

With this code I invoke the addon and write the napi_values in the console:

```<code>binding.startThread((thePrime) =>
  console.log("Received prime from secondary thread: " + thePrime));
</code>```

I already tried using socket.emit.

```<code>socket.emit('dataout', addon.startThread(thePrime));
</code>```

But I only manage to write in the console.

What should be the correct way to send the napi_values I receive from native-addon to the front-end? Should I change "socket.io" to something else?

I'd like to read any crazy code proposals, even if you haven't tried it yourselves.

My code that corresponds to sockets:

```<code>sockets() {
        this.io.on('connection', socket => {

            console.log('cliente conectado', socket.id);

            socket.on('disconnect', () => {
                console.log('Cliente desconectado', socket.id);
            });

            //correct mode
            //addon.startThread((thePrime) => socket.emit('dataout', thePrime));

            socket.on('enviar-mensaje', ( payload, callback ) => {

                callback(payload);

            });

            socket.on('addonexe', () => {

                addon.startThread((thePrime) => socket.emit('dataout', thePrime));

            });

        });

    }
</code>```

答:
This

socket.emit('dataout', addon.startThread(thePrime));
```
<p>emits the result of the function. This is not what you want, you want your callback function to emit:</p>
<pre class="lang-js prettyprint-override"><code>addon.startThread((thePrime) => socket.emit('dataout', thePrime));
</code>```

Body:
I am trying to communicate this native addon with the front-end. It consists of a prime number generator, when it is executed it writes to the console, I want it to send them via Sockets to the browser console.

With this code I invoke the addon and write the napi_values in the console:

binding.startThread((thePrime) =>
  console.log("Received prime from secondary thread: " + thePrime));

I already tried using socket.emit.

socket.emit('dataout', addon.startThread(thePrime));

But I only manage to write in the console.

What should be the correct way to send the napi_values I receive from native-addon to the front-end? Should I change "socket.io" to something else?

I'd like to read any crazy code proposals, even if you haven't tried it yourselves.

My code that corresponds to sockets:

sockets() {
        this.io.on('connection', socket => {

            console.log('cliente conectado', socket.id);

            socket.on('disconnect', () => {
                console.log('Cliente desconectado', socket.id);
            });

            //correct mode
            //addon.startThread((thePrime) => socket.emit('dataout', thePrime));

            socket.on('enviar-mensaje', ( payload, callback ) => {

                callback(payload);

            });

            socket.on('addonexe', () => {

                addon.startThread((thePrime) => socket.emit('dataout', thePrime));

            });

        });

    }

Body:
This

socket.emit('dataout', addon.startThread(thePrime));

emits the result of the function. This is not what you want, you want your callback function to emit:

addon.startThread((thePrime) => socket.emit('dataout', thePrime));


问:
Flex-grow seems to not adjusting height of elements
I want a second element app-item in parent element app to grow in height while there is free space so the footer will be always at the bottom of the website. But it seems that flex-grow: 1; is not working. How should I make it work. On my other projects it is working as I expected but here I can't find reason why it is not.

html, body {
    padding: 0;
    margin: 0;
  }

html{
    height: 100%;
}

body{
    min-height: 100%;
    background-color: #eee;
}

.app{
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-content: stretch;
    align-items: stretch;
    background-color: yellow;
}

.app-item:nth-child(1){
    order: 0;
    flex: 0 1 auto;
    align-self: auto;
    background-color: #fdd;
}

.app-item:nth-child(2){
    order: 0;
    flex: 1 0 0;
    align-self: auto;
    background-color: #dfd;
}

.app-item:nth-child(3){
    order: 0;
    flex: 0 1 auto;
    align-self: auto;
    background-color: #ddf;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <body>
    <div class="app">

        <div class="app-item">
            <nav class="app-item navbar navbar-expand-lg navbar-dark bg-dark" id="navbar">
                <div class="container-fluid">
                QuoraASoL
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
                    <div class="navbar-nav">
                        Profile
                        Logout
                        Create Question
                        <hr>
                        Login
                        Register
                    </div>
                </div>
                </div>
            </nav>
        </div>

        <div id="main-area" class="app-item">
            Content block
        </div>

        <div class="app-item">
            <nav class="navbar navbar-dark bg-dark" id="footer">
                <div class="container-fluid">
                Adventure Side of Life
                </div>
            </nav>
        </div>

    </div>
  </body>
</html></code>```

答:
Your .app container is as high as its content, so there is no space for content elements to grow.

To make the .app container as high as the body, you could specify the height of the body with a minimum of the full window height (height: 100%; min-height: 100vh;), and make the .app as high as the body (height: 100%;).

html, body {
    padding: 0;
    margin: 0;
  }

html{
    height: 100%;
}

body{
    height: 100%;
    min-height: 100vh;
    background-color: #eee;
}

.app{
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-content: stretch;
    align-items: stretch;
    background-color: yellow;
    height: 100%;
}

.app-item:nth-child(1){
    order: 0;
    flex: 0 1 auto;
    align-self: auto;
    background-color: #fdd;
}

.app-item:nth-child(2){
    order: 0;
    flex: 1 0 0;
    align-self: auto;
    background-color: #dfd;
}

.app-item:nth-child(3){
    order: 0;
    flex: 0 1 auto;
    align-self: auto;
    background-color: #ddf;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <body>
    <div class="app">

        <div class="app-item">
            <nav class="app-item navbar navbar-expand-lg navbar-dark bg-dark" id="navbar">
                <div class="container-fluid">
                QuoraASoL
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
                    <div class="navbar-nav">
                        Profile
                        Logout
                        Create Question
                        <hr>
                        Login
                        Register
                    </div>
                </div>
                </div>
            </nav>
        </div>

        <div id="main-area" class="app-item">
            Content block
        </div>

        <div class="app-item">
            <nav class="navbar navbar-dark bg-dark" id="footer">
                <div class="container-fluid">
                Adventure Side of Life
                </div>
            </nav>
        </div>

    </div>
  </body>
</html></code>```

Body:
I want a second element app-item in parent element app to grow in height while there is free space so the footer will be always at the bottom of the website. But it seems that flex-grow: 1; is not working. How should I make it work. On my other projects it is working as I expected but here I can't find reason why it is not.

html, body {
    padding: 0;
    margin: 0;
  }

html{
    height: 100%;
}

body{
    min-height: 100%;
    background-color: #eee;
}

.app{
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-content: stretch;
    align-items: stretch;
    background-color: yellow;
}

.app-item:nth-child(1){
    order: 0;
    flex: 0 1 auto;
    align-self: auto;
    background-color: #fdd;
}

.app-item:nth-child(2){
    order: 0;
    flex: 1 0 0;
    align-self: auto;
    background-color: #dfd;
}

.app-item:nth-child(3){
    order: 0;
    flex: 0 1 auto;
    align-self: auto;
    background-color: #ddf;
}

                QuoraASoL
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                        Profile
                        Logout
                        Create Question

                        Login
                        Register

            Content block

                Adventure Side of Life

Body:
Your .app container is as high as its content, so there is no space for content elements to grow.

To make the .app container as high as the body, you could specify the height of the body with a minimum of the full window height (height: 100%; min-height: 100vh;), and make the .app as high as the body (height: 100%;).

html, body {
    padding: 0;
    margin: 0;
  }

html{
    height: 100%;
}

body{
    height: 100%;
    min-height: 100vh;
    background-color: #eee;
}

.app{
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-content: stretch;
    align-items: stretch;
    background-color: yellow;
    height: 100%;
}

.app-item:nth-child(1){
    order: 0;
    flex: 0 1 auto;
    align-self: auto;
    background-color: #fdd;
}

.app-item:nth-child(2){
    order: 0;
    flex: 1 0 0;
    align-self: auto;
    background-color: #dfd;
}

.app-item:nth-child(3){
    order: 0;
    flex: 0 1 auto;
    align-self: auto;
    background-color: #ddf;
}

<html>
  <body>
    <div class="app">

        <div class="app-item">
            <nav class="app-item navbar navbar-expand-lg navbar-dark bg-dark" id="navbar">
                <div class="container-fluid">
                <a class="navbar-brand" href="#">QuoraASoL</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
                    <div class="navbar-nav">
                        <a class="nav-link" href="#" >Profile</a>
                        <a class="nav-link " href="#">Logout</a>
                        <a class="nav-link " href="#">Create Question</a>
                        <hr>
                        <a class="nav-link " href="#">Login</a>
                        <a class="nav-link " href="#">Register</a>
                    </div>
                </div>
                </div>
            </nav>
        </div>

        <div id="main-area" class="app-item">
            Content block
        </div>

        <div class="app-item">
            <nav class="navbar navbar-dark bg-dark" id="footer">
                <div class="container-fluid">
                <a class="navbar-brand" href="#">Adventure Side of Life</a>
                </div>
            </nav>
        </div>

    </div>
  </body>
</html>


问:
AWS MSK Connectors for Debezium IAM Role Problem
I want creat a connector for Debezium. I am unable to create a kafka connector using the AWSServiceRoleForKafkaConnect role. Here is the error I get when clicking Create Connector on the last page in the form:

```<code>Error creating connector There was a problem creating a connector. If the problem persists, contact AWS Support. API response Invalid parameter serviceExecutionRoleArn: A service linked role ARN cannot be provided as service execution role ARN.
</code>```

Here is the document which I am following:
https://aws.amazon.com/tr/blogs/aws/introducing-amazon-msk-connect-stream-data-to-and-from-your-apache-kafka-clusters-using-managed-connectors/

How Can I fix this problem ? Thanks!

答:
I had a similar problem while creating MSK Connector to S3 bucket. You can solve it using instructions from this tutorial:
https://docs.aws.amazon.com/msk/latest/developerguide/mkc-tutorial-setup.html

You have to create new IAM Role and edit Trust relationship:

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "kafkaconnect.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
</code>```

Body:
I want creat a connector for Debezium. I am unable to create a kafka connector using the AWSServiceRoleForKafkaConnect role. Here is the error I get when clicking Create Connector on the last page in the form:

Error creating connector There was a problem creating a connector. If the problem persists, contact AWS Support. API response Invalid parameter serviceExecutionRoleArn: A service linked role ARN cannot be provided as service execution role ARN.

Here is the document which I am following:
https://aws.amazon.com/tr/blogs/aws/introducing-amazon-msk-connect-stream-data-to-and-from-your-apache-kafka-clusters-using-managed-connectors/

How Can I fix this problem ? Thanks!

Body:
I had a similar problem while creating MSK Connector to S3 bucket. You can solve it using instructions from this tutorial:
https://docs.aws.amazon.com/msk/latest/developerguide/mkc-tutorial-setup.html

You have to create new IAM Role and edit Trust relationship:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "kafkaconnect.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}


问:
How to make div with text to expand if the text does not fit there
My page: page

Html code for message block:

```<code><div class="message-body row">
      <div class="text-box ">
        <p>{{message.text}}</p>
      </div>
    </div>
</code>```

Css styles:

```<code>.text-box {
  display: flex;
  margin-left: 10px;
}
</code>```

message-body does not have any styles from css

答: .text-box { display: flex; margin-left: 10px; word-break: break-all; }

Body:
My page: page

Html code for message block:

{{message.text}}

Css styles:

.text-box {
  display: flex;
  margin-left: 10px;
}

message-body does not have any styles from css


问:
Scanning A Text String Then Month Year Format with Month End Date
I searched on Stackoverflow and was able to write this formula by reading a cell's Month Year Date Time to give me this (Column A from reading Column H):

Column A Cell A2 (A2 indicates 4/1/2021) =DATE(YEAR(H2),MONTH(H2)+1,1) which reads this 3/30/2021 5:09:55 PM.

Then I wrote a formula in Column I for giving me the Month Year format for I2 reading from A2:

=TEXT(A2,"mmmm yyyy") which is April 2021 then I copy and paste as value into Column B (B2 as April 2021)

Is there an IF statement or a formula I can write when scanning say Column I (I2 = "April 2021) to give me the Month~MonthEnd-Date~Year format? ie "April 2021" to "April 30th 2021"?

This might require a new thread but how do I "turn-on" the auto feature whenever I add a new row to keep the new rows as part of a Table?

答:
If you are just looking for the start of the following month in column A, you formula works fine.  An alternative formula for column A could be:

```<code>=EOMONTH(I2,0)+1
</code>```

As an alternative to converting the date to a text value, you can format the cell to display date in the same format.  The advantage to this is the cell is still an excel date that formulas can easily work with.

Again to get the last day of the month use EOMONTH formula.  If you want to keep your text method going, use the following formula:

```<code>=TEXT(EOMONTH(A2,0),"mmmm dd yyyy")
</code>```

Alternatively if you format the cell appropriately, you can just use:

```<code>=EOMONTH(A2,0)
</code>```

Note if you really need the st for days ending in 1 and nd for days end 2, etc,  it gets more complicated.  I am assuming that they are not really needed.

Body:
If you are just looking for the start of the following month in column A, you formula works fine.  An alternative formula for column A could be:

=EOMONTH(I2,0)+1

As an alternative to converting the date to a text value, you can format the cell to display date in the same format.  The advantage to this is the cell is still an excel date that formulas can easily work with.

Again to get the last day of the month use EOMONTH formula.  If you want to keep your text method going, use the following formula:

=TEXT(EOMONTH(A2,0),"mmmm dd yyyy")

Alternatively if you format the cell appropriately, you can just use:

=EOMONTH(A2,0)

Note if you really need the st for days ending in 1 and nd for days end 2, etc,  it gets more complicated.  I am assuming that they are not really needed.


问:
read file in php and insert into ec2 amazon server mysql database
actually im having list of medicine in a file and i want to insert it on ec2 amazon server database which is mysql.I run this file on localhost.when im trying my code, which is in php it show an error as follows:im not getting.

Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on 'ec2-122-248-220-105.ap-southeast-1.compute.amazonaws.com' (10060) in C:\websites\medicine\filehandling.php on line 17
Can't connect to MySQL
This is a servername:ec2-122-248-220-105.ap-southeast-1.compute.amazonaws.com
here is my code... and let me know where im wrong.

```<code><?php

$hostname='http://ec2-122-248-220-105.ap-southeast-1.compute.amazonaws.com';
//$port='3306';
$user='root';//// specify username
$pass='bitnami'; //// specify password
$dbase='fortis'; //// specify database name
set_time_limit(1000);
$connection = mysql_connect("$hostname" , "$user" , "$pass" ,"$port")
or die ("Can't connect to MySQL");
$db = mysql_select_db($dbase , $connection) or die ("Can't select database.");
$file = fopen("med4","r") or exit ("File not found");
$c =0 ;
      while (!feof($file)){
            ++$c;
        $val = fgets($file);
        mysql_query("insert into patientinfo_medicines (medicine) values ('$val')");
      }
fclose($file);
echo $c;
?>
</code>```

答:
There are many possible reasons why you are not able to connect to the server.

Firewall (iptables) settings on the server prevent external access

The MySQL server only listens for local connections

There is no MySQL remote user created on the server

Your $hostname should be 'ec2-122-248-220-105.ap-southeast-1.compute.amazonaws.com';

There might be other reasons as well.

Also, it is generally a bad idea to connect to databases over the internet for reasons varying from security to latency.

Good luck!

Body:
actually im having list of medicine in a file and i want to insert it on ec2 amazon server database which is mysql.I run this file on localhost.when im trying my code, which is in php it show an error as follows:im not getting.

Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on 'ec2-122-248-220-105.ap-southeast-1.compute.amazonaws.com' (10060) in C:\websites\medicine\filehandling.php on line 17
Can't connect to MySQL
This is a servername:ec2-122-248-220-105.ap-southeast-1.compute.amazonaws.com
here is my code... and let me know where im wrong.

<?php

$hostname='http://ec2-122-248-220-105.ap-southeast-1.compute.amazonaws.com';
//$port='3306';
$user='root';//// specify username
$pass='bitnami'; //// specify password
$dbase='fortis'; //// specify database name
set_time_limit(1000);
$connection = mysql_connect("$hostname" , "$user" , "$pass" ,"$port")
or die ("Can't connect to MySQL");
$db = mysql_select_db($dbase , $connection) or die ("Can't select database.");
$file = fopen("med4","r") or exit ("File not found");
$c =0 ;
      while (!feof($file)){
            ++$c;
        $val = fgets($file);
        mysql_query("insert into patientinfo_medicines (medicine) values ('$val')");
      }
fclose($file);
echo $c;
?>


问:
undefined reference to symbol 'vtkImageAlgorithm::GetOutput()'
I want to build a project using make in Ubuntu. This project includes VTK, Xerces and Cmake libraries. While builing I get the following error:

```<code>Linking CXX static library libMA_LaTIM.a
     [ 96%] Built target MA_LaTIM
     Scanning dependencies of target MA_LaTIM_entrainement
     [100%] Building CXX object applications/CMakeFiles/MA_LaTIM_entrainement.dir/entrainement.cxx.o
Linking CXX executable MA_LaTIM_entrainement
    /usr/bin/ld: ../algorithmes/libMA_LaTIM.a(LecteurImage.cxx.o): undefined     reference to symbol 'vtkImageAlgorithm::GetOutput()'
    /usr/bin/ld: note: 'vtkImageAlgorithm::GetOutput()' is defined in DSO     /usr/lib/libvtkFiltering.so.5.8 so try adding it to the linker command line
    /usr/lib/libvtkFiltering.so.5.8: could not read symbols: Invalid operation
collect2: ld returned 1 exit status
</code>```

How can I fix this problem? Here is my CMakeLists.txt, and here is my Makefile.

答:
If you happen to not use cmake to build your application, here is the solution  to resolve the linker error undefined reference to symbol with VTK!
The libraries have to be chosen manually. The problem is, that e.g. with my version VTK 6.1 there are 377 shared libs to choose from. Well, some are as before with version 5 but split in Core and special libs.

Others can be found if you check the header of the module the compiler complains about: there is a macro between "class" and the class name: "class VTK_......_EXPORT" , which gives you a hint how the lib is named.
E.g. class VTKRENDERINGCORE_EXPORT vtkRenderer needs library libvtkRenderingCore. Here an example (Linux) which worked for my application:

```<code>-L/usr/lib64/vtk -lvtkCommonCore -lvtkFiltersCore -lvtkRenderingCore  -lvtkImagingCore -lvtkCommonExecutionModel -l vtkCommonDataModel \
            -lvtkFiltersSources -lvtkFiltersGeometry -lvtkFiltersGeneral -lvtkIOCore -lvtkIOImage -lvtkRenderingOpenGL
</code>```

Body:
I want to build a project using make in Ubuntu. This project includes VTK, Xerces and Cmake libraries. While builing I get the following error:

Linking CXX static library libMA_LaTIM.a
     [ 96%] Built target MA_LaTIM
     Scanning dependencies of target MA_LaTIM_entrainement
     [100%] Building CXX object applications/CMakeFiles/MA_LaTIM_entrainement.dir/entrainement.cxx.o
Linking CXX executable MA_LaTIM_entrainement
    /usr/bin/ld: ../algorithmes/libMA_LaTIM.a(LecteurImage.cxx.o): undefined     reference to symbol 'vtkImageAlgorithm::GetOutput()'
    /usr/bin/ld: note: 'vtkImageAlgorithm::GetOutput()' is defined in DSO     /usr/lib/libvtkFiltering.so.5.8 so try adding it to the linker command line
    /usr/lib/libvtkFiltering.so.5.8: could not read symbols: Invalid operation
collect2: ld returned 1 exit status

How can I fix this problem? Here is my CMakeLists.txt, and here is my Makefile.

Body:
If you happen to not use cmake to build your application, here is the solution  to resolve the linker error undefined reference to symbol with VTK!
The libraries have to be chosen manually. The problem is, that e.g. with my version VTK 6.1 there are 377 shared libs to choose from. Well, some are as before with version 5 but split in Core and special libs.

Others can be found if you check the header of the module the compiler complains about: there is a macro between "class" and the class name: "class VTK_......_EXPORT" , which gives you a hint how the lib is named.
E.g. class VTKRENDERINGCORE_EXPORT vtkRenderer needs library libvtkRenderingCore. Here an example (Linux) which worked for my application:

-L/usr/lib64/vtk -lvtkCommonCore -lvtkFiltersCore -lvtkRenderingCore  -lvtkImagingCore -lvtkCommonExecutionModel -l vtkCommonDataModel \
            -lvtkFiltersSources -lvtkFiltersGeometry -lvtkFiltersGeneral -lvtkIOCore -lvtkIOImage -lvtkRenderingOpenGL


问:
Regex match but do not capture with a ".*"
I have two blocks of code.

```<code><TabItem Header="{materialDesign:PackIcon Kind=Bank, Size=24}"
                     Style="{StaticResource MaterialDesignNavigationRailTabItem}"
                     ToolTip="Example">
</code>```

and

```<code><Button Header="{materialDesign:PackIcon Kind=Bank, Size=24}"
                     Style="{StaticResource MaterialDesignNavigationRailTabItem}"
                     ToolTip="Example">
</code>```

I to select the ToolTip="Example" part and replace it. However, I only want to select the ToolTip that is inside the TabItem block. I can select it with:

```<code>ToolTip\=\"(.*?)\"
</code>```

That selects the one in the Button block as well. I used this StackOverflow Question to try and solve my issue, but I could not figure out how to make it work with a ".*".

So my criteria is:

Must begin with '<TabItem'

Must contain 'ToolTip=".*"'

Must end with ">"

Is what I am trying to achieve possible? If so, how could I achieve this?

答:
This should work

```<code><TabItem\b[^>]*\bToolTip="([^"]*)"[^>]*>
</code>```

Using [^>]* ensures that the regexp won't match across multiple tags, and [^"]* won't allow that capture group to go outside the quoted tooltip attribute.

You can't use a lookaround for this, because you'd need a lookbehind to match the part before ToolTip, and lookbehinds have to be fixed length in most regexp engines.

If you're using this in a regexp replacement, put the parts that should be kept in the replacement into capture groups, and then use back-references in the replacement string.

Body:
I have two blocks of code.

<TabItem Header="{materialDesign:PackIcon Kind=Bank, Size=24}"
                     Style="{StaticResource MaterialDesignNavigationRailTabItem}"
                     ToolTip="Example">

and

<Button Header="{materialDesign:PackIcon Kind=Bank, Size=24}"
                     Style="{StaticResource MaterialDesignNavigationRailTabItem}"
                     ToolTip="Example">

I to select the ToolTip="Example" part and replace it. However, I only want to select the ToolTip that is inside the TabItem block. I can select it with:

ToolTip\=\"(.*?)\"

That selects the one in the Button block as well. I used this StackOverflow Question to try and solve my issue, but I could not figure out how to make it work with a ".*".

So my criteria is:

Must begin with '<TabItem'

Must contain 'ToolTip=".*"'

Must end with ">"

Is what I am trying to achieve possible? If so, how could I achieve this?

Body:
This should work

<TabItem\b[^>]*\bToolTip="([^"]*)"[^>]*>

Using [^>]* ensures that the regexp won't match across multiple tags, and [^"]* won't allow that capture group to go outside the quoted tooltip attribute.

You can't use a lookaround for this, because you'd need a lookbehind to match the part before ToolTip, and lookbehinds have to be fixed length in most regexp engines.

If you're using this in a regexp replacement, put the parts that should be kept in the replacement into capture groups, and then use back-references in the replacement string.


问:
No debuggable processes in logcat when phone detected by Android studio
Everyone!

I got so confused by android studio.
when I plug in my phone to debug apps, logcat can detect my phone, but I can not choose process. It said "no debuggable processes",not common "no debuggable applications".

My phone is samsung s5 (android 6.0),rooted.

Any ideas?

Thanks!

答:
1. Open Edit Configurations:

2. Check the boxes:


问:
Autocomplete for my functions in the google-apps-script editor

Can I get in editor autocomplete for my functions using JSDoc somehow?

I am creating a big google spreadsheet with a lot of code in the associated script editor.

I get autocompletion help when I write the period on LINE 1 (see code below), but not when writing the period on LINE 2. Is it possible to use JSDoc syntax to get autocomplete help when writing the period on LINE 2 also?

I have not succeeded getting this to work for normal javascript objects nor Spreadsheet related objects. I'm interested in both.

```<code>/** Failed attempt on getting autocomplete help using JSDoc on a google Range object
* @returns {Range}
*/
function getMyRange() {
  return SpreadsheetApp.getActiveSpreadsheet().getRangeByName('myRange');
};

/** Failed attempt on getting autocomplete help using JSDoc on standard JS-object
* @returns {Array}
*/
function getMyArray() {
  return SpreadsheetApp.getActiveSpreadsheet().getRangeByName('myRange');
};

function test() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // Please think of the code below as 4 separate examples, nothing
  // of the below is meant to compile as it is. It is just 4 separate
  // demonstrations of when I'd like to get autocompletion help and notes
  // on when I do and don't
  ss.getRangeByName('myRange'). // **** LINE 1 **** I get autocomplete
  getMyRange().                 // **** LINE 2 **** No autocomplete

  [].                           // **** LINE 3 **** I get autocomplete
  getMyArray().                 // **** LINE 4 **** No autocomplete...
};
</code>```

答: From Editor, File, Project Properties, Copy "Script ID", Cancel, Resources, Libraries,Add a Library, Paste, Add, Set Version, Set Identifier to "a" because my left little finger is always on the "a" key, so to see your local script functions in auto complete, just type "a.", then remove "a." when you have your parameters set.</p>

Body:
Can I get in editor autocomplete for my functions using JSDoc somehow?

I am creating a big google spreadsheet with a lot of code in the associated script editor.

I get autocompletion help when I write the period on LINE 1 (see code below), but not when writing the period on LINE 2. Is it possible to use JSDoc syntax to get autocomplete help when writing the period on LINE 2 also?

I have not succeeded getting this to work for normal javascript objects nor Spreadsheet related objects. I'm interested in both.

/** Failed attempt on getting autocomplete help using JSDoc on a google Range object
* @returns {Range}
*/
function getMyRange() {
  return SpreadsheetApp.getActiveSpreadsheet().getRangeByName('myRange');
};

/** Failed attempt on getting autocomplete help using JSDoc on standard JS-object
* @returns {Array}
*/
function getMyArray() {
  return SpreadsheetApp.getActiveSpreadsheet().getRangeByName('myRange');
};

function test() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // Please think of the code below as 4 separate examples, nothing
  // of the below is meant to compile as it is. It is just 4 separate
  // demonstrations of when I'd like to get autocompletion help and notes
  // on when I do and don't
  ss.getRangeByName('myRange'). // **** LINE 1 **** I get autocomplete
  getMyRange().                 // **** LINE 2 **** No autocomplete

  [].                           // **** LINE 3 **** I get autocomplete
  getMyArray().                 // **** LINE 4 **** No autocomplete...
};


问:
mod_python with apache2, (Re)importing module error
I'm trying to get mod-python to work with apache2 but not having any success. I've followed a few tutorials for getting mod-python working but I can't see what I'm doing wrong.

When I visit http://site.example.com/cgi-bin/test.py I actually get my 404 page! (whereas I get a 403 forbidden if the file really doesn't exist)

Here's my setup:

In /etc/apache2/sites-enabled/ there are configuration files named after each of my domains. In the site.example.com file I've added this to the user directives section:

```<code># Begin user directives <--
<Directory /home/default/site.example.com/user/htdocs/cgi-bin/>
     Options Indexes FollowSymLinks MultiViews
     AllowOverride AuthConfig
     Order allow,deny
     allow from all
     AddHandler mod_python .py
     PythonHandler mod_python.publisher
     PythonDebug On
</Directory>
# --> End user directives
</code>```

full file here, which includes the line:

EDIT to add contents of test.py:

```<code>#!/usr/bin/python
print "Content-type: text/html"
print
print 'hello world'
#print 1/0
</code>```

As shown above, I get a 404 /python/test.py was not found on this server.

But if I uncomment the last line I get:

```<code>Mod_python error: "PythonHandler mod_python.publisher"

Traceback (most recent call last):

  File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 299, in HandlerDispatch
    result = object(req)

  File "/usr/lib/python2.4/site-packages/mod_python/publisher.py", line 98, in handler
    path=[path])

  File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 457, in import_module
    module = imp.load_module(mname, f, p, d)

  File "/home/default/site.example.co.uk/user/htdocs/python/test.py", line 5, in ?
    print 1/0

ZeroDivisionError: integer division or modulo by zero
</code>```

Does this traceback look right? Enabling cgitb has no effect by the way.

Is there any other info I can add to help diagnose this?

答:
As far as I know, the Publisher handler needs to take in a request object and a method in order to return the response.

In my scripts, I have something like this:

```<code>#!/usr/bin/python
def run(req):
  return 'Hello world!'
</code>```

Then, go to http://.../python/test.py/run

In this case, req is the request object that gets passed in by the Publisher Handler.

And, in case you don't have one already, you need to have an __init__.py file in the same directory where test.py is.

Also, with the Publisher, I noticed that sometimes, the response gets cached. I will get the same errors back in the browser that I had already fixed. So, it's not a bad idea to restart apache if you see an error that you think you fixed already.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to get mod-python to work with apache2 but not having any success. I've followed a few tutorials for getting mod-python working but I can't see what I'm doing wrong.

When I visit http://site.example.com/cgi-bin/test.py I actually get my 404 page! (whereas I get a 403 forbidden if the file really doesn't exist)

Here's my setup:

In /etc/apache2/sites-enabled/ there are configuration files named after each of my domains. In the site.example.com file I've added this to the user directives section:

# Begin user directives <--
<Directory /home/default/site.example.com/user/htdocs/cgi-bin/>
     Options Indexes FollowSymLinks MultiViews
     AllowOverride AuthConfig
     Order allow,deny
     allow from all
     AddHandler mod_python .py
     PythonHandler mod_python.publisher
     PythonDebug On
</Directory>
# --> End user directives

full file here, which includes the line:

EDIT to add contents of test.py:

#!/usr/bin/python
print "Content-type: text/html"
print
print 'hello world'
#print 1/0

As shown above, I get a 404 /python/test.py was not found on this server.

But if I uncomment the last line I get:

Mod_python error: "PythonHandler mod_python.publisher"

Traceback (most recent call last):

  File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 299, in HandlerDispatch
    result = object(req)

  File "/usr/lib/python2.4/site-packages/mod_python/publisher.py", line 98, in handler
    path=[path])

  File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 457, in import_module
    module = imp.load_module(mname, f, p, d)

  File "/home/default/site.example.co.uk/user/htdocs/python/test.py", line 5, in ?
    print 1/0

ZeroDivisionError: integer division or modulo by zero

Does this traceback look right? Enabling cgitb has no effect by the way.

Is there any other info I can add to help diagnose this?

Body:
As far as I know, the Publisher handler needs to take in a request object and a method in order to return the response.

In my scripts, I have something like this:

#!/usr/bin/python
def run(req):
  return 'Hello world!'

Then, go to http://.../python/test.py/run

In this case, req is the request object that gets passed in by the Publisher Handler.

And, in case you don't have one already, you need to have an __init__.py file in the same directory where test.py is.

Also, with the Publisher, I noticed that sometimes, the response gets cached. I will get the same errors back in the browser that I had already fixed. So, it's not a bad idea to restart apache if you see an error that you think you fixed already.

OwnerDisplayName: Aaron Landerkin

LastEditorDisplayName: Aaron Landerkin


问:
Power shell command to delete files with 1 row
I have files sitting in a folder on windows. I need to delete files with 1 row ( Having just the header) and leave the rest in there. What would be the command to do it in power shell?

The files will be of the below pattern

Test_Files_QS1_202202080808.csv
Test_Files_QS2_202202080808.csv
Test_Files_QS3_202202080808.csv
Test_Files_QS4_202202080808.csv

答:
Attempt to read 2 lines from each file, if you get less than 2 then delete:</p>
```<code>Get-ChildItem -Filter *.csv |Where-Object {@($_ |Get-Content -TotalCount 2 |Where-Object { $_.Trim() -ne '' }).Count -lt 2} |Remove-Item
</code>```

Body:
Attempt to read 2 lines from each file, if you get less than 2 then delete:

Get-ChildItem -Filter *.csv |Where-Object {@($_ |Get-Content -TotalCount 2 |Where-Object { $_.Trim() -ne '' }).Count -lt 2} |Remove-Item


问:
Nginx with worpress as sub-directory returning 404 in posts
After adding various configurations into the Wordpress subdirectory, I can access without any issues the WP homepage, but I'm still not able to access the posts, returning 404.

www.test.com/blog - WP homepage, works perfectly fine

www.test.com/blog/test-post-for-blog - WP Post, 404

Here is the config:

```<code>server {
  listen 80;
  listen [::]:80;

  server_name www.test.com;

  location ^~ /media {
    alias /var/local/test/static/media;
  }

  location ^~ /icons {
    alias /var/local/test/static/icons;
  }

  location /blog {
    alias /var/www/html;
    index  index.html index.htm index.php;
    try_files $uri $uri/ /blog/index.php?$args /blog/index.php?q=$uri&$args;
    # try_files $uri $uri/ /blog/index.php?q=$uri$args;

    location ~ \.php$ {
      try_files $uri =404;
      include fastcgi_params;
      fastcgi_intercept_errors on;
      fastcgi_index index.php;
      fastcgi_pass blog-test:9000;
      fastcgi_split_path_info ^(/blog)(/.*)$;
      fastcgi_param SCRIPT_FILENAME $request_filename;
      fastcgi_param PATH_INFO $fastcgi_path_info;
    }
  }
}
</code>```

And the log:

```<code>2022/02/09 14:47:25 [error] 32#32: *45 open() "/etc/nginx/html/index.php" failed (2: No such file or directory), client: 10.10.10.10, server: www.test.com, request: "GET /blog/test-post-for-blog/ HTTP/1.1", host: "www.test.com", referrer: "https://www.test.com/blog/"
10.10.10.10 - admin [09/Feb/2022:14:47:25 +0000] "GET /blog/test-post-for-blog/ HTTP/1.1" 404 187 "https://www.test.com/blog/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36"
</code>```

Checking the logs, it seems to look into the wrong place, which is /etc/nginx/html/index.php, but if I add the alias in the php location block, then the homepage will stop working as well, which gets me a bit confused.

Currently, I'm not quite sure if the problem is the alias in the blog block ( nginx recommends not using alias together with try_files, apparently due to a bug ), or anything else. If it is indeed the alias directive, I'll try to add root, together with some rewrite rules to avoid modifying the file structure.

It really took me more than it should to figure it out, and still can not actually understand what might be the issue here.

UPDATE 1 :

This is extremely odd. With the following blog config, separating the php location from the blog, the WP posts are accesible, but not the homepage and admin, returning 404:

```<code>  location /blog {
    alias /var/www/html;
    try_files $uri $uri/ /index.php?$args;
  }

  location ~ \.php$ {
    alias /var/www/html;
    try_files $uri =404;
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_pass blog-test:9000;
    fastcgi_split_path_info ^(/blog)(/.*)$;
    fastcgi_param SCRIPT_FILENAME $request_filename;
    fastcgi_param PATH_INFO $fastcgi_path_info;
  }
</code>```

UPDATE 2 :

Now this works ( the blog and the posts can be accesed ) , but the admin seems to be going into a redirect loop:

```<code>  location /blog {
    alias /var/www/html;
    index index.php;
    try_files $uri $uri/ /blog/index.php?q=$uri&$args;
  }

  location ~ \.php$ {
    alias /var/www/html;
    try_files $uri $uri/ /index.php?$args;
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_pass blog-test:9000;
    fastcgi_param SCRIPT_FILENAME $request_filename;
  }
</code>```

UPDATE 3 & FIX :

This apparently works, but the config seems to be really unpleasant and unoptimised. If I try to nest the php location into the blog block, then the php files will download instead of rendering. If I try to use alias instead of root, some pages will not show resulting in 404. In any case, this seems to be functional:

```<code>  root /var/www/html;
  index index.php;

  location /blog {
    rewrite ^/blog(.*)$ /$1 break;
    try_files $uri $uri/ /blog/index.php?$args;
  }

  location ~ \.php$ {
    rewrite ^/blog(.*)$ $1 break;
    fastcgi_pass blog-test:9000;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_split_path_info ^(/blog)(/.*)$;
    fastcgi_param SCRIPT_FILENAME $request_filename;
    fastcgi_param PATH_INFO $fastcgi_path_info;
  }
</code>```

答:
Outside the /blog dir you might also have php files. There should be a separate block for the wordpress install that has the same settings, but then for the blog dir.

This could be the block for wordpress (tested in Docker)

```<code>  location /blog {
    try_files $uri $uri/ /blog/index.php?$args;

    location ~ \.php$ {
      fastcgi_split_path_info ^/blog/(.+\.php)(/.+)$;
      fastcgi_pass wp:9000;
      fastcgi_index index.php;
      include fastcgi_params;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      fastcgi_param SCRIPT_NAME $fastcgi_script_name;
    }
  }
</code>```

So your complete nginx config would look like this:

```<code>server {
  listen 80;
  listen [::]:80;

  server_name www.test.com;
  root /var/www/html;
  index index.php;

  location ^~ /media {
    alias /var/local/test/static/media;
  }

  location ^~ /icons {
    alias /var/local/test/static/icons;
  }

  # This is for Wordpress
  location /blog {
    try_files $uri $uri/ /blog/index.php?$args;

    location ~ \.php$ {
      fastcgi_split_path_info ^/blog/(.+\.php)(/.+)$;
      fastcgi_pass wp:9000;
      fastcgi_index index.php;
      include fastcgi_params;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      fastcgi_param SCRIPT_NAME $fastcgi_script_name;
    }
  }

  # This is for php files in the root. If there is no php to be parsed there you could leave these blocks out.
  location / {
    try_files $uri $uri/ /index.php?$args;
  }

  location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass wp:9000;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param SCRIPT_NAME $fastcgi_script_name;
  }
}
</code>```

UPDATE: I added a root and index property to the nginx server config.

Body:
After adding various configurations into the Wordpress subdirectory, I can access without any issues the WP homepage, but I'm still not able to access the posts, returning 404.

www.test.com/blog - WP homepage, works perfectly fine

www.test.com/blog/test-post-for-blog - WP Post, 404

Here is the config:

server {
  listen 80;
  listen [::]:80;

  server_name www.test.com;

  location ^~ /media {
    alias /var/local/test/static/media;
  }

  location ^~ /icons {
    alias /var/local/test/static/icons;
  }

  location /blog {
    alias /var/www/html;
    index  index.html index.htm index.php;
    try_files $uri $uri/ /blog/index.php?$args /blog/index.php?q=$uri&$args;
    # try_files $uri $uri/ /blog/index.php?q=$uri$args;

    location ~ \.php$ {
      try_files $uri =404;
      include fastcgi_params;
      fastcgi_intercept_errors on;
      fastcgi_index index.php;
      fastcgi_pass blog-test:9000;
      fastcgi_split_path_info ^(/blog)(/.*)$;
      fastcgi_param SCRIPT_FILENAME $request_filename;
      fastcgi_param PATH_INFO $fastcgi_path_info;
    }
  }
}

And the log:

2022/02/09 14:47:25 [error] 32#32: *45 open() "/etc/nginx/html/index.php" failed (2: No such file or directory), client: 10.10.10.10, server: www.test.com, request: "GET /blog/test-post-for-blog/ HTTP/1.1", host: "www.test.com", referrer: "https://www.test.com/blog/"
10.10.10.10 - admin [09/Feb/2022:14:47:25 +0000] "GET /blog/test-post-for-blog/ HTTP/1.1" 404 187 "https://www.test.com/blog/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36"

Checking the logs, it seems to look into the wrong place, which is /etc/nginx/html/index.php, but if I add the alias in the php location block, then the homepage will stop working as well, which gets me a bit confused.

Currently, I'm not quite sure if the problem is the alias in the blog block ( nginx recommends not using alias together with try_files, apparently due to a bug ), or anything else. If it is indeed the alias directive, I'll try to add root, together with some rewrite rules to avoid modifying the file structure.

It really took me more than it should to figure it out, and still can not actually understand what might be the issue here.

UPDATE 1 :

This is extremely odd. With the following blog config, separating the php location from the blog, the WP posts are accesible, but not the homepage and admin, returning 404:

  location /blog {
    alias /var/www/html;
    try_files $uri $uri/ /index.php?$args;
  }

  location ~ \.php$ {
    alias /var/www/html;
    try_files $uri =404;
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_pass blog-test:9000;
    fastcgi_split_path_info ^(/blog)(/.*)$;
    fastcgi_param SCRIPT_FILENAME $request_filename;
    fastcgi_param PATH_INFO $fastcgi_path_info;
  }

UPDATE 2 :

Now this works ( the blog and the posts can be accesed ) , but the admin seems to be going into a redirect loop:

  location /blog {
    alias /var/www/html;
    index index.php;
    try_files $uri $uri/ /blog/index.php?q=$uri&$args;
  }

  location ~ \.php$ {
    alias /var/www/html;
    try_files $uri $uri/ /index.php?$args;
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_pass blog-test:9000;
    fastcgi_param SCRIPT_FILENAME $request_filename;
  }

UPDATE 3 & FIX :

This apparently works, but the config seems to be really unpleasant and unoptimised. If I try to nest the php location into the blog block, then the php files will download instead of rendering. If I try to use alias instead of root, some pages will not show resulting in 404. In any case, this seems to be functional:

  root /var/www/html;
  index index.php;

  location /blog {
    rewrite ^/blog(.*)$ /$1 break;
    try_files $uri $uri/ /blog/index.php?$args;
  }

  location ~ \.php$ {
    rewrite ^/blog(.*)$ $1 break;
    fastcgi_pass blog-test:9000;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_split_path_info ^(/blog)(/.*)$;
    fastcgi_param SCRIPT_FILENAME $request_filename;
    fastcgi_param PATH_INFO $fastcgi_path_info;
  }

Body:
Outside the /blog dir you might also have php files. There should be a separate block for the wordpress install that has the same settings, but then for the blog dir.

This could be the block for wordpress (tested in Docker)

  location /blog {
    try_files $uri $uri/ /blog/index.php?$args;

    location ~ \.php$ {
      fastcgi_split_path_info ^/blog/(.+\.php)(/.+)$;
      fastcgi_pass wp:9000;
      fastcgi_index index.php;
      include fastcgi_params;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      fastcgi_param SCRIPT_NAME $fastcgi_script_name;
    }
  }

So your complete nginx config would look like this:

server {
  listen 80;
  listen [::]:80;

  server_name www.test.com;
  root /var/www/html;
  index index.php;

  location ^~ /media {
    alias /var/local/test/static/media;
  }

  location ^~ /icons {
    alias /var/local/test/static/icons;
  }

  # This is for Wordpress
  location /blog {
    try_files $uri $uri/ /blog/index.php?$args;

    location ~ \.php$ {
      fastcgi_split_path_info ^/blog/(.+\.php)(/.+)$;
      fastcgi_pass wp:9000;
      fastcgi_index index.php;
      include fastcgi_params;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      fastcgi_param SCRIPT_NAME $fastcgi_script_name;
    }
  }

  # This is for php files in the root. If there is no php to be parsed there you could leave these blocks out.
  location / {
    try_files $uri $uri/ /index.php?$args;
  }

  location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass wp:9000;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param SCRIPT_NAME $fastcgi_script_name;
  }
}

UPDATE: I added a root and index property to the nginx server config.