问:
How to prove a SPARK.Text_IO procedure precondition will hold
I'm using SPARK.Text_IO from the spark_io example in SPARK Discovery 2017.

My problem is that many of the SPARK.Text_IO procedures have a precondition that I do not know how to begin to try to prove namely that the standard input is readable and we're not at end of file. My attempt, as displayed in the code below, was to add the precondition of the SPARK.Text_IO procedure (Get_Immediate in this case) to the precondition of the calling procedure, thinking that maybe that would guarantee to the prover that that precondition would be true. It didn't work. Here's an example of what I'm talking about:

Test spec:

```<code>with SPARK.Ada.Text_IO; use SPARK.Ada.Text_IO;

package test with SPARK_Mode
is

   continue_messages_key : Character := ' ';

   procedure User_Wait_For_Continue_Messages_Key
   with Global => (In_Out => Standard_Input,
                   Input => continue_messages_key),
        Pre => Is_Readable (Standard_Input) and then
                    not End_Of_File;

end test;
</code>```

Test body:

```<code>pragma SPARK_Mode(On);

package body test is

   procedure User_Wait_For_Continue_Messages_Key
   is
      IR : Immediate_Result;
      Avail : Boolean;
   begin
      loop
         Get_Immediate(IR, Avail);
         if Avail then
            if IR.Status = Success then
               if IR.Available = True then
                  if IR.Item = continue_messages_key then
                     return;
                  end if;
               end if;
            end if;
         end if;
      end loop;
   end User_Wait_For_Continue_Messages_Key;

end test;
</code>```

The error the prover gives is on the Get_Immediate line "medium: precondition might fail" The prototype and contract of the Get_Immediate procedure is below:

```<code>procedure Get_Immediate (Item      :    out Character_Result)
     with Global => (In_Out => Standard_Input),
          Pre    => Is_Readable (Standard_Input) and then
                    not End_Of_File,
          Post   => Is_Readable (Standard_Input) and
                    Name (Standard_Input) = Name (Standard_Input)'Old and
                    Form (Standard_Input) = Form (Standard_Input)'Old and
                    Is_Standard_Input (Standard_Input);
</code>```

How do you prove to SPARK that Standard_Input is readable and that it's not end of file?

答:
Let me start by saying I haven't used SPARK since the days of special comments, so my answer may not reflect current usage.

One way to look at SPARK is that it makes you think about every thing that your program might encounter. What should your program do if the precondition is False? You have to show that you've considered this possibility.

Presuming that all SPARK.Ada.Text_IO operations on Standard_Input have a postcondition including Is_Readable (Standard_Input) as Get_Immediate does, then it should suffice to put something like

```<code>pragma Assert (Is_Readable (Standard_Input) );
</code>```

at the beginning of your program and add this to the postcondition of your procedure (and any other subprograms you have that read Standard_Input). Then you should be sure that that part of the precondition holds throughout your program. (The assertion may not be needed if SPARK initially guarantees that Standard_Input is readable.)

not End_Of_File is a bit more complicated. It's possible for it to be False, at least on some platforms. Linux, for example, treats Ctrl-D as EOF when entered as the first thing on a line. There's also the cases where you're reading from a pipe or input redirection. Your procedure may call Get_Immediate when End_Of_File is True if the user enters EOF during the loop, so it's not surprising SPARK can't prove otherwise. Probably you need to take this part off the precondition of your procedure and change your body to something like

```<code>All_Chars : loop
   if not End_Of_File then
      Get_Immediate (IR, Avail);

      exit All_Chars when Avail               and then
                          IR.Status = Success and then
                          IR.Available        and then
                          IR.Item = Continue_Messages_Key;
   end if;
end loop All_Chars;
</code>```

Then you'll be sure the precondition of Get_Immediate is satisfied and have the apparently desired behavior (infinite loop) if End_Of_File becomes True (presuming that some field of IR fails one of your checks in that case).

There are some puzzling things about your code. First is the global variable. Global variables are the Root of All Evil, or at least guarantee unreadable code. Then there's the specificity of the procedure. Wouldn't something more general, like

```<code>procedure Wait_For_Key (Key : in Character);
</code>```

be just as easy to write and prove, and more useful? Then there's the string of nested if statements, which I find harder to read than the equivalent conditions connected with and then. Finally, there's comparing a Boolean to True. Since "=" returns Boolean, doesn't that indicate that what's needed is a Boolean, which is what is already on the left side of "="?

Perhaps it means that the result of "=" must also be compared to True. Then the result of that "=" must also be compared to True. This might be better, since it ensures that whoever is writing this will never finish.

Body:
I'm using SPARK.Text_IO from the spark_io example in SPARK Discovery 2017.

My problem is that many of the SPARK.Text_IO procedures have a precondition that I do not know how to begin to try to prove namely that the standard input is readable and we're not at end of file. My attempt, as displayed in the code below, was to add the precondition of the SPARK.Text_IO procedure (Get_Immediate in this case) to the precondition of the calling procedure, thinking that maybe that would guarantee to the prover that that precondition would be true. It didn't work. Here's an example of what I'm talking about:

Test spec:

with SPARK.Ada.Text_IO; use SPARK.Ada.Text_IO;

package test with SPARK_Mode
is

   continue_messages_key : Character := ' ';

   procedure User_Wait_For_Continue_Messages_Key
   with Global => (In_Out => Standard_Input,
                   Input => continue_messages_key),
        Pre => Is_Readable (Standard_Input) and then
                    not End_Of_File;

end test;

Test body:

pragma SPARK_Mode(On);

package body test is

   procedure User_Wait_For_Continue_Messages_Key
   is
      IR : Immediate_Result;
      Avail : Boolean;
   begin
      loop
         Get_Immediate(IR, Avail);
         if Avail then
            if IR.Status = Success then
               if IR.Available = True then
                  if IR.Item = continue_messages_key then
                     return;
                  end if;
               end if;
            end if;
         end if;
      end loop;
   end User_Wait_For_Continue_Messages_Key;

end test;

The error the prover gives is on the Get_Immediate line "medium: precondition might fail" The prototype and contract of the Get_Immediate procedure is below:

procedure Get_Immediate (Item      :    out Character_Result)
     with Global => (In_Out => Standard_Input),
          Pre    => Is_Readable (Standard_Input) and then
                    not End_Of_File,
          Post   => Is_Readable (Standard_Input) and
                    Name (Standard_Input) = Name (Standard_Input)'Old and
                    Form (Standard_Input) = Form (Standard_Input)'Old and
                    Is_Standard_Input (Standard_Input);

How do you prove to SPARK that Standard_Input is readable and that it's not end of file?

Body:
Let me start by saying I haven't used SPARK since the days of special comments, so my answer may not reflect current usage.

One way to look at SPARK is that it makes you think about every thing that your program might encounter. What should your program do if the precondition is False? You have to show that you've considered this possibility.

Presuming that all SPARK.Ada.Text_IO operations on Standard_Input have a postcondition including Is_Readable (Standard_Input) as Get_Immediate does, then it should suffice to put something like

pragma Assert (Is_Readable (Standard_Input) );

at the beginning of your program and add this to the postcondition of your procedure (and any other subprograms you have that read Standard_Input). Then you should be sure that that part of the precondition holds throughout your program. (The assertion may not be needed if SPARK initially guarantees that Standard_Input is readable.)

not End_Of_File is a bit more complicated. It's possible for it to be False, at least on some platforms. Linux, for example, treats Ctrl-D as EOF when entered as the first thing on a line. There's also the cases where you're reading from a pipe or input redirection. Your procedure may call Get_Immediate when End_Of_File is True if the user enters EOF during the loop, so it's not surprising SPARK can't prove otherwise. Probably you need to take this part off the precondition of your procedure and change your body to something like

All_Chars : loop
   if not End_Of_File then
      Get_Immediate (IR, Avail);

      exit All_Chars when Avail               and then
                          IR.Status = Success and then
                          IR.Available        and then
                          IR.Item = Continue_Messages_Key;
   end if;
end loop All_Chars;

Then you'll be sure the precondition of Get_Immediate is satisfied and have the apparently desired behavior (infinite loop) if End_Of_File becomes True (presuming that some field of IR fails one of your checks in that case).

There are some puzzling things about your code. First is the global variable. Global variables are the Root of All Evil, or at least guarantee unreadable code. Then there's the specificity of the procedure. Wouldn't something more general, like

procedure Wait_For_Key (Key : in Character);

be just as easy to write and prove, and more useful? Then there's the string of nested if statements, which I find harder to read than the equivalent conditions connected with and then. Finally, there's comparing a Boolean to True. Since "=" returns Boolean, doesn't that indicate that what's needed is a Boolean, which is what is already on the left side of "="?

Perhaps it means that the result of "=" must also be compared to True. Then the result of that "=" must also be compared to True. This might be better, since it ensures that whoever is writing this will never finish.


来源: stackexchange

问:
MySQL Event Scheduler on a specific time everyday
Here's my query

```<code>CREATE EVENT
RESET ON SCHEDULE AT TIMESTAMP DO
UPDATE `ndic`.`students`
SET `status` = '0';
</code>```

How can I update status to "0" at 1 pm every day.

What can I use instead of TIMESTAMP?

答:
The documentation on CREATE EVENT is quite good, but it takes a while to get it right.

You have two problems, first, making the event recur, second, making it run at 13:00 daily.

This example creates a recurring event.

```<code>CREATE EVENT e_hourly
    ON SCHEDULE
      EVERY 1 HOUR
    COMMENT 'Clears out sessions table each hour.'
    DO
      DELETE FROM site_activity.sessions;
</code>```

When in the command-line MySQL client, you can:

```<code>SHOW EVENTS;
</code>```

This lists each event with its metadata, like if it should run once only, or be recurring.

The second problem: pointing the recurring event to a specific schedule item.

By trying out different kinds of expression, we can come up with something like:

```<code>CREATE EVENT IF NOT EXISTS `session_cleaner_event`
ON SCHEDULE
  EVERY '1 13' DAY_HOUR
  COMMENT 'Clean up sessions at 13:00 daily!'
  DO
    DELETE FROM site_activity.sessions;
</code>```

Update, long over-due: The interval with the unit "DAY_HOUR" takes an expression that looks like 'day-number hour-number'. I have updated the oft-accepted solution to match that. Thanks, commenters for clarifying!

ContentLicense: CC BY-SA 4.0

Body:
Here's my query

CREATE EVENT
RESET ON SCHEDULE AT TIMESTAMP DO
UPDATE `ndic`.`students`
SET `status` = '0';

How can I update status to "0" at 1 pm every day.

What can I use instead of TIMESTAMP?

Body:
The documentation on CREATE EVENT is quite good, but it takes a while to get it right.

You have two problems, first, making the event recur, second, making it run at 13:00 daily.

This example creates a recurring event.

CREATE EVENT e_hourly
    ON SCHEDULE
      EVERY 1 HOUR
    COMMENT 'Clears out sessions table each hour.'
    DO
      DELETE FROM site_activity.sessions;

When in the command-line MySQL client, you can:

SHOW EVENTS;

This lists each event with its metadata, like if it should run once only, or be recurring.

The second problem: pointing the recurring event to a specific schedule item.

By trying out different kinds of expression, we can come up with something like:

CREATE EVENT IF NOT EXISTS `session_cleaner_event`
ON SCHEDULE
  EVERY '1 13' DAY_HOUR
  COMMENT 'Clean up sessions at 13:00 daily!'
  DO
    DELETE FROM site_activity.sessions;

Update, long over-due: The interval with the unit "DAY_HOUR" takes an expression that looks like 'day-number hour-number'. I have updated the oft-accepted solution to match that. Thanks, commenters for clarifying!


问:
Setup VSTS Continuous Integration (CI) for ASP.NET Core Devextreme project
I have tried to setup the Continuous Integration (CI) in  VSTS for the ASP.NET core project developed using Devextreme.

I have checked the NuGet.config file in the project, seems the devextreme-controls-netcore is referred from the local machine.

NuGet.config

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="devextreme-controls-netcore" value="C:\Program Files (x86)\DevExpress 17.1\DevExtreme\System\DevExtreme\Bin\AspNetCore" />
  </packageSources>
</configuration>
</code>```

I have created a build definition in VSTS for this project and queued a build. I am getting error while restoring the packages.

Log file from VS:

```<code>2017-11-17T11:26:33.0089440Z ##[section]Starting: Restore
2017-11-17T11:26:33.0279221Z ==============================================================================
2017-11-17T11:26:33.0279221Z Task         : .NET Core
2017-11-17T11:26:33.0279221Z Description  : Build, test and publish using dotnet core command-line.
2017-11-17T11:26:33.0279221Z Version      : 1.0.2
2017-11-17T11:26:33.0279221Z Author       : Microsoft Corporation
2017-11-17T11:26:33.0279221Z Help         : [More Information](https://go.microsoft.com/fwlink/?linkid=832194)
2017-11-17T11:26:33.0279221Z ==============================================================================
2017-11-17T11:26:34.6038344Z [command]"C:\Program Files\dotnet\dotnet.exe" restore d:\a\3\s\DevExtremeAspNetCoreApp\DevExtremeAspNetCoreApp.csproj
2017-11-17T11:26:42.2434595Z   Restoring packages for d:\a\3\s\DevExtremeAspNetCoreApp\DevExtremeAspNetCoreApp.csproj...
2017-11-17T11:26:42.2434595Z   Restoring packages for d:\a\3\s\DevExtremeAspNetCoreApp\DevExtremeAspNetCoreApp.csproj...
2017-11-17T11:26:42.2434595Z C:\Program Files\dotnet\sdk\2.0.2\NuGet.targets(102,5): **error : The local source 'C:\Program Files (x86)\DevExpress 17.1\DevExtreme\System\DevExtreme\Bin\AspNetCore' doesn't exist.** [d:\a\3\s\DevExtremeAspNetCoreApp\DevExtremeAspNetCoreApp.csproj]
2017-11-17T11:26:42.6496133Z ##[error]Error: C:\Program Files\dotnet\dotnet.exe failed with return code: 1
2017-11-17T11:26:42.6496133Z ##[error]Dotnet command failed with non-zero exit code on the following projects : d:\a\3\s\DevExtremeAspNetCoreApp\DevExtremeAspNetCoreApp.csproj
2017-11-17T11:26:42.6536144Z ##[section]Finishing: Restore
</code>```

How to build the devextreme-controls-netcore is VSTS to setup CI.

Please suggest a solution to fix this issue.

答:
You're referencing a local path (C:\Program Files (x86)\DevExpress 17.1\DevExtreme\System\DevExtreme\Bin\AspNetCore). If that path doesn't exist on your build agent, the build will fail.

The best solution is going to be to set up a Packages feed in VSTS, upload your packages to that, and update your project to pull the packages from the private package feed.

ContentLicense: CC BY-SA 3.0

Body:
I have tried to setup the Continuous Integration (CI) in  VSTS for the ASP.NET core project developed using Devextreme.

I have checked the NuGet.config file in the project, seems the devextreme-controls-netcore is referred from the local machine.

NuGet.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="devextreme-controls-netcore" value="C:\Program Files (x86)\DevExpress 17.1\DevExtreme\System\DevExtreme\Bin\AspNetCore" />
  </packageSources>
</configuration>

I have created a build definition in VSTS for this project and queued a build. I am getting error while restoring the packages.

Log file from VS:

2017-11-17T11:26:33.0089440Z ##[section]Starting: Restore
2017-11-17T11:26:33.0279221Z ==============================================================================
2017-11-17T11:26:33.0279221Z Task         : .NET Core
2017-11-17T11:26:33.0279221Z Description  : Build, test and publish using dotnet core command-line.
2017-11-17T11:26:33.0279221Z Version      : 1.0.2
2017-11-17T11:26:33.0279221Z Author       : Microsoft Corporation
2017-11-17T11:26:33.0279221Z Help         : [More Information](https://go.microsoft.com/fwlink/?linkid=832194)
2017-11-17T11:26:33.0279221Z ==============================================================================
2017-11-17T11:26:34.6038344Z [command]"C:\Program Files\dotnet\dotnet.exe" restore d:\a\3\s\DevExtremeAspNetCoreApp\DevExtremeAspNetCoreApp.csproj
2017-11-17T11:26:42.2434595Z   Restoring packages for d:\a\3\s\DevExtremeAspNetCoreApp\DevExtremeAspNetCoreApp.csproj...
2017-11-17T11:26:42.2434595Z   Restoring packages for d:\a\3\s\DevExtremeAspNetCoreApp\DevExtremeAspNetCoreApp.csproj...
2017-11-17T11:26:42.2434595Z C:\Program Files\dotnet\sdk\2.0.2\NuGet.targets(102,5): **error : The local source 'C:\Program Files (x86)\DevExpress 17.1\DevExtreme\System\DevExtreme\Bin\AspNetCore' doesn't exist.** [d:\a\3\s\DevExtremeAspNetCoreApp\DevExtremeAspNetCoreApp.csproj]
2017-11-17T11:26:42.6496133Z ##[error]Error: C:\Program Files\dotnet\dotnet.exe failed with return code: 1
2017-11-17T11:26:42.6496133Z ##[error]Dotnet command failed with non-zero exit code on the following projects : d:\a\3\s\DevExtremeAspNetCoreApp\DevExtremeAspNetCoreApp.csproj
2017-11-17T11:26:42.6536144Z ##[section]Finishing: Restore

How to build the devextreme-controls-netcore is VSTS to setup CI.

Please suggest a solution to fix this issue.


问:
How to make sure the rx java observable is not run again until the first call finishes
We have a sync in a sync adapter.  Once the sync is called we need to block any other calls, from the OS, to that sync adapter until we have finished handling the response from the first sync.  I thought that calling .blockingGet() on a Single would do the trick, but it doesn't.  How can I make sure that all code being handled in the Single finishes before we allow the Single to be called/subscribed to again?

```<code>@Override
public void onPerformTrackedSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
     try {
        mCurrentUpdater = createUpdater();
        mCurrentUpdater
                .update()
                .blockingGet();
        onSyncCompleted(null);
    } catch (Exception ex) {
        onSyncCompleted(ex);
        onError(ex);
    }
}

@NonNull
public final Single<Complete> update() {
    synchronized (this) {
        if (mUpdateCalled) throw new IllegalStateException("Updaters should not be reused");
        mUpdateCalled = true;
    }
    updateOnePage(); // will call onUpdaterPageSuccess which can continue updating
    return mCompleteSubject
            .take(1)
            .singleOrError();
}

   /**
 * Update an individual "page" of data. Calls to onUpdaterPageSuccess may call back into this function.
*/
void updateOnePage() {
    updateNextPage()
            .subscribe(
                    this::onUpdaterPageSuccess,
                    this::onPageFailure
            );
}
</code>```

This is were the actual network sync is called:

```<code>protected Single<Page> updateNextPage() {
    runMigrations();
    String syncMarker = AreaSyncService.getSyncMarker();
    Log.i("AAAZ", "Area Sync Requested  " + Thread.currentThread());
    return buildRequestData(new Date())
            .flatMap(requestData -> mSalesRabbitService.syncAreas(syncMarker,
                    requestData.syncedAreas,
                    requestData.syncedAreaUserHistories,
                    requestData.deletedAreaIds,
                    requestData.deletedAreaUserHistoryIds)
                    .map(areaSyncValidated -> Pair.create(areaSyncValidated, requestData)))
            .map(pair -> new Page(pair.first, pair.second))
            .flatMap(this::updateWithPage);
}
</code>```

And here we handle the sync response with another Single

```<code>protected Single<Page> updateWithPage(@NonNull Page page) {
    Log.i("AAAZ", "Area Sync Requested  " + Thread.currentThread());
    return Single.just(page)
           .flatMap(this::updateIdTrackersAndLastAreaSyncDevice)
           .flatMap(this::addAreaIdsToNewAreas)
           .flatMap(this::addAreaUserHistoryIdsToNewAreaUserHistories)
           .flatMap(this::updateAreas)
           .flatMap(this::updateHistories)
           .flatMap(this::createAreas)
           .flatMap(this::createHistories)
           .flatMap(this::resetCacheFirstTime)
           .flatMap(this::postChangedEvents)
           .flatMap(this::handleDeletionsResetCachePostEvent)
           .flatMap(this::housekeepingIfApplicable);
}
</code>```

I suspect the issue is something I'm doing wrong between the update() method and the updateOnePage() method.  How can I make sure that the single subscribed() to in updateOnePage() finishes completely before it can be called again?

答:
As part of your observer chain, where the queries are being constructed, at the end of updateNextPage(), you have a flatMap() operator that invokes updateOnePage(). flatMap() takes an additional argument which is the number of parallel operations. Add the parameter 1.

```<code>.flatMap(this::updateWithPage, 1);
</code>```

Body:
We have a sync in a sync adapter.  Once the sync is called we need to block any other calls, from the OS, to that sync adapter until we have finished handling the response from the first sync.  I thought that calling .blockingGet() on a Single would do the trick, but it doesn't.  How can I make sure that all code being handled in the Single finishes before we allow the Single to be called/subscribed to again?

@Override
public void onPerformTrackedSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
     try {
        mCurrentUpdater = createUpdater();
        mCurrentUpdater
                .update()
                .blockingGet();
        onSyncCompleted(null);
    } catch (Exception ex) {
        onSyncCompleted(ex);
        onError(ex);
    }
}

@NonNull
public final Single<Complete> update() {
    synchronized (this) {
        if (mUpdateCalled) throw new IllegalStateException("Updaters should not be reused");
        mUpdateCalled = true;
    }
    updateOnePage(); // will call onUpdaterPageSuccess which can continue updating
    return mCompleteSubject
            .take(1)
            .singleOrError();
}

   /**
 * Update an individual "page" of data. Calls to onUpdaterPageSuccess may call back into this function.
*/
void updateOnePage() {
    updateNextPage()
            .subscribe(
                    this::onUpdaterPageSuccess,
                    this::onPageFailure
            );
}

This is were the actual network sync is called:

protected Single<Page> updateNextPage() {
    runMigrations();
    String syncMarker = AreaSyncService.getSyncMarker();
    Log.i("AAAZ", "Area Sync Requested  " + Thread.currentThread());
    return buildRequestData(new Date())
            .flatMap(requestData -> mSalesRabbitService.syncAreas(syncMarker,
                    requestData.syncedAreas,
                    requestData.syncedAreaUserHistories,
                    requestData.deletedAreaIds,
                    requestData.deletedAreaUserHistoryIds)
                    .map(areaSyncValidated -> Pair.create(areaSyncValidated, requestData)))
            .map(pair -> new Page(pair.first, pair.second))
            .flatMap(this::updateWithPage);
}

And here we handle the sync response with another Single

protected Single<Page> updateWithPage(@NonNull Page page) {
    Log.i("AAAZ", "Area Sync Requested  " + Thread.currentThread());
    return Single.just(page)
           .flatMap(this::updateIdTrackersAndLastAreaSyncDevice)
           .flatMap(this::addAreaIdsToNewAreas)
           .flatMap(this::addAreaUserHistoryIdsToNewAreaUserHistories)
           .flatMap(this::updateAreas)
           .flatMap(this::updateHistories)
           .flatMap(this::createAreas)
           .flatMap(this::createHistories)
           .flatMap(this::resetCacheFirstTime)
           .flatMap(this::postChangedEvents)
           .flatMap(this::handleDeletionsResetCachePostEvent)
           .flatMap(this::housekeepingIfApplicable);
}

I suspect the issue is something I'm doing wrong between the update() method and the updateOnePage() method.  How can I make sure that the single subscribed() to in updateOnePage() finishes completely before it can be called again?

Body:
As part of your observer chain, where the queries are being constructed, at the end of updateNextPage(), you have a flatMap() operator that invokes updateOnePage(). flatMap() takes an additional argument which is the number of parallel operations. Add the parameter 1.

.flatMap(this::updateWithPage, 1);


问:
How to fill text vertically in javaFX?

I've tried stretch height and width out but only width can show text horizontally, not vertically.

Below is what I've tried.

```<code>    Label label5 = new Label("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
    HBox hbox5 = new HBox();
    label5.setMinHeight(Region.USE_COMPUTED_SIZE);
    hbox5.getChildren().add(label5);
    hbox5.setAlignment(Pos.TOP_CENTER);
    hbox5.setMinHeight(Region.USE_COMPUTED_SIZE);
</code>```

but It seems doesn't work.

Please let me know if I missed something Thank you!

答:
The key is making sure you use a Monospaced font.

Code Version:

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication42 extends Application {

    @Override
    public void start(Stage primaryStage) {
        StackPane root = new StackPane();

        Label label = new Label("Hello World");
        label.setFont(Font.font("Monospaced"));
        label.setWrapText(true);
        label.setMinWidth(1);
        label.setPrefWidth(1);
        label.setMaxWidth(1);

        root.getChildren().add(label);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

FXML Version:

```<code>?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.Pane?>

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <Label layoutX="296.0" layoutY="81.0" prefHeight="198.0" prefWidth="0.0" text="HELLO WORLD" wrapText="true" />
   </children>
</Pane>
</code>```

Title: How to fill text vertically in javaFX?

Body:
I've tried stretch height and width out but only width can show text horizontally, not vertically.

Below is what I've tried.

    Label label5 = new Label("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
    HBox hbox5 = new HBox();
    label5.setMinHeight(Region.USE_COMPUTED_SIZE);
    hbox5.getChildren().add(label5);
    hbox5.setAlignment(Pos.TOP_CENTER);
    hbox5.setMinHeight(Region.USE_COMPUTED_SIZE);

but It seems doesn't work.

Please let me know if I missed something Thank you!

Body:
The key is making sure you use a Monospaced font.

Code Version:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication42 extends Application {

    @Override
    public void start(Stage primaryStage) {
        StackPane root = new StackPane();

        Label label = new Label("Hello World");
        label.setFont(Font.font("Monospaced"));
        label.setWrapText(true);
        label.setMinWidth(1);
        label.setPrefWidth(1);
        label.setMaxWidth(1);

        root.getChildren().add(label);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}

FXML Version:

?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.Pane?>

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <Label layoutX="296.0" layoutY="81.0" prefHeight="198.0" prefWidth="0.0" text="HELLO WORLD" wrapText="true" />
   </children>
</Pane>


问:
What does forKey mean? What does it do?
I'm guessing that it gives the object that is being added to the NSMutableDictionary or NSDictionary a name to access it. But, I have to confirm it. Can anybody tell me?</p>

答:
Dictionaries are data structures that contain key-value pairs. They're also known as hash tables. So yes, you use a key to refer to its corresponding value.

For the following dictionary:

```<code>// Pseudo-code, not actual Objective-C code, merely for illustration
// (This {} syntax would be really nice to have though...)
NSDictionary *dict = {
    @"one" => NSNumber (1),
    @"two" => NSNumber (2)
};
</code>```

The following code yields 1:

```<code>NSNumber *one = [dict objectForKey:@"one"];
NSLog(@"%d", [one intValue]);
</code>```

ContentLicense: CC BY-SA 2.5

Title: What does forKey mean? What does it do?

Body:
Dictionaries are data structures that contain key-value pairs. They're also known as hash tables. So yes, you use a key to refer to its corresponding value.

For the following dictionary:

// Pseudo-code, not actual Objective-C code, merely for illustration
// (This {} syntax would be really nice to have though...)
NSDictionary *dict = {
    @"one" => NSNumber (1),
    @"two" => NSNumber (2)
};

The following code yields 1:

NSNumber *one = [dict objectForKey:@"one"];
NSLog(@"%d", [one intValue]);


问:
Linux: Howto setup one application to use different sound card?
I have 3 sound cards - one integrated (A) and 2 on USB (B,C).
I want play default system sounds over integrated card (A),
while application 1 over B card and application 2 over C card.
Say, Firefox on B and Chrome on C, all other on default A.

LinuxMint.

答: ok, I found: apt install pavucontrol :)</p>

Body: ok, I found: apt install pavucontrol :)


问:
Icon is loaded, but not shown (html, css)
I have an icon which is actually on my webpage but I still cant see it.

HTML

```<code><i class="iconMan"></i>
</code>```

CSS

```<code>.iconMan{
    background-image: url(../../assets/imgs/iconMan.png);
    display: block;
  }
</code>```

this is what I get:

The Icon should be next to "Test User" but it's not showing. I already tried adjusting height and width but it didn't work.
Any suggestions what I could do?

答:
You have missed quotes</p>

```<code>.iconMan{
    background-image: url("../../assets/imgs/iconMan.png");
    display: block;
  }
</code>```

Body:
I have an icon which is actually on my webpage but I still cant see it.

HTML

CSS

.iconMan{
    background-image: url(../../assets/imgs/iconMan.png);
    display: block;
  }

this is what I get:

The Icon should be next to "Test User" but it's not showing. I already tried adjusting height and width but it didn't work.
Any suggestions what I could do?

Body:
You have missed quotes

.iconMan{
    background-image: url("../../assets/imgs/iconMan.png");
    display: block;
  }


答:
try to do like this

```<code><img src="/assets/imgs/iconMan.png"
</code>```

I guess it will work
just put this to your html code

Title: Icon is loaded, but not shown (html, css)

Body:
try to do like this

<img src="/assets/imgs/iconMan.png"

I guess it will work
just put this to your html code


问:
Injecting several Spring Beans of the same class using application.properties
I have a security test driven by Spring.  I want to create a set of test users (currentUser, anotherUser, adminUser, etc).  The credentials for the users will be stored in an application.properties like so:

```<code>test.currentUser.username=user1
test.currentUser.password=secret
test.adminUser.username=admin
test.adminUser.password=admin_password
...
</code>```

There is a class that can construct an object for a user.  It looks something like this:

```<code>@Component
public class UserObject{
  public UserObject(
    @Value("${test.currentUser.username}") String username,
    @Value("${test.currentUser.password}") String password){
    //Use username and password to do some authentication stuff
  }
}
</code>```

The client test class looks something like this:

```<code>public class TestClass{
  @Autowired
  public TestClass(UserObject userObject){
  }
}
</code>```

How can the classes above be altered such that several UserObjects are somehow injected by Spring (and get config values from the application.properties file)?

答:
```<code>@ConfigurationProperties
@Getter
@Setter
@Configuration
public class Test {
  Map<String, String> credentials;
}

@Configuration
public class TestCreate {

  @Bean(name = "userList")
  public List<UserObject> creteUser(Test test) {
    List<UserObject> users = new ArrayList<>();
    test.getCredentials().entrySet().forEach(entry -> {
      UserObject user = new UserObject( entry.getKey(), entry.getValue());
      users.add(user);
    });
    return users;
  }
}
</code>```

application.properties

```<code>credentials.user1=secret //user1 is key, secret is value
credentials.user2=someothersecret
</code>```

Now if you do

```<code>@Autowired
List<UserObject> userList;
</code>```

in any of the spring component, you get what you desired.
Hope it helps

Body:
I have a security test driven by Spring.  I want to create a set of test users (currentUser, anotherUser, adminUser, etc).  The credentials for the users will be stored in an application.properties like so:

test.currentUser.username=user1
test.currentUser.password=secret
test.adminUser.username=admin
test.adminUser.password=admin_password
...

There is a class that can construct an object for a user.  It looks something like this:

@Component
public class UserObject{
  public UserObject(
    @Value("${test.currentUser.username}") String username,
    @Value("${test.currentUser.password}") String password){
    //Use username and password to do some authentication stuff
  }
}

The client test class looks something like this:

public class TestClass{
  @Autowired
  public TestClass(UserObject userObject){
  }
}

How can the classes above be altered such that several UserObjects are somehow injected by Spring (and get config values from the application.properties file)?

Body:
@ConfigurationProperties
@Getter
@Setter
@Configuration
public class Test {
  Map<String, String> credentials;
}

@Configuration
public class TestCreate {

  @Bean(name = "userList")
  public List<UserObject> creteUser(Test test) {
    List<UserObject> users = new ArrayList<>();
    test.getCredentials().entrySet().forEach(entry -> {
      UserObject user = new UserObject( entry.getKey(), entry.getValue());
      users.add(user);
    });
    return users;
  }
}

application.properties

credentials.user1=secret //user1 is key, secret is value
credentials.user2=someothersecret

Now if you do

@Autowired
List<UserObject> userList;

in any of the spring component, you get what you desired.
Hope it helps


问:
Word comparison algorithm
I am doing a CSV Import tool for the project I'm working on.
The client needs to be able to enter the data in excel, export them as CSV and upload them to the database.
For example I have this CSV record:

```<code>   1,   John Doe,     ACME Comapny   (the typo is on purpose)
</code>```

Of course, the companies are kept in a separate table and linked with a foreign key, so I need to discover the correct company ID before inserting.
I plan to do this by comparing the company names in the database with the company names in the CSV.
the comparison should return 0 if the strings are exactly the same, and return some value that gets bigger as the strings get more different, but strcmp doesn't cut it here because:

"Acme Company" and "Acme Comapny" should have a very small difference index, but
"Acme Company" and "Cmea Mpnyaco" should have a very big difference index
Or "Acme Company" and "Acme Comp." should also have a small difference index, even though the character count is different.
Also, "Acme Company" and "Company Acme" should return 0.

So if the client makes a type while entering data, i could prompt him to choose the name he most probably wanted to insert.

Is there a known algorithm to do this, or maybe we can invent one :)
?

答:
I've had some success with the Levenshtein Distance algorithm, there is also Soundex.

What language are you implementing this in? we may be able to point to specific examples

OwnerDisplayName: Discodancer

Title: Word comparison algorithm

Body:
I am doing a CSV Import tool for the project I'm working on.
The client needs to be able to enter the data in excel, export them as CSV and upload them to the database.
For example I have this CSV record:

   1,   John Doe,     ACME Comapny   (the typo is on purpose)

Of course, the companies are kept in a separate table and linked with a foreign key, so I need to discover the correct company ID before inserting.
I plan to do this by comparing the company names in the database with the company names in the CSV.
the comparison should return 0 if the strings are exactly the same, and return some value that gets bigger as the strings get more different, but strcmp doesn't cut it here because:

"Acme Company" and "Acme Comapny" should have a very small difference index, but
"Acme Company" and "Cmea Mpnyaco" should have a very big difference index
Or "Acme Company" and "Acme Comp." should also have a small difference index, even though the character count is different.
Also, "Acme Company" and "Company Acme" should return 0.

So if the client makes a type while entering data, i could prompt him to choose the name he most probably wanted to insert.

Is there a known algorithm to do this, or maybe we can invent one :)
?

OwnerDisplayName: Neil Aitken


问:
AWK, printf format specifier %x has problems with negative values
It seems AWK has problems with the unsigned hex format specifier:

```<code>echo 0x80000000 | awk '{printf("0x%08x\n", $1)}'
</code>```

gives back: 0x7fffffff

Is this a known problem with awk?

Thanks!

答:
Not seeing it here, although I wasn't able to use the hex input as you are, but converted to decimal was no problem.

```<code>$ echo 2147483648 | awk '{printf("0x%08x\n", $1)}'
0x80000000
</code>```

If you care to enlighten us what platform you're on (this was GNU awk 3.1.5), we might be able to help you more.

Body:
It seems AWK has problems with the unsigned hex format specifier:

echo 0x80000000 | awk '{printf("0x%08x\n", $1)}'

gives back: 0x7fffffff

Is this a known problem with awk?

Thanks!

Body:
Not seeing it here, although I wasn't able to use the hex input as you are, but converted to decimal was no problem.

$ echo 2147483648 | awk '{printf("0x%08x\n", $1)}'
0x80000000

If you care to enlighten us what platform you're on (this was GNU awk 3.1.5), we might be able to help you more.


问:
How to add total sum to woocommerce cart section
I customized the "checkout" page and added cart section to that page.(Just copy and paste cart table from "cart" to "checkout" page)

I'm using storefront child theme and custom "cart","checkout" page templates are in here.

```<code>child-theme/woocommerce/cart/cart.php
child-theme/woocommerce/checkout/form-checkout.php
</code>```

What I want is to add the total sum section below cart table. Something like this.

How can I handle this one?

答:
For the total part WooCommerce has another template called "cart-totals.php".
So you might need to add its content too.</p>

Body:
I customized the "checkout" page and added cart section to that page.(Just copy and paste cart table from "cart" to "checkout" page)

I'm using storefront child theme and custom "cart","checkout" page templates are in here.

child-theme/woocommerce/cart/cart.php
child-theme/woocommerce/checkout/form-checkout.php

What I want is to add the total sum section below cart table. Something like this.

How can I handle this one?


问:
rspec stub any_instance with attributes
I need to stub all instances of a model that have a particular attribute or set of attributes. For example, using ActiveRecord:

```<code>let(:model1) { Model.create!(uid: 1) }
let(:model2) { Model.create!(uid: 2) }

before do
  allow(model1).to receive(:foo).and_return :bar
  allow(model2).to receive(:foo).and_return :baz
end

it do
  expect(model1.foo).to eq :bar # => passes
  expect(model2.foo).to eq :baz # => passes

  ################################################
  #### Here is the issue I'm trying to solve: ####
  ################################################
  new_instance_of_model1 = Model.find_by(uid: 1)
  new_instance_of_model2 = Model.find_by(uid: 2)

  expect(new_instance_of_model1.foo).to eq :bar # => fails
  expect(new_instance_of_model2.foo).to eq :baz # => fails
end
</code>```

Is there some way to stub all instances of Model that have uid: 1?

I'm looking for something like:

```<code>allow_any_instance_of(Model).with_attributes(uid: 1).to receive(:foo).and_return(:bar)
allow_any_instance_of(Model).with_attributes(uid: 2).to receive(:foo).and_return(:baz)
</code>```

Note:

I can't use something like:

```<code>allow(Model).to receive(:find).with(1)and_return(model1)
allow(Model).to receive(:find).with(2)and_return(model2)
</code>```

because there are many other ways to get to the model (associations, scopes, Arel, etc.)

答:
This isn't a very good idea, but you can accomplish this by passing a block argument to receive instead of a method chain, like this:

```<code>allow_any_instance_of(Model).to receive(:foo) do |model|
  case model.uid
  when 1
    :bar
  when 2
    :baz
  end
end
</code>```

Title: rspec stub any_instance with attributes

Body:
I need to stub all instances of a model that have a particular attribute or set of attributes. For example, using ActiveRecord:

let(:model1) { Model.create!(uid: 1) }
let(:model2) { Model.create!(uid: 2) }

before do
  allow(model1).to receive(:foo).and_return :bar
  allow(model2).to receive(:foo).and_return :baz
end

it do
  expect(model1.foo).to eq :bar # => passes
  expect(model2.foo).to eq :baz # => passes

  ################################################
  #### Here is the issue I'm trying to solve: ####
  ################################################
  new_instance_of_model1 = Model.find_by(uid: 1)
  new_instance_of_model2 = Model.find_by(uid: 2)

  expect(new_instance_of_model1.foo).to eq :bar # => fails
  expect(new_instance_of_model2.foo).to eq :baz # => fails
end

Is there some way to stub all instances of Model that have uid: 1?

I'm looking for something like:

allow_any_instance_of(Model).with_attributes(uid: 1).to receive(:foo).and_return(:bar)
allow_any_instance_of(Model).with_attributes(uid: 2).to receive(:foo).and_return(:baz)

Note:

I can't use something like:

allow(Model).to receive(:find).with(1)and_return(model1)
allow(Model).to receive(:find).with(2)and_return(model2)

because there are many other ways to get to the model (associations, scopes, Arel, etc.)

Body:
This isn't a very good idea, but you can accomplish this by passing a block argument to receive instead of a method chain, like this:

allow_any_instance_of(Model).to receive(:foo) do |model|
  case model.uid
  when 1
    :bar
  when 2
    :baz
  end
end


问:
C++ Avoiding library linking
I currently have a c++ setup like the following

```<code>class FlowController
{
   public:
    //...
   private:
       cntrl::OneWayValve _intake;
}
</code>```

As you can see i'm using a cntrl::OneWayValve instance within my class. The Valve class resides in another library which i link with at compile time. The cntrl::OneWayValve has a cntrl::Value within its implementation like so.

```<code>class OneWayValve
{
   public:
    //...
   private:
       cntrl::Valve _valve;
}
</code>```

And as before the cntrl::Valve resides in a different library for reasons you'll have to ask the previous developer about.

Now when i compile my FlowController class i'm required to link with the OneWayValve library and the cntrl::Valve library as well.

My question:
Is it possible to only link with the cntrl::OneWayValve library at compile time?

Forward declaration?

Static libraries (really don't want to do this tho)?

Another alternative?

Basically i don't want to know that its using a cntrl::Valve internally, its none of my business.

Note: apologies the OS is Unix.

Cheers,
Ben

答: Unfortunately for you, the OneWayValve isn't very well designed. Not only you need to link to both libraries, but you will also have to recompile both the OneWayValve library and your code if the Valve class changes.

Title: C++ Avoiding library linking

Body:
I currently have a c++ setup like the following

class FlowController
{
   public:
    //...
   private:
       cntrl::OneWayValve _intake;
}

As you can see i'm using a cntrl::OneWayValve instance within my class. The Valve class resides in another library which i link with at compile time. The cntrl::OneWayValve has a cntrl::Value within its implementation like so.

class OneWayValve
{
   public:
    //...
   private:
       cntrl::Valve _valve;
}

And as before the cntrl::Valve resides in a different library for reasons you'll have to ask the previous developer about.

Now when i compile my FlowController class i'm required to link with the OneWayValve library and the cntrl::Valve library as well.

My question:
Is it possible to only link with the cntrl::OneWayValve library at compile time?

Forward declaration?

Static libraries (really don't want to do this tho)?

Another alternative?

Basically i don't want to know that its using a cntrl::Valve internally, its none of my business.

Note: apologies the OS is Unix.

Cheers,
Ben


问:
Unity get Type of the service where the dependecy gets injected
Is it possible to get, in Unity, the Type of the service where the dependecy gets injected?

In Ninject you can do it like this:

```<code>kernel.Bind<ILogger>().ToMethod((context) =>
{
    ILogger logger = HttpContextLoggerFactory.GetInstance();

    // Eg: MyApplication.PeopleRepository
    string memberType = context?.Request?.Target?.Member?.DeclaringType?.FullName;

    return new LoggerMemberTypeDecorator(logger, memberType);
});
</code>```

How can the same thing be implemented in Unity?

Here is what i have, but i do not have access to any context

```<code>container.RegisterType<ILogger>(new InjectionFactory(u =>
{
    ILogger logger = HttpContextLoggerFactory.GetInstance();

    // how to get it?
    string memberType = "";

    return new LoggerMemberTypeDecorator(logger, memberType);
});
</code>```

答:
You have to register your Service (whose type then gets reported to the injected dependency's constructor) with a special InjectionConstructor.

Shamelessly copying my own answer (see details here):

```<code>container.RegisterType<IInterface, Implementation>( new MyInjectionConstructor() );

internal class MyInjectionConstructor : InjectionMember
{
    public override void AddPolicies( Type serviceType, Type implementationType, string name, IPolicyList policies )
    {
        policies.Set<IConstructorSelectorPolicy>( new MyConstructorSelectorPolicy(), new NamedTypeBuildKey( implementationType, name ) );
    }
}

internal class MyConstructorSelectorPolicy : DefaultUnityConstructorSelectorPolicy
{
    protected override IDependencyResolverPolicy CreateResolver( ParameterInfo parameter )
    {
        if( parameter.ParameterType == typeof( ILogger ) )
        {
            return new LiteralValueDependencyResolverPolicy( new Logger( parameter.Member.DeclaringType ) );
        }
        return base.CreateResolver( parameter );
    }
}
</code>```

Body:
Is it possible to get, in Unity, the Type of the service where the dependecy gets injected?

In Ninject you can do it like this:

kernel.Bind<ILogger>().ToMethod((context) =>
{
    ILogger logger = HttpContextLoggerFactory.GetInstance();

    // Eg: MyApplication.PeopleRepository
    string memberType = context?.Request?.Target?.Member?.DeclaringType?.FullName;

    return new LoggerMemberTypeDecorator(logger, memberType);
});

How can the same thing be implemented in Unity?

Here is what i have, but i do not have access to any context

container.RegisterType<ILogger>(new InjectionFactory(u =>
{
    ILogger logger = HttpContextLoggerFactory.GetInstance();

    // how to get it?
    string memberType = "";

    return new LoggerMemberTypeDecorator(logger, memberType);
});

Body:
You have to register your Service (whose type then gets reported to the injected dependency's constructor) with a special InjectionConstructor.

Shamelessly copying my own answer (see details here):

container.RegisterType<IInterface, Implementation>( new MyInjectionConstructor() );

internal class MyInjectionConstructor : InjectionMember
{
    public override void AddPolicies( Type serviceType, Type implementationType, string name, IPolicyList policies )
    {
        policies.Set<IConstructorSelectorPolicy>( new MyConstructorSelectorPolicy(), new NamedTypeBuildKey( implementationType, name ) );
    }
}

internal class MyConstructorSelectorPolicy : DefaultUnityConstructorSelectorPolicy
{
    protected override IDependencyResolverPolicy CreateResolver( ParameterInfo parameter )
    {
        if( parameter.ParameterType == typeof( ILogger ) )
        {
            return new LiteralValueDependencyResolverPolicy( new Logger( parameter.Member.DeclaringType ) );
        }
        return base.CreateResolver( parameter );
    }
}


问:
Can't locate DBI.pm in @INC (you may need to install the DBI module)
I want to use the Defects4j dataset,when I do this follow the page of github:
 https://github.com/rjust/defects4j

```<code>$ defects4j checkout Lang
Can't locate DBI.pm in @INC
   (you may need to install the DBI module)
   (@INC contains:
   /c/Users/Liu Fang/defects4j/framework/lib
   /c/Users/Liu Fang/defects4j/framework
   /c/Users/Liu Fang/defects4j/framework/core
   /c/Users/Liu Fang/defects4j/framework/core
   /usr/lib/perl5/site_perl
   /usr/share/perl5/site_perl
   /usr/lib/perl5/vendor_perl
   /usr/share/perl5/vendor_perl
   /usr/lib/perl5/core_perl
   /usr/share/perl5/core_perl .
   ) at /c/Users/Liu Fang/defects4j/framework/core/DB.pm line 43.
</code>```

[Added line breaks for readability]

答:
DBI is the most commonly-used Perl database interface library. It is not included as part of the standard Perl distribution. You will, therefore, need to install this module (as the error message says).

If you update your question to give more information about your environment (what operating system, what version of Perl, how Perl was installed) then we will be able to help you install it.

Body:
I want to use the Defects4j dataset,when I do this follow the page of github:
 https://github.com/rjust/defects4j

$ defects4j checkout Lang
Can't locate DBI.pm in @INC
   (you may need to install the DBI module)
   (@INC contains:
   /c/Users/Liu Fang/defects4j/framework/lib
   /c/Users/Liu Fang/defects4j/framework
   /c/Users/Liu Fang/defects4j/framework/core
   /c/Users/Liu Fang/defects4j/framework/core
   /usr/lib/perl5/site_perl
   /usr/share/perl5/site_perl
   /usr/lib/perl5/vendor_perl
   /usr/share/perl5/vendor_perl
   /usr/lib/perl5/core_perl
   /usr/share/perl5/core_perl .
   ) at /c/Users/Liu Fang/defects4j/framework/core/DB.pm line 43.

[Added line breaks for readability]


问:
How to enforce float in decimal format when encoding to JSON in Go
I have a big.float which I'm encoding into JSON . However the JSON always end up showing the float in scientific notation rater than decimal notation. I can fix this by changing the JSON to be a string rather than a number and using float.Text('f'), however I would really prefer to keep the type as a number.

I was a taking a look at float.Format but I don't believe this is suitable.

A really condensed gist of what I'm doing is below. I do a lot more modification of the value of supply before encoding it to json.

```<code>type TokenSupply struct {
   TotalSupply  *big.Float  `json:"totalSupply, omitempty"`
}
supply := Float.NewFloat(1000000)
json.NewEncoder(w).Encode(TokenSupply{supply})
</code>```

This returns:

```<code>{"totalSupply":"1e+06"}
</code>```

答:
Caveats about encoding numbers that don't fit into 64 bits aside, here is how you could marshal a big.Float as a JSON number by wrapping it in a custom type that implements json.Marshaler. The key is that you can implement theMarshalJSON method anyway you like, as long as it emits valid JSON:

```<code>package main

import (
  "encoding/json"
  "fmt"
  "math/big"
)

type BigFloatNumberJSON struct{ *big.Float }

func (bfn BigFloatNumberJSON) MarshalJSON() ([]byte, error) {
  // Use big.Float.String() or any other string converter
  // that emits a valid JSON number here...
  return []byte(bfn.String()), nil
}

func main() {
  totalSupply := new(big.Float).SetFloat64(1000000)
  obj := map[string]interface{}{
    "totalSupply": BigFloatNumberJSON{totalSupply},
  }
  bytes, err := json.Marshal(&obj)
  if err != nil {
    panic(err)
  }
  fmt.Println(string(bytes))
  // => {"totalSupply":1000000}
}
</code>```

Body:
I have a big.float which I'm encoding into JSON . However the JSON always end up showing the float in scientific notation rater than decimal notation. I can fix this by changing the JSON to be a string rather than a number and using float.Text('f'), however I would really prefer to keep the type as a number.

I was a taking a look at float.Format but I don't believe this is suitable.

A really condensed gist of what I'm doing is below. I do a lot more modification of the value of supply before encoding it to json.

type TokenSupply struct {
   TotalSupply  *big.Float  `json:"totalSupply, omitempty"`
}
supply := Float.NewFloat(1000000)
json.NewEncoder(w).Encode(TokenSupply{supply})

This returns:

{"totalSupply":"1e+06"}

Body:
Caveats about encoding numbers that don't fit into 64 bits aside, here is how you could marshal a big.Float as a JSON number by wrapping it in a custom type that implements json.Marshaler. The key is that you can implement theMarshalJSON method anyway you like, as long as it emits valid JSON:

package main

import (
  "encoding/json"
  "fmt"
  "math/big"
)

type BigFloatNumberJSON struct{ *big.Float }

func (bfn BigFloatNumberJSON) MarshalJSON() ([]byte, error) {
  // Use big.Float.String() or any other string converter
  // that emits a valid JSON number here...
  return []byte(bfn.String()), nil
}

func main() {
  totalSupply := new(big.Float).SetFloat64(1000000)
  obj := map[string]interface{}{
    "totalSupply": BigFloatNumberJSON{totalSupply},
  }
  bytes, err := json.Marshal(&obj)
  if err != nil {
    panic(err)
  }
  fmt.Println(string(bytes))
  // => {"totalSupply":1000000}
}


问:
Unit testing vs functional testing in Flask applications?
I'm reading the following manual: http://flask.pocoo.org/docs/testing/

Flask has features to simulate requests and check results. The whole application is tested including DB.

It plays nicely with Python module unittest. But this seems to me like end-to-end or functional testing and other tools like Selenium (with Python binding) come to mind.

Is unit-testing is only testing particular module/function/class completely isolated
with mocks for external resources (DB, network, files)?

Is it ok to use unit testing frameworks to drive
functional\end-to-end tests?

答:
Flask does not get in the way of Python/JavaScript testing tooling. For example, it is possible to handle all kinds of testing (I deliberately do not want to name them unit/functional/acceptance/integration tests whatever as there always be anybody who will find the classification wrong):

testing simple and/or pure functions or classes

as previous plus database (eg, SQLAlchemy) (this is usually more practical and effective than using mocks for ORM/data objects, albeit slower)

request-level testing (to test views / routes) - no real HTTP requests, but pretty close for the purpose

in-browser testing with real HTTP request, including testing JavaScript modules

For example, with pytest it's just a matter of conftest.py files and fixtures, which provide app, db, http server and Selenium driver (in two separate threads), etc. It is even possible to make certain tests faster by using transaction rollbacks instead of remaking database fixture by substituting (monkeypatching) commit method. During tests, Flask can serve special static folder (by registering test-time only blueprint) to test JavaScript modules using JavaScript-specific testing frameworks of choice.

I guess, other generic testing frameworks (I do not call them unit-testing!) can do the same with more or less boilerplate code and fixture organization.


问:
Doubly Linkedlist in javascript
I wrote the below code just for fun to create doubly LinkedList but it leads to circular referencing. How do i stop the circular referencing?  </p>

```<code>const node = function (value) {
  this.value = value;
  this.next = null;
  this.prev = null;
}

let head = new node(null);
let current = head;

const newnode = new node('1');
newnode.prev = current;
current.next = newnode;
current = current.next;
</code>```

<p>In js, it(above code) leads to circular nesting as its an object. I am worried about memory leak issues coz of this. Any better way to implement Doubly. </p>

答:
tl;dr You can not.

In a doubly linked list, an element holds the reference to the next and the previous element.

If from the element A you have a reference to the next element B, and from the element B you have a reference to the previous element A, that by definition is a circular reference.

Maybe what you're looking for is the Singly linked list structure?

Title: Doubly Linkedlist in javascript

Body:
I wrote the below code just for fun to create doubly LinkedList but it leads to circular referencing. How do i stop the circular referencing?

const node = function (value) {
  this.value = value;
  this.next = null;
  this.prev = null;
}

let head = new node(null);
let current = head;

const newnode = new node('1');
newnode.prev = current;
current.next = newnode;
current = current.next;

In js, it(above code) leads to circular nesting as its an object. I am worried about memory leak issues coz of this. Any better way to implement Doubly.


问:
awk print all parts before a match
I have some text where I want to grab all the text up to the year, inclusive. I've tried starting with something like this

```<code>awk '/[1-2][0-9][0-9][0-9]/{print $1}'
</code>```

but that only prints the first "word" of the input

```<code>"Financial summary 1997 FINAL.doc" => "Financial"
"v4 Minutes 19950705" => "v4"
</code>```

What I want is "Financial summary 1997" and "v4 Minutes 1995". I've played around with $NF and various others with no success as yet I don't know how many words there are, or how many numbers there are, so I can't jut print $1 $2 $3. I don't have to use awk, but it would be useful since I am actually going to print the results out with some surrounding tags for output to an HTML file.

I can set a field separator to be "4 digits" but that discards the year

```<code> awk -F[1-2][0-9][0-9][0-9] '{print $1}
</code>```

EDIT:
This is what I ended up with and then came back to see a solution posted:

```<code>awk 'match($0,/.*(19|20)[0-9]{2}/){print substr($0,RSTART,RLENGTH)}'
</code>```

Thanks all

答:
```<code>awk '{sub(/97/,"97\"");print $1,$2,$3}' file

"Financial summary 1997"
"v4 Minutes 19950705"
</code>```

All we have to do is to print the three first fields
and add a double quote after 1997. With the help of

sub the double is added but it has to be escaped first "\"
that is all.

Title: awk print all parts before a match

Body:
I have some text where I want to grab all the text up to the year, inclusive. I've tried starting with something like this

awk '/[1-2][0-9][0-9][0-9]/{print $1}'

but that only prints the first "word" of the input

"Financial summary 1997 FINAL.doc" => "Financial"
"v4 Minutes 19950705" => "v4"

What I want is "Financial summary 1997" and "v4 Minutes 1995". I've played around with $NF and various others with no success as yet I don't know how many words there are, or how many numbers there are, so I can't jut print $1 $2 $3. I don't have to use awk, but it would be useful since I am actually going to print the results out with some surrounding tags for output to an HTML file.

I can set a field separator to be "4 digits" but that discards the year

 awk -F[1-2][0-9][0-9][0-9] '{print $1}

EDIT:
This is what I ended up with and then came back to see a solution posted:

awk 'match($0,/.*(19|20)[0-9]{2}/){print substr($0,RSTART,RLENGTH)}'

Thanks all

Body:
awk '{sub(/97/,"97\"");print $1,$2,$3}' file

"Financial summary 1997"
"v4 Minutes 19950705"

All we have to do is to print the three first fields
and add a double quote after 1997. With the help of

sub the double is added but it has to be escaped first "\"
that is all.


问:
Parsing optional recursive parser runs in infinite recursion
I'm currently writing a parser for ECMAScript 5 (as a toy). The standard dictates how logical or expressions should be parsed:

```<code><LogicalORExpression> :
    <LogicalANDExpression>
    <LogicalORExpression> || <LogicalANDExpression>
</code>```

basicly this is equivalent to

<logicalOrExpression> = [<logicalOrExpression> ||] <LogicalAndExpression>

but how should I parse this without running into an infite loop? My current parser obviously does:

```<code>logicalOrExpression :: Parser LogicalOrExpression
logicalOrExpression = do
    orExpr <- optional $ do
        e <- logicalOrExpression
        _ <- symbol "||"
        return e
    andExpr <- logicalAndExpression
    case orExpr of
        Just e -> return $ LogicalOrExpression (e, andExpr)
        Nothing -> return $ AndExpression andExpr
</code>```

Thanks

答:
As I want to stay true to the spec in terms of the AST produced, I decided to switch to an Earley based parser and not parser combinators, as Earley's algorithm can handle left recursion.

If I would be OK with flattening the grammar, I would use the answer of Benjamin Hodgson

Body:
I'm currently writing a parser for ECMAScript 5 (as a toy). The standard dictates how logical or expressions should be parsed:

<LogicalORExpression> :
    <LogicalANDExpression>
    <LogicalORExpression> || <LogicalANDExpression>

basicly this is equivalent to

<logicalOrExpression> = [<logicalOrExpression> ||] <LogicalAndExpression>

but how should I parse this without running into an infite loop? My current parser obviously does:

logicalOrExpression :: Parser LogicalOrExpression
logicalOrExpression = do
    orExpr <- optional $ do
        e <- logicalOrExpression
        _ <- symbol "||"
        return e
    andExpr <- logicalAndExpression
    case orExpr of
        Just e -> return $ LogicalOrExpression (e, andExpr)
        Nothing -> return $ AndExpression andExpr

Thanks


问:
iPhone, Monotouch, and XIB outlet issues
I'm having a problem with mapping controls in a subview back to fields on the owning controller. Specifically, I have mapped outlets for each of my "controls" to File's Owner. Monotouch then generated code for the controller's xib designer.cs file to reference these controls as properties on the controller class. However, when I run my code; I get object is null errors when trying to set properties on the controls. Digging into the issue with the debugger; it appears GetNativeField is returning null when trying to access the outlets by their names from the xib file.

Anyone have any ideas why this would be happening? I've checked the .xib file, and the generated code; the Outlet, Property, and Field names are consistent with one another.

答:
I figured out what was causing the issue; it was how I was pushing the controller on the stack:

```<code>using(var batteryController = new BatteryController()){

    navigationController.PushViewController(batteryController,true);

}
</code>```

It seems that when dispose is called on the controller, the NIB resource is removed from memory; which was causing the issue.

However, this brings up another question. Aren't you supposed to call dispose on the new controller once it's been pushed onto the stack? In objective C, when you push a controller on the stack; your supposed to call release afterwards. So what am I doing wrong then?

Body:
I figured out what was causing the issue; it was how I was pushing the controller on the stack:

using(var batteryController = new BatteryController()){

    navigationController.PushViewController(batteryController,true);

}

It seems that when dispose is called on the controller, the NIB resource is removed from memory; which was causing the issue.

However, this brings up another question. Aren't you supposed to call dispose on the new controller once it's been pushed onto the stack? In objective C, when you push a controller on the stack; your supposed to call release afterwards. So what am I doing wrong then?


问:
Getting actual file name (with proper casing) on Windows
Windows file system is case insensitive. How, given a file/folder name (e.g. "somefile"), I get the actual name of that file/folder (e.g. it should return "SomeFile" if Explorer displays it so)?

Some ways I know, all of which seem quite backwards:

Given the full path, search for each folder on the path (via FindFirstFile). This gives proper cased results of each folder. At the last step, search for the file itself.

Get filename from handle (as in MSDN example). This requires opening a file, creating file mapping, getting it's name, parsing device names etc. Pretty convoluted. And it does not work for folders or zero-size files.

Am I missing some obvious WinAPI call? The simplest ones, like GetActualPathName() or GetFullPathName() return the name using casing that was passed in (e.g. returns "program files" if that was passed in, even if it should be "Program Files").

I'm looking for a native solution (not .NET one).

答:
Just found that the Scripting.FileSystemObject suggested by @bugmagnet 10 years ago is a treasure. Unlike my old method, it works on Absolute Path, Relative Path, UNC Path and Very Long Path (path longer than MAX_PATH). Shame on me for not testing his method earlier.

For future reference, I would like to present this code which can be compiled in both C and C++ mode. In C++ mode, the code will use STL and ATL. In C mode, you can clearly see how everything is working behind the scene.

```<code>#include <Windows.h>
#include <objbase.h>
#include <conio.h> // for _getch()

#ifndef __cplusplus
#   include <stdio.h>

#define SafeFree(p, fn) \
    if (p) { fn(p); (p) = NULL; }

#define SafeFreeCOM(p) \
    if (p) { (p)->lpVtbl->Release(p); (p) = NULL; }

static HRESULT CorrectPathCasing2(
    LPCWSTR const pszSrc, LPWSTR *ppszDst)
{
    DWORD const clsCtx = CLSCTX_INPROC_SERVER;
    LCID const lcid = LOCALE_USER_DEFAULT;
    LPCWSTR const pszProgId = L"Scripting.FileSystemObject";
    LPCWSTR const pszMethod = L"GetAbsolutePathName";
    HRESULT hr = 0;
    CLSID clsid = { 0 };
    IDispatch *pDisp = NULL;
    DISPID dispid = 0;
    VARIANT vtSrc = { VT_BSTR };
    VARIANT vtDst = { VT_BSTR };
    DISPPARAMS params = { 0 };
    SIZE_T cbDst = 0;
    LPWSTR pszDst = NULL;

    // CoCreateInstance<IDispatch>(pszProgId, &pDisp)

    hr = CLSIDFromProgID(pszProgId, &clsid);
    if (FAILED(hr)) goto eof;

    hr = CoCreateInstance(&clsid, NULL, clsCtx,
        &IID_IDispatch, (void**)&pDisp);
    if (FAILED(hr)) goto eof;
    if (!pDisp) {
        hr = E_UNEXPECTED; goto eof;
    }

    // Variant<BSTR> vtSrc(pszSrc), vtDst;
    // vtDst = pDisp->InvokeMethod( pDisp->GetIDOfName(pszMethod), vtSrc );

    hr = pDisp->lpVtbl->GetIDsOfNames(pDisp, NULL,
        (LPOLESTR*)&pszMethod, 1, lcid, &dispid);
    if (FAILED(hr)) goto eof;

    vtSrc.bstrVal = SysAllocString(pszSrc);
    if (!vtSrc.bstrVal) {
        hr = E_OUTOFMEMORY; goto eof;
    }
    params.rgvarg = &vtSrc;
    params.cArgs = 1;
    hr = pDisp->lpVtbl->Invoke(pDisp, dispid, NULL, lcid,
        DISPATCH_METHOD, &params, &vtDst, NULL, NULL);
    if (FAILED(hr)) goto eof;
    if (!vtDst.bstrVal) {
        hr = E_UNEXPECTED; goto eof;
    }

    // *ppszDst = AllocWStrCopyBStrFrom(vtDst.bstrVal);

    cbDst = SysStringByteLen(vtDst.bstrVal);
    pszDst = HeapAlloc(GetProcessHeap(),
        HEAP_ZERO_MEMORY, cbDst + sizeof(WCHAR));
    if (!pszDst) {
        hr = E_OUTOFMEMORY; goto eof;
    }
    CopyMemory(pszDst, vtDst.bstrVal, cbDst);
    *ppszDst = pszDst;

eof:
    SafeFree(vtDst.bstrVal, SysFreeString);
    SafeFree(vtSrc.bstrVal, SysFreeString);
    SafeFreeCOM(pDisp);
    return hr;
}

static void Cout(char const *psz)
{
    printf("%s", psz);
}

static void CoutErr(HRESULT hr)
{
    printf("Error HRESULT 0x%.8X!\n", hr);
}

static void Test(LPCWSTR pszPath)
{
    LPWSTR pszRet = NULL;
    HRESULT hr = CorrectPathCasing2(pszPath, &pszRet);
    if (FAILED(hr)) {
        wprintf(L"Input: <%s>\n", pszPath);
        CoutErr(hr);
    }
    else {
        wprintf(L"Was: <%s>\nNow: <%s>\n", pszPath, pszRet);
        HeapFree(GetProcessHeap(), 0, pszRet);
    }
}

#else // Use C++ STL and ATL
#   include <iostream>
#   include <iomanip>
#   include <string>
#   include <atlbase.h>

static HRESULT CorrectPathCasing2(
    std::wstring const &srcPath,
    std::wstring &dstPath)
{
    HRESULT hr = 0;
    CComPtr<IDispatch> disp;
    hr = disp.CoCreateInstance(L"Scripting.FileSystemObject");
    if (FAILED(hr)) return hr;

    CComVariant src(srcPath.c_str()), dst;
    hr = disp.Invoke1(L"GetAbsolutePathName", &src, &dst);
    if (FAILED(hr)) return hr;

    SIZE_T cch = SysStringLen(dst.bstrVal);
    dstPath = std::wstring(dst.bstrVal, cch);
    return hr;
}

static void Cout(char const *psz)
{
    std::cout << psz;
}

static void CoutErr(HRESULT hr)
{
    std::wcout
        << std::hex << std::setfill(L'0') << std::setw(8)
        << "Error HRESULT 0x" << hr << "\n";
}

static void Test(std::wstring const &path)
{
    std::wstring output;
    HRESULT hr = CorrectPathCasing2(path, output);
    if (FAILED(hr)) {
        std::wcout << L"Input: <" << path << ">\n";
        CoutErr(hr);
    }
    else {
        std::wcout << L"Was: <" << path << ">\n"
            << "Now: <" << output << ">\n";
    }
}

#endif

static void TestRoutine(void)
{
    HRESULT hr = CoInitialize(NULL);

    if (FAILED(hr)) {
        Cout("CoInitialize failed!\n");
        CoutErr(hr);
        return;
    }

    Cout("\n[ Absolute Path ]\n");
    Test(L"c:\\uSers\\RayMai\\docuMENTs");
    Test(L"C:\\WINDOWS\\SYSTEM32");

    Cout("\n[ Relative Path ]\n");
    Test(L".");
    Test(L"..");
    Test(L"\\");

    Cout("\n[ UNC Path ]\n");
    Test(L"\\\\VMWARE-HOST\\SHARED FOLDERS\\D\\PROGRAMS INSTALLER");

    Cout("\n[ Very Long Path ]\n");
    Test(L"\\\\?\\C:\\VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME");

    Cout("\n!! Worth Nothing Behavior !!\n");
    Test(L"");
    Test(L"1234notexist");
    Test(L"C:\\bad\\PATH");

    CoUninitialize();
}

int main(void)
{
    TestRoutine();
    _getch();
    return 0;
}
</code>```

Screenshot:

Old Answer:

I found that FindFirstFile() will return the proper casing file name (last part of path) in fd.cFileName.  If we pass c:\winDOWs\exPLORER.exe as first parameter to FindFirstFile(), the fd.cFileName would be explorer.exe like this:

If we replace the last part of path with fd.cFileName, we will get the last part right; the path would become c:\winDOWs\explorer.exe.

Assuming the path is always absolute path (no change in text length), we can just apply this 'algorithm' to every part of path (except the drive letter part).

Talk is cheap, here is the code:

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

/*
    c:\windows\windowsupdate.log --> c:\windows\WindowsUpdate.log
*/
static HRESULT MyProcessLastPart(LPTSTR szPath)
{
    HRESULT hr = 0;
    HANDLE hFind = NULL;
    WIN32_FIND_DATA fd = {0};
    TCHAR *p = NULL, *q = NULL;
    /* thePart = GetCorrectCasingFileName(thePath); */
    hFind = FindFirstFile(szPath, &fd);
    if (hFind == INVALID_HANDLE_VALUE) {
        hr = HRESULT_FROM_WIN32(GetLastError());
        hFind = NULL; goto eof;
    }
    /* thePath = thePath.ReplaceLast(thePart); */
    for (p = szPath; *p; ++p);
    for (q = fd.cFileName; *q; ++q, --p);
    for (q = fd.cFileName; *p = *q; ++p, ++q);
eof:
    if (hFind) { FindClose(hFind); }
    return hr;
}

/*
    Important! 'szPath' should be absolute path only.
    MUST NOT SPECIFY relative path or UNC or short file name.
*/
EXTERN_C
HRESULT __stdcall
CorrectPathCasing(
    LPTSTR szPath)
{
    HRESULT hr = 0;
    TCHAR *p = NULL;
    if (GetFileAttributes(szPath) == -1) {
        hr = HRESULT_FROM_WIN32(GetLastError()); goto eof;
    }
    for (p = szPath; *p; ++p)
    {
        if (*p == '\\' || *p == '/')
        {
            TCHAR slashChar = *p;
            if (p[-1] == ':') /* p[-2] is drive letter */
            {
                p[-2] = toupper(p[-2]);
                continue;
            }
            *p = '\0';
            hr = MyProcessLastPart(szPath);
            *p = slashChar;
            if (FAILED(hr)) goto eof;
        }
    }
    hr = MyProcessLastPart(szPath);
eof:
    return hr;
}

int main()
{
    TCHAR szPath[] = TEXT("c:\\windows\\EXPLORER.exe");
    HRESULT hr = CorrectPathCasing(szPath);
    if (SUCCEEDED(hr))
    {
        MessageBox(NULL, szPath, TEXT("Test"), MB_ICONINFORMATION);
    }
    return 0;
}
</code>```

Advantages:

The code works on every version of Windows since Windows 95.

Basic error-handling.

Highest performance possible. FindFirstFile() is very fast, direct buffer manipulation makes it even faster.

Just C and pure WinAPI. Small executable size.

Disadvantages:

Only absolute path is supported, other are undefined behavior.

Not sure if it is relying on undocumented behavior.

The code might be too raw too much DIY for some people. Might get you flamed.

Reason behind the code style:

I use goto for error-handling because I was used to it (goto is very handy for error-handling in C). I use for loop to perform functions like strcpy and strchr on-the-fly because I want to be certain what was actually executed.

OwnerDisplayName: NeARAZ

LastEditorDisplayName: NeARAZ

Body:
Just found that the Scripting.FileSystemObject suggested by @bugmagnet 10 years ago is a treasure. Unlike my old method, it works on Absolute Path, Relative Path, UNC Path and Very Long Path (path longer than MAX_PATH). Shame on me for not testing his method earlier.

For future reference, I would like to present this code which can be compiled in both C and C++ mode. In C++ mode, the code will use STL and ATL. In C mode, you can clearly see how everything is working behind the scene.

#include <Windows.h>
#include <objbase.h>
#include <conio.h> // for _getch()

#ifndef __cplusplus
#   include <stdio.h>

#define SafeFree(p, fn) \
    if (p) { fn(p); (p) = NULL; }

#define SafeFreeCOM(p) \
    if (p) { (p)->lpVtbl->Release(p); (p) = NULL; }

static HRESULT CorrectPathCasing2(
    LPCWSTR const pszSrc, LPWSTR *ppszDst)
{
    DWORD const clsCtx = CLSCTX_INPROC_SERVER;
    LCID const lcid = LOCALE_USER_DEFAULT;
    LPCWSTR const pszProgId = L"Scripting.FileSystemObject";
    LPCWSTR const pszMethod = L"GetAbsolutePathName";
    HRESULT hr = 0;
    CLSID clsid = { 0 };
    IDispatch *pDisp = NULL;
    DISPID dispid = 0;
    VARIANT vtSrc = { VT_BSTR };
    VARIANT vtDst = { VT_BSTR };
    DISPPARAMS params = { 0 };
    SIZE_T cbDst = 0;
    LPWSTR pszDst = NULL;

    // CoCreateInstance<IDispatch>(pszProgId, &pDisp)

    hr = CLSIDFromProgID(pszProgId, &clsid);
    if (FAILED(hr)) goto eof;

    hr = CoCreateInstance(&clsid, NULL, clsCtx,
        &IID_IDispatch, (void**)&pDisp);
    if (FAILED(hr)) goto eof;
    if (!pDisp) {
        hr = E_UNEXPECTED; goto eof;
    }

    // Variant<BSTR> vtSrc(pszSrc), vtDst;
    // vtDst = pDisp->InvokeMethod( pDisp->GetIDOfName(pszMethod), vtSrc );

    hr = pDisp->lpVtbl->GetIDsOfNames(pDisp, NULL,
        (LPOLESTR*)&pszMethod, 1, lcid, &dispid);
    if (FAILED(hr)) goto eof;

    vtSrc.bstrVal = SysAllocString(pszSrc);
    if (!vtSrc.bstrVal) {
        hr = E_OUTOFMEMORY; goto eof;
    }
    params.rgvarg = &vtSrc;
    params.cArgs = 1;
    hr = pDisp->lpVtbl->Invoke(pDisp, dispid, NULL, lcid,
        DISPATCH_METHOD, &params, &vtDst, NULL, NULL);
    if (FAILED(hr)) goto eof;
    if (!vtDst.bstrVal) {
        hr = E_UNEXPECTED; goto eof;
    }

    // *ppszDst = AllocWStrCopyBStrFrom(vtDst.bstrVal);

    cbDst = SysStringByteLen(vtDst.bstrVal);
    pszDst = HeapAlloc(GetProcessHeap(),
        HEAP_ZERO_MEMORY, cbDst + sizeof(WCHAR));
    if (!pszDst) {
        hr = E_OUTOFMEMORY; goto eof;
    }
    CopyMemory(pszDst, vtDst.bstrVal, cbDst);
    *ppszDst = pszDst;

eof:
    SafeFree(vtDst.bstrVal, SysFreeString);
    SafeFree(vtSrc.bstrVal, SysFreeString);
    SafeFreeCOM(pDisp);
    return hr;
}

static void Cout(char const *psz)
{
    printf("%s", psz);
}

static void CoutErr(HRESULT hr)
{
    printf("Error HRESULT 0x%.8X!\n", hr);
}

static void Test(LPCWSTR pszPath)
{
    LPWSTR pszRet = NULL;
    HRESULT hr = CorrectPathCasing2(pszPath, &pszRet);
    if (FAILED(hr)) {
        wprintf(L"Input: <%s>\n", pszPath);
        CoutErr(hr);
    }
    else {
        wprintf(L"Was: <%s>\nNow: <%s>\n", pszPath, pszRet);
        HeapFree(GetProcessHeap(), 0, pszRet);
    }
}

#else // Use C++ STL and ATL
#   include <iostream>
#   include <iomanip>
#   include <string>
#   include <atlbase.h>

static HRESULT CorrectPathCasing2(
    std::wstring const &srcPath,
    std::wstring &dstPath)
{
    HRESULT hr = 0;
    CComPtr<IDispatch> disp;
    hr = disp.CoCreateInstance(L"Scripting.FileSystemObject");
    if (FAILED(hr)) return hr;

    CComVariant src(srcPath.c_str()), dst;
    hr = disp.Invoke1(L"GetAbsolutePathName", &src, &dst);
    if (FAILED(hr)) return hr;

    SIZE_T cch = SysStringLen(dst.bstrVal);
    dstPath = std::wstring(dst.bstrVal, cch);
    return hr;
}

static void Cout(char const *psz)
{
    std::cout << psz;
}

static void CoutErr(HRESULT hr)
{
    std::wcout
        << std::hex << std::setfill(L'0') << std::setw(8)
        << "Error HRESULT 0x" << hr << "\n";
}

static void Test(std::wstring const &path)
{
    std::wstring output;
    HRESULT hr = CorrectPathCasing2(path, output);
    if (FAILED(hr)) {
        std::wcout << L"Input: <" << path << ">\n";
        CoutErr(hr);
    }
    else {
        std::wcout << L"Was: <" << path << ">\n"
            << "Now: <" << output << ">\n";
    }
}

#endif

static void TestRoutine(void)
{
    HRESULT hr = CoInitialize(NULL);

    if (FAILED(hr)) {
        Cout("CoInitialize failed!\n");
        CoutErr(hr);
        return;
    }

    Cout("\n[ Absolute Path ]\n");
    Test(L"c:\\uSers\\RayMai\\docuMENTs");
    Test(L"C:\\WINDOWS\\SYSTEM32");

    Cout("\n[ Relative Path ]\n");
    Test(L".");
    Test(L"..");
    Test(L"\\");

    Cout("\n[ UNC Path ]\n");
    Test(L"\\\\VMWARE-HOST\\SHARED FOLDERS\\D\\PROGRAMS INSTALLER");

    Cout("\n[ Very Long Path ]\n");
    Test(L"\\\\?\\C:\\VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME");

    Cout("\n!! Worth Nothing Behavior !!\n");
    Test(L"");
    Test(L"1234notexist");
    Test(L"C:\\bad\\PATH");

    CoUninitialize();
}

int main(void)
{
    TestRoutine();
    _getch();
    return 0;
}

Screenshot:

Old Answer:

I found that FindFirstFile() will return the proper casing file name (last part of path) in fd.cFileName.  If we pass c:\winDOWs\exPLORER.exe as first parameter to FindFirstFile(), the fd.cFileName would be explorer.exe like this:

If we replace the last part of path with fd.cFileName, we will get the last part right; the path would become c:\winDOWs\explorer.exe.

Assuming the path is always absolute path (no change in text length), we can just apply this 'algorithm' to every part of path (except the drive letter part).

Talk is cheap, here is the code:

#include <windows.h>
#include <stdio.h>

/*
    c:\windows\windowsupdate.log --> c:\windows\WindowsUpdate.log
*/
static HRESULT MyProcessLastPart(LPTSTR szPath)
{
    HRESULT hr = 0;
    HANDLE hFind = NULL;
    WIN32_FIND_DATA fd = {0};
    TCHAR *p = NULL, *q = NULL;
    /* thePart = GetCorrectCasingFileName(thePath); */
    hFind = FindFirstFile(szPath, &fd);
    if (hFind == INVALID_HANDLE_VALUE) {
        hr = HRESULT_FROM_WIN32(GetLastError());
        hFind = NULL; goto eof;
    }
    /* thePath = thePath.ReplaceLast(thePart); */
    for (p = szPath; *p; ++p);
    for (q = fd.cFileName; *q; ++q, --p);
    for (q = fd.cFileName; *p = *q; ++p, ++q);
eof:
    if (hFind) { FindClose(hFind); }
    return hr;
}

/*
    Important! 'szPath' should be absolute path only.
    MUST NOT SPECIFY relative path or UNC or short file name.
*/
EXTERN_C
HRESULT __stdcall
CorrectPathCasing(
    LPTSTR szPath)
{
    HRESULT hr = 0;
    TCHAR *p = NULL;
    if (GetFileAttributes(szPath) == -1) {
        hr = HRESULT_FROM_WIN32(GetLastError()); goto eof;
    }
    for (p = szPath; *p; ++p)
    {
        if (*p == '\\' || *p == '/')
        {
            TCHAR slashChar = *p;
            if (p[-1] == ':') /* p[-2] is drive letter */
            {
                p[-2] = toupper(p[-2]);
                continue;
            }
            *p = '\0';
            hr = MyProcessLastPart(szPath);
            *p = slashChar;
            if (FAILED(hr)) goto eof;
        }
    }
    hr = MyProcessLastPart(szPath);
eof:
    return hr;
}

int main()
{
    TCHAR szPath[] = TEXT("c:\\windows\\EXPLORER.exe");
    HRESULT hr = CorrectPathCasing(szPath);
    if (SUCCEEDED(hr))
    {
        MessageBox(NULL, szPath, TEXT("Test"), MB_ICONINFORMATION);
    }
    return 0;
}

Advantages:

The code works on every version of Windows since Windows 95.

Basic error-handling.

Highest performance possible. FindFirstFile() is very fast, direct buffer manipulation makes it even faster.

Just C and pure WinAPI. Small executable size.

Disadvantages:

Only absolute path is supported, other are undefined behavior.

Not sure if it is relying on undocumented behavior.

The code might be too raw too much DIY for some people. Might get you flamed.

Reason behind the code style:

I use goto for error-handling because I was used to it (goto is very handy for error-handling in C). I use for loop to perform functions like strcpy and strchr on-the-fly because I want to be certain what was actually executed.


问:
Better way to register ItemBlock than what I have here?
So, I am trying to get an ItemBlock to register alongside my Block when it gets registered. I have come up with this so far. Is there a better way to be doing this?  I'm not really happy with the itemBlock.setRegistryName part inside registerBlock() !

```<code>public class ModBlocks {

    public static Block tinBlock;

    public static void init(){
        tinBlock = new BlockTinBlock("tin_block", "tin_block");
    }

    public static void register(){
        registerBlock(tinBlock);
    }

    public static void registerRenders(){
        registerRender(tinBlock);
    }

    public static void registerBlock(Block block){
        GameRegistry.register(block);
        ItemBlock itemBlock = new ItemBlock(block);
        itemBlock.setRegistryName(Reference.MODID, block.getUnlocalizedName().substring(5));
        GameRegistry.register(itemBlock);
    }

    public static void registerRender(Block block){
        ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(block), 0, new ModelResourceLocation(new ResourceLocation(Reference.MODID, block.getUnlocalizedName().substring(5)), "inventory"));
    }
}
</code>```

答:
What you are doing is pretty much it, but for the registration of Blocks, Items and Models etc. you should use the corresponding event:

To do this you will need an Event listener listening for the Event.

An event listener is a function that takes the Event as the parameter and is Annotated @SubscribeEvent  they can either be located in your @Mod class
or in classes Annotated  @Mod.EventBusSubscriber(modid = "yourmodid")

To register Blocks, Items and Models in a separate class you would write something like this:

```<code>@Mod.EventBusSubscriber(modid = "yourmodid")
public class Registration{
    @SubscribeEvent
    public static void registerBlocks(RegistryEvent.Register<Block> event) {
        IForgeRegistry registry = event.getRegistry();
        //register blocks here using registry
    }

    @SubscribeEvent
    public static void registerItems(RegistryEvent.Register<Item> event) {
        //register items here like we did with the blocks
    }

    @SideOnly(Side.CLIENT)
    @SubscribeEvent
    public static void initModels(ModelRegistryEvent event) {
        //register models here
    }
}
</code>```

More information on this subject can be found in the official Minecraft Forge Documentation that can be found here.

Body:
So, I am trying to get an ItemBlock to register alongside my Block when it gets registered. I have come up with this so far. Is there a better way to be doing this?  I'm not really happy with the itemBlock.setRegistryName part inside registerBlock() !

public class ModBlocks {

    public static Block tinBlock;

    public static void init(){
        tinBlock = new BlockTinBlock("tin_block", "tin_block");
    }

    public static void register(){
        registerBlock(tinBlock);
    }

    public static void registerRenders(){
        registerRender(tinBlock);
    }

    public static void registerBlock(Block block){
        GameRegistry.register(block);
        ItemBlock itemBlock = new ItemBlock(block);
        itemBlock.setRegistryName(Reference.MODID, block.getUnlocalizedName().substring(5));
        GameRegistry.register(itemBlock);
    }

    public static void registerRender(Block block){
        ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(block), 0, new ModelResourceLocation(new ResourceLocation(Reference.MODID, block.getUnlocalizedName().substring(5)), "inventory"));
    }
}

Body:
What you are doing is pretty much it, but for the registration of Blocks, Items and Models etc. you should use the corresponding event:

To do this you will need an Event listener listening for the Event.

An event listener is a function that takes the Event as the parameter and is Annotated @SubscribeEvent  they can either be located in your @Mod class
or in classes Annotated  @Mod.EventBusSubscriber(modid = "yourmodid")

To register Blocks, Items and Models in a separate class you would write something like this:

@Mod.EventBusSubscriber(modid = "yourmodid")
public class Registration{
    @SubscribeEvent
    public static void registerBlocks(RegistryEvent.Register<Block> event) {
        IForgeRegistry registry = event.getRegistry();
        //register blocks here using registry
    }

    @SubscribeEvent
    public static void registerItems(RegistryEvent.Register<Item> event) {
        //register items here like we did with the blocks
    }

    @SideOnly(Side.CLIENT)
    @SubscribeEvent
    public static void initModels(ModelRegistryEvent event) {
        //register models here
    }
}

More information on this subject can be found in the official Minecraft Forge Documentation that can be found here.


问:
Owl Carousel 2 - autoHeight (multiple items)
At the moment the Owl Carousel autoHeight works only with 1 item on screen. Their plan is to calculate all visible items and change height according to highest item.

I work around this problem by calling the .active classes on the visible items, and give the invisible items a small height. Is there already a more elegant solution?

```<code>$('.owl-carousel').owlCarousel({
loop: true,
items: 3,
margin: 1,
autoHeight: true,
});
</code>```

Fiddle

Any Ideas? Thanks!

答:
I had same issue. I only resolved adding a autoWidth:true,  and it works now!

My owl script is:

```<code> $('.owl-carousel').owlCarousel({
  loop: false,
  margin: 10,
  items: 1,
  autoHeight: true,
  autoWidth: true,
  nav: true,
  navText: [
    "<i class='fa fa-caret-left'></i>",
    "<i class='fa fa-caret-right'></i>"
  ],
  autoplay: true,
  autoplayHoverPause: true,
  responsive: {
    0: {
      items: 1
    },
    600: {
      items: 3
    },
    1000: {
      items: 5
    }
  }
})
</code>```

Body:
At the moment the Owl Carousel autoHeight works only with 1 item on screen. Their plan is to calculate all visible items and change height according to highest item.

I work around this problem by calling the .active classes on the visible items, and give the invisible items a small height. Is there already a more elegant solution?

$('.owl-carousel').owlCarousel({
loop: true,
items: 3,
margin: 1,
autoHeight: true,
});

Fiddle

Any Ideas? Thanks!

Body:
I had same issue. I only resolved adding a autoWidth:true,  and it works now!

My owl script is:

 $('.owl-carousel').owlCarousel({
  loop: false,
  margin: 10,
  items: 1,
  autoHeight: true,
  autoWidth: true,
  nav: true,
  navText: [
    "<i class='fa fa-caret-left'></i>",
    "<i class='fa fa-caret-right'></i>"
  ],
  autoplay: true,
  autoplayHoverPause: true,
  responsive: {
    0: {
      items: 1
    },
    600: {
      items: 3
    },
    1000: {
      items: 5
    }
  }
})


问:
Python list: Copy single list to 2D list
how can i copy a single dimensional list to a two dimensional list?</p>

```<code>import copy
dataList=[1,2,3,4,5]
multiList=([[],[],[],[],[]])

multiList = copy.deepcopy(dataList)
print(multiList[0][0])
</code>```

答:
```<code>import copy
dataList=[1,2,3,4,5]
multiList=([[],[],[],[],[]])

multiList[0] = copy.deepcopy(dataList)

dataList[0] = 7
print dataList
print(multiList)
</code>```

Its trivial - I suggest to delete the question :)

Output:

```<code> [7, 2, 3, 4, 5]
[[1, 2, 3, 4, 5], [], [], [], []]
</code>```

Body:
how can i copy a single dimensional list to a two dimensional list?

import copy
dataList=[1,2,3,4,5]
multiList=([[],[],[],[],[]])

multiList = copy.deepcopy(dataList)
print(multiList[0][0])

Body:
import copy
dataList=[1,2,3,4,5]
multiList=([[],[],[],[],[]])

multiList[0] = copy.deepcopy(dataList)

dataList[0] = 7
print dataList
print(multiList)

Its trivial - I suggest to delete the question :)

Output:

 [7, 2, 3, 4, 5]
[[1, 2, 3, 4, 5], [], [], [], []]


问:
Find two rectangles with minimum areas that cover all points
You're given a n points, unsorted in an array. You're supposed to find two rectangles that cover all points and they should not overlap. Edges of rectangles should be parallel to x or y ordinate.

The program should return the minimum area covered by all these dots. Area of first rectangle + area of second rectangle.

I tried to solve this problem. I sorted points by X ordinate and the first one is the leftmost one of the first rectangle. When we go through the points we find the highest and lowest one. I was thinking that when the difference between two points by x is the biggest, that means that the first point is rightmost one of the first rectangle, and the second point is the leftmost one of the second rectangle.

It should work when the points are given as in first example, however, if the example is the second one it doesn't work. As it would return something like this and that's wrong:

This should be correct:

Then i was thinking doing sorting twice, just, the second time do it by Y ordinate and then compare two total areas. Areas when points are sorted by x and when points are sorted by y and the smaller area is the correct answer.

答:
The first observation is that any edge of a rectangle must touch one of the points. Edges that didn't touch a point could be pulled back, resulting in less area.

Given n points, there are thus n selections total for left1, right1, bottom1, top1, left2, right2, bottom2 and top2. This gives a simple O(n^8) algorithm already: try all possible assignments and remember the one giving the least total area (right1 - left1)(top1 - bottom1) + (right2 - left2)(top2 - bottom2). Indeed, you can skip any combinations with right < left or top < bottom. This gives a speedup, though it does not change the O(n^8) bound.

Another observation is that the edges should stay within the minimum and maximum X and Y bounds of all points. Find the minimum and maximum X and Y values of any points. Call these minX, maxX, minY and maxY. At least one of your rectangles will need to have its left, right, bottom and top edges, respectively, at those levels.

Because minx, maxX, minY and maxY must be assigned to one of the two rectangles, and there are exactly 2^4 = 16 ways to do this, you can try each of the four possible assignments with the remaining coordinates assigned as above. This gives an O(n^4) algorithm: O(n) to get minX, maxX, minY and maxY, and then O(n^4) to fill in the four unassigned variables for each of 16 assignments of minX, maxX, minY and maxY to the eight edge coordinates.

We have so far ignored the requirement that rectangles not overlap. To accommodate that, we must ensure at least one of the following four conditions holds true:

a horizontal line at Y coordinate h with top1 <= h <= bottom2

a horizontal line at Y coordinate h with top2 <= h <= bottom1

a vertical line at X coordinate w with right1 <= h <= left2

a vertical line at X coordinate w with right2 <= h <= left1

The two rectangles overlap if and only if all four of these conditions are simultaneously false. This allows us to skip over candidate solutions, giving a speedup but not changing the asymptotic bound O(n^4). Note that we need to check this condition specifically since, otherwise, optimal solutions might have overlap (exercise: show such an example).

Let's try to shave some more time off of this. Assume we have non-overlapping rectangles by condition #1 above. Then there are n choices for h; we can try each of these n choices and then determine the area of the resulting selections by finding the minimum and maximum coordinates of points in the resulting halves. By trying all n selections for h, we can determine the "best case" vertical split. We need not try condition #2, since the only difference is in the ordering of the rectangles which is arbitrary. We must also try condition #3 with a horizontal split. This suggests an O(n^2) algorithm:

For each point, choose h = point.y

Separate the points into groups with point.y <= h and point.y > h.

Find the minimum and maximum X and Y coordinates of both subsets of points.

Compute the sum of the areas of the two rectangles.

Remember the minimum area obtained from the above and the corresponding h.

Repeat, but using w and X coordinates.

Determine whether minimum area was obtained for a vertical or horizontal split

Return the corresponding rectangles as the answer

Can we do even better? This is O(n^2) and not O(n) because for each choice of h and w we need to then find the minimum and maximum coordinates of each subgroup. This assumes a linear scan through both subgroups. We don't actually need to do this for the min and max X/Y coordinates when scanning horizontally/vertically, since those will be known. What we need is a solution to this problem:

Given n points and a value h, find the maximum X coordinate of any point whose Y coordinate is no greater than h.

The obvious solution I give above is O(n^2), but you might be able to find an O(n log n) solution by clever application of sorting or maybe even an O(n) solution by some even more clever method. I will not attempt this.

Our solution is O(n^2); the theoretically optimal solution is Omega(n) since you must at least look at all the points. So we're pretty close but there is room for improvement.