问:
Robot Framework test case naming convention and running with bat-file
I have a question about Robot Framework test case naming conventions and running a test case with .bat-file on Windows-10 laptop.
During my limited experience of working with Robot Framework I have been mostly using RIDE-editor and there has not been many problems when running with that.

When looking at test case naming conventions in a link below a good way seems to be to put
space between words. Very simple example being Open Browser so there is a space between those
two words belonging to a test case name. Longer example would be Empty Username And Password                                                                  I personally like that kind of style with spaces.

https://github.com/robotframework/HowToWriteGoodTestCases/blob/master/HowToWriteGoodTestCases.rst#test-case-names

However I noticed that if I try to run from .bat-file like this.

robot -t testcasename testsuitename.robot

```<code>@echo off
cd C:\Users\developer\Robot
robot -t Open Browser Demosuite.robot
</code>```

Then command prompt just blinks shortly before disappearing and running test case like that does not work. When running with RIDE-editor there is no problem with running.

But if I rename test case like this.

```<code>@echo off
cd C:\Users\developer\Robot
robot -t Open_Browser Demosuite.robot
</code>```

That works. So is this expected behaviour that it should not work with spaces when running from .bat?

Robot Framework-code:

```<code>Resource          Resources/CommonResources.robot

*** Test Cases ***
Open Browser
    Open Browser    https://www.google.com    Firefox
</code>```

答:
The problem is related to how windows and other operating systems handle arguments on the command line. Windows knows nothing about robot and doesn't know anything about the -t argument or what it expects. When it sees robot -t Open Browser Demosuite.robot it sees the following:

```<code>* command name: robot
* argument 1: -t
* argument 2: Open
* argument 3: Browser
* argument 4: Demosuite.robot
</code>```

Notice that "Open" and "Browser" are treated as two separate arguments.

Passing arguments with spaces, whether with robot or any other command line tool, requires that you use quotes. In your case you could do robot -t "Open Browser" Demosuite.robot, or as you observed you can use an underscore in place of the space which robot (and likely only robot) will convert to spaces for you.

Body:
I have a question about Robot Framework test case naming conventions and running a test case with .bat-file on Windows-10 laptop.
During my limited experience of working with Robot Framework I have been mostly using RIDE-editor and there has not been many problems when running with that.

When looking at test case naming conventions in a link below a good way seems to be to put
space between words. Very simple example being Open Browser so there is a space between those
two words belonging to a test case name. Longer example would be Empty Username And Password                                                                  I personally like that kind of style with spaces.

https://github.com/robotframework/HowToWriteGoodTestCases/blob/master/HowToWriteGoodTestCases.rst#test-case-names

However I noticed that if I try to run from .bat-file like this.

robot -t testcasename testsuitename.robot

@echo off
cd C:\Users\developer\Robot
robot -t Open Browser Demosuite.robot

Then command prompt just blinks shortly before disappearing and running test case like that does not work. When running with RIDE-editor there is no problem with running.

But if I rename test case like this.

@echo off
cd C:\Users\developer\Robot
robot -t Open_Browser Demosuite.robot

That works. So is this expected behaviour that it should not work with spaces when running from .bat?

Robot Framework-code:

Resource          Resources/CommonResources.robot

*** Test Cases ***
Open Browser
    Open Browser    https://www.google.com    Firefox

Body:
The problem is related to how windows and other operating systems handle arguments on the command line. Windows knows nothing about robot and doesn't know anything about the -t argument or what it expects. When it sees robot -t Open Browser Demosuite.robot it sees the following:

* command name: robot
* argument 1: -t
* argument 2: Open
* argument 3: Browser
* argument 4: Demosuite.robot

Notice that "Open" and "Browser" are treated as two separate arguments.

Passing arguments with spaces, whether with robot or any other command line tool, requires that you use quotes. In your case you could do robot -t "Open Browser" Demosuite.robot, or as you observed you can use an underscore in place of the space which robot (and likely only robot) will convert to spaces for you.


来源: stackexchange

问:
Recursive jQuery submit function doesn't submit the form
I need some code to run right after the submit button has been clicked and before the form has actually been submitted.
I've stripped the code and left only the parts needed to show you the problem.
What I need the code to do is go inside the submit function, but instead of submitting the form call the function again.
The form should submit only in that second iteration.
Except it doesn't. The code is fully executed as it should but the form doesn't submit in the end.

I would appreciate it if someone can explain why.

Here's the code (simplr-reg's the form's name):

```<code><script>

var reallySubmit = false;

$(‘#simplr-reg’).submit(function(event)
{
   if (false == reallySubmit)
   {
      reallySubmit = true;
      $(‘#simplr-reg’).submit();
      event.preventDefault();
      return false;
   }
   else
   {
      return true;
   }
});

</script>
</code>```

答:
Change it from a 'submit' event to a 'click' event and attach it to the button itself rather than the form?

ETA: be sure to 'return false' on your non-submit case.

```<code>$("#simplr-reg-submit").click(function()
{
      alert("1st iteration");
      $("#simplr-reg").submit();
       return false;
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Change it from a 'submit' event to a 'click' event and attach it to the button itself rather than the form?

ETA: be sure to 'return false' on your non-submit case.

$("#simplr-reg-submit").click(function()
{
      alert("1st iteration");
      $("#simplr-reg").submit();
       return false;
});


问:
Using ffmpeg to overlay black line or add border to two side by side videos
I am using the following to generate a video that is side by side.

```<code>ffmpeg -i left.mp4 -i right.mp4 -filter_complex "[0:v]setpts=PTS-STARTPTS, pad=iw*2:ih[bg]; [1:v]setpts=PTS-STARTPTS[fg]; [bg][fg]overlay=w" -y final.mp4
</code>```

It looks like this.

http://www.mo-de.net/d/partnerAcrobatics.mp4

I would like to place a vertical black line on top right in the middle or add a black border to the video on the left.  If I add a border to the left video I would like to maintain the original sum dimension of the original videos.  This solution would require subtracting the border width from the left videos width.  I will take either solution.

Thanks

答:
Since you've already joined the videos, seems like you wanna separate them with a vertical black line.

Since this line is stationary (inanimate), this overlay can be a still picture, eg. black.png (10px wide & same height as your video)

If you want this line to be animated or a moving picture, then the overlay can be another video.

If the videos had NOT been joined, you could pad the 2nd video on the left or 1st video on the right, before joining
eg. ffmpeg -i 1.mp4 -vf "pad=width=<new width>:height=<same height>:color=black" out.mp4

The code below answers your question, with a vertical line of width 10 pixels in the middle, separating the 2 videos:

ffmpeg -i in.mp4 -i black.png -filter_complex "overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2" out.mp4

Body:
I am using the following to generate a video that is side by side.

ffmpeg -i left.mp4 -i right.mp4 -filter_complex "[0:v]setpts=PTS-STARTPTS, pad=iw*2:ih[bg]; [1:v]setpts=PTS-STARTPTS[fg]; [bg][fg]overlay=w" -y final.mp4

It looks like this.

http://www.mo-de.net/d/partnerAcrobatics.mp4

I would like to place a vertical black line on top right in the middle or add a black border to the video on the left.  If I add a border to the left video I would like to maintain the original sum dimension of the original videos.  This solution would require subtracting the border width from the left videos width.  I will take either solution.

Thanks

ContentLicense: CC BY-SA 4.0


问:
Getting if a Column is nullable (declared as not null or implicit declared nullable) using SqlClient on C#
I have this code which shows the database I created using SqlClient, but I don't know how I could check if a column was added as nullable or not nullable in the table.

```<code>string[] defaultTables = { "AspNetUsers", "AspNetRoleClaims", "AspNetUserClaims", "AspNetUserLogins", "AspNetUserRoles", "AspNetUserTokens", "AspNetRoles", "__EFMigrationsHistory" };
dblist.ForEach((string DbName) => {
    strConnection = $@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog={DbName};Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";

    using (SqlConnection conn = new SqlConnection(strConnection)) {
        conn.Open();
        using (cmdSql = new SqlCommand(strConnection, conn)) {
            DataTable dt = conn.GetSchema("Tables");

            foreach (DataRow row in dt.Rows) {
                string tablename = row[2].ToString();
                if (!defaultTables.Any(x => x == tablename)) {
                    tables.Add(tablename);

                    using (cmdSql = new SqlCommand($"Select * FROM {tablename}", conn)) {
                        SqlDataReader reader = cmdSql.ExecuteReader();
                        if (reader.Read()) {
                            for (int i = 0; i < reader.FieldCount; i++)
                                Console.Write(reader.GetName(i) + " " + reader.GetDataTypeName(i) + $"" + ',');
                        }
                    }
                }
            }
        }
    }
});
</code>```

答:
Your approach seems a bit complicated to extract that kind of information. We have the INFORMATION_SCHEMA views in the database that contains exactly the information required.

So for example:

```<code>using(SqlConnection con = new SqlConnection(.....))
{
    con.Open();
    DataTable dt = new DataTable();

    // Get info on all tables...
    SqlCommand cmd = new SqlCommand(@"SELECT * FROM INFORMATION_SCHEMA.TABLES
                                      WHERE TABLE_TYPE = 'BASE TABLE'", con);
    dt.Load(cmd.ExecuteReader());
    foreach (DataRow r in dt.Rows)
    {
        // Get info on the current table's columns
        string sqltext = $"SELECT * FROM INFORMATION_SCHEMA.Columns
                           WHERE TABLE_NAME = '{r.Field<string>("TABLE_NAME")}'";
        SqlCommand cmd1 = new SqlCommand(sqltext, con);
        DataTable dt1 = new DataTable();
        dt1.Load(cmd1.ExecuteReader());
        foreach (DataRow x in dt1.Rows)
        {
            Console.WriteLine($"Table:{x.Field<string>("TABLE_NAME")}");
            Console.WriteLine($"Column:{x.Field<string>("COLUMN_NAME")}");
            Console.WriteLine($"Data type:{x.Field<string>("DATA_TYPE")}");
            Console.WriteLine($"Nullable:{x.Field<string>("IS_NULLABLE")}");
        }
    }
</code>```

Body:
I have this code which shows the database I created using SqlClient, but I don't know how I could check if a column was added as nullable or not nullable in the table.

string[] defaultTables = { "AspNetUsers", "AspNetRoleClaims", "AspNetUserClaims", "AspNetUserLogins", "AspNetUserRoles", "AspNetUserTokens", "AspNetRoles", "__EFMigrationsHistory" };
dblist.ForEach((string DbName) => {
    strConnection = $@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog={DbName};Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";

    using (SqlConnection conn = new SqlConnection(strConnection)) {
        conn.Open();
        using (cmdSql = new SqlCommand(strConnection, conn)) {
            DataTable dt = conn.GetSchema("Tables");

            foreach (DataRow row in dt.Rows) {
                string tablename = row[2].ToString();
                if (!defaultTables.Any(x => x == tablename)) {
                    tables.Add(tablename);

                    using (cmdSql = new SqlCommand($"Select * FROM {tablename}", conn)) {
                        SqlDataReader reader = cmdSql.ExecuteReader();
                        if (reader.Read()) {
                            for (int i = 0; i < reader.FieldCount; i++)
                                Console.Write(reader.GetName(i) + " " + reader.GetDataTypeName(i) + $"" + ',');
                        }
                    }
                }
            }
        }
    }
});

Body:
Your approach seems a bit complicated to extract that kind of information. We have the INFORMATION_SCHEMA views in the database that contains exactly the information required.

So for example:

using(SqlConnection con = new SqlConnection(.....))
{
    con.Open();
    DataTable dt = new DataTable();

    // Get info on all tables...
    SqlCommand cmd = new SqlCommand(@"SELECT * FROM INFORMATION_SCHEMA.TABLES
                                      WHERE TABLE_TYPE = 'BASE TABLE'", con);
    dt.Load(cmd.ExecuteReader());
    foreach (DataRow r in dt.Rows)
    {
        // Get info on the current table's columns
        string sqltext = $"SELECT * FROM INFORMATION_SCHEMA.Columns
                           WHERE TABLE_NAME = '{r.Field<string>("TABLE_NAME")}'";
        SqlCommand cmd1 = new SqlCommand(sqltext, con);
        DataTable dt1 = new DataTable();
        dt1.Load(cmd1.ExecuteReader());
        foreach (DataRow x in dt1.Rows)
        {
            Console.WriteLine($"Table:{x.Field<string>("TABLE_NAME")}");
            Console.WriteLine($"Column:{x.Field<string>("COLUMN_NAME")}");
            Console.WriteLine($"Data type:{x.Field<string>("DATA_TYPE")}");
            Console.WriteLine($"Nullable:{x.Field<string>("IS_NULLABLE")}");
        }
    }


问:
How to get CSV integers read as integers from a string variable
I have a string that I get from sanitizing some values from an xml file.

```<code>$resolutions=strip_tags($resolutions,allow);  // gives me '75 75 300 300 600 600'
</code>```

Then I change the spaces to commas:

```<code>$resolutions = preg_replace('#\s+#',',',trim($resolutions)); // gives me '75,75,300,300,600,600'
</code>```

Then I take that and want to extract min and max values like this

```<code>$resolution_min = min($resolutions);
</code>```

on the page for display

```<code>echo $resolution_min; // still gives me '75,75,300,300,600,600'
</code>```

However when I  change the code where I want it displayed on the page

```<code> echo min(75,75,300,300,600,600);  // it displays '75' as it should
</code>```

I think, the issue is that the CSV values are being interpreted as a single text string and I need them read as CSV integer values.

Is there some way to force these to be read as numeric values by min and max?

I think part of my problem comes from this line or a line like it, jus befor an "explode" command

```<code>$list = "" . substr($scansupportedresolutions, $start,$length) . "";
</code>```

I have never seen this kind of double double quote dot and dot double double quote and have no idea what it means

Is it simply saying the entire string in $list will be

```<code>".<CONTENT HERE>."
</code>```

but specifically in double quotes? Whatever it is i seems crucial to the explode command.

答:
AbraCadaver is correct in his answer.

I have tried to improve your code. Take a look

```<code><?php
// After Stripping tag
$resolutions = "75 75 300 300 600 600";
// No need to conver to Space to comma
$resolutionsArray = explode(" ", $resolutions);
$resolutionMin = min($resolutionsArray);
print($resolutionMin);
</code>```

There is no gain by converting the "white Space" to "Comma". You can explode the string into array by setting "white Space" as delimiter.

Hope it helps you.

Body:
I have a string that I get from sanitizing some values from an xml file.

$resolutions=strip_tags($resolutions,allow);  // gives me '75 75 300 300 600 600'

Then I change the spaces to commas:

$resolutions = preg_replace('#\s+#',',',trim($resolutions)); // gives me '75,75,300,300,600,600'

Then I take that and want to extract min and max values like this

$resolution_min = min($resolutions);

on the page for display

echo $resolution_min; // still gives me '75,75,300,300,600,600'

However when I  change the code where I want it displayed on the page

 echo min(75,75,300,300,600,600);  // it displays '75' as it should

I think, the issue is that the CSV values are being interpreted as a single text string and I need them read as CSV integer values.

Is there some way to force these to be read as numeric values by min and max?

I think part of my problem comes from this line or a line like it, jus befor an "explode" command

$list = "" . substr($scansupportedresolutions, $start,$length) . "";

I have never seen this kind of double double quote dot and dot double double quote and have no idea what it means

Is it simply saying the entire string in $list will be

".<CONTENT HERE>."

but specifically in double quotes? Whatever it is i seems crucial to the explode command.

Body:
AbraCadaver is correct in his answer.

I have tried to improve your code. Take a look

<?php
// After Stripping tag
$resolutions = "75 75 300 300 600 600";
// No need to conver to Space to comma
$resolutionsArray = explode(" ", $resolutions);
$resolutionMin = min($resolutionsArray);
print($resolutionMin);

There is no gain by converting the "white Space" to "Comma". You can explode the string into array by setting "white Space" as delimiter.

Hope it helps you.


问:
Lock orientation (Portrait) on VueJS PWA for all browsers
I am trying to get a screen lock to work for my web application.
I have been searching the forums but cant find a solution to this problem.

Does anybody know how I can tackle this problem?

Problem solved with a css fix.

答:
Currently PWAs do not have an overall working solution and I think the CSS approach is not very satisfying.

But you can use the ScreenOrientation API which will work for all browser except Safari and Edge (mobile/desktop). Do not use the outdatet Screen API.

If you plan to wrap your PWA into a mobile app, frameworks like Capacitor or Cordova will provide a native bridge to access the respective orientation lock feature.


问:
"Groupby" to multiple Dataframes
I'm pulling data from SQL, and get it in the following format:

I'm trying to use the "Groupby" function, to create unique Pandas Dataframes for each Identifier like in the picture. I have a list of all the identifiers (which in reality are different than (1,2,3 etc). How do I go about this?

I eventually want to Export it all to Excel (as is required by my job). Therefore, I would like to keep it all within one loop, so something like:

```<code>sht = xw.Book()
for i in (0, "Number of Unique Identifier"):
     Dataframe_i = Hist_Prices.groupby('Element i of the Unique identifier list')
     sht.sheets.add("DF_i")
     sht.sheets['DF_i'].range('A1').value = Dataframe_i
     i = i+1
</code>```

答:
You can do something like:</p>

```<code>identifiers = sorted(df['identifier'].unique())

for i in identifiers:
    df_i = df[df['identifier'] == i]
    # export df_i to excel sheet
</code>```

Title: "Groupby" to multiple Dataframes

Body:
I'm pulling data from SQL, and get it in the following format:

I'm trying to use the "Groupby" function, to create unique Pandas Dataframes for each Identifier like in the picture. I have a list of all the identifiers (which in reality are different than (1,2,3 etc). How do I go about this?

I eventually want to Export it all to Excel (as is required by my job). Therefore, I would like to keep it all within one loop, so something like:

sht = xw.Book()
for i in (0, "Number of Unique Identifier"):
     Dataframe_i = Hist_Prices.groupby('Element i of the Unique identifier list')
     sht.sheets.add("DF_i")
     sht.sheets['DF_i'].range('A1').value = Dataframe_i
     i = i+1

Body:
You can do something like:

identifiers = sorted(df['identifier'].unique())

for i in identifiers:
    df_i = df[df['identifier'] == i]
    # export df_i to excel sheet


问:
How do I import a scss npm module into Ember
How do I correctly import a non-plugin npm module into Ember?

I'm trying to use the sass version of flag-icon-css with ember-cli so that the sass is being built during deploy with the rest of ember-cli-sass, but I can't figure out how to do it in an automated fashion (e.g. without manually copying files over to public).

Using ember-auto-import seems like a good place to start but it is more tailored towards javascript imports.

I have tried this configuration in ember-cli-build.js:

```<code>    'sassOptions': {
        includePaths: [
            'node_modules/flag-icon-css/sass' // flag-icon.scss
        ]
    },
</code>```

It will add the styles, but it doesn't include the images used in the styles.

I have read this documentation, but it doesn't specify something more complicated than a single file.

答:
I figured this out, but I'm not sure it's the best or easiest way. It has some drawbacks.

const EmberApp = require('ember-cli/lib/broccoli/ember-app')
const Funnel = require('broccoli-funnel')

module.exports = function(defaults) {
    const app = new EmberApp(defaults, {
        'sassOptions': {
            includePaths: [
                'node_modules/flag-icon-css/sass'
            ]
        }
    })

    const flags = new Funnel('node_modules/flag-icon-css/', {
        srcDir: 'flags',
        destDir: '/flags',
    })

    return app.toTree([flags])
}
```

The drawback is that the css image urls are not processed, and hardlinked to ../flags, so I have to funnel them into /flags, which is not the convention, as these assets should be compiled into public/assets/images.

This is a two-step implementation (or more steps if the npm module would be more complex). It would be preferred to include just the scss and have (an) Ember (plugin) automatically fetch the dependent resources.

Body:
How do I correctly import a non-plugin npm module into Ember?

I'm trying to use the sass version of flag-icon-css with ember-cli so that the sass is being built during deploy with the rest of ember-cli-sass, but I can't figure out how to do it in an automated fashion (e.g. without manually copying files over to public).

Using ember-auto-import seems like a good place to start but it is more tailored towards javascript imports.

I have tried this configuration in ember-cli-build.js:

    'sassOptions': {
        includePaths: [
            'node_modules/flag-icon-css/sass' // flag-icon.scss
        ]
    },

It will add the styles, but it doesn't include the images used in the styles.

I have read this documentation, but it doesn't specify something more complicated than a single file.

Body:
I figured this out, but I'm not sure it's the best or easiest way. It has some drawbacks.

const EmberApp = require('ember-cli/lib/broccoli/ember-app')
const Funnel = require('broccoli-funnel')

module.exports = function(defaults) {
    const app = new EmberApp(defaults, {
        'sassOptions': {
            includePaths: [
                'node_modules/flag-icon-css/sass'
            ]
        }
    })

    const flags = new Funnel('node_modules/flag-icon-css/', {
        srcDir: 'flags',
        destDir: '/flags',
    })

    return app.toTree([flags])
}

The drawback is that the css image urls are not processed, and hardlinked to ../flags, so I have to funnel them into /flags, which is not the convention, as these assets should be compiled into public/assets/images.

This is a two-step implementation (or more steps if the npm module would be more complex). It would be preferred to include just the scss and have (an) Ember (plugin) automatically fetch the dependent resources.


问:
Why does my ViewController not respond?
I have a class set up with a UIImageView and I want to add that to the main viewcontrollers view, but it doesnt work.

Here is my code, Im sure theres something obvious missing:

MyViewController.h:

```<code>   #import <UIKit/UIKit.h>

   #import "ImageClass.h"

   @class ImageClass;

   @interface MyViewController : UIViewController {
   }

   @end
</code>```

MyViewController.m:

```<code>   #import "MyViewController.h"

   @implementation MyViewController

   - (void)viewDidLoad {

ImageClass *test = [[ImageClass alloc] init];

[test draw];

[super viewDidLoad];
   }
</code>```

ImageClass.h:

```<code>   #import <UIKit/UIKit.h>
   #import "EnkelBildeKlasseViewController.h"

   @class MyViewController;

   @interface ImageClass : NSObject {

MyViewController *maincontroller;

UIImageView *image;

      }

    @property (nonatomic, retain) UIImageView *image;

    -(void)draw;

      @end
</code>```

ImageClass.m:

```<code>   #import "ImageClass.h"
   #import "MyViewController.h"

   @implementation ImageClass
   @synthesize image;

      - (id)init {
       if ((self = [super init])) {

        }
     return self;
    }

    -(void)draw {

maincontroller.view.backgroundColor = [UIColor redColor];

image = [[UIImageView alloc] init];

image.backgroundColor = [UIColor greenColor];

image.frame = CGRectMake(100, 100, 100, 100);

[maincontroller.view addSubview:image];

     }
</code>```

Nothing in the main viewcontroller changes.. What is wrong?

I have also tried to connect it with IB:

```<code>        IBOutlet MyViewController *maincontroller;
</code>```

But it still doesnt respond! What should I do?

答: You need to do your drawing in drawRect:, and you need to make imageClass a UIView subclass, and add it as a subview. See this tutorial: http://littlecomputers.net/2010/?page_id=41</p>

Title: Why does my ViewController not respond?

Body:
I have a class set up with a UIImageView and I want to add that to the main viewcontrollers view, but it doesnt work.

Here is my code, Im sure theres something obvious missing:

MyViewController.h:

   #import <UIKit/UIKit.h>

   #import "ImageClass.h"

   @class ImageClass;

   @interface MyViewController : UIViewController {
   }

   @end

MyViewController.m:

   #import "MyViewController.h"

   @implementation MyViewController

   - (void)viewDidLoad {

ImageClass *test = [[ImageClass alloc] init];

[test draw];

[super viewDidLoad];
   }

ImageClass.h:

   #import <UIKit/UIKit.h>
   #import "EnkelBildeKlasseViewController.h"

   @class MyViewController;

   @interface ImageClass : NSObject {

MyViewController *maincontroller;

UIImageView *image;

      }

    @property (nonatomic, retain) UIImageView *image;

    -(void)draw;

      @end

ImageClass.m:

   #import "ImageClass.h"
   #import "MyViewController.h"

   @implementation ImageClass
   @synthesize image;

      - (id)init {
       if ((self = [super init])) {

        }
     return self;
    }

    -(void)draw {

maincontroller.view.backgroundColor = [UIColor redColor];

image = [[UIImageView alloc] init];

image.backgroundColor = [UIColor greenColor];

image.frame = CGRectMake(100, 100, 100, 100);

[maincontroller.view addSubview:image];

     }

Nothing in the main viewcontroller changes.. What is wrong?

I have also tried to connect it with IB:

        IBOutlet MyViewController *maincontroller;

But it still doesnt respond! What should I do?


问:
Sign a transaction to smart contract from migrations
I want to call smart contract method via sendTransaction from one of migrations. I'm using Truffle. During this migration I create a new wallet with a mnemonic.

```<code>const seed = bip39.mnemonicToSeed(mnemonic)
const hdk = hdkey.fromMasterSeed(seed)
const addrNode = hdk.derivePath("m/44'/60'/0'/0/0")
const walletAddr = wallet.getAddressString()
await someFactory.createProfile.sendTransaction(detailsHash, { from: walletAddr })
</code>```

During the transaction I receive an exception

```<code>Returned error: sender account not recognized
</code>```

How to send transaction with a newly created from a mnemonic profile?

答:
You can set your provider to your contract instance then</p>

```<code>const HDWalletProvider = require("@truffle/hdwallet-provider");
const mnemonic = "Your mnemonic"; //

module.exports = function(deployer) {

  deployer.deploy(SomeFactory).then(someFactory => {
  provider = new HDWalletProvider(mnemonic, "YourURL", 0);

  someFactory.contract.setProvider(provider);

  someFactory.createProfile.sendTransaction(detailsHash, { from:provider.addresses[0] })
  });
};
</code>```

Body:
I want to call smart contract method via sendTransaction from one of migrations. I'm using Truffle. During this migration I create a new wallet with a mnemonic.

const seed = bip39.mnemonicToSeed(mnemonic)
const hdk = hdkey.fromMasterSeed(seed)
const addrNode = hdk.derivePath("m/44'/60'/0'/0/0")
const walletAddr = wallet.getAddressString()
await someFactory.createProfile.sendTransaction(detailsHash, { from: walletAddr })

During the transaction I receive an exception

Returned error: sender account not recognized

How to send transaction with a newly created from a mnemonic profile?

Body:
You can set your provider to your contract instance then

const HDWalletProvider = require("@truffle/hdwallet-provider");
const mnemonic = "Your mnemonic"; //

module.exports = function(deployer) {

  deployer.deploy(SomeFactory).then(someFactory => {
  provider = new HDWalletProvider(mnemonic, "YourURL", 0);

  someFactory.contract.setProvider(provider);

  someFactory.createProfile.sendTransaction(detailsHash, { from:provider.addresses[0] })
  });
};


问:
Reactive programming - observable cache
I am rather new to reactive programming and observables, so there may be an obvious solution, but nonetheless I just cannot figure out how to make this simple caching service in javascript with observables

```<code>private legalIds: number[]
private personsCache: Person[] // Person has an id as a property

getPersons(ids: number[]) {
  const fromCache = personsCache.filter(p => ids.includes(p.id)) // Get the cached persons
  const newPersons = getPersons(ids.filter(id => legalIds.includes(id) && !fromCache.includes(id))) // Get the ones not already cached, if the ids are allowed

  return fromCache.concat(newPserons)
}

</code>```

How would you implement the above chaching functionality scritly using observables? no imperative programming of storing arrays etc.

答:
I am actually unsure about your inner recursive getPersons(..) call. But lets imagine it's a function that just returns you persons regarding some ids and it's non recursive.

```<code>private legalIds$: Subject<number[]> = new Subject();
private personsCache$: Subject<Person[]> = new Subject();

getPersons$(ids: number[]) {
  const fromCache$ = personsCache$.pipe(
    map(personsCache => personsCache.filter(p => ids.includes(p.id))
  );

  const newPersons$ = legalIds$.pipe(
    map(legalIds => getPersons(ids.filter(id => legalIds.includes(id) && !fromCache.includes(id)))
  );

  return combineLatest([fromCache$, newPersons$]).pipe(
    map(([fromCache, newPersons]) => fromCache.concat(newPersons))
  );
}
</code>```

- Most of the times if you have/need a recursive behavior in synchronus programming, you can solve this in rx by using scan, because of it's state

- If I could understand the usecase/szenario a bit more it should be possible not to require onto a getPersons$ call. Normally you can also provide an Observable (like public persons$) that uses an ids$ Observable/Subject (that is given your getPersons function).

Title: Reactive programming - observable cache

Body:
I am rather new to reactive programming and observables, so there may be an obvious solution, but nonetheless I just cannot figure out how to make this simple caching service in javascript with observables

private legalIds: number[]
private personsCache: Person[] // Person has an id as a property

getPersons(ids: number[]) {
  const fromCache = personsCache.filter(p => ids.includes(p.id)) // Get the cached persons
  const newPersons = getPersons(ids.filter(id => legalIds.includes(id) && !fromCache.includes(id))) // Get the ones not already cached, if the ids are allowed

  return fromCache.concat(newPserons)
}

How would you implement the above chaching functionality scritly using observables? no imperative programming of storing arrays etc.

Body:
I am actually unsure about your inner recursive getPersons(..) call. But lets imagine it's a function that just returns you persons regarding some ids and it's non recursive.

private legalIds$: Subject<number[]> = new Subject();
private personsCache$: Subject<Person[]> = new Subject();

getPersons$(ids: number[]) {
  const fromCache$ = personsCache$.pipe(
    map(personsCache => personsCache.filter(p => ids.includes(p.id))
  );

  const newPersons$ = legalIds$.pipe(
    map(legalIds => getPersons(ids.filter(id => legalIds.includes(id) && !fromCache.includes(id)))
  );

  return combineLatest([fromCache$, newPersons$]).pipe(
    map(([fromCache, newPersons]) => fromCache.concat(newPersons))
  );
}

- Most of the times if you have/need a recursive behavior in synchronus programming, you can solve this in rx by using scan, because of it's state

- If I could understand the usecase/szenario a bit more it should be possible not to require onto a getPersons$ call. Normally you can also provide an Observable (like public persons$) that uses an ids$ Observable/Subject (that is given your getPersons function).


问:
Xcode does not detect custom font
I added custom font in xcode, target membership is checked but it does not seen in custom fonts menu.

target membership

location

info.plist

copy bundle resources

答:
Project Name > Build Phases > Copy Bundle Resources.

You should see all font_name.ttf files listed. if you can't see that add your fonts files here. that should solve the problem.

Title: Xcode does not detect custom font


问:
NGXS: Testing Asynchronous Actions: Automatic subscription doesn't work
from official website NGXS

I write unit tests for NGXS store(Jasmine + Karma, angular 2)

In NGXS store in Asynchronous Actions(it's like Effect in NGRX) we don't subscribe inside - we just return observable. And it's fine, because the automatics subscription works.

BUT when I launch my tests, the automatic subscription on Asynchronous Actions(EFFECTS) - just doesn't work. As the result - test failed.

To sum up - I can't test Asynchronous Actions NGXS

What I have already  tried :
1) I wrote like in the official website NGXS(in the picture) 2)I tried it(done()) construction, 3) I tried actions$.subscribe() construction.

It works when I make manually - .subscribe() in the Action - but it's problem, because it have to work without this

This is link to official page: https://www.ngxs.io/recipes/unit-testing (topic : Testing Asynchronous Actions)
Please, help :)

答:
The example from the official page works correctly. If you stub some function from an action, which returns Observable, try embedding the delay inside your stub function.
For example,

stubFunc: () => {
    return timer(0).pipe( ... );
}


问:
Matrix which is 1 when row and column are both odd or both even
I want to create a matrix which which has:

The value 1 if the row is odd and the column is odd

The value 1 if the row is even and the column is even

The value 0 Otherwise.

I want to get the same results as the code below, but in a one line (command window) expression:

```<code> N=8;
 A = zeros(N);

 for row = 1:1:length(A)
     for column = 1:1:length(A)
        if(mod(row,2) == 1 && mod(column,2) == 1)

             A(row,column*(mod(column,2) == 1)) = 1;

         elseif(mod(row,2)== 0 && mod(column,2) == 0 )

             A(row,column*(mod(column,2) == 0)) = 1;

        end
     end
  end
 disp(A)
</code>```

This is the expected result:

```<code> 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
</code>```

答:
A simple approach is to use implicit expansion of addition, noting that

```<code>odd+odd = even+even = 0
</code>```

So this is your answer:

```<code>A = 1 - mod( (1:N) + (1:N).', 2 );
</code>```

You could also do this with toeplitz, as shown in this MATLAB Answers Post

For a square matrix with number of rows = number of columns = N

```<code>A = toeplitz(mod(1:N,2));
</code>```

If the number of rows (M) is not equal to the number of columns (N) then

```<code>A = toeplitz(mod(1:M,2),mod(1:N,2))
</code>```

FWIW, you're asking a specific case of this question:

How to generate a customized checker board matrix as fast as possible?

Body:
I want to create a matrix which which has:

The value 1 if the row is odd and the column is odd

The value 1 if the row is even and the column is even

The value 0 Otherwise.

I want to get the same results as the code below, but in a one line (command window) expression:

 N=8;
 A = zeros(N);

 for row = 1:1:length(A)
     for column = 1:1:length(A)
        if(mod(row,2) == 1 && mod(column,2) == 1)

             A(row,column*(mod(column,2) == 1)) = 1;

         elseif(mod(row,2)== 0 && mod(column,2) == 0 )

             A(row,column*(mod(column,2) == 0)) = 1;

        end
     end
  end
 disp(A)

This is the expected result:

 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1

Body:
A simple approach is to use implicit expansion of addition, noting that

odd+odd = even+even = 0

So this is your answer:

A = 1 - mod( (1:N) + (1:N).', 2 );

You could also do this with toeplitz, as shown in this MATLAB Answers Post

For a square matrix with number of rows = number of columns = N

A = toeplitz(mod(1:N,2));

If the number of rows (M) is not equal to the number of columns (N) then

A = toeplitz(mod(1:M,2),mod(1:N,2))

FWIW, you're asking a specific case of this question:

How to generate a customized checker board matrix as fast as possible?


问:
Copy link from same parent div - add to another child within the same div jquery
I have a cms that outputs lists of categories for ecommerce - I am trying to hide any list items after the first 4 and then add a link to view more which links to a category page. The category page link is within the same parent (or grandparent??) element as the list I am adding it to. I have this working to add the link but it appears to put the first link found across all divs. Please see code below:

$(".ecommMenuItem ul").append('
View All
');

  $(".ecommMenuItems").each(function(){
    var divtext = $(".category-link", this).attr("href");
    $(".view-all", this).attr("href", divtext);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="ecommMenuItems">
 <div class="ecommMenuItem">
  <i class="category-icon"><img src="/ebuyerfix-com/_img/img/placeholder.jpg"></i><span class="category-title" style="height: 15px;">BGA Stencil</span>
  <ul>
   <li>UR Selected Stencil</li>
   <li>Laser Tech Stencil</li>
   <li>3D Stencil</li>
   <li>Black Stencil</li>
   <li style="display: none;">Magnetic Stencil</li>
   <li style="display: none;">MacBook Stencil</li>

  </ul>
 </div>

<div class="ecommMenuItem">
 <i class="category-icon"><img src="/ebuyerfix-com/_img/img/placeholder.jpg"></i><span class="category-title" style="height: 15px;">Hand Tools</span>
 <ul>
  <li>Screwdrivers</li>
  <li>Tweezers</li>
  <li>Tool Kit Set</li>
  <li>Worksurface Mats</li>
  <li style="display: none;">Prying & Cutting</li>
  <li style="display: none;">Gripping & Holding</li>
  <li style="display: none;">Crimping & Heating</li>
  <li style="display: none;">Cleaning Tools</li>
  <li style="display: none;">SIM Card Tools</li>
  <li style="display: none;">Fume Extractor</li>
  <li style="display: none;">Labour Protection</li>
  <li style="display: none;">Static Personnel Grounding</li>

 </ul>
</div>

</div></code>```

So what I am trying to achieve is that the href from ".category-link" on each individual ".ecommMenuItem" is added to the ".view-all" href in the same .ecommMenuItem.

Any help is much appreciated.

答:
You're looping over the .ecommMenuItems element which is the level above the grouping for each menu. You instead need to loop over the .ecommMenuItem instead:

```<code>$(".ecommMenuItem").each(...
</code>```

Also note that can avoid the need to set an inline display: none on the median li elements by using :nth-child() in CSS. Try this:

$(".ecommMenuItem ul").append('
View All
');

$(".ecommMenuItem").each(function() {
  var divtext = $(".category-link", this).attr("href");
  $(".view-all", this).attr("href", divtext);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.ecommMenuItem li:nth-child(n+5):not(:last-child) {
  display: none;
}</code>```

      BGA Stencil

UR Selected Stencil

Laser Tech Stencil

3D Stencil

Black Stencil

Magnetic Stencil

MacBook Stencil

      Hand Tools

Screwdrivers

Tweezers

Tool Kit Set

Worksurface Mats

Prying & Cutting

Gripping & Holding

Crimping & Heating

Cleaning Tools

SIM Card Tools

Fume Extractor

Labour Protection

Static Personnel Grounding

```

Body:
I have a cms that outputs lists of categories for ecommerce - I am trying to hide any list items after the first 4 and then add a link to view more which links to a category page. The category page link is within the same parent (or grandparent??) element as the list I am adding it to. I have this working to add the link but it appears to put the first link found across all divs. Please see code below:

$(".ecommMenuItem ul").append('
View All
');

  $(".ecommMenuItems").each(function(){
    var divtext = $(".category-link", this).attr("href");
    $(".view-all", this).attr("href", divtext);
  });

  BGA Stencil

UR Selected Stencil

Laser Tech Stencil

3D Stencil

Black Stencil

Magnetic Stencil

MacBook Stencil

 Hand Tools

Screwdrivers

Tweezers

Tool Kit Set

Worksurface Mats

Prying & Cutting

Gripping & Holding

Crimping & Heating

Cleaning Tools

SIM Card Tools

Fume Extractor

Labour Protection

Static Personnel Grounding

So what I am trying to achieve is that the href from ".category-link" on each individual ".ecommMenuItem" is added to the ".view-all" href in the same .ecommMenuItem.

Any help is much appreciated.

Body:
You're looping over the .ecommMenuItems element which is the level above the grouping for each menu. You instead need to loop over the .ecommMenuItem instead:

$(".ecommMenuItem").each(...

Also note that can avoid the need to set an inline display: none on the median li elements by using :nth-child() in CSS. Try this:

$(".ecommMenuItem ul").append('<li><a href="#" class="view-all">View All</a></li>');

$(".ecommMenuItem").each(function() {
  var divtext = $(".category-link", this).attr("href");
  $(".view-all", this).attr("href", divtext);
});

.ecommMenuItem li:nth-child(n+5):not(:last-child) {
  display: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="ecommMenuItems">
  <div class="ecommMenuItem">
    <a class="category-link" href="/subgroup/bga-stencil/" title="BGA Stencil"><i class="category-icon">
      <img src="/ebuyerfix-com/_img/img/placeholder.jpg"></i>
      <span class="category-title" style="height: 15px;">BGA Stencil</span>
    </a>
    <ul>
      <li><a id="catId8468" href="/_shop/ur-selected-stencil/" title="UR Selected Stencil">UR Selected Stencil</a></li>
      <li><a id="catId8469" href="/_shop/laser-tech-stencil/" title="Laser Tech Stencil">Laser Tech Stencil</a></li>
      <li><a id="catId8470" href="/_shop/3d-stencil/" title="3D Stencil">3D Stencil</a></li>
      <li><a id="catId8471" href="/_shop/black-stencil/" title="Black Stencil">Black Stencil</a></li>
      <li><a id="catId8472" href="/_shop/magnetic-stencil/" title="Magnetic Stencil">Magnetic Stencil</a></li>
      <li><a id="catId8473" href="/_shop/macbook-stencil/" title="MacBook Stencil">MacBook Stencil</a></li>
    </ul>
  </div>
  <div class="ecommMenuItem">
    <a class="category-link" href="/subgroup/hand-tools/" title="Hand Tools"><i class="category-icon">
      <img src="/ebuyerfix-com/_img/img/placeholder.jpg"></i>
      <span class="category-title" style="height: 15px;">Hand Tools</span>
    </a>
    <ul>
      <li><a id="catId8449" href="/_shop/screwdrivers/" title="Screwdrivers">Screwdrivers</a></li>
      <li><a id="catId8450" href="/_shop/tweezers/" title="Tweezers">Tweezers</a></li>
      <li><a id="catId8451" href="/_shop/tool-kit-set/" title="Tool Kit Set">Tool Kit Set</a></li>
      <li><a id="catId8452" href="/_shop/worksurface-mats/" title="Worksurface Mats">Worksurface Mats</a></li>
      <li><a id="catId8453" href="/_shop/prying--cutting/" title="Prying &amp; Cutting">Prying &amp; Cutting</a></li>
      <li><a id="catId8454" href="/_shop/gripping--holding/" title="Gripping &amp; Holding">Gripping &amp; Holding</a></li>
      <li><a id="catId8455" href="/_shop/crimping--heating/" title="Crimping &amp; Heating">Crimping &amp; Heating</a></li>
      <li><a id="catId8456" href="/_shop/cleaning-tools/" title="Cleaning Tools">Cleaning Tools</a></li>
      <li><a id="catId8457" href="/_shop/sim-card-tools/" title="SIM Card Tools">SIM Card Tools</a></li>
      <li><a id="catId8458" href="/_shop/fume-extractor/" title="Fume Extractor">Fume Extractor</a></li>
      <li><a id="catId8459" href="/_shop/labour-protection/" title="Labour Protection">Labour Protection</a></li>
      <li><a id="catId8460" href="/_shop/static-personnel-grounding/" title="Static Personnel Grounding">Static Personnel Grounding</a></li>
    </ul>
  </div>
</div>


问:
Rails association with errors is not invalid
I found this strange case with adding errors to an ActiveRecord object instantiated from an association. This case works as expected:

```<code>payment = Payment.new
# #<Payment:0x00007f996c3b8848 ...>
payment.errors.add(:base, 'some message')
payment.valid?
# false
</code>```

Yet, if I attempt to do the same thing with an object instantiated from the association, the error is not blocking the validation:

```<code>payment = Customer.payments.build
# #<Payment:0x00007f994d318538 ...>
payment.valid?
# true
payment.errors.add(:base, 'error')
# ["error"]
payment.errors
# #<ActiveModel::Errors:0x00007f8d2c00a5a8
 @base= #<Payment:0x00007f8d20dcb680 id: nil>,
 @details={:base=>[{:error=>"error"}]},
 @messages={:base=>["error"]}>
## Yet, agonizingly --
payment.valid?
# true
</code>```

Anyone has any ideas about what I'm missing here?

答: The difference between these cases is payment.customer attribute, which may be validated for presence (at least) and is in fact present in your second case (the one returning true) and is not present in the first case, hence you (probably) get validation error. Of course I'm not sure since I didn't see your model. But it have to be something like this.

Body:
I found this strange case with adding errors to an ActiveRecord object instantiated from an association. This case works as expected:

payment = Payment.new
# #<Payment:0x00007f996c3b8848 ...>
payment.errors.add(:base, 'some message')
payment.valid?
# false

Yet, if I attempt to do the same thing with an object instantiated from the association, the error is not blocking the validation:

payment = Customer.payments.build
# #<Payment:0x00007f994d318538 ...>
payment.valid?
# true
payment.errors.add(:base, 'error')
# ["error"]
payment.errors
# #<ActiveModel::Errors:0x00007f8d2c00a5a8
 @base= #<Payment:0x00007f8d20dcb680 id: nil>,
 @details={:base=>[{:error=>"error"}]},
 @messages={:base=>["error"]}>
## Yet, agonizingly --
payment.valid?
# true

Anyone has any ideas about what I'm missing here?


问:
index of N highest elements from a list of numpy array
I need a function that returns the index (row and column) of the N highest element from a matrix/list of numpy array.

Suppose that I have the following matrix:

```<code>a = [[4,2,3],
     [5,0,3]]
</code>```

I would like to get a list of the indexes (row,column) of the N highest elements. For example, if I want the index of the 4 highest element, the function should return

```<code>[(1,0), (0,0), (0,2), (1,2)]
</code>```

I have tried implementing this as following, but it returns a list of (value, row number), which is not want I need

```<code>for i, sub_list in enumerate(a):
    max_list.append((max(sub_list), i))
</code>```

答:
I would flatten, argsort, and unravel_index

```<code>f = a.ravel().argsort()
[*zip(*np.unravel_index(f[-n:], a.shape))]
</code>```

```<code>[(0, 2), (1, 2), (0, 0), (1, 0)]
</code>```

As yatu points out, if you have a larger array, and a small-ish n, you can replace argsort with np.argpartition(a.ravel(), -n).

Body:
I need a function that returns the index (row and column) of the N highest element from a matrix/list of numpy array.

Suppose that I have the following matrix:

a = [[4,2,3],
     [5,0,3]]

I would like to get a list of the indexes (row,column) of the N highest elements. For example, if I want the index of the 4 highest element, the function should return

[(1,0), (0,0), (0,2), (1,2)]

I have tried implementing this as following, but it returns a list of (value, row number), which is not want I need

for i, sub_list in enumerate(a):
    max_list.append((max(sub_list), i))

Body:
I would flatten, argsort, and unravel_index

f = a.ravel().argsort()
[*zip(*np.unravel_index(f[-n:], a.shape))]

[(0, 2), (1, 2), (0, 0), (1, 0)]

As yatu points out, if you have a larger array, and a small-ish n, you can replace argsort with np.argpartition(a.ravel(), -n).


问:
Ant target to remove old build directories
I have my builds published to the directories like:

```<code>/some/dir/build-1/
/some/dir/build-2/
/some/dir/build-3/
...
/some/dir/build-n/
</code>```

I need ant task to delete all the previous build directories except the last three (n, n-1 and n-3).

I suppose I shuould use <delete> task, but how to configure the attributes?

答:
Make use of resources. When empty and non empty directories are mixed up, i believe you have to use a mix of fileset and dirset to make it work with selectors, because delete in combination with selectors and fileset won't work for empty directories.Whereas if you have only nonempty directories you may use the fileset part only - here's a snippet using some sort + date selector, deleting the latest 3 directories =

```<code><project name="foo">

  <delete includeEmptyDirs="true" verbose="true">
    <last count="3">
      <sort>
      <date/>
        <fileset dir="/some/dir">
          <include name="**/*build*/**" />
        </fileset>
      </sort>
    </last>
  </delete>

  <delete verbose="true">
    <last count="3">
      <sort>
      <date/>
        <dirset dir="/some/dir">
          <include name="**/*build*/**" />
        </dirset>
      </sort>
    </last>
  </delete>

</project>
</code>```

see Ant Manual/Resources for further details..

Body:
I have my builds published to the directories like:

/some/dir/build-1/
/some/dir/build-2/
/some/dir/build-3/
...
/some/dir/build-n/

I need ant task to delete all the previous build directories except the last three (n, n-1 and n-3).

I suppose I shuould use <delete> task, but how to configure the attributes?

Body:
Make use of resources. When empty and non empty directories are mixed up, i believe you have to use a mix of fileset and dirset to make it work with selectors, because delete in combination with selectors and fileset won't work for empty directories.Whereas if you have only nonempty directories you may use the fileset part only - here's a snippet using some sort + date selector, deleting the latest 3 directories =

<project name="foo">

  <delete includeEmptyDirs="true" verbose="true">
    <last count="3">
      <sort>
      <date/>
        <fileset dir="/some/dir">
          <include name="**/*build*/**" />
        </fileset>
      </sort>
    </last>
  </delete>

  <delete verbose="true">
    <last count="3">
      <sort>
      <date/>
        <dirset dir="/some/dir">
          <include name="**/*build*/**" />
        </dirset>
      </sort>
    </last>
  </delete>

</project>

see Ant Manual/Resources for further details..


问:
How can i generate a sequence of numbers as text in python
I need to generate a sequence of numbres, for example from 1 to 100 (this number could be much greater) in an array but as text like

```<code>[
    'one',
    'two',
    'three',
    ...
    'one hundred',
]
</code>```

is there a library that do this? or i have to do it manually? and if there is a way to do it in spanish will be a plus.

答:
This might help you but in order to do it in spanish you need to understand the code and change the code a little
https://www.geeksforgeeks.org/convert-number-to-words/

EDIT:
I think this will help you more there are multiple languages supported in this module
https://pypi.org/project/num2words/

Body:
I need to generate a sequence of numbres, for example from 1 to 100 (this number could be much greater) in an array but as text like

[
    'one',
    'two',
    'three',
    ...
    'one hundred',
]

is there a library that do this? or i have to do it manually? and if there is a way to do it in spanish will be a plus.


答: You have to do it manually just use replace.</p>

Title: How can i generate a sequence of numbers as text in python


问:
USB Mass Storrage on File Level
The Challenge: I have an Linux hand-held device, which records data and stores it to the disc. It should exchange these data with a Windows application via USB. When this data is accessible by the user - e.g. via USB-mass-storage - it has to be encrypted. It should work out-of-the-box, with a variety of OS, also for citrix terminal sessions, etc.

The Plan: I create a file-system in user-space with FUSE, and offer it to windows via mass-storage. Whenever Windows accesses one file, I get a callback and encrypt the data on the fly. Further more, we can have some dynamic content - e.g. when some password is written into a file, more content is shown.

The Problem: When using the mass-storage gadget (e.g. g_file_storage) it only accepts files or block-devices - but no file-systems (directories). Why?

[...] it provides a simple interface to read and write sectors of data—much like the low-level interface used to access any hard drive [...]. Operating systems may treat the USB drive like a hard drive, and can format it with any file system they like. (from wikipedia)

So there is no chance to have a dynamic file-system via mass-storage... and this seems to be the reason, why my android mobile phone un-mounts all data on the phone, when I connect it to the PC.

Options:

Create a 'block-device in userspace' - similar to FUSE (need a reverse-FAT-driver, when I want to offer files dynamically)

Implement my own nbd-server to create a block-device (need a reverse-FAT-driver as well?)

I save encrypted files to a partition, and pass this partition to the mass-storage gadget (Problem would be the performance and the lack of dynamic interaction)

Do not offer a mass-storrage device and watch out for other ideas (eth over USB)

At the moment, only the last option seems to be realistic - or do you have another tip for me?

I would be grateful!

Charly

答:
The USB mass storage protocol is a block device protocol; it does not operate at the level of files or directories. The Windows host expects to see a raw VFAT filesystem exposed by the g_mass_storage driver, and will make writes and reads to VFAT metadata as appropriate to figure out how directories are structured.

Because of this, it's nontrivial to expose a FUSE filesystem to the windows host. You'd have to emulate VFAT, assigning blocks in the virtual filesystem to metadata and to data, and since the windows host is free to cache any data or metadata it reads, once you assign some metadata or data it cannot change (so changes to your FUSE data could not be reflected in the windows filesystem). The windows host can also delay and reorder writes to both metadata and data - it's all real mess if you try to emulate.

Now, there are some things you can do:

You can write a custom IFS driver on the windows side to interact with your linux device over a custom protocol that works at the file/directory level.

You can treat the USB device as a virtual ethernet port, and speak CIFS to the windows host

You can somehow create a static VFAT layout on connection time to expose to the windows host; not-yet-decryptable data can return I/O errors in order to avoid the Windows host caching raw encrypted data.

You can just encrypt a raw block device using dm-crypt, and expose this entire block device (encrypted as one chunk) to windows.

You could implement a MTP gadget.

These approaches come with their own problems:

Requires a windows driver to be installed, and to be signed by microsoft etc. Can't be used on a machine without administrative access to install the driver.

Won't autoplay; the user would need to browse through the network browser to get access to the files. Firewall settings may interfere. May have significant overhead.

Very complex. Handling metadata updates on the backend may be extremely difficult. Surprise unplug events may be devastating. Windows behavior on receiving an IO error may be a problem if the user tries to access a locked file.

No file-level encryption is available, but otherwise should work well.

I'm unsure exactly how much support for non-media files MTP has; support is not as widespread as mass storage support.

Title: USB Mass Storrage on File Level


问:
Setting a value to a cell in a pandas dataframe
I have the following pandas dataframe:

```<code>K = pd.DataFrame({"A":[1,2,3,4], "B":[5,6,7,8]})
</code>```

Then I set the cell in the first row and first column to 11:

```<code>K.iloc[0]["A"] = 11
</code>```

And when I check the dataframe again, I see that the value assignment is done and K.iloc[0]["A"] is equal to 11. However when I add a column to this data frame and do the same operation for a cell in the new column, the value assignment is not successful:

```<code>K["C"] = 0
K.iloc[0]["C"] = 11
</code>```

So, when I check the dataframe again, the value of K.iloc[0]["C"] is still zero. I appreciate if somebody can tell me what is going on here and how I can resolve this issue.

答:
loc should work :

```<code>K.loc[0]['C'] = 11
K.loc[0, 'C'] = 11
</code>```

Both the above versions of loc will be able to assign values to the dataframe K.

Body:
I have the following pandas dataframe:

K = pd.DataFrame({"A":[1,2,3,4], "B":[5,6,7,8]})

Then I set the cell in the first row and first column to 11:

K.iloc[0]["A"] = 11

And when I check the dataframe again, I see that the value assignment is done and K.iloc[0]["A"] is equal to 11. However when I add a column to this data frame and do the same operation for a cell in the new column, the value assignment is not successful:

K["C"] = 0
K.iloc[0]["C"] = 11

So, when I check the dataframe again, the value of K.iloc[0]["C"] is still zero. I appreciate if somebody can tell me what is going on here and how I can resolve this issue.

Body:
loc should work :

K.loc[0]['C'] = 11
K.loc[0, 'C'] = 11

Both the above versions of loc will be able to assign values to the dataframe K.


问:
How to count the number of clicks for button
How to count the number of clicks for CAT or DOG button in my program and save to log.txt  </p>

```<code>from Tkinter import *

import Tkinter as tk

import sys

stdoutOrigin=sys.stdout
sys.stdout = open("log.txt", "w")

master = Tk()
Label(master, text='Who is your favourate animal ?? ').grid(row=0)

Button(master, text='CAT' ,).grid(row=1, sticky=W, pady=4)
Button(master, text='DOG' ,).grid(row=1,column=1,sticky=W, pady=4)
mainloop()

sys.stdout.close()
sys.stdout=stdoutOrigin
</code>```

答:
I don't know if this script is the best one to overwrite a number in a file, but you can try it. If your file is empty, it will create lines (for ex : dog = 0), and if it exists it will increment it (for ex : dog = 1) when you click on the button.

I also remove your from Tkinter import *, and instead I replaced Button by tk.Button for all widgets.

```<code>def save_in_file(animal):
    f = open("log.txt", "r+")

    animal_exists = False
    data = f.read()

    # separate the file into lines
    lines = data.split("\n") # list of lines : ['dog = 2', 'cat = 1']
    for i, v in enumerate(lines):
        # separate the lines into words
        words = v.split() # list of words : ['dog', '=', '3']
        if animal in words:
            animal_exists = True

            # here we search for the "number_to_increment"
            number_to_increment = words[-1]

            # we convert "number_to_increment" into integer, then add 1
            new_number = str(int(number_to_increment) +1)

            # we convert "new_number" back to string
            words[-1] = new_number

        # concatenate words to form the new line
        lines[i] = " ".join(words)

    # creates a new line with "animal = 0" if "animal" is not in file
    if not animal_exists:
        if lines[0] == "":
            lines.remove("")
        lines.append("{} = 0".format(animal))

    # concatenate all lines to get the whole text for new file
    data = "\n".join(lines)

    f.close()

    # open file with write permission
    f = open("log.txt", "wt")

    # overwrite the file with our modified data
    f.write(data)
    f.close()

def cat():
    save_in_file("cat")

def dog():
    save_in_file("dog")

import tkinter as tk

master = tk.Tk()
tk.Label(master, text='Who is your favourate animal ?? ').grid(row=0)

tk.Button(master, text='CAT', command=cat).grid(row=1, sticky="w", pady=4)
tk.Button(master, text='DOG', command=dog).grid(row=1,column=1,sticky="w", pady=4)
master.mainloop()

</code>```

Output :

```<code># log.txt
dog = 2
cat = 1
</code>```

Body:
How to count the number of clicks for CAT or DOG button in my program and save to log.txt

from Tkinter import *

import Tkinter as tk

import sys

stdoutOrigin=sys.stdout
sys.stdout = open("log.txt", "w")

master = Tk()
Label(master, text='Who is your favourate animal ?? ').grid(row=0)

Button(master, text='CAT' ,).grid(row=1, sticky=W, pady=4)
Button(master, text='DOG' ,).grid(row=1,column=1,sticky=W, pady=4)
mainloop()

sys.stdout.close()
sys.stdout=stdoutOrigin

Body:
I don't know if this script is the best one to overwrite a number in a file, but you can try it. If your file is empty, it will create lines (for ex : dog = 0), and if it exists it will increment it (for ex : dog = 1) when you click on the button.

I also remove your from Tkinter import *, and instead I replaced Button by tk.Button for all widgets.

def save_in_file(animal):
    f = open("log.txt", "r+")

    animal_exists = False
    data = f.read()

    # separate the file into lines
    lines = data.split("\n") # list of lines : ['dog = 2', 'cat = 1']
    for i, v in enumerate(lines):
        # separate the lines into words
        words = v.split() # list of words : ['dog', '=', '3']
        if animal in words:
            animal_exists = True

            # here we search for the "number_to_increment"
            number_to_increment = words[-1]

            # we convert "number_to_increment" into integer, then add 1
            new_number = str(int(number_to_increment) +1)

            # we convert "new_number" back to string
            words[-1] = new_number

        # concatenate words to form the new line
        lines[i] = " ".join(words)

    # creates a new line with "animal = 0" if "animal" is not in file
    if not animal_exists:
        if lines[0] == "":
            lines.remove("")
        lines.append("{} = 0".format(animal))

    # concatenate all lines to get the whole text for new file
    data = "\n".join(lines)

    f.close()

    # open file with write permission
    f = open("log.txt", "wt")

    # overwrite the file with our modified data
    f.write(data)
    f.close()

def cat():
    save_in_file("cat")

def dog():
    save_in_file("dog")

import tkinter as tk

master = tk.Tk()
tk.Label(master, text='Who is your favourate animal ?? ').grid(row=0)

tk.Button(master, text='CAT', command=cat).grid(row=1, sticky="w", pady=4)
tk.Button(master, text='DOG', command=dog).grid(row=1,column=1,sticky="w", pady=4)
master.mainloop()

Output :

# log.txt
dog = 2
cat = 1


问:
msg.payload.split fails for mqtt in python. How to fix?
I have created an MQTT class. It does connect fine and publishes the "Online" message upon connection. However something is wrong with the on_message method, as it starts but gets stuck on splitting the payload

```<code>class mqtt_function():
    def __init__(self):
        self.mqttc = mqtt.Client()
        # MQTT settings here
        self.mqttc.loop_forever()
    def on_connect(self, client, userdata,flags, rc):
        message = "connected with rc: " + str(rc)
        self.mqttc.subscribe(self.topic, 2)
        print("subscribed to ", self.topic)
        self.mqttc.publish(self.topicStatus, "Online", 1, True)
    def on_message(self, client, obj, msg):
        print("on_message method started")
        print(msg.payload)
        info = msg.payload.split(",")
        print("message was split")
</code>```

returns

```<code>subscribed to commands/home
on_message method started
b'60,1581638400'
</code>```

Expectation:
The msg.payload.split should have separated the payload message by commas into the list named info. However, this does not happen.

答:
The issue lies with understanding the msg.payload format.

While print(msg.payload) returns a legible text, msg.payload is not a string but ASCII code. After converting msg.payload from ASCII to a string, the .split function can be used.
Here is the working conversion for the mqtt payload.

```<code>    def on_message(self, client, obj, msg):
        characters = [chr(ascii) for ascii in msg.payload] # Convert ASCII to char
        chars_joined = ''.join(characters) # Join chars to a string
        received_message = chars_joined.split(",")     # Split string by comma
</code>```

Body:
I have created an MQTT class. It does connect fine and publishes the "Online" message upon connection. However something is wrong with the on_message method, as it starts but gets stuck on splitting the payload

class mqtt_function():
    def __init__(self):
        self.mqttc = mqtt.Client()
        # MQTT settings here
        self.mqttc.loop_forever()
    def on_connect(self, client, userdata,flags, rc):
        message = "connected with rc: " + str(rc)
        self.mqttc.subscribe(self.topic, 2)
        print("subscribed to ", self.topic)
        self.mqttc.publish(self.topicStatus, "Online", 1, True)
    def on_message(self, client, obj, msg):
        print("on_message method started")
        print(msg.payload)
        info = msg.payload.split(",")
        print("message was split")

returns

subscribed to commands/home
on_message method started
b'60,1581638400'

Expectation:
The msg.payload.split should have separated the payload message by commas into the list named info. However, this does not happen.

Body:
The issue lies with understanding the msg.payload format.

While print(msg.payload) returns a legible text, msg.payload is not a string but ASCII code. After converting msg.payload from ASCII to a string, the .split function can be used.
Here is the working conversion for the mqtt payload.

    def on_message(self, client, obj, msg):
        characters = [chr(ascii) for ascii in msg.payload] # Convert ASCII to char
        chars_joined = ''.join(characters) # Join chars to a string
        received_message = chars_joined.split(",")     # Split string by comma


问:
"The number of parameters does not match number of values for stored procedure" System.Data.Common.DbCommand nuance
This could be an sql server database setup issue, but I am not to sure where to start looking.

I have a stored procedure:

```<code>CREATE PROCEDURE aStoredProcedure
@dteSince DATETIME = null
AS
...
</code>```

The C# code to call the stored procedure is:

```<code>using (IDataReader dr = database.ExecuteReader("aStoredProcedure"))
{
...
</code>```

The C# code works fine on the Production environment. Here, dteSince will be set to null as it is not supplied as a input parameter.

Problem is when I run this in the UAT environment, it returns the message shown in the title - wrong number of parameters...

I can fix this by changing the code to:

```<code>using (IDataReader dr = database.ExecuteReader (CommandType.StoredProcedure, "aStoredProcedure"))
{
...
</code>```

The fix just masks the real problem as to how can the code fails on one environment and works fine on another.

I have dropped and recreated the stored procedure, with no luck.

Technologies used C# 2.0 & Sql Server 2005.

答:
Here are some of the troubleshooting tips I usually try.

Check the assembly version of DAL assembly that "database" object type resides in.

Check library reference to your DAL - Whether you are referencing the DLL from GAC or not  - I had trouble before with DLL referencing GAC, which contained old assembly

Check your default database when your code tries to connect to database in UAT environment - It might be pointing to other databases depending on how you are connected to database.

And all's still not well, clean and Rebuild solution

side comment: Beh, I don't think "System.Data.IDataReader" is to be included in technology used ;)

OwnerDisplayName: Ferds

Body:
This could be an sql server database setup issue, but I am not to sure where to start looking.

I have a stored procedure:

CREATE PROCEDURE aStoredProcedure
@dteSince DATETIME = null
AS
...

The C# code to call the stored procedure is:

using (IDataReader dr = database.ExecuteReader("aStoredProcedure"))
{
...

The C# code works fine on the Production environment. Here, dteSince will be set to null as it is not supplied as a input parameter.

Problem is when I run this in the UAT environment, it returns the message shown in the title - wrong number of parameters...

I can fix this by changing the code to:

using (IDataReader dr = database.ExecuteReader (CommandType.StoredProcedure, "aStoredProcedure"))
{
...

The fix just masks the real problem as to how can the code fails on one environment and works fine on another.

I have dropped and recreated the stored procedure, with no luck.

Technologies used C# 2.0 & Sql Server 2005.

LastEditorDisplayName: Ferds

OwnerDisplayName: Sung Meister

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Sung Meister


问:
Unknown exceptions when connecting to MongoDB via java driver
I'm currently trying to connect to a mongoDB database via the java driver and I'm given the exceptions listed below when I run the code above it. Not sure what to do or what's wrong. If it appears to be an import or JRE problem please list the part to import if you can.

Code in Java:

```<code>MongoClient mongoClient = new MongoClient(new
MongoClientURI("mongodb+srv://wendulem:MYPASSWORD@cluster0
ugj9q.mongodb.net/test?retryWrites=true"));
    MongoDatabase database = mongoClient.getDatabase("GradeU");
    MongoCollection<Document> collection =
    database.getCollection("profiles");
    Document myDoc;
    myDoc = collection.find(eq("username", "admin")).first();
    System.out.println(myDoc.toJson());
</code>```

Console Logs:

```<code>Jul 06, 2018 12:49:55 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[cluster0-shard-00-02-ugj9q.mongodb.net:27017, cluster0-shard-00-00-ugj9q.mongodb.net:27017, cluster0-shard-00-01-ugj9q.mongodb.net:27017], mode=MULTIPLE, requiredClusterType=REPLICA_SET, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500, requiredReplicaSetName='Cluster0-shard-0'}
Jul 06, 2018 12:49:55 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Adding discovered server cluster0-shard-00-02-ugj9q.mongodb.net:27017 to client view of cluster
Jul 06, 2018 12:49:55 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Adding discovered server cluster0-shard-00-00-ugj9q.mongodb.net:27017 to client view of cluster
Jul 06, 2018 12:49:55 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Adding discovered server cluster0-shard-00-01-ugj9q.mongodb.net:27017 to client view of cluster
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by com.mongodb.client.internal.MongoClientDelegate$1@11438d26 from cluster description ClusterDescription{type=REPLICA_SET, connectionMode=MULTIPLE, serverDescriptions=[ServerDescription{address=cluster0-shard-00-02-ugj9q.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=cluster0-shard-00-01-ugj9q.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=cluster0-shard-00-00-ugj9q.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:4355}] to cluster0-shard-00-02-ugj9q.mongodb.net:27017
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:3, serverValue:4703}] to cluster0-shard-00-01-ugj9q.mongodb.net:27017
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:7669}] to cluster0-shard-00-00-ugj9q.mongodb.net:27017
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=cluster0-shard-00-00-ugj9q.mongodb.net:27017, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 5]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=21097463, setName='Cluster0-shard-0', canonicalAddress=cluster0-shard-00-00-ugj9q.mongodb.net:27017, hosts=[cluster0-shard-00-00-ugj9q.mongodb.net:27017, cluster0-shard-00-01-ugj9q.mongodb.net:27017, cluster0-shard-00-02-ugj9q.mongodb.net:27017], passives=[], arbiters=[], primary='cluster0-shard-00-00-ugj9q.mongodb.net:27017', tagSet=TagSet{[]}, electionId=7fffffff0000000000000001, setVersion=1, lastWriteDate=Fri Jul 06 12:49:50 EDT 2018, lastUpdateTimeNanos=75088686541038}
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=cluster0-shard-00-01-ugj9q.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 5]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=28398802, setName='Cluster0-shard-0', canonicalAddress=cluster0-shard-00-01-ugj9q.mongodb.net:27017, hosts=[cluster0-shard-00-00-ugj9q.mongodb.net:27017, cluster0-shard-00-01-ugj9q.mongodb.net:27017, cluster0-shard-00-02-ugj9q.mongodb.net:27017], passives=[], arbiters=[], primary='cluster0-shard-00-00-ugj9q.mongodb.net:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Fri Jul 06 12:49:50 EDT 2018, lastUpdateTimeNanos=75088689801046}
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=cluster0-shard-00-02-ugj9q.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 5]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=22170448, setName='Cluster0-shard-0', canonicalAddress=cluster0-shard-00-02-ugj9q.mongodb.net:27017, hosts=[cluster0-shard-00-00-ugj9q.mongodb.net:27017, cluster0-shard-00-01-ugj9q.mongodb.net:27017, cluster0-shard-00-02-ugj9q.mongodb.net:27017], passives=[], arbiters=[], primary='cluster0-shard-00-00-ugj9q.mongodb.net:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Fri Jul 06 12:49:50 EDT 2018, lastUpdateTimeNanos=75088684046959}
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Setting max election id to 7fffffff0000000000000001 from replica set primary cluster0-shard-00-00-ugj9q.mongodb.net:27017
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Setting max set version to 1 from replica set primary cluster0-shard-00-00-ugj9q.mongodb.net:27017
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Discovered replica set primary cluster0-shard-00-00-ugj9q.mongodb.net:27017
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Closed connection [connectionId{localValue:4}] to cluster0-shard-00-00-ugj9q.mongodb.net:27017 because there was a socket exception raised by this connection.
Exception in thread "main" com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='wendulem', source='admin', password=<hidden>, mechanismProperties={}}
    at com.mongodb.internal.connection.SaslAuthenticator.wrapException(SaslAuthenticator.java:173)
    at com.mongodb.internal.connection.SaslAuthenticator.access$300(SaslAuthenticator.java:40)
    at com.mongodb.internal.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:70)
    at com.mongodb.internal.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:47)
    at com.mongodb.internal.connection.SaslAuthenticator.doAsSubject(SaslAuthenticator.java:179)
    at com.mongodb.internal.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:47)
    at com.mongodb.internal.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:151)
    at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:64)
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:127)
    at com.mongodb.internal.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:50)
    at com.mongodb.internal.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:390)
    at com.mongodb.internal.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:106)
    at com.mongodb.internal.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:92)
    at com.mongodb.internal.connection.DefaultServer.getConnection(DefaultServer.java:85)
    at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:114)
    at com.mongodb.client.internal.ClientSessionBinding$SessionBindingConnectionSource.getConnection(ClientSessionBinding.java:111)
    at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:455)
    at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:401)
    at com.mongodb.operation.FindOperation.execute(FindOperation.java:695)
    at com.mongodb.operation.FindOperation.execute(FindOperation.java:83)
    at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.execute(MongoClientDelegate.java:179)
    at com.mongodb.client.internal.FindIterableImpl.first(FindIterableImpl.java:198)
    at gradebook.grademain.main(grademain.java:39)
Caused by: com.mongodb.MongoCommandException: Command failed with error 8000 (AtlasError): 'bad auth Authentication failed.' on server cluster0-shard-00-00-ugj9q.mongodb.net:27017. The full response is { "ok" : 0, "errmsg" : "bad auth Authentication failed.", "code" : 8000, "codeName" : "AtlasError" }
    at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:179)
    at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:293)
    at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:255)
    at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:83)
    at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:33)
    at com.mongodb.internal.connection.SaslAuthenticator.sendSaslContinue(SaslAuthenticator.java:134)
    at com.mongodb.internal.connection.SaslAuthenticator.access$200(SaslAuthenticator.java:40)
    at com.mongodb.internal.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:67)
</code>```

答:
Increasing socketTimeoutMS and adding authSource param fixed this issue.

Ex: mongodb://<user>:<pwd>@<mongoServer>:<port>/<db_name>?socketTimeoutMS=1000000&authSource=<db_name>```

Body:
I'm currently trying to connect to a mongoDB database via the java driver and I'm given the exceptions listed below when I run the code above it. Not sure what to do or what's wrong. If it appears to be an import or JRE problem please list the part to import if you can.

Code in Java:

MongoClient mongoClient = new MongoClient(new
MongoClientURI("mongodb+srv://wendulem:MYPASSWORD@cluster0
ugj9q.mongodb.net/test?retryWrites=true"));
    MongoDatabase database = mongoClient.getDatabase("GradeU");
    MongoCollection<Document> collection =
    database.getCollection("profiles");
    Document myDoc;
    myDoc = collection.find(eq("username", "admin")).first();
    System.out.println(myDoc.toJson());

Console Logs:

Jul 06, 2018 12:49:55 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[cluster0-shard-00-02-ugj9q.mongodb.net:27017, cluster0-shard-00-00-ugj9q.mongodb.net:27017, cluster0-shard-00-01-ugj9q.mongodb.net:27017], mode=MULTIPLE, requiredClusterType=REPLICA_SET, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500, requiredReplicaSetName='Cluster0-shard-0'}
Jul 06, 2018 12:49:55 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Adding discovered server cluster0-shard-00-02-ugj9q.mongodb.net:27017 to client view of cluster
Jul 06, 2018 12:49:55 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Adding discovered server cluster0-shard-00-00-ugj9q.mongodb.net:27017 to client view of cluster
Jul 06, 2018 12:49:55 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Adding discovered server cluster0-shard-00-01-ugj9q.mongodb.net:27017 to client view of cluster
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by com.mongodb.client.internal.MongoClientDelegate$1@11438d26 from cluster description ClusterDescription{type=REPLICA_SET, connectionMode=MULTIPLE, serverDescriptions=[ServerDescription{address=cluster0-shard-00-02-ugj9q.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=cluster0-shard-00-01-ugj9q.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=cluster0-shard-00-00-ugj9q.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:4355}] to cluster0-shard-00-02-ugj9q.mongodb.net:27017
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:3, serverValue:4703}] to cluster0-shard-00-01-ugj9q.mongodb.net:27017
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:7669}] to cluster0-shard-00-00-ugj9q.mongodb.net:27017
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=cluster0-shard-00-00-ugj9q.mongodb.net:27017, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 5]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=21097463, setName='Cluster0-shard-0', canonicalAddress=cluster0-shard-00-00-ugj9q.mongodb.net:27017, hosts=[cluster0-shard-00-00-ugj9q.mongodb.net:27017, cluster0-shard-00-01-ugj9q.mongodb.net:27017, cluster0-shard-00-02-ugj9q.mongodb.net:27017], passives=[], arbiters=[], primary='cluster0-shard-00-00-ugj9q.mongodb.net:27017', tagSet=TagSet{[]}, electionId=7fffffff0000000000000001, setVersion=1, lastWriteDate=Fri Jul 06 12:49:50 EDT 2018, lastUpdateTimeNanos=75088686541038}
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=cluster0-shard-00-01-ugj9q.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 5]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=28398802, setName='Cluster0-shard-0', canonicalAddress=cluster0-shard-00-01-ugj9q.mongodb.net:27017, hosts=[cluster0-shard-00-00-ugj9q.mongodb.net:27017, cluster0-shard-00-01-ugj9q.mongodb.net:27017, cluster0-shard-00-02-ugj9q.mongodb.net:27017], passives=[], arbiters=[], primary='cluster0-shard-00-00-ugj9q.mongodb.net:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Fri Jul 06 12:49:50 EDT 2018, lastUpdateTimeNanos=75088689801046}
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=cluster0-shard-00-02-ugj9q.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 5]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=22170448, setName='Cluster0-shard-0', canonicalAddress=cluster0-shard-00-02-ugj9q.mongodb.net:27017, hosts=[cluster0-shard-00-00-ugj9q.mongodb.net:27017, cluster0-shard-00-01-ugj9q.mongodb.net:27017, cluster0-shard-00-02-ugj9q.mongodb.net:27017], passives=[], arbiters=[], primary='cluster0-shard-00-00-ugj9q.mongodb.net:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Fri Jul 06 12:49:50 EDT 2018, lastUpdateTimeNanos=75088684046959}
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Setting max election id to 7fffffff0000000000000001 from replica set primary cluster0-shard-00-00-ugj9q.mongodb.net:27017
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Setting max set version to 1 from replica set primary cluster0-shard-00-00-ugj9q.mongodb.net:27017
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Discovered replica set primary cluster0-shard-00-00-ugj9q.mongodb.net:27017
Jul 06, 2018 12:49:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Closed connection [connectionId{localValue:4}] to cluster0-shard-00-00-ugj9q.mongodb.net:27017 because there was a socket exception raised by this connection.
Exception in thread "main" com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='wendulem', source='admin', password=<hidden>, mechanismProperties={}}
    at com.mongodb.internal.connection.SaslAuthenticator.wrapException(SaslAuthenticator.java:173)
    at com.mongodb.internal.connection.SaslAuthenticator.access$300(SaslAuthenticator.java:40)
    at com.mongodb.internal.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:70)
    at com.mongodb.internal.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:47)
    at com.mongodb.internal.connection.SaslAuthenticator.doAsSubject(SaslAuthenticator.java:179)
    at com.mongodb.internal.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:47)
    at com.mongodb.internal.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:151)
    at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:64)
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:127)
    at com.mongodb.internal.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:50)
    at com.mongodb.internal.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:390)
    at com.mongodb.internal.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:106)
    at com.mongodb.internal.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:92)
    at com.mongodb.internal.connection.DefaultServer.getConnection(DefaultServer.java:85)
    at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:114)
    at com.mongodb.client.internal.ClientSessionBinding$SessionBindingConnectionSource.getConnection(ClientSessionBinding.java:111)
    at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:455)
    at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:401)
    at com.mongodb.operation.FindOperation.execute(FindOperation.java:695)
    at com.mongodb.operation.FindOperation.execute(FindOperation.java:83)
    at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.execute(MongoClientDelegate.java:179)
    at com.mongodb.client.internal.FindIterableImpl.first(FindIterableImpl.java:198)
    at gradebook.grademain.main(grademain.java:39)
Caused by: com.mongodb.MongoCommandException: Command failed with error 8000 (AtlasError): 'bad auth Authentication failed.' on server cluster0-shard-00-00-ugj9q.mongodb.net:27017. The full response is { "ok" : 0, "errmsg" : "bad auth Authentication failed.", "code" : 8000, "codeName" : "AtlasError" }
    at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:179)
    at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:293)
    at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:255)
    at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:83)
    at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:33)
    at com.mongodb.internal.connection.SaslAuthenticator.sendSaslContinue(SaslAuthenticator.java:134)
    at com.mongodb.internal.connection.SaslAuthenticator.access$200(SaslAuthenticator.java:40)
    at com.mongodb.internal.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:67)


问:
Waiting until a variables value isset to display it php
I have a variable $infoCollectedAndSold that is being set inside a form (its values are whatever is being checked in the checkbox).
I want to display this variable, once its values are set. Currently the echo is displaying nothing until i submit the form and then the values are displayed from the variable. Is it possible to display the information inside the variable without submitting the form?</p>

```<code>//Set variable to the form inputs
$infoCollectedAndSold = "";
if (!empty($_POST['infoCollectedAndSold'])) {
    foreach ($_POST['infoCollectedAndSold'] as $value) {
        $infoCollectedAndSold .= $value . ', ';
    }
}

//Display variable content (Does not display until form is submitted)
<?php
if(isset($infoCollectedAndSold)){
   echo '<h3>'.$infoCollectedAndSold.'</h3>';
}
?>
</code>```

答:
$infoCollectedAndSold is always set as the first line of your code. You have to check it against an empty string if you don't want the h3 tag to display.

```<code>if($infoCollectedAndSold !== "")
</code>```

If you instead want to print the h3 regardless of its initial emptiness and then populate it while you fill in the form without submitting it you have to move the logic to frontend, eg with javascript.

Body:
I have a variable $infoCollectedAndSold that is being set inside a form (its values are whatever is being checked in the checkbox).
I want to display this variable, once its values are set. Currently the echo is displaying nothing until i submit the form and then the values are displayed from the variable. Is it possible to display the information inside the variable without submitting the form?

//Set variable to the form inputs
$infoCollectedAndSold = "";
if (!empty($_POST['infoCollectedAndSold'])) {
    foreach ($_POST['infoCollectedAndSold'] as $value) {
        $infoCollectedAndSold .= $value . ', ';
    }
}

//Display variable content (Does not display until form is submitted)
<?php
if(isset($infoCollectedAndSold)){
   echo '
'.$infoCollectedAndSold.'
';
}
?>

Body:
$infoCollectedAndSold is always set as the first line of your code. You have to check it against an empty string if you don't want the h3 tag to display.

if($infoCollectedAndSold !== "")

If you instead want to print the h3 regardless of its initial emptiness and then populate it while you fill in the form without submitting it you have to move the logic to frontend, eg with javascript.


问:
Best practices for drake pipeline experimentation
I'm new to drake but loving it so far. One thing I'm having trouble with is how to best go about experimenting with different pipeline configurations. That is, my plans consist purely of a chain of targets where the output from the first target is the input for the second, the second forms the input for the third, etc. My targets all have the same basic structure (dynamic targets with tibbles as individual entries) expected as input and supplied as output, and I want to experiment with different orderings, inclusion/exclusion of certain steps, etc. For example:

plan = drake::drake_plan(

    a_transformed = target(
        compute_a_transform(list_of_input_data)
        , dynamic = map(list_of_input_data)
    )

    , b_transformed = target(
        compute_b_transform(a_transformed)
        , dynamic = map(a_transformed)
    )

    , c_transformed = target(
        compute_c_transform(c_transformed)
        , dynamic = map(c_transformed)
    )

)
```

<p>The way I've been using drake so far is that each target has a unique/meaningful name, so when I, for example, remove a target, I have to rename the input supplied to the subsequent target:</p>

<pre class="lang-r prettyprint-override"><code>plan = drake::drake_plan(

    a_transformed = target(
        compute_a_transform(list_of_input_data)
        , dynamic = map(list_of_input_data)
    )

    #, b_transformed = target(
    #    compute_b_transform(a_transformed)
    #    , dynamic = map(a_transformed)
    #)

    #note the b-transform step has been removed (commented-out), requiring inputs to c_transform to be changed from `b_transform` to `a_transform`

    , c_transformed = target(
        compute_c_transform(a_transformed) #had to rename things here
        , dynamic = map(a_transformed) #and here
    )

)
</code>```

Would it be too much to hope that there's a better way of experimenting that doesn't require this manual commenting-out and renaming?

答:
I worked out a method that is a bit of a hack but works for me. I simply add a skip argument to each function that triggers return of the input if TRUE:

```<code>compute_a_transform = function(x,skip=F){
    if(skip){
        return(x)
    }
    ... #regular compute_a_transform stuff here
}

</code>```

Then, when I want to skip a step in the processing chain, I simply set skip=TRUE without commenting-out or renaming anything

```<code>plan = drake::drake_plan(

    a_transformed = target(
        compute_a_transform(list_of_input_data)
        , dynamic = map(list_of_input_data)
    )

    , b_transformed = target(
        compute_b_transform(a_transformed, skip=TRUE) #skip=TRUE means the b-transform isn't actually applied
        , dynamic = map(a_transformed)
    )

    , c_transformed = target(
        compute_c_transform(c_transformed)
        , dynamic = map(c_transformed)
    )

)
</code>```

Body:
I'm new to drake but loving it so far. One thing I'm having trouble with is how to best go about experimenting with different pipeline configurations. That is, my plans consist purely of a chain of targets where the output from the first target is the input for the second, the second forms the input for the third, etc. My targets all have the same basic structure (dynamic targets with tibbles as individual entries) expected as input and supplied as output, and I want to experiment with different orderings, inclusion/exclusion of certain steps, etc. For example:

plan = drake::drake_plan(

    a_transformed = target(
        compute_a_transform(list_of_input_data)
        , dynamic = map(list_of_input_data)
    )

    , b_transformed = target(
        compute_b_transform(a_transformed)
        , dynamic = map(a_transformed)
    )

    , c_transformed = target(
        compute_c_transform(c_transformed)
        , dynamic = map(c_transformed)
    )

)

The way I've been using drake so far is that each target has a unique/meaningful name, so when I, for example, remove a target, I have to rename the input supplied to the subsequent target:

plan = drake::drake_plan(

    a_transformed = target(
        compute_a_transform(list_of_input_data)
        , dynamic = map(list_of_input_data)
    )

    #, b_transformed = target(
    #    compute_b_transform(a_transformed)
    #    , dynamic = map(a_transformed)
    #)

    #note the b-transform step has been removed (commented-out), requiring inputs to c_transform to be changed from `b_transform` to `a_transform`

    , c_transformed = target(
        compute_c_transform(a_transformed) #had to rename things here
        , dynamic = map(a_transformed) #and here
    )

)

Would it be too much to hope that there's a better way of experimenting that doesn't require this manual commenting-out and renaming?

Body:
I worked out a method that is a bit of a hack but works for me. I simply add a skip argument to each function that triggers return of the input if TRUE:

compute_a_transform = function(x,skip=F){
    if(skip){
        return(x)
    }
    ... #regular compute_a_transform stuff here
}

Then, when I want to skip a step in the processing chain, I simply set skip=TRUE without commenting-out or renaming anything

plan = drake::drake_plan(

    a_transformed = target(
        compute_a_transform(list_of_input_data)
        , dynamic = map(list_of_input_data)
    )

    , b_transformed = target(
        compute_b_transform(a_transformed, skip=TRUE) #skip=TRUE means the b-transform isn't actually applied
        , dynamic = map(a_transformed)
    )

    , c_transformed = target(
        compute_c_transform(c_transformed)
        , dynamic = map(c_transformed)
    )

)