问:
Move Top cut corner to bottom using linear-gradient
Good morning,

I need assistance with the below attached image:

Cut corner

Using linear gradient how do I move the top cut corner to the bottom corner and make the top corner square/sharp like the other corners. Please see current css below:

```<code>body.page {
  background: url(../img/Login-bg.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
  font-size: 14px;
  align-items: center;
  padding-top: 50px;
  padding-bottom: 50px;
}

.cut-corner {
  position: relative;
  color: #4a4a4c;
  background-repeat: no-repeat;
  background-image: linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431),
    linear-gradient(to bottom left, transparent calc(50% - 0.5px), #bcd431 calc(50% - 0.5px), #bcd431 calc(50% + 0.5px), transparent calc(50% + 0.5px)), linear-gradient(transparent, transparent), linear-gradient(transparent, transparent);
  background-size: 1.5px 100%, 1.5px 100%, 100% 1.5px, 100% 1.5px, 65px 65px, 100% 100%, 100% 100%;
  background-position: 0% 0%, 100% 65px, -65px 0%, 0px 100%, 100% 0%, -65px 0%, 100% 65px;
  margin: 25px;
}

.cut-corner:after {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  top: 0;
  z-index: -1;
  opacity: 100%;
  background-repeat: no-repeat;
  background-image: linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431),
    linear-gradient(to bottom left, transparent calc(50% - 0.5px), #bcd431 calc(50% - 0.5px), #bcd431 calc(50% + 0.5px), transparent calc(50% + 0.5px)), linear-gradient(transparent, transparent), linear-gradient(transparent, transparent);
  background-size: 0.5px 100%, 1.5px 100%, 100% 0.5px, 100% 1.5px, 65px 65px, 100% 100%, 100% 100%;
  background-position: 0% 0%, 100% 65px, -65px 0%, 0px 100%, 100% 0%, -65px 0%, 100% 65px;
}
</code>```

HTML:

```<code><body class="page cut-corner">
...
</body>
</code>```

Any assistance would be greatly appreciated.

答:
You can try like below, a combination of gradient and clip-path which is easier to handle

.box {
  margin:10px;
  height:200px;
  border: 2px solid red;
  background:
    linear-gradient(to bottom right,transparent 50%,red 50.5%)
    bottom right/50px 50px no-repeat;
  clip-path:polygon(0 0,100% 0,100% calc(100% - 50px),calc(100% - 50px) 100%, 0 100%);
}

body {
  background:yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></div></code>```

With CSS variable to easily adjust the corner:

.box {
  --c:50px;

  margin:10px;
  height:200px;
  border: 2px solid red;
  background:
    linear-gradient(to bottom right,transparent 50%,red 50.5%)
    bottom right/var(--c) var(--c) no-repeat;
  clip-path:polygon(0 0,100% 0,100% calc(100% - var(--c)),calc(100% - var(--c)) 100%, 0 100%);
}

body {
  background:yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></div>

<div class="box" style="--c:100px;"></div></code>```

Body:
Good morning,

I need assistance with the below attached image:

Cut corner

Using linear gradient how do I move the top cut corner to the bottom corner and make the top corner square/sharp like the other corners. Please see current css below:

body.page {
  background: url(../img/Login-bg.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
  font-size: 14px;
  align-items: center;
  padding-top: 50px;
  padding-bottom: 50px;
}

.cut-corner {
  position: relative;
  color: #4a4a4c;
  background-repeat: no-repeat;
  background-image: linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431),
    linear-gradient(to bottom left, transparent calc(50% - 0.5px), #bcd431 calc(50% - 0.5px), #bcd431 calc(50% + 0.5px), transparent calc(50% + 0.5px)), linear-gradient(transparent, transparent), linear-gradient(transparent, transparent);
  background-size: 1.5px 100%, 1.5px 100%, 100% 1.5px, 100% 1.5px, 65px 65px, 100% 100%, 100% 100%;
  background-position: 0% 0%, 100% 65px, -65px 0%, 0px 100%, 100% 0%, -65px 0%, 100% 65px;
  margin: 25px;
}

.cut-corner:after {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  top: 0;
  z-index: -1;
  opacity: 100%;
  background-repeat: no-repeat;
  background-image: linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431),
    linear-gradient(to bottom left, transparent calc(50% - 0.5px), #bcd431 calc(50% - 0.5px), #bcd431 calc(50% + 0.5px), transparent calc(50% + 0.5px)), linear-gradient(transparent, transparent), linear-gradient(transparent, transparent);
  background-size: 0.5px 100%, 1.5px 100%, 100% 0.5px, 100% 1.5px, 65px 65px, 100% 100%, 100% 100%;
  background-position: 0% 0%, 100% 65px, -65px 0%, 0px 100%, 100% 0%, -65px 0%, 100% 65px;
}

HTML:

...

Any assistance would be greatly appreciated.

Body:
You can try like below, a combination of gradient and clip-path which is easier to handle

.box {
  margin:10px;
  height:200px;
  border: 2px solid red;
  background:
    linear-gradient(to bottom right,transparent 50%,red 50.5%)
    bottom right/50px 50px no-repeat;
  clip-path:polygon(0 0,100% 0,100% calc(100% - 50px),calc(100% - 50px) 100%, 0 100%);
}

body {
  background:yellow;
}

<div class="box"></div>

With CSS variable to easily adjust the corner:

.box {
  --c:50px;

  margin:10px;
  height:200px;
  border: 2px solid red;
  background:
    linear-gradient(to bottom right,transparent 50%,red 50.5%)
    bottom right/var(--c) var(--c) no-repeat;
  clip-path:polygon(0 0,100% 0,100% calc(100% - var(--c)),calc(100% - var(--c)) 100%, 0 100%);
}

body {
  background:yellow;
}

<div class="box"></div>

<div class="box" style="--c:100px;"></div>


来源: stackexchange

问:
How to access input value in multiple component?
I have 2 components :  headerComponent and searchPageComponent.

    Whatever the value we enter on header component search bar, the search page component should get the value.

header.component.html

```<code><form class="form-inline md-form form-sm">
          <input class="form-control form-control-sm mr-3 w-75" id="searchString" type="text"
             placeholder="Search" [(ngModel)]="searchValue" name="searchString" (ngModelChange)="onChange($event)">
          <button class="headerSearchbarBtn" id="btnSearch" routerLink="/searchResult">
              <span class="headerSearchbarIcon"></span>
           </button>
       </form>
</code>```

header.component.ts

```<code>export class HeaderComponent implements OnInit {
        searchValue: string;
        constructor(private router: Router) { }
        ngOnInit() {
         }
         onChange($event) {
          this.searchValue = $event;
         }
       }
</code>```

Search.component.ts

```<code>export class SearchComponent implements  OnInit {
        ngOnInit() {
          console.log(this.searchValue); // 'this.searchValue' => value should come from header.compomnent.ts
        }
      }
</code>```

There is no parent child relation here, I want to know how the data is passed from one component to other,
    and Why cant we directly access the input field box value in different components in Angular?

答:
You can use a service and a subject to communicate between sibling components</p>

```<code>export class SharedService {

    private searchInputSource = new Subject<string>();

    searchInput = this.searchInputSource.asObservable();

    setSearchInput(value: string) {
        this.searchInput.next(value);
    }
}
</code>```

```<code>export class HeaderComponent implements OnInit {
    searchInput: string;
    constructor(private sharedService: SharedService) { }
    ngOnInit() {
    }
    onChange($event) {
        this.sharedService.setSearchInput.next($event);
    });
}
</code>```

```<code>export class SearchComponent implements OnInit, OnDestroy {

    privates subscription: Subscription;
    searchInput: string;

    ngOnInit(private sharedService: SharedService) {
        this.subscription = sharedService.searchInput.subscribe(
            value => {
                this.searchInput = value;
            });
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have 2 components :  headerComponent and searchPageComponent.

    Whatever the value we enter on header component search bar, the search page component should get the value.

header.component.html

<form class="form-inline md-form form-sm">
          <input class="form-control form-control-sm mr-3 w-75" id="searchString" type="text"
             placeholder="Search" [(ngModel)]="searchValue" name="searchString" (ngModelChange)="onChange($event)">
          <button class="headerSearchbarBtn" id="btnSearch" routerLink="/searchResult">

           </button>
       </form>

header.component.ts

export class HeaderComponent implements OnInit {
        searchValue: string;
        constructor(private router: Router) { }
        ngOnInit() {
         }
         onChange($event) {
          this.searchValue = $event;
         }
       }

Search.component.ts

export class SearchComponent implements  OnInit {
        ngOnInit() {
          console.log(this.searchValue); // 'this.searchValue' => value should come from header.compomnent.ts
        }
      }

There is no parent child relation here, I want to know how the data is passed from one component to other,
    and Why cant we directly access the input field box value in different components in Angular?

Body:
You can use a service and a subject to communicate between sibling components

export class SharedService {

    private searchInputSource = new Subject<string>();

    searchInput = this.searchInputSource.asObservable();

    setSearchInput(value: string) {
        this.searchInput.next(value);
    }
}

export class HeaderComponent implements OnInit {
    searchInput: string;
    constructor(private sharedService: SharedService) { }
    ngOnInit() {
    }
    onChange($event) {
        this.sharedService.setSearchInput.next($event);
    });
}

export class SearchComponent implements OnInit, OnDestroy {

    privates subscription: Subscription;
    searchInput: string;

    ngOnInit(private sharedService: SharedService) {
        this.subscription = sharedService.searchInput.subscribe(
            value => {
                this.searchInput = value;
            });
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}


问:
How do you fight design complexity?
I often find myself fighting overengineering -- the person in charge of designing the software comes up with an architecture that's, way, way overcomplicated.

It's all fine and dandy to have all the esoteric features that users will never know about and get that sense of achievement when you're doing something that all the magazine articles are telling you is the latest, cool thing, but we are going to spend half of our  engineering time on this monument to our cleverness, and not, you know, the actual product that our users need and upper management expects to be completed within a reasonable or at least a bounded time frame.

And you'll probably just have to revert back to the simpler solution anyway when you start running out of time, that is, if you get that chance.

We've all heard the refrain: Keep It Simple, Stupid™.

How do you fight with overcomplexity in your team?

One example I've had to work with repeatedly lately is when the decision has been made to go to a fully denormalized database design rather than an RDBMS. "because it's faster!" Fully denormalized databases are really hard to get right, and are only appropriate for really specialized data problems like Flickr or ebay, and which can be extremely expensive in terms of developer time relative to the rest of your development.

答:
The solution should be no more complex than the problem.

The question intertwines itself with the thought of essential complexity. A sort must touch each element, by its essence. How much more complex must it then get, to solve the problem, given the technical constraints existing on it?

OwnerDisplayName: ʞɔıu

ContentLicense: CC BY-SA 2.5

Title: How do you fight design complexity?

LastEditorDisplayName: philippe

OwnerDisplayName: Paul Nathan


问:
Laravel Eager Loading for relationship model - unable to reduce queries unless i return null
I am trying to make reduce my database queries when retrieving from the database using Eloquent.

I'm trying to take advantage of Eager Loading to reduce the queries and not get the N+1 issue.. I've got some relationships in my models too.

I have noticed (and I'm not sure if this is a red herring) that if I just return null from my controller method then I get 6 queries. Which would indicate Eager Loading working. But I get 492 queries when I return the result of the eloquent variable. EG. In my controller:

```<code>    public function getJobItems()
    {

        $userId = auth()->user()->id;

        $jobs = JobItem::with(['project', 'user'])
            ->whereHas('project', function ($query) use ($userId) {
                $query->where('user_id', '=', $userId);
            })
            ->get();

        return $jobs;

    }
</code>```

If I change return $jobs; to just return; then I can see only 6 queries (shown with Laravel Telescope). I'm not sure how outputting the $jobs var changes the queries made to the DB. Here is what I get from Telescope query inspector for those 6 queries:

```<code>update `sessions` set `payload` =...
select `users`.*, `projects`.`user_id` as `laravel_through_key` from `users` inner join `projects` on...
select * from `projects` where `projects`.`id` in (5, 9, 15, 111, 116, 117, 118, 119, 123, 124) and...
select * from `job_items` where exists (select * from `projects` where `job_items`.`project_id` =...
select * from `users` where `id` = 1 and `users`.`deleted_at`
select * from `sessions` where `id` = 'acx7zPzeeRVrtI5FTUGUbULm1bEVQ0T5AVylFIf6'
</code>```

When I use return $jobs; I get 492 queries and telescope explains 484 are duplicates. For instance variations on:

```<code>select * from `projects` where `projects`.`id` = 15 and `projects`.`deleted_at` is null limit 1
</code>```

In my JobItem Model I have the following:

```<code>
    public function project()
    {
        return $this->belongsTo('App\Project', 'project_id');
    }

    public function user()
    {

        return $this->hasOneThrough(
            User::class,
            Project::class,
            'user_id',
            'id',
            'project_id',
            'id'
        );
    }
</code>```

I have the following tables:

```<code>table: job_items
columns: id, project_id

table: projects
columns: id, user_id

table: users
column: id

</code>```

I want to output all users connected to JobItems

In my JobItem.php model I have tried

```<code>class JobItem extends Model
{

    public function user()
    {

        return $this->hasOneThrough(
            Project::class,
            User::class,
            'project_id',
            'id',
            'belongs_to',
            'user_id'
        );

    }
}

</code>```

Any ideas on how to reduce my queries with these models would be appreciated. Thanks

答:
Change your controller to this one.

```<code>public function getJobItems()
{

        $userId = auth()->user()->id;

        $jobs = JobItem::whereHas('project', function ($query) use ($userId) {
                $query->where('user_id', '=', $userId);
            })->with(['project', 'user'])->get();

        return $jobs;

}
</code>```

It might be because the order of your whereHas should before your with.

Body:
I am trying to make reduce my database queries when retrieving from the database using Eloquent.

I'm trying to take advantage of Eager Loading to reduce the queries and not get the N+1 issue.. I've got some relationships in my models too.

I have noticed (and I'm not sure if this is a red herring) that if I just return null from my controller method then I get 6 queries. Which would indicate Eager Loading working. But I get 492 queries when I return the result of the eloquent variable. EG. In my controller:

    public function getJobItems()
    {

        $userId = auth()->user()->id;

        $jobs = JobItem::with(['project', 'user'])
            ->whereHas('project', function ($query) use ($userId) {
                $query->where('user_id', '=', $userId);
            })
            ->get();

        return $jobs;

    }

If I change return $jobs; to just return; then I can see only 6 queries (shown with Laravel Telescope). I'm not sure how outputting the $jobs var changes the queries made to the DB. Here is what I get from Telescope query inspector for those 6 queries:

update `sessions` set `payload` =...
select `users`.*, `projects`.`user_id` as `laravel_through_key` from `users` inner join `projects` on...
select * from `projects` where `projects`.`id` in (5, 9, 15, 111, 116, 117, 118, 119, 123, 124) and...
select * from `job_items` where exists (select * from `projects` where `job_items`.`project_id` =...
select * from `users` where `id` = 1 and `users`.`deleted_at`
select * from `sessions` where `id` = 'acx7zPzeeRVrtI5FTUGUbULm1bEVQ0T5AVylFIf6'

When I use return $jobs; I get 492 queries and telescope explains 484 are duplicates. For instance variations on:

select * from `projects` where `projects`.`id` = 15 and `projects`.`deleted_at` is null limit 1

In my JobItem Model I have the following:

    public function project()
    {
        return $this->belongsTo('App\Project', 'project_id');
    }

    public function user()
    {

        return $this->hasOneThrough(
            User::class,
            Project::class,
            'user_id',
            'id',
            'project_id',
            'id'
        );
    }

I have the following tables:

table: job_items
columns: id, project_id

table: projects
columns: id, user_id

table: users
column: id

I want to output all users connected to JobItems

In my JobItem.php model I have tried

class JobItem extends Model
{

    public function user()
    {

        return $this->hasOneThrough(
            Project::class,
            User::class,
            'project_id',
            'id',
            'belongs_to',
            'user_id'
        );

    }
}

Any ideas on how to reduce my queries with these models would be appreciated. Thanks

Body:
Change your controller to this one.

public function getJobItems()
{

        $userId = auth()->user()->id;

        $jobs = JobItem::whereHas('project', function ($query) use ($userId) {
                $query->where('user_id', '=', $userId);
            })->with(['project', 'user'])->get();

        return $jobs;

}

It might be because the order of your whereHas should before your with.


问:
How to implement a triggerless .NET Core Console App as a continuous Azure WebJob?
All the code samples I've seen so far for Azure WebJobs rely on some kind of trigger (e.g. TimerTrigger or QueueTrigger).
I am looking specifically at WebJobs SDK 3.x, by the way.

So. For a triggerless WebJob (Windows Service-alike one), am I expected to use NoAutomaticTrigger and find a way to kickoff my "main" code manually?

Or should I resort to implementing and registering a class that implements the IHostedService interface?
So far that's the approach I'm taking but it feels more of a hack than a recommended way.
I have not even tried to deploy this code and only ran it on my local machine, so I am afraid that the publishing process will confirm my code is not suitable for Azure WebJobs in its current form.

EntryPoint.cs

This is how the application is being bootstrap when the process is starting.

using Microsoft.Azure.ServiceBus;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace AbcCorp.Jobs
{
    public static class Program
    {
        static async Task Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", false)
                .Build();

            var hostBuilder = new HostBuilder()
                .ConfigureWebJobs(builder => { builder.AddAzureStorageCoreServices(); })
                .ConfigureServices(serviceCollection =>
                {
                    ConfigureServices(serviceCollection, config);
                    serviceCollection.AddHostedService<ConsoleApplication>();
                });

            using (var host = hostBuilder.Build())
                await host.RunAsync();
        }

        private static IServiceCollection ConfigureServices(IServiceCollection services, IConfigurationRoot configuration)
        {
            services.AddTransient<ConsoleApplication>();
            // ... more DI registrations
            return services;
        }
    }
}
```

<p><strong>ConsoleApplication.cs</strong></p>

<p>This would normally be implemented as a function with a trigger.
The thing is, I want this code to only run once on the process startup.
It will start listening on the service bus events using the regular <code>Microsoft.Azure.ServiceBus</code> SDK package.</p>

<pre class="lang-cs prettyprint-override"><code>using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using AbcCorp.Internal.Microsoft.Azure.ServiceBus;
using AbcCorp.Api.Messaging;

namespace AbcCorp.Jobs
{
    public sealed class ConsoleApplication: IHostedService
    {
        private readonly IReceiver<SubmissionNotification> _messageReceiver;
        private readonly MessageHandler _messageHandler;

        public ConsoleApplication(IReceiver<SubmissionNotification> messageReceiver, MessageHandler messageHandler)
        {
            _messageReceiver = messageReceiver;
            _messageHandler = messageHandler;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _messageReceiver.StartListening(_messageHandler.HandleMessage, _messageHandler.HandleException);
            return Task.Delay(Timeout.Infinite);
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _messageReceiver.Dispose();
            return Task.CompletedTask;
        }
    }
}
</code>```

答:
I have some workers attached to service bus topics and what we do is the following (ServiceBusClient is a custom Class that contains our Subscription Client):

```<code>public override Task StartAsync(CancellationToken cancellationToken)
    {
        _serviceBusClient.RegisterOnMessageHandlerAndReceiveMessages(MessageReceivedAsync);

        _logger.LogDebug($"Started successfully the Import Client. Listening for messages...");
        return base.StartAsync(cancellationToken);
    }

        public void RegisterOnMessageHandlerAndReceiveMessages(Func<Message, CancellationToken, Task> ProcessMessagesAsync)
    {
        // Configure the message handler options in terms of exception handling, number of concurrent messages to deliver, etc.
        var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
        {
            // Maximum number of concurrent calls to the callback ProcessMessagesAsync(), set to 1 for simplicity.
            // Set it according to how many messages the application wants to process in parallel.
            MaxConcurrentCalls = 1,

            // Indicates whether MessagePump should automatically complete the messages after returning from User Callback.
            // False below indicates the Complete will be handled by the User Callback as in `ProcessMessagesAsync` below.
            AutoComplete = false
        };

        // Register the function that processes messages.
        SubscriptionClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
    }
</code>```

And then you can use DI to instantiate your service bus client and inject on the constructor of your Worker class.

Here i have the initialization of the singleton instance of my custom class Service Bus Client

```<code>services.AddSingleton<IServiceBusClient, ServiceBusClient>((p) =>
                {

                    var diagnostics = p.GetService<EventHandling>();
                    var sbc = new ServiceBusClient(
                        programOptions.Endpoint,
                        programOptions.TopicName,
                        programOptions.Subscriber,
                        programOptions.SubscriberKey);

                    sbc.Exception += exception => diagnostics.HandleException(exception);

                    return sbc;
                });
</code>```

Then on this custom class, i initialize my subscription client

```<code>public ServiceBusClient(
        string endpoint,
        string topicName,
        string subscriberName,
        string subscriberKey, ReceiveMode mode = ReceiveMode.PeekLock)
    {
        var connBuilder = new ServiceBusConnectionStringBuilder(endpoint, topicName, subscriberName, subscriberKey);
        var connectionString = connBuilder.GetNamespaceConnectionString();

        ConnectionString = connectionString;
        TopicName = topicName;
        SubscriptionName = topicName;

        SubscriptionClient = new SubscriptionClient(connectionString, topicName, subscriberName, mode);
    }
</code>```

Body:
All the code samples I've seen so far for Azure WebJobs rely on some kind of trigger (e.g. TimerTrigger or QueueTrigger).
I am looking specifically at WebJobs SDK 3.x, by the way.

So. For a triggerless WebJob (Windows Service-alike one), am I expected to use NoAutomaticTrigger and find a way to kickoff my "main" code manually?

Or should I resort to implementing and registering a class that implements the IHostedService interface?
So far that's the approach I'm taking but it feels more of a hack than a recommended way.
I have not even tried to deploy this code and only ran it on my local machine, so I am afraid that the publishing process will confirm my code is not suitable for Azure WebJobs in its current form.

EntryPoint.cs

This is how the application is being bootstrap when the process is starting.

using Microsoft.Azure.ServiceBus;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace AbcCorp.Jobs
{
    public static class Program
    {
        static async Task Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", false)
                .Build();

            var hostBuilder = new HostBuilder()
                .ConfigureWebJobs(builder => { builder.AddAzureStorageCoreServices(); })
                .ConfigureServices(serviceCollection =>
                {
                    ConfigureServices(serviceCollection, config);
                    serviceCollection.AddHostedService<ConsoleApplication>();
                });

            using (var host = hostBuilder.Build())
                await host.RunAsync();
        }

        private static IServiceCollection ConfigureServices(IServiceCollection services, IConfigurationRoot configuration)
        {
            services.AddTransient<ConsoleApplication>();
            // ... more DI registrations
            return services;
        }
    }
}

ConsoleApplication.cs

This would normally be implemented as a function with a trigger.
The thing is, I want this code to only run once on the process startup.
It will start listening on the service bus events using the regular Microsoft.Azure.ServiceBus SDK package.

using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using AbcCorp.Internal.Microsoft.Azure.ServiceBus;
using AbcCorp.Api.Messaging;

namespace AbcCorp.Jobs
{
    public sealed class ConsoleApplication: IHostedService
    {
        private readonly IReceiver<SubmissionNotification> _messageReceiver;
        private readonly MessageHandler _messageHandler;

        public ConsoleApplication(IReceiver<SubmissionNotification> messageReceiver, MessageHandler messageHandler)
        {
            _messageReceiver = messageReceiver;
            _messageHandler = messageHandler;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _messageReceiver.StartListening(_messageHandler.HandleMessage, _messageHandler.HandleException);
            return Task.Delay(Timeout.Infinite);
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _messageReceiver.Dispose();
            return Task.CompletedTask;
        }
    }
}

Body:
I have some workers attached to service bus topics and what we do is the following (ServiceBusClient is a custom Class that contains our Subscription Client):

public override Task StartAsync(CancellationToken cancellationToken)
    {
        _serviceBusClient.RegisterOnMessageHandlerAndReceiveMessages(MessageReceivedAsync);

        _logger.LogDebug($"Started successfully the Import Client. Listening for messages...");
        return base.StartAsync(cancellationToken);
    }

        public void RegisterOnMessageHandlerAndReceiveMessages(Func<Message, CancellationToken, Task> ProcessMessagesAsync)
    {
        // Configure the message handler options in terms of exception handling, number of concurrent messages to deliver, etc.
        var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
        {
            // Maximum number of concurrent calls to the callback ProcessMessagesAsync(), set to 1 for simplicity.
            // Set it according to how many messages the application wants to process in parallel.
            MaxConcurrentCalls = 1,

            // Indicates whether MessagePump should automatically complete the messages after returning from User Callback.
            // False below indicates the Complete will be handled by the User Callback as in `ProcessMessagesAsync` below.
            AutoComplete = false
        };

        // Register the function that processes messages.
        SubscriptionClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
    }

And then you can use DI to instantiate your service bus client and inject on the constructor of your Worker class.

Here i have the initialization of the singleton instance of my custom class Service Bus Client

services.AddSingleton<IServiceBusClient, ServiceBusClient>((p) =>
                {

                    var diagnostics = p.GetService<EventHandling>();
                    var sbc = new ServiceBusClient(
                        programOptions.Endpoint,
                        programOptions.TopicName,
                        programOptions.Subscriber,
                        programOptions.SubscriberKey);

                    sbc.Exception += exception => diagnostics.HandleException(exception);

                    return sbc;
                });

Then on this custom class, i initialize my subscription client

public ServiceBusClient(
        string endpoint,
        string topicName,
        string subscriberName,
        string subscriberKey, ReceiveMode mode = ReceiveMode.PeekLock)
    {
        var connBuilder = new ServiceBusConnectionStringBuilder(endpoint, topicName, subscriberName, subscriberKey);
        var connectionString = connBuilder.GetNamespaceConnectionString();

        ConnectionString = connectionString;
        TopicName = topicName;
        SubscriptionName = topicName;

        SubscriptionClient = new SubscriptionClient(connectionString, topicName, subscriberName, mode);
    }


问:
How to make django reload server without change any code after few hours?
I have develop a django apps, and i start the server by using python manage.py runserver. without stop the server and without edit any code I wish it reload the server after 24 hoursy, any ideas on this?</p>

答:
Does it automatically reload when you edit one of its source files, like it does on Linux?

In that case, arrange for something to execute periodically, that "edits" a source file. Almost certainly, open for write and close is sufficient. On linux, touch file.py causes a restart. As a last resort  create a Python file that is imported by your project, containing a function that you don't actually use. To restart, replace it with a copy of itself.


问:
using numpy.memmap to map a device file
Is there a reason that opening a device file (rather than a regular file) using numpy's memmap shouldn't work?

```<code>self.surface = np.memmap('/dev/fb1', dtype=np.uint16, mode='r+', shape=(320,240))
</code>```

I'm working with a custom kernel module that adds a framebuffer device, which works fine with python's regular mmap module. But using numpy seems to hang the kernel's mutex on accessing the filesystem or something (I'm really not sure exactly what's happening).

My question here is specifically is this something that numpy's memmap can't handle and I should go a different way?

I've asked another question on unix stackexchange, but I feel like it's 2 different questions so I've posted them both.

Obviously this is on linux (kubuntu maverick with custom kernel module)

Update:

Well, it turns out I can create the memmap fine. The problem it seems is that when I close the process without specifically closing the memmap object and it will just hang on the mutex in the kernel.

I have no idea if this issue is with numpy, or my kernel module, or somewhere else.

答:
If your code works fine with the python mmap module,  you can use it directly instead of numpy.memmap:

```<code>>>> fd = os.open("a", os.O_RDWR)
>>> buffer = mmap.mmap(fd, 0)
>>> surface = np.ndarray((320,240), np.uint16, buffer)
</code>```

This has the other advantage that you have more control over the memory mapping used.

Now, python's mmap has its own peculiarities.   As the source shows, it calls msync on delallocation.  Maybe this is where your program hangs? (You might be able to reproduce your issue with buffer.flush(), which also calls msync).  Your solution of calling close() first probably works because it circumvents msync!

ContentLicense: CC BY-SA 3.0

Title: using numpy.memmap to map a device file

Body:
Is there a reason that opening a device file (rather than a regular file) using numpy's memmap shouldn't work?

self.surface = np.memmap('/dev/fb1', dtype=np.uint16, mode='r+', shape=(320,240))

I'm working with a custom kernel module that adds a framebuffer device, which works fine with python's regular mmap module. But using numpy seems to hang the kernel's mutex on accessing the filesystem or something (I'm really not sure exactly what's happening).

My question here is specifically is this something that numpy's memmap can't handle and I should go a different way?

I've asked another question on unix stackexchange, but I feel like it's 2 different questions so I've posted them both.

Obviously this is on linux (kubuntu maverick with custom kernel module)

Update:

Well, it turns out I can create the memmap fine. The problem it seems is that when I close the process without specifically closing the memmap object and it will just hang on the mutex in the kernel.

I have no idea if this issue is with numpy, or my kernel module, or somewhere else.

Body:
If your code works fine with the python mmap module,  you can use it directly instead of numpy.memmap:

>>> fd = os.open("a", os.O_RDWR)
>>> buffer = mmap.mmap(fd, 0)
>>> surface = np.ndarray((320,240), np.uint16, buffer)

This has the other advantage that you have more control over the memory mapping used.

Now, python's mmap has its own peculiarities.   As the source shows, it calls msync on delallocation.  Maybe this is where your program hangs? (You might be able to reproduce your issue with buffer.flush(), which also calls msync).  Your solution of calling close() first probably works because it circumvents msync!


问:
I am getting the bottom line for only first two characters in the dropdown in bootstrap
In my code, I am getting the bottom borders for only "High Spot" but I need to get the border for all the label help me with this  </p>

```<code><div class="form-group">
      <label for="text" class="font-weight-bold"> What is the preferred order methodology? </label>
      <br>
      <button type="button" class="btn btn dropdown-toggle border-bottom" data-toggle="dropdown">
          High Spot Frequency.Low Avg.Rate
      </button>
</div>
</code>```

答: thank you guys i get the answer just by adding the css and increase the width </p>

Body:
In my code, I am getting the bottom borders for only "High Spot" but I need to get the border for all the label help me with this

       What is the preferred order methodology?

      <button type="button" class="btn btn dropdown-toggle border-bottom" data-toggle="dropdown">
          High Spot Frequency.Low Avg.Rate
      </button>


问:
Creating an update trigger that uses data from 2 tables
Okay, so I have made the changes that i know how to make but I am still stuck at how to bring the accessory table in. For those first time here, I'm trying to create a trigger that checks that prices are appropriately changed. However, one of the columns I need comes from another table and I'm not quite sure how to declare that variable. This is my current attempt.

The ACCESSORY table is a child of the PRODUCT table being connected with ProductCode and has only 1 other column called Class which stands for classification. The trigger i created is currently for the PRODUCT table as that is where all the prices are recorded

```<code>CREATE TRIGGER PriceCheck1
ON PRODUCT
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @ProductCode        AS  Char(6),
        @ProductName        AS  VarChar(50),
        @StockLevel         AS  Int,
        @OldPrice           AS  float, @NewPrice AS float,
        @ProductType        AS  VarChar(9)
        --@Class                AS VarChar(20)
/*SELECT i.ProductCode, i.ProductName, i.ProductStockLevel, i.ProductPrice, i.ProductType, a.Class
INTO #TempTable
FROM inserted i JOIN ACCESSORY a ON i.ProductCode = a.ProductCode*/

SELECT  @ProductCode = ProductCode, @ProductName = ProductName,
        @StockLevel = ProductStockLevel, @NewPrice = ProductPrice,
        @ProductType = ProductType --@Class = Class
FROM    inserted;--FROM    #TempTable

SELECT  @ProductCode = ProductCode, @ProductName = ProductName,
        @StockLevel = ProductStockLevel, @OldPrice = ProductPrice,
        @ProductType = ProductType
FROM    deleted;

IF UPDATE(ProductPrice)
BEGIN
    IF (@ProductType = 'Food Item' AND @NewPrice > 200)
    BEGIN
        RAISERROR('The price of food item cannot exceed $200.', 16, 1)
        ROLLBACK TRANSACTION
    END
    ELSE IF (@ProductType = 'Accessory' AND @NewPrice < 50)--AND @Class = 'Bed and Bedding'
    BEGIN
        RAISERROR('The price of any accessory with a classification that includes the word bed cannot be less than $50.', 16, 1)
        ROLLBACK TRANSACTION
    END
    ELSE
        print 'Price of Product Code ' + @ProductCode + ' has been changed from $' + Cast(@OldPrice AS nVarChar(10)) + ' to $' + Cast(@NewPrice AS nVarChar(10)) + '.'
END
END
</code>```

The Areas that i commented out are the codes i tried. The trigger works fine without the commented out areas but now when i tried to bring the accessory table in, the trigger doesn't even fire when i update the table.

答:
You're not declaring @Class, and you're not assigning it a value.
What are you expecting @Class to be, and how is it getting assigned a value?

edit: I don't think you even need to do this. Confirm that there is only a 1-1 relationship between Product and Accessory? In which case you don't need the where clause.

```<code>SELECT *
INTO #TempTable
FROM PRODUCT p JOIN ACCESSORY a ON p.ProductCode = a.ProductCode
</code>```

And then Class will be in that temp table, and you can assign it as required the same as you have already done for the other values.

Body:
Okay, so I have made the changes that i know how to make but I am still stuck at how to bring the accessory table in. For those first time here, I'm trying to create a trigger that checks that prices are appropriately changed. However, one of the columns I need comes from another table and I'm not quite sure how to declare that variable. This is my current attempt.

The ACCESSORY table is a child of the PRODUCT table being connected with ProductCode and has only 1 other column called Class which stands for classification. The trigger i created is currently for the PRODUCT table as that is where all the prices are recorded

CREATE TRIGGER PriceCheck1
ON PRODUCT
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @ProductCode        AS  Char(6),
        @ProductName        AS  VarChar(50),
        @StockLevel         AS  Int,
        @OldPrice           AS  float, @NewPrice AS float,
        @ProductType        AS  VarChar(9)
        --@Class                AS VarChar(20)
/*SELECT i.ProductCode, i.ProductName, i.ProductStockLevel, i.ProductPrice, i.ProductType, a.Class
INTO #TempTable
FROM inserted i JOIN ACCESSORY a ON i.ProductCode = a.ProductCode*/

SELECT  @ProductCode = ProductCode, @ProductName = ProductName,
        @StockLevel = ProductStockLevel, @NewPrice = ProductPrice,
        @ProductType = ProductType --@Class = Class
FROM    inserted;--FROM    #TempTable

SELECT  @ProductCode = ProductCode, @ProductName = ProductName,
        @StockLevel = ProductStockLevel, @OldPrice = ProductPrice,
        @ProductType = ProductType
FROM    deleted;

IF UPDATE(ProductPrice)
BEGIN
    IF (@ProductType = 'Food Item' AND @NewPrice > 200)
    BEGIN
        RAISERROR('The price of food item cannot exceed $200.', 16, 1)
        ROLLBACK TRANSACTION
    END
    ELSE IF (@ProductType = 'Accessory' AND @NewPrice < 50)--AND @Class = 'Bed and Bedding'
    BEGIN
        RAISERROR('The price of any accessory with a classification that includes the word bed cannot be less than $50.', 16, 1)
        ROLLBACK TRANSACTION
    END
    ELSE
        print 'Price of Product Code ' + @ProductCode + ' has been changed from $' + Cast(@OldPrice AS nVarChar(10)) + ' to $' + Cast(@NewPrice AS nVarChar(10)) + '.'
END
END

The Areas that i commented out are the codes i tried. The trigger works fine without the commented out areas but now when i tried to bring the accessory table in, the trigger doesn't even fire when i update the table.

Body:
You're not declaring @Class, and you're not assigning it a value.
What are you expecting @Class to be, and how is it getting assigned a value?

edit: I don't think you even need to do this. Confirm that there is only a 1-1 relationship between Product and Accessory? In which case you don't need the where clause.

SELECT *
INTO #TempTable
FROM PRODUCT p JOIN ACCESSORY a ON p.ProductCode = a.ProductCode

And then Class will be in that temp table, and you can assign it as required the same as you have already done for the other values.


问:
Can we use rems to style a component in react native
I want to use rems for styling as I normally do in other CSS projects. But I don't understand how to get this working. This doesn't seem to work at all.

```<code>const styles = StyleSheet.create({
  header: {
    fontSize: 3rem,
    fontWeight: 400
  }
});
</code>```

答:
Yes, you can!  Using this npm package you can easily do.

STEPS

run npm i react-native-extended-stylesheet --save

Define styles using EStyleSheet.create() instead of StyleSheet.create():

Simple Example :

```<code>/* component.js */
import EStyleSheet from 'react-native-extended-stylesheet';

// define extended styles
const styles = EStyleSheet.create({
  column: {
    width: '80%'                                    // 80% of screen width
  },
  text: {
    color: '$textColor',                            // global variable $textColor
    fontSize: '1.5rem'                              // relative REM unit
  },
  '@media (min-width: 350) and (max-width: 500)': { // media queries
    text: {
      fontSize: '2rem',
    }
  }
});

// use styles as usual
class MyComponent extends React.Component {
  render() {
    return (
      <View style={styles.column}>
        <Text style={styles.text}>Hello</Text>
      </View>
    );
  }
}
</code>```

Body:
I want to use rems for styling as I normally do in other CSS projects. But I don't understand how to get this working. This doesn't seem to work at all.

const styles = StyleSheet.create({
  header: {
    fontSize: 3rem,
    fontWeight: 400
  }
});

Body:
Yes, you can!  Using this npm package you can easily do.

STEPS

run npm i react-native-extended-stylesheet --save

Define styles using EStyleSheet.create() instead of StyleSheet.create():

Simple Example :

/* component.js */
import EStyleSheet from 'react-native-extended-stylesheet';

// define extended styles
const styles = EStyleSheet.create({
  column: {
    width: '80%'                                    // 80% of screen width
  },
  text: {
    color: '$textColor',                            // global variable $textColor
    fontSize: '1.5rem'                              // relative REM unit
  },
  '@media (min-width: 350) and (max-width: 500)': { // media queries
    text: {
      fontSize: '2rem',
    }
  }
});

// use styles as usual
class MyComponent extends React.Component {
  render() {
    return (
      <View style={styles.column}>
        <Text style={styles.text}>Hello</Text>
      </View>
    );
  }
}


问:
Building a plot for each unique value of a column
I have data with multiple variables and I want to make a plot for each of the unique values in one column. I looked at multiple answers on here for similar problems but I couldnt solve mine.

An example of the dataset looks as follows:

```<code>structure(list(ID = c(1, 1, 1, 2, 2), Date = c("01/02/20", "01/03/20",
"01/05/20", "01/02/20", "01/05/20"), New = c(10, 5, 5, 10, 5),
    Old = c(20, 20, 20, 20, 20), Percentage = c(0.5, 0.25, 0.25,
    0.5, 0.25)), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

```<code>ID      Date          New    Old   Percentage
1       01/02/20      10     20    0.5
1       01/03/20      5      20    0.25
1       01/05/20      5      20    0.25
2       01/02/20      10     20    0.5
2       01/05/20      5      20    0.25
</code>```

I wanted to do a for loop that goes over the unique values of ID and plot the new and old vs date. Also maybe another facet that should the percent change but mainly the first comparison plot. I tried first to make it as date vs new as follow:

```<code>for (ii in unique(data$ID)) {
  plt <- ggplot(data %>% filter(ID == ii),
                aes(x = "Month",
                    y = "New")) +
    geom_point(color = "dodgerblue3") +
    theme_minimal()
  print(plt)

}

</code>```

The result basically gave me a on point plot which I didnt understand. How can I add the Old comparison and also another plot for the percentage.

答:
-Regarding your loop, I think you could just use a facet function instead

-About the old/new question, I think that your problem comes from your data structure, which is not tidy.

try this :

```<code>## get tidy data
tidy_data <- data %>% pivot_longer(c("New", "Old"), names_to = "Age", values_to = "Number")

## get the plots (facet_wrap is used to have multiple plots)
plt <- ggplot(tidy_data, aes(x = Date, y = Number, color = Age)) + geom_point() + facet_wrap(~ ID)
plt
</code>```

Body:
I have data with multiple variables and I want to make a plot for each of the unique values in one column. I looked at multiple answers on here for similar problems but I couldnt solve mine.

An example of the dataset looks as follows:

structure(list(ID = c(1, 1, 1, 2, 2), Date = c("01/02/20", "01/03/20",
"01/05/20", "01/02/20", "01/05/20"), New = c(10, 5, 5, 10, 5),
    Old = c(20, 20, 20, 20, 20), Percentage = c(0.5, 0.25, 0.25,
    0.5, 0.25)), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))

ID      Date          New    Old   Percentage
1       01/02/20      10     20    0.5
1       01/03/20      5      20    0.25
1       01/05/20      5      20    0.25
2       01/02/20      10     20    0.5
2       01/05/20      5      20    0.25

I wanted to do a for loop that goes over the unique values of ID and plot the new and old vs date. Also maybe another facet that should the percent change but mainly the first comparison plot. I tried first to make it as date vs new as follow:

for (ii in unique(data$ID)) {
  plt <- ggplot(data %>% filter(ID == ii),
                aes(x = "Month",
                    y = "New")) +
    geom_point(color = "dodgerblue3") +
    theme_minimal()
  print(plt)

}

The result basically gave me a on point plot which I didnt understand. How can I add the Old comparison and also another plot for the percentage.

Body:
-Regarding your loop, I think you could just use a facet function instead

-About the old/new question, I think that your problem comes from your data structure, which is not tidy.

try this :

## get tidy data
tidy_data <- data %>% pivot_longer(c("New", "Old"), names_to = "Age", values_to = "Number")

## get the plots (facet_wrap is used to have multiple plots)
plt <- ggplot(tidy_data, aes(x = Date, y = Number, color = Age)) + geom_point() + facet_wrap(~ ID)
plt


问:
Domain controller and user based on email VBA
I'm trying to resolve domain controller name and user(dc\user) using email address.

I have below code(borrowed) but it only solves user name for default domain. Any suggestions much appreciated.

```<code>Function Get_LDAP_User_Properties(strObjectType, strSearchField, strObjectToGet, strCommaDelimProps)

    If InStr(strObjectToGet, "\") > 0 Then
        arrGroupBits = Split(strObjectToGet, "\")
        strDC = arrGroupBits(0)
        strDNSDomain = strDC & "/" & "DC=" & Replace(Mid(strDC, InStr(strDC, ".") + 1), ".", ",DC=")
        strObjectToGet = arrGroupBits(1)
    Else
        ' Otherwise we just connect to the default domain
        Set objRootDSE = GetObject("LDAP://RootDSE")
        strDNSDomain = objRootDSE.Get("defaultNamingContext")
    End If

    strBase = "<LDAP://" & strDNSDomain & ">"
    ' Setup ADO objects.
    Set adoCommand = CreateObject("ADODB.Command")
    Set ADOConnection = CreateObject("ADODB.Connection")
    ADOConnection.Provider = "ADsDSOObject"
    ADOConnection.Open "Active Directory Provider"
    adoCommand.ActiveConnection = ADOConnection

    ' Filter on user objects.
    'strFilter = "(&(objectCategory=person)(objectClass=user))"
    strFilter = "(&(objectClass=" & strObjectType & ")(" & strSearchField & "=" & strObjectToGet & "))"

    ' Comma delimited list of attribute values to retrieve.
    strAttributes = strCommaDelimProps
    arrProperties = Split(strCommaDelimProps, ",")

    ' Construct the LDAP syntax query.
    strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
    adoCommand.CommandText = strQuery
    ' Define the maximum records to return
    adoCommand.Properties("Page Size") = 100
    adoCommand.Properties("Timeout") = 30
    adoCommand.Properties("Cache Results") = False

    ' Run the query.

End Function
</code>```

Thanks in advance
Michal

答:
Please elaborate about the given email addresses and add examples about the parameters strObjectType, strSearchField, strObjectToGet and strCommaDelimProps when calling the function Get_LDAP_User_Properties().

What is the expected result?

What is the actual result?

My interpretation of your question:
Your input is an email address like myuser@dc.example.com and you want to get following result: dc.example.com\myuser

Is this correct?

In that case this could be the solution:

```<code>Public Function LdapUserByMailAddress(strMailAddress As String) As String
    Dim arrParts() As String

    arrParts = Split(strMailAddress, "@")

    If 1 <> UBound(arrParts) Then
        LdapUserByMailAddress = "Not a valid email address"
        Exit Function
    End If

    LdapUserByMailAddress = arrParts(1) & "\" & arrParts(0)

End Function
</code>```

If you call this function in your worksheet with following code:
=LdapUserByMailAddress("user@dc.example.com")

you get this result: dc.example.com\user

Body:
I'm trying to resolve domain controller name and user(dc\user) using email address.

I have below code(borrowed) but it only solves user name for default domain. Any suggestions much appreciated.

Function Get_LDAP_User_Properties(strObjectType, strSearchField, strObjectToGet, strCommaDelimProps)

    If InStr(strObjectToGet, "\") > 0 Then
        arrGroupBits = Split(strObjectToGet, "\")
        strDC = arrGroupBits(0)
        strDNSDomain = strDC & "/" & "DC=" & Replace(Mid(strDC, InStr(strDC, ".") + 1), ".", ",DC=")
        strObjectToGet = arrGroupBits(1)
    Else
        ' Otherwise we just connect to the default domain
        Set objRootDSE = GetObject("LDAP://RootDSE")
        strDNSDomain = objRootDSE.Get("defaultNamingContext")
    End If

    strBase = "<LDAP://" & strDNSDomain & ">"
    ' Setup ADO objects.
    Set adoCommand = CreateObject("ADODB.Command")
    Set ADOConnection = CreateObject("ADODB.Connection")
    ADOConnection.Provider = "ADsDSOObject"
    ADOConnection.Open "Active Directory Provider"
    adoCommand.ActiveConnection = ADOConnection

    ' Filter on user objects.
    'strFilter = "(&(objectCategory=person)(objectClass=user))"
    strFilter = "(&(objectClass=" & strObjectType & ")(" & strSearchField & "=" & strObjectToGet & "))"

    ' Comma delimited list of attribute values to retrieve.
    strAttributes = strCommaDelimProps
    arrProperties = Split(strCommaDelimProps, ",")

    ' Construct the LDAP syntax query.
    strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
    adoCommand.CommandText = strQuery
    ' Define the maximum records to return
    adoCommand.Properties("Page Size") = 100
    adoCommand.Properties("Timeout") = 30
    adoCommand.Properties("Cache Results") = False

    ' Run the query.

End Function

Thanks in advance
Michal

Body:
Please elaborate about the given email addresses and add examples about the parameters strObjectType, strSearchField, strObjectToGet and strCommaDelimProps when calling the function Get_LDAP_User_Properties().

What is the expected result?

What is the actual result?

My interpretation of your question:
Your input is an email address like myuser@dc.example.com and you want to get following result: dc.example.com\myuser

Is this correct?

In that case this could be the solution:

Public Function LdapUserByMailAddress(strMailAddress As String) As String
    Dim arrParts() As String

    arrParts = Split(strMailAddress, "@")

    If 1 <> UBound(arrParts) Then
        LdapUserByMailAddress = "Not a valid email address"
        Exit Function
    End If

    LdapUserByMailAddress = arrParts(1) & "\" & arrParts(0)

End Function

If you call this function in your worksheet with following code:
=LdapUserByMailAddress("user@dc.example.com")

you get this result: dc.example.com\user


问:
Beautifulsoup not finding the tag
im working on a project on beautifulsoup

```<code>from bs4 import BeautifulSoup as soup
from requests import get

url = "https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1"
clnt = get(url)
page=soup(clnt.text,"html.parser")
container = page.findAll("div",{"class":"lemon--div__373c0__1mboc container__373c0__ZB8u4 hoverable__373c0__3CcYQ margin-t3__373c0__1l90z margin-b3__373c0__q1DuY padding-t3__373c0__1gw9E padding-r3__373c0__57InZ padding-b3__373c0__342DA padding-l3__373c0__1scQ0 border--top__373c0__3gXLy border--right__373c0__1n3Iv border--bottom__373c0__3qNtD border--left__373c0__d1B7K border-color--default__373c0__3-ifU"})

container = container[1]
url2= "https://www.yelp.com"+container.a["href"]
clnt2 = get(url2)
page2 = soup(clnt2.text, 'html.parser')

info = page2.find("div",{"class":"lemon--div__373c0__1mboc island__373c0__3fs6U u-padding-t1 u-padding-r1 u-padding-b1 u-padding-l1 border--top__373c0__19Owr border--right__373c0__22AHO border--bottom__373c0__uPbXS border--left__373c0__1SjJs border-color--default__373c0__2oFDT background-color--white__373c0__GVEnp"})

contact=info.div (Example contact variable)
</code>```

In this "info" variable i am getting the div which has all the contact details, I want to grab the Contact number form this div

And as I print this "info" variable it also shows that contact no. is present in the variable including other details but as I traverse through the div's to get the Contact No. I couldn't find it.
I have also tried to get all the child div's and even including the class of the div itself I wasn't able to get that

First url given is this  :https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1

Second url "url2" is this : https://www.yelp.com/biz/levain-bakery-new-york Which has the Contact details

Any Solutions ???

答:
You can get the contact number with the help of the class name. But I seriously doubt if it works for any given page as the class names seem to be dynamic. But you could give it a try.

```<code>from bs4 import BeautifulSoup as soup
from requests import get

url = "https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1"
clnt = get(url)
page=soup(clnt.text,"html.parser")
container = page.findAll("div",{"class":"lemon--div__373c0__1mboc container__373c0__ZB8u4 hoverable__373c0__3CcYQ margin-t3__373c0__1l90z margin-b3__373c0__q1DuY padding-t3__373c0__1gw9E padding-r3__373c0__57InZ padding-b3__373c0__342DA padding-l3__373c0__1scQ0 border--top__373c0__3gXLy border--right__373c0__1n3Iv border--bottom__373c0__3qNtD border--left__373c0__d1B7K border-color--default__373c0__3-ifU"})

container = container[1]
url2= "https://www.yelp.com"+container.a["href"]
clnt2 = get(url2)
page2 = soup(clnt2.text, 'html.parser')

info = page2.find("div",{"class":"lemon--div__373c0__1mboc island__373c0__3fs6U u-padding-t1 u-padding-r1 u-padding-b1 u-padding-l1 border--top__373c0__19Owr border--right__373c0__22AHO border--bottom__373c0__uPbXS border--left__373c0__1SjJs border-color--default__373c0__2oFDT background-color--white__373c0__GVEnp"})

ContactNumber = info.find("p",{"class":"lemon--p__373c0__3Qnnj text__373c0__2pB8f text-color--normal__373c0__K_MKN text-align--left__373c0__2pnx_"})

print(ContactNumber.text)
</code>```

Output:

```<code>(917) 464-3769
</code>```

Title: Beautifulsoup not finding the tag

Body:
im working on a project on beautifulsoup

from bs4 import BeautifulSoup as soup
from requests import get

url = "https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1"
clnt = get(url)
page=soup(clnt.text,"html.parser")
container = page.findAll("div",{"class":"lemon--div__373c0__1mboc container__373c0__ZB8u4 hoverable__373c0__3CcYQ margin-t3__373c0__1l90z margin-b3__373c0__q1DuY padding-t3__373c0__1gw9E padding-r3__373c0__57InZ padding-b3__373c0__342DA padding-l3__373c0__1scQ0 border--top__373c0__3gXLy border--right__373c0__1n3Iv border--bottom__373c0__3qNtD border--left__373c0__d1B7K border-color--default__373c0__3-ifU"})

container = container[1]
url2= "https://www.yelp.com"+container.a["href"]
clnt2 = get(url2)
page2 = soup(clnt2.text, 'html.parser')

info = page2.find("div",{"class":"lemon--div__373c0__1mboc island__373c0__3fs6U u-padding-t1 u-padding-r1 u-padding-b1 u-padding-l1 border--top__373c0__19Owr border--right__373c0__22AHO border--bottom__373c0__uPbXS border--left__373c0__1SjJs border-color--default__373c0__2oFDT background-color--white__373c0__GVEnp"})

contact=info.div (Example contact variable)

In this "info" variable i am getting the div which has all the contact details, I want to grab the Contact number form this div

And as I print this "info" variable it also shows that contact no. is present in the variable including other details but as I traverse through the div's to get the Contact No. I couldn't find it.
I have also tried to get all the child div's and even including the class of the div itself I wasn't able to get that

First url given is this  :https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1

Second url "url2" is this : https://www.yelp.com/biz/levain-bakery-new-york Which has the Contact details

Any Solutions ???

Body:
You can get the contact number with the help of the class name. But I seriously doubt if it works for any given page as the class names seem to be dynamic. But you could give it a try.

from bs4 import BeautifulSoup as soup
from requests import get

url = "https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1"
clnt = get(url)
page=soup(clnt.text,"html.parser")
container = page.findAll("div",{"class":"lemon--div__373c0__1mboc container__373c0__ZB8u4 hoverable__373c0__3CcYQ margin-t3__373c0__1l90z margin-b3__373c0__q1DuY padding-t3__373c0__1gw9E padding-r3__373c0__57InZ padding-b3__373c0__342DA padding-l3__373c0__1scQ0 border--top__373c0__3gXLy border--right__373c0__1n3Iv border--bottom__373c0__3qNtD border--left__373c0__d1B7K border-color--default__373c0__3-ifU"})

container = container[1]
url2= "https://www.yelp.com"+container.a["href"]
clnt2 = get(url2)
page2 = soup(clnt2.text, 'html.parser')

info = page2.find("div",{"class":"lemon--div__373c0__1mboc island__373c0__3fs6U u-padding-t1 u-padding-r1 u-padding-b1 u-padding-l1 border--top__373c0__19Owr border--right__373c0__22AHO border--bottom__373c0__uPbXS border--left__373c0__1SjJs border-color--default__373c0__2oFDT background-color--white__373c0__GVEnp"})

ContactNumber = info.find("p",{"class":"lemon--p__373c0__3Qnnj text__373c0__2pB8f text-color--normal__373c0__K_MKN text-align--left__373c0__2pnx_"})

print(ContactNumber.text)

Output:

(917) 464-3769


问:
Why can we still use a disposed object?
I have DisposedPatterenDemo class inherit from IDisposable. I have Disposed the object of this class and then after it tries to call the Method() of the same class, I am getting returned value from Method but obj is already disposed of.
var res=obj.Method(); not failing ? Why it is not getting failed?</p>

```<code>     class Program
        {
            static void Main(string[] args)
            {

                DisposedPatterenDemo obj = new DisposedPatterenDemo();
                obj.Initialize();
                obj.Dispose();
                var res=obj.Method(); //Here it return value
    }
    }

 class DisposedPatterenDemo:IDisposable
    {
        private bool Disposed = false;
        StreamReader str = null;
        PaymentStub obj = new PaymentStub();

        public void Initialize()
        {
            str = new StreamReader(@"C:\Test\abc.pdf");
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);

        }
        public string Method()
        {
            var abc = "New";
            return abc;
        }
        public void Dispose(bool disposing)
        {
            if (!Disposed)
            {
                if (disposing)
                {
                    Console.WriteLine("Called From Dispose");
                    if(str!=null)
                    {
                        str.Dispose();
                    }
                }
                else
                {
                    //Clear all the unmanaged resources here
                }
                Disposed = true;
            }
        }
    }
</code>```

答:
Disposing only means that Unmanaged resources used by the object would be disposed off. It does not mean that the object would be cleared off memory. This means that methods of that object, which does not depend on any unamanaged resources could still be called without problem.

To prevent this, As @Matthew suggested, you need to keep an instance variable that tells whether the current instance was disposed or not, and handle it accordingly in the method.

Title: Why can we still use a disposed object?

Body:
I have DisposedPatterenDemo class inherit from IDisposable. I have Disposed the object of this class and then after it tries to call the Method() of the same class, I am getting returned value from Method but obj is already disposed of.
var res=obj.Method(); not failing ? Why it is not getting failed?

     class Program
        {
            static void Main(string[] args)
            {

                DisposedPatterenDemo obj = new DisposedPatterenDemo();
                obj.Initialize();
                obj.Dispose();
                var res=obj.Method(); //Here it return value
    }
    }

 class DisposedPatterenDemo:IDisposable
    {
        private bool Disposed = false;
        StreamReader str = null;
        PaymentStub obj = new PaymentStub();

        public void Initialize()
        {
            str = new StreamReader(@"C:\Test\abc.pdf");
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);

        }
        public string Method()
        {
            var abc = "New";
            return abc;
        }
        public void Dispose(bool disposing)
        {
            if (!Disposed)
            {
                if (disposing)
                {
                    Console.WriteLine("Called From Dispose");
                    if(str!=null)
                    {
                        str.Dispose();
                    }
                }
                else
                {
                    //Clear all the unmanaged resources here
                }
                Disposed = true;
            }
        }
    }


问:
CodeFirst & EDMX in the same application
I have a "legacy" EDMX-based EF model, and a newer CodeFirst model.  I want to be able to incrementally migrate an application from the EDMX to the CF, having both in use at the same time.  Having both models operating in the same AppDomain seems to cause problems. Things work okay with one model until the other model is used, and then everything goes to hell with mapping errors, and remains in that state until the AppDomain is recycled.  For the moment, I have segregated the two models in two different web service applications.  This works fine, but is not ideal.  Is there any way to get them to cooperate in the same AppDomain?</p>

答: Take a look at this discussion on MSDN forums. Hopefully, this information is helpful.</p>


问:
Add Swagger base path field in Nest.js project
I am trying to use nestjs/swagger to create a swagger file from my back-end and I am facing a problem related to the base path. What I want to achieve is to show version as base path instead of showing it in all the methods available, which is ugly and confusing.

My API, right now, has the following structure (this is a set of what is present in app.module.ts):

const routes: Routes = [
  {
    path: '/api',
    module: ApiModule,
    children: [
      {
        path: '/v1',
        module: V1Module,
        children: [
          {
            path: '/orders',
            module: OrdersModule
          },
          {
            path: '/users',
            module: UsersModule
          }
        ]
      }
    ]
  }
];
```

<p>This way, once I generate and check the swagger, I see all my methods following the <code>/api/v1</code> prefix. This could be an example:</p>

<p><strong>orders</strong></p>

```GET   /api/v1/orders
POST  /api/v1/orders
GET   /api/v1/orders/{order_id}
...
```

<p><strong>users</strong></p>

```GET   /api/v1/users
POST  /api/v1/users
GET   /api/v1/users/{user_id}
...
```

What I want is to get rid of /api/v1 appearing in any method. I know that SWAGGER has fields for host and basePath, but do not find any way to populate it in Nest.js. Researching, I have found that there were .setBasePath() and .addServer() methods, but they do not work for me (I am pretty sure they are deprecated).

Thank very much for your help.

答:
If you want nestjs to add api/v1 to every endpoint then use setGlobalPrefix('api/v1') to do that.

https://docs.nestjs.com/faq/global-prefix#global-prefix

Body:
I am trying to use nestjs/swagger to create a swagger file from my back-end and I am facing a problem related to the base path. What I want to achieve is to show version as base path instead of showing it in all the methods available, which is ugly and confusing.

My API, right now, has the following structure (this is a set of what is present in app.module.ts):

const routes: Routes = [
  {
    path: '/api',
    module: ApiModule,
    children: [
      {
        path: '/v1',
        module: V1Module,
        children: [
          {
            path: '/orders',
            module: OrdersModule
          },
          {
            path: '/users',
            module: UsersModule
          }
        ]
      }
    ]
  }
];

This way, once I generate and check the swagger, I see all my methods following the /api/v1 prefix. This could be an example:

orders

GET   /api/v1/orders
POST  /api/v1/orders
GET   /api/v1/orders/{order_id}
...

users

GET   /api/v1/users
POST  /api/v1/users
GET   /api/v1/users/{user_id}
...

What I want is to get rid of /api/v1 appearing in any method. I know that SWAGGER has fields for host and basePath, but do not find any way to populate it in Nest.js. Researching, I have found that there were .setBasePath() and .addServer() methods, but they do not work for me (I am pretty sure they are deprecated).

Thank very much for your help.


问:
displaying laravel show method on vue component
i have a list of movies am trying to display the details of one movie using the show method
here is my component for all movies

```<code><template>
    <div>
        <el-row :gutter="10">
            <el-col :span="6" v-for="movie in movies" v-bind:key="movie">
                <el-card shadow="always" :body-style="{ padding: '0px'} ">
                    <img v-bind:src="movie.cover_photo" class="image" >
                        <div style="padding: 14px;">
                            <div class="bottom clearfix">

                                <router-link :to="{name:'details',params:{id:movie.id}}">{{movie.title}}</router-link>
                                    <router-view></router-view>
                                    <h4>{{ movie.year }}</h4>
                                    <h4>{{ movie.type }}</h4>
                            </div>
                            <div class="block">
                                <el-rate  :max="10" ></el-rate>
                            </div>
                        </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    import axios from 'axios'
    export default {
        data() {
            return {
                movies: [],
                movie:{
                    id:'',
                }
            };
        },
        created(){
          this. fetchMovieList();
          this.showMovie
        },
        methods: {
            fetchMovieList() {
                    axios.get('/movies').then(response => {
                        this.movies = response.data;
                    })
                   .catch(error=>console.log(error))
            },
            showMovie(id){
                axios.get('/movies/'+id).then((res)=>{

                if(res.data.status==true){
                    this.movie= res.data.movie;
                    console.log(res.data.movie)
                }else{
                    alert('No Movie founded with this id')
                }
            })
            .catch((err)=>{alert('error')})
            }
        }
    }
</script>

<style scoped>
.image {
    width: 100%;
    display: block;
  }

</style>
</code>```

my show method:

```<code>public function show($id)
{
        $movie=Movie::find($id);
    if($movie){
        return response()->json(['status'=>true,'movie'=>$movie]);
    }else{
        return response()->json(['status'=>false]);
    }
}
</code>```

my router on app.js:

```<code>const movie=Vue.component('details', require('./components/DetailsComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */
const router=new VueRouter({
    mode:'history',
    routes:[
        {
            path:'/movie/:id',
            name:'movie',
            component:movie
        },

    ],

});

const app = new Vue({
    el: '#app',
   router,
});
</code>```

when i click on the router link it just changes the url to the id of the movie but it doesnt show the component with details when i hit the show endpoint with a specific id  it returns the movie in json format on the browser

答:
I think your variable  of v-for conflict with the same variable of data().
You should try another variable name of v-for.
Something like</p>

```<code><el-col :span="6" v-for="value in movies" v-bind:key="movie">
    <el-card shadow="always" :body-style="{ padding: '0px'} ">
        <img v-bind:src="value.cover_photo" class="image" >
        <div style="padding: 14px;">
            <div class="bottom clearfix">
                <router-link :to="{name:'details',params:{id:value.id}}">{{value.title}}</router-link>
                <router-view></router-view>
                <h4>{{ value.year }}</h4>
                <h4>{{ value.type }}</h4>
            </div>
            <div class="block">
                <el-rate  :max="10" ></el-rate>
            </div>
        </div>
    </el-card>
</el-col>
</code>```

Body:
i have a list of movies am trying to display the details of one movie using the show method
here is my component for all movies

<template>

        <el-row :gutter="10">
            <el-col :span="6" v-for="movie in movies" v-bind:key="movie">
                <el-card shadow="always" :body-style="{ padding: '0px'} ">

                                <router-link :to="{name:'details',params:{id:movie.id}}">{{movie.title}}</router-link>
                                    <router-view></router-view>

{{ movie.year }}

{{ movie.type }}

                                <el-rate  :max="10" ></el-rate>

                </el-card>
            </el-col>
        </el-row>

</template>

my show method:

public function show($id)
{
        $movie=Movie::find($id);
    if($movie){
        return response()->json(['status'=>true,'movie'=>$movie]);
    }else{
        return response()->json(['status'=>false]);
    }
}

my router on app.js:

const movie=Vue.component('details', require('./components/DetailsComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */
const router=new VueRouter({
    mode:'history',
    routes:[
        {
            path:'/movie/:id',
            name:'movie',
            component:movie
        },

    ],

});

const app = new Vue({
    el: '#app',
   router,
});

when i click on the router link it just changes the url to the id of the movie but it doesnt show the component with details when i hit the show endpoint with a specific id  it returns the movie in json format on the browser

Body:
I think your variable  of v-for conflict with the same variable of data().
You should try another variable name of v-for.
Something like

<el-col :span="6" v-for="value in movies" v-bind:key="movie">
    <el-card shadow="always" :body-style="{ padding: '0px'} ">
        <img v-bind:src="value.cover_photo" class="image" >
        <div style="padding: 14px;">
            <div class="bottom clearfix">
                <router-link :to="{name:'details',params:{id:value.id}}">{{value.title}}</router-link>
                <router-view></router-view>
                <h4>{{ value.year }}</h4>
                <h4>{{ value.type }}</h4>
            </div>
            <div class="block">
                <el-rate  :max="10" ></el-rate>
            </div>
        </div>
    </el-card>
</el-col>


问:
Export all files name in all disks powershell
I have to export the names of all the files on all the disks on some machines.
At the moment I have this command line.

```<code>$date = (Get-Date).tostring("dd-MM-yyyy")
gci . *.* -rec | where { ! $_.PSIsContainer} | Select-Object FullName | Export-Csv -Delimiter ";" C:\$env:COMPUTERNAME'_'FilesAudit'_'$date.csv -NoTypeInformation
</code>```

The problem is that if I execute this code, it only extracts the information from the disk I am running and not from the other disks.

I don't know how I can get the information from the other disks, and as an extra problem, each machine has different disks, for example, C: + D: or C: + E: or C: + F: + Q: etc..

Someone has some idea how to help me.

Thank you so much.

答:
Something like this might work for you:

```<code>$drives = Get-PSDrive -PSProvider FileSystem

foreach ($drive in $drives){
    Get-ChildItem $drive.Root -Recurse
}
</code>```

Let me know how you get on

Body:
I have to export the names of all the files on all the disks on some machines.
At the moment I have this command line.

$date = (Get-Date).tostring("dd-MM-yyyy")
gci . *.* -rec | where { ! $_.PSIsContainer} | Select-Object FullName | Export-Csv -Delimiter ";" C:\$env:COMPUTERNAME'_'FilesAudit'_'$date.csv -NoTypeInformation

The problem is that if I execute this code, it only extracts the information from the disk I am running and not from the other disks.

I don't know how I can get the information from the other disks, and as an extra problem, each machine has different disks, for example, C: + D: or C: + E: or C: + F: + Q: etc..

Someone has some idea how to help me.

Thank you so much.

Body:
Something like this might work for you:

$drives = Get-PSDrive -PSProvider FileSystem

foreach ($drive in $drives){
    Get-ChildItem $drive.Root -Recurse
}

Let me know how you get on


问:
How to generate a random number if there is no input from the keyboard
I have been given help on how to generate a random name if input from keyboard is "". How do I do the same to generate a random number if input is ""? input "please enter the first number: " out - if no value is entered "" then generate random number.</p>

```<code>package username;

import java.util.Scanner;
import java.util.Random;

public class UserName {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        String user_Name1;
        System.out.print("Please enter the first username: ");
        user_Name1 = input.nextLine();
        if (user_Name1.equals("")) {
            String[] random = {"Luke", "Leia", "Hans", "Darth" , "Vader" , "Chewbacca"};
            user_Name1 = random[(int) (Math.random() * random.length)];
        }

        System.out.println("" + user_Name1);

        System.out.print("Please enter the first number: ");
        int user_number1 = input.nextInt();
    }
}
</code>```

答: Here input.nextInt(); means Scanner.nextInt is not taking enterkey as an valid input. So you can try by input.nextLine() and casting the value to an Integer.

Body:
I have been given help on how to generate a random name if input from keyboard is "". How do I do the same to generate a random number if input is ""? input "please enter the first number: " out - if no value is entered "" then generate random number.

package username;

import java.util.Scanner;
import java.util.Random;

public class UserName {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        String user_Name1;
        System.out.print("Please enter the first username: ");
        user_Name1 = input.nextLine();
        if (user_Name1.equals("")) {
            String[] random = {"Luke", "Leia", "Hans", "Darth" , "Vader" , "Chewbacca"};
            user_Name1 = random[(int) (Math.random() * random.length)];
        }

        System.out.println("" + user_Name1);

        System.out.print("Please enter the first number: ");
        int user_number1 = input.nextInt();
    }
}


问:
Javascript hide the scroll after clicking and reach the top of the page
I'm using this in my website:
http://www.dynamicdrive.com/dynamicindex3/scrolltop.htm

and it works great for me. But the only thing that I face is that when I click on the picture, it's opacity become 0 but there is still a link in the same place of the picture. I want to hide the link as well!
I have tried display none for the css in the js file but reached nothing!

答:
```<code>this.$control.stop().animate({opacity:1}, this.setting.fadeduration[0])//find
this.$control.stop().fadeIn(this.setting.fadeduration[0])//replace
</code>```

find and replace the lines above, and also look for other animate({opacity}) functions and use them using common sense :)
when its opacity:0 use fadeOut

Other wise leave everything as it is

and use this

```<code>function mychecker(){
   if(!$('#topcontrol').is(':visible')){
       $(this).hide();
   }
   setTimeout(function (){mychecker();},100);
}
</code>```

the above will check every so often if the thing is visible or not and then hide the contents properly :)

Body:
this.$control.stop().animate({opacity:1}, this.setting.fadeduration[0])//find
this.$control.stop().fadeIn(this.setting.fadeduration[0])//replace

find and replace the lines above, and also look for other animate({opacity}) functions and use them using common sense :)
when its opacity:0 use fadeOut

Other wise leave everything as it is

and use this

function mychecker(){
   if(!$('#topcontrol').is(':visible')){
       $(this).hide();
   }
   setTimeout(function (){mychecker();},100);
}

the above will check every so often if the thing is visible or not and then hide the contents properly :)


问:
node version always is back , after closing terminal
I installed node 10.13 and am using mac 10.14.6.

However, after closing terminal, the version of the node is changed to 10.0.

I would appreciate it if you would tell me how to stick the node version.

```<code>$sudo n 10.13
$export PATH=$HOME/.nodebrew/current/bin:$PATH
</code>```

答:
nvm (Node Version Manager) does its job by changing the PATH variable, so you need to make sure you aren't somehow changing your PATH to something else after sourcing the nvm.sh script.

Use the command in the terminal

```<code>nvm alias default v10.13
</code>```

For more detail about the nvm , you can check the link

In case, if you got error as nvm not found then you need to install that

To install nvm, use the install script cURL.

```<code>curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
</code>```

Body:
I installed node 10.13 and am using mac 10.14.6.

However, after closing terminal, the version of the node is changed to 10.0.

I would appreciate it if you would tell me how to stick the node version.

$sudo n 10.13
$export PATH=$HOME/.nodebrew/current/bin:$PATH

Body:
nvm (Node Version Manager) does its job by changing the PATH variable, so you need to make sure you aren't somehow changing your PATH to something else after sourcing the nvm.sh script.

Use the command in the terminal

nvm alias default v10.13

For more detail about the nvm , you can check the link

In case, if you got error as nvm not found then you need to install that

To install nvm, use the install script cURL.

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash


问:
Iterate blocks of struct in memory using pointer
Good day,

    I am trying to create dynamic list of struct using malloc function. For each block of struct, i want to set the struct fields and then i would like to loop through each memory. Below is the code that i wrote :-

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int id;
    int portnum;
    int baudrate;
} port_t;

int main()
{

    port_t *port_pt = (port_t *)malloc(sizeof(port_t) * 2); //allocate two blocks

    port_pt->id = 1;
    port_pt->portnum = 9;
    port_pt->baudrate = 4800;

    printf("id : %i, port :COM%i baud : %i\n\n", port_pt->id, port_pt->portnum, port_pt->baudrate);

    port_pt++; //try make pointer point to next block
    port_pt->id = 2;
    port_pt->portnum = 9;
    port_pt->baudrate = 4800;
    port_pt--; //try to make pointer point to prev block

    int count = 0;
    while (port_pt != NULL)
    {
        printf("DEBUG id : %i, port :COM%i baud : %i\n", port_pt->id, port_pt->portnum, port_pt->baudrate);
        port_pt++;
    }

    return 0;
}

```

    However, when i compile and run this code. I get this lines output instead of two lines only : -

    Can anyone show me where i did wrong? I am really struggling with pointers.

答:
```<code>int count = 0;
    while (port_pt != NULL)
    {
        printf("DEBUG id : %i, port :COM%i baud : %i\n", port_pt->id, port_pt->portnum, port_pt->baudrate);
        port_pt++;
    }
</code>```

change this to

```<code>int count;
   for(count=0;count<2;count++)
   {
        printf("DEBUG id : %i, port :COM%i baud : %i\n", port_pt->id, port_pt->portnum, port_pt->baudrate);
        port_pt++;
   }
</code>```

Because, By incrementing port_pt did not comes to NULL and don't forget to free() the memory allocated by malloc()

Body:
Good day,

    I am trying to create dynamic list of struct using malloc function. For each block of struct, i want to set the struct fields and then i would like to loop through each memory. Below is the code that i wrote :-

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int id;
    int portnum;
    int baudrate;
} port_t;

int main()
{

    port_t *port_pt = (port_t *)malloc(sizeof(port_t) * 2); //allocate two blocks

    port_pt->id = 1;
    port_pt->portnum = 9;
    port_pt->baudrate = 4800;

    printf("id : %i, port :COM%i baud : %i\n\n", port_pt->id, port_pt->portnum, port_pt->baudrate);

    port_pt++; //try make pointer point to next block
    port_pt->id = 2;
    port_pt->portnum = 9;
    port_pt->baudrate = 4800;
    port_pt--; //try to make pointer point to prev block

    int count = 0;
    while (port_pt != NULL)
    {
        printf("DEBUG id : %i, port :COM%i baud : %i\n", port_pt->id, port_pt->portnum, port_pt->baudrate);
        port_pt++;
    }

    return 0;
}

    However, when i compile and run this code. I get this lines output instead of two lines only : -

    Can anyone show me where i did wrong? I am really struggling with pointers.

Body:
int count = 0;
    while (port_pt != NULL)
    {
        printf("DEBUG id : %i, port :COM%i baud : %i\n", port_pt->id, port_pt->portnum, port_pt->baudrate);
        port_pt++;
    }

change this to

int count;
   for(count=0;count<2;count++)
   {
        printf("DEBUG id : %i, port :COM%i baud : %i\n", port_pt->id, port_pt->portnum, port_pt->baudrate);
        port_pt++;
   }

Because, By incrementing port_pt did not comes to NULL and don't forget to free() the memory allocated by malloc()


问:
merging videos together (AVFoundation)
In my app, I'm recording small videos and adding them into an NSMutableArray as AVAsset so that i keep record of what has been captured. when the user press a button to merge them, the final result is only the first video taken (example, if three short videos where taken, the final result after merging is only the first video and the others do not appear). my code on iterating in the NSMutableArray and stitching the videos together is here:

```<code>if (self.capturedVideos.count != 0) {
    //Create AVMutableComposition Object.This object will hold our multiple AVMutableCompositionTrack.
    AVMutableComposition* mixComposition = [[AVMutableComposition alloc] init];

    for (AVAsset *asset in self.capturedVideos) {
        //check if the video is the first one captures so that it  is placed at time 0.
        if ([self.capturedVideos indexOfObject:asset] == 0) {
            AVMutableCompositionTrack *firstTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
            [firstTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset.duration) ofTrack:[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:kCMTimeZero error:nil];
            previousAsset = asset;
        } else{
            AVMutableCompositionTrack *track = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
            [track insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset.duration) ofTrack:[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:previousAsset.duration error:nil];
            previousAsset = asset;
        }
    }

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:
    [NSString stringWithFormat:@"mergeVideo-%d.mov",arc4random() % 1000]];
    NSURL *url = [NSURL fileURLWithPath:myPathDocs];
    // 5 - Create exporter
    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
    exporter.outputURL=url;
    exporter.outputFileType = AVFileTypeQuickTimeMovie;
    exporter.shouldOptimizeForNetworkUse = YES;
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self exportDidFinish:exporter];
        });
    }];
}
</code>```

what's after the for loop is for exporting the video to be saved in camera roll. so where is my mistake? the durations are right (so there is no over lapping). however, i'm doubting in something. There is an instance variable i added after @implementation in braces which is previousAsset which tracks the previous asset added thus knowing where to place the next one. it's of class AVAsset so i didn't initialize it because when i try to it's showing me an error.

previousAsset = [[AVAsset alloc] init];

答:
updated @brenoxp's answer for Swift 5.1</p>

```<code>func merge(arrayVideos:[AVAsset], completion:@escaping (URL?, Error?) -> ()) {

  let mainComposition = AVMutableComposition()
  let compositionVideoTrack = mainComposition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)
  compositionVideoTrack?.preferredTransform = CGAffineTransform(rotationAngle: .pi / 2)

  let soundtrackTrack = mainComposition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)

    var insertTime = CMTime.zero

  for videoAsset in arrayVideos {
    try! compositionVideoTrack?.insertTimeRange(CMTimeRangeMake(start: .zero, duration: videoAsset.duration), of: videoAsset.tracks(withMediaType: .video)[0], at: insertTime)
    try! soundtrackTrack?.insertTimeRange(CMTimeRangeMake(start: .zero, duration: videoAsset.duration), of: videoAsset.tracks(withMediaType: .audio)[0], at: insertTime)

    insertTime = CMTimeAdd(insertTime, videoAsset.duration)
  }

  let outputFileURL = URL(fileURLWithPath: NSTemporaryDirectory() + "merge.mp4")

  let fileManager = FileManager()
  try? fileManager.removeItem(at: outputFileURL)

  let exporter = AVAssetExportSession(asset: mainComposition, presetName: AVAssetExportPresetHighestQuality)

  exporter?.outputURL = outputFileURL
  exporter?.outputFileType = AVFileType.mp4
  exporter?.shouldOptimizeForNetworkUse = true

  exporter?.exportAsynchronously {
    if let url = exporter?.outputURL{
        completion(url, nil)
    }
    if let error = exporter?.error {
        completion(nil, error)
    }
  }
}
</code>```

Title: merging videos together (AVFoundation)

Body:
In my app, I'm recording small videos and adding them into an NSMutableArray as AVAsset so that i keep record of what has been captured. when the user press a button to merge them, the final result is only the first video taken (example, if three short videos where taken, the final result after merging is only the first video and the others do not appear). my code on iterating in the NSMutableArray and stitching the videos together is here:

if (self.capturedVideos.count != 0) {
    //Create AVMutableComposition Object.This object will hold our multiple AVMutableCompositionTrack.
    AVMutableComposition* mixComposition = [[AVMutableComposition alloc] init];

    for (AVAsset *asset in self.capturedVideos) {
        //check if the video is the first one captures so that it  is placed at time 0.
        if ([self.capturedVideos indexOfObject:asset] == 0) {
            AVMutableCompositionTrack *firstTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
            [firstTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset.duration) ofTrack:[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:kCMTimeZero error:nil];
            previousAsset = asset;
        } else{
            AVMutableCompositionTrack *track = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
            [track insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset.duration) ofTrack:[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:previousAsset.duration error:nil];
            previousAsset = asset;
        }
    }

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:
    [NSString stringWithFormat:@"mergeVideo-%d.mov",arc4random() % 1000]];
    NSURL *url = [NSURL fileURLWithPath:myPathDocs];
    // 5 - Create exporter
    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
    exporter.outputURL=url;
    exporter.outputFileType = AVFileTypeQuickTimeMovie;
    exporter.shouldOptimizeForNetworkUse = YES;
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self exportDidFinish:exporter];
        });
    }];
}

what's after the for loop is for exporting the video to be saved in camera roll. so where is my mistake? the durations are right (so there is no over lapping). however, i'm doubting in something. There is an instance variable i added after @implementation in braces which is previousAsset which tracks the previous asset added thus knowing where to place the next one. it's of class AVAsset so i didn't initialize it because when i try to it's showing me an error.

previousAsset = [[AVAsset alloc] init];

Body:
updated @brenoxp's answer for Swift 5.1

func merge(arrayVideos:[AVAsset], completion:@escaping (URL?, Error?) -> ()) {

  let mainComposition = AVMutableComposition()
  let compositionVideoTrack = mainComposition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)
  compositionVideoTrack?.preferredTransform = CGAffineTransform(rotationAngle: .pi / 2)

  let soundtrackTrack = mainComposition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)

    var insertTime = CMTime.zero

  for videoAsset in arrayVideos {
    try! compositionVideoTrack?.insertTimeRange(CMTimeRangeMake(start: .zero, duration: videoAsset.duration), of: videoAsset.tracks(withMediaType: .video)[0], at: insertTime)
    try! soundtrackTrack?.insertTimeRange(CMTimeRangeMake(start: .zero, duration: videoAsset.duration), of: videoAsset.tracks(withMediaType: .audio)[0], at: insertTime)

    insertTime = CMTimeAdd(insertTime, videoAsset.duration)
  }

  let outputFileURL = URL(fileURLWithPath: NSTemporaryDirectory() + "merge.mp4")

  let fileManager = FileManager()
  try? fileManager.removeItem(at: outputFileURL)

  let exporter = AVAssetExportSession(asset: mainComposition, presetName: AVAssetExportPresetHighestQuality)

  exporter?.outputURL = outputFileURL
  exporter?.outputFileType = AVFileType.mp4
  exporter?.shouldOptimizeForNetworkUse = true

  exporter?.exportAsynchronously {
    if let url = exporter?.outputURL{
        completion(url, nil)
    }
    if let error = exporter?.error {
        completion(nil, error)
    }
  }
}