问:
Why the "finish" button on the ObjectDataSource's Wizard is always disabled?
I'm using the ObjectDataSource Control. Below is how I have decorated the classe I'me about to use with the Datasource control.

```<code>[System.ComponentModel.DataObject]
public class LoadAndUploadPhoto
{
  [System.ComponentModel.DataObjectMethodAttribute
  (System.ComponentModel.DataObjectMethodType.Insert, true)]
  public bool SaveImage(int number)
  {
    //implement here...
  }
}
</code>```

When trying to configure the ObjectDataSource, I can see the both the LoadAndUploadPhoto and the SaveImage method on the dropdownList.

Unfortunately, the button "Finish" is disabled. Is there anything I am missing?

Thanks for helping.

答: Are you specifying a parameter source?  Did you give it a property name?</p>

Body:
I'm using the ObjectDataSource Control. Below is how I have decorated the classe I'me about to use with the Datasource control.

[System.ComponentModel.DataObject]
public class LoadAndUploadPhoto
{
  [System.ComponentModel.DataObjectMethodAttribute
  (System.ComponentModel.DataObjectMethodType.Insert, true)]
  public bool SaveImage(int number)
  {
    //implement here...
  }
}

When trying to configure the ObjectDataSource, I can see the both the LoadAndUploadPhoto and the SaveImage method on the dropdownList.

Unfortunately, the button "Finish" is disabled. Is there anything I am missing?

Thanks for helping.


来源: stackexchange

问:
RabbitMQ unacked messages not removed from queue after expiration
I have a RabbitMQ server (v.3.8.2) with a simple exchange fanout-queue binding running, with several producers and one consumer. The average delivery/ack rate is quite low, about 6 msg/s.

The queue is created at runtime by producers with the x-message-ttl parameter set at 900000 (15 minutes).

In very specific conditions (e.g. rare error situation), messages are rejected by the consumer. These messages then are shown in the unacked counter on the RabbitMQ admin web page indefinitely. They never expire or get discarded event after they timeout.

There are no specific per-message overrides in ttl parameters.

I do not need any dead letter processing as these particular messages do not require processing high reliabilty, and I can afford to lose some of them every now and then under those specific error conditions.

Exchange parameters:

```<code>name: poll
type: fanout
features: durable=true
bound queue: poll
routing key: poll
</code>```

Queue parameters:

```<code>name: poll
features: x-message-ttl=900000 durable=true
</code>```

For instance, this is what I am currently seeing in the RabbitMQ server queue admin page:

As you can see, there are 12 rejected/unack'ed messages in the queue, and they have been living there for more than a week now.

How can I have the nacked messages expire as per the ttl parameter?
Am I missing some pieces of configuration?

Here is an extract from the consumer source code:

// this code is executed during setup
...
consumer = new EventingBasicConsumer(channel);
consumer.Received += (sender, e) =>
{
    // Retrieve retry count & death list if present
    List<object> DeathList = ((e?.BasicProperties?.Headers != null) && e.BasicProperties.Headers.TryGetValue("x-death", out object obj)) ? obj as List<object> : null;
    int count = ((DeathList != null) &&
        (DeathList.Count > 0) &&
        (DeathList[0] is Dictionary<string, object> values) &&
        values.TryGetValue("count", out obj)
    ) ? Convert.ToInt32(obj) : 0;

    // call actual event method
    switch (OnRequestReceived(e.Body, count, DeathList))
    {
        default:
            channel.BasicAck(e.DeliveryTag, false);
            break;
        case OnReceivedResult.Reject:
            channel.BasicReject(e.DeliveryTag, false);
            break;
        case OnReceivedResult.Requeue:
            channel.BasicReject(e.DeliveryTag, true);
            break;
    }
};
...

// this is the actual "OnReceived" method

static OnReceivedResult OnRequestReceived(byte[] payload, int count, List<object> DeathList)
{
    OnReceivedResult retval = OnReceivedResult.Ack; // success by default

    try
    {
        object request = MessagePackSerializer.Typeless.Deserialize(payload);
        if (request is PollRequestContainer prc)
        {
            Log.Out(
                Level.Info,
                LogFamilies.PollManager,
                log_method,
                null,
                "RequestPoll message received did={0} type=={1} items#={2}", prc.DeviceId, prc.Type, prc.Items == null ? 0 : prc.Items.Length
            );
            if (!RequestManager.RequestPoll(prc.DeviceId, prc.Type, prc.Items)) retval = OnReceivedResult.Reject;
        }
        else if (request is PollUpdateContainer puc)
        {
            Log.Out(Level.Info, LogFamilies.PollManager, log_method, null, "RequestUpdates message received dids#={0} type=={1}", puc.DeviceIds.Length, puc.Type);
            if (!RequestManager.RequestUpdates(puc.DeviceIds, puc.Type)) retval = OnReceivedResult.Reject;
        }
        else Log.Out(Level.Error, LogFamilies.PollManager, log_method, null, "Message payload deserialization error length={0} count={1}", payload.Length, count);
    }
    catch (Exception e)
    {
        Log.Out(Level.Error, LogFamilies.PollManager, log_method, null, e, "Exception dequeueing message. Payload length={0} count={1}", payload.Length, count);
    }

    // message is rejected only if RequestUpdates() or RequestPoll() return false
    // message is always acked if an exception occurs within the try-catch or if a deserialization type check error occurs
    return retval;
}

```

答:
This state occurs when the Consumer does not ack or reject both after receiving the message.

In the unacked state, the message does not expire.

After receiving the message, you must ack or reject it.

This issue isn't a problem that doesn't expire, problem is you don't ack or reject the message.

ContentLicense: CC BY-SA 4.0

Body:
I have a RabbitMQ server (v.3.8.2) with a simple exchange fanout-queue binding running, with several producers and one consumer. The average delivery/ack rate is quite low, about 6 msg/s.

The queue is created at runtime by producers with the x-message-ttl parameter set at 900000 (15 minutes).

In very specific conditions (e.g. rare error situation), messages are rejected by the consumer. These messages then are shown in the unacked counter on the RabbitMQ admin web page indefinitely. They never expire or get discarded event after they timeout.

There are no specific per-message overrides in ttl parameters.

I do not need any dead letter processing as these particular messages do not require processing high reliabilty, and I can afford to lose some of them every now and then under those specific error conditions.

Exchange parameters:

name: poll
type: fanout
features: durable=true
bound queue: poll
routing key: poll

Queue parameters:

name: poll
features: x-message-ttl=900000 durable=true

For instance, this is what I am currently seeing in the RabbitMQ server queue admin page:

As you can see, there are 12 rejected/unack'ed messages in the queue, and they have been living there for more than a week now.

How can I have the nacked messages expire as per the ttl parameter?
Am I missing some pieces of configuration?

Here is an extract from the consumer source code:

// this code is executed during setup
...
consumer = new EventingBasicConsumer(channel);
consumer.Received += (sender, e) =>
{
    // Retrieve retry count & death list if present
    List<object> DeathList = ((e?.BasicProperties?.Headers != null) && e.BasicProperties.Headers.TryGetValue("x-death", out object obj)) ? obj as List<object> : null;
    int count = ((DeathList != null) &&
        (DeathList.Count > 0) &&
        (DeathList[0] is Dictionary<string, object> values) &&
        values.TryGetValue("count", out obj)
    ) ? Convert.ToInt32(obj) : 0;

    // call actual event method
    switch (OnRequestReceived(e.Body, count, DeathList))
    {
        default:
            channel.BasicAck(e.DeliveryTag, false);
            break;
        case OnReceivedResult.Reject:
            channel.BasicReject(e.DeliveryTag, false);
            break;
        case OnReceivedResult.Requeue:
            channel.BasicReject(e.DeliveryTag, true);
            break;
    }
};
...

// this is the actual "OnReceived" method

static OnReceivedResult OnRequestReceived(byte[] payload, int count, List<object> DeathList)
{
    OnReceivedResult retval = OnReceivedResult.Ack; // success by default

    try
    {
        object request = MessagePackSerializer.Typeless.Deserialize(payload);
        if (request is PollRequestContainer prc)
        {
            Log.Out(
                Level.Info,
                LogFamilies.PollManager,
                log_method,
                null,
                "RequestPoll message received did={0} type=={1} items#={2}", prc.DeviceId, prc.Type, prc.Items == null ? 0 : prc.Items.Length
            );
            if (!RequestManager.RequestPoll(prc.DeviceId, prc.Type, prc.Items)) retval = OnReceivedResult.Reject;
        }
        else if (request is PollUpdateContainer puc)
        {
            Log.Out(Level.Info, LogFamilies.PollManager, log_method, null, "RequestUpdates message received dids#={0} type=={1}", puc.DeviceIds.Length, puc.Type);
            if (!RequestManager.RequestUpdates(puc.DeviceIds, puc.Type)) retval = OnReceivedResult.Reject;
        }
        else Log.Out(Level.Error, LogFamilies.PollManager, log_method, null, "Message payload deserialization error length={0} count={1}", payload.Length, count);
    }
    catch (Exception e)
    {
        Log.Out(Level.Error, LogFamilies.PollManager, log_method, null, e, "Exception dequeueing message. Payload length={0} count={1}", payload.Length, count);
    }

    // message is rejected only if RequestUpdates() or RequestPoll() return false
    // message is always acked if an exception occurs within the try-catch or if a deserialization type check error occurs
    return retval;
}


问:
Open Browser with URL WPF
How to open an external browser by hyperlink, in a browser it would be target='_top'.

What is the code in a WPF netcore 3.1 app?

Use CommandParameter

```<code><TextBlock>
    <Hyperlink CommandParameter="{Binding ExternalURL}"
               Command="{Binding NavHomeViewCommand}" >Open in Browser ...
    </Hyperlink>
</TextBlock>
</code>```

Change DelegateCommand to use object parameter (using the prismlibrary mvvm pattern)

```<code>navHomeViewCommand = new DelegateCommand<object>(NavHomeView);
</code>```

Command Properties:

```<code>public string ExternalURL{ get => "https://www.google.com/";}
private readonly ICommand navHomeViewCommand;
public ICommand NavHomeViewCommand
{
    get { return navHomeViewCommand; }
}
</code>```

Open a browser

```<code>private void NavHomeView(object ID)
{
    if(obj is string destinationurl)
        System.Diagnostics.Process.Start("https://google.com");  //???????
}
</code>```

An exception is thrown 'unknown executable'.

答:
Solution that opens Windows OS level default Browser with the specified URL. Recommended via WPF Github issue 2566:

```<code>        var destinationurl = "https://www.bing.com/";
        var sInfo = new System.Diagnostics.ProcessStartInfo(destinationurl)
        {
            UseShellExecute = true,
        };
        System.Diagnostics.Process.Start(sInfo);
</code>```

OLD:
The solution that opens a silent CMD prompt and opens the Windows OS default browser:

```<code>    private void NavHomeView(object ID)
    {
        //return;
        if (IDis string destinationurl)
        {
            var link = new Uri(destinationurl);
            var psi = new ProcessStartInfo
            {
                FileName = "cmd",
                WindowStyle = ProcessWindowStyle.Hidden,
                UseShellExecute = false,
                CreateNoWindow = true,
                Arguments = $"/c start {link.AbsoluteUri}"
            };
            Process.Start(psi);
        ...
</code>```

but if your intent is to package the app using the MSIX packaging project type and put it in the Windows Store, then you'll fail certification for using CMD.EXE.

Title: Open Browser with URL WPF

Body:
How to open an external browser by hyperlink, in a browser it would be target='_top'.

What is the code in a WPF netcore 3.1 app?

Use CommandParameter

<TextBlock>
    <Hyperlink CommandParameter="{Binding ExternalURL}"
               Command="{Binding NavHomeViewCommand}" >Open in Browser ...
    </Hyperlink>
</TextBlock>

Change DelegateCommand to use object parameter (using the prismlibrary mvvm pattern)

navHomeViewCommand = new DelegateCommand<object>(NavHomeView);

Command Properties:

public string ExternalURL{ get => "https://www.google.com/";}
private readonly ICommand navHomeViewCommand;
public ICommand NavHomeViewCommand
{
    get { return navHomeViewCommand; }
}

Open a browser

private void NavHomeView(object ID)
{
    if(obj is string destinationurl)
        System.Diagnostics.Process.Start("https://google.com");  //???????
}

An exception is thrown 'unknown executable'.

Body:
Solution that opens Windows OS level default Browser with the specified URL. Recommended via WPF Github issue 2566:

        var destinationurl = "https://www.bing.com/";
        var sInfo = new System.Diagnostics.ProcessStartInfo(destinationurl)
        {
            UseShellExecute = true,
        };
        System.Diagnostics.Process.Start(sInfo);

OLD:
The solution that opens a silent CMD prompt and opens the Windows OS default browser:

    private void NavHomeView(object ID)
    {
        //return;
        if (IDis string destinationurl)
        {
            var link = new Uri(destinationurl);
            var psi = new ProcessStartInfo
            {
                FileName = "cmd",
                WindowStyle = ProcessWindowStyle.Hidden,
                UseShellExecute = false,
                CreateNoWindow = true,
                Arguments = $"/c start {link.AbsoluteUri}"
            };
            Process.Start(psi);
        ...

but if your intent is to package the app using the MSIX packaging project type and put it in the Windows Store, then you'll fail certification for using CMD.EXE.


问:
How to split the column by identifier (|) and get the first item and group by?
I have a table of category and has an attribute of

This tag_id is the sequence or pattern on what its parent or child is.

Sample:

```<code>CREATE TABLE category (
    id int,
    parent_id int,
    code varchar(255),
    name varchar(255).
    tag_id varchar(255)
);

INSERT INTO category (id, parent_id, code, name, tag_id)
VALUES
    (1,null,0,'category 1','|1|'),
    (2,null,1,'category 2','|2|'),
    (3,null,2,'category 3','|3|'),
    (4,null,3,'category 4','|4|'),
    (5,4,4,'category 5','|4|5|'),
    (6,5,5,'category 6','|4|5|6|');
</code>```

As you can see, you may determine if the category is parent, if the first value inside the tag_id is its id.

I want to group by this category by same first parent id

Reason: I'm joining this table to another table wherein there's an amount column and I want to sum and group by using the first parent id.

For example I have a sales table wherein it has a relationship with product table. And this product table has relationship with category table.

In sales table it has column there total_amount, and product_id. This product_id is linked to the id of the product table. And this product table has a category_id column that is linked to the id of the category table.

The main goal is to get the SUM OF TOTAL_AMOUNT that a first level category was sold. I just need how to split this | character and get only the first level category

Thank you!

答:
If you need the first distinct values of tag no need to group also</p>

```<code>    Select distinct id as tag_id from (SELECT SUBSTRING(s.tag_id,3,CHARINDEX('|',S.tag_id,3)-3) id from category s) temp
</code>```

Body:
I have a table of category and has an attribute of

This tag_id is the sequence or pattern on what its parent or child is.

Sample:

CREATE TABLE category (
    id int,
    parent_id int,
    code varchar(255),
    name varchar(255).
    tag_id varchar(255)
);

INSERT INTO category (id, parent_id, code, name, tag_id)
VALUES
    (1,null,0,'category 1','|1|'),
    (2,null,1,'category 2','|2|'),
    (3,null,2,'category 3','|3|'),
    (4,null,3,'category 4','|4|'),
    (5,4,4,'category 5','|4|5|'),
    (6,5,5,'category 6','|4|5|6|');

As you can see, you may determine if the category is parent, if the first value inside the tag_id is its id.

I want to group by this category by same first parent id

Reason: I'm joining this table to another table wherein there's an amount column and I want to sum and group by using the first parent id.

For example I have a sales table wherein it has a relationship with product table. And this product table has relationship with category table.

In sales table it has column there total_amount, and product_id. This product_id is linked to the id of the product table. And this product table has a category_id column that is linked to the id of the category table.

The main goal is to get the SUM OF TOTAL_AMOUNT that a first level category was sold. I just need how to split this | character and get only the first level category

Thank you!

Body:
If you need the first distinct values of tag no need to group also

    Select distinct id as tag_id from (SELECT SUBSTRING(s.tag_id,3,CHARINDEX('|',S.tag_id,3)-3) id from category s) temp


问:
How to add a UIView at top of whole app that pushes every screen design to downward
I am tring to add a UIView at top of the app when internet is not available. I am using this code that works fine too.

```<code>let currentWindow: UIWindow? = UIApplication.shared.keyWindow
self.myView = UIView(frame: CGRect(x: 0, y: 0, width: currentWindow?.frame.size.width ?? 620 , height: newSafeArea.bottom + 35))
currentWindow?.addSubview(self.myView)
</code>```

But the main problem with this code it, I want to add it also the screen should push downward as per images below.

P.S: This will be added on Window object and it needs to stay on every screen.

Before

After

答: There are few workarounds for that. You can simply resize the constant of the top constraint of the view from 0 to desired height of alert or vice versa upon network changes. Then add the alert in the App Delegate.</p>

Body:
I am tring to add a UIView at top of the app when internet is not available. I am using this code that works fine too.

let currentWindow: UIWindow? = UIApplication.shared.keyWindow
self.myView = UIView(frame: CGRect(x: 0, y: 0, width: currentWindow?.frame.size.width ?? 620 , height: newSafeArea.bottom + 35))
currentWindow?.addSubview(self.myView)

But the main problem with this code it, I want to add it also the screen should push downward as per images below.

P.S: This will be added on Window object and it needs to stay on every screen.

Before

After


问:
ASP.NET C# How to retrieve data from SQL Server and convert multi-row data into one row seperated by comma?
I have this table in SQL Server:

```<code>Colors
-----------
Grey
Black
Pink.Red
</code>```

I wish to retrieve data from SQL Server and display in a label.

Expected output:

```<code>Grey,Black,Pink.Red
</code>```

The code I have tried:

```<code>SqlCommand cmd2 = new SqlCommand("SELECT Colors FROM ROCK", con);
cmd.Connection.Open();
pdl.Text = cmd.ExecuteScalar().ToString(); // assign to label
cmd.Connection.Close();
</code>```

Does anyone have any ideas?

答:
Please use the below code in your .cs page</p>

```<code>string color="";
for (int i = 0; i < Colors.Items.Count; i++)
        {
            if (Colors.Items[i].Selected == true)
            {
                color += Colors.Items[i].Text + ",";
            }
        }
        color = color.TrimEnd(',');
        pd1.text=color;
</code>```

Body:
I have this table in SQL Server:

Colors
-----------
Grey
Black
Pink.Red

I wish to retrieve data from SQL Server and display in a label.

Expected output:

Grey,Black,Pink.Red

The code I have tried:

SqlCommand cmd2 = new SqlCommand("SELECT Colors FROM ROCK", con);
cmd.Connection.Open();
pdl.Text = cmd.ExecuteScalar().ToString(); // assign to label
cmd.Connection.Close();

Does anyone have any ideas?

Body:
Please use the below code in your .cs page

string color="";
for (int i = 0; i < Colors.Items.Count; i++)
        {
            if (Colors.Items[i].Selected == true)
            {
                color += Colors.Items[i].Text + ",";
            }
        }
        color = color.TrimEnd(',');
        pd1.text=color;


问:
How to list names of all pods serving traffic behind a service in kubernetes
I want to list names of all pods which are actually serving traffic behind a kubernetes service.My question is how to achieve this by executing a single kubectl command.</p>

答:
This command worked </p>

```<code>kubectl get ep servicename -o=jsonpath='{.subsets[*].addresses[*].ip}' | tr ' ' '\n' | xargs -I % kubectl get pods -o=name --field-selector=status.podIP=%
</code>```

Body:
This command worked

kubectl get ep servicename -o=jsonpath='{.subsets[*].addresses[*].ip}' | tr ' ' '\n' | xargs -I % kubectl get pods -o=name --field-selector=status.podIP=%


问:
EF4 conditional mapping over a relationship
I'm currently using conditional mappings in EF4 to filter out any records where their IsActive column is false. This works as intended, but I'm running into an issue when navigating relationships.

As an example, I have a one-to-many relationship where a Store can have many Inventory records. A Store can be marked IsActive as can the Inventory records that belong to it. Querying directly for records in those tables works as intended (only active records are returned), but I am also able to retrieve Inventory records where the associated store is not active. This allows the inactive Store to be accessed and gives me no way of detecting whether the store is active.

Prior to switching over to using conditional mapping, we were using queries similar to the following:

```<code>Inventories.Where(i => i.IsActive && i.Store.IsActive && i.Product.IsActive && i.Product.Id == productId);
</code>```

I was hoping we could simplify that query to this:

```<code>Inventories.Where(i => i.Product.Id == productId);
</code>```

This doesn't work for me though, as I no longer have any way of knowing whether the Store or Product are active (as I can't use conditional mapping on IsActive while still mapping that column).

Is there any way of replicating that query while taking advantage of conditional mapping in EF4? Am I forced to leave conditional mapping out of this and hope that all queries make sure to check all relevant IsActive fields?

答:
While the other answer may work for some, we decided to map the EF EntitySet to a view instead. The view joins to appropriate tables and checks their appropriate IsActive fields. The resulting portion of our EDMX looks similar to the following:

```<code><EntitySet Name="Inventory" EntityType="Model.Store.Inventory" store:Type="Views" store:Schema="dbo" store:Name="Inventory">
    <DefiningQuery>SELECT
  [ActiveInventory].[InventoryId] AS [InventoryId],
  {Other columns being selected}
  FROM [dbo].[ActiveInventory] AS [ActiveInventory]</DefiningQuery>
</EntitySet>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm currently using conditional mappings in EF4 to filter out any records where their IsActive column is false. This works as intended, but I'm running into an issue when navigating relationships.

As an example, I have a one-to-many relationship where a Store can have many Inventory records. A Store can be marked IsActive as can the Inventory records that belong to it. Querying directly for records in those tables works as intended (only active records are returned), but I am also able to retrieve Inventory records where the associated store is not active. This allows the inactive Store to be accessed and gives me no way of detecting whether the store is active.

Prior to switching over to using conditional mapping, we were using queries similar to the following:

Inventories.Where(i => i.IsActive && i.Store.IsActive && i.Product.IsActive && i.Product.Id == productId);

I was hoping we could simplify that query to this:

Inventories.Where(i => i.Product.Id == productId);

This doesn't work for me though, as I no longer have any way of knowing whether the Store or Product are active (as I can't use conditional mapping on IsActive while still mapping that column).

Is there any way of replicating that query while taking advantage of conditional mapping in EF4? Am I forced to leave conditional mapping out of this and hope that all queries make sure to check all relevant IsActive fields?

Body:
While the other answer may work for some, we decided to map the EF EntitySet to a view instead. The view joins to appropriate tables and checks their appropriate IsActive fields. The resulting portion of our EDMX looks similar to the following:

<EntitySet Name="Inventory" EntityType="Model.Store.Inventory" store:Type="Views" store:Schema="dbo" store:Name="Inventory">
    <DefiningQuery>SELECT
  [ActiveInventory].[InventoryId] AS [InventoryId],
  {Other columns being selected}
  FROM [dbo].[ActiveInventory] AS [ActiveInventory]</DefiningQuery>
</EntitySet>

ContentLicense: CC BY-SA 3.0


问:
hikari/jdbc connections are waiting until timeout to report invalid/lp or account is locked errors
I am using hikaricp with jdbc drivers for oracle. When I change the l/p or when I lock the account on the db, the connections are waiting the timeout value (of 10 minutes) before failing when attempting to add a connection. Is there a way to have them fail right away rather than wait till the timeout?

Here are my settings.

```<code><bean id="myDataSource" class="com.zaxxer.hikari.HikariDataSource">
   <constructor-arg index="0">
      <bean parent="baseHikariConfig"
            p:poolName="hikariCP-readOnlyPool"
            p:jdbcUrl="#{jdbcUrl}"
            p:username="#{jdbcUsername}"
            p:password="#{jdbcPassword}"
            p:maximumPoolSize="#{JdbcPoolSize}"
            />
   </constructor-arg>
</bean>

<bean id="baseHikariConfig" class="com.zaxxer.hikari.HikariConfig" abstract="true"
         p:poolName="abstractSpringHikariCP"
         p:driverClassName="oracle.jdbc.driver.OracleDriver"
         p:connectionTimeout="600000"
         p:idleTimeout="600000"
         p:maxLifetime="1800000"
         p:leakDetectionThreshold="3600000"
         p:initializationFailFast="true"
         p:minimumIdle="0"
         p:maximumPoolSize="#{ConnectionPoolSize}"
         p:registerMbeans="true"
         >
   <property name="dataSourceProperties">
      <props>
         <prop key="oracle.jdbc.ReadTimeout">
            #{queryTimeout}
         </prop>
         <prop key="defaultRowPrefetch">1000</prop>
         <prop key="oracle.jdbc.StreamBufferSize">65536</prop>
         <prop key="v$session.program">Tomcat</prop>
         <prop key="oracle.jdbc.RetainV9LongBindBehavior">true</prop>
      </props>
   </property>
</bean>
</code>```

Here is the stack trace I am seeing when an account is locked.

```<code>org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Timeout after 600001ms of waiting for a connection.
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:615)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:680)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:712)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:722)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:772)
    at org.springframework.jdbc.core.JdbcTemplate.queryForList(JdbcTemplate.java:834)
    [..snip.. my code..]
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLException: Timeout after 600001ms of waiting for a connection.
    at com.zaxxer.hikari.pool.BaseHikariPool.getConnection(BaseHikariPool.java:209)
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:91)
    at sun.reflect.GeneratedMethodAccessor41.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.bull.javamelody.JdbcWrapper$3.invoke(JdbcWrapper.java:765)
    at net.bull.javamelody.JdbcWrapper$DelegatingInvocationHandler.invoke(JdbcWrapper.java:285)
    at com.sun.proxy.$Proxy45.getConnection(Unknown Source)
    at net.sf.log4jdbc.sql.jdbcapi.DataSourceSpy.getConnection(DataSourceSpy.java:149)
    at sun.reflect.GeneratedMethodAccessor41.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.bull.javamelody.JdbcWrapper$3.invoke(JdbcWrapper.java:765)
    at net.bull.javamelody.JdbcWrapper$DelegatingInvocationHandler.invoke(JdbcWrapper.java:285)
    at com.sun.proxy.$Proxy47.getConnection(Unknown Source)
    at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111)
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77)
    ... 67 more
Caused by: java.sql.SQLException: ORA-28000: the account is locked
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:461)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:394)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:386)
    at oracle.jdbc.driver.T4CTTIfun.processError(T4CTTIfun.java:1121)
    at oracle.jdbc.driver.T4CTTIoauthenticate.processError(T4CTTIoauthenticate.java:502)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:541)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:264)
    at oracle.jdbc.driver.T4CTTIoauthenticate.doOAUTH(T4CTTIoauthenticate.java:435)
    at oracle.jdbc.driver.T4CTTIoauthenticate.doOAUTH(T4CTTIoauthenticate.java:1020)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:707)
    at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:755)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:38)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:599)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:57)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:63)
    at com.zaxxer.hikari.pool.BaseHikariPool.addConnection(BaseHikariPool.java:376)
    at com.zaxxer.hikari.pool.HikariPool.lambda$addBagItem$2(HikariPool.java:75)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    ... 1 more
</code>```

答:
Your oracle account is locked.

alter user <user_name> account unlock;

Body:
I am using hikaricp with jdbc drivers for oracle. When I change the l/p or when I lock the account on the db, the connections are waiting the timeout value (of 10 minutes) before failing when attempting to add a connection. Is there a way to have them fail right away rather than wait till the timeout?

Here are my settings.

<bean id="myDataSource" class="com.zaxxer.hikari.HikariDataSource">
   <constructor-arg index="0">
      <bean parent="baseHikariConfig"
            p:poolName="hikariCP-readOnlyPool"
            p:jdbcUrl="#{jdbcUrl}"
            p:username="#{jdbcUsername}"
            p:password="#{jdbcPassword}"
            p:maximumPoolSize="#{JdbcPoolSize}"
            />
   </constructor-arg>
</bean>

<bean id="baseHikariConfig" class="com.zaxxer.hikari.HikariConfig" abstract="true"
         p:poolName="abstractSpringHikariCP"
         p:driverClassName="oracle.jdbc.driver.OracleDriver"
         p:connectionTimeout="600000"
         p:idleTimeout="600000"
         p:maxLifetime="1800000"
         p:leakDetectionThreshold="3600000"
         p:initializationFailFast="true"
         p:minimumIdle="0"
         p:maximumPoolSize="#{ConnectionPoolSize}"
         p:registerMbeans="true"
         >
   <property name="dataSourceProperties">
      <props>
         <prop key="oracle.jdbc.ReadTimeout">
            #{queryTimeout}
         </prop>
         <prop key="defaultRowPrefetch">1000</prop>
         <prop key="oracle.jdbc.StreamBufferSize">65536</prop>
         <prop key="v$session.program">Tomcat</prop>
         <prop key="oracle.jdbc.RetainV9LongBindBehavior">true</prop>
      </props>
   </property>
</bean>

Here is the stack trace I am seeing when an account is locked.

org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Timeout after 600001ms of waiting for a connection.
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:615)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:680)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:712)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:722)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:772)
    at org.springframework.jdbc.core.JdbcTemplate.queryForList(JdbcTemplate.java:834)
    [..snip.. my code..]
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLException: Timeout after 600001ms of waiting for a connection.
    at com.zaxxer.hikari.pool.BaseHikariPool.getConnection(BaseHikariPool.java:209)
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:91)
    at sun.reflect.GeneratedMethodAccessor41.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.bull.javamelody.JdbcWrapper$3.invoke(JdbcWrapper.java:765)
    at net.bull.javamelody.JdbcWrapper$DelegatingInvocationHandler.invoke(JdbcWrapper.java:285)
    at com.sun.proxy.$Proxy45.getConnection(Unknown Source)
    at net.sf.log4jdbc.sql.jdbcapi.DataSourceSpy.getConnection(DataSourceSpy.java:149)
    at sun.reflect.GeneratedMethodAccessor41.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.bull.javamelody.JdbcWrapper$3.invoke(JdbcWrapper.java:765)
    at net.bull.javamelody.JdbcWrapper$DelegatingInvocationHandler.invoke(JdbcWrapper.java:285)
    at com.sun.proxy.$Proxy47.getConnection(Unknown Source)
    at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111)
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77)
    ... 67 more
Caused by: java.sql.SQLException: ORA-28000: the account is locked
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:461)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:394)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:386)
    at oracle.jdbc.driver.T4CTTIfun.processError(T4CTTIfun.java:1121)
    at oracle.jdbc.driver.T4CTTIoauthenticate.processError(T4CTTIoauthenticate.java:502)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:541)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:264)
    at oracle.jdbc.driver.T4CTTIoauthenticate.doOAUTH(T4CTTIoauthenticate.java:435)
    at oracle.jdbc.driver.T4CTTIoauthenticate.doOAUTH(T4CTTIoauthenticate.java:1020)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:707)
    at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:755)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:38)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:599)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:57)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:63)
    at com.zaxxer.hikari.pool.BaseHikariPool.addConnection(BaseHikariPool.java:376)
    at com.zaxxer.hikari.pool.HikariPool.lambda$addBagItem$2(HikariPool.java:75)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    ... 1 more


问:
I am trying to make a chart using google-chart directive.But my chart is not displaying
I am trying to make pieCharts, Barcharts using angular google charts .
I have made a colChartObject and assign data to it and several other options like size,colors but nothing is displaying on the browser.I tried the same using my custom directive too but had the same problem .
Can anyone please let me know the problem in my code??

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-google-chart/1.0.0-beta.1/ng-google-chart.min.js" type="text/javascript"></script>

</head>
<body ng-app = "ngapp">
    <div ng-controller="ChartController">
        <div google-chart chart="colChartObject"></div>
     </div>
</body>
</html>
</code>```

JS

```<code>var app = angular.module('ngapp',[]);
app.controller('ChartController',function($scope){
    $scope.colChartObject={};
    $scope.colChartObject.type = "PieChart"; //setting chart type
    $scope.colChartObject.displayed = true;

    $scope.Colors = [
        ['#CB7472', '#A895BF', '#F8A769', '#A7514F', '#C0504D', '#9BBB59'],
        ['#7399C9', '#A8C472', '#8AC8D9', '#426690', '#4BACC6', '#8064A2'],
        ['#4F81BD', '#C0504D', '#9BBB59', '#A895BF', '#F8A769', '#A7514F'],
        ['#F79646', '#4BACC6', '#8064A2', '#A8C472', '#8AC8D9', '#426690']
    ];

   // $scope.colChartObject.data = $scope.data; //setting chart data
    //setting chart options
    $scope.colChartObject.options = {
        title: 'nothing special',              //chart title
        isStacked: 'true',        //chart is stacked or not
        titleTextStyle: { color: '#000000',
        fontName: 'Open Sans', fontSize: 16,
                     bold: true, italic: false },  //title style
        height: 250,
        colors: $scope.Colors[Math.floor(Math.random() * $scope.Colors.length)]  //colors
    };

    $scope.colChartObject.data= {
        cols: [
            {
                id: "month",
                label: "Month",
                type: "string"
            },
            {
                id: "Tables-id",
                label: "Tables",
                type: "number"
            },
            {
                id: "Chairs-id",
                label: "Chairs",
                type: "number"
            },
            {
                id: "Bed-id",
                label: "Bed",
                type: "number"
            },
            {
                id: "Desk-id",
                label: "Desk",
                type: "number"
            }
        ],
        rows: [
            {
                c: [
                    {
                        v: "January"
                    },
                    {
                        v: 19,          //value required to plot chart
                        f: "19 Tables"  //description which is shown on mouse hover
                    },
                    {
                        v: 12,
                        f: "12 Chairs"
                    },
                    {
                        v: 7,
                        f: "7 Beds"
                    },
                    {
                        v: 4,
                        f: "4 Desks"
                    }
                ]
            },
            {
                c: [
                    {
                        v: "February"
                    },
                    {
                        v: 13
                    },
                    {
                        v: 1,
                        f: "only 1unit"
                    },
                    {
                        v: 12
                    },
                    {
                        v: 2
                    }
                ]
            },
            {
                c: [
                    {
                        v: "March"
                    },
                    {
                        v: 24
                    },
                    {
                        v: 5
                    },
                    {
                        v: 11
                    },
                    {
                        v: 6
                    }
                ]
            }
        ]
    }
});
</code>```

答:
You forgot to declare the module of "google-chart" as a dependency of your module "ngapp".

You have to change

```<code>  var app = angular.module('ngapp', []);
</code>```

to

```<code>  var app = angular.module('ngapp', ['googlechart']);
</code>```

Body:
I am trying to make pieCharts, Barcharts using angular google charts .
I have made a colChartObject and assign data to it and several other options like size,colors but nothing is displaying on the browser.I tried the same using my custom directive too but had the same problem .
Can anyone please let me know the problem in my code??

<!DOCTYPE html>

    <title></title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

JS

var app = angular.module('ngapp',[]);
app.controller('ChartController',function($scope){
    $scope.colChartObject={};
    $scope.colChartObject.type = "PieChart"; //setting chart type
    $scope.colChartObject.displayed = true;

    $scope.Colors = [
        ['#CB7472', '#A895BF', '#F8A769', '#A7514F', '#C0504D', '#9BBB59'],
        ['#7399C9', '#A8C472', '#8AC8D9', '#426690', '#4BACC6', '#8064A2'],
        ['#4F81BD', '#C0504D', '#9BBB59', '#A895BF', '#F8A769', '#A7514F'],
        ['#F79646', '#4BACC6', '#8064A2', '#A8C472', '#8AC8D9', '#426690']
    ];

   // $scope.colChartObject.data = $scope.data; //setting chart data
    //setting chart options
    $scope.colChartObject.options = {
        title: 'nothing special',              //chart title
        isStacked: 'true',        //chart is stacked or not
        titleTextStyle: { color: '#000000',
        fontName: 'Open Sans', fontSize: 16,
                     bold: true, italic: false },  //title style
        height: 250,
        colors: $scope.Colors[Math.floor(Math.random() * $scope.Colors.length)]  //colors
    };

    $scope.colChartObject.data= {
        cols: [
            {
                id: "month",
                label: "Month",
                type: "string"
            },
            {
                id: "Tables-id",
                label: "Tables",
                type: "number"
            },
            {
                id: "Chairs-id",
                label: "Chairs",
                type: "number"
            },
            {
                id: "Bed-id",
                label: "Bed",
                type: "number"
            },
            {
                id: "Desk-id",
                label: "Desk",
                type: "number"
            }
        ],
        rows: [
            {
                c: [
                    {
                        v: "January"
                    },
                    {
                        v: 19,          //value required to plot chart
                        f: "19 Tables"  //description which is shown on mouse hover
                    },
                    {
                        v: 12,
                        f: "12 Chairs"
                    },
                    {
                        v: 7,
                        f: "7 Beds"
                    },
                    {
                        v: 4,
                        f: "4 Desks"
                    }
                ]
            },
            {
                c: [
                    {
                        v: "February"
                    },
                    {
                        v: 13
                    },
                    {
                        v: 1,
                        f: "only 1unit"
                    },
                    {
                        v: 12
                    },
                    {
                        v: 2
                    }
                ]
            },
            {
                c: [
                    {
                        v: "March"
                    },
                    {
                        v: 24
                    },
                    {
                        v: 5
                    },
                    {
                        v: 11
                    },
                    {
                        v: 6
                    }
                ]
            }
        ]
    }
});

Body:
You forgot to declare the module of "google-chart" as a dependency of your module "ngapp".

You have to change

  var app = angular.module('ngapp', []);

to

  var app = angular.module('ngapp', ['googlechart']);


问:
Map result of 2 groupings to 2-dimensional object in rails
I have a model that I'd like to group on 2 columns:

```<code>ModelName.group(:location_id, :referrer).count
</code>```

The result of this is an object that is difficult to deal with:

```<code>{
    [ '1', 'friend' ] => 100,
    [ '1', 'family' ] => 23,
    [ '2', 'friend' ] => 43,
    [ '2', 'family' ] => 65
}
</code>```

I'd like to map these values to an easier to sue structure but I can't get it working.  Ideally it'd be something like:

```<code>{
    '1' => {
        'friend' => 100
        'family' => 23
    },
    '2' => {
        'friend' => 100
        'family' => 23
    }
}
</code>```

How can I accomplish this (preferably it would work with a 3rd dimension as well)?

答:
Given:

```<code>original = {
  [ '1', 'friend' ] => 100,
  [ '1', 'family' ] => 23,
  [ '2', 'friend' ] => 43,
  [ '2', 'family' ] => 65
}
</code>```

You can get there nicely by combining an autovivifying hash:

```<code>desired = Hash.new { |h, k| h[k] = { } }
</code>```

and some nested destructing:

```<code>original.each_with_object(desired) do |((loc, ref), n), h|
  h[loc][ref] = n
end
desired
# {"1"=>{"friend"=>100, "family"=>23}, "2"=>{"friend"=>43, "family"=>65}}
</code>```

Or, if you don't like predeclaring desired:

```<code>desired = original.each_with_object(Hash.new { |h, k| h[k] = { } }) do |((loc, ref), n), h|
  h[loc][ref] = n
end
# {"1"=>{"friend"=>100, "family"=>23}, "2"=>{"friend"=>43, "family"=>65}}
</code>```

or perhaps:

```<code>reorg   = ->(((loc, ref), n), h) { h[loc][ref] = n }
desired = original.each_with_object(Hash.new { |h, k| h[k] = { } }, &reorg)
# {"1"=>{"friend"=>100, "family"=>23}, "2"=>{"friend"=>43, "family"=>65}}
</code>```

Body:
I have a model that I'd like to group on 2 columns:

ModelName.group(:location_id, :referrer).count

The result of this is an object that is difficult to deal with:

{
    [ '1', 'friend' ] => 100,
    [ '1', 'family' ] => 23,
    [ '2', 'friend' ] => 43,
    [ '2', 'family' ] => 65
}

I'd like to map these values to an easier to sue structure but I can't get it working.  Ideally it'd be something like:

{
    '1' => {
        'friend' => 100
        'family' => 23
    },
    '2' => {
        'friend' => 100
        'family' => 23
    }
}

How can I accomplish this (preferably it would work with a 3rd dimension as well)?

Body:
Given:

original = {
  [ '1', 'friend' ] => 100,
  [ '1', 'family' ] => 23,
  [ '2', 'friend' ] => 43,
  [ '2', 'family' ] => 65
}

You can get there nicely by combining an autovivifying hash:

desired = Hash.new { |h, k| h[k] = { } }

and some nested destructing:

original.each_with_object(desired) do |((loc, ref), n), h|
  h[loc][ref] = n
end
desired
# {"1"=>{"friend"=>100, "family"=>23}, "2"=>{"friend"=>43, "family"=>65}}

Or, if you don't like predeclaring desired:

desired = original.each_with_object(Hash.new { |h, k| h[k] = { } }) do |((loc, ref), n), h|
  h[loc][ref] = n
end
# {"1"=>{"friend"=>100, "family"=>23}, "2"=>{"friend"=>43, "family"=>65}}

or perhaps:

reorg   = ->(((loc, ref), n), h) { h[loc][ref] = n }
desired = original.each_with_object(Hash.new { |h, k| h[k] = { } }, &reorg)
# {"1"=>{"friend"=>100, "family"=>23}, "2"=>{"friend"=>43, "family"=>65}}


问:
Is a finally block without a catch block a java anti-pattern?
I just had a pretty painful troubleshooting experience in troubleshooting some code that looked like this:

```<code>try {
   doSomeStuff()
   doMore()
} finally {
   doSomeOtherStuff()
}
</code>```

The problem was difficult to troubleshoot because doSomeStuff() threw an exception, which in turn caused doSomeOtherStuff() to also throw an exception.  The second exception (thrown by the finally block) was thrown up to my code, but it did not have a handle on the first exception (thrown from doSomeStuff()), which was the real root-cause of the problem.

If the code had said this instead, the problem would have been readily apparent:

```<code>try {
    doSomeStuff()
    doMore()
} catch (Exception e) {
    log.error(e);
} finally {
   doSomeOtherStuff()
}
</code>```

So, my question is this:

Is a finally block used without any catch block a well-known java anti-pattern?  (It certainly seems to be a not-readily-apparent subclass of the obviously well-known anti-pattern "Don't gobble exceptions!")

答:
In my opinion, it's more the case that finally with a catch indicate some kind of problem. The resource idiom is very simple:

```<code>acquire
try {
    use
} finally {
    release
}
</code>```

In Java you can have an exception from pretty much anywhere. Often the acquire throws a checked exception, the sensible way to handle that is to put a catch around the how lot. Don't try some hideous null checking.

If you were going to be really anal you should note that there are implied priorities among exceptions. For instance ThreadDeath should clobber all, whether it comes from acquire/use/release. Handling these priorities correctly is unsightly.

Therefore, abstract your resource handling away with the Execute Around idiom.

OwnerDisplayName: Jared

Body:
I just had a pretty painful troubleshooting experience in troubleshooting some code that looked like this:

try {
   doSomeStuff()
   doMore()
} finally {
   doSomeOtherStuff()
}

The problem was difficult to troubleshoot because doSomeStuff() threw an exception, which in turn caused doSomeOtherStuff() to also throw an exception.  The second exception (thrown by the finally block) was thrown up to my code, but it did not have a handle on the first exception (thrown from doSomeStuff()), which was the real root-cause of the problem.

If the code had said this instead, the problem would have been readily apparent:

try {
    doSomeStuff()
    doMore()
} catch (Exception e) {
    log.error(e);
} finally {
   doSomeOtherStuff()
}

So, my question is this:

Is a finally block used without any catch block a well-known java anti-pattern?  (It certainly seems to be a not-readily-apparent subclass of the obviously well-known anti-pattern "Don't gobble exceptions!")

Body:
In my opinion, it's more the case that finally with a catch indicate some kind of problem. The resource idiom is very simple:

acquire
try {
    use
} finally {
    release
}

In Java you can have an exception from pretty much anywhere. Often the acquire throws a checked exception, the sensible way to handle that is to put a catch around the how lot. Don't try some hideous null checking.

If you were going to be really anal you should note that there are implied priorities among exceptions. For instance ThreadDeath should clobber all, whether it comes from acquire/use/release. Handling these priorities correctly is unsightly.

Therefore, abstract your resource handling away with the Execute Around idiom.

OwnerDisplayName: Tom Hawtin - tackline


问:
Form elements are not shown?
Created Form in projectfolder/application/forms/Login.php

```<code>class Form_Login extends Zend_Form {

    public function _construct() {

        $this->setMethod('post');

        $elements = array();

        $element = $this->addElement('text', 'username');
        $element->setLabel('Username');
        $elements[] = $element;

        $element = $this->addElement('password', 'password');
        $element->setLabel('Password');
        $elements[] = $element;

        $this->addElements( $elements );

        $this->setElementDecorators( array( 'ViewHelper' ) );

    }
}
</code>```

Accessing Form in myproject/application/controllers/AuthenticationController.php

```<code>public function loginAction() {
   $this->view->heading = 'Login';
   $this->view->form = new Form_Login();
}
</code>```

in login.phtml

```<code><h1><?= $this->heading; ?></h1>
<?= $this->form; ?>
</code>```

Problem:

Heading is shown but not any form element is shown. What am I doing wrong here ?

Thanks

答:
Here is my complete solution:

Form Class in Login.php:

```<code>class Form_Login extends Zend_Form {

    /**
     * Constructor
     */
    public function __construct( $options = null ) {

        parent::__construct( $options );

        // Set the method for the display form to POST
        $this->setMethod('post');

        $elements = array();

        $element = $this->CreateElement('text', 'username');
        $element->setLabel('Username');
        $elements[] = $element;

        $element = $this->CreateElement('password', 'password');
        $element->setLabel('Password');
        $elements[] = $element;

        $element = $this->CreateElement('submit', 'submit');
        $element->setLabel('Login');
        $elements[] = $element;

        $this->addElements( $elements );

        $this->setElementDecorators( array( 'ViewHelper' ) );

        $this->setDecorators( array( array( 'ViewScript', array( 'viewScript' => 'authentication/login-form.phtml' ) ) ) );

    } // end construct

} // end class
</code>```

login-form.phtml

```<code><form action=<?= $this->element->getAction() ?> method=<?= $this->element->getMethod() ?> >

<table>
    <tr>
        <td><label><?= $this->element->username->getLabel() ?></label></td>
        <td><?= $this->element->username; ?></td>
    </tr>
    <tr>
        <td><label><?= $this->element->password->getLabel() ?></label></td>
        <td><?= $this->element->password; ?></td>
    </tr>
</table>

</form>
</code>```

Title: Form elements are not shown?

Body:
Created Form in projectfolder/application/forms/Login.php

class Form_Login extends Zend_Form {

    public function _construct() {

        $this->setMethod('post');

        $elements = array();

        $element = $this->addElement('text', 'username');
        $element->setLabel('Username');
        $elements[] = $element;

        $element = $this->addElement('password', 'password');
        $element->setLabel('Password');
        $elements[] = $element;

        $this->addElements( $elements );

        $this->setElementDecorators( array( 'ViewHelper' ) );

    }
}

Accessing Form in myproject/application/controllers/AuthenticationController.php

public function loginAction() {
   $this->view->heading = 'Login';
   $this->view->form = new Form_Login();
}

in login.phtml

<?= $this->heading; ?>

<?= $this->form; ?>

Problem:

Heading is shown but not any form element is shown. What am I doing wrong here ?

Thanks

Body:
Here is my complete solution:

Form Class in Login.php:

class Form_Login extends Zend_Form {

    /**
     * Constructor
     */
    public function __construct( $options = null ) {

        parent::__construct( $options );

        // Set the method for the display form to POST
        $this->setMethod('post');

        $elements = array();

        $element = $this->CreateElement('text', 'username');
        $element->setLabel('Username');
        $elements[] = $element;

        $element = $this->CreateElement('password', 'password');
        $element->setLabel('Password');
        $elements[] = $element;

        $element = $this->CreateElement('submit', 'submit');
        $element->setLabel('Login');
        $elements[] = $element;

        $this->addElements( $elements );

        $this->setElementDecorators( array( 'ViewHelper' ) );

        $this->setDecorators( array( array( 'ViewScript', array( 'viewScript' => 'authentication/login-form.phtml' ) ) ) );

    } // end construct

} // end class

login-form.phtml

<form action=<?= $this->element->getAction() ?> method=<?= $this->element->getMethod() ?> >

<table>
    <tr>
        <td><label><?= $this->element->username->getLabel() ?></label></td>
        <td><?= $this->element->username; ?></td>
    </tr>
    <tr>
        <td><label><?= $this->element->password->getLabel() ?></label></td>
        <td><?= $this->element->password; ?></td>
    </tr>
</table>

</form>


问:
Only show certain custom posts in all_items
When I register my custom post it adds a menu option to the WP Admin Dashboard that users can click and it lists all custom posts of that type. (Please see my image below if I am not making sense about the page I am describing).

That page listing all the custom posts of that type is good and working, but I only want that page to show certain custom posts. I only want to show custom posts whose post_meta my_flag equals true. Everyone of my custom posts has a my_flag post_meta set to true or false. I want my list page to only show custom posts whose my_flag = true.

Is that possible to do when I register the custom post type? Even if it isn't, how would I achieve this?

```<code>$labels = array(
    'name'                => _x( '_foo', 'Post Type General Name', '_foo' ),
    'singular_name'       => _x( 'Foo', 'Post Type Singular Name', '_foo' ),
    'menu_name'           => __( '_foo', '_foo' ),
    'parent_item_colon'   => __( 'Parent _foo', '_foo' ),
    'all_items'           => __( 'Foo Posts', '_foo' ),
    'view_item'           => __( 'View Foo', '_foo' ),
    'add_new_item'        => __( 'Add New Foo', '_foo' ),
    'add_new'             => __( 'Add New', '_foo' ),
    'edit_item'           => __( 'Edit Foo', '_foo' ),
    'update_item'         => __( 'Update Foo', '_foo' ),
    'search_items'        => __( 'Search Foo', '_foo' ),
    'not_found'           => __( 'Not Found', '_foo' ),
    'not_found_in_trash'  => __( 'Not found in Trash', '_foo' ),
);

$args = array(
    'label'               => __( 'foo', '_foo' ),
    'description'         => __( 'My custom posts', '_foo' ),
    'labels'              => $labels,
    'supports'            => array( 'title', 'revisions',
    'taxonomies'          => array( 'foo' ),
    'hierarchical'        => false,
    'public'              => true,
    'show_ui'             => true,
    'show_in_menu'        => 'my-plugin-menu',
    'show_in_nav_menus'   => true,
    'show_in_admin_bar'   => true,
    'show_in_rest'        => true,
    'query_var'           => true,
    'menu_position'       => 5,
    'can_export'          => true,
    'has_archive'         => true,
    'exclude_from_search' => false,
    'publicly_queryable'  => true,
    'capability_type'     => 'page'
);

register_post_type('foo', $args);
</code>```

I set the post_meta like so:

```<code>add_post_meta($post_id, 'my_flag', true, true);
</code>```

答:
you can edit the wp_query that will get the posts list from the database.
Please  try the below function:

```<code>function filter_my_posts($query) {
    if ( $query->is_home() && $query->is_main_query() && is_post_type_archive( 'your_custom_post_type' ) ) {
        $query->set(
            'meta_key' => 'my_flag',
            'meta_value => true,
        );
    }
}
add_action( 'pre_get_posts', 'filter_my_posts' );
</code>```

Good luck, please test and let me know what happens.

Body:
When I register my custom post it adds a menu option to the WP Admin Dashboard that users can click and it lists all custom posts of that type. (Please see my image below if I am not making sense about the page I am describing).

That page listing all the custom posts of that type is good and working, but I only want that page to show certain custom posts. I only want to show custom posts whose post_meta my_flag equals true. Everyone of my custom posts has a my_flag post_meta set to true or false. I want my list page to only show custom posts whose my_flag = true.

Is that possible to do when I register the custom post type? Even if it isn't, how would I achieve this?

$labels = array(
    'name'                => _x( '_foo', 'Post Type General Name', '_foo' ),
    'singular_name'       => _x( 'Foo', 'Post Type Singular Name', '_foo' ),
    'menu_name'           => __( '_foo', '_foo' ),
    'parent_item_colon'   => __( 'Parent _foo', '_foo' ),
    'all_items'           => __( 'Foo Posts', '_foo' ),
    'view_item'           => __( 'View Foo', '_foo' ),
    'add_new_item'        => __( 'Add New Foo', '_foo' ),
    'add_new'             => __( 'Add New', '_foo' ),
    'edit_item'           => __( 'Edit Foo', '_foo' ),
    'update_item'         => __( 'Update Foo', '_foo' ),
    'search_items'        => __( 'Search Foo', '_foo' ),
    'not_found'           => __( 'Not Found', '_foo' ),
    'not_found_in_trash'  => __( 'Not found in Trash', '_foo' ),
);

$args = array(
    'label'               => __( 'foo', '_foo' ),
    'description'         => __( 'My custom posts', '_foo' ),
    'labels'              => $labels,
    'supports'            => array( 'title', 'revisions',
    'taxonomies'          => array( 'foo' ),
    'hierarchical'        => false,
    'public'              => true,
    'show_ui'             => true,
    'show_in_menu'        => 'my-plugin-menu',
    'show_in_nav_menus'   => true,
    'show_in_admin_bar'   => true,
    'show_in_rest'        => true,
    'query_var'           => true,
    'menu_position'       => 5,
    'can_export'          => true,
    'has_archive'         => true,
    'exclude_from_search' => false,
    'publicly_queryable'  => true,
    'capability_type'     => 'page'
);

register_post_type('foo', $args);

I set the post_meta like so:

add_post_meta($post_id, 'my_flag', true, true);

Body:
you can edit the wp_query that will get the posts list from the database.
Please  try the below function:

function filter_my_posts($query) {
    if ( $query->is_home() && $query->is_main_query() && is_post_type_archive( 'your_custom_post_type' ) ) {
        $query->set(
            'meta_key' => 'my_flag',
            'meta_value => true,
        );
    }
}
add_action( 'pre_get_posts', 'filter_my_posts' );

Good luck, please test and let me know what happens.


问:
What is the scope of variable defined in kotlin console?
For example, I enter the kotlin console via kotlinc command.

Then define a variable: val pi = 3.14, what is its scope ?

I have tried const val PI = 3.14, which would be an error as following:

error: const 'val' are only allowed on top level or in objects

So, I am wondering what is the scope of code entered in the console ?

答:
Command line REPL compilation is very similar to .kts script compilation, which result is documented here. Each line is compiled as a separate script.

kotlinc creates a new class for each line you entered and creates an init block that executes your line. If you declare a property/function/class, it will be a public property/function/subclass of generated class.

Generated class constructor takes instances of ALL classes that were generated before it (a class for each line) and uses them as receivers for your code.

It can be verified if you use reflection in your command line compiler. There are some examples that verify what I said:

```<code>> println(this::class)
class Line_0
> val a = 0
> println(::a.visibility)
PUBLIC
> import kotlin.reflect.full.*
> println(Line_1::class.memberProperties)
[val Line_1.a: kotlin.Int]
> println(Line_1::class.constructors)
[fun <init>(): Line_1]
</code>```

You can create an instance of Line_0 easily:

```<code>> println(Line_0::class.java.constructors.first().newInstance())
Line_0@5b8caf1b
</code>```

But creating instances of other lines requires passing instances of all previous lines:

```<code>> val line0 = Line_0::class.java.constructors.first().newInstance()
> println(Line_1::class.java.constructors.first().newInstance(line0))
Line_1@1baba519
</code>```

Also, you can create an infinite recursion with creating instances (if you write the following line as the first line in kotlinc):

```<code>Line_0::class.java.constructors.first().newInstance()
</code>```

Body:
Command line REPL compilation is very similar to .kts script compilation, which result is documented here. Each line is compiled as a separate script.

kotlinc creates a new class for each line you entered and creates an init block that executes your line. If you declare a property/function/class, it will be a public property/function/subclass of generated class.

Generated class constructor takes instances of ALL classes that were generated before it (a class for each line) and uses them as receivers for your code.

It can be verified if you use reflection in your command line compiler. There are some examples that verify what I said:

> println(this::class)
class Line_0
> val a = 0
> println(::a.visibility)
PUBLIC
> import kotlin.reflect.full.*
> println(Line_1::class.memberProperties)
[val Line_1.a: kotlin.Int]
> println(Line_1::class.constructors)
[fun <init>(): Line_1]

You can create an instance of Line_0 easily:

> println(Line_0::class.java.constructors.first().newInstance())
Line_0@5b8caf1b

But creating instances of other lines requires passing instances of all previous lines:

> val line0 = Line_0::class.java.constructors.first().newInstance()
> println(Line_1::class.java.constructors.first().newInstance(line0))
Line_1@1baba519

Also, you can create an infinite recursion with creating instances (if you write the following line as the first line in kotlinc):

Line_0::class.java.constructors.first().newInstance()


问:
Java service return the Result message along with Object class
Hi i have to return the ResultMessage  along with my object class in my below code.

```<code>public List<EmployeeInformation> findAll(String IndexName) throws Exception {

        String ResultMessage = new String();
        if (Strings.isNullOrEmpty(IndexName)) {
            ResultMessage= "Index name is null or empty";
        } else if (isTextContainUpperCase(IndexName)) {
            ResultMessage= "Index name should be in lowercase";
        } else if (!checkEsConnection(client)) {
            ResultMessage= "Elasticsearch deployment is not reachable";
        }
        SearchRequest searchRequest = new SearchRequest(IndexName);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        return getSearchResult(searchResponse);
    }

private List<EmployeeInformation> getSearchResult(SearchResponse response) {

        SearchHit[] searchHit = response.getHits().getHits();

        List<EmployeeInformation> EmployeeDocuments = new ArrayList<>();

        for (SearchHit hit : searchHit) {
            EmployeeDocuments
                    .add(objectMapper
                            .convertValue(hit
                                    .getSourceAsMap(), EmployeeInformation.class));
        }

        return EmployeeDocuments;
    }
</code>```

What is the best way to return the ResultMessage along with my employeeinformation object. Could some one Modify the above code accordingly and post your answer or suggest me how to achieve this? thanks in advance

答:
This code is my suggested sample code for your requirement.</p>

```<code>public class Test {

    public static void main(String args[]) {

        Test test = new Test();
        String dept = "test";

        Object[] result = test.searchUser(dept);

        // Here must and should be follow the initailize order.
        String something = null;
        EmployeeInformation employee = null;
        if (result.length>= 0 && result[0] instanceof String) {
            something = (String) result[0];
        }

        if (result.length>= 1 && result[1] instanceof EmployeeInformation) {
            employee = (EmployeeInformation) result[1];
        }
        // do something
    }

    public Object[] searchUser(String dept) {

        Object[] result = new Object[2];

        result[0] = dept;
        result[1] = getUser(dept);

        return result;

    }

    private List<EmployeeInformation> getUser(String dept) {

        List<EmployeeInformation> userList = null;

        // some logic for get the EmployeeInformationInformation List based on
        // department.

        return userList;

    }

}
</code>```

Body:
Hi i have to return the ResultMessage  along with my object class in my below code.

public List<EmployeeInformation> findAll(String IndexName) throws Exception {

        String ResultMessage = new String();
        if (Strings.isNullOrEmpty(IndexName)) {
            ResultMessage= "Index name is null or empty";
        } else if (isTextContainUpperCase(IndexName)) {
            ResultMessage= "Index name should be in lowercase";
        } else if (!checkEsConnection(client)) {
            ResultMessage= "Elasticsearch deployment is not reachable";
        }
        SearchRequest searchRequest = new SearchRequest(IndexName);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        return getSearchResult(searchResponse);
    }

private List<EmployeeInformation> getSearchResult(SearchResponse response) {

        SearchHit[] searchHit = response.getHits().getHits();

        List<EmployeeInformation> EmployeeDocuments = new ArrayList<>();

        for (SearchHit hit : searchHit) {
            EmployeeDocuments
                    .add(objectMapper
                            .convertValue(hit
                                    .getSourceAsMap(), EmployeeInformation.class));
        }

        return EmployeeDocuments;
    }

What is the best way to return the ResultMessage along with my employeeinformation object. Could some one Modify the above code accordingly and post your answer or suggest me how to achieve this? thanks in advance

Body:
This code is my suggested sample code for your requirement.

public class Test {

    public static void main(String args[]) {

        Test test = new Test();
        String dept = "test";

        Object[] result = test.searchUser(dept);

        // Here must and should be follow the initailize order.
        String something = null;
        EmployeeInformation employee = null;
        if (result.length>= 0 && result[0] instanceof String) {
            something = (String) result[0];
        }

        if (result.length>= 1 && result[1] instanceof EmployeeInformation) {
            employee = (EmployeeInformation) result[1];
        }
        // do something
    }

    public Object[] searchUser(String dept) {

        Object[] result = new Object[2];

        result[0] = dept;
        result[1] = getUser(dept);

        return result;

    }

    private List<EmployeeInformation> getUser(String dept) {

        List<EmployeeInformation> userList = null;

        // some logic for get the EmployeeInformationInformation List based on
        // department.

        return userList;

    }

}


问:
Pure CSS styling of <select> element but only when non-default option is selected
Is it possible to conditionally style the following <select> element

```<code><select>
  <option>one</option>
  <option selected>default</option>
  <option>two</option>
</select>
</code>```

whenever the non-default options are selected, using pure CSS (no javascript)?

If there is a way, I would expect it to use some combination of pseudo-classes, something along the lines of

```<code>select:some-pseudo-class { border: 1px; }
</code>```

but probably more complicated. I already looked through the list of pseudo-classes and it seems this isn't possible, but I want to confirm this with the wisdom of the crowds before giving up completely. I have also done some research on this site and came across this question from 2013 which is asking a more general question, where the (possibly outdated) answer is "no". I don't believe my question is an exact duplicate of this question, because I am asking if a special case is possible and I am looking for an answer that is up-to-date as of February 2020.

答: You can try with the pseudo-class option:checked {border: 1px;}

Body:
Is it possible to conditionally style the following <select> element

<select>
  <option>one</option>
  <option selected>default</option>
  <option>two</option>
</select>

whenever the non-default options are selected, using pure CSS (no javascript)?

If there is a way, I would expect it to use some combination of pseudo-classes, something along the lines of

select:some-pseudo-class { border: 1px; }

but probably more complicated. I already looked through the list of pseudo-classes and it seems this isn't possible, but I want to confirm this with the wisdom of the crowds before giving up completely. I have also done some research on this site and came across this question from 2013 which is asking a more general question, where the (possibly outdated) answer is "no". I don't believe my question is an exact duplicate of this question, because I am asking if a special case is possible and I am looking for an answer that is up-to-date as of February 2020.


答:
You can get all the sequence, then group and finally and get the max.

```<code>>>> sequences = re.findall(str.join('|',sqc_large_dictionary),l)
>>> groups = [(k,len(list(grp))) for k,grp in itertools.groupby(sequences)]
>>> max(groups, key=lambda x:x[1])
('GAAA', 47)
</code>```

To get the max for each sequence type you can do:

```<code>>>> res = defaultdict(int)
>>> for k,v in groups:
...     res[k] = max(res[k], v)
...
>>> res
defaultdict(<class 'int'>, {'TCTG': 41, 'GATA': 27, 'AATG': 42, 'GAAA': 47, 'TATC': 19, 'AGATC': 23, 'TTTTTTCT': 33, 'TCTAG': 12})
</code>```

Title: Largest consecutive number of words

Body:
Consider the following Lavender DNA Sequence:

GCTAAATTTGTTCAGCCAGATGTAGGCTTACAAATCAAGCTGTCCGCTCGGCACGGCCTACACACGTCGTGTAACTACAACAGCTAGTTAATCTGGATATCACCATGACCGAATCATAGATTTCGCCTTAAGGAGCTTTACCATGGCTTGGGATCCAATACTAAGGGCTCGACCTAGGCGAATGAGTTTCAGGTTGGCAATCAGCAACGCTCGCCATCCGGACGACGGCTTACAGTTAGTAGCATAGTACGCGATTTTCGGGAAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCCCGTCAACTCATTCACACCGCATCCTTTCCTGCCACTGTAACTAGTCGACTGGGGAACCTCATCATCCATACTCTCCCACATTATGCCTCCCAACCTTGTTAAGCGTGGCATGCTTGGGATTGCATTGATGCTTCTTGGAGAGGACGCTTTCGTTTTGGAGATTACAGGGATCCAATTTTATCATCGGTTCGACTCCCGTAACGACTTAGCAGTAAGGGTGCTAGTTCCTGGTTAGAATCTTAATAAATCACGTCGCTTGGAGCAAGACAAAGATCGTCGTAATGCCAAGTGCACGACCACCTTCAGACTTGCAGGACCCGTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTCGATAGCTATGCGGTTCAATACAATCTTAACGCAATGCAGCGATGTGGTTTCGTACACTTAGCATAAAACCCCCCACATTAAATCGATGTACCCGCCCTCTTAGACGCCAATTTCAATGCCGAACCTCCGGCGGGTATCTCTGCACTAGGAGAAGTAGCACGTCGCTGTAGCGAACTCCTATCGTGAGATAATTTGTAGAGCTGCTCTTATAATACAATAGCTCAGATGGATTATTCCATGGACATCCCCGTGCGTTGTTTCGAGGATGGTAGGTGGAAATTTTGCCAGACCTCTAGTCTTAAACATGGTTGACGTTATAGGCGCTATCTCTTGCGTCTGGAAGTGTTAATCCGTGAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAACACGCAACTCTGGAGGAGGGCACTGCACTGCAAACTTGCGTAATATCCTTCACCCACACTTGCCTGGCCTCCTTGCTTAAAGCTCTGGCGATGCGATTTTTCGGCCCAGTAGCTGAATAGGTCATGAAATGGGCACCGAACTGGAAAGACCCATATATTCGATACTCACAACTTAATGATAGCGCGATTAAGAGCGACACCAAAAACCAAATTACGTTCACGAACCTTTGAGAGTCAAGGAGACTTAGACCGAATTGAATGATCACTGATGCGCCCGCTGATACTGAGCCTCACCATTAATCGCCGACCAATACGGCGTGTACCGGGCGCGGCCTTGCCGCATAACGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATATCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTACACAGCCCCGTCCTCATTGCTAAGTGCACTGGCAACTGGACCTAAAGATTTTTCGAGTATGGCCCTCGAATCAAGCGCCCACCCAGAAACCTACGAGCCAGTAACCCCAGTAAACAAGCATTAGTGCTATATGCTTGCTGCCCACTAGGACCCTTATGGTTCATACCAGGGTGACGTGTCTTGCGGGCCAAGGATGAACCAGAAGCAAGATCCTTAGATGGACGACTGTCTCATTGCTTAAACTCCACATACCAAAGGGCGCGGTAAACGATAGTTTTAGGTAATGTTAGTCGGATGGTTGTCTGCAGCTACCAATACAGCCTGGCACCCAGGGTCTGAACAATAACGCGTGAGAGCAGCTCTCCCGCGTGTGGTGGATTTGCCGTCTATGAAATTGAGGCTCTTGCAACTATTCGCACTCGGAATGCCCTCATATCTGGTGCCTAGCGGCCTTTGCCCCGTGCCGGTAGGACTAAACTCTACGGATCGTTGACGGATCTCGATGTGGAAGATGGTTATGAAAGATAACAACGCGTGTGCTAATTGATTTAGACAAGTATTGCGGCAGTAAAAGATAATCGGCTGCAGAGTTACGAAAGACTTCCATGCATGGATTCCATTCCTTCTAGTATAGGACCCACTCTGAATACACGTCTTGCGGGCCGATCATCTCCACCGCTGCGGAAGAAAGCAATTAAGAATCTATGCTCATTAAGAGTGCGACTATAATGCGGATCTTACAGTGCTAATGATCAGGACGTCGTCCAAGCAGGCTGCATGCCGAATTTAGCTTACGTCAGGATCAGGCGTTATAGCCTGGGAATCGGACTATGAGGACGCCACGACCTCTGGGAGAAAGCTATATACATTGAGGATCGCGCCATCTTTATGAGACTCAAATGAATCTAGATAGGTAGCATTGCGGACTTGAGTTAGCACATCGGTATTGGAAGGTGAGGGTCCTGCCGCTCGTTCTATGTTCGGTTTATAGTATACAAATAGGTCATCCCGAACGTTGAAGTTAAACTCATGACACGTTGTCGTAATGAAACGGGCCTGTTATTAGGGATACAGACAAAAGGCACAAGCTGGCTTGCACATTAAGGCGCACTAGAGATCCTCACAACCGTTGCCCGCACGGAGGTCGTGTCTAACAGACAGTGAACCAGCCGTATTGGGGTGGATGACCTGAGCTTCTTGGGGCCTGTTGTACACCGCGTGTGGTTCAACTGGTACACATACTACGAATATTCGAAATCATTGTACTGTGCTCTTCGGTGCTACTGACTGTGAGCGAATGCATCCCAATCCCAAACAATGCTTGTGGTAGGAGAATTGAAACTCTCGAAGCCTGGCCCAATGTCATCTACTTTTAACATGTCGGGCCAGGAGTTACGGGCATTGCTTACTTACTTTGCCCCCTTACACCACAGCAGCGCGATTCTTGTTGTAGTAGATTTTATACGACTCGCGAATTAAATGGAACTTGTCTGTCCCATATCGATCGTGTCCATCGTAAGATGAGATTGTAGGAGCATTCGGAAGTCTATGCGGCCCAGGGACTACTACGTTAAATCTGGTCAGACGTGGTTTACAAGGCGTCCCGATCTTCTCAGAACATATGGGAAAGCACTACCGTTCCTTCACGCATACAGTTGTTCGTGCCGAACGAGTAAGCTTGCGACCAGCCCACCCGCTAGGGCTATGCAGCGGGTCATGGCTGGCGCCATACTGTGCGGACAACCCACGCTCTGGCAGAAAGCGTCTTGTGTTTTGTAGTAGCTCCAACGGTTAGACCTTCGATATCTATTCAGAGCGCGAGCGACCACTATTAGACGGCATGTAAACAATGTGTATTTGTTCGGCCCAACCGGTATATGGGTAAGACCGCGAAGGGCCTGCGCGAATACCAGCGTCCAAAAATTCCTCACCCGAGATATGCGGTTAGTACCCCTTGGGTAACGGTCCGCTACGGGTAGCGACGCGAGCCGGCCGCATCGGTTGGAGCCGAGTTGTCGGGCAGGCGAGTAACGTGTGCAATTTGATGGGCCCAAGCCTCCGGCACTATCCACCTCATACATCGACAAAAGCACCAAATATGGGGAAAAGCTGAGCGTCGATATGTACATCTACCCAGGAACCGGCCCGAACATTAGGCGGACGTGAATTTCCGACCTAGGTTCGGCTACATTTCTACGATCCAAGCACACGTGAAGGAGGAGGGGTGTTCCGACCGTAAATGAACGAGGTGCGCAGTGACCCGATGGCGTTTAGCGGATAGCCTTCCTATGCCGGCCTATGCTGTATGGTAGTTGGTTGGTGCCTCCAGAGCCACTGCACCCAATCATAGGGTCTACAGCAGCGTACTTATAAAATTGTACGGGTGACCCATATCCATTACGGGTTGCGACCAGTATAGGAGAGTATAACTGCGTGAACTAATGCGTTATGACGCTTCAGAGTTTGCTCGGGCCCGAGTTCTAGGGCTATAATGTGTTAGGGCGCAAGTATGCCAAGCTAAGATGTGGCGTGCACACTAGGAGTTGTGTTCCTCTGCAAGCAGACACGAGCACTCTGGCAGTAGTTTGACCACACCCGGGTATCACTGCTACTCCATTTCGAACAAGCTATTGGAGCGGACAAAATATGCTACTCAAGAGCATTAGTTATAGGTCTACGAGACAGAAGCAGTTACTGAGTCTGAATATTCGATATAAGTAGGCATGGAGGCGGAGCAAAACAACGTCTGCGATCAATCGTGTTGATGACGTATGGCGACTGGAAGGTAAGGACTATGGCCGGACGGAATGATTCATGTTCTGTTCAAAGCTATATTTCGAAGGGGTATATTAGCGGTCCTACACTTGGTTAGCACCCTCCCCCCTCTGGATCCTGCACTAATTCGAGCTGGCCTCCATCGGTATCAGTCCGGAAGCTCCACTCTCTATCGTAGTCCTAATCAACAGGGTGCCAGTTTGCTCACGTGGAAGTTTGAGGCCCTTTGTGCTCCATAGCCAATCACTAACCATGCACGCGCGACCCACTCTACGTCCAGATCGGCTATAATAGTTGCGCCCGGGACTGGCAGAGTAGACATGTAAGCTAGATAGAGCCCCGACATCGGCCAAGAGATCCTACGCTGCTTCCAGATAATGAGAGACATTCTAGCATTAGACATGCAAGTCGGCAGGGACTCCCCTTATCTAGTAATTTCGATGAATTGGTTTTTCGGCTAGCATCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGACCATGCCGACCTCATCATAGAAGGAATGCTCTAAACTTAGAGTGCTACTAGGAAAACTATTAATCAATGATCGTCCTGCTTACATAGCTGGACGGCGAAAGTTCTTATACTGCGGAGGTTGCTGACGTAGAGTGCGCTGGGTACAGCGGATAAGTTGATCAGGGTGGGGATAGGGTGGCTCACCGTTTATACTCATATAGATTCCTGGCGTCGACGCTGTGACAGGGTCGAGATCGAGGGGGAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGCGGAGCGGAGGGAAAATTATCACCAGAGGGTAGGGGCTCGCGACATTCTATTCAATGCATTTCAAGCTACTTACGTATTTCGGCACAGTGACTACTGCCTGCGCGGCAGCCGTAAGGTTTCCCGTCAATAGGTGGCACGTATCATTGATGAAAGTGTCAGCTAATCATTCAGGCCTTA

and this dictionary

sqc_large_dictionary = ["AGATC","TTTTTTCT","AATG","TCTAG","GATA","TATC","GAAA","TCTG"]

That are the words we have to look for in Lavender's DNA sequence.

The problem is that, for example, I have managed with re and collections to create an algorithm that detects all AATG's (66). But the spec tells me that I should only count the longest consecutive sequence, in this case 43, since the others are watered, but there are 43 AATGs that are one behind the other and that is the number I should take. How could I implement this?

Body:
You can get all the sequence, then group and finally and get the max.

>>> sequences = re.findall(str.join('|',sqc_large_dictionary),l)
>>> groups = [(k,len(list(grp))) for k,grp in itertools.groupby(sequences)]
>>> max(groups, key=lambda x:x[1])
('GAAA', 47)

To get the max for each sequence type you can do:

>>> res = defaultdict(int)
>>> for k,v in groups:
...     res[k] = max(res[k], v)
...
>>> res
defaultdict(<class 'int'>, {'TCTG': 41, 'GATA': 27, 'AATG': 42, 'GAAA': 47, 'TATC': 19, 'AGATC': 23, 'TTTTTTCT': 33, 'TCTAG': 12})


问:
Python: openpyxl how to read a cell font color
I have tried to print some_cell.font.color.rgb and got various results.

For some I got what I want (like "FF000000"), but for others it gives me Value must be type 'basetring'. I assume that the latter is because I haven't actually defined the font color for these cells.

I'm using openpyxl 2.2.2

答:
Possible alternative solution, is to test the types of cell.color and cell.color.rgb.

The following test seems to give cells which their colors set:

```<code>if cl.font.color != None and type(cl.font.color.rgb) == str:
   # where cl =  cell of interest
   rbg = cl.font.color.rgb
</code>```

It seems cell.font.color is None when style is used and type(cell.color.rgb) is <class 'openpyxl.styles.colors.RGB'> when no color is set.

Note: This solution has not been tested thoroughly and may not work for all cases.

Body:
Possible alternative solution, is to test the types of cell.color and cell.color.rgb.

The following test seems to give cells which their colors set:

if cl.font.color != None and type(cl.font.color.rgb) == str:
   # where cl =  cell of interest
   rbg = cl.font.color.rgb

It seems cell.font.color is None when style is used and type(cell.color.rgb) is <class 'openpyxl.styles.colors.RGB'> when no color is set.

Note: This solution has not been tested thoroughly and may not work for all cases.


问:
How to crop an image and save a copy in the database on upload with MERN
I currently have a webpage where users can upload images and the images get saved to a mongodb database. I used the code from This Tutorial for the basic image uploading. I want the program to make a copy of the image, crop a square out of the center and save the copy to the database. How would I do that?</p>

答:
You can do that using node module called sharp.
You may go through documentation</p>


问:
Angular 4 - Select default value in dropdown [Reactive Forms]
In Angular 4, I have the following configuration defined in a json config file.

```<code> countries: ['USA', 'UK', 'Canada'];
 default: 'UK'
</code>```

I need to display these in a dropdown using Reactive module.

Here is the code to do this (ts)

```<code>countries: string[] = [];
default: string;
...
this.countries = config.countries;
this.default = config.default;
</code>```

html

```<code><select id="country" formControlName="country"  >
 <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>
</code>```

This does the job and displays the countries in a drop down.
However, I also need to select a country by default and the default country comes from the 'default' key defined in json.

So, I tried doing something like this

 {{ c }}

However, this does not work. By default an empty value if selected.

How can I make sure that a predefined value is selected by default?

答:
I was struggling and Found this Easy and Effective way from IntelliJ IDEA suggestion

```<code><select id="country" formControlName="country"  >
  <option [defaultSelected]=true [value]="default" >{{default}}</option>
  <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>
</code>```

And On your ts file assign the values

```<code> countries = ['USA', 'UK', 'Canada'];
 default = 'UK'
</code>```

Just make sure your formControlName accepts string, because you already assigned it as a string.

Body:
In Angular 4, I have the following configuration defined in a json config file.

 countries: ['USA', 'UK', 'Canada'];
 default: 'UK'

I need to display these in a dropdown using Reactive module.

Here is the code to do this (ts)

countries: string[] = [];
default: string;
...
this.countries = config.countries;
this.default = config.default;

html

<select id="country" formControlName="country"  >
 <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>

This does the job and displays the countries in a drop down.
However, I also need to select a country by default and the default country comes from the 'default' key defined in json.

So, I tried doing something like this

 {{ c }}

However, this does not work. By default an empty value if selected.

How can I make sure that a predefined value is selected by default?

Body:
I was struggling and Found this Easy and Effective way from IntelliJ IDEA suggestion

<select id="country" formControlName="country"  >
  <option [defaultSelected]=true [value]="default" >{{default}}</option>
  <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>

And On your ts file assign the values

 countries = ['USA', 'UK', 'Canada'];
 default = 'UK'

Just make sure your formControlName accepts string, because you already assigned it as a string.


问:
Issue with creating an Azure Function "No job functions found" error
What I am trying to achieve is that, I want to be able to create an Azure Function that would upload a video to YouTube using the YouTube API. example:https://developers.google.com/youtube/v3/docs/videos/insert . After creating the azure function, I then want to use that function inside my Azure logic app. Here is the code for the Azure function(uploded video):

```<code>using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;

namespace Google.Apis.YouTube.Samples
    {
        /// <summary>
        /// YouTube Data API v3 sample: upload a video.
        /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
        /// See https://developers.google.com/api-client-library/dotnet/get_started
        /// </summary>
        public class UploadVideo
        {
            [STAThread]
            static void Main(string[] args)
            {
                Console.WriteLine("YouTube Data API: Upload Video");
                Console.WriteLine("==============================");

                try
                {
                    new UploadVideo().Run().Wait();
                }
                catch (AggregateException ex)
                {
                    foreach (var e in ex.InnerExceptions)
                    {
                        Console.WriteLine("Error: " + e.Message);
                    }
                }

                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
            }

            private async Task Run()
            {
                UserCredential credential;
                using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
                {
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        // This OAuth 2.0 access scope allows an application to upload files to the
                        // authenticated user's YouTube channel, but doesn't allow other types of access.
                        new[] { YouTubeService.Scope.YoutubeUpload },
                        "user",
                        CancellationToken.None
                    );
                }

                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
                });

                var video = new Video();
                video.Snippet = new VideoSnippet();
                video.Snippet.Title = "Default Video Title";
                video.Snippet.Description = "Default Video Description";
                video.Snippet.Tags = new string[] { "tag1", "tag2" };
                video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
                video.Status = new VideoStatus();
                video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
                var filePath = @"/Users/sean/Desktop/audio/test1.mp4"; // Replace with path to actual movie file.

                using (var fileStream = new FileStream(filePath, FileMode.Open))
                {
                    var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                    videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                    videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                    await videosInsertRequest.UploadAsync();
                }
            }

            void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
            {
                switch (progress.Status)
                {
                    case UploadStatus.Uploading:
                        Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                        break;

                    case UploadStatus.Failed:
                        Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                        break;
                }
            }

            void videosInsertRequest_ResponseReceived(Video video)
            {
                Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
            }
        }
    }
</code>```

When I run this code, I am not seeing the expected outcome like this: https://developers.google.com/youtube/v3/docs/videos#resource . Instead, I am getting an error :

No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).

I have made all my methods public. I am not sure what I am missing.

答:
You are missing out the FunctionName attribute

```<code>[FunctionName("Function1")]
        public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
                ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
             //UploadVideoToYoutube() method call here;
            return new OkResult();
        }
</code>```

Getting started docs

Body:
What I am trying to achieve is that, I want to be able to create an Azure Function that would upload a video to YouTube using the YouTube API. example:https://developers.google.com/youtube/v3/docs/videos/insert . After creating the azure function, I then want to use that function inside my Azure logic app. Here is the code for the Azure function(uploded video):

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;

namespace Google.Apis.YouTube.Samples
    {
        ///
        /// YouTube Data API v3 sample: upload a video.
        /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
        /// See https://developers.google.com/api-client-library/dotnet/get_started
        ///
        public class UploadVideo
        {
            [STAThread]
            static void Main(string[] args)
            {
                Console.WriteLine("YouTube Data API: Upload Video");
                Console.WriteLine("==============================");

                try
                {
                    new UploadVideo().Run().Wait();
                }
                catch (AggregateException ex)
                {
                    foreach (var e in ex.InnerExceptions)
                    {
                        Console.WriteLine("Error: " + e.Message);
                    }
                }

                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
            }

            private async Task Run()
            {
                UserCredential credential;
                using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
                {
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        // This OAuth 2.0 access scope allows an application to upload files to the
                        // authenticated user's YouTube channel, but doesn't allow other types of access.
                        new[] { YouTubeService.Scope.YoutubeUpload },
                        "user",
                        CancellationToken.None
                    );
                }

                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
                });

                var video = new Video();
                video.Snippet = new VideoSnippet();
                video.Snippet.Title = "Default Video Title";
                video.Snippet.Description = "Default Video Description";
                video.Snippet.Tags = new string[] { "tag1", "tag2" };
                video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
                video.Status = new VideoStatus();
                video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
                var filePath = @"/Users/sean/Desktop/audio/test1.mp4"; // Replace with path to actual movie file.

                using (var fileStream = new FileStream(filePath, FileMode.Open))
                {
                    var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                    videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                    videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                    await videosInsertRequest.UploadAsync();
                }
            }

            void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
            {
                switch (progress.Status)
                {
                    case UploadStatus.Uploading:
                        Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                        break;

                    case UploadStatus.Failed:
                        Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                        break;
                }
            }

            void videosInsertRequest_ResponseReceived(Video video)
            {
                Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
            }
        }
    }

When I run this code, I am not seeing the expected outcome like this: https://developers.google.com/youtube/v3/docs/videos#resource . Instead, I am getting an error :

No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).

I have made all my methods public. I am not sure what I am missing.

Body:
You are missing out the FunctionName attribute

[FunctionName("Function1")]
        public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
                ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
             //UploadVideoToYoutube() method call here;
            return new OkResult();
        }

Getting started docs