答:
I like this syntax myself ( when working in mixed HTML/PHP )

```<code><?php
    $blogname = get_bloginfo('name');
    if ($blogname == 'Wobbling Willy'):  //-note- colon not semi-colon
?>
<meta name="description" content="<?= bloginfo('description'); ?>" />
<meta name="keywords" content=”keyword1, keyword2, keyword3” />
<?php endif; ?>
</code>```

OR

```<code><?php
    $blogname = get_bloginfo('name');
    if ($blogname == 'Wobbling Willy'){  //open bracket
?>
<meta name="description" content="<?= bloginfo('description'); ?>" />
<meta name="keywords" content=”keyword1, keyword2, keyword3” />
<?php } // close bracket?>
</code>```

It's shorter and you don't have to worry about quoting.  Or even use a heredoc
but that involves setting bloginfo('description') to a variable and a few other quirks...

```<code><?php
    $blogname = get_bloginfo('name');
    if ($blogname == 'Wobbling Willy'){  //open bracket
        $description = bloginfo('description');
        echo <<<HTML
            <meta name="description" content="$description" />
            <meta name="keywords" content=”keyword1, keyword2, keyword3” />
HTML; //nothing can go here no space ( before or after ) and not even this comment, nothing but HTML; litterally
    }
?>
</code>```

HEREDOC is my preferred way, but I never mix HTML and PHP in the same file.  Because I use a template system.

Title: How to nest php inside if statement

Body:
I like this syntax myself ( when working in mixed HTML/PHP )

<?php
    $blogname = get_bloginfo('name');
    if ($blogname == 'Wobbling Willy'):  //-note- colon not semi-colon
?>
<meta name="description" content="<?= bloginfo('description'); ?>" />
<meta name="keywords" content=”keyword1, keyword2, keyword3” />
<?php endif; ?>

OR

<?php
    $blogname = get_bloginfo('name');
    if ($blogname == 'Wobbling Willy'){  //open bracket
?>
<meta name="description" content="<?= bloginfo('description'); ?>" />
<meta name="keywords" content=”keyword1, keyword2, keyword3” />
<?php } // close bracket?>

It's shorter and you don't have to worry about quoting.  Or even use a heredoc
but that involves setting bloginfo('description') to a variable and a few other quirks...

<?php
    $blogname = get_bloginfo('name');
    if ($blogname == 'Wobbling Willy'){  //open bracket
        $description = bloginfo('description');
        echo <<<HTML
            <meta name="description" content="$description" />
            <meta name="keywords" content=”keyword1, keyword2, keyword3” />
HTML; //nothing can go here no space ( before or after ) and not even this comment, nothing but HTML; litterally
    }
?>

HEREDOC is my preferred way, but I never mix HTML and PHP in the same file.  Because I use a template system.


来源: stackexchange

问:
python: alternative way of built in function "any"
I'm working with python 2.4 and I need to use the function any which is not available in my python version.

Is there a function or expression that I can use to replace it?

I need to find if at least one element of a string list is in a text Line.

答:
The any function is rather easy to re-implement.

The idea is just to iterate over an iterable, and as soon as a truthy object is found, return True; else return False.

Without cheating and peeking at the doc, here is a re-implementation:

```<code>def my_any(iterable):
    for it_element in iterable:
        if it_element:
            return True
    return False
</code>```

Now with the doc's version:

```<code>def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
</code>```

It's so easy, my version is exactly the same as the doc's.

About how to use it...
The any function takes an iterable.
It's generally used either with a list, or a generator expression.
For instance, if you want to check if any character of 'abcd' is in the line string:

```<code>any(it_character in line for it_character in 'abcd')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The any function is rather easy to re-implement.

The idea is just to iterate over an iterable, and as soon as a truthy object is found, return True; else return False.

Without cheating and peeking at the doc, here is a re-implementation:

def my_any(iterable):
    for it_element in iterable:
        if it_element:
            return True
    return False

Now with the doc's version:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

It's so easy, my version is exactly the same as the doc's.

About how to use it...
The any function takes an iterable.
It's generally used either with a list, or a generator expression.
For instance, if you want to check if any character of 'abcd' is in the line string:

any(it_character in line for it_character in 'abcd')


问:
Intellij SVN keeps asking for path to certificate when there is none
A slightly different version of this
Subversion in Intellij keeps asking for authentication

I enter my credentials just fine. Once I enter the correct credentials it takes me to a popup that asks for my path to certificate, and certificate passphrase.

This didn't used to happen until I changed my SVN password. Prior to this, simply enter in my SVN credentials would work fine without issue. Hitting cancel on that gives me an SVN:E175013 error, and hitting OK closes then reopens the same box.

The same issue does not happen in Eclipse. Simply providing the userid and pwd will allow me to access SVN, this is only happening in intellij.

So I cleared the SVN settings for my PC in the %APPDATA% path, as well as my Intellij svn's directory (.IntelliJIdea2017.1\system) I cleaned vcs/vcsCache and vcs-users in that folder.

My Intellij info

IntelliJ IDEA 2017.1.3

Build #IU-171.4424.56

JRE: 1.8.0_112-release-736-b21 amd64

JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Windows 7 6.1

I'm using svn 1.9.5.1210.

答:
Seems similar to https://youtrack.jetbrains.com/issue/IDEA-150404

Try clearing SVN credential cache using Settings - Version control - SUbverion - General | Clear auth cache button


问:
Can't register my jQuery script in WordPress
For some reason my jQuery script is not being registered, I believe I am doing it correctly but maybe I'm missing something. Here's my code: </p>

```<code>/*registering script*/
    function register_my_script(){
        wp_register_script('alliance_script', get_template_directory_uri() . '/js/script.js');
    }
    add_action('enqueue_scripts', 'register_my_script');
</code>```

答:
In WordPress used wp_enqueue_scripts() to register your scripts.

For more information click here

```<code>add_action('wp_enqueue_scripts', 'my_enqueue_scripts');

function my_enqueue_scripts() {

   wp_register_script( 'alliance_script', get_template_directory_uri() . '/js/script.js');
   wp_enqueue_script( 'alliance_script' );
}
</code>```

wp_register_script vs. wp_enqueue_script

wp_register_script() function makes your scripts available for use while wp_enqueue_script() functions loads the script to the theme/plugin.

You can register without enqueuing. But to load the script on the page, you need to enqueue. If you register the script, you can then enqueue it by its handle alone. If you don’t register it ahead of time, you will need to provide the full parameters in the enqueue function.

You can skip the register function for the scripts that you are going to enqueue right away. Also, you don’t need to register scripts which are included in WordPress.

Body:
For some reason my jQuery script is not being registered, I believe I am doing it correctly but maybe I'm missing something. Here's my code:

/*registering script*/
    function register_my_script(){
        wp_register_script('alliance_script', get_template_directory_uri() . '/js/script.js');
    }
    add_action('enqueue_scripts', 'register_my_script');

Body:
In WordPress used wp_enqueue_scripts() to register your scripts.

For more information click here

add_action('wp_enqueue_scripts', 'my_enqueue_scripts');

function my_enqueue_scripts() {

   wp_register_script( 'alliance_script', get_template_directory_uri() . '/js/script.js');
   wp_enqueue_script( 'alliance_script' );
}

wp_register_script vs. wp_enqueue_script

wp_register_script() function makes your scripts available for use while wp_enqueue_script() functions loads the script to the theme/plugin.

You can register without enqueuing. But to load the script on the page, you need to enqueue. If you register the script, you can then enqueue it by its handle alone. If you don’t register it ahead of time, you will need to provide the full parameters in the enqueue function.

You can skip the register function for the scripts that you are going to enqueue right away. Also, you don’t need to register scripts which are included in WordPress.


问:
Initialising mock in new objects
My class cannot autowired UserService - it throws NullPointerException. I would like to find a way to test UserValidator class. I don't know how to inject mocks in ExistingValidationRule class.</p>

```<code>public class ExistingValidationRule implements RegistrationRule<User> {
@Autowired
private UserService service;

@Override
public void validate(User user, Errors errors) {

    service.find(user, errors);
}
}

@Component
public class UserValidator implements Validator {

    @Override
    public void validate(Object o, Errors errors) {
        User user = (User) o;
        rules.add(new ExistingValidationRule());

        for(RegistrationRule<User> rule : rules){
            rule.validate(user, errors);
        }
    }
}

public class UserValidatorTest {
@InjectMocks
private UserValidator userValidator;

@InjectMocks
private ExistingValidationRule existingValidationRule;

@Mock
private UserService service;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}
@Test
    public void testValidUser() throws Exception{

        userValidator.validate(createdUser,errors);
}
</code>```

答:
@Autowired is a Spring annotation and unless you run your unit test with a Spring test runner, this will just not do anything.

However, @InjectMocks of Mockito will just fill your fields with Mocks, as long as you provide a constructor to reach those fields. Try the following:

```<code>public class ExistingValidationRule implements RegistrationRule<User> {
    @Autowired
    private UserService service;

    public ExistingValidationRule(UserService service) {
        this.service = service;
    }

    public ExistingValidationRule() {
    }

    @Override
    public void validate(User user, Errors errors) {

        service.find(user, errors);
    }
}
</code>```

I added a second empty constructor for making Spring happy. The first one should do the trick for your unit test.

Happy testing!

Title: Initialising mock in new objects

Body:
My class cannot autowired UserService - it throws NullPointerException. I would like to find a way to test UserValidator class. I don't know how to inject mocks in ExistingValidationRule class.

public class ExistingValidationRule implements RegistrationRule<User> {
@Autowired
private UserService service;

@Override
public void validate(User user, Errors errors) {

    service.find(user, errors);
}
}

@Component
public class UserValidator implements Validator {

    @Override
    public void validate(Object o, Errors errors) {
        User user = (User) o;
        rules.add(new ExistingValidationRule());

        for(RegistrationRule<User> rule : rules){
            rule.validate(user, errors);
        }
    }
}

public class UserValidatorTest {
@InjectMocks
private UserValidator userValidator;

@InjectMocks
private ExistingValidationRule existingValidationRule;

@Mock
private UserService service;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}
@Test
    public void testValidUser() throws Exception{

        userValidator.validate(createdUser,errors);
}

Body:
@Autowired is a Spring annotation and unless you run your unit test with a Spring test runner, this will just not do anything.

However, @InjectMocks of Mockito will just fill your fields with Mocks, as long as you provide a constructor to reach those fields. Try the following:

public class ExistingValidationRule implements RegistrationRule<User> {
    @Autowired
    private UserService service;

    public ExistingValidationRule(UserService service) {
        this.service = service;
    }

    public ExistingValidationRule() {
    }

    @Override
    public void validate(User user, Errors errors) {

        service.find(user, errors);
    }
}

I added a second empty constructor for making Spring happy. The first one should do the trick for your unit test.

Happy testing!


问:
Implement Stack using Two Queues
A similar question was asked earlier there, but the question here is the reverse of it, using two queues as a stack.  The question...

Given two queues with their standard operations (enqueue, dequeue, isempty, size), implement a stack with its standard operations (pop, push, isempty, size).

There should be two versions of the solution.

Version A: The stack should be efficient when pushing an item; and

Version B: The stack should be efficient when popping an item.

I am interested in the algorithm more than any specific language implementations.  However, I welcome solutions expressed in languages which I am familiar (java,c#,python,vb,javascript,php).

答:
Here is very simple solution which uses one Queue and gives functionality like Stack.

```<code>public class CustomStack<T>
{
    Queue<T> que = new Queue<T>();

    public void push(T t) // STACK = LIFO / QUEUE = FIFO
    {

        if( que.Count == 0)
        {
            que.Enqueue(t);
        }
        else
        {
            que.Enqueue(t);
            for (int i = 0; i < que.Count-1; i++)
            {
                var data = que.Dequeue();

                que.Enqueue(data);
            }
        }

    }

    public void pop()
    {

        Console.WriteLine("\nStack Implementation:");
        foreach (var item in que)
        {
            Console.Write("\n" + item.ToString() + "\t");
        }

        var data = que.Dequeue();
        Console.Write("\n Dequeing :" + data);
    }

    public void top()
    {

        Console.Write("\n Top :" + que.Peek());
    }

}
</code>```

So in the above class named "CustomStack" what I am doing is just checking the queue for empty , if empty then insert one and from then on wards insert and then remove insert. By this logic first will come last.
Example : In queue I inserted 1 and now trying to insert 2. Second time remove 1 and again insert so it becomes in reverse order.

Thank you.

Title: Implement Stack using Two Queues

LastEditorDisplayName: rampion

Body:
Here is very simple solution which uses one Queue and gives functionality like Stack.

public class CustomStack<T>
{
    Queue<T> que = new Queue<T>();

    public void push(T t) // STACK = LIFO / QUEUE = FIFO
    {

        if( que.Count == 0)
        {
            que.Enqueue(t);
        }
        else
        {
            que.Enqueue(t);
            for (int i = 0; i < que.Count-1; i++)
            {
                var data = que.Dequeue();

                que.Enqueue(data);
            }
        }

    }

    public void pop()
    {

        Console.WriteLine("\nStack Implementation:");
        foreach (var item in que)
        {
            Console.Write("\n" + item.ToString() + "\t");
        }

        var data = que.Dequeue();
        Console.Write("\n Dequeing :" + data);
    }

    public void top()
    {

        Console.Write("\n Top :" + que.Peek());
    }

}

So in the above class named "CustomStack" what I am doing is just checking the queue for empty , if empty then insert one and from then on wards insert and then remove insert. By this logic first will come last.
Example : In queue I inserted 1 and now trying to insert 2. Second time remove 1 and again insert so it becomes in reverse order.

Thank you.


问:
Change foreach loop by for loop
I am creating a Fingerprint Verification System in which I have to match fingerprints using records in database.  I have used foreach loop to to so but it is taking almost 40 seconds for only 350 records.  I want to speed it up.  I want my foreach loop to convert into for loop but I am facing some difficulties in initializing the for loop.  Here is my code.

foreach (KeyValuePair<decimal, MemoryStream> tt in profileDic)
{
    this.Invoke(new Function(delegate()
    {
        textBox1.Text += "\n" + tt.Key.ToString();
    }));
    temp = new DPFP.Template(tt.Value);

    Verificator = new DPFP.Verification.Verification();
    featuresForVerification = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification);
    if (featuresForVerification != null)
    {
        DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
        Verificator.Verify(featuresForVerification, temp, ref result);

        #region UI Envoke
        this.Invoke(new Function(delegate()
        {
            if (result.Verified)
            {
                MessageBox.Show("FAR " + result.FARAchieved + "\n" + tt.Key.ToString());
            }
            else
            {
                //MessageBox.Show("No Match");
            }
        }));
        #endregion
    }
    this.Invoke(new Function(delegate()
    {
        progressBar1.Value += 1;
    }));
    Thread.CurrentThread.Priority = ThreadPriority.Highest;
}
```

I am confused at the first line foreach (KeyValuePair<decimal, MemoryStream> tt in profileDic).  Can someone tell me how I can iterate through every item in Dictionary object profileDic using a for loop.  I am not sure how to get KeyValuePair<decimal, MemoryStream> tt in profileDic when using a for loop.

答:
To answer your stated question: to replace a foreach loop with a for loop, replace:

```<code>foreach (KeyValuePair<decimal, MemoryStream> tt in profileDic)
{
    //...
}
</code>```

with

```<code>for (var i=0; i < profileDic.Count, i++)
{
    KeyValuePair<decimal, MemoryStream> tt = profileDic.ElementAt(i);
    //...
}
</code>```

To use this you'd also need to include a using System.Linq; statement in your code.
That said, this assumes that the order of elements in your dictionary will not change; which is not guaranteed (unless you're using a SortedDictionary or OrderedDictionary).
A better approach is therefore:

```<code>[decimal[]]keys = profileDic.Keys;
for (var i=0; i < keys.Count, i++)
{
    KeyValuePair<decimal, MemoryStream> tt = profileDic[keys[i]];
    //...
}
</code>```

But this adds more overhead / likely pushes the for loop's time over that of the foreach loop / is a micro-optimisation that won't solve your real performance issue.

Per comments, the loop is likely not your problem, but what's occurring within that loop (if in this part of the code at all).

We don't know enough about your code to comment on it, so it's likely best that you investigate yourself; e.g. using the performance analysis techniques described here: https://msdn.microsoft.com/en-us/library/ms182372.aspx

I've refactored your code to make it more readable (i.e. by pulling the UI updates into their own methods, so they don't clutter the main thread).

I also moved those operations which look like they wouldn't need to be updated each iteration outside of your loop... but without knowing your code this is pure guesswork / so no guarantees.

Finally I removed your code to alter the priority of the current thread at the end of each iteration.  Playing with thread priorities is not a good way to fix slow code; there are only certain cases where it's appropriate, and seeing it's context here I'm over 99% certain that this is not one of those cases.

```<code>//...
featuresForVerification = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification); //since this appears unaffected by our profileDic values, let's initialise once
if (featuresForVerification != null)
{
    DPFP.Verification.Verification verificator = new DPFP.Verification.Verification();
    foreach (KeyValuePair<decimal, MemoryStream> tt in profileDic)
    {
        string key = tt.Key.ToString(); //we use this a lot, so let's only convert it to string once, then reuse that
        UIReportCurrentKey(key);
        temp = new DPFP.Template(tt.Value);
        DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
        verificator.Verify(featuresForVerification, temp, ref result);
        UIReportMatch(result, key);
        //if a match were found, would we want to keep comparing, or exit on first match?  If the latter, add code to record which record matched, then use break to exit the loop
        UIIncremementProgressBar();
    }
} else {
    throw new NoFeaturesToVerifyException("The verfication tool was not given any features to verify");
    //alternatively set progress bar to complete / whatever other UI actions you have /
    //whatever you want to happen if no features were selected for comparison
}

//...

#region UI Updaters
/*
    I don't know much about winforms updates; have a feeling these can be made more efficient too,
    but for the moment just shoving the code into its own functions to make the main method less
    cluttered with UI logic.
*/

// Adds the key of the item currently being processed to the UI textbox
private void UIReportCurrentKey(string key)
{
    this.Invoke(new Function(delegate()
    {
        textBox1.Text += "\n" + key;
    }));
}
private void UIReportMatch(DPFP.Verification.Verification.Result result, string key)
{
    if (result.Verified)
    {
        this.Invoke(new Function(delegate()
        {
                MessageBox.Show("FAR " + result.FARAchieved + "\n" + key);
        }));
    }
    /*
    else
    {
        this.Invoke(new Function(delegate()
        {
                MessageBox.Show("No Match");
        }));
    }
    */
}
private void UIIncremementProgressBar()
{
    this.Invoke(new Function(delegate()
    {
        progressBar1.Value++;
    }));
}

#endregion UI Updaters

#region Custom Exceptions
public class NoFeaturesToVerifyException: ApplicationException
{ //Choose base class appropriately
    public NoFeaturesToVerifyException(): base() {}
    public NoFeaturesToVerifyException(string message): base(message) {}
    //...
}
#endregion Custom Exceptions
</code>```

Title: Change foreach loop by for loop

Body:
I am creating a Fingerprint Verification System in which I have to match fingerprints using records in database.  I have used foreach loop to to so but it is taking almost 40 seconds for only 350 records.  I want to speed it up.  I want my foreach loop to convert into for loop but I am facing some difficulties in initializing the for loop.  Here is my code.

foreach (KeyValuePair<decimal, MemoryStream> tt in profileDic)
{
    this.Invoke(new Function(delegate()
    {
        textBox1.Text += "\n" + tt.Key.ToString();
    }));
    temp = new DPFP.Template(tt.Value);

    Verificator = new DPFP.Verification.Verification();
    featuresForVerification = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification);
    if (featuresForVerification != null)
    {
        DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
        Verificator.Verify(featuresForVerification, temp, ref result);

        #region UI Envoke
        this.Invoke(new Function(delegate()
        {
            if (result.Verified)
            {
                MessageBox.Show("FAR " + result.FARAchieved + "\n" + tt.Key.ToString());
            }
            else
            {
                //MessageBox.Show("No Match");
            }
        }));
        #endregion
    }
    this.Invoke(new Function(delegate()
    {
        progressBar1.Value += 1;
    }));
    Thread.CurrentThread.Priority = ThreadPriority.Highest;
}

I am confused at the first line foreach (KeyValuePair<decimal, MemoryStream> tt in profileDic).  Can someone tell me how I can iterate through every item in Dictionary object profileDic using a for loop.  I am not sure how to get KeyValuePair<decimal, MemoryStream> tt in profileDic when using a for loop.

Body:
To answer your stated question: to replace a foreach loop with a for loop, replace:

foreach (KeyValuePair<decimal, MemoryStream> tt in profileDic)
{
    //...
}

with

for (var i=0; i < profileDic.Count, i++)
{
    KeyValuePair<decimal, MemoryStream> tt = profileDic.ElementAt(i);
    //...
}

To use this you'd also need to include a using System.Linq; statement in your code.
That said, this assumes that the order of elements in your dictionary will not change; which is not guaranteed (unless you're using a SortedDictionary or OrderedDictionary).
A better approach is therefore:

[decimal[]]keys = profileDic.Keys;
for (var i=0; i < keys.Count, i++)
{
    KeyValuePair<decimal, MemoryStream> tt = profileDic[keys[i]];
    //...
}

But this adds more overhead / likely pushes the for loop's time over that of the foreach loop / is a micro-optimisation that won't solve your real performance issue.

Per comments, the loop is likely not your problem, but what's occurring within that loop (if in this part of the code at all).

We don't know enough about your code to comment on it, so it's likely best that you investigate yourself; e.g. using the performance analysis techniques described here: https://msdn.microsoft.com/en-us/library/ms182372.aspx

I've refactored your code to make it more readable (i.e. by pulling the UI updates into their own methods, so they don't clutter the main thread).

I also moved those operations which look like they wouldn't need to be updated each iteration outside of your loop... but without knowing your code this is pure guesswork / so no guarantees.

Finally I removed your code to alter the priority of the current thread at the end of each iteration.  Playing with thread priorities is not a good way to fix slow code; there are only certain cases where it's appropriate, and seeing it's context here I'm over 99% certain that this is not one of those cases.

//...
featuresForVerification = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification); //since this appears unaffected by our profileDic values, let's initialise once
if (featuresForVerification != null)
{
    DPFP.Verification.Verification verificator = new DPFP.Verification.Verification();
    foreach (KeyValuePair<decimal, MemoryStream> tt in profileDic)
    {
        string key = tt.Key.ToString(); //we use this a lot, so let's only convert it to string once, then reuse that
        UIReportCurrentKey(key);
        temp = new DPFP.Template(tt.Value);
        DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
        verificator.Verify(featuresForVerification, temp, ref result);
        UIReportMatch(result, key);
        //if a match were found, would we want to keep comparing, or exit on first match?  If the latter, add code to record which record matched, then use break to exit the loop
        UIIncremementProgressBar();
    }
} else {
    throw new NoFeaturesToVerifyException("The verfication tool was not given any features to verify");
    //alternatively set progress bar to complete / whatever other UI actions you have /
    //whatever you want to happen if no features were selected for comparison
}

//...

#region UI Updaters
/*
    I don't know much about winforms updates; have a feeling these can be made more efficient too,
    but for the moment just shoving the code into its own functions to make the main method less
    cluttered with UI logic.
*/

// Adds the key of the item currently being processed to the UI textbox
private void UIReportCurrentKey(string key)
{
    this.Invoke(new Function(delegate()
    {
        textBox1.Text += "\n" + key;
    }));
}
private void UIReportMatch(DPFP.Verification.Verification.Result result, string key)
{
    if (result.Verified)
    {
        this.Invoke(new Function(delegate()
        {
                MessageBox.Show("FAR " + result.FARAchieved + "\n" + key);
        }));
    }
    /*
    else
    {
        this.Invoke(new Function(delegate()
        {
                MessageBox.Show("No Match");
        }));
    }
    */
}
private void UIIncremementProgressBar()
{
    this.Invoke(new Function(delegate()
    {
        progressBar1.Value++;
    }));
}

#endregion UI Updaters

#region Custom Exceptions
public class NoFeaturesToVerifyException: ApplicationException
{ //Choose base class appropriately
    public NoFeaturesToVerifyException(): base() {}
    public NoFeaturesToVerifyException(string message): base(message) {}
    //...
}
#endregion Custom Exceptions


问:
JS: Group array by values in nested array
I have an array:

```<code>[
  {
    theme: "low battery",
    Number: "S-10",
    components: [ "hardware", "battery" ]
  },
  {
    theme: "bad sync",
    Number: "S-11",
    components: [ "software" ]
  },
  {
    theme: "misc troubles",
    Number: "S-12",
    components: [ "hardware", "software" ]
  }
]
</code>```

So i want to group this array by "components" values. In other words, i want to know, how many times does component occures in array. For example:

```<code>[
  {
    component: "hardware",
    amount: 2
  },
  {
    component: "software",
    amount: 2
  },
  {
    component: "battery",
    amount: 1
  }
]
</code>```

答:
 var arr = [
      {
        theme: "low battery",
        Number: "S-10",
        components: [ "hardware", "battery" ]
      },
      {
        theme: "bad sync",
        Number: "S-11",
        components: [ "software" ]
      },
      {
        theme: "misc troubles",
        Number: "S-12",
        components: [ "hardware", "software" ]
      }
    ];
    var components = {};
    arr.forEach(function(val){
        val.components.forEach(function(c){
           components[c] = !(c in components) ? 1 : Number(components[c])+1;
        });
    });

    var componentCount = [];
    for(key in components){
     componentCount.push({'component' : key, 'amount' : components[key]});
    }

   console.log(componentCount);```

Body:
I have an array:

[
  {
    theme: "low battery",
    Number: "S-10",
    components: [ "hardware", "battery" ]
  },
  {
    theme: "bad sync",
    Number: "S-11",
    components: [ "software" ]
  },
  {
    theme: "misc troubles",
    Number: "S-12",
    components: [ "hardware", "software" ]
  }
]

So i want to group this array by "components" values. In other words, i want to know, how many times does component occures in array. For example:

[
  {
    component: "hardware",
    amount: 2
  },
  {
    component: "software",
    amount: 2
  },
  {
    component: "battery",
    amount: 1
  }
]


问:
in loopback nodejs, nobody can create shop details through shop model
nobody is allowed to create directly through shop model
only admin can create shop through user/id/shop

by using ACL, I deny creating details in shop model. but I don't know how to create shop through admin only

```<code>"acls": [
    {
      "principalType": "USER",
      "principalId": "admin",
      "permission": "ALLOW",
      "property": "create"
    },
    {
    "principalType": "ROLE",
    "principalId": "$everyone",
    "permission": "DENY",
    "property": "create"
    }
]
</code>```

thanks in advance

this is my script.js,

```<code>module.exports = function(app) {
  var User = app.models.User;
  var Role = app.models.Role;
  var RoleMapping = app.models.RoleMapping;
  debugger;
  User.create([
    {username: 'admin', email: 'admin@gmail.com', password: 'admin'},
  ], function(err, users) {

//create the admin role
Role.create({
  name: 'admin'
}, function(err, role) {

  role.principals.create({
    principalType: RoleMapping.USER,
    principalId: users[0].id
  }, function(err, principal) {
    //cb(err);
  });
});

});
}
</code>```

but still i got authorization error

答:
If you want to be able to create a Shop as an admin through User model (POST /users/{id}/shops), you also need to set correct ACL on User. I'm assuming you've set relations between these two models correctly and you've created an admin role.

user.json (relevant part)

```<code>"acls": [
  {
    "accessType": "WRITE",
    "principalType": "ROLE",
    "principalId": "admin",
    "permission": "ALLOW",
    "property": [ "__create__shops" ]
  }
]
</code>```

You can find more related information in official LoopBack docs.

Body:
nobody is allowed to create directly through shop model
only admin can create shop through user/id/shop

by using ACL, I deny creating details in shop model. but I don't know how to create shop through admin only

"acls": [
    {
      "principalType": "USER",
      "principalId": "admin",
      "permission": "ALLOW",
      "property": "create"
    },
    {
    "principalType": "ROLE",
    "principalId": "$everyone",
    "permission": "DENY",
    "property": "create"
    }
]

thanks in advance

this is my script.js,

module.exports = function(app) {
  var User = app.models.User;
  var Role = app.models.Role;
  var RoleMapping = app.models.RoleMapping;
  debugger;
  User.create([
    {username: 'admin', email: 'admin@gmail.com', password: 'admin'},
  ], function(err, users) {

//create the admin role
Role.create({
  name: 'admin'
}, function(err, role) {

  role.principals.create({
    principalType: RoleMapping.USER,
    principalId: users[0].id
  }, function(err, principal) {
    //cb(err);
  });
});

});
}

but still i got authorization error

Body:
If you want to be able to create a Shop as an admin through User model (POST /users/{id}/shops), you also need to set correct ACL on User. I'm assuming you've set relations between these two models correctly and you've created an admin role.

user.json (relevant part)

"acls": [
  {
    "accessType": "WRITE",
    "principalType": "ROLE",
    "principalId": "admin",
    "permission": "ALLOW",
    "property": [ "__create__shops" ]
  }
]

You can find more related information in official LoopBack docs.


答:
For your specific use case (the "break" is optional):</p>

```<code>ans = False
for string in lst:
    if string in line:
        ans = True
        break
</code>```

Title: python: alternative way of built in function "any"

Body:
I'm working with python 2.4 and I need to use the function any which is not available in my python version.

Is there a function or expression that I can use to replace it?

I need to find if at least one element of a string list is in a text Line.

Body:
For your specific use case (the "break" is optional):

ans = False
for string in lst:
    if string in line:
        ans = True
        break


问:
SQL Server CTE -Find top parentID forEach childID?
I have a table which contains hierarchy data - something like:

```<code>childID  |  parentID
____________________
  1      |     5
  5      |     9
  9      |     20
  2      |     4
  3      |     7
  7      |     8
  8      |     8
 20      |     20
  4      |     4
  8      |     8
</code>```

desired output:

I've created a recursive CTE which finds me the top fatherID.

Something like:

```<code>;WITH cte AS (
                 SELECT a.childID
                       ,a.parentID
                       ,1 AS lvl
                 FROM   [Agent_Agents] a
                 WHERE   a.childID = 214 //<==== value to begin with !! - thats part the problem
                 UNION ALL
                 SELECT tmp.childID
                       ,tmp.parentID
                       ,cte.lvl+1
                 FROM   [Agent_Agents] tmp
                         INNER JOIN cte  ON  tmp.childID = cte.parentID
                 WHERE   cte.childID<>cte.parentID
             )
SELECT *
FROM   cte
WHERE   lvl = (
            SELECT MAX(lvl)
            FROM   cte
        )
</code>```

The problem:

I executed the CTE with explicit childID value to begin with (214) !
So it gives me the value for 214 only.
the CTE do the recursive part and find topParent for childID.

but
I want ForEach row in the Table - to execute the CTE with the childID value !

I have tried to do it with CROSS APPLY:

Something like:

```<code>select * from myTable Cross Apply (
                                     ;WITH cte AS (....)
                                  )
</code>```

but IMHO (from my testing !!)  - its impossible.

The other idea of putting the recursive CTE in a UDF has a performance penalty (udf's problem as we know).

How can I create this query so that it'll actually work? (  or some near solution )?

here is what I've tried

https://data.stackexchange.com/stackoverflow/query/edit/69458

答:
Consider this sample data and respective SQL to access child records along with their top parent.

Sample DATA

SQL code:

```<code>;WITH c AS (
   SELECT Id, Name, ParentId as CategoryId,
          Id as MainCategoryId, Name AS MainCategory
     FROM   pmsItemCategory
     WHERE  ParentId is null

     UNION ALL

     SELECT T.Id, T.Name, T.ParentId,  MainCategoryId, MainCategory
     FROM   pmsItemCategory AS T
            INNER JOIN c  ON T.ParentId = c.Id
     WHERE  T.ParentId is not null
    )

SELECT Id, Name, CategoryId, MainCategoryId, MainCategory
FROM   c
order by Id
</code>```

Body:
I have a table which contains hierarchy data - something like:

childID  |  parentID
____________________
  1      |     5
  5      |     9
  9      |     20
  2      |     4
  3      |     7
  7      |     8
  8      |     8
 20      |     20
  4      |     4
  8      |     8

desired output:

I've created a recursive CTE which finds me the top fatherID.

Something like:

;WITH cte AS (
                 SELECT a.childID
                       ,a.parentID
                       ,1 AS lvl
                 FROM   [Agent_Agents] a
                 WHERE   a.childID = 214 //<==== value to begin with !! - thats part the problem
                 UNION ALL
                 SELECT tmp.childID
                       ,tmp.parentID
                       ,cte.lvl+1
                 FROM   [Agent_Agents] tmp
                         INNER JOIN cte  ON  tmp.childID = cte.parentID
                 WHERE   cte.childID<>cte.parentID
             )
SELECT *
FROM   cte
WHERE   lvl = (
            SELECT MAX(lvl)
            FROM   cte
        )

The problem:

I executed the CTE with explicit childID value to begin with (214) !
So it gives me the value for 214 only.
the CTE do the recursive part and find topParent for childID.

but
I want ForEach row in the Table - to execute the CTE with the childID value !

I have tried to do it with CROSS APPLY:

Something like:

select * from myTable Cross Apply (
                                     ;WITH cte AS (....)
                                  )

but IMHO (from my testing !!)  - its impossible.

The other idea of putting the recursive CTE in a UDF has a performance penalty (udf's problem as we know).

How can I create this query so that it'll actually work? (  or some near solution )?

here is what I've tried

https://data.stackexchange.com/stackoverflow/query/edit/69458

Body:
Consider this sample data and respective SQL to access child records along with their top parent.

Sample DATA

SQL code:

;WITH c AS (
   SELECT Id, Name, ParentId as CategoryId,
          Id as MainCategoryId, Name AS MainCategory
     FROM   pmsItemCategory
     WHERE  ParentId is null

     UNION ALL

     SELECT T.Id, T.Name, T.ParentId,  MainCategoryId, MainCategory
     FROM   pmsItemCategory AS T
            INNER JOIN c  ON T.ParentId = c.Id
     WHERE  T.ParentId is not null
    )

SELECT Id, Name, CategoryId, MainCategoryId, MainCategory
FROM   c
order by Id


问:
skew data causing long running query in hive
I am running a hive query like tableA left join tableB on tableA.col1=tableB.col1 and tableA.col2=tableB.col2. tableA is having 1.8 billion data and tableB is having 31 million records. Now the last reducers in my join is not getting completed and it is running for long.

It may be because of skew data. I did tried MAPJOIN and the query failed because of huge data volume for tableA. Is there any other options these can be handled in a better way?

The task which I can see running for long is as below

```<code>reduce > copy task(attempt_1498868574233_185232_m_001336_0 succeeded at 8.94 MB/s) Aggregated copy rate(1121 of 2532 at 108.94 MB/s)
</code>```

What exactly it is trying to do in that step?

答:
set hive.optimize.skewjoin to true

hive.optimize.skewjoin

  Default Value: false

  Added In: Hive 0.6.0

  Whether to enable skew join optimization.

You might also want to tune hive.skewjoin.key, hive.skewjoin.mapjoin.map.tasks and hive.skewjoin.mapjoin.min.split.

hive.skewjoin.key

  Default Value: 100000

  Added In: Hive 0.6.0

  Determine if we get a skew key in join. If we see more than the
  specified number of rows with the same key in join operator, we think
  the key as a skew join key.

hive.skewjoin.mapjoin.map.tasks

  Default Value: 10000

  Added In: Hive 0.6.0

  Determine the number of map task used in the follow up map
  join job for a skew join. It should be used together with
  hive.skewjoin.mapjoin.min.split to perform a fine grained control.

hive.skewjoin.mapjoin.min.split

  Default Value: 33554432

  Added In: Hive 0.6.0

  Determine the number of map task at most used in the follow
  up map join job for a skew join by specifying the minimum split size.
  It should be used together with hive.skewjoin.mapjoin.map.tasks to
  perform a fine grained control.

https://cwiki.apache.org/confluence/display/Hive/Configuration+Properties

Body:
I am running a hive query like tableA left join tableB on tableA.col1=tableB.col1 and tableA.col2=tableB.col2. tableA is having 1.8 billion data and tableB is having 31 million records. Now the last reducers in my join is not getting completed and it is running for long.

It may be because of skew data. I did tried MAPJOIN and the query failed because of huge data volume for tableA. Is there any other options these can be handled in a better way?

The task which I can see running for long is as below

reduce > copy task(attempt_1498868574233_185232_m_001336_0 succeeded at 8.94 MB/s) Aggregated copy rate(1121 of 2532 at 108.94 MB/s)

What exactly it is trying to do in that step?


问:
URL Redirect, HTML, PHP
I want to link links on my website via go.php?urlhere, I have been told and I have tried using go.php?url=urlhere however the URL's to which I redirect, redirect to another URL with-in it for example go.php?http://.com/click?p=0&a=0&url=http://.com, many of the redirect I have tried to use simply copy the URL in the go.php file and use a meta refresh or a window.location reload; however they redirect to the second URL and not the first one. Sometimes when I do actually get it to redirect the first part of the redirected URL gets all the dots changed to "_" which stops it redirecting.

I want to have something like this website using on its "Buy It Now" buttons

http://www.searchchief.co.uk/Search/Sony-PSP-Go

答:
So I think this is what you are asking: How do I redirect to a page using a url as a query string parameter?

eg.

```<code>http://www.myurl.com/go.php?url=http%3A%2F%2Fwww.myotherurl.com
</code>```

You must do two things to achieve this on the url:

have a query string parameter. eg.
go.php?url=mysite.com or
go.php?redirect=mysite.com not
just go.php?mysite.com.

you must URL ENCODE this query
string parameter value. eg. go.php?url=http%3A%2F%2Fwww.myotherurl.com
NOT go.php?url=http://www.myotherurl.com. In php you can use the urlencode() function or http://meyerweb.com/eric/tools/dencoder/ can do it for you if you have a small number of urls to convert.

On the PHP side of things you will use the following

```<code><?php
     header('Location: '.urldecode($_GET['url']));
     exit();
?>
</code>```

You can do other basic checks on the php side of things eg. check for a valid url format etc

OwnerDisplayName: Jack

Title: URL Redirect, HTML, PHP

Body:
So I think this is what you are asking: How do I redirect to a page using a url as a query string parameter?

eg.

http://www.myurl.com/go.php?url=http%3A%2F%2Fwww.myotherurl.com

You must do two things to achieve this on the url:

have a query string parameter. eg.
go.php?url=mysite.com or
go.php?redirect=mysite.com not
just go.php?mysite.com.

you must URL ENCODE this query
string parameter value. eg. go.php?url=http%3A%2F%2Fwww.myotherurl.com
NOT go.php?url=http://www.myotherurl.com. In php you can use the urlencode() function or http://meyerweb.com/eric/tools/dencoder/ can do it for you if you have a small number of urls to convert.

On the PHP side of things you will use the following

<?php
     header('Location: '.urldecode($_GET['url']));
     exit();
?>

You can do other basic checks on the php side of things eg. check for a valid url format etc

ContentLicense: CC BY-SA 2.5


问:
unable to get data from html in angular js
in this code of HTML, we get input text value and send to the Angular controller
so they get to work as defined in code.

```<code>    <div class="row" ng-controller="RegionController">

    <div class="col-lg-12" >
    <div class="hpanel">
    <div class="panel-heading">
      <!--  <div panel-tools></div>  -->
        <h2>Region Master Entry</h2>
    </div>
    <div class="panel-body">

        <!--change form name,and submit controller name-->

        <form role="form">

            <div class="form-group">
                <label class="col-sm-2 control-label">Region Name</label>

                <div class="col-sm-10">
                    <input type="text" placeholder="please enter Region name" class="form-control m-b" required name="Region Name" ng-model="formRegionData.region_name" >

                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-2 control-label">Region Code</label>

                <div class="col-sm-10">
                    <input type="text" placeholder="please enter Region code" class="form-control m-b" required name="Region Code" ng-model="formRegionData.region_code">

                </div>
            </div>

            <div class="form-group">
            <div class="col-sm-3">
                <label>Active</label>
            </div>

             <div class="checkbox checkbox-success col-sm-9">
                 <input id="checkbox3" type="checkbox" checked="" ng-model="formRegionData.status">
                 <label for="checkbox3">

                 </label>
             </div>
         </div>

            <div class="form-group">
                <div class="col-sm-4"></div>

                <div class="col-sm-8">
                    <button  class="btn btn-sm btn-primary btn-xl text-right"  type="submit" ng-click="createRegion()"><strong> Save Region </strong></button>
                </div>

            </div>

 {{formRegionData | json}}
        </form>
    </div>
   </div>
   </div>
 </div>
</code>```

"{{formRegionData | json}}" this will return in HTML input text result of but not send data to the controller

in Controller the code is written as

```<code>.controller('RegionController', function( $scope , regionService) {
$scope.createRegion = function() {
    debugger;
    vm.processing = true;
    vm.message = '';
    console.log(formRegionData);
    regionService.SaveRegion( formRegionData )
        .then(function(data) {
            debugger;
            //console.log(data);
            //.success(function(data) {
            vm.processing = false;
            vm.storyData = {};
            vm.message = data.message;
        });
  }
  })
</code>```

and my service to work according to Controller

```<code>   .factory('regionService',function($http ){
          var regionFactory = {};
    regionFactory.SaveRegion = function(formRegionData) {
    debugger;
            return $http.post('/api/region/', formRegionData);

    }
    return regionFactory;
});
</code>```

答:
You have missed of $scope in form region data
Here is the link Jsfiddle

JS

```<code>angular.module('myApp', ['ngStorage'])
  .controller('RegionController', function($scope, regionService) {
    var vm = this;
    $scope.createRegion = function() {
      debugger;
      vm.processing = true;
      vm.message = '';
      regionService.SaveRegion($scope.formRegionData)
        .then(function(data) {
          debugger;
          //console.log(data);
          //.success(function(data) {
          vm.processing = false;
          vm.storyData = {};
          vm.message = data.message;
        });
    }
  }).factory('regionService', function($http) {
    var regionFactory = {};
    regionFactory.SaveRegion = function(formRegionData) {
      debugger;
      return $http.post('/api/region/', formRegionData);

    }
    return regionFactory;
  });
</code>```

Body:
in this code of HTML, we get input text value and send to the Angular controller
so they get to work as defined in code.

Region Master Entry

        <form role="form">

                Region Name

                    <input type="text" placeholder="please enter Region name" class="form-control m-b" required name="Region Name" ng-model="formRegionData.region_name" >

                Region Code

                    <input type="text" placeholder="please enter Region code" class="form-control m-b" required name="Region Code" ng-model="formRegionData.region_code">

                Active

                 <input id="checkbox3" type="checkbox" checked="" ng-model="formRegionData.status">

                    <button  class="btn btn-sm btn-primary btn-xl text-right"  type="submit" ng-click="createRegion()"> Save Region </button>

 {{formRegionData | json}}
        </form>

"{{formRegionData | json}}" this will return in HTML input text result of but not send data to the controller

in Controller the code is written as

.controller('RegionController', function( $scope , regionService) {
$scope.createRegion = function() {
    debugger;
    vm.processing = true;
    vm.message = '';
    console.log(formRegionData);
    regionService.SaveRegion( formRegionData )
        .then(function(data) {
            debugger;
            //console.log(data);
            //.success(function(data) {
            vm.processing = false;
            vm.storyData = {};
            vm.message = data.message;
        });
  }
  })

and my service to work according to Controller

   .factory('regionService',function($http ){
          var regionFactory = {};
    regionFactory.SaveRegion = function(formRegionData) {
    debugger;
            return $http.post('/api/region/', formRegionData);

    }
    return regionFactory;
});

Body:
You have missed of $scope in form region data
Here is the link Jsfiddle

JS

angular.module('myApp', ['ngStorage'])
  .controller('RegionController', function($scope, regionService) {
    var vm = this;
    $scope.createRegion = function() {
      debugger;
      vm.processing = true;
      vm.message = '';
      regionService.SaveRegion($scope.formRegionData)
        .then(function(data) {
          debugger;
          //console.log(data);
          //.success(function(data) {
          vm.processing = false;
          vm.storyData = {};
          vm.message = data.message;
        });
    }
  }).factory('regionService', function($http) {
    var regionFactory = {};
    regionFactory.SaveRegion = function(formRegionData) {
      debugger;
      return $http.post('/api/region/', formRegionData);

    }
    return regionFactory;
  });


问:
pyteomics: calculate mass from a file containing the sequence of several proteins
I want to calculate the mass for every protein of my file.

My code so far:

```<code>from pyteomics import mass
 with open('file.txt') as f:
        for line in f:
             mass.calculate_mass(line)
</code>```

When I replace the mass.calculate_mass with print(line) all the lines are correctly printed. But with mass.calculate_mass(line) come several error messages:

```<code>Traceback (most recent call last):
File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/parser.py", line 275, in parse
    n, body, c = re.match(_modX_sequence, sequence).groups() AttributeError: 'NoneType' object has no attribute 'groups'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 304, in __init__
    self._from_sequence(args[0], aa_comp)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 200, in _from_sequence
    show_unmodified_termini=True)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/parser.py", line 277, in parse
    raise PyteomicsError('Not a valid modX sequence: ' + sequence) pyteomics.auxiliary.PyteomicsError: Pyteomics error, message: "Not a valid modX sequence: 'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'\n"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 307, in __init__
    self._from_formula(args[0], mass_data)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 205, in _from_formula
    raise PyteomicsError('Invalid formula: ' + formula) pyteomics.auxiliary.PyteomicsError: Pyteomics error, message: "Invalid formula: 'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'\n"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/home/michaela/calculatemass.py", line 5, in <module>
    mass.calculate_mass(line)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 499, in calculate_mass
    else Composition(*args, **kwargs))   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 312, in __init__
    'formula'.format(args[0])) pyteomics.auxiliary.PyteomicsError: Pyteomics error, message: 'Could not create a Composition object from string: "\'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY\'\n": not a valid sequence or formula'
</code>```

my file looks like this:

```<code>'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'
</code>```

I also tried it with

sequence='MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'

There are no empty lines in my file.
If I try the same in the shell, it works:

```<code>mass.calculate_mass('MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY')
</code>```

49589.2790365072

I also tried mass.calculate_mass(str(line)) but that did not help.

Do you know what I am doing wrong?

答:
It worked after changing the file to:

MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY
  (without sequence = or quotes)

and by changing the code to:

```<code>from pyteomics import mass
</code>```

with open('file.txt') as f:
        for line in f:
             print(mass.calculate_mass(line))

Body:
I want to calculate the mass for every protein of my file.

My code so far:

from pyteomics import mass
 with open('file.txt') as f:
        for line in f:
             mass.calculate_mass(line)

When I replace the mass.calculate_mass with print(line) all the lines are correctly printed. But with mass.calculate_mass(line) come several error messages:

Traceback (most recent call last):
File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/parser.py", line 275, in parse
    n, body, c = re.match(_modX_sequence, sequence).groups() AttributeError: 'NoneType' object has no attribute 'groups'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 304, in __init__
    self._from_sequence(args[0], aa_comp)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 200, in _from_sequence
    show_unmodified_termini=True)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/parser.py", line 277, in parse
    raise PyteomicsError('Not a valid modX sequence: ' + sequence) pyteomics.auxiliary.PyteomicsError: Pyteomics error, message: "Not a valid modX sequence: 'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'\n"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 307, in __init__
    self._from_formula(args[0], mass_data)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 205, in _from_formula
    raise PyteomicsError('Invalid formula: ' + formula) pyteomics.auxiliary.PyteomicsError: Pyteomics error, message: "Invalid formula: 'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'\n"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/home/michaela/calculatemass.py", line 5, in <module>
    mass.calculate_mass(line)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 499, in calculate_mass
    else Composition(*args, **kwargs))   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 312, in __init__
    'formula'.format(args[0])) pyteomics.auxiliary.PyteomicsError: Pyteomics error, message: 'Could not create a Composition object from string: "\'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY\'\n": not a valid sequence or formula'

my file looks like this:

'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'

I also tried it with

sequence='MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'

There are no empty lines in my file.
If I try the same in the shell, it works:

mass.calculate_mass('MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY')

49589.2790365072

I also tried mass.calculate_mass(str(line)) but that did not help.

Do you know what I am doing wrong?

Body:
It worked after changing the file to:

MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY
  (without sequence = or quotes)

and by changing the code to:

from pyteomics import mass

with open('file.txt') as f:
        for line in f:
             print(mass.calculate_mass(line))


问:
(Scrapy pipeline): Unable to create database table as part of Scrapy pipeline script
I am trying to create a database table as part of a Scrapy pipeline script.

My pipelines.py file is as follows:

```<code>import pymysql.cursors

class mySQLTest(object):

    def __init__(self):
        self.conn = pymysql.connect(host='localhost',
                             user='root',
                             password='',
                             db='testDB',
                             charset='utf8mb4',
                          cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.conn.cursor()

    def process_target(self):
        sql = "CREATE TABLE items2 (id INT(11) NOT NULL);"

        self.cursor.execute(sql)
        self.conn.commit()
</code>```

When I run the script in the PyCharm Python Console, I can see the table is created.

However, when I run it as part of Scrapy, no table is created.

Does Scrapy pipeline not enable creation of tables?  What is the best way to trace what errors the script may be running into?

Tech Specs:

Mac OS X El Capitan 10.11

PyCharm Community Edition 2017.1.4

Python 3.6.1

Maria DB 10.2.6

答:
=> I suggest you to change the name of method process_target(self) to process_item(self, item).

=> Is the item pipeline activated inside settings.py file ?

=> do you yield any object to the pipeline ?

Body:
I am trying to create a database table as part of a Scrapy pipeline script.

My pipelines.py file is as follows:

import pymysql.cursors

class mySQLTest(object):

    def __init__(self):
        self.conn = pymysql.connect(host='localhost',
                             user='root',
                             password='',
                             db='testDB',
                             charset='utf8mb4',
                          cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.conn.cursor()

    def process_target(self):
        sql = "CREATE TABLE items2 (id INT(11) NOT NULL);"

        self.cursor.execute(sql)
        self.conn.commit()

When I run the script in the PyCharm Python Console, I can see the table is created.

However, when I run it as part of Scrapy, no table is created.

Does Scrapy pipeline not enable creation of tables?  What is the best way to trace what errors the script may be running into?

Tech Specs:

Mac OS X El Capitan 10.11

PyCharm Community Edition 2017.1.4

Python 3.6.1

Maria DB 10.2.6


问:
Authorize.Net pingback to my site
I am using Authorize.Net ARB for paid membership. I am not sure, how to know when recurring payment has been cancelled (or something else) and I should disable the account.

The only one thing I have found is a Silent Post functionality, but not all transactions post a respose with Silent Post.

Is there any other way my script can be notified about all transactions?

答:
Using Webhooks is the preferred method over Silent post.
Specifically, in this case, the following events:

net.authorize.customer.subscription.terminated

net.authorize.customer.subscription.cancelled

net.authorize.customer.subscription.expiring

Title: Authorize.Net pingback to my site


问:
Read records dbf foxpro 2.6 have been deleted on excel
How to read records that have been deleted. Can the record be read on excel or another software? If so, how? </p>

答:
If they have been deleted but the table has not been PACKed, then issuing the RECALL ALL command will undelete them.

You can also issue SET DELETED OFF to make records marked for deletion available to SELECT-SQL commands and so forth.

If you're connecting to the data with the OLEDB driver, include 'DELETED=FALSE' in the connection string.

If the table has been PACKed then they are gone, restore a backup.


问:
span height width unable to change
trying to make one horizontal box.. inside that update limits.
if u see the below sample code, u can understand how i set limits.
those limit classes height, i am unable to decrease.
could please tel me what is reason..
i want to make it using div and span only</p>

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" dir="ltr">
    <head>
    <style>
        .limitBlock
        {
            border-left: 1px solid black;
        }
        .limitRBlack
        {
            border-right: 1px solid black;
        }
        .horbox
        {
           background-color:#FFFFFF;
           height:4px;
           width:400px;
           margin-left:5px;
           border: 1px solid #AAAAAA;
        }
    </style>
    </head>
    <body>
        <div class="horbox">
            <div style="margin-top:-3px">
                <span style="margin-top: -4px;height: 9px;">
                    <span id="limit1" class="limitBlock" style="margin-left:-1px;"></span>
                    <span id="limit2" class="limitBlock" style="margin-left:100px;"></span>
                    <span id="limit3" class="limitBlock" style="margin-left:100px;"></span>
                    <span id="limit4" class="limitBlock" style="margin-left:100px;"></span>
                </span>
                <span id="limit5"class="limitRBlack" style="margin-left:96px;"></span>
            </div>
        </div>
    </body>
</html>
</code>```

答: spans are not block elements so you can't set their height.  That's what divs are for.

Title: span height width unable to change

Body:
trying to make one horizontal box.. inside that update limits.
if u see the below sample code, u can understand how i set limits.
those limit classes height, i am unable to decrease.
could please tel me what is reason..
i want to make it using div and span only

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">


问:
cakePHP3: Change Entity membername before render
Is there a elegant way to change an entity membername before it is passed to a view? In my example I have an entity product. My product has a member application_id. I output it to json. Now my Frontend Developer would like to recieve this value as applicationId (no underscore).

As I'm returning a rather complex structure with objects, containing other objects and so on, I won't like to iterate over the whole resultset and change membernames in a loop. So I looked into the entity and hoped to find something like a $_map where I could map membernames to custom names, but I didn't find anything.

Is there a way to do that without using a loop in beforeRender?

答:
The manual says

When converting an entity to an JSON the virtual & hidden field lists
  are applied. Entities are recursively converted to JSON as well. This
  means that if you eager loaded entities and their associations CakePHP
  will correctly handle converting the associated data into the correct
  format.

So you can create a virtual property in your Entoty this way

```<code>protected $_virtual = ['ApplicationId'];

protected function _getapplicationId()
{
    return $this->application_id;
}
</code>```

seems a little bit against cake naming conventions but it works

Body:
The manual says

When converting an entity to an JSON the virtual & hidden field lists
  are applied. Entities are recursively converted to JSON as well. This
  means that if you eager loaded entities and their associations CakePHP
  will correctly handle converting the associated data into the correct
  format.

So you can create a virtual property in your Entoty this way

protected $_virtual = ['ApplicationId'];

protected function _getapplicationId()
{
    return $this->application_id;
}

seems a little bit against cake naming conventions but it works


问:
Azure Blob Store SAS token missing Service Resource field
I created a Shared Access Signature(SAS) token on my Azure storage account using the web interface. The token looks like

?sv=xxxx-xx-xx&ss=b&srt=sco&sp=rl&se=xxxx-xx-xxTxx:xx:xxZ&st=xxxx-xx-xxTxx:xx:xxZ&spr=https&sig=xxxxxxxxxxxxxxxxxxxxxx

The SAS token here is missing the sr field for Service Resource. I have to manually prepend the sr=b to the query string to get things to work. I must be doing something wrong, because this seems extremely finicky.

```<code>from azure.storage.blob import BlockBlobService
sas_token = "?sv=xxxx-xx-xx&ss=b&srt=sco&sp=rl&se=xxxx-xx-xxTxx:xx:xxZ&st=xxxx-xx-xxTxx:xx:xxZ&spr=https&sig=xxxxxxxxxxxxxxxxxxxxxx"
sas_token = "?sr=b&" + sas_token[1:]

serv = BlockBlobService(account_name='myaccount', sas_token=sas_token)

for cont in serv.list_containers():
    print cont.name
</code>```

Without the sas_token = "?sr=b&" + sas_token[1:] I get the error:

sr is mandatory. Cannot be empty

And if the sr=b field is not first in the query, I get an authentication error like

Access without signed identifier cannot have time window more than 1 hour

答:
Access without signed identifier cannot have time window more than 1 hour

Based on this error message, you may need to set expiry time less than 1 hour from now. See Windows Azure Shared Access Signature always gives: Forbidden 403.

I took your code with Python v2.7.12 and @azure-storage-python v0.34.3 (the latest version). And it worked well on my site. So, I'd recommend you upgrade to latest version and try it again.

UPDATE:

I traced the code of Azure Storage SDK for Python and here's what I found. The SDK is a REST API warpper which assumes that the SAS token looks like this:

```<code>sv=2015-04-05&ss=bfqt&srt=sco&sp=rl&se=2015-09-20T08:49Z&sip=168.1.5.60-168.1.5.70&sig=a39%2BYozJhGp6miujGymjRpN8tsrQfLo9Z3i8IRyIpnQ%3d
</code>```

As you can see, the token doesn't include ?. And the SDK will append ? before the SAS token when it makes a GET request to the Azure Storage REST service.

This would cause that the key of the signed version was parsed as ?sv, then it raised the issue. So, to avoid this, we should remove the ? from the SAS token.

Body:
I created a Shared Access Signature(SAS) token on my Azure storage account using the web interface. The token looks like

?sv=xxxx-xx-xx&ss=b&srt=sco&sp=rl&se=xxxx-xx-xxTxx:xx:xxZ&st=xxxx-xx-xxTxx:xx:xxZ&spr=https&sig=xxxxxxxxxxxxxxxxxxxxxx

The SAS token here is missing the sr field for Service Resource. I have to manually prepend the sr=b to the query string to get things to work. I must be doing something wrong, because this seems extremely finicky.

from azure.storage.blob import BlockBlobService
sas_token = "?sv=xxxx-xx-xx&ss=b&srt=sco&sp=rl&se=xxxx-xx-xxTxx:xx:xxZ&st=xxxx-xx-xxTxx:xx:xxZ&spr=https&sig=xxxxxxxxxxxxxxxxxxxxxx"
sas_token = "?sr=b&" + sas_token[1:]

serv = BlockBlobService(account_name='myaccount', sas_token=sas_token)

for cont in serv.list_containers():
    print cont.name

Without the sas_token = "?sr=b&" + sas_token[1:] I get the error:

sr is mandatory. Cannot be empty

And if the sr=b field is not first in the query, I get an authentication error like

Access without signed identifier cannot have time window more than 1 hour

Body:
Access without signed identifier cannot have time window more than 1 hour

Based on this error message, you may need to set expiry time less than 1 hour from now. See Windows Azure Shared Access Signature always gives: Forbidden 403.

I took your code with Python v2.7.12 and @azure-storage-python v0.34.3 (the latest version). And it worked well on my site. So, I'd recommend you upgrade to latest version and try it again.

UPDATE:

I traced the code of Azure Storage SDK for Python and here's what I found. The SDK is a REST API warpper which assumes that the SAS token looks like this:

sv=2015-04-05&ss=bfqt&srt=sco&sp=rl&se=2015-09-20T08:49Z&sip=168.1.5.60-168.1.5.70&sig=a39%2BYozJhGp6miujGymjRpN8tsrQfLo9Z3i8IRyIpnQ%3d

As you can see, the token doesn't include ?. And the SDK will append ? before the SAS token when it makes a GET request to the Azure Storage REST service.

This would cause that the key of the signed version was parsed as ?sv, then it raised the issue. So, to avoid this, we should remove the ? from the SAS token.


问:
restoring scroll position in Flex Web Page
This is a fairly crucial but overlooked functionality I guess in a web page - on a standard (non flex) web page, navigate away from the page and return to it via the back or forward button and it restores the scroll position you were at on the page previously.  This is a crucial function and it would get very annoying if it wasn't there - having a page automatically go back to the very top each time when you were previously scrolled way down on a long text site.  I guess the browser itself must be managing this,as I was surprised to find that even deleting cookies, the cache and basically everything will not get rid of that saved scroll position.

So the problem is doing that on a flex web page - what is the correct way to do it.  I have been using SHaredObject.getLocal,  but was dumbfounded to discover that once a local shared object is created , it will NEVER be deleted, there is nothing a user can do in the browser to delete them (deleting cookies, etc has no effect.)  So I had like 100 different sharedobjects in a Macromedia subdirectory storing nothing but scroll positions.  Even with standard web pages you can delete browsing history, but with SharedObject they're there for good unless you actually just delve into that file subdirectory and delete them manually (which of course a user would never do.) So a subquestion would be, is it really true that there is no way to delete SharedObjects from the browser.  FLex even calls SharedObjects "Flash cookies" in their docs,  but with real cookies the user can delete them.

答:
My solution is to have just one SharedObject for all URL's generated, and this SHaredObject holds an object operating as a circular buffer.  This object has properties indexed by URL, with each property pointing to the session info for that URL (e.g. scroll position, etc.).  Haven't tested the following yet, but this is what I've got.  If there is already a built in way in Flex to do a circular buffer in a local SharedObject I haven't found it.</p>

```<code>function createSessionInfo(url:String,info:Object):void {

  var so_obj:SharedObject = null;
  try {
    so_obj = SharedObject.getLocal("Session_Info","/");
  } catch (e:*) {}
  if (!so_obj) return;

  if (so_obj.data.session == undefined)
    so_obj.data.session = new Object();

  var session:Object = so_obj.data.session;

  var date:Date = new Date();
  var max:int = 100;
  var first:String;
  var first_created:int=date.time;
  var cnt:int=0
  for (var p:String in session) {
    if (session[p].created < first_created) {
      first_created = session[p].created;
      first = p;
    }
    if (++cnt == max)
      delete session[first];
  }

  session[url] = new Object();
  session[url].created = date.time;
  session[url].info = info;

}
</code>```

Body:
My solution is to have just one SharedObject for all URL's generated, and this SHaredObject holds an object operating as a circular buffer.  This object has properties indexed by URL, with each property pointing to the session info for that URL (e.g. scroll position, etc.).  Haven't tested the following yet, but this is what I've got.  If there is already a built in way in Flex to do a circular buffer in a local SharedObject I haven't found it.

function createSessionInfo(url:String,info:Object):void {

  var so_obj:SharedObject = null;
  try {
    so_obj = SharedObject.getLocal("Session_Info","/");
  } catch (e:*) {}
  if (!so_obj) return;

  if (so_obj.data.session == undefined)
    so_obj.data.session = new Object();

  var session:Object = so_obj.data.session;

  var date:Date = new Date();
  var max:int = 100;
  var first:String;
  var first_created:int=date.time;
  var cnt:int=0
  for (var p:String in session) {
    if (session[p].created < first_created) {
      first_created = session[p].created;
      first = p;
    }
    if (++cnt == max)
      delete session[first];
  }

  session[url] = new Object();
  session[url].created = date.time;
  session[url].info = info;

}


问:
Azure DocumentDB (CosmosDB?) Timstamp Issue
I have an Azure DocumentDB collection that I'm writing time-stamped documents to via an Event Hub triggered function.  The timestamp that I'm writing to the document (my_timestamp) originates from the function that processes the event, and I've confirmed that it is accurate.

The problem that I'm encountering is that the _ts metadata timestamp that's created by DocumentDB itself is showing a unix timestamp value that's a number of seconds previous to the timestamp I'm creating, i.e., it's actually applying a timestamp that's earlier than the beginning of the function execution that creates the document...

It appears that this may be a quirk in the underlying DocumentDB mechanics.

Anyway, I wanted to see if anyone else is encountering this discrepancy.  Here are the timestamps as they appear in my document:

```<code>"my_timestamp": 1499301915, // here's my timestamp that originates from the Azure Function
"_ts":          1499301899  // and here's the timestamp created by DocDB?
</code>```

And the code used to derive my_timestamp in the Azure Function:

```<code>var timeStamp = + Math.floor(new Date().getTime() / 1000);
</code>```

答:
AFAIK, The _ts field is a unix-style epoch timestamp representing the date and time and it would be updated every time when a document is modified.

Anyway, I wanted to see if anyone else is encountering this discrepancy.

According to your description, I checked this issue and I encountered the same issue for some times. But when I check this issue today, I could not reproduce this issue, Here is my code for testing:

Javascript

```<code>var doc={
    timestamp:Math.floor(new Date().getTime() / 1000)
    };

context.bindings.outputDocument = doc;

setTimeout( function() {
    context.res={
        status:200,
        body:JSON.stringify(doc)
    };
    context.done();
}, 10*1000);
</code>```

Query result via Query Explorer from azure portal:

Also, I have checked with azure function C# template and DocumentDB client SDK for adding new document. If this issue persists on your side, I assumed that you could add your feedback here.

Body:
I have an Azure DocumentDB collection that I'm writing time-stamped documents to via an Event Hub triggered function.  The timestamp that I'm writing to the document (my_timestamp) originates from the function that processes the event, and I've confirmed that it is accurate.

The problem that I'm encountering is that the _ts metadata timestamp that's created by DocumentDB itself is showing a unix timestamp value that's a number of seconds previous to the timestamp I'm creating, i.e., it's actually applying a timestamp that's earlier than the beginning of the function execution that creates the document...

It appears that this may be a quirk in the underlying DocumentDB mechanics.

Anyway, I wanted to see if anyone else is encountering this discrepancy.  Here are the timestamps as they appear in my document:

"my_timestamp": 1499301915, // here's my timestamp that originates from the Azure Function
"_ts":          1499301899  // and here's the timestamp created by DocDB?

And the code used to derive my_timestamp in the Azure Function:

var timeStamp = + Math.floor(new Date().getTime() / 1000);

Body:
AFAIK, The _ts field is a unix-style epoch timestamp representing the date and time and it would be updated every time when a document is modified.

Anyway, I wanted to see if anyone else is encountering this discrepancy.

According to your description, I checked this issue and I encountered the same issue for some times. But when I check this issue today, I could not reproduce this issue, Here is my code for testing:

Javascript

var doc={
    timestamp:Math.floor(new Date().getTime() / 1000)
    };

context.bindings.outputDocument = doc;

setTimeout( function() {
    context.res={
        status:200,
        body:JSON.stringify(doc)
    };
    context.done();
}, 10*1000);

Query result via Query Explorer from azure portal:

Also, I have checked with azure function C# template and DocumentDB client SDK for adding new document. If this issue persists on your side, I assumed that you could add your feedback here.


问:
Indexing Between two Matrices
I have two Matrices (V; Vertex Node Coordinates x,y,z & T; List of Triangles showing the nodes (1,2,3) that make up the triangle)

I want to replace the values in T with the coordinates of the corresponding vertex nodes ie:

```<code>V
    1 --- 1.35234 1.2542445 1.32234324
    2 --- 3.42354 1.2521345 1.34325524
    3 --- 2.26434 1.2323345 1.33225324
T
1 2 3

should go to

T_V

1.35234 1.2542445 1.32234324 3.42354 1.2521345 1.34325524 2.26434 1.2323345 1.33225324
</code>```

Title: Indexing Between two Matrices

Body:
I have two Matrices (V; Vertex Node Coordinates x,y,z & T; List of Triangles showing the nodes (1,2,3) that make up the triangle)

I want to replace the values in T with the coordinates of the corresponding vertex nodes ie:

V
    1 --- 1.35234 1.2542445 1.32234324
    2 --- 3.42354 1.2521345 1.34325524
    3 --- 2.26434 1.2323345 1.33225324
T
1 2 3

should go to

T_V

1.35234 1.2542445 1.32234324 3.42354 1.2521345 1.34325524 2.26434 1.2323345 1.33225324

Body:
I don't know if you mean something this basic, but

V = [1.35234 1.2542445 1.32234324;
      3.42354 1.2521345 1.34325524;
      2.26434 1.2323345 1.33225324];
T = [1 2 3]
Tv = [V(T(1),:),V(T(1),:),V(T(3),:)];


问:
Get objects filtered by value of another table
I have the following model which links a user to his session:

```<code>class UserSession(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    session = models.ForeignKey(Session)
</code>```

Now I want to get all active sessions from the given user.

How can I do the following SQL in Django 1.10?

```<code>SELECT * FROM django_session WHERE session_key IN (SELECT session_id FROM usersys_usersession WHERE user_id = 1) AND expire_date > now()
</code>```

答:
I assume you want all sessions which are not expired for a given user? Then there would be no reason for a subquery. Just join the user and session table, and compare for the expire_date?</p>

```<code>UserSession.objects.filter(user_id = 1, session__expire_data__gt = timezone.now())
</code>```

Body:
I have the following model which links a user to his session:

class UserSession(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    session = models.ForeignKey(Session)

Now I want to get all active sessions from the given user.

How can I do the following SQL in Django 1.10?

SELECT * FROM django_session WHERE session_key IN (SELECT session_id FROM usersys_usersession WHERE user_id = 1) AND expire_date > now()

Body:
I assume you want all sessions which are not expired for a given user? Then there would be no reason for a subquery. Just join the user and session table, and compare for the expire_date?

UserSession.objects.filter(user_id = 1, session__expire_data__gt = timezone.now())


问:
c# booleans: return true if first boolean is true and the second is false
I'm learning C# and have attempted this question. Please see my two attempts underneath the question below, and can someone point out to me where/how I have gone wrong please? Thanks.

Attempt 1:

        Return true if the first boolean is true and the second is false.

```<code>public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    if (boolean1 = true && (boolean2 = false))
    {
        return true;
    }
    return false;
}
</code>```

Attempt 2:

```<code>public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    boolean1 = true;
    boolean2 = false;
    return boolean1 && boolean2;
}
</code>```

答:
a single = sets a variable.
You need to use a double.

Also, you can rewrite it somewhat.

```<code>public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    return boolean1 && !boolean2;
}
</code>```

if you want to keep it as you have it, it would be like this:

```<code>public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    if (boolean1 == true && boolean2 == false)
    {
        return true;
    }

    return false;
    }
}
</code>```

Body:
I'm learning C# and have attempted this question. Please see my two attempts underneath the question below, and can someone point out to me where/how I have gone wrong please? Thanks.

Attempt 1:

        Return true if the first boolean is true and the second is false.

public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    if (boolean1 = true && (boolean2 = false))
    {
        return true;
    }
    return false;
}

Attempt 2:

public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    boolean1 = true;
    boolean2 = false;
    return boolean1 && boolean2;
}

Body:
a single = sets a variable.
You need to use a double.

Also, you can rewrite it somewhat.

public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    return boolean1 && !boolean2;
}

if you want to keep it as you have it, it would be like this:

public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    if (boolean1 == true && boolean2 == false)
    {
        return true;
    }

    return false;
    }
}


问:
If statements(no returns) in Pharo Smalltalk for flatten list
I'm trying to make a list(30) of lists (30).
I have this:

```<code>#(#(a a a) nil nil #(b) #(c) #(d) nil nil nil #(e e) nil #(f f) nil #(g)
  #(h) nil nil nil #(i  i) nil nil nil #(j) nil nil nil nil nil
  #(k) #(l l l)
</code>```

And I want to do a program that turns that into just a list like this:

```<code> #(a a a b c d e e f f g hi i j k l l l)
</code>```

My code is this:

```<code>ToList: lista
    | retorno y z |
    retorno := Array new: 30.
    y := 1.
    (1 to: lista size)
        do: [ :i |
            z := 0.
            (lista at: i) isNil
            ifFalse:
            (1 to: (lista at: i) size do: [ :j | retorno at: (y + z) put: ((lista at: i) at: j )
                y:= y+1.
                z:= z +1.]
            )].
        ^retorno
</code>```

I think there are some problems with the if-statements, because there's no return. I don't know what to do, because it works without the y:= y+1., but it keeps some nil spaces.

Please, help me!

答:
You could write it as:

```<code>flattenArray: anArray
  | ws |

  ws = WriteStream on: (Array new).
  anArray do: [:subArr| :
                     subArr notNil ifTrue: [
                        subArr do: [ :el | ws nextPut: el ]]].
  ^ws contents.
</code>```

There are 2 general remarks, it is rarely necessary to access collection elements by index, if you are doing it, stop, and think if there are more elegant methods available. Second WriteStreams are handy when you want to collect series of results.

Body:
I'm trying to make a list(30) of lists (30).
I have this:

#(#(a a a) nil nil #(b) #(c) #(d) nil nil nil #(e e) nil #(f f) nil #(g)
  #(h) nil nil nil #(i  i) nil nil nil #(j) nil nil nil nil nil
  #(k) #(l l l)

And I want to do a program that turns that into just a list like this:

 #(a a a b c d e e f f g hi i j k l l l)

My code is this:

ToList: lista
    | retorno y z |
    retorno := Array new: 30.
    y := 1.
    (1 to: lista size)
        do: [ :i |
            z := 0.
            (lista at: i) isNil
            ifFalse:
            (1 to: (lista at: i) size do: [ :j | retorno at: (y + z) put: ((lista at: i) at: j )
                y:= y+1.
                z:= z +1.]
            )].
        ^retorno

I think there are some problems with the if-statements, because there's no return. I don't know what to do, because it works without the y:= y+1., but it keeps some nil spaces.

Please, help me!

Body:
You could write it as:

flattenArray: anArray
  | ws |

  ws = WriteStream on: (Array new).
  anArray do: [:subArr| :
                     subArr notNil ifTrue: [
                        subArr do: [ :el | ws nextPut: el ]]].
  ^ws contents.

There are 2 general remarks, it is rarely necessary to access collection elements by index, if you are doing it, stop, and think if there are more elegant methods available. Second WriteStreams are handy when you want to collect series of results.


问:
Bootstrap v3 Caret Position toggle
I am trying to find the default way that bootstrap toggles the up/down display of the caret when toggling a .collapse div.

So the code is:

```<code><div class='row'>
    <div class='col-sm-8'><h3>Select Image</h3></div>
    <div class='col-sm-4 text-right'><button type='button' class='btn btn-default' data-toggle='collapse' data-target='#image-files' aria-expanded="false"><b class="caret"></b></button></div>
</div>
<div id='image-files' class='collapse'>
    <div class='row'>
    Content
    </div>
</div>
</code>```

I'm sure i've read somewhere that the bootstrap library will automatically change the caret from down to up somehow.

Of course I could use a line of Jquery to do it but I'm sure it's built into bootstrap and I want to know how to use that.

答:
There is a built-in up/down option if this is what you are looking for:

```<code><span class="dropup">
    <span class="caret"></span>
</span>
</code>```

(Or are you looking for any more detail or something else? I am not completely sure I understood your problem perfectly.)

Title: Bootstrap v3 Caret Position toggle

Body:
I am trying to find the default way that bootstrap toggles the up/down display of the caret when toggling a .collapse div.

So the code is:

Select Image

<button type='button' class='btn btn-default' data-toggle='collapse' data-target='#image-files' aria-expanded="false"></button>

    Content

I'm sure i've read somewhere that the bootstrap library will automatically change the caret from down to up somehow.

Of course I could use a line of Jquery to do it but I'm sure it's built into bootstrap and I want to know how to use that.

Body:
There is a built-in up/down option if this is what you are looking for:

<span class="dropup">
    <span class="caret"></span>
</span>

(Or are you looking for any more detail or something else? I am not completely sure I understood your problem perfectly.)


问:
How can I check if MSBuild is using .NET Core?
I am using Scripty.MsBuild to generate some files in a ASP.NET Core project. When I build from VS2017, the target runs successfully, but when I build via dotnet, I get the error:

```<code>Scripty.MsBuild.targets(31,5): error MSB4062: The "ScriptyTask" task could not be loaded from the assembly C:\Users\geirsagberg\.nuget\packages\scripty.msbuild\0.7.4\build\\..\tools\Scripty.MsBuild.dll. Could not load file or assembly 'Microsoft.Build.Utilities.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified. Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.
</code>```

My current workaround is to disable Scripty.MsBuild for Release configuration:

```<code><PackageReference Include="Scripty.MsBuild" Version="0.7.4" Condition="'$(Configuration)'=='Debug'" />
</code>```

This lets me build from VS in debug mode, and build with dotnet on the build server.

However, I still want to be able to do dotnet run locally in debug mode (for running from VSCode). Therefore I need to include the PackageReference conditionally, based on whether Visual Studio's MSBuild is running, or the dotnet version. As far as I can tell, these two have the exact same version number; am I missing something?

Is there a property in MSBuild I can use to distinguish between the VS MSBuild and the dotnet one?

答:
Turns out there is a property MSBuildRuntimeType that can be either Core, Mono or Full. So I can do:

```<code><PackageReference Include="Scripty.MsBuild" Version="0.7.4" Condition="'$(MSBuildRuntimeType)'!='Core'" />
</code>```

Reference from SDK

Body:
I am using Scripty.MsBuild to generate some files in a ASP.NET Core project. When I build from VS2017, the target runs successfully, but when I build via dotnet, I get the error:

Scripty.MsBuild.targets(31,5): error MSB4062: The "ScriptyTask" task could not be loaded from the assembly C:\Users\geirsagberg\.nuget\packages\scripty.msbuild\0.7.4\build\\..\tools\Scripty.MsBuild.dll. Could not load file or assembly 'Microsoft.Build.Utilities.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified. Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.

My current workaround is to disable Scripty.MsBuild for Release configuration:

<PackageReference Include="Scripty.MsBuild" Version="0.7.4" Condition="'$(Configuration)'=='Debug'" />

This lets me build from VS in debug mode, and build with dotnet on the build server.

However, I still want to be able to do dotnet run locally in debug mode (for running from VSCode). Therefore I need to include the PackageReference conditionally, based on whether Visual Studio's MSBuild is running, or the dotnet version. As far as I can tell, these two have the exact same version number; am I missing something?

Is there a property in MSBuild I can use to distinguish between the VS MSBuild and the dotnet one?

Body:
Turns out there is a property MSBuildRuntimeType that can be either Core, Mono or Full. So I can do:

<PackageReference Include="Scripty.MsBuild" Version="0.7.4" Condition="'$(MSBuildRuntimeType)'!='Core'" />

Reference from SDK


问:
Intellisense not recognising type hinting for python 3
I would like to use Visual Studio and see intellisense using type hints, for example in the function argument list, to workout the type of a variable.

This can be achieved through isinstance(param,type) statements, but I wonder if we can get it to work without these additional statements:

Note: I have tried Visual Studio with Python Tools for Visual Studio and also the early 2017 Visual Studio Preview, that has python support built in, but neither seem to appreciate type hints.

答:
After confirmed, this result is by designed, please check this: Python 3.6: using type hints to describe a variable in the function argument list and the Quick Info of this variable display ‘unknown type’

Int19h: The result is as expected currently, because PTVS does not yet support type hints to drive code completion. The following issue is tracking that feature: #82.