问:
How to run data bricck notebook with mlflow in azure data factory pipeline?
My colleagues and I are facing an issue when trying to run my databricks notebook in Azure Data Factory and the error is coming from MLFlow.

The command that is failing is the following:

```<code># Take the parent notebook path to use as path for the experiment
context = json.loads(dbutils.notebook.entry_point.getDbutils().notebook().getContext().toJson())
nb_base_path = context['extraContext']['notebook_path'][:-len("00_training_and_validation")]

experiment_path = nb_base_path + 'trainings'
mlflow.set_experiment(experiment_path)
experiment = mlflow.get_experiment_by_name(experiment_path)
experiment_id = experiment.experiment_id

run = mlflow.start_run(experiment_id=experiment_id, run_name=f"run_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}")
</code>```

And the error that is throwing is:

An exception was thrown from a UDF: 'mlflow.exceptions.RestException: INVALID_PARAMETER_VALUE: No experiment ID was specified. An experiment ID must be specified in Databricks Jobs and when logging to the MLflow server from outside the Databricks workspace. If using the Python fluent API, you can set an active experiment under which to create runs by calling mlflow.set_experiment("/path/to/experiment/in/workspace") at the start of your program.', from , line 32.

The pipeline just runs the notebook from ADF, it does not have any other step and the cluster we are using is type 7.3 ML.

Could you please help us?

Thank you in advance!

答:
I think you need to set artifact URI and specify experiment ID (if in the artifact directory has much experiment ID

Reference: https://www.mlflow.org/docs/latest/tracking.html#how-runs-and-artifacts-are-recorded

Body:
My colleagues and I are facing an issue when trying to run my databricks notebook in Azure Data Factory and the error is coming from MLFlow.

The command that is failing is the following:

# Take the parent notebook path to use as path for the experiment
context = json.loads(dbutils.notebook.entry_point.getDbutils().notebook().getContext().toJson())
nb_base_path = context['extraContext']['notebook_path'][:-len("00_training_and_validation")]

experiment_path = nb_base_path + 'trainings'
mlflow.set_experiment(experiment_path)
experiment = mlflow.get_experiment_by_name(experiment_path)
experiment_id = experiment.experiment_id

run = mlflow.start_run(experiment_id=experiment_id, run_name=f"run_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}")

And the error that is throwing is:

An exception was thrown from a UDF: 'mlflow.exceptions.RestException: INVALID_PARAMETER_VALUE: No experiment ID was specified. An experiment ID must be specified in Databricks Jobs and when logging to the MLflow server from outside the Databricks workspace. If using the Python fluent API, you can set an active experiment under which to create runs by calling mlflow.set_experiment("/path/to/experiment/in/workspace") at the start of your program.', from , line 32.

The pipeline just runs the notebook from ADF, it does not have any other step and the cluster we are using is type 7.3 ML.

Could you please help us?

Thank you in advance!


来源: stackexchange

问:
Is there a syntax to inherit the value of content in CSS and concatenate it?
I would like the content property to be concatenated instead of overriding.

```
<pre class="lang-css prettyprint-override"><code>div::after {
  content: "hello";
}
.bear::after {
  content: " bear"; /* Here, I would like bear to be concatenated to "hello" instead of overriding it */
}
</code>```

答:
You can't 'inherit' the content as such but you can pick up a CSS variable value.

This snippet sets the variable --content in the div setting and uses that in the .bear pseudo element as well as the div pseudo element.

div::after {
  --content: "hello";
  content: var(--content);
}

.bear::after {
  content: var(--content) " bear";
  /* Here, I would like bear to be concatenated to "hello" instead of overriding it */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bear"></div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like the content property to be concatenated instead of overriding.

div::after {
  content: "hello";
}
.bear::after {
  content: " bear"; /* Here, I would like bear to be concatenated to "hello" instead of overriding it */
}

Body:
You can't 'inherit' the content as such but you can pick up a CSS variable value.

This snippet sets the variable --content in the div setting and uses that in the .bear pseudo element as well as the div pseudo element.

div::after {
  --content: "hello";
  content: var(--content);
}

.bear::after {
  content: var(--content) " bear";
  /* Here, I would like bear to be concatenated to "hello" instead of overriding it */
}

<div class="bear"></div>


问:
Is it possible to run aframe inside electron?
i've just started learning both electronjs (https://electronjs.org/) and aframe VR 3D (https://aframe.io/). But i'm not sure if aframe works inside electron? I cant find anything within google search. I get cross-origin policy error in the console then multiple three.js errors and a-scene.js errors. Ive have added the js file inside the html page:

```<code><head>
<script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script
</head>
</code>```

Any help in the right direction would be appreciated.

Thanks.

--- more info

im using https://github.com/electron/electron-quick-start and then main.js consists of mainWindow.loadFile('index.html')

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<script src="aframe.min.js"></script>
</head>
<body>

<a-scene>

<a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9"></a-box>

<a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>

<a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D"></a-cylinder>

<a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4"></a-plane>

<a-sky color="#ECECEC"></a-sky>

</a-scene>

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

aframe.min.js is now local but i still get the same errors

答:
I use aframe with electron, it works fine for me.

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/aframe/1.2.0/aframe.min.js" integrity="sha512-/gO16YMp20RIqCZXZyvMlzALQqEoiDU0akshw25wFiXCRGl+0p/HPWkOd8HWFn6bnatGhxakGLfYhWaPPVQIyA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</code>```

I got this script tag from https://cdnjs.com/libraries/aframe

Body:
i've just started learning both electronjs (https://electronjs.org/) and aframe VR 3D (https://aframe.io/). But i'm not sure if aframe works inside electron? I cant find anything within google search. I get cross-origin policy error in the console then multiple three.js errors and a-scene.js errors. Ive have added the js file inside the html page:

Any help in the right direction would be appreciated.

Thanks.

--- more info

im using https://github.com/electron/electron-quick-start and then main.js consists of mainWindow.loadFile('index.html')

<!DOCTYPE html>

<meta charset="UTF-8">
<title>Hello World!</title>

aframe.min.js is now local but i still get the same errors

Body:
I use aframe with electron, it works fine for me.

<script src="https://cdnjs.cloudflare.com/ajax/libs/aframe/1.2.0/aframe.min.js" integrity="sha512-/gO16YMp20RIqCZXZyvMlzALQqEoiDU0akshw25wFiXCRGl+0p/HPWkOd8HWFn6bnatGhxakGLfYhWaPPVQIyA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

I got this script tag from https://cdnjs.com/libraries/aframe


问:
MassTransit Automatonymous - State not changing when a message is Sent
I am trying to figure why "Sending" a message does not invoke state machine, but if I "Publish" a message, it works and I can see the state changing.

Following is my code, it is similar to the documentation, except that I am trying to "Send" a message.

Components

State Machine:

```<code>public class OrderState: SagaStateMachineInstance
{
    public Guid CorrelationId { get; set; }
    public int CurrentState { get; set; }
    public DateTime? OrderDate { get; set; }
}

public class OrderStateMachine: MassTransitStateMachine<OrderState>
{
    public State Submitted { get; private set; }
    public State Accepted { get; private set; }
    public State Completed { get; private set; }

    public Event<SubmitOrder> SubmitOrder { get; private set; }
    public Event<OrderAccepted> OrderAccepted { get; private set; }
    public Event<OrderCompleted> OrderCompleted { get; private set; }

    public OrderStateMachine()
    {
        InstanceState(x => x.CurrentState, Submitted, Accepted, Completed);
        Event(() => SubmitOrder, x => x.CorrelateById(context => context.Message.OrderId));
        Event(() => OrderAccepted, x => x.CorrelateById(context => context.Message.OrderId));
        Event(() => OrderCompleted, x => x.CorrelateById(context => context.Message.OrderId));

        Initially(
            When(SubmitOrder)
                .Then(context => context.Instance.OrderDate = context.Data.OrderDate)
                .TransitionTo(Submitted));

        During(Submitted,
            When(OrderAccepted)
                .TransitionTo(Accepted));

        During(Accepted,
            Ignore(SubmitOrder));

        DuringAny(
            When(OrderCompleted)
                .TransitionTo(Completed));

        SetCompleted(async instance =>
        {
            var currentState = await this.GetState(instance);
            return Completed.Equals(currentState);
        });
    }
}
</code>```

Contracts:

```<code>public record SubmitOrder(Guid OrderId, DateTime? OrderDate);
public record OrderAccepted(Guid OrderId);
public record OrderCompleted(Guid OrderId);
</code>```

Consumers:

```<code>public class SubmitOrderConsumer: IConsumer<SubmitOrder>
{
    public async Task Consume(ConsumeContext<SubmitOrder> context)
    {
        await Task.Delay(2000);
    }
}

public class SubmitOrderConsumerDefinition : ConsumerDefinition<SubmitOrderConsumer>
{
    public SubmitOrderConsumerDefinition()
    {
        EndpointName = "submit-order";
    }

    protected override void ConfigureConsumer(IReceiveEndpointConfigurator endpointConfigurator, IConsumerConfigurator<SubmitOrderConsumer> consumerConfigurator)
    {
        endpointConfigurator.ConfigureConsumeTopology = false;
    }
}
</code>```

Web API

Program.cs (snippet)

```<code>// Add services to the container.
builder.Services.AddMassTransit(cfg =>
{
    cfg.SetKebabCaseEndpointNameFormatter();
    cfg.UsingRabbitMq((context, configurator) =>
    {
        configurator.Host("localhost", "/", hostConfigurator =>
        {
            hostConfigurator.Username("guest");
            hostConfigurator.Password("guest");
        });
    });
});
builder.Services.AddMassTransitHostedService();
builder.Services.AddControllers();

</code>```

OrderController

```<code>[Route("order")]
public class OrderController : ControllerBase
{
    private readonly ISendEndpointProvider _sendEndpointProvider;
    public OrderController(ISendEndpointProvider sendEndpointProvider)
    {
        _sendEndpointProvider = sendEndpointProvider;
    }

    [HttpPost]
    public async Task<IActionResult> SendOrder()
    {
        var endpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri("exchange:submit-order"));
        await endpoint.Send(new SubmitOrder(Guid.NewGuid(), DateTime.Now));
        return Ok();
    }
}
</code>```

Worker Service

Program.cs

```<code>using IHost = Microsoft.Extensions.Hosting.IHost;

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddMassTransit(cfg =>
        {
            cfg.AddConsumer<SubmitOrderConsumer>(typeof(SubmitOrderConsumerDefinition));
            cfg.AddSagaStateMachine<OrderStateMachine, OrderState>().InMemoryRepository();
            cfg.UsingRabbitMq((context, rabbitMqConfigurator) =>
            {
                rabbitMqConfigurator.Host("localhost", "/", hostConfigurator =>
                {
                    hostConfigurator.Username("guest");
                    hostConfigurator.Password("guest");
                });
                rabbitMqConfigurator.ReceiveEndpoint("saga-order", endpointConfigurator =>
                {
                    endpointConfigurator.ConfigureSaga<OrderState>(context);
                });
                rabbitMqConfigurator.ConfigureEndpoints(context);
            });
        });
        services.AddMassTransitHostedService();
        services.AddHostedService<Worker>();
    })
    .Build();

await host.RunAsync();
</code>```

Then I do a POST via Postman to: http://localhost:5000/order

It does call the SubmitOrderConsumer, but for some reason, the State machine does not get invoked (it won't hit breakpoint inside the Then handler that sets the Order Date inside Initially state.). I think I am missing something that connects the two together.
Any feedback is greatly appreciated. Thank you.

答: In your example, you'd want to use Publish, especially in this scenario where you have two consumers (the consumer, and the state machine) on separate endpoints (queue) that would be consuming the message. Sending directly to the exchange would only get the message to one of the endpoints.

Body:
I am trying to figure why "Sending" a message does not invoke state machine, but if I "Publish" a message, it works and I can see the state changing.

Following is my code, it is similar to the documentation, except that I am trying to "Send" a message.

Components

State Machine:

public class OrderState: SagaStateMachineInstance
{
    public Guid CorrelationId { get; set; }
    public int CurrentState { get; set; }
    public DateTime? OrderDate { get; set; }
}

public class OrderStateMachine: MassTransitStateMachine<OrderState>
{
    public State Submitted { get; private set; }
    public State Accepted { get; private set; }
    public State Completed { get; private set; }

    public Event<SubmitOrder> SubmitOrder { get; private set; }
    public Event<OrderAccepted> OrderAccepted { get; private set; }
    public Event<OrderCompleted> OrderCompleted { get; private set; }

    public OrderStateMachine()
    {
        InstanceState(x => x.CurrentState, Submitted, Accepted, Completed);
        Event(() => SubmitOrder, x => x.CorrelateById(context => context.Message.OrderId));
        Event(() => OrderAccepted, x => x.CorrelateById(context => context.Message.OrderId));
        Event(() => OrderCompleted, x => x.CorrelateById(context => context.Message.OrderId));

        Initially(
            When(SubmitOrder)
                .Then(context => context.Instance.OrderDate = context.Data.OrderDate)
                .TransitionTo(Submitted));

        During(Submitted,
            When(OrderAccepted)
                .TransitionTo(Accepted));

        During(Accepted,
            Ignore(SubmitOrder));

        DuringAny(
            When(OrderCompleted)
                .TransitionTo(Completed));

        SetCompleted(async instance =>
        {
            var currentState = await this.GetState(instance);
            return Completed.Equals(currentState);
        });
    }
}

Contracts:

public record SubmitOrder(Guid OrderId, DateTime? OrderDate);
public record OrderAccepted(Guid OrderId);
public record OrderCompleted(Guid OrderId);

Consumers:

public class SubmitOrderConsumer: IConsumer<SubmitOrder>
{
    public async Task Consume(ConsumeContext<SubmitOrder> context)
    {
        await Task.Delay(2000);
    }
}

public class SubmitOrderConsumerDefinition : ConsumerDefinition<SubmitOrderConsumer>
{
    public SubmitOrderConsumerDefinition()
    {
        EndpointName = "submit-order";
    }

    protected override void ConfigureConsumer(IReceiveEndpointConfigurator endpointConfigurator, IConsumerConfigurator<SubmitOrderConsumer> consumerConfigurator)
    {
        endpointConfigurator.ConfigureConsumeTopology = false;
    }
}

Web API

Program.cs (snippet)

// Add services to the container.
builder.Services.AddMassTransit(cfg =>
{
    cfg.SetKebabCaseEndpointNameFormatter();
    cfg.UsingRabbitMq((context, configurator) =>
    {
        configurator.Host("localhost", "/", hostConfigurator =>
        {
            hostConfigurator.Username("guest");
            hostConfigurator.Password("guest");
        });
    });
});
builder.Services.AddMassTransitHostedService();
builder.Services.AddControllers();

OrderController

[Route("order")]
public class OrderController : ControllerBase
{
    private readonly ISendEndpointProvider _sendEndpointProvider;
    public OrderController(ISendEndpointProvider sendEndpointProvider)
    {
        _sendEndpointProvider = sendEndpointProvider;
    }

    [HttpPost]
    public async Task<IActionResult> SendOrder()
    {
        var endpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri("exchange:submit-order"));
        await endpoint.Send(new SubmitOrder(Guid.NewGuid(), DateTime.Now));
        return Ok();
    }
}

Worker Service

Program.cs

using IHost = Microsoft.Extensions.Hosting.IHost;

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddMassTransit(cfg =>
        {
            cfg.AddConsumer<SubmitOrderConsumer>(typeof(SubmitOrderConsumerDefinition));
            cfg.AddSagaStateMachine<OrderStateMachine, OrderState>().InMemoryRepository();
            cfg.UsingRabbitMq((context, rabbitMqConfigurator) =>
            {
                rabbitMqConfigurator.Host("localhost", "/", hostConfigurator =>
                {
                    hostConfigurator.Username("guest");
                    hostConfigurator.Password("guest");
                });
                rabbitMqConfigurator.ReceiveEndpoint("saga-order", endpointConfigurator =>
                {
                    endpointConfigurator.ConfigureSaga<OrderState>(context);
                });
                rabbitMqConfigurator.ConfigureEndpoints(context);
            });
        });
        services.AddMassTransitHostedService();
        services.AddHostedService<Worker>();
    })
    .Build();

await host.RunAsync();

Then I do a POST via Postman to: http://localhost:5000/order

It does call the SubmitOrderConsumer, but for some reason, the State machine does not get invoked (it won't hit breakpoint inside the Then handler that sets the Order Date inside Initially state.). I think I am missing something that connects the two together.
Any feedback is greatly appreciated. Thank you.


问:
Ascii to Hex conversion in Xquery
I have a requirement to convert the ASCII to Hex String using XQuery, Please help to provide any respective reference or code snippets to achieve this functionality, by example I have then string: 1239565447854 and I need convert to hex: 31323339353635343437383534

答:
You can use string-to-codepoints() to get the numeric codepoint for each character. For each codepoint, determine how many times it is divisible by 16 using idiv, and the remainder using the mod operator. For both of those numbers, get their hex value by looking up by position in a sequence of the 16 characters and then join the results:

```<code>declare function local:codepoint-to-hex($codepoint as xs:integer) as xs:string {
  let $hex-index := ("0123456789ABCDEF" => string-to-codepoints()) ! codepoints-to-string(.)
  let $base16 := $codepoint idiv 16
  let $remainder := $codepoint mod 16
  return
    string-join((
      $hex-index[$base16 + 1],
      if ($remainder = 0)
      then ()
      else $hex-index[$remainder + 1]
      ), "")
};

declare function local:string-to-hex($str as xs:string) as xs:string {
  string-join( string-to-codepoints($str) ! local:codepoint-to-hex(.), "")
};

local:string-to-hex('1239565447854')
</code>```

Title: Ascii to Hex conversion in Xquery

Body:
You can use string-to-codepoints() to get the numeric codepoint for each character. For each codepoint, determine how many times it is divisible by 16 using idiv, and the remainder using the mod operator. For both of those numbers, get their hex value by looking up by position in a sequence of the 16 characters and then join the results:

declare function local:codepoint-to-hex($codepoint as xs:integer) as xs:string {
  let $hex-index := ("0123456789ABCDEF" => string-to-codepoints()) ! codepoints-to-string(.)
  let $base16 := $codepoint idiv 16
  let $remainder := $codepoint mod 16
  return
    string-join((
      $hex-index[$base16 + 1],
      if ($remainder = 0)
      then ()
      else $hex-index[$remainder + 1]
      ), "")
};

declare function local:string-to-hex($str as xs:string) as xs:string {
  string-join( string-to-codepoints($str) ! local:codepoint-to-hex(.), "")
};

local:string-to-hex('1239565447854')


问:
How to set the rounded corners of TabItem to achieve the same effect as Google?
I have the code for the TabControl below. I want to achieve tab style similar to google chrome browser.
I want to make the bottom corners slightly rounder towards the pinkish background and not inwards.

How to set the rounded corners of TabItem to achieve the same effect as Google?

The resulting graph I have now：

Xmal:

```<code><Window.Resources>
        <SolidColorBrush x:Key="PrimaryBG" Color="#ad00ad"/>
        <SolidColorBrush x:Key="Blueish" Color="#5252ff"/>
        <SolidColorBrush x:Key="Greenish" Color="#005757"/>
        <SolidColorBrush x:Key="Blackish" Color="#2e2e00"/>
        <Style x:Key="{x:Type TabControl}" TargetType="{x:Type TabControl}">
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="BorderBrush" Value="Transparent"/>
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="TabControl">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"/>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>
                            <Border BorderThickness="0,0,1,1" BorderBrush="#D0CEBF" Grid.Row="1">
                                <Border BorderThickness="{TemplateBinding BorderThickness}"
                                          BorderBrush="{TemplateBinding BorderBrush}">
                                    <Border Background="{TemplateBinding Background}">
                                        <ContentPresenter ContentSource="SelectedContent"/>
                                    </Border>
                                </Border>
                            </Border>
                            <TabPanel Grid.Row="0" IsItemsHost="true" HorizontalAlignment="Center"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style TargetType="TabItem">
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="BorderBrush" Value="Transparent"/>
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TabItem}">
                        <!--In order to click on the blank part of the TabItem can be successfully selected-->
                        <Border Background="Transparent" >
                            <Grid>
                                <Grid x:Name="g">
                                    <Border CornerRadius="5,5,7,7" Background="{TemplateBinding Background}" Margin="0,0,0,-1"
                                               BorderBrush="{TemplateBinding BorderBrush}"
                                               BorderThickness="{TemplateBinding BorderThickness}"/>

                                </Grid>
                                <Border  BorderThickness="{TemplateBinding BorderThickness}"
                                          Padding="{TemplateBinding Padding}">
                                    <ContentPresenter ContentSource="Header"
                                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                                </Border>
                            </Grid>
                        </Border>
                        <!--Add ControlTemplate.Triggers to change the background color of the selected TabItem.-->

                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid Background="{DynamicResource PrimaryBG}" Name="grid" >
        <TabControl HorizontalAlignment="Center" HorizontalContentAlignment="Stretch"  Margin="0,0,0,0"
                      Name="tabControl1" VerticalAlignment="Top" >
            <TabItem Header="Dashboard" Name="tabItem1" Background="{DynamicResource Blueish}" Foreground="White"
                       HorizontalContentAlignment="Center" VerticalAlignment="Stretch" Width="180" HorizontalAlignment="Center"
                       FontFamily="Leelawadee UI" FontSize="20" Margin="0,0,0,0" Padding="0,0,0,0">
                <Border Background="#5252ff" Margin="0,0,0,0" Padding="0,0,0,0" HorizontalAlignment="Center"  VerticalAlignment="Stretch" Width="{Binding ElementName=grid,Path=ActualWidth}" Height="{Binding ElementName=grid, Path=ActualHeight}">
                    <StackPanel>
                        <TextBox Width="200" Height="25"/>
                        <TextBox Width="200" Height="25"/>
                    </StackPanel>
                </Border>
            </TabItem>
            <TabItem Header="Invoicing" Name="tabItem2"  Background="{DynamicResource Greenish}" Foreground="White"
                       HorizontalContentAlignment="Center" VerticalAlignment="Stretch" Width="180" HorizontalAlignment="Center"
                       FontFamily="Leelawadee UI" FontSize="20" Margin="0,0,0,0" Padding="0,0,0,0">
                <Border Background="#005757" Margin="0,0,0,0" Padding="0,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Stretch" Width="{Binding ElementName=grid,Path=ActualWidth}"  Height="{Binding ElementName=grid, Path=ActualHeight}" >
                    <Button Width="80" Height="25"/>
                </Border>
            </TabItem>
            <TabItem Header="Transactions" Name="tabItem3" Background="{DynamicResource Blackish}" Foreground="White"
                       HorizontalContentAlignment="Center" VerticalAlignment="Stretch" Width="180" HorizontalAlignment="Center"
                       FontFamily="Leelawadee UI" FontSize="20" Margin="0,0,0,0" Padding="0,0,0,0" >
                <Border Background="#2e2e00" Margin="0,0,0,0" Padding="0,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Stretch" Width="{Binding ElementName=grid,Path=ActualWidth}" Height="{Binding ElementName=grid, Path=ActualHeight}" >
                    <ComboBox Width="300" Height="25"/>
                </Border>
            </TabItem>
        </TabControl>

    </Grid>
</code>```

Edit:
Is it possible to give a path of the red line in the figure?

答:
You can create any shape by Path and place it both sides of tab. For example, such Path would be as follows.

<Path Width="20" Height="40" Stretch="Uniform" Fill="Blue"
      StrokeThickness="2" Stroke="Red"
      Data="M 20,40 L 0,40 0,40 C 4,40 10,36 10,30 L 10,10 C 10,0 16,0 20,0"/>
```

You can flip it by <ScaleTransform ScaleX="-1"/>.

Edit:

Edited Path. You can draw outline by Stroke and leave a segment open by removing Z.

Body:
I have the code for the TabControl below. I want to achieve tab style similar to google chrome browser.
I want to make the bottom corners slightly rounder towards the pinkish background and not inwards.

How to set the rounded corners of TabItem to achieve the same effect as Google?

The resulting graph I have now：

Xmal:

<Window.Resources>
        <SolidColorBrush x:Key="PrimaryBG" Color="#ad00ad"/>
        <SolidColorBrush x:Key="Blueish" Color="#5252ff"/>
        <SolidColorBrush x:Key="Greenish" Color="#005757"/>
        <SolidColorBrush x:Key="Blackish" Color="#2e2e00"/>

    </Window.Resources>
    <Grid Background="{DynamicResource PrimaryBG}" Name="grid" >
        <TabControl HorizontalAlignment="Center" HorizontalContentAlignment="Stretch"  Margin="0,0,0,0"
                      Name="tabControl1" VerticalAlignment="Top" >
            <TabItem Header="Dashboard" Name="tabItem1" Background="{DynamicResource Blueish}" Foreground="White"
                       HorizontalContentAlignment="Center" VerticalAlignment="Stretch" Width="180" HorizontalAlignment="Center"
                       FontFamily="Leelawadee UI" FontSize="20" Margin="0,0,0,0" Padding="0,0,0,0">
                <Border Background="#5252ff" Margin="0,0,0,0" Padding="0,0,0,0" HorizontalAlignment="Center"  VerticalAlignment="Stretch" Width="{Binding ElementName=grid,Path=ActualWidth}" Height="{Binding ElementName=grid, Path=ActualHeight}">
                    <StackPanel>
                        <TextBox Width="200" Height="25"/>
                        <TextBox Width="200" Height="25"/>
                    </StackPanel>
                </Border>
            </TabItem>
            <TabItem Header="Invoicing" Name="tabItem2"  Background="{DynamicResource Greenish}" Foreground="White"
                       HorizontalContentAlignment="Center" VerticalAlignment="Stretch" Width="180" HorizontalAlignment="Center"
                       FontFamily="Leelawadee UI" FontSize="20" Margin="0,0,0,0" Padding="0,0,0,0">
                <Border Background="#005757" Margin="0,0,0,0" Padding="0,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Stretch" Width="{Binding ElementName=grid,Path=ActualWidth}"  Height="{Binding ElementName=grid, Path=ActualHeight}" >
                    <Button Width="80" Height="25"/>
                </Border>
            </TabItem>
            <TabItem Header="Transactions" Name="tabItem3" Background="{DynamicResource Blackish}" Foreground="White"
                       HorizontalContentAlignment="Center" VerticalAlignment="Stretch" Width="180" HorizontalAlignment="Center"
                       FontFamily="Leelawadee UI" FontSize="20" Margin="0,0,0,0" Padding="0,0,0,0" >
                <Border Background="#2e2e00" Margin="0,0,0,0" Padding="0,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Stretch" Width="{Binding ElementName=grid,Path=ActualWidth}" Height="{Binding ElementName=grid, Path=ActualHeight}" >
                    <ComboBox Width="300" Height="25"/>
                </Border>
            </TabItem>
        </TabControl>

    </Grid>

Edit:
Is it possible to give a path of the red line in the figure?

Body:
You can create any shape by Path and place it both sides of tab. For example, such Path would be as follows.

<Path Width="20" Height="40" Stretch="Uniform" Fill="Blue"
      StrokeThickness="2" Stroke="Red"
      Data="M 20,40 L 0,40 0,40 C 4,40 10,36 10,30 L 10,10 C 10,0 16,0 20,0"/>

You can flip it by <ScaleTransform ScaleX="-1"/>.

Edit:

Edited Path. You can draw outline by Stroke and leave a segment open by removing Z.


问:
How to select folders from a directory based on a python list of the folder names?
I have a list of folder names - "df_train_pos_list"

I want to iterate through a directory and select folders with those names, and add them to another list - "train_images"

So far what I have tried doesn't work:

```<code>train_images = []
train_labels = []

for i in df_train_pos_list:
    for currentpath, folders, files in os.walk('D:\Arm C Deep Learning\SH_OCTAPUS\Train'):
        for file in files:
            if i in currentpath:
                train_images.append('D:\Arm C Deep Learning\SH_OCTAPUS\Train' + file)
                train_labels.append(1)
            else:
                train_images.append('D:\Arm C Deep Learning\SH_OCTAPUS\Train' + file)
                train_labels.append(0)
train_labels = np.asarray(train_labels, dtype=np.int64)
print(train_labels)
np.unique(train_labels, return_counts='TRUE')
</code>```

答:
Kind of unsure if you want to add folder path to the list or the individual files in the folder to your list but the below snippet will add the folder paths to your trains_list. would need more details on what you want out of the label to add that.

```<code>import os
df_train_pos_list =[]
train_images = []
#train_labels = []
root = 'D:\Arm C Deep Learning\SH_OCTAPUS\Train'
for f in os.listdir(root):
    if f in df_train_pos_list:
        train_label = 1
    else:
        train_label = 0
    train_images.append((os.path.join(root,f),train_label)) #this will add your folder file path to train images

for folder, label in train_images:
    if label==1:
        #do something here
</code>```

Body:
I have a list of folder names - "df_train_pos_list"

I want to iterate through a directory and select folders with those names, and add them to another list - "train_images"

So far what I have tried doesn't work:

train_images = []
train_labels = []

for i in df_train_pos_list:
    for currentpath, folders, files in os.walk('D:\Arm C Deep Learning\SH_OCTAPUS\Train'):
        for file in files:
            if i in currentpath:
                train_images.append('D:\Arm C Deep Learning\SH_OCTAPUS\Train' + file)
                train_labels.append(1)
            else:
                train_images.append('D:\Arm C Deep Learning\SH_OCTAPUS\Train' + file)
                train_labels.append(0)
train_labels = np.asarray(train_labels, dtype=np.int64)
print(train_labels)
np.unique(train_labels, return_counts='TRUE')

Body:
Kind of unsure if you want to add folder path to the list or the individual files in the folder to your list but the below snippet will add the folder paths to your trains_list. would need more details on what you want out of the label to add that.

import os
df_train_pos_list =[]
train_images = []
#train_labels = []
root = 'D:\Arm C Deep Learning\SH_OCTAPUS\Train'
for f in os.listdir(root):
    if f in df_train_pos_list:
        train_label = 1
    else:
        train_label = 0
    train_images.append((os.path.join(root,f),train_label)) #this will add your folder file path to train images

for folder, label in train_images:
    if label==1:
        #do something here


问:
half-daily rollover in log4j2
Half-daily rollover for log4j2 not working for the given propertie file.

```<code>status = error
name = Proper

property.filepath = C\:/xi/doc/home/new/log
property.filename1 = ${filepath}/Common.log

filter.threshold.type = ThresholdFilter
filter.threshold.level = debug

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %5p [%C].%M %m %n

appender.rolling1.type = RollingFile
appender.rolling1.name = RollingFile1
appender.rolling1.fileName = ${filename1}
appender.rolling1.filePattern = ${filepath}/Common.%d{yyyy-MM-dd-a}.%i.log.gz
appender.rolling1.layout.type = PatternLayout
appender.rolling1.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %5p [%C].%M %m %n
appender.rolling1.policies.type = Policies
appender.rolling1.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling1.policies.time.interval = 1
appender.rolling1.policies.time.modulate = true
appender.rolling1.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling1.policies.size.size = 100MB
appender.rolling1.strategy.type = DefaultRolloverStrategy
appender.rolling1.strategy.max = 20
appender.rolling1.strategy.delete.type = Delete
appender.rolling1.strategy.delete.basePath = ${basePath}
appender.rolling1.strategy.delete.maxDepth = 10
appender.rolling1.strategy.delete.ifLastModified.type = IfLastModified

# Delete all files older than 1 day
appender.rolling1.strategy.delete.ifLastModified.age = 1d

# loggers
logger.name = common
logger.level = debug
logger.additivity = false
logger.appenderRefs = rolling1
logger.appenderRefs.level = debug
logger.appenderRef.rolling1.ref = RollingFile1
</code>```

The rollover works hourly and minutely if interval given and filepattern is given as ${filepath}/Common.%d{yyyy-MM-dd-HH} and ${filepath}/Common.%d{yyyy-MM-HH-minutely}

How to rollover half-daily? Is it supported in log4j2?

答:
Log4j 1.x used to check at every message if the file pattern resolved to a different file name and rotated if it did.

However Log4j 2.x uses another approach. The date pattern is used twofold:

the date pattern %d{yyyy-MM-dd-a} is used to determine the rollover frequency (cf. source code), which in this case is days. This determines the time of the next rollover.

the date pattern is also used to determine the name of the file, which would contains AM in the morning and PM in the afternoon.

If you want two daily rotations you really need to add an hour specifier to the pattern: e.g. %d{yyyy-MM-dd-Ka} and set interval to 12.

Title: half-daily rollover in log4j2

Body:
Half-daily rollover for log4j2 not working for the given propertie file.

status = error
name = Proper

property.filepath = C\:/xi/doc/home/new/log
property.filename1 = ${filepath}/Common.log

filter.threshold.type = ThresholdFilter
filter.threshold.level = debug

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %5p [%C].%M %m %n

appender.rolling1.type = RollingFile
appender.rolling1.name = RollingFile1
appender.rolling1.fileName = ${filename1}
appender.rolling1.filePattern = ${filepath}/Common.%d{yyyy-MM-dd-a}.%i.log.gz
appender.rolling1.layout.type = PatternLayout
appender.rolling1.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %5p [%C].%M %m %n
appender.rolling1.policies.type = Policies
appender.rolling1.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling1.policies.time.interval = 1
appender.rolling1.policies.time.modulate = true
appender.rolling1.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling1.policies.size.size = 100MB
appender.rolling1.strategy.type = DefaultRolloverStrategy
appender.rolling1.strategy.max = 20
appender.rolling1.strategy.delete.type = Delete
appender.rolling1.strategy.delete.basePath = ${basePath}
appender.rolling1.strategy.delete.maxDepth = 10
appender.rolling1.strategy.delete.ifLastModified.type = IfLastModified

# Delete all files older than 1 day
appender.rolling1.strategy.delete.ifLastModified.age = 1d

# loggers
logger.name = common
logger.level = debug
logger.additivity = false
logger.appenderRefs = rolling1
logger.appenderRefs.level = debug
logger.appenderRef.rolling1.ref = RollingFile1

The rollover works hourly and minutely if interval given and filepattern is given as ${filepath}/Common.%d{yyyy-MM-dd-HH} and ${filepath}/Common.%d{yyyy-MM-HH-minutely}

How to rollover half-daily? Is it supported in log4j2?


问:
Groovy: json get value of id based on child value
I have a json as below:

```<code>[
   {
      "id":6619137,
      "oid":"6fykq37gm60x",
      "key":{
         "key":"6619137"
      },
      "name":"Prod",
      "planKey":{
         "key":"PDP"
      },
      "environments":[
         {
            "id":6225923,
            "key":{
               "key":"6619137-6225923"
            },
            "name":"Production",
            "deploymentProjectId":6619137,
         }
      ],
   },
   {
      "id":6619138,
      "oid":"6fykq37gm60y",
      "key":{
         "key":"6619138"
      },
      "name":"QA",
      "planKey":{
         "key":"QDP"
      },
      "environments":[
         {
            "id":6225924,
            "key":{
               "key":"6619138-6225924"
            },
            "name":"QA",
            "deploymentProjectId":6619138,
         }
      ],
   },
]
</code>```

I can use the below code to extract the value of id and environments.id based on the name value. projectID will give 6619137 and environmentID will give 6225923

```<code>def e = json.planKey.find{it.name=='Prod'}
def projectID = e.id
def environmentID = e.environments[0].id
</code>```

However, when I try to extract the value of id and environments.id based on the plankey.key value (e.g. PDP or QDP), using the same format above returns me an error of java.lang.NullPointerException: Cannot get property 'id' on null object at Script60.run(Script60.groovy:52)

```<code>def e = json.planKey.find{it.planKey=='{key=PDP}'}
def projectID = e.id
def environmentID = e.environments[0].id
</code>```

Is there a way I can get the projectID with the plankey key value?

答:
Think of your JSON object as a key/value map with multiple levels.  There is no such item as

```<code>json.find{it.planKey=='{key=PDP}'}
</code>```

However, you can find with values at any level, like this:

```<code>def e = json.find{it.planKey.key == "PDP"}
</code>```

If you have a structure where planKey may  not exist, or it doesn't always have key, that's a bit different, but from your question it sounds like that's not the case here.

EDIT: correcting syntax based on comment below.

Body:
I have a json as below:

[
   {
      "id":6619137,
      "oid":"6fykq37gm60x",
      "key":{
         "key":"6619137"
      },
      "name":"Prod",
      "planKey":{
         "key":"PDP"
      },
      "environments":[
         {
            "id":6225923,
            "key":{
               "key":"6619137-6225923"
            },
            "name":"Production",
            "deploymentProjectId":6619137,
         }
      ],
   },
   {
      "id":6619138,
      "oid":"6fykq37gm60y",
      "key":{
         "key":"6619138"
      },
      "name":"QA",
      "planKey":{
         "key":"QDP"
      },
      "environments":[
         {
            "id":6225924,
            "key":{
               "key":"6619138-6225924"
            },
            "name":"QA",
            "deploymentProjectId":6619138,
         }
      ],
   },
]

I can use the below code to extract the value of id and environments.id based on the name value. projectID will give 6619137 and environmentID will give 6225923

def e = json.planKey.find{it.name=='Prod'}
def projectID = e.id
def environmentID = e.environments[0].id

However, when I try to extract the value of id and environments.id based on the plankey.key value (e.g. PDP or QDP), using the same format above returns me an error of java.lang.NullPointerException: Cannot get property 'id' on null object at Script60.run(Script60.groovy:52)

def e = json.planKey.find{it.planKey=='{key=PDP}'}
def projectID = e.id
def environmentID = e.environments[0].id

Is there a way I can get the projectID with the plankey key value?

Body:
Think of your JSON object as a key/value map with multiple levels.  There is no such item as

json.find{it.planKey=='{key=PDP}'}

However, you can find with values at any level, like this:

def e = json.find{it.planKey.key == "PDP"}

If you have a structure where planKey may  not exist, or it doesn't always have key, that's a bit different, but from your question it sounds like that's not the case here.

EDIT: correcting syntax based on comment below.


问:
Set Faker's seed globally for Laravel's factories
I want to generate the same data every time with already existing Laravel (5.7) factories. I saw that Faker does have an option to set seed - $faker->seed(123);, but this have to be added to every single factory.

I was looking for a way to do this, but without success. The $faker is set in the constructor of the Factory class, and I thought I can just extend it and add the seed method to $faker. The problem is this class is used in the helpers.php (line 495) which is vendor file, that cannot be modified. Is there maybe a way to overwrite those helper functions in Laravel? Or maybe there is a easier way, that I'm not seeing.

答:
For anyone looking for more recent version:

public function setUp(): void
{
    parent::setUp();
    app(\Faker\Generator::class)->seed(919237);
}

```

Our use-case was making tests deterministic while keeping seeders random.

Body:
For anyone looking for more recent version:

public function setUp(): void
{
    parent::setUp();
    app(\Faker\Generator::class)->seed(919237);
}

Our use-case was making tests deterministic while keeping seeders random.


问:
How to access the files in bin/debug within the project folder in Visual studio 2010?
I have my docx.xsl file in my project/bin/debug folder.Now i want to access this file whenever i needed.But i could not able to access this file.

```<code> WordprocessingDocument wordDoc = WordprocessingDocument.Open(inputFile, true);
 MainDocumentPart mainDocPart = wordDoc.MainDocumentPart;
 XPathDocument xpathDoc = new XPathDocument(mainDocPart.GetStream());
 XslCompiledTransform xslt = new XslCompiledTransform();

 string xsltFile = @"\\docx.xsl"; // or @"docx.xsl";

 xslt.Load(xsltFile);
 XmlTextWriter writer = new XmlTextWriter(outputFile, null);
 xslt.Transform(xpathDoc, null, writer);
 writer.Close();
 wordDoc.Close();
</code>```

Please Guide me to put correct valid path to access docx.xsl file...

答:
You can determine the location of your executable, and assuming the file will be deployed with the application to the relevant directory, then this should help you find the file in debugging and in deployment:

```<code>string executableLocation = Path.GetDirectoryName(
    Assembly.GetExecutingAssembly().Location);
string xslLocation = Path.Combine(executableLocation, "docx.xsl");
</code>```

You might need the following namespaces imported at the top of your file:

```<code>using System;
using System.IO;
using System.Reflection;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have my docx.xsl file in my project/bin/debug folder.Now i want to access this file whenever i needed.But i could not able to access this file.

 WordprocessingDocument wordDoc = WordprocessingDocument.Open(inputFile, true);
 MainDocumentPart mainDocPart = wordDoc.MainDocumentPart;
 XPathDocument xpathDoc = new XPathDocument(mainDocPart.GetStream());
 XslCompiledTransform xslt = new XslCompiledTransform();

 string xsltFile = @"\\docx.xsl"; // or @"docx.xsl";

 xslt.Load(xsltFile);
 XmlTextWriter writer = new XmlTextWriter(outputFile, null);
 xslt.Transform(xpathDoc, null, writer);
 writer.Close();
 wordDoc.Close();

Please Guide me to put correct valid path to access docx.xsl file...

Body:
You can determine the location of your executable, and assuming the file will be deployed with the application to the relevant directory, then this should help you find the file in debugging and in deployment:

string executableLocation = Path.GetDirectoryName(
    Assembly.GetExecutingAssembly().Location);
string xslLocation = Path.Combine(executableLocation, "docx.xsl");

You might need the following namespaces imported at the top of your file:

using System;
using System.IO;
using System.Reflection;


问:
If there's a pandas row with two distinct value, do this
I have a pandas dataframe (df) that looks like this

```<code>   Phase  Sig  EJO
0      1    -1    2
1      1     0    2
2      1     1    2
3      2    -1    7
4      2     1    1
</code>```

I want to figure how to write a statement such that if there is any row with a 1 for Phase and 0 for Sig to multiple that row's EJO by 2

This is my desired output

```<code>   Phase  Sig  EJO
0      1    -1    2
1      1     0    4
2      1     1    2
3      2    -1    7
4      2     1    1
</code>```

I will be doing this on a much larger scale

答:
You can use np.where:

```<code>df['EJO'] = df['EJO'] * np.where(df['Phase'].eq(1) & df['Sig'].eq(0), 2, 1)
</code>```

Output:

```<code>>>> df
   Phase  Sig  EJO
0      1   -1    2
1      1    0    4
2      1    1    2
3      2   -1    7
4      2    1    1
</code>```

Body:
I have a pandas dataframe (df) that looks like this

   Phase  Sig  EJO
0      1    -1    2
1      1     0    2
2      1     1    2
3      2    -1    7
4      2     1    1

I want to figure how to write a statement such that if there is any row with a 1 for Phase and 0 for Sig to multiple that row's EJO by 2

This is my desired output

   Phase  Sig  EJO
0      1    -1    2
1      1     0    4
2      1     1    2
3      2    -1    7
4      2     1    1

I will be doing this on a much larger scale

Body:
You can use np.where:

df['EJO'] = df['EJO'] * np.where(df['Phase'].eq(1) & df['Sig'].eq(0), 2, 1)

Output:

>>> df
   Phase  Sig  EJO
0      1   -1    2
1      1    0    4
2      1    1    2
3      2   -1    7
4      2    1    1


问:
Get item contains substring Terraform
I have the feollowing variable in my code:

```<code>variable "mylist" {
  default = ["cardigan.com", "crazy-apple.com", "blue-pen.com"]
}
</code>```

On a creation of given resource, I have to pass the name of element in this list according to a substring. How can a retrieve the element of this list that contains the substring "apple", for example?

答:
A collect/filter/map family function also does not exist yet in Terraform. We therefore can use a for expression lambda with a conditional inside a list constructor:

```<code>[ for item in var.my_list : item if can(regex("apple", item)) ]
</code>```

and this returns ["crazy-apple.com"] for your example variable value. You can then access its elements to return the string e.g. crazy-apple.com as per normal. If you are using >= 0.15, and are very confident only one match exists, then you could also do:

```<code>one([ for item in var.my_list : item if can(regex("apple", item)) ])
</code>```

to directly return crazy-apple.com.

Title: Get item contains substring Terraform

Body:
I have the feollowing variable in my code:

variable "mylist" {
  default = ["cardigan.com", "crazy-apple.com", "blue-pen.com"]
}

On a creation of given resource, I have to pass the name of element in this list according to a substring. How can a retrieve the element of this list that contains the substring "apple", for example?

Body:
A collect/filter/map family function also does not exist yet in Terraform. We therefore can use a for expression lambda with a conditional inside a list constructor:

[ for item in var.my_list : item if can(regex("apple", item)) ]

and this returns ["crazy-apple.com"] for your example variable value. You can then access its elements to return the string e.g. crazy-apple.com as per normal. If you are using >= 0.15, and are very confident only one match exists, then you could also do:

one([ for item in var.my_list : item if can(regex("apple", item)) ])

to directly return crazy-apple.com.


问:
Group values based on annotation
Suppose I have the following lists

```<code>a = (np.array([ 0, 1, 2, 5, 6, 7, 8, 9, 12]), np.array([ 2, 3, 4, 0, 2, 2, 3, 4, 0]))
b = (np.array([ 5, 6, 7, 8, 9, 12]), np.array([ 100, 200, 300, 400, 500, 600]))
</code>```

Where elements of a[1] are between 0 and 4

My objective is to cluster elements of b in terms of elements of a. Given the example, the results would be:

```<code>c = (np.array([0, 1, 2, 3, 4, 0]), np.array([ val1, val2, val3, val4, val5, val6]))
c = (np.array([val1, val6]), np.array([val2]), np.array([val3]), np.array([val4]), np.array([val5]))
</code>```

This is because b[1][0] = val1 and b[1][5] = val6 reference to a annotation 0, as b[0][0] = a[0][3] = 5 and a[1][3] = 0, and similar for b[0][5].

One easy way of doing this is:

```<code>c = [ [] for i in range(5)]

for idx in range(len(b[0])):
    ids = np.argwhere(a[0] == b[0][idx])

    for id in ids:

        inc = id[0]
        elem = b[1][idx]
        index = a[1][inc]
        #print(inc, elem, index)
        c[index].append(elem)

c = [ np.array(element) for element in c ]
</code>```

Yet, I find it very simplicistic and not scalable. Is there any other way of doing this easily?

答:
You have a pretty convoluted series of indexing you want to perform, is there a way to simplify what you're doing? If not, giving each element of each tuple a different name will at least make things somewhat more understandable.

But to answer your question, here's a one-liner that will give you the same list as c in your example:

import numpy as np

a = np.array([ 2, 3, 4, 0, 2, 2, 3, 4, 0])
b = np.array([ 0, 1, 2, 5, 6, 7, 8, 9, 12])
c = np.array([ 5, 6, 7, 8, 9, 12])
d = np.array([ 100, 200, 300, 400, 500, 600])

e = [d[np.searchsorted(c, b[a == value])] for value in range(5)]
```

For each value from 0 to 4 (inclusive), the index of elements in a that match value are used into index into b. Then np.searchsorted is used to find the location in c of all the values selected b. Finally, these indices are used to index into d.

It's horribly unreadable, so you would probably want to do each operation on a separate line.

Title: Group values based on annotation

Body:
Suppose I have the following lists

a = (np.array([ 0, 1, 2, 5, 6, 7, 8, 9, 12]), np.array([ 2, 3, 4, 0, 2, 2, 3, 4, 0]))
b = (np.array([ 5, 6, 7, 8, 9, 12]), np.array([ 100, 200, 300, 400, 500, 600]))

Where elements of a[1] are between 0 and 4

My objective is to cluster elements of b in terms of elements of a. Given the example, the results would be:

c = (np.array([0, 1, 2, 3, 4, 0]), np.array([ val1, val2, val3, val4, val5, val6]))
c = (np.array([val1, val6]), np.array([val2]), np.array([val3]), np.array([val4]), np.array([val5]))

This is because b[1][0] = val1 and b[1][5] = val6 reference to a annotation 0, as b[0][0] = a[0][3] = 5 and a[1][3] = 0, and similar for b[0][5].

One easy way of doing this is:

c = [ [] for i in range(5)]

for idx in range(len(b[0])):
    ids = np.argwhere(a[0] == b[0][idx])

    for id in ids:

        inc = id[0]
        elem = b[1][idx]
        index = a[1][inc]
        #print(inc, elem, index)
        c[index].append(elem)

c = [ np.array(element) for element in c ]

Yet, I find it very simplicistic and not scalable. Is there any other way of doing this easily?

Body:
You have a pretty convoluted series of indexing you want to perform, is there a way to simplify what you're doing? If not, giving each element of each tuple a different name will at least make things somewhat more understandable.

But to answer your question, here's a one-liner that will give you the same list as c in your example:

import numpy as np

a = np.array([ 2, 3, 4, 0, 2, 2, 3, 4, 0])
b = np.array([ 0, 1, 2, 5, 6, 7, 8, 9, 12])
c = np.array([ 5, 6, 7, 8, 9, 12])
d = np.array([ 100, 200, 300, 400, 500, 600])

e = [d[np.searchsorted(c, b[a == value])] for value in range(5)]

For each value from 0 to 4 (inclusive), the index of elements in a that match value are used into index into b. Then np.searchsorted is used to find the location in c of all the values selected b. Finally, these indices are used to index into d.

It's horribly unreadable, so you would probably want to do each operation on a separate line.


问:
Using rbind within a pipe
Is it possible to use rbind within a pipe so that I don't have to define and store a variable to use it?

```<code>library(tidyverse)

## works fine
df <- iris %>%
  group_by(Species) %>%
  summarise(Avg.Sepal.Length = mean(Sepal.Length)) %>%
  ungroup

df %>%
  rbind(df)

## anyway to make this work?
iris %>%
  group_by(Species) %>%
  summarise(Avg.Sepal.Length = mean(Sepal.Length)) %>%
  ungroup %>%
  rbind(.)
</code>```

答:
Just to elaborate @MichaelDewar's answer, note the following section of ?magrittr::`%>%`:

Placing lhs elsewhere in rhs call

Often you will want lhs to the rhs call at another position than the first. For this purpose you can use the dot (.) as placeholder. For example, y %>% f(x, .) is equivalent to f(x, y) and z %>% f(x, y, arg = .) is equivalent to f(x, y, arg = z).

My understanding is that when . appears as an argument in the right hand side call, the left hand side is not inserted in the first position. The call is evaluated "as is", with . evaluating to the left hand side. Hence:

library("dplyr")
x <- data.frame(a = 1:2, b = 3:4)

x %>% rbind() # rbind(x)
##   a b
## 1 1 3
## 2 2 4

x %>% rbind(.) # same
##   a b
## 1 1 3
## 2 2 4

x %>% rbind(x) # rbind(x, x)
##   a b
## 1 1 3
## 2 2 4
## 3 1 3
## 4 2 4

x %>% rbind(x, .) # same
x %>% rbind(., x) # same
x %>% rbind(., .) # same
##   a b
## 1 1 3
## 2 2 4
## 3 1 3
## 4 2 4
```
<p>You can devise clever tricks if you know the rules:</p>
<pre class="lang-r prettyprint-override"><code>x %>% rbind((.)) # rbind(x, (x))
##   a b
## 1 1 3
## 2 2 4
## 3 1 3
## 4 2 4
</code>```

(.) isn't parsed like ., so the left hand is inserted in the first position of the right hand side call. Compare:

as.list(quote(.))
## [[1]]
## .

as.list(quote((.)))
## [[1]]
## `(`
##
## [[2]]
## .
```

Title: Using rbind within a pipe

Body:
Is it possible to use rbind within a pipe so that I don't have to define and store a variable to use it?

library(tidyverse)

## works fine
df <- iris %>%
  group_by(Species) %>%
  summarise(Avg.Sepal.Length = mean(Sepal.Length)) %>%
  ungroup

df %>%
  rbind(df)

## anyway to make this work?
iris %>%
  group_by(Species) %>%
  summarise(Avg.Sepal.Length = mean(Sepal.Length)) %>%
  ungroup %>%
  rbind(.)

Body:
Just to elaborate @MichaelDewar's answer, note the following section of ?magrittr::`%>%`:

Placing lhs elsewhere in rhs call

Often you will want lhs to the rhs call at another position than the first. For this purpose you can use the dot (.) as placeholder. For example, y %>% f(x, .) is equivalent to f(x, y) and z %>% f(x, y, arg = .) is equivalent to f(x, y, arg = z).

My understanding is that when . appears as an argument in the right hand side call, the left hand side is not inserted in the first position. The call is evaluated "as is", with . evaluating to the left hand side. Hence:

library("dplyr")
x <- data.frame(a = 1:2, b = 3:4)

x %>% rbind() # rbind(x)
##   a b
## 1 1 3
## 2 2 4

x %>% rbind(.) # same
##   a b
## 1 1 3
## 2 2 4

x %>% rbind(x) # rbind(x, x)
##   a b
## 1 1 3
## 2 2 4
## 3 1 3
## 4 2 4

x %>% rbind(x, .) # same
x %>% rbind(., x) # same
x %>% rbind(., .) # same
##   a b
## 1 1 3
## 2 2 4
## 3 1 3
## 4 2 4

You can devise clever tricks if you know the rules:

x %>% rbind((.)) # rbind(x, (x))
##   a b
## 1 1 3
## 2 2 4
## 3 1 3
## 4 2 4

(.) isn't parsed like ., so the left hand is inserted in the first position of the right hand side call. Compare:

as.list(quote(.))
## [[1]]
## .

as.list(quote((.)))
## [[1]]
## `(`
##
## [[2]]
## .


问:
Stop mod_rewrite returning REQUEST_URI when (.*) is empty
```<code>Options +FollowSymLinks
RewriteEngine On
RewriteRule ^mocks/site/(.*)$ http://thelivewebsite.com/$1 [R=301,L]
</code>```

That is my htaccess file's contents.

The htaccess file is in the root directory of the hosting account and I just want to redirect the directory mocks/site/ to the new domain (with or without any extra directories).

eg: if someone goes to http://mywebsite.com/mocks/site then it needs to redirect to http://thelivewebsite.com. If they go to http://mywebsite.com/mocks/site/another/directory then it needs to redirect to http://thelivewebsite.com/another/directory. I hope that makes sense.

So the problem I have is that the htaccess code above seems to work pretty well when there is something after mocks/site/ however when there isn't something after that then the $1 in the redirect seems to reference the whole REQUEST_URI (eg: mocks/site/ rather than nothing - as there is nothing after it).

I don't know how to stop this. I thought about using a RewriteCond, but I'm not sure what to use there. I can't find anything that helps me to determine if there is anything after mocks/site/ or not.

Any help will be much appreciated.

Thank you.

答:
That's very strange behaviour -- never seen anything like that. Therefore I think it could be something else (another rule somewhere -- on old or even new site). I recommend enabling rewrite debugging (RewriteLogLevel 9) and check the rewrite log (that's if you can edit Apache's config file / virtual host definition).

In any case, try this combination:

```<code>Options +FollowSymLinks
RewriteEngine On

RewriteRule ^mocks/site/$ http://thelivewebsite.com/ [R=301,L]
RewriteRule ^mocks/site/(.+)$ http://thelivewebsite.com/$1 [R=301,L]
</code>```

It will do matching/redirecting in 2 steps: first rule is for exact directory match (so no $1 involved at all) and 2nd will work if there is at least 1 character after the /mocks/site/.

Alternatively (Apache docs even recommending this one) use Redirect directive (no need for mod_rewrite at all for such simple redirects):

```<code>Redirect 301 /mocks/site/ http://thelivewebsite.com/
</code>```

Body:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^mocks/site/(.*)$ http://thelivewebsite.com/$1 [R=301,L]

That is my htaccess file's contents.

The htaccess file is in the root directory of the hosting account and I just want to redirect the directory mocks/site/ to the new domain (with or without any extra directories).

eg: if someone goes to http://mywebsite.com/mocks/site then it needs to redirect to http://thelivewebsite.com. If they go to http://mywebsite.com/mocks/site/another/directory then it needs to redirect to http://thelivewebsite.com/another/directory. I hope that makes sense.

So the problem I have is that the htaccess code above seems to work pretty well when there is something after mocks/site/ however when there isn't something after that then the $1 in the redirect seems to reference the whole REQUEST_URI (eg: mocks/site/ rather than nothing - as there is nothing after it).

I don't know how to stop this. I thought about using a RewriteCond, but I'm not sure what to use there. I can't find anything that helps me to determine if there is anything after mocks/site/ or not.

Any help will be much appreciated.

Thank you.

Body:
That's very strange behaviour -- never seen anything like that. Therefore I think it could be something else (another rule somewhere -- on old or even new site). I recommend enabling rewrite debugging (RewriteLogLevel 9) and check the rewrite log (that's if you can edit Apache's config file / virtual host definition).

In any case, try this combination:

Options +FollowSymLinks
RewriteEngine On

RewriteRule ^mocks/site/$ http://thelivewebsite.com/ [R=301,L]
RewriteRule ^mocks/site/(.+)$ http://thelivewebsite.com/$1 [R=301,L]

It will do matching/redirecting in 2 steps: first rule is for exact directory match (so no $1 involved at all) and 2nd will work if there is at least 1 character after the /mocks/site/.

Alternatively (Apache docs even recommending this one) use Redirect directive (no need for mod_rewrite at all for such simple redirects):

Redirect 301 /mocks/site/ http://thelivewebsite.com/


问:
Python error only size-1 arrays can be converted to Python scalars
I'm writing a tKinter GUI and I've come accross a problem. Given the the main code is way to large, I've made a dummy example to replicate my problem.

```<code>class test():
    def __init__(self,time,a):

        self.time = time
        self.a = a

    def something(self):

        self.b = float(self.time) * self.a

        return {'bVar':self.b}

time = np.linspace(0,100,10)
testObj = test(time,2.2)
print(testObj.something().get('bVar'))
</code>```

The error is:

```<code>----> 9         self.b = float(self.time) * self.a
     10
     11         return {'bVar':self.b}

TypeError: only size-1 arrays can be converted to Python scalars
</code>```

If I remove the float conversion of time, then it works. But in my main GUI I need to keep float(self.time).
self.a in my GUI is a tKinter entry that has to be also of type float(entry[1].get())

Any thoughts on how I can remedy this?

答:
Well, this is a workaround</p>
```<code>class test():
    def __init__(self,time, a):

        self.time = time
        self.a = a

    def something(self):

        self.b = float(self.time) * self.a
        self.c = float(self.time) * 10

        return {'bVar':self.b, 'cVar':self.c}

#time = np.linspace(0,100,10)
list1 = []
list2 = []
for time in range(0,1000):
    testObj = test(time, 2.2)
    list1.append(testObj.something().get('bVar'))
    list2.append(testObj.something().get('cVar'))

a = np.array([list1,list2])
a[0]
</code>```

Body:
I'm writing a tKinter GUI and I've come accross a problem. Given the the main code is way to large, I've made a dummy example to replicate my problem.

class test():
    def __init__(self,time,a):

        self.time = time
        self.a = a

    def something(self):

        self.b = float(self.time) * self.a

        return {'bVar':self.b}

time = np.linspace(0,100,10)
testObj = test(time,2.2)
print(testObj.something().get('bVar'))

The error is:

----> 9         self.b = float(self.time) * self.a
     10
     11         return {'bVar':self.b}

TypeError: only size-1 arrays can be converted to Python scalars

If I remove the float conversion of time, then it works. But in my main GUI I need to keep float(self.time).
self.a in my GUI is a tKinter entry that has to be also of type float(entry[1].get())

Any thoughts on how I can remedy this?

Body:
Well, this is a workaround

class test():
    def __init__(self,time, a):

        self.time = time
        self.a = a

    def something(self):

        self.b = float(self.time) * self.a
        self.c = float(self.time) * 10

        return {'bVar':self.b, 'cVar':self.c}

#time = np.linspace(0,100,10)
list1 = []
list2 = []
for time in range(0,1000):
    testObj = test(time, 2.2)
    list1.append(testObj.something().get('bVar'))
    list2.append(testObj.something().get('cVar'))

a = np.array([list1,list2])
a[0]


问:
How to transfer eth from an account to a contract?
I'm fresh on solidity, when I use remix to test my contract, I want to transfer some eth from my account to the smart contract. I have tried this code, but it seems to transfer the eth from the contract but not my account.

```<code>    function addStaker (uint _stakeAmount) public membership(master, msg.sender) returns(bool) {
    if(!members[msg.sender].alreadyExist) {
        Member memory newMember = Member(msg.sender, true);
        members[msg.sender] = newMember;
        bool sent = payable(address(this)).send(_stakeAmount);
        require(sent, "invalid balance");
        return true;
    } else {
        return false;
    }
}
</code>```

How could I transfer eth from my account to the smart contract?

答:
If you want to implement a defi contract (since your function name is addStaker) that accepts staked coins from ERC20 tokens, the implementation is different. But if you just want to send money to contract from your metamask account, you have to mark the function payable.

```<code> function pay() public payable {
            //  msg.value is the amount of wei sent with the message to the contract.
            // with this you are setting a minimum amount
            require(msg.value > .01 ether);
            // add your logic
    }
</code>```

Body:
I'm fresh on solidity, when I use remix to test my contract, I want to transfer some eth from my account to the smart contract. I have tried this code, but it seems to transfer the eth from the contract but not my account.

    function addStaker (uint _stakeAmount) public membership(master, msg.sender) returns(bool) {
    if(!members[msg.sender].alreadyExist) {
        Member memory newMember = Member(msg.sender, true);
        members[msg.sender] = newMember;
        bool sent = payable(address(this)).send(_stakeAmount);
        require(sent, "invalid balance");
        return true;
    } else {
        return false;
    }
}

How could I transfer eth from my account to the smart contract?

Body:
If you want to implement a defi contract (since your function name is addStaker) that accepts staked coins from ERC20 tokens, the implementation is different. But if you just want to send money to contract from your metamask account, you have to mark the function payable.

 function pay() public payable {
            //  msg.value is the amount of wei sent with the message to the contract.
            // with this you are setting a minimum amount
            require(msg.value > .01 ether);
            // add your logic
    }


答:
From what I understood, you are trying to generate 2 lists: one containing all the paths in "D:\Arm C Deep Learning\SH_OCTAPUS\Train" and one containing 0s and 1s depending on whether a path is in df_train_pos_list.

This should do the trick:

from pathlib import Path

df_train_pos_list = []
train_images = []
train_labels = []
df_train_pos_set = set(df_train_pos_list)

for path in Path("D:\Arm C Deep Learning\SH_OCTAPUS\Train").glob("*"):
    train_images.append(path)
    train_labels.append(1 if path.name in df_train_pos_set else 0)
```

A couple things to note:

pathlib is best practice when dealing with the file system.

I'm creating a set from your df_train_pos_list to improve complexity. It will take O(N) time complexity to create the set from the list but it will take O(1) to check whether a path is in the set whereas it would take O(N) using a list.

Title: How to select folders from a directory based on a python list of the folder names?

Body:
I have a list of folder names - "df_train_pos_list"

I want to iterate through a directory and select folders with those names, and add them to another list - "train_images"

So far what I have tried doesn't work:

train_images = []
train_labels = []

for i in df_train_pos_list:
    for currentpath, folders, files in os.walk('D:\Arm C Deep Learning\SH_OCTAPUS\Train'):
        for file in files:
            if i in currentpath:
                train_images.append('D:\Arm C Deep Learning\SH_OCTAPUS\Train' + file)
                train_labels.append(1)
            else:
                train_images.append('D:\Arm C Deep Learning\SH_OCTAPUS\Train' + file)
                train_labels.append(0)
train_labels = np.asarray(train_labels, dtype=np.int64)
print(train_labels)
np.unique(train_labels, return_counts='TRUE')

Body:
From what I understood, you are trying to generate 2 lists: one containing all the paths in "D:\Arm C Deep Learning\SH_OCTAPUS\Train" and one containing 0s and 1s depending on whether a path is in df_train_pos_list.

This should do the trick:

from pathlib import Path

df_train_pos_list = []
train_images = []
train_labels = []
df_train_pos_set = set(df_train_pos_list)

for path in Path("D:\Arm C Deep Learning\SH_OCTAPUS\Train").glob("*"):
    train_images.append(path)
    train_labels.append(1 if path.name in df_train_pos_set else 0)

A couple things to note:

pathlib is best practice when dealing with the file system.

I'm creating a set from your df_train_pos_list to improve complexity. It will take O(N) time complexity to create the set from the list but it will take O(1) to check whether a path is in the set whereas it would take O(N) using a list.


问:
Bash script FOR in create folder
System Linux Mint. 3-4 lines. Please inspect the code. And is it possible to somehow write the cycle in one line, as I tried below?</p>
```<code>#!/bin/bash
cd MyFolder
name_folder=('MyFolder1' 'MyFolder1' 'MyFolder3')
for i in ${name_folder} do mkdir $i
cd MyFolder3
FOR %%A IN (txt1.txt,txt2.txt,txt3.txt) DO touch "%%~A"
FOR %%A IN (json1.json,json2.json) DO touch "%%~A"
FOR %%A IN (NewFolder1,NewFolder1,NewFolder3) DO mkdir "%%~A"
ls
mv json1.json ../Myfolder1
mv json1.json ../Myfolder1
</code>```

答:
```<code>#!/bin/bash
mkdir MyFolder
cd MyFolder
name_folder="MyFolder1 MyFolder2 MyFolder3"
for i in ${name_folder}; do mkdir $i; done
cd MyFolder3
F="txt1.txt txt2.txt txt3.txt"
for A in $F; do touch "$A"; done
F="json1.json json2.json"
for A in $F; do touch "$A"; done
F="NewFolder1 NewFolder2 NewFolder3"
for A in $F ; do mkdir "$A"; done
ls
mv json1.json ../Myfolder1
mv json2.json ../Myfolder1

</code>```

Title: Bash script FOR in create folder

Body:
System Linux Mint. 3-4 lines. Please inspect the code. And is it possible to somehow write the cycle in one line, as I tried below?

#!/bin/bash
cd MyFolder
name_folder=('MyFolder1' 'MyFolder1' 'MyFolder3')
for i in ${name_folder} do mkdir $i
cd MyFolder3
FOR %%A IN (txt1.txt,txt2.txt,txt3.txt) DO touch "%%~A"
FOR %%A IN (json1.json,json2.json) DO touch "%%~A"
FOR %%A IN (NewFolder1,NewFolder1,NewFolder3) DO mkdir "%%~A"
ls
mv json1.json ../Myfolder1
mv json1.json ../Myfolder1


问:
Unable to pull the key:value from dictionary in column to multiple columns
So I was using the solution in this post (Split / Explode a column of dictionaries into separate columns with pandas) but nothing changes in my df.

Here is df before code:

```<code>    number  status_timestamps
0   234234  {"created": "2020-11-30T19:44:42Z", "complete"...
1   2342    {"created": "2020-12-14T13:43:48Z", "complete"...
</code>```

Here is a sample of the dictionary in that column:

```<code>{"created": "2020-11-30T19:44:42Z",
"complete": "2021-01-17T14:20:58Z",
 "invoiced": "2020-12-16T22:55:02Z",
 "confirmed": "2020-11-30T21:16:48Z",
 "in_production": "2020-12-11T18:59:26Z",
 "invoice_needed": "2020-12-11T22:00:09Z",
 "accepted": "2020-12-01T00:00:23Z",
 "assets_uploaded": "2020-12-11T17:16:53Z",
 "notified": "2020-11-30T21:17:48Z",
 "processing": "2020-12-11T18:49:50Z",
 "classified": "2020-12-11T18:49:50Z"}
</code>```

Here is what I tried and df does not change:

```<code>df_final = pd.concat([df, df['status_timestamps'].progress_apply(pd.Series)], axis = 1).drop('status_timestamps', axis = 1)
</code>```

Here is what happens in a notebook:

答:
I was able to use another answer from that post but change to a safer option of literal_eval since it was using eval

Here is working code:

```<code>import pandas as pd
from ast import literal_eval
df  = pd.read_csv('c:/status_timestamps.csv')
df["status_timestamps"] = df["status_timestamps"].apply(lambda x : dict(literal_eval(x)) )
df2 = df["status_timestamps"].apply(pd.Series )
df_final = pd.concat([df, df2], axis=1).drop('status_timestamps', axis=1)
df_final
</code>```

Body:
So I was using the solution in this post (Split / Explode a column of dictionaries into separate columns with pandas) but nothing changes in my df.

Here is df before code:

    number  status_timestamps
0   234234  {"created": "2020-11-30T19:44:42Z", "complete"...
1   2342    {"created": "2020-12-14T13:43:48Z", "complete"...

Here is a sample of the dictionary in that column:

{"created": "2020-11-30T19:44:42Z",
"complete": "2021-01-17T14:20:58Z",
 "invoiced": "2020-12-16T22:55:02Z",
 "confirmed": "2020-11-30T21:16:48Z",
 "in_production": "2020-12-11T18:59:26Z",
 "invoice_needed": "2020-12-11T22:00:09Z",
 "accepted": "2020-12-01T00:00:23Z",
 "assets_uploaded": "2020-12-11T17:16:53Z",
 "notified": "2020-11-30T21:17:48Z",
 "processing": "2020-12-11T18:49:50Z",
 "classified": "2020-12-11T18:49:50Z"}

Here is what I tried and df does not change:

df_final = pd.concat([df, df['status_timestamps'].progress_apply(pd.Series)], axis = 1).drop('status_timestamps', axis = 1)

Here is what happens in a notebook:

Body:
I was able to use another answer from that post but change to a safer option of literal_eval since it was using eval

Here is working code:

import pandas as pd
from ast import literal_eval
df  = pd.read_csv('c:/status_timestamps.csv')
df["status_timestamps"] = df["status_timestamps"].apply(lambda x : dict(literal_eval(x)) )
df2 = df["status_timestamps"].apply(pd.Series )
df_final = pd.concat([df, df2], axis=1).drop('status_timestamps', axis=1)
df_final


问:
How best to loop over a batch of Results with a C# DbDataReader
I'm executing a number of SQL query's as a batch and then getting all of the result sets back in a batch.  The way that my code is currently put together, the first result set gets skipped.  Now that I know this, I could simply throw in another statement outside of my loop that grabs the first result, however I'm wondering if there is a more elegant solution to this problem.

Here is some sudo code of whats going on:

```<code>DbDataReader reader= /*some stuff that returns a batch of results...*/;

while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do things with the data....
       }
   }
}
</code>```

Now i would have expected that NextResult() advances you to the first result the first time you call it, which is what Read() seems to do.  However what it actually seems to do is bring you to the second result on the first call.  Am I misunderstanding how you're expected to use this method, or are you really expected to do some like the following:

```<code>DbDataReader reader= /*some stuff that returns a batch of results...*/;

//this deals with the row in the the very first result
while (reader.Read())
{
    if (!reader.IsDBNull(0))
    {
        //do things with the data....
    }
}

//this deals with the rest of the rows...
while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do exact same things with the data....
           //is this not pretty klugey?
       }
   }
}
</code>```

This strikes me as rotten programming style, but I don't see a way around it.  Does anyone know of a more elegant solution to this?

答:
In the great majority of cases, you will only be returning a single result set with any given call so it would not make sense for the designers to have required a "NextResultSet" every time you use a reader.

Thus, your second example does indeed hold if you are pulling multiple result sets.  The other thing that your post makes me wonder, though, is why you'd be doing the "exact same things with the data" if you are retrieving multiple result sets - wouldn't the structure of the data be different enough that you wouldn't be doing the exact same things?

That is, your example makes me wonder if you don't have some kind of bug in your thinking about how the data management functions work.

OwnerDisplayName: sweeney

ContentLicense: CC BY-SA 2.5

Body:
I'm executing a number of SQL query's as a batch and then getting all of the result sets back in a batch.  The way that my code is currently put together, the first result set gets skipped.  Now that I know this, I could simply throw in another statement outside of my loop that grabs the first result, however I'm wondering if there is a more elegant solution to this problem.

Here is some sudo code of whats going on:

DbDataReader reader= /*some stuff that returns a batch of results...*/;

while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do things with the data....
       }
   }
}

Now i would have expected that NextResult() advances you to the first result the first time you call it, which is what Read() seems to do.  However what it actually seems to do is bring you to the second result on the first call.  Am I misunderstanding how you're expected to use this method, or are you really expected to do some like the following:

DbDataReader reader= /*some stuff that returns a batch of results...*/;

//this deals with the row in the the very first result
while (reader.Read())
{
    if (!reader.IsDBNull(0))
    {
        //do things with the data....
    }
}

//this deals with the rest of the rows...
while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do exact same things with the data....
           //is this not pretty klugey?
       }
   }
}

This strikes me as rotten programming style, but I don't see a way around it.  Does anyone know of a more elegant solution to this?

OwnerDisplayName: Mark Brittingham


问:
Create a gke pod from a google cloud function
I want to create a google cloud function to create pods on my gke cluster. I  use the python kubernetes client to create them (I don't know if there is a better way to achive this).

Normally I would use the command: gcloud container clusters get-credentials cluster_name --region=cluster_region but cloud sdk is not installed in the cloud function environment.

I've read the python api documentation and I found that it is possible to pass the path to the kubeconfig file, but I didn't found how to create that file

答:
The get credential does nothing special:

Check if the cluster exists

Check if you have the permission on the cluster

Create the Kube config file with your access token.

That's all.

Now, when you use the kubectl command, the access token is used and put in the Authorization: Bearer header and perform an API call to Kubernetes control plane.

Therefore, if you want to reach directly the control plane from your Cloud Functions with an API call, simply the Cloud Functions access token in the security header and that's all!


问:
how to set a default value for a headerLeft?
Inside of my component render() method, I'm doing the following:

```<code>    if (this.state.text) {
      this.props.navigation.setOptions({
        headerLeft: this.headerLeft,
      });
    } else {
      this.props.navigation.setOptions({
        headerLeft: this.headerDEFAULT,
      });
    }
</code>```

I would like to leave headerLeft as empty instead of this.headerDEFAULT, to go back to its default state. How can that be done?

答:
it looks like this is inside of screen then use navigation.setOptions

headerLeft prop is your custom component so you override it

const navigation = useNavigation()
navigation.setOptions({headerLeft: (...props) => null})
```

Body:
Inside of my component render() method, I'm doing the following:

    if (this.state.text) {
      this.props.navigation.setOptions({
        headerLeft: this.headerLeft,
      });
    } else {
      this.props.navigation.setOptions({
        headerLeft: this.headerDEFAULT,
      });
    }

I would like to leave headerLeft as empty instead of this.headerDEFAULT, to go back to its default state. How can that be done?


问:
Is DS PhotoEditor SDK deprecated?
It uses onActivityResult and startActivityForResult  methods which are deprecated in android.

```<code>startActivityForResult(dsPhotoEditorIntent, 200);

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

     if (resultCode == RESULT_OK) {

         switch (requestCode) {

             case 200:

                 Uri outputUri = data.getData();

                 // handle the result uri as you want, such as display it in an imageView;

                 // imageView.setImageURI(outputUri);

                 break;

         }

     }

 }
</code>```

SDK Changelog says :

Android SDK:
Version 2.3 (v10):  //Latest
i) Support Android Q
ii) Migrate to AndroidX

So can we use it with registerForActivityResult method ?

答:
You can make it much simpler,

```<code>private var intentLaunch=
registerForActivityResult(ActivityResultContracts.StartActivityForResult()
{result ->

}
</code>```

Then you can just launch your intent here,

```<code>intentLaunch.launch(dsPhotoEditorIntent)
</code>```

You won't need a request code for this. You can directly handle it from the result. Here is the kotlin code sample. You can write similarly in java

```<code>ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    // There are no request codes
                    Intent data = result.getData();
                    doSomeOperations();
                }
            }
        });

public void openSomeActivityForResult() {
    someActivityResultLauncher.launch(dsPhotoEditorIntent);
}
</code>```

Title: Is DS PhotoEditor SDK deprecated?

Body:
It uses onActivityResult and startActivityForResult  methods which are deprecated in android.

startActivityForResult(dsPhotoEditorIntent, 200);

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

     if (resultCode == RESULT_OK) {

         switch (requestCode) {

             case 200:

                 Uri outputUri = data.getData();

                 // handle the result uri as you want, such as display it in an imageView;

                 // imageView.setImageURI(outputUri);

                 break;

         }

     }

 }

SDK Changelog says :

Android SDK:
Version 2.3 (v10):  //Latest
i) Support Android Q
ii) Migrate to AndroidX

So can we use it with registerForActivityResult method ?

Body:
You can make it much simpler,

private var intentLaunch=
registerForActivityResult(ActivityResultContracts.StartActivityForResult()
{result ->

}

Then you can just launch your intent here,

intentLaunch.launch(dsPhotoEditorIntent)

You won't need a request code for this. You can directly handle it from the result. Here is the kotlin code sample. You can write similarly in java

ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    // There are no request codes
                    Intent data = result.getData();
                    doSomeOperations();
                }
            }
        });

public void openSomeActivityForResult() {
    someActivityResultLauncher.launch(dsPhotoEditorIntent);
}


问:
Calculating dates and adding them to a list using a starting date, number of days and a number of payment occurences
I have a starting date, a number of days before payment occurs and a number of payment occurrences.
I want to create a list that has all the dates on which the subsequent payments occur.
I know the way to go about is to add the number of days to the starting date. As i have done below:

```<code> nextpaymentdate() {
    DateTime nextdate = startingDate!.add(Duration(days: 7));
    return nextdate;
  }
</code>```

But how do i add the dates for all the payment occurences in a list.

答:
You can just use a for loop to create the list.

List paymentOccurences = [];
int numberOfPaymentOccurrences = 5;
for (int i = 0; i < numberOfPaymentOccurrences; i++) {
    paymentOccurences.add(nextpaymentdate());
}
```
<p>and then use something like ListView.builder to display it in flutter.
https://docs.flutter.dev/cookbook/lists/long-lists</p>
<pre class="lang-dart prettyprint-override"><code>ListView.builder(
  itemCount: paymentOccurences.length,
  itemBuilder: (context, index) {
    return ListTile(
      title: Text(paymentOccurences[index]),
    );
  },
)
</code>```

Body:
I have a starting date, a number of days before payment occurs and a number of payment occurrences.
I want to create a list that has all the dates on which the subsequent payments occur.
I know the way to go about is to add the number of days to the starting date. As i have done below:

 nextpaymentdate() {
    DateTime nextdate = startingDate!.add(Duration(days: 7));
    return nextdate;
  }

But how do i add the dates for all the payment occurences in a list.

Body:
You can just use a for loop to create the list.

List paymentOccurences = [];
int numberOfPaymentOccurrences = 5;
for (int i = 0; i < numberOfPaymentOccurrences; i++) {
    paymentOccurences.add(nextpaymentdate());
}

and then use something like ListView.builder to display it in flutter.
https://docs.flutter.dev/cookbook/lists/long-lists

ListView.builder(
  itemCount: paymentOccurences.length,
  itemBuilder: (context, index) {
    return ListTile(
      title: Text(paymentOccurences[index]),
    );
  },
)


问:
R using a list of column names to remove unwanted character from data
I have read several CSVs into a tibble and am working to clean up the data. I have several columns where I need to remove the '%' character from the data. Every column with entries containing '%' has a similar name (for simplicity's sake,lets say they all end with 'A'), so I made a list of all column names, then used a for loop to create a list of columns names that need to be changed.

```<code>list_col <- colnames(df1)
change_col <- list()

for (i in seq_along(list_col)){
  last_char <- substr(list_col[i], nchar(col_list[i]), nchar(col_list[i]))
  ifelse(last_char == 'A', change_cols <- c(change_cols,list_col[i]),0))
}
</code>```

To get rid of the '%', my next step is to loop through the list I just created and mutate the df for each entry on the list. I figured out you can't pass variables as an argument to the mutate function, so I tried passing   parse_character(change_cols[[i]]) as an argument as shown below:

```<code>for (i in seq_along(change_col)){
  df1 <- df1 %>%
    mutate(parse_character(change_col[[i]])
           = gsub('\\%',"", parse_character(change_col[[i]])))
}
</code>```

When I run this code, I get Error: unexpected '}' in "}". I'm presuming it's because it does not like the arguments I've given the mutate function, but I've run out of ideas for a different way to run the loop.

答:
With dplyr, you can use across() inside mutate to pick which columns to work on. You haven't provided any sample data so this is untested, but should give you the idea:

```<code>df1 %>%
  mutate(across(
    ends_with("A"), ## all columns that end with "A"
    gsub, pattern = "%", replacement = "", fixed = TRUE
  ))
</code>```

Setting fixed = TRUE means we will match the pattern exactly, not with regex, so we don't have to worry about escapes. It will also be faster (not that that should matter unless you have tons of data).

See the ?across help page for more explanation and examples.

Body:
I have read several CSVs into a tibble and am working to clean up the data. I have several columns where I need to remove the '%' character from the data. Every column with entries containing '%' has a similar name (for simplicity's sake,lets say they all end with 'A'), so I made a list of all column names, then used a for loop to create a list of columns names that need to be changed.

list_col <- colnames(df1)
change_col <- list()

for (i in seq_along(list_col)){
  last_char <- substr(list_col[i], nchar(col_list[i]), nchar(col_list[i]))
  ifelse(last_char == 'A', change_cols <- c(change_cols,list_col[i]),0))
}

To get rid of the '%', my next step is to loop through the list I just created and mutate the df for each entry on the list. I figured out you can't pass variables as an argument to the mutate function, so I tried passing   parse_character(change_cols[[i]]) as an argument as shown below:

for (i in seq_along(change_col)){
  df1 <- df1 %>%
    mutate(parse_character(change_col[[i]])
           = gsub('\\%',"", parse_character(change_col[[i]])))
}

When I run this code, I get Error: unexpected '}' in "}". I'm presuming it's because it does not like the arguments I've given the mutate function, but I've run out of ideas for a different way to run the loop.

Body:
With dplyr, you can use across() inside mutate to pick which columns to work on. You haven't provided any sample data so this is untested, but should give you the idea:

df1 %>%
  mutate(across(
    ends_with("A"), ## all columns that end with "A"
    gsub, pattern = "%", replacement = "", fixed = TRUE
  ))

Setting fixed = TRUE means we will match the pattern exactly, not with regex, so we don't have to worry about escapes. It will also be faster (not that that should matter unless you have tons of data).

See the ?across help page for more explanation and examples.


问:
Maltego Local Transform: ParseError at [row,col];[1,1] Message: Content is not allowed in prolog
Im running a simple maltego transform taken from its website https://docs.maltego.com/support/solutions/articles/15000017605-local-transforms-example-#adding-the-transform-to-maltego-0-6 to get a person's name by searching their phone number.

My code looks like this.

```<code> @staticmethod
    def get_names(search_phone):
        matching_names = []
        with open("phone_to_names.csv") as f:
            for ln in f.readlines():
                phone, name, age = ln.split(",", 2)
                if phone.strip() == search_phone.strip():
                    matching_names.append(name.strip())
        return matching_names

if __name__ == "__main__":
    print(NameFromCSV.get_names("1-541-754-3010"))
</code>```

And my csv looks like this

```<code>1-541-754-3010, John Smith, 23
1-541-800-6987, Jane Doe, 24
1-336-854-1155, Alex Walker, 25
</code>```

When i run my transform on maltego i get ParseError at [row,col];[1,1] Message: Content is not allowd in prolog:

What is wrong?

答:
As said here by totakura

What's happening here is that Maltego expects XML to be written to standard transforms by your local transforms. If for some reason you python script writes anything else to the standard output (e.g printing a stack trace upon an exception, logging, or simply print()'ing) Maltego throws this error.

I think if you comment the print line print(NameFromCSV.get_names("1-541-754-3010")) will fix this error

Body:
Im running a simple maltego transform taken from its website https://docs.maltego.com/support/solutions/articles/15000017605-local-transforms-example-#adding-the-transform-to-maltego-0-6 to get a person's name by searching their phone number.

My code looks like this.

 @staticmethod
    def get_names(search_phone):
        matching_names = []
        with open("phone_to_names.csv") as f:
            for ln in f.readlines():
                phone, name, age = ln.split(",", 2)
                if phone.strip() == search_phone.strip():
                    matching_names.append(name.strip())
        return matching_names

if __name__ == "__main__":
    print(NameFromCSV.get_names("1-541-754-3010"))

And my csv looks like this

1-541-754-3010, John Smith, 23
1-541-800-6987, Jane Doe, 24
1-336-854-1155, Alex Walker, 25

When i run my transform on maltego i get ParseError at [row,col];[1,1] Message: Content is not allowd in prolog:

What is wrong?


问:
Find first file in directory with Java
I have some sort of batch program that should pick up a file from a directory and process it.

Since this program is supposed to:

run on JDK 5,

be small (no external libraries)

and fast! (with a bang)

...what is the best way to only pick one file from the directory - without using File.list() (might be hundreds of files)?

答:
Edit: My implementation made use of .list() as you said it wouldn't but It may hold some value anyways :)

If you look at the File implementation public String[] list() method seems to have less overhead than File[] listFiles(). So fastest should be

```<code>String[] ss = myDir.list();
File toProcess = null;
for(int i = o ; i< ss.length ; i++){
 toProcess = new File(myDir.list()[i], myDir));
 if(toProcess.isFile())break;
}
</code>```

From File.class

```<code>public File[] listFiles() {
String[] ss = list();
if (ss == null) return null;
int n = ss.length;
File[] fs = new File[n];
for (int i = 0; i < n; i++) {
    fs[i] = new File(ss[i], this);
}
return fs;
}
</code>```

Title: Find first file in directory with Java

Body:
Edit: My implementation made use of .list() as you said it wouldn't but It may hold some value anyways :)

If you look at the File implementation public String[] list() method seems to have less overhead than File[] listFiles(). So fastest should be

String[] ss = myDir.list();
File toProcess = null;
for(int i = o ; i< ss.length ; i++){
 toProcess = new File(myDir.list()[i], myDir));
 if(toProcess.isFile())break;
}

From File.class

public File[] listFiles() {
String[] ss = list();
if (ss == null) return null;
int n = ss.length;
File[] fs = new File[n];
for (int i = 0; i < n; i++) {
    fs[i] = new File(ss[i], this);
}
return fs;
}


问:
Scan dynamodb table based on filter which is not present in all object
So I'm trying to filter my dynamoDb data based on role as you can see role attribute is present in some of the objects not in all

```<code>
[
  {
    id: "7",
    email: 'test1@gmail.com',
    name: 'test1',
    age: '12',
  },
  {
    id: "8",
    email: 'test2@gmail.com',
    name: 'test2',
    age: '12',
  },
  {
    email: 'test3@gmail.com',
    name: 'test3',
    age: '12',
    test: 'test',
    role: 'ADMIN'
  },
  {
    email: 'test4@gmail.com',
    name: 'test4',
    age: '12',
    test: 'test',
    role: 'ADMIN'
  }
]
</code>```

if I try to scan with email it works but if I try to scan with role its gives me error:
Invalid FilterExpression: Attribute name is a reserved keyword; reserved keyword: role

I tried with code

```<code>let params = {
  TableName: 'tableName',
  FilterExpression: 'role =:role',
  ExpressionAttributeValues: { ':role': 'ADMIN' },
  expressionAttributeNames: { '#role': 'role' }
}
let result = await this.docClient.scan(params).promise();
</code>```

and this

```<code>let params = {
  TableName: 'tableName',
  FilterExpression: 'attribute_not_exists(role)',
  ExpressionAttributeValues: { ':role': 'ADMIN' },
  expressionAttributeNames: { '#role': 'role' }
}
let result = await this.docClient.scan(params).promise();
</code>```

both giving me same error

答:
I believe you had a typo in your first code snippet. FilterExpression: 'role =:role', should be FilterExpression: '#role =:role',.

So the following should work,

```<code>let params = {
  TableName: 'tableName',
  FilterExpression: '#role =:role',
  ExpressionAttributeValues: { ':role': 'ADMIN' },
  ExpressionAttributeNames: { '#role': 'role' }
}
let result = await this.docClient.scan(params).promise();
</code>```

Body:
So I'm trying to filter my dynamoDb data based on role as you can see role attribute is present in some of the objects not in all

[
  {
    id: "7",
    email: 'test1@gmail.com',
    name: 'test1',
    age: '12',
  },
  {
    id: "8",
    email: 'test2@gmail.com',
    name: 'test2',
    age: '12',
  },
  {
    email: 'test3@gmail.com',
    name: 'test3',
    age: '12',
    test: 'test',
    role: 'ADMIN'
  },
  {
    email: 'test4@gmail.com',
    name: 'test4',
    age: '12',
    test: 'test',
    role: 'ADMIN'
  }
]

if I try to scan with email it works but if I try to scan with role its gives me error:
Invalid FilterExpression: Attribute name is a reserved keyword; reserved keyword: role

I tried with code

let params = {
  TableName: 'tableName',
  FilterExpression: 'role =:role',
  ExpressionAttributeValues: { ':role': 'ADMIN' },
  expressionAttributeNames: { '#role': 'role' }
}
let result = await this.docClient.scan(params).promise();

and this

let params = {
  TableName: 'tableName',
  FilterExpression: 'attribute_not_exists(role)',
  ExpressionAttributeValues: { ':role': 'ADMIN' },
  expressionAttributeNames: { '#role': 'role' }
}
let result = await this.docClient.scan(params).promise();

both giving me same error

Body:
I believe you had a typo in your first code snippet. FilterExpression: 'role =:role', should be FilterExpression: '#role =:role',.

So the following should work,

let params = {
  TableName: 'tableName',
  FilterExpression: '#role =:role',
  ExpressionAttributeValues: { ':role': 'ADMIN' },
  ExpressionAttributeNames: { '#role': 'role' }
}
let result = await this.docClient.scan(params).promise();