问:
The database cannot be opened because the VBA cannot be read
I have an Access, 2007 – 2016, accdb database on my Toshiba Satellite Pro running Windows 7 32 bit. I am using MS Office 365.

The database that opens at its home page, but any attempt to open a table, form or module brings up this message:

“The database cannot be opened because the VBA project contained in it cannot be read…”

I have 2 backups of this database, but they do the same thing.

I have read several posts on the internet that indicate that the problem can be solved by decompiling the database.

I have tried the VBS Script solution contained in:

How does one decompile and recompile a database application?

However, it does not get to decompile as the same message displays when the .vbs file opens the database.

I have read some other posts that indicate a problem with a VBA7 file, but these refer to Access 2010, so I do not know if they also apply to me. I have VBA7.1 by the way.

Attempts to decompile through the Command Prompt has its own problems that seem to be associated with file names with spaces.

So, I’m stuck. Any help would be much appreciated

答:
I ran into this same error at work, Have you tried shift-clicking and opening? I know that seems obvious, What I did, was I got the DB open in safe mode, and opened up a module in the vba editor, and tried to fight the problematic code, if anything you could delete all your modules after copying them into a notepad.

I also right clicked and restored previous versions from windows, I am not sure if you have tried this when you say you have to back ups, but i was unaware of this fix and i luckily had a version from last week that fixed my issue.


来源: stackexchange

问:
Loader object not firing complete event after an external css/swf file got loaded
Hi
I am a bit stuck here for the past few days. I have a SWF running in Security.LOCAL_TRUSTED sandbox.

I can load my JPEGs and simple SWFs without any problems

```<code>var loader:Loader = new Loader();
loader.load(new URLRequest('file:///test.jpg'));
</code>```

But once, I successfully load a SWF created from an CSS (e.g. myfont.swf) file using Flash Builder 4 (Compile CSS to SWF), then I am unable to load any images or SWFs again as I was before.

The process events are getting fired and looks like its loading but the complete event never gets fired. Neither does any other IOError or Security warning occur.

Can the loaded SWF (myfont.swf) change the sandbox of the loading swf? Or what am I missing here.

CSS for myfont.swf

```<code>/* CSS file */
@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";

@font-face {
    src: url("../assets/fonts/Arial.ttf");
    fontFamily: "Arial";
    embedAsCFF: true;
    unicodeRange:
        U+0000-U+007F,
        U+00A0-U+00FF,
        U+2000-U+206F,
        U+20A0-U+20CF;
}

@font-face {
    src: url("../assets/fonts/Arial Bold.ttf");
    fontFamily: "Arial";
    fontWeight: "bold";
    embedAsCFF: true;
    unicodeRange:
        U+0000-U+007F,
        U+00A0-U+00FF,
        U+2000-U+206F,
        U+20A0-U+20CF;
}
</code>```

答:
Try this: make your loader a class variable, instead of local variable. The garbage collector destroys it before the file gets loaded.

So in the class body:

```<code>private var loader:Loader;
</code>```

and later in your method:

```<code>loader = new Loader();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hi
I am a bit stuck here for the past few days. I have a SWF running in Security.LOCAL_TRUSTED sandbox.

I can load my JPEGs and simple SWFs without any problems

var loader:Loader = new Loader();
loader.load(new URLRequest('file:///test.jpg'));

But once, I successfully load a SWF created from an CSS (e.g. myfont.swf) file using Flash Builder 4 (Compile CSS to SWF), then I am unable to load any images or SWFs again as I was before.

The process events are getting fired and looks like its loading but the complete event never gets fired. Neither does any other IOError or Security warning occur.

Can the loaded SWF (myfont.swf) change the sandbox of the loading swf? Or what am I missing here.

CSS for myfont.swf

/* CSS file */
@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";

@font-face {
    src: url("../assets/fonts/Arial.ttf");
    fontFamily: "Arial";
    embedAsCFF: true;
    unicodeRange:
        U+0000-U+007F,
        U+00A0-U+00FF,
        U+2000-U+206F,
        U+20A0-U+20CF;
}

@font-face {
    src: url("../assets/fonts/Arial Bold.ttf");
    fontFamily: "Arial";
    fontWeight: "bold";
    embedAsCFF: true;
    unicodeRange:
        U+0000-U+007F,
        U+00A0-U+00FF,
        U+2000-U+206F,
        U+20A0-U+20CF;
}

Body:
Try this: make your loader a class variable, instead of local variable. The garbage collector destroys it before the file gets loaded.

So in the class body:

private var loader:Loader;

and later in your method:

loader = new Loader();


问:
Instagram API - Getting invalid media id with video shortcode
I'm using the /media/shortcode/shortcode endpoint of instagram to get information about a certain media with a shortcode.

https://www.instagram.com/developer/endpoints/media/#get_media_by_shortcode

The problem is when I pass a photo's shortcode to the endpoint everything works fine and I get the result I'm expecting from Instagram, however, when I pass a video's shortcode to that endpoint, the api returns the following:

```<code>{
  "meta": {
    "code": 400,
    "error_type": "APINotFoundError",
    "error_message": "invalid media id"
  }
}
</code>```

Which does not make a lot of sense to me since the given endpoint should work just fine with videos.

答:
The best and the easiest way to get the media info, either being photo or video is by calling this url (GET method) Insta Fetch Media URL

Sample code written in Python.

```<code>import requests, json
def get_media_id(image_url):

     url = "https://api.instagram.com/oembed/"

     querystring = {"callback": "", "url": image_url}

     headers = {
        'cache-control': "no-cache"
     }

     response = requests.request("GET", url, headers=headers, params=querystring)
     return json.loads(response.text)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using the /media/shortcode/shortcode endpoint of instagram to get information about a certain media with a shortcode.

https://www.instagram.com/developer/endpoints/media/#get_media_by_shortcode

The problem is when I pass a photo's shortcode to the endpoint everything works fine and I get the result I'm expecting from Instagram, however, when I pass a video's shortcode to that endpoint, the api returns the following:

{
  "meta": {
    "code": 400,
    "error_type": "APINotFoundError",
    "error_message": "invalid media id"
  }
}

Which does not make a lot of sense to me since the given endpoint should work just fine with videos.

Body:
The best and the easiest way to get the media info, either being photo or video is by calling this url (GET method) Insta Fetch Media URL

Sample code written in Python.

import requests, json
def get_media_id(image_url):

     url = "https://api.instagram.com/oembed/"

     querystring = {"callback": "", "url": image_url}

     headers = {
        'cache-control': "no-cache"
     }

     response = requests.request("GET", url, headers=headers, params=querystring)
     return json.loads(response.text)


问:
Async function not behaving as I expect with Jest
The Javascript Jest testing framework documentation says that I need to add done() in my callback to test an asynchronous function, as otherwise the function will return after the test completes and so the test will fail. I have Jest added to my package.json, and the following two files:

src.js:

```<code>function fetchData(cb) {
  setTimeout(cb, 2000, 'peanut butter')
}

module.exports = fetchData
</code>```

src.test.js:

```<code>const fetchData = require('./src')

test('the data is peanut butter', () => {
  function callback(data) {
    expect(data).toBe('peanut butter')
    // no done() method!
  }

  fetchData(callback);
})
</code>```

I get passing tests with the above code, but I think I should get a failing test since I don't have done() in my test file. Is my fetchData() method not asynchronous?

EDIT: Following Nicholas' answer, I changed the code to this:

src.js:

```<code>function fetchData(cb) {
  setTimeout(cb, 2000, 'peanut')
}

module.exports = fetchData
</code>```

src.test.js:

```<code>const fetchData = require('./src')

test('the data is peanut butter', () => {
  function callback(data) {
    expect(data).toBe('peanut butter')
    done()
  }

  fetchData(callback);
})
</code>```

The test runner should evaluate the expectation/assertion per the Jest documentation and fail (peanut being passed, peanut butter expected), but still shows a passing test.

Also, the Jest documentation says:

```<code>If done() is never called, the test will fail, which is what you want to happen
</code>```

The test passes both with and without the done() method in the callback, and both with and without a correct (peanut butter) argument passed to the callback (i.e. all four variants pass).

答:
If you don't pass done as an argument, the test runner considers the code synchronous and doesn't wait for something special to occur - in this case invoking done.

Therefore, the test is marked as succesful before your assertions/expectations get a chance to run.

Body:
The Javascript Jest testing framework documentation says that I need to add done() in my callback to test an asynchronous function, as otherwise the function will return after the test completes and so the test will fail. I have Jest added to my package.json, and the following two files:

src.js:

function fetchData(cb) {
  setTimeout(cb, 2000, 'peanut butter')
}

module.exports = fetchData

src.test.js:

const fetchData = require('./src')

test('the data is peanut butter', () => {
  function callback(data) {
    expect(data).toBe('peanut butter')
    // no done() method!
  }

  fetchData(callback);
})

I get passing tests with the above code, but I think I should get a failing test since I don't have done() in my test file. Is my fetchData() method not asynchronous?

EDIT: Following Nicholas' answer, I changed the code to this:

src.js:

function fetchData(cb) {
  setTimeout(cb, 2000, 'peanut')
}

module.exports = fetchData

src.test.js:

const fetchData = require('./src')

test('the data is peanut butter', () => {
  function callback(data) {
    expect(data).toBe('peanut butter')
    done()
  }

  fetchData(callback);
})

The test runner should evaluate the expectation/assertion per the Jest documentation and fail (peanut being passed, peanut butter expected), but still shows a passing test.

Also, the Jest documentation says:

If done() is never called, the test will fail, which is what you want to happen

The test passes both with and without the done() method in the callback, and both with and without a correct (peanut butter) argument passed to the callback (i.e. all four variants pass).

ContentLicense: CC BY-SA 4.0


问:
AWS Lambda update DynamoDB item
I have a DynamoDB table called Wishlist, and an existing DynamoDB Item which I'm calling "monitor".

I am trying to write a Lambda function that updates the "monitor" item as follows:

takes the user's login ID, appends @gmail.com to it, and writes it to a new email attribute

writes a timestamp to the item

Here is my code:

```<code>console.log('Loading function');
var doc = require('dynamodb-doc');
var db = new doc.DynamoDB();

exports.handler = function(event, context)
{
     var username  = event.username;
     var email = event.username+"@gmail.com";
     console.log(username + "," + email);

     var tableName = "WishList";
     var item = {
           "username":username,
           "email":  email,
     };

     var params = {
         TableName:tableName,
         Item: item
     };

     console.log(params);
     db.putItem(params, function(err,data){
         if (err) console.log(err);
         else console.log(data);
     });
};
</code>```

How do I read the existing "monitor" item so that I can update it with putItem?

答:
If I understand your question, you need to:

get the existing item by its key using getItem

modify the returned item

put the modified item using putItem

Alternatively, you can simply use updateItem which will edit an existing item's attributes, or add a new item to the table if it does not already exist.

You can see sample code here.

Title: AWS Lambda update DynamoDB item

Body:
I have a DynamoDB table called Wishlist, and an existing DynamoDB Item which I'm calling "monitor".

I am trying to write a Lambda function that updates the "monitor" item as follows:

takes the user's login ID, appends @gmail.com to it, and writes it to a new email attribute

writes a timestamp to the item

Here is my code:

console.log('Loading function');
var doc = require('dynamodb-doc');
var db = new doc.DynamoDB();

exports.handler = function(event, context)
{
     var username  = event.username;
     var email = event.username+"@gmail.com";
     console.log(username + "," + email);

     var tableName = "WishList";
     var item = {
           "username":username,
           "email":  email,
     };

     var params = {
         TableName:tableName,
         Item: item
     };

     console.log(params);
     db.putItem(params, function(err,data){
         if (err) console.log(err);
         else console.log(data);
     });
};

How do I read the existing "monitor" item so that I can update it with putItem?


问:
Store values from file in arrays depending a value in the array in JAVA
Hello everyone i am new in java .I want to write a programm that reads from a file and by a specific way.My file is mix with strings and ints.
In the first line there is a number that tell us how many lines will follow.
After this, in each line there will be a String and an int.The int value will tell us how many values there are in this line.
For example :
text file:

```<code>2
Coffee       2  Water 200   cofe 300
SweetCoffee  3  Water 200   cofe 300   Sugar 10
</code>```

I want to pass values in different arrays.

```<code>   nameOfProduct[0]=Coffee
   nameOfProduct[1]=SweetCoffee
   numofIngredients[0]=2
   element[0][0]=water
   element[0][1]=cofe
   element[1][3]=sugar
</code>```

i try to find a way that works.This is what i have done until now

```<code>package pkg1;
import java.io.*;
import java.util.*;

public class readfile {

    private Scanner x;
    int count=0;
    int i,j,noIngredients;

    public void openfile() {
        try {
            x = new Scanner(new File("MyRecipes.txt"));
        }
        catch(Exception e) {
            System.out.println("could not find the file");
        }
    }

    public void readFile() {
        i=0;
        int numofRecipes = x.nextInt();

        String nameOfProduct[] = new String[numofRecipes];
        int numofIngredients[]  = new int[numofRecipes];

        while (x.hasNext()) {
        //   String line = x.nextLine();
            nameOfProduct[i] = x.next();

            numofIngredients[i] = x.nextInt();

            noIngredients=numofIngredients[i];

            String element[][] = new String[numofRecipes][noIngredients];

            int quantity[][] = new int[numofRecipes][noIngredients];

            System.out.printf("%s %d ",nameOfProduct,numofIngredients);

            j=0;

            while( x.hasNext() || x.hasNextInt())  {
                element[i][j] = x.next();
                quantity[i][j] = x.nextInt();
                System.out.printf("%s %d ",element[i][j],quantity[i][j]);
                j++;
            }
            i++;
            x.nextLine() ;
        }
    }
 }
</code>```

答:
You can check the type with scanner class. Where you write x.next() there you can write:
if(x.hasNextInt()
  int k = x.nextInt()
 else String s = x.next()

You can always check type and for more types you can check java libarary.

Body:
Hello everyone i am new in java .I want to write a programm that reads from a file and by a specific way.My file is mix with strings and ints.
In the first line there is a number that tell us how many lines will follow.
After this, in each line there will be a String and an int.The int value will tell us how many values there are in this line.
For example :
text file:

2
Coffee       2  Water 200   cofe 300
SweetCoffee  3  Water 200   cofe 300   Sugar 10

I want to pass values in different arrays.

   nameOfProduct[0]=Coffee
   nameOfProduct[1]=SweetCoffee
   numofIngredients[0]=2
   element[0][0]=water
   element[0][1]=cofe
   element[1][3]=sugar

i try to find a way that works.This is what i have done until now

package pkg1;
import java.io.*;
import java.util.*;

public class readfile {

    private Scanner x;
    int count=0;
    int i,j,noIngredients;

    public void openfile() {
        try {
            x = new Scanner(new File("MyRecipes.txt"));
        }
        catch(Exception e) {
            System.out.println("could not find the file");
        }
    }

    public void readFile() {
        i=0;
        int numofRecipes = x.nextInt();

        String nameOfProduct[] = new String[numofRecipes];
        int numofIngredients[]  = new int[numofRecipes];

        while (x.hasNext()) {
        //   String line = x.nextLine();
            nameOfProduct[i] = x.next();

            numofIngredients[i] = x.nextInt();

            noIngredients=numofIngredients[i];

            String element[][] = new String[numofRecipes][noIngredients];

            int quantity[][] = new int[numofRecipes][noIngredients];

            System.out.printf("%s %d ",nameOfProduct,numofIngredients);

            j=0;

            while( x.hasNext() || x.hasNextInt())  {
                element[i][j] = x.next();
                quantity[i][j] = x.nextInt();
                System.out.printf("%s %d ",element[i][j],quantity[i][j]);
                j++;
            }
            i++;
            x.nextLine() ;
        }
    }
 }


问:
Selenium Webdriverjs (javascript) with chrome
Selenium Webdriver works nicely with Chromium. But when I want to use Chrome (which I want because chrome can be installed easily in the new version that does support headless mode), then chrome never starts up.

WebDriverError: unknown error: Chrome failed to start: exited abnormally
  (Driver info: chromedriver=2.29.461571 (8a88bbe0775e2a23afda0ceaf2ef7ee74e822cc5),platform=Linux 4.2.8.11-1-MANJARO x86_64)

```<code>var selenium = require ('selenium-webdriver'),
By = selenium.By,
until = selenium.until,
Select = selenium.Select;

var chrome = require ("selenium-webdriver/chrome");
var o = new chrome.Options();

o.setChromeBinaryPath( "/opt/google/chrome-unstable/");

var service = new chrome.ServiceBuilder()
    .loggingTo('/tmp/chromescraper.txt')
    .enableVerboseLogging()
    .build();

var driver = chrome.Driver.createSession(o, service);

 driver.get ("http://news.google.com");
</code>```

Any ideas?

答:
I ran into the same issue and what I found out is each ChromeDriver supports certain Chrome binary version. If they don't match, you might run into issues. For example, the current latest ChromeDriver below at the time of this writing is 2.33 will support Chrome v60-62. If you go to the site below and find on your ChromeDriver version, it should tell you which Chrome version it supports. Good luck!

https://sites.google.com/a/chromium.org/chromedriver/downloads

Body:
Selenium Webdriver works nicely with Chromium. But when I want to use Chrome (which I want because chrome can be installed easily in the new version that does support headless mode), then chrome never starts up.

WebDriverError: unknown error: Chrome failed to start: exited abnormally
  (Driver info: chromedriver=2.29.461571 (8a88bbe0775e2a23afda0ceaf2ef7ee74e822cc5),platform=Linux 4.2.8.11-1-MANJARO x86_64)

var selenium = require ('selenium-webdriver'),
By = selenium.By,
until = selenium.until,
Select = selenium.Select;

var chrome = require ("selenium-webdriver/chrome");
var o = new chrome.Options();

o.setChromeBinaryPath( "/opt/google/chrome-unstable/");

var service = new chrome.ServiceBuilder()
    .loggingTo('/tmp/chromescraper.txt')
    .enableVerboseLogging()
    .build();

var driver = chrome.Driver.createSession(o, service);

 driver.get ("http://news.google.com");

Any ideas?


问:
Amazon Athena: Dateparse shows Invalid Format
I have a CSV file having Orderdate as string in it. In Amazon Atena trying to use dateparse to convert the format of data but getting error. This is what i am trying:

```<code>select parse_datetime(orderdate,'%m/%d/%y %H:%i:%s') from orders
</code>```

Error: INVALID_FUNCTION_ARGUMENT: Invalid format: "9/1/2015 15:43"

答:
The error means that your format string '%m/%d/%y %H:%i:%s' does not match the orderdate string.

Your orderdate does not have seconds and the year is 4 digits. Change your format string to '%m/%d/%Y %H:%i'

Date and Time Functions and Operators

Body:
I have a CSV file having Orderdate as string in it. In Amazon Atena trying to use dateparse to convert the format of data but getting error. This is what i am trying:

select parse_datetime(orderdate,'%m/%d/%y %H:%i:%s') from orders

Error: INVALID_FUNCTION_ARGUMENT: Invalid format: "9/1/2015 15:43"


问:
Accessing Python instance variables with __dict__- Is it wrong?
If I want to access the list of instance variables of an object, I can call myObject.__dict__.keys().  I want to use this attribute to print out all instance variables of an object.  I am hesitant to do this because __dict__ is a "secret" attribute, and I do not understand what this footnote means.

So is it wrong to use myObject.__dict__?

答: You could use dir function to list all attributes of an object.


问:
InstallShield 2013 SQLServerSelectLogin screen doesn't populate
I've inherited an InstallShield 2013 InstallScript MSI project that installs our product and I'm really new to IS. I've figured out the basics and even created an new project, but this has me baffled. One of our installers uses SQLServerSelectLogin (or at least I assume that it does) to get the user to select a SQL server to install to, and just recently it stopped populating with the list of installed servers and I need to figure out why.

I've rolled back just about all of the changes that have been made since this started being an issue and it's still happening. (The changes that I haven't rolled back are really minor and shouldn't effect the install). Being new to IS I really don't even know where to look for this to debug it. So my questions are:

Where would I find the code that populates this list?

How can I debug an install to figure out what's not happening?

答: I found an obscure post that describes three files that need to be downloaded and installed. Doing this fixed the problem.</p>


问:
chef-client cannot find cookbooks using berkshelf
I'm new to chef and ran into problems with berkshelf and chef-client. I want to have my own cookbook with dependencies and apply it. My initial cookbook looks like this:

```<code>.
├── Berksfile
├── Berksfile.lock
├── chefignore
├── client.rb
├── Gemfile
├── Gemfile.lock
├── metadata.rb
├── README.md
└── recipes
    └── default.rb

#./Berksfile
source 'https://supermarket.getchef.com'

metadata

cookbook 'znc'

#./client.rb
cookbook_path '~/.berkshelf/cookbooks'
</code>```

and when I run sudo bundle exec chef-client -z -o znc --config=client.rb the chef-client cannot find the cookbook:

```<code>Starting Chef Client, version 11.16.4
[2014-10-25T15:34:59+02:00] WARN: Run List override has been provided.
[2014-10-25T15:34:59+02:00] WARN: Original Run List: []
[2014-10-25T15:34:59+02:00] WARN: Overridden Run List: [recipe[znc]]
resolving cookbooks for run list: ["znc"]

================================================================================
Error Resolving Cookbooks for Run List:
================================================================================

Missing Cookbooks:
------------------
No such cookbook: znc

Expanded Run List:
------------------
* znc

Running handlers:
[2014-10-25T15:34:59+02:00] ERROR: Running exception handlers
Running handlers complete
[2014-10-25T15:34:59+02:00] ERROR: Exception handlers complete
[2014-10-25T15:34:59+02:00] FATAL: Stacktrace dumped to /home/sebastian/.chef/local-mode-cache/cache/chef-stacktrace.out
Chef Client failed. 0 resources updated in 3.474758165 seconds
[2014-10-25T15:34:59+02:00] ERROR: 412 "Precondition Failed "
[2014-10-25T15:34:59+02:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)
</code>```

also note:

```<code>ls ~/.berkshelf/cookbooks
build-essential-2.1.2  znc-0.0.1
</code>```

Any suggestions why the cookbooks cannot be found?

EDIT:

Thanks for the quick answer. The solution was as John Bellone said to bundle exec berks vendor and change my client.rb configuration to:

```<code># ./client.rb
cookbook_path File.dirname(File.expand_path(__FILE__)) + '/berks-cookbooks'
</code>```

答:
All credit to @revau.lt's answer as I only made a couple tweaks for my own use. This may require a certain version of Berkshelf, but all the documentation I've seen implies you can use "PATH" at the end to tell it where to put the dependencies. This also explicitly cleans up the $tmpdir after since some of the files end up owned as root from the run.

I run this with the path to any chef cookbook repo with ./local-chef-client my_cookbook_name or ./local-chef-client path/to/chef-repos/specific_repo where the path gets resolved by pwd -P and cookbook is the basename of the $1 referenced in the script.

```<code>#!/bin/bash -x
: ${1:?"Usage: $0 ./path/to/cookbook [doit]"}
case $1 in
 .) cookbook=$(basename $(pwd -P $1));repodir=$(dirname $(pwd -P $1));;
 *) cookbook=$(basename $1);repodir=$(pwd -P $1);;
esac
case $2 in
 doit) whyrun="";;
 *) whyrun="-W ";;
esac
realcookbook=$(grep '^name' $repodir/$cookbook/metadata.rb | sed "s/'//g" | awk '{ print $2 }')
# echo "cookbook is $cookbook"
# echo "realcookbook is $realcookbook"
# echo "repodir is $repodir"
cmd="berks vendor -b $repodir/$cookbook/Berksfile cookbooks"
tmpdir=$(mktemp -d)
pushd $tmpdir
$cmd
sudo chef-client $whyrun -z -o "$realcookbook"
popd
sudo rm -rf $tmpdir
if [ ! "${whyrun}x" == "x" ]; then echo "Append 'doit' after the recipe name to really apply, eg $0 $1 doit"; fi
</code>```

This should handle the case that somebody runs it from INSIDE the repo, or pretty much any path to the repo. I'll have to write some BATS tests someday to prove that, but for now it works splendidly.

I updated it to handle folders that don't match the cookbook name in case the repository name doesn't match or somebody cloned to a custom path. I actually had somebody try this under my direction and then had to dig in to Chef a bit and find out why it didn't work, turns out the folder name matters a little less than the recipe/cookbook name.

Body:
I'm new to chef and ran into problems with berkshelf and chef-client. I want to have my own cookbook with dependencies and apply it. My initial cookbook looks like this:

.
├── Berksfile
├── Berksfile.lock
├── chefignore
├── client.rb
├── Gemfile
├── Gemfile.lock
├── metadata.rb
├── README.md
└── recipes
    └── default.rb

#./Berksfile
source 'https://supermarket.getchef.com'

metadata

cookbook 'znc'

#./client.rb
cookbook_path '~/.berkshelf/cookbooks'

and when I run sudo bundle exec chef-client -z -o znc --config=client.rb the chef-client cannot find the cookbook:

Starting Chef Client, version 11.16.4
[2014-10-25T15:34:59+02:00] WARN: Run List override has been provided.
[2014-10-25T15:34:59+02:00] WARN: Original Run List: []
[2014-10-25T15:34:59+02:00] WARN: Overridden Run List: [recipe[znc]]
resolving cookbooks for run list: ["znc"]

================================================================================
Error Resolving Cookbooks for Run List:
================================================================================

Missing Cookbooks:
------------------
No such cookbook: znc

Expanded Run List:
------------------
* znc

Running handlers:
[2014-10-25T15:34:59+02:00] ERROR: Running exception handlers
Running handlers complete
[2014-10-25T15:34:59+02:00] ERROR: Exception handlers complete
[2014-10-25T15:34:59+02:00] FATAL: Stacktrace dumped to /home/sebastian/.chef/local-mode-cache/cache/chef-stacktrace.out
Chef Client failed. 0 resources updated in 3.474758165 seconds
[2014-10-25T15:34:59+02:00] ERROR: 412 "Precondition Failed "
[2014-10-25T15:34:59+02:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)

also note:

ls ~/.berkshelf/cookbooks
build-essential-2.1.2  znc-0.0.1

Any suggestions why the cookbooks cannot be found?

EDIT:

Thanks for the quick answer. The solution was as John Bellone said to bundle exec berks vendor and change my client.rb configuration to:

# ./client.rb
cookbook_path File.dirname(File.expand_path(__FILE__)) + '/berks-cookbooks'

Body:
All credit to @revau.lt's answer as I only made a couple tweaks for my own use. This may require a certain version of Berkshelf, but all the documentation I've seen implies you can use "PATH" at the end to tell it where to put the dependencies. This also explicitly cleans up the $tmpdir after since some of the files end up owned as root from the run.

I run this with the path to any chef cookbook repo with ./local-chef-client my_cookbook_name or ./local-chef-client path/to/chef-repos/specific_repo where the path gets resolved by pwd -P and cookbook is the basename of the $1 referenced in the script.

#!/bin/bash -x
: ${1:?"Usage: $0 ./path/to/cookbook [doit]"}
case $1 in
 .) cookbook=$(basename $(pwd -P $1));repodir=$(dirname $(pwd -P $1));;
 *) cookbook=$(basename $1);repodir=$(pwd -P $1);;
esac
case $2 in
 doit) whyrun="";;
 *) whyrun="-W ";;
esac
realcookbook=$(grep '^name' $repodir/$cookbook/metadata.rb | sed "s/'//g" | awk '{ print $2 }')
# echo "cookbook is $cookbook"
# echo "realcookbook is $realcookbook"
# echo "repodir is $repodir"
cmd="berks vendor -b $repodir/$cookbook/Berksfile cookbooks"
tmpdir=$(mktemp -d)
pushd $tmpdir
$cmd
sudo chef-client $whyrun -z -o "$realcookbook"
popd
sudo rm -rf $tmpdir
if [ ! "${whyrun}x" == "x" ]; then echo "Append 'doit' after the recipe name to really apply, eg $0 $1 doit"; fi

This should handle the case that somebody runs it from INSIDE the repo, or pretty much any path to the repo. I'll have to write some BATS tests someday to prove that, but for now it works splendidly.

I updated it to handle folders that don't match the cookbook name in case the repository name doesn't match or somebody cloned to a custom path. I actually had somebody try this under my direction and then had to dig in to Chef a bit and find out why it didn't work, turns out the folder name matters a little less than the recipe/cookbook name.


问:
Strikethrough UITableViewCell text field after cell is "complete"
How can I strikethrough text in a UITableViewCell during and after a UIContextualAction? (If it can't be done during, after only would be helpful)

Strikethrough example

```<code>func tableView(_ tableView: UITableView,
               leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
    let doneAction = UIContextualAction(style: .normal, title:  "DONE", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
        print("Done left")

        self.dailyTasks.append("\(self.dailyTasks[indexPath.row])")
        self.dailyTasks.remove(at: indexPath.row)

        UserDefaults.standard.set(self.dailyTasks, forKey: "dailyTasks")

        self.dailyTable.reloadData()

        success(true)

    })
    doneAction.backgroundColor = .darkGray

    return UISwipeActionsConfiguration(actions: [doneAction])

}
</code>```

答:
You should display label text as attributedtext. Try this code. The getRespectiveCell method is not implemented. Put your own logic to get respective cell for that indexpath

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your Text")
    attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))

let cell = getRespectiveCell(indexPath.row)
cell.textLabel.attributedText = attributeString
```

Body:
How can I strikethrough text in a UITableViewCell during and after a UIContextualAction? (If it can't be done during, after only would be helpful)

Strikethrough example

func tableView(_ tableView: UITableView,
               leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
    let doneAction = UIContextualAction(style: .normal, title:  "DONE", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
        print("Done left")

        self.dailyTasks.append("\(self.dailyTasks[indexPath.row])")
        self.dailyTasks.remove(at: indexPath.row)

        UserDefaults.standard.set(self.dailyTasks, forKey: "dailyTasks")

        self.dailyTable.reloadData()

        success(true)

    })
    doneAction.backgroundColor = .darkGray

    return UISwipeActionsConfiguration(actions: [doneAction])

}


问:
Pandas How to Not Include Grouping Index in Groupby-Apply
In Pandas, if I perform a groupby-apply operation and look at each of the 'groupby' objects, the grouping index are retained.

```<code>>>> df = pd.DataFrame({'gender':['M','M','F','F','F','M'],'age':[10,10,20,20,30,30],'income':[10000,15000,20000,25000,30000,35000],'education':[0,1,2,2,2,3]})
>>> df
   age  education gender  income
0   10          0      M   10000
1   10          1      M   15000
2   20          2      F   20000
3   20          2      F   25000
4   30          2      F   30000
5   30          3      M   35000
>>> df.groupby(['age','education']).apply(lambda x:x.iloc[np.argmax(x['income'].values),:])
                age  education gender  income
age education
10  0           10          0      M   10000
    1           10          1      M   15000
20  2           20          2      F   25000
30  2           30          2      F   30000
    3           30          3      M   35000
</code>```

You can see here that ['age','education'] appear on both the index and the values in the returns. This to me is redundant and clumsy to work with. Is there a way to not include the grouping index in the 'groupby' object? For example, to get something like this:

```<code>                gender  income
age education
10  0           M       10000
    1           M       15000
20  2           F       25000
30  2           F       30000
    3           M       35000
</code>```

P.S. I know I can call dropindex() but just want to know if there is a cleaner way, and is there any reason to retain the grouping index in the grouped object. I come from R world to Python, and in R data.table, you can do the same operation in a concise manner with dt[,.SD[which.max(income)],by=.(age,education)]

答:
The groupby syntax can be a little clunky, I admit.  But it's a little cleaner if you find the indices of the maximal incomes and use that to index into df:</p>

```<code>In [46]: df.groupby(['age','education'])['income'].idxmax()
Out[46]:
age  education
10   0            0
     1            1
20   2            3
30   2            4
     3            5
Name: income, dtype: int64

In [47]: df.loc[df.groupby(['age','education'])['income'].idxmax()]
Out[47]:
   age  education gender  income
0   10          0      M   10000
1   10          1      M   15000
3   20          2      F   25000
4   30          2      F   30000
5   30          3      M   35000
</code>```

Body:
In Pandas, if I perform a groupby-apply operation and look at each of the 'groupby' objects, the grouping index are retained.

>>> df = pd.DataFrame({'gender':['M','M','F','F','F','M'],'age':[10,10,20,20,30,30],'income':[10000,15000,20000,25000,30000,35000],'education':[0,1,2,2,2,3]})
>>> df
   age  education gender  income
0   10          0      M   10000
1   10          1      M   15000
2   20          2      F   20000
3   20          2      F   25000
4   30          2      F   30000
5   30          3      M   35000
>>> df.groupby(['age','education']).apply(lambda x:x.iloc[np.argmax(x['income'].values),:])
                age  education gender  income
age education
10  0           10          0      M   10000
    1           10          1      M   15000
20  2           20          2      F   25000
30  2           30          2      F   30000
    3           30          3      M   35000

You can see here that ['age','education'] appear on both the index and the values in the returns. This to me is redundant and clumsy to work with. Is there a way to not include the grouping index in the 'groupby' object? For example, to get something like this:

                gender  income
age education
10  0           M       10000
    1           M       15000
20  2           F       25000
30  2           F       30000
    3           M       35000

P.S. I know I can call dropindex() but just want to know if there is a cleaner way, and is there any reason to retain the grouping index in the grouped object. I come from R world to Python, and in R data.table, you can do the same operation in a concise manner with dt[,.SD[which.max(income)],by=.(age,education)]

Body:
The groupby syntax can be a little clunky, I admit.  But it's a little cleaner if you find the indices of the maximal incomes and use that to index into df:

In [46]: df.groupby(['age','education'])['income'].idxmax()
Out[46]:
age  education
10   0            0
     1            1
20   2            3
30   2            4
     3            5
Name: income, dtype: int64

In [47]: df.loc[df.groupby(['age','education'])['income'].idxmax()]
Out[47]:
   age  education gender  income
0   10          0      M   10000
1   10          1      M   15000
3   20          2      F   25000
4   30          2      F   30000
5   30          3      M   35000


问:
Makefile will link files upon a file change, but not recompile the source file that changed
I have the following makefile which seems to work pretty well:

```<code>HDRS =  include/config.h include/opcode_def.h include/x86lib.h include/x86lib_internal.h
CXX ?= g++
AR ?= ar

TEST_CC ?= i386-elf-gcc
TEST_CFLAGS ?= -fdata-sections -ffunction-sections

CXX_VM_SRC = vm/x86lib.cpp vm/modrm.cpp vm/device_manager.cpp vm/cpu_helpers.cpp vm/ops/strings.cpp vm/ops/store.cpp vm/ops/maths.cpp \
          vm/ops/groups.cpp vm/ops/flow.cpp vm/ops/flags.cpp vm/ops/etc.cpp

CXX_VM_OBJS = $(subst .cpp,.o,$(CXX_VM_SRC))

CXX_TESTBENCH_SRC = testbench/testbench.cpp

CXX_TESTBENCH_OBJS = $(subst .cpp,.o,$(CXX_TESTBENCH_SRC))

CXXFLAGS ?= -Wall -g3 -fexceptions -fPIC -Wall
CXXFLAGS += -DX86LIB_BUILD -I./include

VERSION=1.1

VM_OUTPUTS = libx86lib.a libx86lib.so.$(VERSION)
OUTPUTS = $(VM_OUTPUTS) x86testbench

default: build

build: $(OUTPUTS)

libx86lib.a: $(CXX_VM_OBJS) $(CXX_VM_SRC)
    ar crs libx86lib.a $(CXX_VM_OBJS)

libx86lib.so.$(VERSION): $(CXX_VM_OBJS) $(CXX_VM_SRC)
    $(CXX) -shared $(CXX_VM_OBJS) -o libx86lib.so.$(VERSION)

x86testbench: $(CXX_TESTBENCH_OBJS) $(VM_OUTPUTS)
    $(CXX) $(CXXFLAGS) -static -o x86testbench $(CXX_TESTBENCH_OBJS) -lx86lib -L.

$(CXX_TESTBENCH_OBJS): $(HDRS)
    $(CXX) $(CXXFLAGS) -c $*.cpp -o $@

$(CXX_VM_OBJS): $(HDRS)
    $(CXX) $(CXXFLAGS) -c $*.cpp -o $@

clean:
    rm $(CXX_VM_OBJS) $(OUTPUTS) $(CXX_TESTBENCH_OBJS)
</code>```

My problem is that if I change a file, such as "vm/x86lib.cpp" then it will relink the final outputs and such, but it will not recompile vm/x86lib.o. I don't know how to express this recompile requirement to the $(CXX_VM_OBJS) build rule.

How do I fix this so that it will recompile my the source files as well as relink them?

Note: if I put $(CXX_VM_SRC) as a dependency on $(CXX_VM_OBJS), then it will recompile every file anytime a single file changes. Also, I'm only concerned about GNU Make and OSX/Linux environments.

答:
As others have pointed out, the reason your makefile doesn't rebuild any object files when a source changes is that your rule:

```<code>$(CXX_VM_OBJS): $(HDRS)
    ...
</code>```

doesn't mention that the source files are prerequisites. And the reason the proposed solution of adding them:

```<code>$(CXX_VM_OBJS): $(HDRS) $(CXX_VM_SRC)
    ...
</code>```

causes Make to rebuild all source files when any source file changes, is that that is exactly what this rule demands. It makes all source files prerequisites of any object file.

The right way to handle this is with a static pattern rule:

```<code>$(CXX_VM_OBJS): %.o: %.cpp $(HDRS)
    ...
</code>```

And I would recommend the same for your $(CXX_TESTBENCH_OBJS) rule; even though it applies to only one object file now, it's clear that you are thinking of adding others later.

Body:
I have the following makefile which seems to work pretty well:

HDRS =  include/config.h include/opcode_def.h include/x86lib.h include/x86lib_internal.h
CXX ?= g++
AR ?= ar

TEST_CC ?= i386-elf-gcc
TEST_CFLAGS ?= -fdata-sections -ffunction-sections

CXX_VM_SRC = vm/x86lib.cpp vm/modrm.cpp vm/device_manager.cpp vm/cpu_helpers.cpp vm/ops/strings.cpp vm/ops/store.cpp vm/ops/maths.cpp \
          vm/ops/groups.cpp vm/ops/flow.cpp vm/ops/flags.cpp vm/ops/etc.cpp

CXX_VM_OBJS = $(subst .cpp,.o,$(CXX_VM_SRC))

CXX_TESTBENCH_SRC = testbench/testbench.cpp

CXX_TESTBENCH_OBJS = $(subst .cpp,.o,$(CXX_TESTBENCH_SRC))

CXXFLAGS ?= -Wall -g3 -fexceptions -fPIC -Wall
CXXFLAGS += -DX86LIB_BUILD -I./include

VERSION=1.1

VM_OUTPUTS = libx86lib.a libx86lib.so.$(VERSION)
OUTPUTS = $(VM_OUTPUTS) x86testbench

default: build

build: $(OUTPUTS)

libx86lib.a: $(CXX_VM_OBJS) $(CXX_VM_SRC)
    ar crs libx86lib.a $(CXX_VM_OBJS)

libx86lib.so.$(VERSION): $(CXX_VM_OBJS) $(CXX_VM_SRC)
    $(CXX) -shared $(CXX_VM_OBJS) -o libx86lib.so.$(VERSION)

x86testbench: $(CXX_TESTBENCH_OBJS) $(VM_OUTPUTS)
    $(CXX) $(CXXFLAGS) -static -o x86testbench $(CXX_TESTBENCH_OBJS) -lx86lib -L.

$(CXX_TESTBENCH_OBJS): $(HDRS)
    $(CXX) $(CXXFLAGS) -c $*.cpp -o $@

$(CXX_VM_OBJS): $(HDRS)
    $(CXX) $(CXXFLAGS) -c $*.cpp -o $@

clean:
    rm $(CXX_VM_OBJS) $(OUTPUTS) $(CXX_TESTBENCH_OBJS)

My problem is that if I change a file, such as "vm/x86lib.cpp" then it will relink the final outputs and such, but it will not recompile vm/x86lib.o. I don't know how to express this recompile requirement to the $(CXX_VM_OBJS) build rule.

How do I fix this so that it will recompile my the source files as well as relink them?

Note: if I put $(CXX_VM_SRC) as a dependency on $(CXX_VM_OBJS), then it will recompile every file anytime a single file changes. Also, I'm only concerned about GNU Make and OSX/Linux environments.

Body:
As others have pointed out, the reason your makefile doesn't rebuild any object files when a source changes is that your rule:

$(CXX_VM_OBJS): $(HDRS)
    ...

doesn't mention that the source files are prerequisites. And the reason the proposed solution of adding them:

$(CXX_VM_OBJS): $(HDRS) $(CXX_VM_SRC)
    ...

causes Make to rebuild all source files when any source file changes, is that that is exactly what this rule demands. It makes all source files prerequisites of any object file.

The right way to handle this is with a static pattern rule:

$(CXX_VM_OBJS): %.o: %.cpp $(HDRS)
    ...

And I would recommend the same for your $(CXX_TESTBENCH_OBJS) rule; even though it applies to only one object file now, it's clear that you are thinking of adding others later.


问:
RolesProvider asp.net mvc
Does public override string[] GetRolesForUser(string userId) always call to the database on every page load? How do I lower the database calls just to check the roles? Will it cause any security problems if it is cached?

答:
You can store them in a cookie using cacheRolesInCookie.

http://msdn.microsoft.com/en-us/library/ff647401.aspx

Title: RolesProvider asp.net mvc


问:
Facebook Audience Overlap via API
Is there a way to query the overlap feature as it's possible in the Business Manager via the php sdk for the marketing API?

I'm thinking sending two or more audience IDs of existing audiences and getting the overlap back? I couldn't find anything in the docs so far.

Any help is greatly appreciated!

答:
No. There is currently no php sdk support for this and the API call is not documented.

If you are willing to make direct call you could call graph.facebook.com/v2.10/act_< acctid >/audienceoverlap?access_token=< access_token >&comparison_ids=["< audienceid >"]&pivot_id=< audienceid >

Most likely you'll need the browser's access token for this.

Title: Facebook Audience Overlap via API


问:
composer runtime install command not recognized
I'm trying to install the fabric composer runtime on my local hyperledger fabric using the composer runtime install command but 'runtime' is not recognized as a command.

```<code>$ composer runtime install -n manuf-network -c PeerAdmin@hlfv1

Commands:
  archive <subcommand>      Composer archive command
  generator <subcommand>    Composer generator command to convert a Business Network Definition to code
  identity <subcommand>     Composer identity command
  network <subcommand>      Composer network command
  participant <subcommand>  Composer participant command
  transaction <subcommand>  Composer transaction command
  shell                     Interactive shell  [aliases: shell, i]

Options:
  --help         Show help  [boolean]
  -v, --version  Show version number  [boolean]

Examples:
  composer archive create --inputDir .
  composer identity issue
  composer network deploy
  composer participant add
  composer transaction submit

For more information on Hyperledger Composer: https://hyperledger.github.io/composer/

Unknown arguments: n, c, runtime, install
</code>```

I have composer-cli installed as a global.

Here is the version:

```<code>$ composer --version

composer-cli                   v0.8.1
composer-admin                 v0.8.1
composer-client                v0.8.1
composer-common                v0.8.1
composer-runtime-hlf           v0.8.1
composer-runtime-hlfv1         v0.8.1
</code>```

I have uninstalled and re-installed composer-cli (npm uninstall/install -g composer-cli) but still cannot get it to recognize the runtime install command.

I see the latest version of composer is 15 but I can't get my system to recognize anything but 8.1 (see above).

As part of the Installing a Development Environments steps at https://hyperledger.github.io/composer/installing/development-tools.html, I installed nvm and am wondering if this has something to do with the problem.

答: The problem is that composer was installed at multiple locations - (it had been installed as the 8.1 version prior to the recent installation of nvm and as the most recent version subsequent to installation of nvm).  To fix the problem, I found and deleted all instances of composer (from .npm and from .nvm except for in the specific version of node that I am using within nvm).</p>

Body:
I'm trying to install the fabric composer runtime on my local hyperledger fabric using the composer runtime install command but 'runtime' is not recognized as a command.

$ composer runtime install -n manuf-network -c PeerAdmin@hlfv1

Commands:
  archive <subcommand>      Composer archive command
  generator <subcommand>    Composer generator command to convert a Business Network Definition to code
  identity <subcommand>     Composer identity command
  network <subcommand>      Composer network command
  participant <subcommand>  Composer participant command
  transaction <subcommand>  Composer transaction command
  shell                     Interactive shell  [aliases: shell, i]

Options:
  --help         Show help  [boolean]
  -v, --version  Show version number  [boolean]

Examples:
  composer archive create --inputDir .
  composer identity issue
  composer network deploy
  composer participant add
  composer transaction submit

For more information on Hyperledger Composer: https://hyperledger.github.io/composer/

Unknown arguments: n, c, runtime, install

I have composer-cli installed as a global.

Here is the version:

$ composer --version

composer-cli                   v0.8.1
composer-admin                 v0.8.1
composer-client                v0.8.1
composer-common                v0.8.1
composer-runtime-hlf           v0.8.1
composer-runtime-hlfv1         v0.8.1

I have uninstalled and re-installed composer-cli (npm uninstall/install -g composer-cli) but still cannot get it to recognize the runtime install command.

I see the latest version of composer is 15 but I can't get my system to recognize anything but 8.1 (see above).

As part of the Installing a Development Environments steps at https://hyperledger.github.io/composer/installing/development-tools.html, I installed nvm and am wondering if this has something to do with the problem.


问:
Correctly nesting If statements in For loops for R
I am attempting to create a new variable using information within another variable in my dataset.  This dataset contains 7 variables and over a million rows of data. Because of the size I thought it would be less difficult to create a new variable using an already existing variable with an if statement nested in a for loop as I want values for every iteration of the old variable.

The old variable is a categorical variable with 7 different values. Because of that I am trying to make 7 different variables with the the if statement. if the old variable = 1 the data point in the new variable = 1, if not 0. Same with the other variables

My code is as follows:

```<code>for (i in new_2001_2002_data$`Main Source of Power`)
  {
  No_Power = 0
    if (new_2001_2002_data$`Main Source of Power`=1)
      {
      No_Power = 1
      }
    else
      {
      No_Power = 0
      }
  }
</code>```

Yet I keep getting error messages all throughout the loop. I assume it has something to do with my usage of i, but that isnt the only problem

答:
Some potential mistakes:

Inside your if statement, when we perform comparison, we should use "==" rather than "=".

Note that your i variable is not used inside the loop.

Body:
I am attempting to create a new variable using information within another variable in my dataset.  This dataset contains 7 variables and over a million rows of data. Because of the size I thought it would be less difficult to create a new variable using an already existing variable with an if statement nested in a for loop as I want values for every iteration of the old variable.

The old variable is a categorical variable with 7 different values. Because of that I am trying to make 7 different variables with the the if statement. if the old variable = 1 the data point in the new variable = 1, if not 0. Same with the other variables

My code is as follows:

for (i in new_2001_2002_data$`Main Source of Power`)
  {
  No_Power = 0
    if (new_2001_2002_data$`Main Source of Power`=1)
      {
      No_Power = 1
      }
    else
      {
      No_Power = 0
      }
  }

Yet I keep getting error messages all throughout the loop. I assume it has something to do with my usage of i, but that isnt the only problem


问:
how to read the parameters from excel or other type of file and run the rest API request one by one using groovy script
I have soap ui project structure like below :
TestSuite
 TestCase
  TestStep
   Rest request (json)

I would like to get data from file (e.g) like below :

```<code>title description type name date surname

myTitle myDescription 111111 Maria 2017-01-01 Romano

myTitle myDescription1 222222 John 2017-01-02 Soprano

myTitle2 myDescription2 333333 Robert 2017-01-03 Hermano
</code>```

(any file : xls, csv, json) and run my rest request using data from file for each row in file.

```<code>{

 "action":"save",
   "value" : {

      "title":"${title}",
      "description":"${description}",
      "type":${type},
      "name":"${name}",
      "date":${date},
      "surname": "${surname}",
}

}
</code>```

How can I do this ?

答:
One way to do this is to get request content , parse it, change value, build request again , set request and send it.

There is lot of reference on web on how to parse excel with groovy like this . Look around, you may find more ways . So ,
If you have values in these groovy variables after parsing excel,

```<code>title
description
type name
date
urname
</code>```

then for a test case, you can do like below. I'll explain for one variable title , you can do others same way. Put this in a groovy test step of a test case and run

```<code> import groovy.json.*

 //get the test step
   getAllHttpSteps=testRunner.testCase.getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep)
    for (step in getAllHttpSteps){

    //get request content
    RawRequest = step.testRequest.getRequestContent()

    //Parse Json request content
    def slurper = new JsonSlurper()
    def parsed_MessageBody = slurper.parseText(RawRequest)

      //get the node you want to change and its new node value
       def TitleKey= value.title   //from your json

       //change desired json node in request
    def node= "parsed_MessageBody"+"."+TitleKey
    Eval.me('parsed_MessageBody', parsed_MessageBody, "$node = '$title'")

         //Build Json request again with new values
    def builder = new JsonBuilder(parsed_MessageBody)
    def json = builder.toPrettyString()
    json = groovy.json.StringEscapeUtils.unescapeJava(json)

      //set new request content to request
    step.testRequest.setRequestContent(json)

    //Run new request
    step.run(testRunner,testRunner.getRunContext())

    }
</code>```

Body:
I have soap ui project structure like below :
TestSuite
 TestCase
  TestStep
   Rest request (json)

I would like to get data from file (e.g) like below :

title description type name date surname

myTitle myDescription 111111 Maria 2017-01-01 Romano

myTitle myDescription1 222222 John 2017-01-02 Soprano

myTitle2 myDescription2 333333 Robert 2017-01-03 Hermano

(any file : xls, csv, json) and run my rest request using data from file for each row in file.

{

 "action":"save",
   "value" : {

      "title":"${title}",
      "description":"${description}",
      "type":${type},
      "name":"${name}",
      "date":${date},
      "surname": "${surname}",
}

}

How can I do this ?

Body:
One way to do this is to get request content , parse it, change value, build request again , set request and send it.

There is lot of reference on web on how to parse excel with groovy like this . Look around, you may find more ways . So ,
If you have values in these groovy variables after parsing excel,

title
description
type name
date
urname

then for a test case, you can do like below. I'll explain for one variable title , you can do others same way. Put this in a groovy test step of a test case and run

 import groovy.json.*

 //get the test step
   getAllHttpSteps=testRunner.testCase.getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep)
    for (step in getAllHttpSteps){

    //get request content
    RawRequest = step.testRequest.getRequestContent()

    //Parse Json request content
    def slurper = new JsonSlurper()
    def parsed_MessageBody = slurper.parseText(RawRequest)

      //get the node you want to change and its new node value
       def TitleKey= value.title   //from your json

       //change desired json node in request
    def node= "parsed_MessageBody"+"."+TitleKey
    Eval.me('parsed_MessageBody', parsed_MessageBody, "$node = '$title'")

         //Build Json request again with new values
    def builder = new JsonBuilder(parsed_MessageBody)
    def json = builder.toPrettyString()
    json = groovy.json.StringEscapeUtils.unescapeJava(json)

      //set new request content to request
    step.testRequest.setRequestContent(json)

    //Run new request
    step.run(testRunner,testRunner.getRunContext())

    }


问:
How to add images to the slides using python?
I am doing process automation. it involve adding of images to the slides (total 8 images, 2 per slide, even some text below it.). I could add the image using pptx. but images need some cropping. How do I go about cropping it ?
I also need to use some specific format for the slide. How to use that layout ?
If someone can give process flow for doing it, would be grateful. </p>

答:
Maybe you could use SlideMight, a data merge tool for PowerPoint.

Suppose you have the images in files, and a data file listing the file locations or URLs. You would then make a "pattern file", which is much like a PowerPoint template. There you make a slide with a table having 2 rows or columns; each image will get into a cell. You may add extra rows for some texts. Alternatively you can predefine 4 slides each having 2 placeholders for images, which are then named like image1 to image8.

Then let SlideMight generate the desired presentation. SlideMight will do the resizing, and span the table over extra slides as needed. Normally SlideMight runs in a GUI. It should also be able to run as a command line program, although this has not been tested lately (please let me know if you need it).

Would this be of use?

Disclaimer: I am the developer and vendor of SlideMight.


问:
cool project to use a genetic algorithm for?
I'm looking for a practical application to use a genetic algorithm for. Some things that have thought of are:

Website interface optimization

Vehicle optimization with a physics simulator

Genetic programming

Automatic test case generation

But none have really popped out at me. So if you had some free time (a few months) to spend on a genetic algorithms project, what would you choose to tackle?

答:
One topic with lots of possibilities is to use evolutionary algorithms to evolve strategies for game playing.  People have used evolution to generate strategies for poker, checkers/draughts, Go and many other games.  The J-GAP people have used genetic programming to evolve bots for Robocode.

I recently posted an introductory article about evolutionary computation.  It includes details of some of the things evolutionary algorithms have been used for.  Adam Marczyk has also written an excellent article with lots of examples.  The Genetic Argonaut blog contains dozens of links to interesting evolutionary projects.

A less common type of evolutionary algorithm is the learning classifier system.  This evolves a set of rules for classifying inputs.  It can be applied to the same kind of problems that neural networks are used for.  It could be interesting to develop an LCS for a particular problem, such as attempting to predict sports results based on form.

OwnerDisplayName: Ryan

OwnerDisplayName: Dan Dyer


问:
Need to design a table with loads of attributes which must all be searchable by SQL
I'm in a fix here. I'm building a home reservation site and the client requires a filter search facility to allow visitors to search and filter through properties based upon criteria. The thing is that his list of criteria is exceedingly long, largely boolean values and calculable values stuff like:

Attached bathroom, balcony, smoking, alcoholic, maximum number of occupants, cable TV, Internet, carpeted, airconditioning, central heating, room service, etc., etc., etc...

I'm thinking of having to create a field for each of these, but there's a very strong chance that the number of preferences might even go up. I dished out the idea of storing everying in a serialised object as a string as then it would be impossible to search using an SQL query. Do I have any options apart from setting up individual fields for each preference here?

Thanks. I'm using PHP MySQL.

答:
I would suggest creating a field for each criteria.  This is going to allow you to have a the fastest search capability.  With that being said you could always create a TEXT or a MEDIUMTEXT and store JSON in that field.  So you could use json_encode on an array such as:

```<code>$amenities['bathroom'] = 1;
$amenities['balcony'] = 1;
$amenities['smoking'] = 0;
</code>```

Then if you were looking for a home that had a balcony you could do:

```<code>SELECT * FROM `homes` WHERE `json_field` LIKE '%balcony: 1%'
</code>```

And instead of a LIKE you could always use FULLTEXT searches if you have that capability on your server.

Body:
I would suggest creating a field for each criteria.  This is going to allow you to have a the fastest search capability.  With that being said you could always create a TEXT or a MEDIUMTEXT and store JSON in that field.  So you could use json_encode on an array such as:

$amenities['bathroom'] = 1;
$amenities['balcony'] = 1;
$amenities['smoking'] = 0;

Then if you were looking for a home that had a balcony you could do:

SELECT * FROM `homes` WHERE `json_field` LIKE '%balcony: 1%'

And instead of a LIKE you could always use FULLTEXT searches if you have that capability on your server.


问:
How to catch changing of property in model by another property in ViewModel?
I have a problem with the extension of the model. I need to update AngleNegative property in same time as property Angle updated in Station class. AngleNegative property data based on data from Angle as you can see in example. I can't modify Station model, because it used in another VM and have same problem but with another properties. What solution of this can be?

```<code>  public class Station : BindableBase, IStation
     {
        //some properties
        .
        .
        .

        private int _angle;

        public int Angle
        {
            get => _angle;
            set => SetProperty(ref _angle, value);
        }
     }

public class ViewModel : BindableBase
    {
        private Station _station;
        public Station Station
        {
            get => _station;
            set => SetProperty(ref _station, value);
        }

        //delete this property duplicate and base on Station.Angle
        private int _angle;
        public int Angle
        {
            get => _angle;
            set
            {
                SetProperty(ref _angle, value);
                AngleNegative = value - 180;
            }
        }

        private int _angleNegative;

        public int AngleNegative
        {
            get => _angleNegative;
            set => SetProperty(ref _angleNegative, value);
        }
    }
</code>```

I think i can inherit VM from IStation, but its a lot of code duplicate after.

答:
I would do it by having a method on the ViewModel that listens for PropertyChanged events on its Station, like this:

```<code>public class ViewModel : BindableBase
{
    private Station _station;
    public Station Station
    {
        get => _station;
        set => SetProperty(ref _station, value);
    }

    private int _angleNegative;
    public int AngleNegative
    {
        get => _angleNegative;
        set => SetProperty(ref _angleNegative, value);
    }

    public ViewModel()
    {
        Station.PropertyChanged += Station_PropertyChanged;
    }

    private void Station_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "Angle")
        {
            AngleNegative = Station.Angle - 180;
        }
    }
}
</code>```

Body:
I have a problem with the extension of the model. I need to update AngleNegative property in same time as property Angle updated in Station class. AngleNegative property data based on data from Angle as you can see in example. I can't modify Station model, because it used in another VM and have same problem but with another properties. What solution of this can be?

  public class Station : BindableBase, IStation
     {
        //some properties
        .
        .
        .

        private int _angle;

        public int Angle
        {
            get => _angle;
            set => SetProperty(ref _angle, value);
        }
     }

public class ViewModel : BindableBase
    {
        private Station _station;
        public Station Station
        {
            get => _station;
            set => SetProperty(ref _station, value);
        }

        //delete this property duplicate and base on Station.Angle
        private int _angle;
        public int Angle
        {
            get => _angle;
            set
            {
                SetProperty(ref _angle, value);
                AngleNegative = value - 180;
            }
        }

        private int _angleNegative;

        public int AngleNegative
        {
            get => _angleNegative;
            set => SetProperty(ref _angleNegative, value);
        }
    }

I think i can inherit VM from IStation, but its a lot of code duplicate after.

Body:
I would do it by having a method on the ViewModel that listens for PropertyChanged events on its Station, like this:

public class ViewModel : BindableBase
{
    private Station _station;
    public Station Station
    {
        get => _station;
        set => SetProperty(ref _station, value);
    }

    private int _angleNegative;
    public int AngleNegative
    {
        get => _angleNegative;
        set => SetProperty(ref _angleNegative, value);
    }

    public ViewModel()
    {
        Station.PropertyChanged += Station_PropertyChanged;
    }

    private void Station_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "Angle")
        {
            AngleNegative = Station.Angle - 180;
        }
    }
}


问:
Dividing a bag of mixed candy
Assuming I have a bag of candy Ci with N pieces of candy. It's a mix of t different types of candy, Ti. I want to share it between my M friends.

Each of them has a preference for each type of candy, P(m,Ti) where m is one of the M friends. P(m,Ti) is an integer and distinct, and the sum of P(m,T) for each friend is 50 (each friend distributes 50 points as he wishes between the candy types, with no types getting the same amount of points).

We want to divide the N pieces of candy between all the m friends in such a way that everybody is pleased. All the candy needs to be divided. Each person does not need to be given the same amount of candy.

1) Is there any way to objectively reach a solution for the "perfect" way to divide the candy?

Assuming the answer to (1) is "no", we will define it as follows. Sm is sum[P(m,Tj)], where j is subset of i that m is given. The definition of the optimal solution is the distribution with the lowest possible standard deviation of Sm with highest possible average Sm as tie breaker.

2) What is the best way to approach this problem? Is there any known algorithms?

答:
For (2), we can find a starting point by letting each friend in turn pick a piece of candy until the bag is empty. Each friend will always pick the candy with the highest preference. We have to calculate Sm for multiple solutions where we alternate the pick order. This should yields us the best starting point.

A Genetic algorithm can the be used to further find better solutions.

Title: Dividing a bag of mixed candy


问:
go routines in ec2 instance
Im writing an app in golang, and I'm doing some tests in a c5.18xlarge ec2 instance from aws, which has 72 vCPUs.

Is it correct to say that the go routines will be distributed among the 72 vCPUs?

答:
As Go 1.5 Release Notes says

By default, Go programs run with GOMAXPROCS set to the number of cores available; in prior releases it defaulted to 1.

So starting from Go 1.5, the default value should be the number of cores.  Which means that yes, the go routines should be distributed among the 72 CPUs unless you do something like runtime.GOMAXPROCS(1)

Title: go routines in ec2 instance


问:
AudioKit - Drawing full waveform of file
I've been going through documentation looking for an answer for this.  I see that AudioKit can draw waveforms for in realtime as you record or playback, but I was wondering if you could load in a file and it draw the waveform in full so I can see the whole file's waveform without playing it back.

Any help would be greatly appreciated.  Even just a pointer to what object I should look into.

答:
You can also use the Objective C EZAudioPlot class which is in AudioKitUI:

```<code>let file = EZAudioFile(url: url)
guard let data = file?.getWaveformData() else { return }

let waveform = EZAudioPlot()
addSubview( waveform )
waveform.frame = NSMakeRect(0, 0, 200, 20)
waveform.plotType = EZPlotType.buffer
waveform.shouldFill = true
waveform.shouldMirror = true
waveform.color = NSColor.black
waveform.updateBuffer( data.buffers[0], withBufferSize: data.bufferSize )
</code>```

I haven't benchmarked the two methods, but the plot version is very fast for longer files. For stereo files, make two stacked plots using buffers[0] and [1]

Body:
You can also use the Objective C EZAudioPlot class which is in AudioKitUI:

let file = EZAudioFile(url: url)
guard let data = file?.getWaveformData() else { return }

let waveform = EZAudioPlot()
addSubview( waveform )
waveform.frame = NSMakeRect(0, 0, 200, 20)
waveform.plotType = EZPlotType.buffer
waveform.shouldFill = true
waveform.shouldMirror = true
waveform.color = NSColor.black
waveform.updateBuffer( data.buffers[0], withBufferSize: data.bufferSize )

I haven't benchmarked the two methods, but the plot version is very fast for longer files. For stereo files, make two stacked plots using buffers[0] and [1]


问:
JAXB provider Eclipselink MOXy ignores @XmlAccessorType(XmlAccessType.NONE)
I use @XmlAccessorType(XmlAccessType.NONE) in package-info.java for my.package which means JAXB should care only about annotated elements. However, when I run my JUnit test with un/marshalling code for simple POJO MOXy just screams about every class (even from package without jaxb.properties or from other maven modules which are referenced in dependencies) in this manner:

```<code>Exception Description: The class other.maven.module.package.class requires a zero argument constructor or a specified factory method.  Note that non-static inner classes do not have zero argument constructors and are not supported.
</code>```

I haven't encountered such issue with Metro (reference implementation, but it has other defects for my usage) and unfortunately I really can't modify every class in this way.

答:
I have been able to verify this issue, the following bug has been entered to track this issue.

https://bugs.eclipse.org/334681

Issue summary:

For the following object model:

```<code>import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;

@XmlAccessorType(XmlAccessType.NONE)
public class Foo {

    private Bar bar;

    public Bar getBar() {
        return bar;
    }

    public void setBar(Bar bar) {
        this.bar = bar;
    }

}
</code>```

and:

```<code>public class Bar {

    public Bar(String name) {
    }

}
</code>```

The EclipseLink MOXy JAXB implementation is processing the Bar class although it should not be, because it is not mapped.

Body:
I use @XmlAccessorType(XmlAccessType.NONE) in package-info.java for my.package which means JAXB should care only about annotated elements. However, when I run my JUnit test with un/marshalling code for simple POJO MOXy just screams about every class (even from package without jaxb.properties or from other maven modules which are referenced in dependencies) in this manner:

Exception Description: The class other.maven.module.package.class requires a zero argument constructor or a specified factory method.  Note that non-static inner classes do not have zero argument constructors and are not supported.

I haven't encountered such issue with Metro (reference implementation, but it has other defects for my usage) and unfortunately I really can't modify every class in this way.

Body:
I have been able to verify this issue, the following bug has been entered to track this issue.

https://bugs.eclipse.org/334681

Issue summary:

For the following object model:

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;

@XmlAccessorType(XmlAccessType.NONE)
public class Foo {

    private Bar bar;

    public Bar getBar() {
        return bar;
    }

    public void setBar(Bar bar) {
        this.bar = bar;
    }

}

and:

public class Bar {

    public Bar(String name) {
    }

}

The EclipseLink MOXy JAXB implementation is processing the Bar class although it should not be, because it is not mapped.


问:
Action on Google Test Account
Im virtually ready to send my Actions on Google App live for Google Home. It uses Account Linking to link a Google Account. I don't handle login as such, I just use the inbuilt routine to detect if the user is logged in and push them over to a Google Auth page which takes care of everything and I get the results back to generate a code.

The notes for submission say that if we're using account linking:

Your agent requires account linking so you must provide a username and
  password for a test account. Please make sure that any provided
  accounts are not real user accounts. This information will only be
  used by the review team, and will not be visible to users.

What is not clear at this step, is what credentials I give to the review team to be able to test. I don't process any logins. Do I need to enable Email/Password authentication in Firebase then or something and on my OAuth page request Username/Password then authenticating with Firebase?

答:
The answer lies in how you're authenticating the user:

push them over to a Google Auth page which takes care of everything

So you're expecting your users to login with some account (I assume you mean a Google account in this case) and you are either using the code that comes back as the auth code or getting the userid and using that to authenticate the user or something else along those lines.

Basically - you need to create whatever you expect them to do as if they were a user. If you're expecting your users to log in using a Google account - create a Google account for them to use. If you're expecting them to login with Email/Password auth in Firebase - set that up. But setup an account with however you expect your users to do so.

Title: Action on Google Test Account


问:
Add more grouping to grouped bar chart
I am making a grouped bar chart, for which the script is given at this link:
    https://jsfiddle.net/yL5z1q04/4/

Here I have groups of "salary" and "investment" for rank_buckets. Now, I want to add one more level of "grouping" on X-Axis based on "nation" key given in data.

My data is as follows:

```<code> var data = [
    {group: "investment", height: 84636, rank_bucket: "a", nation: "United States"},
    {group: "salary", height: 76536, rank_bucket: "a", nation: "United States"},
    {group: "investment", height: 84636, rank_bucket: "a", nation: "Australia"},
    {group: "salary", height: 76536, rank_bucket: "a", nation: "Australia"},
    {group: "investment", height: 89626, rank_bucket: "b", nation: "Australia"},
    {group: "salary", height: 98234, rank_bucket: "b", nation: "Australia"},
    {group: "investment", height: 89626, rank_bucket: "b", nation: "United States"},
    {group: "salary", height: 98234, rank_bucket: "b", nation: "United States"}

   ];
</code>```

The expected output should look somewhat like this:

How do I do this? I want to have "nation" information depicted on X-Axis along with rank_bucket.

Thanks!

答:
you can create multiple scaleBands, for rank_bucket, nation and group.

For each scales' range width, use the each bandwidth() of the preceding scale. For example,

```<code>var xscale_rank_bucket = d3.scaleBand()
          .rangeRound([0,width])
          .padding(0.2)
          .domain(Array.from(rank_buckets));

var xscale_nation = d3.scaleBand()
          .rangeRound([0,xscale_rank_bucket.bandwidth()])
          .padding(0.1)
          .domain(Array.from(nations));
</code>```

You had done some of this already, but it just needed extending to the third scale.

Also, you can create multiple x-axes for nation and rank_bucket.  For the nation axes, you will need one per rank_bucket, so you can add them based on a rank_bucket data join, for example:

```<code>var axisNationG = axes.selectAll(".axis-nation")
        .data(Array.from(rank_buckets))
      .enter()
      .append("g")
      .attr("transform", function(d){
        return "translate(" + xscale_rank_bucket(d) + ",0)"
      })
      .attr("class", "x axis")
      .call(axisNation)
</code>```

The axes can be translated and styled to look like your mock up.

https://jsfiddle.net/yL5z1q04/5/

PS - The updated fiddle uses Sets to extract the unique values for each scale, and converts the Sets to Arrays for use in the scales and data joins.

Title: Add more grouping to grouped bar chart

Body:
I am making a grouped bar chart, for which the script is given at this link:
    https://jsfiddle.net/yL5z1q04/4/

Here I have groups of "salary" and "investment" for rank_buckets. Now, I want to add one more level of "grouping" on X-Axis based on "nation" key given in data.

My data is as follows:

 var data = [
    {group: "investment", height: 84636, rank_bucket: "a", nation: "United States"},
    {group: "salary", height: 76536, rank_bucket: "a", nation: "United States"},
    {group: "investment", height: 84636, rank_bucket: "a", nation: "Australia"},
    {group: "salary", height: 76536, rank_bucket: "a", nation: "Australia"},
    {group: "investment", height: 89626, rank_bucket: "b", nation: "Australia"},
    {group: "salary", height: 98234, rank_bucket: "b", nation: "Australia"},
    {group: "investment", height: 89626, rank_bucket: "b", nation: "United States"},
    {group: "salary", height: 98234, rank_bucket: "b", nation: "United States"}

   ];

The expected output should look somewhat like this:

How do I do this? I want to have "nation" information depicted on X-Axis along with rank_bucket.

Thanks!

Body:
you can create multiple scaleBands, for rank_bucket, nation and group.

For each scales' range width, use the each bandwidth() of the preceding scale. For example,

var xscale_rank_bucket = d3.scaleBand()
          .rangeRound([0,width])
          .padding(0.2)
          .domain(Array.from(rank_buckets));

var xscale_nation = d3.scaleBand()
          .rangeRound([0,xscale_rank_bucket.bandwidth()])
          .padding(0.1)
          .domain(Array.from(nations));

You had done some of this already, but it just needed extending to the third scale.

Also, you can create multiple x-axes for nation and rank_bucket.  For the nation axes, you will need one per rank_bucket, so you can add them based on a rank_bucket data join, for example:

var axisNationG = axes.selectAll(".axis-nation")
        .data(Array.from(rank_buckets))
      .enter()
      .append("g")
      .attr("transform", function(d){
        return "translate(" + xscale_rank_bucket(d) + ",0)"
      })
      .attr("class", "x axis")
      .call(axisNation)

The axes can be translated and styled to look like your mock up.

https://jsfiddle.net/yL5z1q04/5/

PS - The updated fiddle uses Sets to extract the unique values for each scale, and converts the Sets to Arrays for use in the scales and data joins.


问:
Storing metadata about password hashes in the database?
I was talking to a friend of mine and he stated that to store user passwords in the database, he, and I quote:

Takes a users password

Hashes it with a random salt

Then, he prefixes the result of #2 with the hash type and the salt, joining them with a pipe delimited string. (e.g. SHA1|RANDOMSALT|afde4343....)

Stores result of #3 in the db

He claims that's it readable, as he "can instantly know" what type of hash digest is used.

I don't think I've ever seen this before, but, I'm looking for reasons on why it would be bad aside from the fact than an unauthorized user can instantly know what type of hash is used to encrypt the passwords and the extra space required for storing the field.

My gut reaction is that this approach to working with passwords is silly, as any indication to help an attacker break passwords is a weakness. Any other reasons I should use to convince him that this is a bad idea?

Thanks!

答:
It is a good idea. Everybody does that, including in the /etc/password (/etc/shadow...) file on Unix systems.

Any decent security model will assume that the attacker knows what kind of hash function is used, if only because the hashing system is a piece of software, store on a hard disk. Conversely, believing in the virtue of not announcing which hash function is used is akin to security through obscurity and that's bad.

So do not try to convince your friend that what he is doing is bad. Instead, let him convince you that what he is doing is good.

PS: this is not password encryption, this is password hashing. Hashing is not a kind of encryption.


问:
How programmatically push segue in Storyboard?

How to push view controller programmatically? In some case not button press but programmatic trigger needs. How?

Need write something like:

```<code>[self performSegueWithIdentifier:@"menu41" sender:self];
</code>```

or

```<code>[self.self.navigationController performSegueWithIdentifier:@"menu41" sender:self];
</code>```

Added an identifier "menu41" to segue.

答:
You should use   <code>[self performSegueWithIdentifier:@"menu41" sender:self];
</code>
See the Discussion section on Apple Dev forum </p>

Body:
How to push view controller programmatically? In some case not button press but programmatic trigger needs. How?

Need write something like:

[self performSegueWithIdentifier:@"menu41" sender:self];

or

[self.self.navigationController performSegueWithIdentifier:@"menu41" sender:self];

Added an identifier "menu41" to segue.

Body:
You should use   [self performSegueWithIdentifier:@"menu41" sender:self];

See the Discussion section on Apple Dev forum


问:
Is there a reason we cannot name a non-static member function in an unevaluated context?
When reading [expr.prim.id], one will see that

An id-expression that denotes a non-static data member or non-static
  member function of a class can only be used:

if that id-expression denotes a non-static data member and it appears in an unevaluated operand.

The fact that the bullet above applies only to data members is unclear to me. Intuitively I'd expect the following to be well formed:

```<code>#include <type_traits>

using func = int();

class bar {
  func foo; // This is valid, and not the subject of the question
};

static_assert(std::is_same<decltype(bar::foo), func>::value, "No Symmetry!");
</code>```

But the decltype() is ill-formed even before the static assertion is checked.

Is there some ambiguity I'm missing?

答:
Is there some ambiguity I'm missing?

I don't think so. It's probably more that there was a definite need to evaluate non-static data members and not so much for non-static member functions.

However, this:

```<code>static_assert(std::is_same<decltype(bar::foo), func>::value, "No Symmetry!");
</code>```

doesn't make much sense. The type of &bar::foo is not func*, it's func bar::*. And there isn't a way to spell that without a pointer, so having to be able to evaluate decltype(bar::foo) means introducing whole new type syntax? Doesn't seem worth it.

Note that decltype(bar::foo) cannot be func because func is a function type, but bar::foo is a member function.

Body:
When reading [expr.prim.id], one will see that

An id-expression that denotes a non-static data member or non-static
  member function of a class can only be used:

if that id-expression denotes a non-static data member and it appears in an unevaluated operand.

The fact that the bullet above applies only to data members is unclear to me. Intuitively I'd expect the following to be well formed:

#include <type_traits>

using func = int();

class bar {
  func foo; // This is valid, and not the subject of the question
};

static_assert(std::is_same<decltype(bar::foo), func>::value, "No Symmetry!");

But the decltype() is ill-formed even before the static assertion is checked.

Is there some ambiguity I'm missing?

Body:
Is there some ambiguity I'm missing?

I don't think so. It's probably more that there was a definite need to evaluate non-static data members and not so much for non-static member functions.

However, this:

static_assert(std::is_same<decltype(bar::foo), func>::value, "No Symmetry!");

doesn't make much sense. The type of &bar::foo is not func*, it's func bar::*. And there isn't a way to spell that without a pointer, so having to be able to evaluate decltype(bar::foo) means introducing whole new type syntax? Doesn't seem worth it.

Note that decltype(bar::foo) cannot be func because func is a function type, but bar::foo is a member function.