问:
Odata , .Net 6 And Inheriting Controllers
Assume we create a sample app, let's call it MyOdataApp:
I am unable to dynamically create controllers for these two models which you see in the Program.cs, I also have no errors to tell my where I have gone awry.
What's in these models is irrelavant, let's assume they are: Order & LineItem

```<code>namespace MyOdataApp.Models
    {
        public class Order
        {
            public string OrderId { get; set; } = null!;
            public string? CustomerName { get; set; }
            public string? BillingAddress { get; set; }
            public string? ShippingAddress { get; set; }
            public decimal? SubTotal { get; set; }
            public string? Currency { get; set; }
            public double? ExchangeRate { get; set; }
            public string? Status { get; set; }
            public DateTimeOffset CreateTs { get; set; }

            public virtual ICollection <LineItem> LineItems { get; set; }
        }

        public class LineItem
        {
            public string LineItemId { get; set; } = null!;
            public string? OrderId { get; set; }
            public int? LineIndex { get; set; }
            public string? Name { get; set; }
            public string? Description { get; set; }
            public int? Quantity { get; set; }
            public decimal? UnitPrice { get; set; }
            public double? Discount { get; set; }
            public DateTimeOffset CreateTs { get; set; }

            public virtual Order? Order { get; set; }
        }
    }
</code>```

Here's my code: Program.cs

```<code>static IEdmModel GetEdmModel()
    {
        Microsoft.OData.ModelBuilder.ODataConventionModelBuilder builder = new();
        builder.EntitySet(nameof(MyOdataApp.Models.Order));
        builder.EntitySet(nameof(MyOdataApp.Models.LineItem));
        return builder.GetEdmModel();
    }

    builder.Services.AddControllers()
        .AddOData(opt => opt.EnableQueryFeatures().AddRouteComponents("odata", GetEdmModel()).Expand())
        .ConfigureApplicationPartManager(p => p.FeatureProviders.Add(new Controllers.GenericControllerFeatureProvider()));
</code>```

OdataTemplateController.cs

```<code>using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.OData.Query;
    using Microsoft.EntityFrameworkCore;

    namespace Controllers;

    [GenericControllerName]
    [Route("odata/[Controller]")]
    public abstract class OdataTemplateController<T> : Microsoft.AspNetCore.OData.Routing.Controllers.ODataController
    {
        public readonly DbContext _context;
        public readonly ILogger<T> _logger;

        public OdataTemplateController(ILogger<T> logger, DbContext context)
        {
            _context = context;
            _logger = logger;
        }

        [EnableQuery]
        public virtual IQueryable Get() where T : class => _context.Set().AsQueryable();
    }
</code>```

GenericControllerFeature.cs

```<code>using Microsoft.AspNetCore.Mvc.ApplicationParts;
    using Microsoft.AspNetCore.Mvc.Controllers;
    using System.Reflection;

    namespace Controllers;

    public class GenericControllerFeatureProvider : IApplicationFeatureProvider
    {
        public void PopulateFeature(IEnumerable parts, ControllerFeature feature)
        {
            var sysParts = parts.First() as dynamic;
            foreach (TypeInfo entityType in sysParts.Types)
            {
                if (entityType.FullName!.StartsWith("MyOdataApp.Models") && !feature.Controllers.Any(t => t.Name == entityType.Name))
                {
                    feature.Controllers.Add(typeof(OdataTemplateController<>)
                            .MakeGenericType(entityType.AsType())
                            .GetTypeInfo());

                }
            }
        }
    }
</code>```

GenericControllerNameAttribute.cs

```<code>using Microsoft.AspNetCore.Mvc.ApplicationModels;

    namespace Controllers;
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class GenericControllerNameAttribute : Attribute, IControllerModelConvention
    {
        public void Apply(ControllerModel controller)
        {
            if (controller.ControllerType.Name == "OdataTemplateController`1")
                controller.ControllerName = controller.ControllerType.GenericTypeArguments[0].Name;

        }
    }
</code>```

Now, aside from some very poor choices like using the (literal) Name ("OdataTemplateController`1") of the ControllerType and taking shortcuts like StartsWith "MyOdataApp.Models" which you can beat/ whip me for later... ...What am I doing wrong?

I noticed the Edm relationships are perfect at /$metadata but the (ControllerFeature) features is only injecting the MetadataController and nothing else. Could this be the problem?

Please help :)

答:
The main issue here is that you are trying to resolve the Entity Types from the parts, but I cannot see where you have registered a resolver for these types. It might be easier to enumerate the DbSet<> definitions on the DbContext (if you have registered them) or you could enumerate all types in the MyOdataApp.Models namespace;

Looking at this implementation on SO, you can see that they have separately constructed an EntityTypes provider singleton, there are various other techniques, but it is important that those controller instance get created.

I noticed the Edm relationships are perfect at /$metadata

The Edm is provided by the IEdmModel, it will show the correct schema even if you have no controllers defined. By explicityly adding the builder.EntitySet() definitions the convention model builder does not resolve from the available routes, that takes too long at runtime anyway, but if the routes are not available then the requests will result in 404s, or if the builder and routes do not match correctly you may also experience 503s.

I have had more long-term success in creating concrete stubs that match the expected names of the controllers that inherit from the base controller. So bypassing the GenericControllerFeatureProvider. Without whipping you for all the other crimes against C#, this gives you a good hybrid approach that allows you to quickly implement customizations on specific controllers when you need them, otherwise I would recommend modifying the GenericControllerFeatureProvider to only create controllers for the types that do not already have a controller implementation.

I use T4 templates to generate the controller stubs and extend them through partial classes when or if I need to.

Body:
Assume we create a sample app, let's call it MyOdataApp:
I am unable to dynamically create controllers for these two models which you see in the Program.cs, I also have no errors to tell my where I have gone awry.
What's in these models is irrelavant, let's assume they are: Order & LineItem

namespace MyOdataApp.Models
    {
        public class Order
        {
            public string OrderId { get; set; } = null!;
            public string? CustomerName { get; set; }
            public string? BillingAddress { get; set; }
            public string? ShippingAddress { get; set; }
            public decimal? SubTotal { get; set; }
            public string? Currency { get; set; }
            public double? ExchangeRate { get; set; }
            public string? Status { get; set; }
            public DateTimeOffset CreateTs { get; set; }

            public virtual ICollection <LineItem> LineItems { get; set; }
        }

        public class LineItem
        {
            public string LineItemId { get; set; } = null!;
            public string? OrderId { get; set; }
            public int? LineIndex { get; set; }
            public string? Name { get; set; }
            public string? Description { get; set; }
            public int? Quantity { get; set; }
            public decimal? UnitPrice { get; set; }
            public double? Discount { get; set; }
            public DateTimeOffset CreateTs { get; set; }

            public virtual Order? Order { get; set; }
        }
    }

Here's my code: Program.cs

static IEdmModel GetEdmModel()
    {
        Microsoft.OData.ModelBuilder.ODataConventionModelBuilder builder = new();
        builder.EntitySet(nameof(MyOdataApp.Models.Order));
        builder.EntitySet(nameof(MyOdataApp.Models.LineItem));
        return builder.GetEdmModel();
    }

    builder.Services.AddControllers()
        .AddOData(opt => opt.EnableQueryFeatures().AddRouteComponents("odata", GetEdmModel()).Expand())
        .ConfigureApplicationPartManager(p => p.FeatureProviders.Add(new Controllers.GenericControllerFeatureProvider()));

OdataTemplateController.cs

using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.OData.Query;
    using Microsoft.EntityFrameworkCore;

    namespace Controllers;

    [GenericControllerName]
    [Route("odata/[Controller]")]
    public abstract class OdataTemplateController<T> : Microsoft.AspNetCore.OData.Routing.Controllers.ODataController
    {
        public readonly DbContext _context;
        public readonly ILogger<T> _logger;

        public OdataTemplateController(ILogger<T> logger, DbContext context)
        {
            _context = context;
            _logger = logger;
        }

        [EnableQuery]
        public virtual IQueryable Get() where T : class => _context.Set().AsQueryable();
    }

GenericControllerFeature.cs

using Microsoft.AspNetCore.Mvc.ApplicationParts;
    using Microsoft.AspNetCore.Mvc.Controllers;
    using System.Reflection;

    namespace Controllers;

    public class GenericControllerFeatureProvider : IApplicationFeatureProvider
    {
        public void PopulateFeature(IEnumerable parts, ControllerFeature feature)
        {
            var sysParts = parts.First() as dynamic;
            foreach (TypeInfo entityType in sysParts.Types)
            {
                if (entityType.FullName!.StartsWith("MyOdataApp.Models") && !feature.Controllers.Any(t => t.Name == entityType.Name))
                {
                    feature.Controllers.Add(typeof(OdataTemplateController<>)
                            .MakeGenericType(entityType.AsType())
                            .GetTypeInfo());

                }
            }
        }
    }

GenericControllerNameAttribute.cs

using Microsoft.AspNetCore.Mvc.ApplicationModels;

    namespace Controllers;
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class GenericControllerNameAttribute : Attribute, IControllerModelConvention
    {
        public void Apply(ControllerModel controller)
        {
            if (controller.ControllerType.Name == "OdataTemplateController`1")
                controller.ControllerName = controller.ControllerType.GenericTypeArguments[0].Name;

        }
    }

Now, aside from some very poor choices like using the (literal) Name ("OdataTemplateController`1") of the ControllerType and taking shortcuts like StartsWith "MyOdataApp.Models" which you can beat/ whip me for later... ...What am I doing wrong?

I noticed the Edm relationships are perfect at /$metadata but the (ControllerFeature) features is only injecting the MetadataController and nothing else. Could this be the problem?

Please help :)


来源: stackexchange

问:
Nginx docker container exits with error “fopen:No such file or directory:fopen('/etc/nginx/ssl/live/test.example.dev/fullchain.pem'” in Ubuntu 20.04
Okay so I'm learning Docker and I am trying to deploy a test app with a subdomain (who's domain was bought from another provider) which is pointing to my server. The server already has non-dockerized Nginx setup which serves couple of other non-dockerized apps perfectly. And that part means Nginx is already using port 80 and 443. It's also worth mentioning that the subdomain's main domain (example.dev) has a non-dockerized app with active SSL cert from Let's Encrypt already running in the server. And now the subdomain (test.example.dev) somehow shows Nginx default page when visited. This is my server situation. Now let me explain what happens with Nginx and Certbot in a dockerized app.

The app is using 4 images to create 4 containers: Nodejs, Mongodb, Nginx and Certbot(for SSL). Before adding Certbot, I could perfectly access the app with :. But now I need to attach that subdomain (test.example.dev) to my app with Let's Encrypt SSL certificates.

So after the build is done with Docker Compose, I see that Nginx and Certbot is exited with errors.

This is my nginx/default.conf file:

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

    server_name test.example.dev;
    server_tokens off;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://test.example.dev$request_uri;
    }
}

server {
    listen 443 default_server ssl http2;
    listen [::]:443 ssl http2;

    server_name test.example.dev;

    ssl_certificate /etc/nginx/ssl/live/test.example.dev/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/live/test.example.dev/privkey.pem;

    location /api {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://practice-app:3050;
        proxy_redirect off;

    }
}
</code>```

And here’s my docker-compose.yml file:

```<code>version: '3'
services:

  practice-app:
    build:
      context: .
      args:
        NODE_ENV: production
    environment:
      - NODE_ENV=production
    command: node index.js
    depends_on:
      - mongo

  nginx:
    image: nginx:stable-alpine
    ports:
      - "4088:80"
    volumes:
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
      - ./certbot/www:/var/www/certbot/:ro
      - ./certbot/conf/:/etc/nginx/ssl/:ro

  certbot:
    image: certbot/certbot:latest
    volumes:
      - ./certbot/www/:/var/www/certbot/:rw
      - ./certbot/conf/:/etc/letsencrypt/:rw
    depends_on:
      - nginx

  mongo:
    image: mongo:4.4.6
    environment:
      - MONGO_INITDB_ROOT_USERNAME=test
      - MONGO_INITDB_ROOT_PASSWORD=test
    volumes:
      - mongo-db:/data/db

volumes:
  mongo-db:

</code>```

Nginx logs says:

```<code>/docker-entrypoint.sh: Configuration complete; ready for start up
2022/01/31 13:42:28 [emerg] 1#1: cannot load certificate "/etc/nginx/ssl/live/test.example.dev/fullchain.pem": BIO_new_file() failed (SSL: error:02001002:system library:fopen:No such file or directory:fopen('/etc/nginx/ssl/live/test.example.dev/fullchain.pem','r') error:2006D080:BIO routines:BIO_new_file:no such file)
nginx: [emerg] cannot load certificate "/etc/nginx/ssl/live/test.example.dev/fullchain.pem": BIO_new_file() failed (SSL: error:02001002:system library:fopen:No such file or directory:fopen('/etc/nginx/ssl/live/test.example.dev/fullchain.pem','r') error:2006D080:BIO routines:BIO_new_file:no such file)
</code>```

And Certbot logs says:

```<code>Saving debug log to /var/log/letsencrypt/letsencrypt.log
Certbot doesn't know how to automatically configure the web server on this system. However, it can still get a certificate for you. Please run "certbot certonly" to do so. You'll need to manually configure your web server to use the resulting certificate.
</code>```

But after adding the following code:

```<code>command: certonly --webroot -w /var/www/certbot --force-renewal --email example@gmail.com -d test.example.dev --agree-tos
</code>```

under certbot service, the log changed to this:

```<code>[17:00] [server1.com test] # docker logs test_certbot_1

Requesting a certificate for test.example.dev

Certbot failed to authenticate some domains (authenticator: webroot). The Certificate Authority reported these problems:
  Domain: test.example.dev
  Type:   unauthorized
  Detail: Invalid response from http://test.example.dev/.well-known/acme-challenge/HCFXwB1BXb-provr8lr6mJCDG9LRoGbVV0e9BWiiwAo [63.250.33.76]: "<html>\r\n<head><title>404 Not Found</title></head>\r\n<body>\r\n<center><h1>404 Not Found</h1></center>\r\n<hr><center>nginx</center>\r\n"

Hint: The Certificate Authority failed to download the temporary challenge files created by Certbot. Ensure that the listed domains serve their content from the provided --webroot-path/-w and that files created there can be downloaded from the internet.

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Some challenges have failed.
Ask for help or search for solutions at https://community.letsencrypt.org. See the logfile /var/log/letsencrypt/letsencrypt.log or re-run Certbot with -v for more details.

</code>```

What am I doing wrong here? Please give me a beginner friendly solution as I am new to DevOps.

答:
You have some mistakes in your docker-compose file. Your nginx should be linked with Practice_app not on nginx and your practice app should open the port 3050 in here.</p>
```<code>version: '3'
services:

  practice-app:
    build:
      context: .
      args:
        NODE_ENV: production
    environment:
      - NODE_ENV=production
    command: node index.js
    ports:
    - "3050:3050"
    depends_on:
      - mongo

  nginx:
    image: nginx:stable-alpine
    ports:
      - "4088:80"
    volumes:
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
      - ./certbot/www:/var/www/certbot/:ro
      - ./certbot/conf/:/etc/nginx/ssl/:ro
    links:
      - practice-app

  certbot:
    image: certbot/certbot:latest
    volumes:
      - ./certbot/www/:/var/www/certbot/:rw
      - ./certbot/conf/:/etc/letsencrypt/:rw
    depends_on:
      - nginx

  mongo:
    image: mongo:4.4.6
    environment:
      - MONGO_INITDB_ROOT_USERNAME=test
      - MONGO_INITDB_ROOT_PASSWORD=test
    volumes:
      - mongo-db:/data/db

volumes:
  mongo-db:

</code>```

ContentLicense: CC BY-SA 4.0

Body:
Okay so I'm learning Docker and I am trying to deploy a test app with a subdomain (who's domain was bought from another provider) which is pointing to my server. The server already has non-dockerized Nginx setup which serves couple of other non-dockerized apps perfectly. And that part means Nginx is already using port 80 and 443. It's also worth mentioning that the subdomain's main domain (example.dev) has a non-dockerized app with active SSL cert from Let's Encrypt already running in the server. And now the subdomain (test.example.dev) somehow shows Nginx default page when visited. This is my server situation. Now let me explain what happens with Nginx and Certbot in a dockerized app.

The app is using 4 images to create 4 containers: Nodejs, Mongodb, Nginx and Certbot(for SSL). Before adding Certbot, I could perfectly access the app with :. But now I need to attach that subdomain (test.example.dev) to my app with Let's Encrypt SSL certificates.

So after the build is done with Docker Compose, I see that Nginx and Certbot is exited with errors.

This is my nginx/default.conf file:

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

    server_name test.example.dev;
    server_tokens off;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://test.example.dev$request_uri;
    }
}

server {
    listen 443 default_server ssl http2;
    listen [::]:443 ssl http2;

    server_name test.example.dev;

    ssl_certificate /etc/nginx/ssl/live/test.example.dev/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/live/test.example.dev/privkey.pem;

    location /api {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://practice-app:3050;
        proxy_redirect off;

    }
}

And here’s my docker-compose.yml file:

version: '3'
services:

  practice-app:
    build:
      context: .
      args:
        NODE_ENV: production
    environment:
      - NODE_ENV=production
    command: node index.js
    depends_on:
      - mongo

  nginx:
    image: nginx:stable-alpine
    ports:
      - "4088:80"
    volumes:
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
      - ./certbot/www:/var/www/certbot/:ro
      - ./certbot/conf/:/etc/nginx/ssl/:ro

  certbot:
    image: certbot/certbot:latest
    volumes:
      - ./certbot/www/:/var/www/certbot/:rw
      - ./certbot/conf/:/etc/letsencrypt/:rw
    depends_on:
      - nginx

  mongo:
    image: mongo:4.4.6
    environment:
      - MONGO_INITDB_ROOT_USERNAME=test
      - MONGO_INITDB_ROOT_PASSWORD=test
    volumes:
      - mongo-db:/data/db

volumes:
  mongo-db:

Nginx logs says:

/docker-entrypoint.sh: Configuration complete; ready for start up
2022/01/31 13:42:28 [emerg] 1#1: cannot load certificate "/etc/nginx/ssl/live/test.example.dev/fullchain.pem": BIO_new_file() failed (SSL: error:02001002:system library:fopen:No such file or directory:fopen('/etc/nginx/ssl/live/test.example.dev/fullchain.pem','r') error:2006D080:BIO routines:BIO_new_file:no such file)
nginx: [emerg] cannot load certificate "/etc/nginx/ssl/live/test.example.dev/fullchain.pem": BIO_new_file() failed (SSL: error:02001002:system library:fopen:No such file or directory:fopen('/etc/nginx/ssl/live/test.example.dev/fullchain.pem','r') error:2006D080:BIO routines:BIO_new_file:no such file)

And Certbot logs says:

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Certbot doesn't know how to automatically configure the web server on this system. However, it can still get a certificate for you. Please run "certbot certonly" to do so. You'll need to manually configure your web server to use the resulting certificate.

But after adding the following code:

command: certonly --webroot -w /var/www/certbot --force-renewal --email example@gmail.com -d test.example.dev --agree-tos

under certbot service, the log changed to this:

[17:00] [server1.com test] # docker logs test_certbot_1

Requesting a certificate for test.example.dev

Certbot failed to authenticate some domains (authenticator: webroot). The Certificate Authority reported these problems:
  Domain: test.example.dev
  Type:   unauthorized
  Detail: Invalid response from http://test.example.dev/.well-known/acme-challenge/HCFXwB1BXb-provr8lr6mJCDG9LRoGbVV0e9BWiiwAo [63.250.33.76]: "\r\n<title>404 Not Found</title>\r\n\r\n
404 Not Found
\r\n
nginx\r\n"

Hint: The Certificate Authority failed to download the temporary challenge files created by Certbot. Ensure that the listed domains serve their content from the provided --webroot-path/-w and that files created there can be downloaded from the internet.

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Some challenges have failed.
Ask for help or search for solutions at https://community.letsencrypt.org. See the logfile /var/log/letsencrypt/letsencrypt.log or re-run Certbot with -v for more details.

What am I doing wrong here? Please give me a beginner friendly solution as I am new to DevOps.

Body:
You have some mistakes in your docker-compose file. Your nginx should be linked with Practice_app not on nginx and your practice app should open the port 3050 in here.

version: '3'
services:

  practice-app:
    build:
      context: .
      args:
        NODE_ENV: production
    environment:
      - NODE_ENV=production
    command: node index.js
    ports:
    - "3050:3050"
    depends_on:
      - mongo

  nginx:
    image: nginx:stable-alpine
    ports:
      - "4088:80"
    volumes:
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
      - ./certbot/www:/var/www/certbot/:ro
      - ./certbot/conf/:/etc/nginx/ssl/:ro
    links:
      - practice-app

  certbot:
    image: certbot/certbot:latest
    volumes:
      - ./certbot/www/:/var/www/certbot/:rw
      - ./certbot/conf/:/etc/letsencrypt/:rw
    depends_on:
      - nginx

  mongo:
    image: mongo:4.4.6
    environment:
      - MONGO_INITDB_ROOT_USERNAME=test
      - MONGO_INITDB_ROOT_PASSWORD=test
    volumes:
      - mongo-db:/data/db

volumes:
  mongo-db:


问:
Idle's Code Context in Eclipse
I find the Code Context option of IDLE to be extremely useful when working on big projects.
I wanted to know if there is a similar feature for Eclipse?

Edit:
I would like this feature in CDT and/or PyDev.

Example image:
http://i38.tinypic.com/95sb39.jpg

答:
That's still not available for PyDev... for now you can either use the outline view and leave it synchronized with the editor or you can use the quick outline (ctrl+O) as it'll focus which method you're in (I know it's not really a substitute, but until the the 'breadcrumb' feature is not added, that's probably the best way to know where you are).

Note that this is for PyDev 2.2.1 (please keep an eye on the upcoming releases as this feature is close to being implemented).

ContentLicense: CC BY-SA 2.5

Title: Idle's Code Context in Eclipse

ContentLicense: CC BY-SA 3.0


问:
What exactly is undefined in accessing out of bound of array?
Let's say I have the following array

```<code>unsigned char array[5];
</code>```

So I'm trying to understand what exactly is undefined in accessing

```<code>array[6]
</code>```

for my understanding, the compiler will try to read the value inside *(array+6), so it is defined. So, if I understand right, what is undefined is what happens when you try to read uninitialized memory.

If this is the case, then the top answer here says that reading uninitialized value is defined unless you have trap representation, but we know that unsigned char does not have that.

So is it defined well here? Will it always read the *(array+6)?

答:
I'm trying to understand what exactly is undefined in accessing

array[6]

Per C 2018 3.4.3, “undefined behavior” means the C standard imposes no requirements. So, undefined behavior is not a specific thing; it means there is a complete lack of the C standard saying what should or should not happen.

array[6] is undefined because arithmetic outside of array bounds is not defined.  array[6] is specified to be equivalent to *(array+6), and addition to a pointer is specified in C 2018 6.5.6 8.  It says that additions that result in pointing to an element in the array or one beyond the last element are defined, but “otherwise, the behavior is undefined.” So array[6] has undefined behavior because the C standard explicitly says so.

If we consider that other case, pointing one beyond the last array element, then array+5 is defined. However *(array+5) is not defined, because C 2018 6.5.6 8 tells us that, while array+5 points to the location just beyond the last element of the array, the * operator shall not be applied to it:

If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.

In this context (a paragraph of the standard that is not one of the “Constraints” paragraphs), violating a “shall not” rule means the behavior is undefined, because C 2018 4 2 says:

If a "shall" or "shall not" requirement that appears outside of a constraint or runtime-constraint is violated, the behavior is undefined…

So, exactly what causes this to be undefined is that it violates an explicit rule of the standard, and violating that rule means the behavior is undefined.

for my understanding, the compiler will try to read the value inside * (array+6) so it is defined,…

No, *(array+i) refers to element i of the array array when the behavior is defined. When the behavior is not defined, it does not have any meaning.

… so if I understand right, what is undefined is what happens when you try to read uninitialized memory.

The rules around this are complicated, and they are not actually relevant here. Since *(array+6) is undefined, it does not mean to read memory. It has no meaning as far as the C standard is concerned.

When the compiler is compiling code and encounters *(array+6) used as a value, it will ordinarily generate instructions to get the value of element 6 of the array. By “ordinarily,” I mean when the behavior is defined. However, modern compiler are not simplistic code generators. They perform semantic analysis and optimization of the program. Instead of reading code and generating instructions, they read code and generate a semantic representation of the program. That semantic representation and the rules of the C standard are operated on by optimizing software. Once the optimizing software is done, then instructions are generated. In this process, the semantic analyzer may determine that *(array+6) has no meaning, and then the optimizer will strip it away. It will not generate code to load from the memory that array+6 would reference if things were different.

This is useful when there is code such as:

```<code>if (some test)
{
    x = array[6];
    various code;
}
else
{
    x = array[3];
    various code;
}
</code>```

When the compiler can deduce in a certain situation that array[6]is not defined, then it can conclude that the only defined path through this code is if some test is false. It can then generate the code for the “else” case and remove the code for the “then” case.

Logically, this is equivalent to “Since the behavior of the code in the ‘then’ case is not defined, it can be anything. If we choose to make it the same as the code in the ‘else’ case, then we can use the same instructions for both cases, so we do not need to branch based on some test and will have smaller code. This conforms to the C standard, because it does not define what the ‘then’ case does.”

Body:
Let's say I have the following array

unsigned char array[5];

So I'm trying to understand what exactly is undefined in accessing

array[6]

for my understanding, the compiler will try to read the value inside *(array+6), so it is defined. So, if I understand right, what is undefined is what happens when you try to read uninitialized memory.

If this is the case, then the top answer here says that reading uninitialized value is defined unless you have trap representation, but we know that unsigned char does not have that.

So is it defined well here? Will it always read the *(array+6)?

Body:
I'm trying to understand what exactly is undefined in accessing

array[6]

Per C 2018 3.4.3, “undefined behavior” means the C standard imposes no requirements. So, undefined behavior is not a specific thing; it means there is a complete lack of the C standard saying what should or should not happen.

array[6] is undefined because arithmetic outside of array bounds is not defined.  array[6] is specified to be equivalent to *(array+6), and addition to a pointer is specified in C 2018 6.5.6 8.  It says that additions that result in pointing to an element in the array or one beyond the last element are defined, but “otherwise, the behavior is undefined.” So array[6] has undefined behavior because the C standard explicitly says so.

If we consider that other case, pointing one beyond the last array element, then array+5 is defined. However *(array+5) is not defined, because C 2018 6.5.6 8 tells us that, while array+5 points to the location just beyond the last element of the array, the * operator shall not be applied to it:

If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.

In this context (a paragraph of the standard that is not one of the “Constraints” paragraphs), violating a “shall not” rule means the behavior is undefined, because C 2018 4 2 says:

If a "shall" or "shall not" requirement that appears outside of a constraint or runtime-constraint is violated, the behavior is undefined…

So, exactly what causes this to be undefined is that it violates an explicit rule of the standard, and violating that rule means the behavior is undefined.

for my understanding, the compiler will try to read the value inside * (array+6) so it is defined,…

No, *(array+i) refers to element i of the array array when the behavior is defined. When the behavior is not defined, it does not have any meaning.

… so if I understand right, what is undefined is what happens when you try to read uninitialized memory.

The rules around this are complicated, and they are not actually relevant here. Since *(array+6) is undefined, it does not mean to read memory. It has no meaning as far as the C standard is concerned.

When the compiler is compiling code and encounters *(array+6) used as a value, it will ordinarily generate instructions to get the value of element 6 of the array. By “ordinarily,” I mean when the behavior is defined. However, modern compiler are not simplistic code generators. They perform semantic analysis and optimization of the program. Instead of reading code and generating instructions, they read code and generate a semantic representation of the program. That semantic representation and the rules of the C standard are operated on by optimizing software. Once the optimizing software is done, then instructions are generated. In this process, the semantic analyzer may determine that *(array+6) has no meaning, and then the optimizer will strip it away. It will not generate code to load from the memory that array+6 would reference if things were different.

This is useful when there is code such as:

if (some test)
{
    x = array[6];
    various code;
}
else
{
    x = array[3];
    various code;
}

When the compiler can deduce in a certain situation that array[6]is not defined, then it can conclude that the only defined path through this code is if some test is false. It can then generate the code for the “else” case and remove the code for the “then” case.

Logically, this is equivalent to “Since the behavior of the code in the ‘then’ case is not defined, it can be anything. If we choose to make it the same as the code in the ‘else’ case, then we can use the same instructions for both cases, so we do not need to branch based on some test and will have smaller code. This conforms to the C standard, because it does not define what the ‘then’ case does.”


问:
How to programmatically get asset catalog color variants from Xcode 13 in SwiftUI / Swift5.5?
I have a color asset catalog in Xcode 13 that defines a set of colors in both light ("Any") and dark ("Dark") variants. For example:

I would like to programmatically enumerate the different colors, meaning, I'd like to get the color (Color("hkMagenta")) in both variants. Just getting it by name returns the "Any" variant.

How can I get the dark variant?

I had thought this would work:

ColorManager.hkMagenta.environment(\.colorScheme, .dark)

Unfortunately, no-go...

Cannot convert value of type 'some View' to expected element type 'Array<Color>.ArrayLiteralElement' (aka 'Color')

Any ideas?

答:
Thanks to @Asperi for pointing out https://stackoverflow.com/a/66950858/12299030.

TL;DR is, you can get the light and dark variants using UIColor.resolvedColor() like so:

let c = Color(UIColor(named: "hkMagenta")!.resolvedColor(with: UITraitCollection(userInterfaceStyle: .dark)))


问:
Ansible playbook with "replace" and "after" marching lines that are not directly after
A simple playbook code intended to update dhcpcd

---
- name: Set ES heap min
  hosts: local

  tasks:
    - name: test task
      replace:
        path: /home/pedro/ansible_test/test.conf
        after: 'interface eth0'
        regexp: '^static ip_address=[0-9 ]*\.[0-9 ]*\.[0-9 ]*\.[0-9 ]*\/[0-9 ]*'
        replace: "static ip_address={{ ip_address }}/24"
        backup: yes

```
<p>The idea is to update an IP of a particular interface (in this case eth0)
(note my regex needs improvement but has no effect on what is happening)</p>
<p>So it works OK as log as the other interface is commented out, else it will update the line <code>static ip_address=</code> in all interfaces that as not commented out.</p>
<p>test file:</p>
<pre class="lang-none prettyprint-override"><code># Example static IP configuration:
interface eth0
static ip_address=192.168.1.390/24
static ip6_address=fd51:42f8:caae:d92e::ff/64
static routers=192.168.1.1
static domain_name_servers=192.168.1.1 #8.8.8.8 fd51:42f8:caae:d92e::1

# It is possible to fall back to a static IP if DHCP fails:
# define static profile
#profile static_eth0
#static ip_address=192.168.1.30/24
#static routers=192.168.1.1
#static domain_name_servers=192.168.1.1

# fallback to static profile on eth0
#interface eth0
#fallback static_eth0

</code>```

If like above then profile other than eth0 will not be touched which is desired. However if the line #static ip_address=192.168.1.30/2 would be commented, this line would be also modified, which is undesired.

Looking at the documentation one gets the idea that the line that has "interface eth0" will be identified and ONLY the line with the matching regex will be modified, but that does not seem to be true.

example of result after running with Uncommented line:

# Example static IP configuration:
interface eth0
static ip_address=192.168.1.390/24
static ip6_address=fd51:42f8:caae:d92e::ff/64
static routers=192.168.1.1
static domain_name_servers=192.168.1.1 #8.8.8.8 fd51:42f8:caae:d92e::1

# It is possible to fall back to a static IP if DHCP fails:
# define static profile
#profile static_eth0
static ip_address=192.168.1.390/24
#static routers=192.168.1.1
#static domain_name_servers=192.168.1.1

# fallback to static profile on eth0
#interface eth0
#fallback static_eth0

```
<p>Am I doing something wrong, or am I misinterpreting the documentation, or is this not intended to work as I described, is there a bug ?</p>
<p>Please help me understand</p>
<p>I am running Ansible 1.9 with python 3.8:</p>
```ansible --version
ansible 2.9.6
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/pedro/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.8.10 (default, Nov 26 2021, 20:14:08) [GCC 9.3.0]
```

答:
I understand your use case that you like to update the entry of the first occurrence of static ip_address= only. As already mentioned in the comments, I've found the approach with lineinfile working to replace first occurrence of certain expression in file dhcpcd.conf.

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:
    IP_ADDRESS: "192.0.2.0/24"

  tasks:

  - name: Update IP for eth0
    lineinfile:
      path: /etc/dhcpcd.conf
      regexp: '^static ip_address=[0-9 ]*\.[0-9 ]*\.[0-9 ]*\.[0-9 ]*\/[0-9 ]*'
      line: "static ip_address={{ IP_ADDRESS }}"
      firstmatch: true
      state: present
      backup: true
```

Body:
A simple playbook code intended to update dhcpcd

---
- name: Set ES heap min
  hosts: local

  tasks:
    - name: test task
      replace:
        path: /home/pedro/ansible_test/test.conf
        after: 'interface eth0'
        regexp: '^static ip_address=[0-9 ]*\.[0-9 ]*\.[0-9 ]*\.[0-9 ]*\/[0-9 ]*'
        replace: "static ip_address={{ ip_address }}/24"
        backup: yes

The idea is to update an IP of a particular interface (in this case eth0)
(note my regex needs improvement but has no effect on what is happening)

So it works OK as log as the other interface is commented out, else it will update the line static ip_address= in all interfaces that as not commented out.

test file:

# Example static IP configuration:
interface eth0
static ip_address=192.168.1.390/24
static ip6_address=fd51:42f8:caae:d92e::ff/64
static routers=192.168.1.1
static domain_name_servers=192.168.1.1 #8.8.8.8 fd51:42f8:caae:d92e::1

# It is possible to fall back to a static IP if DHCP fails:
# define static profile
#profile static_eth0
#static ip_address=192.168.1.30/24
#static routers=192.168.1.1
#static domain_name_servers=192.168.1.1

# fallback to static profile on eth0
#interface eth0
#fallback static_eth0

If like above then profile other than eth0 will not be touched which is desired. However if the line #static ip_address=192.168.1.30/2 would be commented, this line would be also modified, which is undesired.

Looking at the documentation one gets the idea that the line that has "interface eth0" will be identified and ONLY the line with the matching regex will be modified, but that does not seem to be true.

example of result after running with Uncommented line:

# Example static IP configuration:
interface eth0
static ip_address=192.168.1.390/24
static ip6_address=fd51:42f8:caae:d92e::ff/64
static routers=192.168.1.1
static domain_name_servers=192.168.1.1 #8.8.8.8 fd51:42f8:caae:d92e::1

# It is possible to fall back to a static IP if DHCP fails:
# define static profile
#profile static_eth0
static ip_address=192.168.1.390/24
#static routers=192.168.1.1
#static domain_name_servers=192.168.1.1

# fallback to static profile on eth0
#interface eth0
#fallback static_eth0

Am I doing something wrong, or am I misinterpreting the documentation, or is this not intended to work as I described, is there a bug ?

Please help me understand

I am running Ansible 1.9 with python 3.8:

ansible --version
ansible 2.9.6
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/pedro/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.8.10 (default, Nov 26 2021, 20:14:08) [GCC 9.3.0]


问:
SSIS look up table questions
I am using SSIS (SQL Server 2008) to lookup values from a table. I wanted to know if the following are possible:

Question 1

Lookup Table 1

```<code>Manager_Name    EMP_UNIT    Job_Profile_ID
AAA             SALES       27
BBB             HR          28
AAA             SALES       29
</code>```

I have to pass the ‘Manager_Name ‘and ‘EMP_UNIT ‘value in the Lookup table and fetch
Job Profile ID in Comma separated format.
Like I will pass the Values ‘AAA’ and ‘SALES’ and I want the return value as 27,29
How will I do this?

Question 2

Lookup Table 2

```<code>Job_Profile_ID  Job_Name
27              Jr. Salesman
28              Sales Manager
29              Sr. Salesman
</code>```

I have to pass the Job Profile ID values in Comma separated format (27, 29) and
I want the return value in Comma separated format (Jr. Salesman, Sr. Salesman).
Is this possible in SSIS?

Environment details:
MS SQL Server integration services (bids) 2008 on windows 2008 server

any help is appreciated,

Thanks

答:
I can help you with question 1, but i'm not sure about your second question.

To look up a single column, you would normally use the LookUp component, matching the search columns accordingly and returning the corresponding value.

However, as you are expecting multiple values to be returned, this is not going to be an option for you as the LookUp component will only return the first matching value.

To achieve multiple results per starting row, you will have to use two source controls (one for main table and other for lookup table) along with the Merge Join control

The merge join control will enable you to combine both sets of data, however when multiple matches exist you will get multiple rows.  So in your example, AAA and Sales as input will provide two rows;

AAA, Sales, 27

AAA, Sales, 29

You can then pass this data to a destination table.

For the second question, it is unusual to query and expect a consolidated response with comma separated values in SQL Server.

If you able to utilise the data with multiple search and result rows (i.e. search for row id 27 first and then row with id 29) then use the lookup task will suffice.

Otherwise, maybe make a second pass (new data flow task) and use the first pass temporary table to consolidate the data (using a script?) into your desired csv format.

Title: SSIS look up table questions

Body:
I am using SSIS (SQL Server 2008) to lookup values from a table. I wanted to know if the following are possible:

Question 1

Lookup Table 1

Manager_Name    EMP_UNIT    Job_Profile_ID
AAA             SALES       27
BBB             HR          28
AAA             SALES       29

I have to pass the ‘Manager_Name ‘and ‘EMP_UNIT ‘value in the Lookup table and fetch
Job Profile ID in Comma separated format.
Like I will pass the Values ‘AAA’ and ‘SALES’ and I want the return value as 27,29
How will I do this?

Question 2

Lookup Table 2

Job_Profile_ID  Job_Name
27              Jr. Salesman
28              Sales Manager
29              Sr. Salesman

I have to pass the Job Profile ID values in Comma separated format (27, 29) and
I want the return value in Comma separated format (Jr. Salesman, Sr. Salesman).
Is this possible in SSIS?

Environment details:
MS SQL Server integration services (bids) 2008 on windows 2008 server

any help is appreciated,

Thanks


问:
How to get My PUBLIC IP address Using Node js
I want to get my Public IP address using Node js only

For example when i search on Google "What is my Ip address "

Gives me output like 10X.XX.XX.XXX

How to get this Ip address Using node js without importing any Libraries like ip , Public-ip etc ...

I want to write my Custom Code to get public ip Without sending requests to other websites like whatismyipaddress.com , ipconfig.com etc ...

答:
```<code>const { exec } = require('child_process')

exec('curl ip-adresim.app', function(error, stdout, stderr){
    if(error)
        return;
    console.log('your ip is :'+ stdout);
})
</code>```

you could run a command and get the output like curl or ping

Body:
const { exec } = require('child_process')

exec('curl ip-adresim.app', function(error, stdout, stderr){
    if(error)
        return;
    console.log('your ip is :'+ stdout);
})

you could run a command and get the output like curl or ping


问:
gsap Flip.fit svg element not moving to expected coordinates because of { duration: x }
I am confused with gsap's  Flip.fit moving to coordinates.

I have a game board with 182 tiles and 182 playing tiles.

The goal

When the user clicks the bag, a random playing tile is selected and is "supposed" to move over the tile on the board.

If you change

```<code>Flip.fit(PTILE[tileArray], TILE[tileArray], {duration: 1 , scale: true});
</code>```

when changing { duration: 0, ... }  the move works as expected, however no animation. When duration is above zero, the final location is very random.

codepen

答:
I'm not sure how the duration affects the final position, however, I found a way to get the positions right. That is reset the transform of your PTILE before telling GSAP to do the Flip animation.

// reset transform value
gsap.set(PTILE[tileArray], { transform: "" });

// animate with new transform value
Flip.fit(PTILE[tileArray], TILE[tileArray], {
    duration: 1,
    scale: true
});
```

My reason is that PTITLE and TITLE are placed in different <g> tags which means their transform systems are inconsistent. Plus, Flip.fit() will act like gsap.to() with new TITLE position is the to object, GSAP will try to calculate the from object from your original transforms which are already set in the SVG as transform:matrix(). This process, somehow, is messing up. So what I did is give GSAP an exact transform value for the from object, which is empty.

Body:
I am confused with gsap's  Flip.fit moving to coordinates.

I have a game board with 182 tiles and 182 playing tiles.

The goal

When the user clicks the bag, a random playing tile is selected and is "supposed" to move over the tile on the board.

If you change

Flip.fit(PTILE[tileArray], TILE[tileArray], {duration: 1 , scale: true});

when changing { duration: 0, ... }  the move works as expected, however no animation. When duration is above zero, the final location is very random.

codepen

Body:
I'm not sure how the duration affects the final position, however, I found a way to get the positions right. That is reset the transform of your PTILE before telling GSAP to do the Flip animation.

// reset transform value
gsap.set(PTILE[tileArray], { transform: "" });

// animate with new transform value
Flip.fit(PTILE[tileArray], TILE[tileArray], {
    duration: 1,
    scale: true
});

My reason is that PTITLE and TITLE are placed in different <g> tags which means their transform systems are inconsistent. Plus, Flip.fit() will act like gsap.to() with new TITLE position is the to object, GSAP will try to calculate the from object from your original transforms which are already set in the SVG as transform:matrix(). This process, somehow, is messing up. So what I did is give GSAP an exact transform value for the from object, which is empty.


问:
Trying to fix table header, getting css issue
Initially I asked this Question and written my own plugin to achieve the same,But i am facing very strange issue regarding to css of table.

After applying the plugin table cells borders are getting dis-sorted.

jsFiddle of the problem: Problem demo

In fiddle you can see that after first cell of the first tr, the header border line and table border line don't line up. I want the border line of thead cells and td cells to line up.
Can anyone tell me how to achieve that?

答:
Lets start by doing a bit of a clean up of the code you posted so I can actually read your code and maintain a firm grasp on reality while we go down this rabbit hole.

If you write clean code, your problems will be exceptionally easier to see.

So lets clean it up and watch as all the problems here reveal themselves.

Step one: Your jsFiddle sets it to run "onDomReady," which basically means you've got $(document).ready(...) calling all the code in the box, which is fine, except you're got another got $(document).ready(...) inside there. Lets change that.

Step two: Lets add some white space and proper indentation in there, and stop using these one letter variable names.

{} are scope brackets, they should indent, not cover everything, they let us know what part of scope something is in.

Don't write .each() loops on one line, this adds no value and makes your code confusing to read.

$t should be called something meaningful, lets try element, because it holds the $(this) element, which is the active element you're working with.

w should be called something meaningful, but since you only use it twice I'm just going with element.width().

o needs to be less ambiguious, lets go with obj.

Step three: Selection structures

```<code>if(typeof(i)=='number')o.height=i;
else if(typeof(i)=='object')o=i;
else if(typeof(i)=='undefined')o={height:300}
</code>```

Break that up, make it readable. Saving lines doesn't make you a better program, writing clean and easily understandable code will.

Why not use the switch-case statement?

```<code>    switch (typeof(i)){
        case "number":
            o.height=i;
            break;
        case "object":
            o=i;
            break;
        case "undefined":
            o={height:300};
            break;
    }
</code>```

Step four: Don't in-line styles. Just don't. There's no reason to do it, and it makes everyone's life harder.

Instead, lets just place the styles gently into the style sheet where it belongs, and make the parent=$('...') line look like parent=$('

').appendTo('body');.

Step five: Closure doesn't pass any value to arguments

After a bit of clean up, we see this block of code:

```<code>self.width(self.width() -
    function(width){
        var parent,child;
        if(width===undefined){
            parent=$('<div><div></div></div>').appendTo('body');
            child=parent.children();
            width= (child.innerWidth()) - (child.height(99).innerWidth());
            parent.remove();
        }
        return width;
    }()
);
</code>```

Okay, that's a problem. Lets cut out a few lines to point out the problem here:

```<code>self.width(
   self.width() -
    function(width){
        /*...*/
        if(width===undefined){
            /*...*/
        }
        return width;
    }()
);
</code>```

So, a quick refresher on this pattern you have here:

```<code>(function(arg1){
    /*code*/
})(data);
</code>```

Data gets passed to arg1. Arg1 declaires a variable in the scope local to that function, it doesn't get anything from outside. Outside data is passed in through the set of () that call the function, which your code had left abandoned. Think of it this way:

```<code>var msg = function(text) {
    alert(text);
};
</code>```

Then you call it as...

```<code>msg("hello world");
</code>```

What your closure is doing is almost the same thing, except where you define your function, you also call it. Thus...

```<code>(function(text) {
    alert(text);
})("hello world");
</code>```

So, you need to pass a value of some sort into there, other wise this whole thing is always undefined. Lets do that. What are we passing? I have no way to be sure. This is why programmers need to add comments to their code.

Step six: Comment your code so people other than yourself will look at this code and have not a damn clue what you truthfuly wanted to do, and can only guess. It's like you posted a 200 point bounty and didn't bother helping people who want to help you. Why are you doing this to yourself, dude? Why couldn't you just go //This is what this does to give me a hint? What did I ever do to you?

Step Seven: Lets see if we can make the JS changes work with the JS Fiddle

Great odin... that HTML's 2000 lines long?

Okay, I'm working with pastebin here for the sake of saving space in the post here.

Alright, you started off with this: http://pastebin.com/xjmm4cev

You're using a lot of no-wrap, and putting classes onto individual elements. You shouldn't have to do this on each HTML element, CSS takes care of that very effectively, so lets go ahead and just rip out all the nowrap=nowrap and class="header" stuff (we'll put it back in a moment, but only ONE per group, not each element).

Then lets get rid of the useless blank lines.

Lets run this through HTML tidy and get it nice and indented correctly.

http://pastebin.com/uHtSZ4h5

Much easier to read over. Okay, so what do we see here? Well, it looks like you keep going in circles, cutting and pasting the same thing again and again. You also in-line javascript such as using onchange and onclick attributes. This is generally an awful thing to do to your code, and makes it hard to maintain (as I'm sure you've seen with this 2000+ line beast of cut+paste 27 times in a row).

So, lets take a look here:

 elements, not inside a form

Elements in a table that are outside of rows, but not head/body/footer sections of a table

Code that's a huge pain to maintain because it keep going in circles, if you need to change this, you're basically screwed.

Lets fix all that.

We're going to use events in the  tags, rather than in-line things. So, all of those in-line onchange and click attributes get the boot.

All of these inputs that are just floating around need to get put into a form, and taken out of this place in tables that only rows or table sections belong in.

Figure out how we can not have excessive input elements, if we can help it.

What the heck is the )="" that you have on every input button? Deleted.

So, here's all of your hidden  boxes: http://pastebin.com/LXZSkvyf which I've removed, because we don't have a  anywhere.

And here's what the code looks like without all of these weird things in it: http://pastebin.com/MiaJTGpb

Much more readable, but still not quite there.

Step 8: What can you do to make the HTML of the table work better?

You're using Thead and Tbody, and that's good.

You're using attributes for things like cellpadding, that's bad.

You've given each body row an ID. I don't feel you needed to do this, but it's not always bad. However, I'll show you how you could work without it.

You give some selects a select-box class, but it's nowhere in the css. I've removed it.

You give a title attribute to the selects that says "option_value". The title attribute is generally used to make a tool-tip popup when you leave the mouse over something. I'm not sure what you're going to do here, but that's bound to confuse your user. I'd highly suggest giving something better than option_value in that place.

You keep using the ID Submit_FMS_AddDelivery. HTML ID tags are meant to be unique, and used only once on one element. You've got it 27 times, that's bad. I don't think you need an ID on it, so I've removed it.

You've also got input-btn going on, I'm removing it, because you haven't shown it's used anywhere.

You probably don't need any of these ID tags on select and TR to be honest, so I'm pulling them.

What's that look like? Basically, you've got what's almost just the data, in it's nice pure form. That's good. http://pastebin.com/UNS6CAtb

Step 9: What were you trying to do?

Lets step back and take a look here.

All you really wanted to do was keep a fixed header, but you've ended up doing a lot of JavaScript hacks and manipulating the DOM in a lot of places. We need to stop doing this. Is there a simpler way to do what you want?

I'll have to expand on how to make this function with the rest of your stuff, but I get up for work in a few hours. I'll update again with more... But we'll get there.

Right now, because I haven't fixed what I took out, it doesn't look right. But I'm tired.

So, here's where we are so far: http://jsfiddle.net/5C6z7/
Plus those inputs we took out (and will be going back in later, in a different way)

Body:
Lets start by doing a bit of a clean up of the code you posted so I can actually read your code and maintain a firm grasp on reality while we go down this rabbit hole.

If you write clean code, your problems will be exceptionally easier to see.

So lets clean it up and watch as all the problems here reveal themselves.

Step one: Your jsFiddle sets it to run "onDomReady," which basically means you've got $(document).ready(...) calling all the code in the box, which is fine, except you're got another got $(document).ready(...) inside there. Lets change that.

Step two: Lets add some white space and proper indentation in there, and stop using these one letter variable names.

{} are scope brackets, they should indent, not cover everything, they let us know what part of scope something is in.

Don't write .each() loops on one line, this adds no value and makes your code confusing to read.

$t should be called something meaningful, lets try element, because it holds the $(this) element, which is the active element you're working with.

w should be called something meaningful, but since you only use it twice I'm just going with element.width().

o needs to be less ambiguious, lets go with obj.

Step three: Selection structures

if(typeof(i)=='number')o.height=i;
else if(typeof(i)=='object')o=i;
else if(typeof(i)=='undefined')o={height:300}

Break that up, make it readable. Saving lines doesn't make you a better program, writing clean and easily understandable code will.

Why not use the switch-case statement?

    switch (typeof(i)){
        case "number":
            o.height=i;
            break;
        case "object":
            o=i;
            break;
        case "undefined":
            o={height:300};
            break;
    }

Step four: Don't in-line styles. Just don't. There's no reason to do it, and it makes everyone's life harder.

Instead, lets just place the styles gently into the style sheet where it belongs, and make the parent=$('...') line look like parent=$('<div><div></div></div>').appendTo('body');.

Step five: Closure doesn't pass any value to arguments

After a bit of clean up, we see this block of code:

self.width(self.width() -
    function(width){
        var parent,child;
        if(width===undefined){
            parent=$('<div><div></div></div>').appendTo('body');
            child=parent.children();
            width= (child.innerWidth()) - (child.height(99).innerWidth());
            parent.remove();
        }
        return width;
    }()
);

Okay, that's a problem. Lets cut out a few lines to point out the problem here:

self.width(
   self.width() -
    function(width){
        /*...*/
        if(width===undefined){
            /*...*/
        }
        return width;
    }()
);

So, a quick refresher on this pattern you have here:

(function(arg1){
    /*code*/
})(data);

Data gets passed to arg1. Arg1 declaires a variable in the scope local to that function, it doesn't get anything from outside. Outside data is passed in through the set of () that call the function, which your code had left abandoned. Think of it this way:

var msg = function(text) {
    alert(text);
};

Then you call it as...

msg("hello world");

What your closure is doing is almost the same thing, except where you define your function, you also call it. Thus...

(function(text) {
    alert(text);
})("hello world");

So, you need to pass a value of some sort into there, other wise this whole thing is always undefined. Lets do that. What are we passing? I have no way to be sure. This is why programmers need to add comments to their code.

Step six: Comment your code so people other than yourself will look at this code and have not a damn clue what you truthfuly wanted to do, and can only guess. It's like you posted a 200 point bounty and didn't bother helping people who want to help you. Why are you doing this to yourself, dude? Why couldn't you just go //This is what this does to give me a hint? What did I ever do to you?

Step Seven: Lets see if we can make the JS changes work with the JS Fiddle

Great odin... that HTML's 2000 lines long?

Okay, I'm working with pastebin here for the sake of saving space in the post here.

Alright, you started off with this: http://pastebin.com/xjmm4cev

You're using a lot of no-wrap, and putting classes onto individual elements. You shouldn't have to do this on each HTML element, CSS takes care of that very effectively, so lets go ahead and just rip out all the nowrap=nowrap and class="header" stuff (we'll put it back in a moment, but only ONE per group, not each element).

Then lets get rid of the useless blank lines.

Lets run this through HTML tidy and get it nice and indented correctly.

http://pastebin.com/uHtSZ4h5

Much easier to read over. Okay, so what do we see here? Well, it looks like you keep going in circles, cutting and pasting the same thing again and again. You also in-line javascript such as using onchange and onclick attributes. This is generally an awful thing to do to your code, and makes it hard to maintain (as I'm sure you've seen with this 2000+ line beast of cut+paste 27 times in a row).

So, lets take a look here:

 elements, not inside a form

Elements in a table that are outside of rows, but not head/body/footer sections of a table

Code that's a huge pain to maintain because it keep going in circles, if you need to change this, you're basically screwed.

Lets fix all that.

We're going to use events in the  tags, rather than in-line things. So, all of those in-line onchange and click attributes get the boot.

All of these inputs that are just floating around need to get put into a form, and taken out of this place in tables that only rows or table sections belong in.

Figure out how we can not have excessive input elements, if we can help it.

What the heck is the )="" that you have on every input button? Deleted.

So, here's all of your hidden  boxes: http://pastebin.com/LXZSkvyf which I've removed, because we don't have a  anywhere.

And here's what the code looks like without all of these weird things in it: http://pastebin.com/MiaJTGpb

Much more readable, but still not quite there.

Step 8: What can you do to make the HTML of the table work better?

You're using Thead and Tbody, and that's good.

You're using attributes for things like cellpadding, that's bad.

You've given each body row an ID. I don't feel you needed to do this, but it's not always bad. However, I'll show you how you could work without it.

You give some selects a select-box class, but it's nowhere in the css. I've removed it.

You give a title attribute to the selects that says "option_value". The title attribute is generally used to make a tool-tip popup when you leave the mouse over something. I'm not sure what you're going to do here, but that's bound to confuse your user. I'd highly suggest giving something better than option_value in that place.

You keep using the ID Submit_FMS_AddDelivery. HTML ID tags are meant to be unique, and used only once on one element. You've got it 27 times, that's bad. I don't think you need an ID on it, so I've removed it.

You've also got input-btn going on, I'm removing it, because you haven't shown it's used anywhere.

You probably don't need any of these ID tags on select and TR to be honest, so I'm pulling them.

What's that look like? Basically, you've got what's almost just the data, in it's nice pure form. That's good. http://pastebin.com/UNS6CAtb

Step 9: What were you trying to do?

Lets step back and take a look here.

All you really wanted to do was keep a fixed header, but you've ended up doing a lot of JavaScript hacks and manipulating the DOM in a lot of places. We need to stop doing this. Is there a simpler way to do what you want?

I'll have to expand on how to make this function with the rest of your stuff, but I get up for work in a few hours. I'll update again with more... But we'll get there.

Right now, because I haven't fixed what I took out, it doesn't look right. But I'm tired.

So, here's where we are so far: http://jsfiddle.net/5C6z7/
Plus those inputs we took out (and will be going back in later, in a different way)


问:
R - Impute missing values by group (linear / moving average)
I have a large dataset with a lot of missing values and I want to impute it by group "name" either linearly or with moving average.

```<code>d <-  data.frame(
  name = c('a', 'a','a','a','b','b','b','b','c','c','c','c'),
  year = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4),
  V = c(NA, 21, 31, 41, 11, NA, NA, 41, NA, NA, NA, 41),
  W = c(11, NA, 31, 41, 11, 21, NA, NA, NA, NA, 31, NA),
  X = c(11, 21, NA, 41, NA, 21, NA, 41, 11, NA, NA, NA),
  Y = c(11, 21, 31, NA, NA, 21, 31, NA, NA, 21, NA, NA),
  Z = c(NA, NA, 31, 41, 11, NA, 31, NA, NA, NA, NA, NA)
)

> d
   name year  V  W  X  Y  Z
1     a    1 NA 11 11 11 NA
2     a    2 21 NA 21 21 NA
3     a    3 31 31 NA 31 31
4     a    4 41 41 41 NA 41
5     b    1 11 11 NA NA 11
6     b    2 NA 21 21 21 NA
7     b    3 NA NA NA 31 31
8     b    4 41 NA 41 NA NA
9     c    1 NA NA 11 NA NA
10    c    2 NA NA NA 21 NA
11    c    3 NA 31 NA NA NA
12    c    4 41 NA NA NA NA
</code>```

Hopefully the results can be as closed as the following:

```<code>   name year  V  W  X  Y  Z
1     a    1 11 11 11 11 11
2     a    2 21 21 21 21 21
3     a    3 31 31 31 31 31
4     a    4 41 41 41 41 41
5     b    1 11 11 11 11 11
6     b    2 21 21 21 21 21
7     b    3 31 31 31 31 31
8     b    4 41 41 41 41 41
9     c    1 11 11 11 11 NA
10    c    2 21 21 21 21 NA
11    c    3 31 31 31 31 NA
12    c    4 41 41 41 41 NA
</code>```

I found this and this. Tried the following without groupby but it didn't work:

```<code>data.frame(lapply(d, function(X) approxfun(seq_along(X), X)(seq_along(X))))
</code>```
```<code>imputeTS::na_ma(d, k = 2, weighting = "simple")
</code>```

The first one gave an error as below:

```<code>Error in approxfun(seq_along(X), X) :
  need at least two non-NA values to interpolate
In addition: Warning message:
In xy.coords(x, y, setLab = FALSE) :
 Error in approxfun(seq_along(X), X) :
  need at least two non-NA values to interpolate
</code>```

So I tried the second one and it keep loading for a long time and nothing happened. According to the reply from the first link,

the package requires time series/vector input (that's why each column
has to be called separately).

Any help is greatly appreciated!

答:
One issue I see is, that some of the series you want to impute have only 1 non-NA value, thus na_ma or na_interpolation from imputeTS or also other packages can not be applied successfully, since these require at least 2 non-NA values.

That is why in this solution I created a impute_select function for you, that let's you choose, what to to when > 1 values or present, when exactly == 1 values are present or when there are only NAs.

In this case, when > 1 values is present, it uses na_ma, but you could also use na_interpoltion or any other imputation function from imputeTS here.
When only 1 value is present, it uses na_locf since this method also works with only 1 value in the series.
When no non-NA values are in the series, it uses na_replace, just replacing all the NAs with a default value (I just set it to 11)

By adjusting this function you should be able to individually adjust the imputation for different amounts of NAs in the series.

```<code>library("imputeTS")

d <-  data.frame(
  name = c('a', 'a','a','a','b','b','b','b','c','c','c','c'),
  year = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4),
  V = c(NA, 21, 31, 41, 11, NA, NA, 41, NA, NA, NA, 41),
  W = c(11, NA, 31, 41, 11, 21, NA, NA, NA, NA, 31, NA),
  X = c(11, 21, NA, 41, NA, 21, NA, 41, 11, NA, NA, NA),
  Y = c(11, 21, 31, NA, NA, 21, 31, NA, NA, 21, NA, NA),
  Z = c(NA, NA, 31, 41, 11, NA, 31, NA, NA, NA, NA, NA)
)

impute_select <- function(x) {
  # select a method to use when more than 1 values are available
  if (sum(!is.na(x)) > 1) {
    result <- na_ma(x)
  }
  # Select value when only 1 value is in series
  if (sum(!is.na(x)) == 1) {
    result <- na_locf(x)
  }
  # Select method, when no non-NA value is present
  else {
    result <- na_replace(x, 11)
  }
}

# This code is to apply the function row-wise to your data frame
# Since usually the imputation would happen column-wise instead
d[,3:7] <- t(apply(d[,3:7], MARGIN =1, FUN = impute_select))

d
</code>```

This are the results (hopefully exactly what you wanted):

```<code>   name year  V  W  X  Y  Z
1     a    1 11 11 11 11 11
2     a    2 21 11 21 21 11
3     a    3 31 31 11 31 31
4     a    4 41 41 41 11 41
5     b    1 11 11 11 11 11
6     b    2 11 21 21 21 11
7     b    3 11 11 11 31 31
8     b    4 41 11 41 11 11
9     c    1 11 11 11 11 11
10    c    2 21 21 21 21 21
11    c    3 31 31 31 31 31
12    c    4 41 41 41 41 41
</code>```

Body:
I have a large dataset with a lot of missing values and I want to impute it by group "name" either linearly or with moving average.

d <-  data.frame(
  name = c('a', 'a','a','a','b','b','b','b','c','c','c','c'),
  year = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4),
  V = c(NA, 21, 31, 41, 11, NA, NA, 41, NA, NA, NA, 41),
  W = c(11, NA, 31, 41, 11, 21, NA, NA, NA, NA, 31, NA),
  X = c(11, 21, NA, 41, NA, 21, NA, 41, 11, NA, NA, NA),
  Y = c(11, 21, 31, NA, NA, 21, 31, NA, NA, 21, NA, NA),
  Z = c(NA, NA, 31, 41, 11, NA, 31, NA, NA, NA, NA, NA)
)

> d
   name year  V  W  X  Y  Z
1     a    1 NA 11 11 11 NA
2     a    2 21 NA 21 21 NA
3     a    3 31 31 NA 31 31
4     a    4 41 41 41 NA 41
5     b    1 11 11 NA NA 11
6     b    2 NA 21 21 21 NA
7     b    3 NA NA NA 31 31
8     b    4 41 NA 41 NA NA
9     c    1 NA NA 11 NA NA
10    c    2 NA NA NA 21 NA
11    c    3 NA 31 NA NA NA
12    c    4 41 NA NA NA NA

Hopefully the results can be as closed as the following:

   name year  V  W  X  Y  Z
1     a    1 11 11 11 11 11
2     a    2 21 21 21 21 21
3     a    3 31 31 31 31 31
4     a    4 41 41 41 41 41
5     b    1 11 11 11 11 11
6     b    2 21 21 21 21 21
7     b    3 31 31 31 31 31
8     b    4 41 41 41 41 41
9     c    1 11 11 11 11 NA
10    c    2 21 21 21 21 NA
11    c    3 31 31 31 31 NA
12    c    4 41 41 41 41 NA

I found this and this. Tried the following without groupby but it didn't work:

data.frame(lapply(d, function(X) approxfun(seq_along(X), X)(seq_along(X))))

imputeTS::na_ma(d, k = 2, weighting = "simple")

The first one gave an error as below:

Error in approxfun(seq_along(X), X) :
  need at least two non-NA values to interpolate
In addition: Warning message:
In xy.coords(x, y, setLab = FALSE) :
 Error in approxfun(seq_along(X), X) :
  need at least two non-NA values to interpolate

So I tried the second one and it keep loading for a long time and nothing happened. According to the reply from the first link,

the package requires time series/vector input (that's why each column
has to be called separately).

Any help is greatly appreciated!

Body:
One issue I see is, that some of the series you want to impute have only 1 non-NA value, thus na_ma or na_interpolation from imputeTS or also other packages can not be applied successfully, since these require at least 2 non-NA values.

That is why in this solution I created a impute_select function for you, that let's you choose, what to to when > 1 values or present, when exactly == 1 values are present or when there are only NAs.

In this case, when > 1 values is present, it uses na_ma, but you could also use na_interpoltion or any other imputation function from imputeTS here.
When only 1 value is present, it uses na_locf since this method also works with only 1 value in the series.
When no non-NA values are in the series, it uses na_replace, just replacing all the NAs with a default value (I just set it to 11)

By adjusting this function you should be able to individually adjust the imputation for different amounts of NAs in the series.

library("imputeTS")

d <-  data.frame(
  name = c('a', 'a','a','a','b','b','b','b','c','c','c','c'),
  year = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4),
  V = c(NA, 21, 31, 41, 11, NA, NA, 41, NA, NA, NA, 41),
  W = c(11, NA, 31, 41, 11, 21, NA, NA, NA, NA, 31, NA),
  X = c(11, 21, NA, 41, NA, 21, NA, 41, 11, NA, NA, NA),
  Y = c(11, 21, 31, NA, NA, 21, 31, NA, NA, 21, NA, NA),
  Z = c(NA, NA, 31, 41, 11, NA, 31, NA, NA, NA, NA, NA)
)

impute_select <- function(x) {
  # select a method to use when more than 1 values are available
  if (sum(!is.na(x)) > 1) {
    result <- na_ma(x)
  }
  # Select value when only 1 value is in series
  if (sum(!is.na(x)) == 1) {
    result <- na_locf(x)
  }
  # Select method, when no non-NA value is present
  else {
    result <- na_replace(x, 11)
  }
}

# This code is to apply the function row-wise to your data frame
# Since usually the imputation would happen column-wise instead
d[,3:7] <- t(apply(d[,3:7], MARGIN =1, FUN = impute_select))

d

This are the results (hopefully exactly what you wanted):

   name year  V  W  X  Y  Z
1     a    1 11 11 11 11 11
2     a    2 21 11 21 21 11
3     a    3 31 31 11 31 31
4     a    4 41 41 41 11 41
5     b    1 11 11 11 11 11
6     b    2 11 21 21 21 11
7     b    3 11 11 11 31 31
8     b    4 41 11 41 11 11
9     c    1 11 11 11 11 11
10    c    2 21 21 21 21 21
11    c    3 31 31 31 31 31
12    c    4 41 41 41 41 41


问:
Shortcut to turn a ONE element dict into ONE tuple in Python
There are dozens of questions on turning a Python dict with some number of elements into a list of tuples. I am looking for a shortcut to turn a one element dict into a tuple.

Ideally, it would:

Be idiomatic and simple (ie, not a subclass of dict, not a function, etc).

Throw an error if there are more that one element in the dict.

Support multiple assignment by tuple unpacking.

Not destroy the dict.

I am looking for a shortcut to do this (that is not destructive to the dict):

```<code>k,v=unpack_this({'unknown_key':'some value'})
</code>```

* does not work here.

I have come up with these that work:

```<code>k,v=next(iter(di.items()))   # have to call 'iter' since 'dict_items' is not
</code>```

Or:

```<code>k,v=(next(((k,v) for k,v in di.items())))
</code>```

Or even:

```<code>k,v=next(zip(di.keys(), di.values()))
</code>```

Finally, the best I can come up with:

```<code>k,v=list(di.items())[0]      # probably the best...
</code>```

Which can be wrapped into a function if I want a length check:

```<code>def f(di):
    if (len(di)==1): return list(di.items())[0]
    raise ValueError(f'Too many items to unpack. Expected 2, got {len(di)*2}')
</code>```

These methods seem super clumsy and none throw an error if there is more than one element.

Is there an idiomatic shortcut that I am missing?

答:
```<code>>>> d = {'a': 1}
>>> d.popitem()
('a', 1)
</code>```

This will return the pair associated with the last key added, with no error error if the dict has multiple keys, but the same length check you've made in your function f can be used.

```<code>def f(di):
    if len(di) == 1:
        return d.popitem()
    raise ValueError(f'Dict has multiple keys')
</code>```

Body:
There are dozens of questions on turning a Python dict with some number of elements into a list of tuples. I am looking for a shortcut to turn a one element dict into a tuple.

Ideally, it would:

Be idiomatic and simple (ie, not a subclass of dict, not a function, etc).

Throw an error if there are more that one element in the dict.

Support multiple assignment by tuple unpacking.

Not destroy the dict.

I am looking for a shortcut to do this (that is not destructive to the dict):

k,v=unpack_this({'unknown_key':'some value'})

* does not work here.

I have come up with these that work:

k,v=next(iter(di.items()))   # have to call 'iter' since 'dict_items' is not

Or:

k,v=(next(((k,v) for k,v in di.items())))

Or even:

k,v=next(zip(di.keys(), di.values()))

Finally, the best I can come up with:

k,v=list(di.items())[0]      # probably the best...

Which can be wrapped into a function if I want a length check:

def f(di):
    if (len(di)==1): return list(di.items())[0]
    raise ValueError(f'Too many items to unpack. Expected 2, got {len(di)*2}')

These methods seem super clumsy and none throw an error if there is more than one element.

Is there an idiomatic shortcut that I am missing?

Body:
>>> d = {'a': 1}
>>> d.popitem()
('a', 1)

This will return the pair associated with the last key added, with no error error if the dict has multiple keys, but the same length check you've made in your function f can be used.

def f(di):
    if len(di) == 1:
        return d.popitem()
    raise ValueError(f'Dict has multiple keys')


问:
php $_GET passing variables from one page to another
I'm trying to pass my variables from one page to another, I'm using $_GET and it's grabbing my variables but on the same page instead of a new one, is it possible to pass them to a new page using $_GET or do I have to do another method, I've seen this done on the site using javascript asp and jquery but cant seem to find one with PHP that is explaining things very well.

this is what I have, other then this I'm pretty clueless on how to make this happen.

```<code>foreach($obj->jigsawes as $jigsaw):

   if(isset($_GET['p']) && $_GET['p']==''.$query.'') {
echo "<a href='?p=$jigsaw_url'><img border=0 src='".$jigsaw->photo_url."'></a><br />";

echo "$jigsaw->name</ br>
 $jigsaw->address1<br />
 $jigsaw->phone<br />
 $jigsaw->city<br />
 $jigsaw->state<br />
 $jigsaw->zip<br />";

}else{
$query = htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES);

echo "<div><a href='?$query'>$jigsaw->name</a></div>";
    }
endforeach;
}
</code>```

答:
I would probably use session variables.

http://php.net/manual/en/function.session-start.php

Body:
I'm trying to pass my variables from one page to another, I'm using $_GET and it's grabbing my variables but on the same page instead of a new one, is it possible to pass them to a new page using $_GET or do I have to do another method, I've seen this done on the site using javascript asp and jquery but cant seem to find one with PHP that is explaining things very well.

this is what I have, other then this I'm pretty clueless on how to make this happen.

foreach($obj->jigsawes as $jigsaw):

   if(isset($_GET['p']) && $_GET['p']==''.$query.'') {
echo "photo_url."'>
";

echo "$jigsaw->name

 $jigsaw->address1

 $jigsaw->phone

 $jigsaw->city

 $jigsaw->state

 $jigsaw->zip
";

}else{
$query = htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES);

echo "
$jigsaw->name
";
    }
endforeach;
}


问:
How to process 20GB of data file from HDFS
I have a requirement to get a unique JSON record depending on certain conditions from 20GB of data present in a file(depending on queryId). Each line in the file is a JSON record.
EX :

{"sessionID":"xyz","appID":"abc","tenantID":"123","realmId":"buyer_2021","topology":"top456","queryId":"12346278","signalType":"USER_QUERY_RESULTS",XYZ content.....}

答:
Each line in the file is a JSON record.

Start with Spark. You don't need Hadoop for only 20 GB of data

val df = spark.read.json("file.json")
```

With that, you can select/filter/groupBy, etc the query ID field.

https://spark.apache.org/docs/latest/sql-data-sources-json.html

Body:
Each line in the file is a JSON record.

Start with Spark. You don't need Hadoop for only 20 GB of data

val df = spark.read.json("file.json")

With that, you can select/filter/groupBy, etc the query ID field.

https://spark.apache.org/docs/latest/sql-data-sources-json.html


问:
Mongocxx getting value of retrieved db document
I'm currently working on project, where I need to retrieve value from Mongo db record. Currently I can retrieve values using 'get_utf8().value.get_string()' for string values in document, but specifically 'expires_in' value, which is not enclosed in double quotes crashes code:

```<code>{ "_id" : ObjectId("61ffc0e17b589b87520ce6a1"), "access_token" : "<hidden>", "expires_in" : 7200, "token_type" : "Application Access Token" }
</code>```

As an example to retrieve 'access_token':

```<code>mongocxx::collection col(mongocxx::database);
mongocxx::options::find opts;
opts.limit(1);
auto cursor = col.find({}, opts);
auto t = *cursor.begin();
// This code retrieves 'token_type' as expected
std::cout << "token_type : " << t["token_type"].get_utf8().value.to_string() << std::endl;
// This code isn't working neither for 'get_utf8', nor 'get_double()', nor
// 'get_int64()' and many others I looked into
std::cout << t["expires_in"].get_utf8().value.to_string() << std::endl;
</code>```

Crash example:

token_type: Application Access Token terminate called after throwing
an instance of 'bsoncxx::v_noabi::exception'   what():  expected
element type k_utf8 Aborted

Would appreciate any ideas.

Thanks!

答:
My mistake, somehow skipped one of the types & it worked:

```<code>std::cout << t["expires_in"].get_int32().value << std::endl;
</code>```

Thanks

Body:
I'm currently working on project, where I need to retrieve value from Mongo db record. Currently I can retrieve values using 'get_utf8().value.get_string()' for string values in document, but specifically 'expires_in' value, which is not enclosed in double quotes crashes code:

{ "_id" : ObjectId("61ffc0e17b589b87520ce6a1"), "access_token" : "<hidden>", "expires_in" : 7200, "token_type" : "Application Access Token" }

As an example to retrieve 'access_token':

mongocxx::collection col(mongocxx::database);
mongocxx::options::find opts;
opts.limit(1);
auto cursor = col.find({}, opts);
auto t = *cursor.begin();
// This code retrieves 'token_type' as expected
std::cout << "token_type : " << t["token_type"].get_utf8().value.to_string() << std::endl;
// This code isn't working neither for 'get_utf8', nor 'get_double()', nor
// 'get_int64()' and many others I looked into
std::cout << t["expires_in"].get_utf8().value.to_string() << std::endl;

Crash example:

token_type: Application Access Token terminate called after throwing
an instance of 'bsoncxx::v_noabi::exception'   what():  expected
element type k_utf8 Aborted

Would appreciate any ideas.

Thanks!

Body:
My mistake, somehow skipped one of the types & it worked:

std::cout << t["expires_in"].get_int32().value << std::endl;

Thanks


问:
Summary for multiple / specific columns
I have a table with multiple columns and instead of running the summary on specific rows e.g. summary(a), summary(b) etc. I was wondering if there's a way to do it with a for loop.

In psuedo code, I'd look something like this:

```<code>list = [a, b, c] #where a,b,c are column names
for i in list:
    print(summary(i))
</code>```

答:
Appending to Ronak's answer; if you don't want to create an otherwise unneeded variable, you can subset the desired columns directly in the dataframe for a single-line solution:

summary(mtcars[c("mpg", "cyl")]
```

Title: Summary for multiple / specific columns

Body:
I have a table with multiple columns and instead of running the summary on specific rows e.g. summary(a), summary(b) etc. I was wondering if there's a way to do it with a for loop.

In psuedo code, I'd look something like this:

list = [a, b, c] #where a,b,c are column names
for i in list:
    print(summary(i))


问:
Truncate text in AspxGridView cells
Is there a way to truncate long text in AspxGridView cells?

I've read and implemented this solution. , http://documentation.devexpress.com/#AspNet/DevExpressWebASPxGridViewASPxGridView_CustomColumnDisplayTexttopic

...which of course works BUT only for one column and I need to create this with several columns.

Here is my solution so far

```<code>protected void AsPxGridView1CustomColumnDisplayText(object sender, ASPxGridViewColumnDisplayTextEventArgs e)
{
    if (e.Column.FieldName != "AnalysisFeedbackAuto") return;
    if (e.Value.ToString().Length > 13)
    {
        var displayText = Regex.Replace(e.Value.ToString(), "<.*?>", string.Empty).Substring(0, 10);
        e.DisplayText = string.Concat(displayText, "...");
    }
}
</code>```

Any advice?

Thanks

=== UPDATE ===
Obviously this was the solution

```<code>protected void AsPxGridView1CustomColumnDisplayText(object sender, ASPxGridViewColumnDisplayTextEventArgs e)
{
    if (e.Column.FieldName == "AnalysisFeedbackAuto"
        || e.Column.FieldName == "AnalysisResults"
        || e.Column.FieldName == "AnalysisAnswers"
        )
    {
        if (e.Value.ToString().Length > 13)
        {
            var displayText = Regex.Replace(e.Value.ToString(), "<.*?>", string.Empty).Substring(0, 10);
            e.DisplayText = string.Concat(displayText, "...");
        }
    }
}
</code>```

Title: Truncate text in AspxGridView cells

Body:
Is there a way to truncate long text in AspxGridView cells?

I've read and implemented this solution. , http://documentation.devexpress.com/#AspNet/DevExpressWebASPxGridViewASPxGridView_CustomColumnDisplayTexttopic

...which of course works BUT only for one column and I need to create this with several columns.

Here is my solution so far

protected void AsPxGridView1CustomColumnDisplayText(object sender, ASPxGridViewColumnDisplayTextEventArgs e)
{
    if (e.Column.FieldName != "AnalysisFeedbackAuto") return;
    if (e.Value.ToString().Length > 13)
    {
        var displayText = Regex.Replace(e.Value.ToString(), "<.*?>", string.Empty).Substring(0, 10);
        e.DisplayText = string.Concat(displayText, "...");
    }
}

Any advice?

Thanks

=== UPDATE ===
Obviously this was the solution

protected void AsPxGridView1CustomColumnDisplayText(object sender, ASPxGridViewColumnDisplayTextEventArgs e)
{
    if (e.Column.FieldName == "AnalysisFeedbackAuto"
        || e.Column.FieldName == "AnalysisResults"
        || e.Column.FieldName == "AnalysisAnswers"
        )
    {
        if (e.Value.ToString().Length > 13)
        {
            var displayText = Regex.Replace(e.Value.ToString(), "<.*?>", string.Empty).Substring(0, 10);
            e.DisplayText = string.Concat(displayText, "...");
        }
    }
}


问:
How to exclude results within the Mongo aggregation pipeline?
I'm new to the Mongo aggregation pipeline, and what I'm trying to do is find a simple way to exclude documents from my query. Each document in this collection can have multiple usernames. What I'm trying to exclude in my aggregation are any documents which have usernames other than userA and userB. What I'd like to do is something like:

```<code>...
{$dontmatch: {usernames: {$nin: ['userA', 'userB']}}}
</code>```

My current query:

```<code>...
{$match:{
    $or: [
        {$and: [{usernames: {$size: 1}}, {usernames: {$in: ["userA", "userB"]}}]},
        {$and: [{usernames: {$size: 2}}, {usernames: {$all: ["userA", "userB"]}}]}
    ]}
}
</code>```

What I have at the moment works, but I'm just wondering if there is a more clean or efficient way of doing this, such as I've suggested above?

答:
Just came across this, if I understand the question correctly - we want to exclude the documents where the usernames array contains anything other than "userA" and "userB".

One possible way to achieve this using aggregation pipeline would be something like this: https://mongoplayground.net/p/oncv4_iRx35

Here's what I did:

Use $project stage to create empty "usernames" array where the condition doesn't satisfy

Use $addFields to add a size field containing the size of modified usernames array

Use $match to filter out the desired documents.

There might be more succinct approaches to this but this is the one I came up with.

Body:
I'm new to the Mongo aggregation pipeline, and what I'm trying to do is find a simple way to exclude documents from my query. Each document in this collection can have multiple usernames. What I'm trying to exclude in my aggregation are any documents which have usernames other than userA and userB. What I'd like to do is something like:

...
{$dontmatch: {usernames: {$nin: ['userA', 'userB']}}}

My current query:

...
{$match:{
    $or: [
        {$and: [{usernames: {$size: 1}}, {usernames: {$in: ["userA", "userB"]}}]},
        {$and: [{usernames: {$size: 2}}, {usernames: {$all: ["userA", "userB"]}}]}
    ]}
}

What I have at the moment works, but I'm just wondering if there is a more clean or efficient way of doing this, such as I've suggested above?


问:
Retrieve the value of a variable that stores in local storage the options chosen by users in a dropdown list
I need to retrieve the value of a variable that stores in local storage the options chosen by users in a dropdown list in order to use it elsewhere.

This is the code, the dropdown has a list of years from 2020 to the current year.

I store the year in local storage on change and in Chrome Dev Tools you can see how the stored variable changes when other years are chosen from the dropdown.

So far so good. But when I try to retrieve the year in the userSelectedYearStorage variable the last console.log line won't show. What am I doing wrong? Thanks!

```<code>    <body>
      <div id="app">
        <select id="yearSelection">
          <option value="0" selected>Select a year</option>
        </select>
      </div>

          <script>

            var yearSelection = document.getElementById("yearSelection");
            var currentYear = new Date().getFullYear();
            for (let y = 2020; y <= currentYear; y++) {
              var element = document.createElement("option");
              element.textContent = y;
              element.value = y;
              yearSelection.appendChild(element);
            }

            var userSelectedYear = 0;
            $("#yearSelection").on("change", function () {
              userSelectedYear = this.value;
              console.log("userSelectedYear inside on change: " + userSelectedYear);
              localStorage.setItem("userSelectedYear", userSelectedYear);
            });

            var userSelectedYearStorage = localStorage.getItem('userSelectedYear')
//this line below won't be printed:
            console.log("userSelectedYear outside on change: " + userSelectedYearStorage);

          </script>
        </body>
</code>```

答:
That's because when the page is first loaded, localStorage.getItem('userSelectedYear') equals null (it is not yet set). It only gets set when the change event is triggered. You can fix this by giving userSelectedYearStorage a default value like so

```<code>// userSelectedYear defaults to 0
var userSelectedYearStorage = localStorage.getItem('userSelectedYear') ?? userSelectedYear;
</code>```

Body:
I need to retrieve the value of a variable that stores in local storage the options chosen by users in a dropdown list in order to use it elsewhere.

This is the code, the dropdown has a list of years from 2020 to the current year.

I store the year in local storage on change and in Chrome Dev Tools you can see how the stored variable changes when other years are chosen from the dropdown.

So far so good. But when I try to retrieve the year in the userSelectedYearStorage variable the last console.log line won't show. What am I doing wrong? Thanks!

        <select id="yearSelection">
          <option value="0" selected>Select a year</option>
        </select>

Body:
That's because when the page is first loaded, localStorage.getItem('userSelectedYear') equals null (it is not yet set). It only gets set when the change event is triggered. You can fix this by giving userSelectedYearStorage a default value like so

// userSelectedYear defaults to 0
var userSelectedYearStorage = localStorage.getItem('userSelectedYear') ?? userSelectedYear;


问:
Move backdrop filter element behind absolute positioned element
Here's the problem

* {
  color: white;
}

.must-be-top {
  background-color: red;
  height: 200px;
  width: 200px;
  position: absolute;
  left: 20px;
  top: 20px;
  z-index: 1999;
}

.v-space {
  height: 10px;
}

.blur {
  height: 50px;
  width: 400px;
  background-color: rgba(0, 0, 0, .8);
  backdrop-filter: blur(10px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="blur">
This is the blurred container
  <div class="must-be-top">This div must be on top</div>
</div>
<div class="v-space"></div>
<div class="must-be-behind blur">This div must be behind</div></code>```

I'm looking for a workaround to make the red div go over the blurred div. I've already read about stacking order and painting order but couldn't come up with any solution. Any ideas?

UPDATE

I need the red div to be on top of any element regardless of what they are, and I'm not in control of editing them.

答:
Why is blur a parent of must-be-top? Changing that, and applying z-index: -1; to must-be-behind will fix your problem:

* {
  color: white;
}

.must-be-top {
  background-color: red;
  height: 200px;
  width: 200px;
  position: absolute;
  left: 20px;
  top: 20px;
}
.v-space {
  height: 10px;
}
.blur {
  height: 50px;
  width: 400px;
  background-color: rgba(0, 0, 0, .8);
  -webkit-filter: blur(1px);
}
.must-be-behind {
  z-index: -1;          /* new line */
  position: relative;   /* new line */
  -webkit-filter: blur(1px) /* new line */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html>
    <head>
    </head>
    <body>
        <div class="blur">This is the blurred container</div> <!-- edited line -->
        <div class="must-be-top">This div must be on top</div>
        <div class="v-space"></div>
        <div class="must-be-behind blur">This div must be behind</div>
    </body>
    </html></code>```

Body:
Here's the problem

* {
  color: white;
}

.must-be-top {
  background-color: red;
  height: 200px;
  width: 200px;
  position: absolute;
  left: 20px;
  top: 20px;
  z-index: 1999;
}

.v-space {
  height: 10px;
}

.blur {
  height: 50px;
  width: 400px;
  background-color: rgba(0, 0, 0, .8);
  backdrop-filter: blur(10px);
}

This is the blurred container

This div must be on top

This div must be behind

I'm looking for a workaround to make the red div go over the blurred div. I've already read about stacking order and painting order but couldn't come up with any solution. Any ideas?

UPDATE

I need the red div to be on top of any element regardless of what they are, and I'm not in control of editing them.

Body:
Why is blur a parent of must-be-top? Changing that, and applying z-index: -1; to must-be-behind will fix your problem:

* {
  color: white;
}

.must-be-top {
  background-color: red;
  height: 200px;
  width: 200px;
  position: absolute;
  left: 20px;
  top: 20px;
}
.v-space {
  height: 10px;
}
.blur {
  height: 50px;
  width: 400px;
  background-color: rgba(0, 0, 0, .8);
  -webkit-filter: blur(1px);
}
.must-be-behind {
  z-index: -1;          /* new line */
  position: relative;   /* new line */
  -webkit-filter: blur(1px) /* new line */
}

<!DOCTYPE HTML>
<html>
    <head>
    </head>
    <body>
        <div class="blur">This is the blurred container</div> <!-- edited line -->
        <div class="must-be-top">This div must be on top</div>
        <div class="v-space"></div>
        <div class="must-be-behind blur">This div must be behind</div>
    </body>
    </html>


问:
Special function in Google Sheet

Hi everyone, please advise.

I can't come up with a combination of functions (MATCH,LOOKUP,etc.) in Google Sheets that would return the row number of the cell that matches the given rule in the given range. Moreover, I need to find this value from bottom to top.

I am attaching an image in which I show the invented function "FIRST_VALUE", which in this particular case should return the value "5", because just 5 rows above is the value 655.79, which is higher than the rule ">655".

Thank you very much!

答:
Simpler option:

```<code>=ArrayFormula(ROW()-MAX(ROW(A:A)*(A:A>655)*(ROW(A:A)<ROW())))
</code>```

Title: Special function in Google Sheet

Body:
Simpler option:

=ArrayFormula(ROW()-MAX(ROW(A:A)*(A:A>655)*(ROW(A:A)<ROW())))