问:
C++ RemoveFront function for Doubly Linked List
I'm working on a lab for school and I'm stuck on a function for a doubly linked list. When I try to remove the front node from the list with the removeFront() function it returns NULL and couts for me to create a list even though there already is one. I'll post my cpp file and main below and hopefully someone can help me understand what's going wrong with it.</p>

```<code>//DLinkedList.h

#pragma once

#include <string>
using namespace std;

typedef string Elem;

struct DNode
{
    Elem value;
    DNode* next;
    DNode* prev;
};

class DLinkedList
{
public:
    DLinkedList() { header_ = NULL; }
    ~DLinkedList() { };
    bool empty() const;
    const Elem& front() const;
    const Elem& back() const;
    void addFront(const Elem& e);
    void addBack(const Elem& e);
    void removeFront();
    void removeBack();

private:
    DNode* header_;
    DNode* trailer_;

protected:
    void add(DNode* v, const DNode& e);
    void remove(DNode* v);
};

//DLinkedList.cpp

#include <iostream>
#include "DLinkedList.h"

using namespace std;

const Elem& DLinkedList::front() const
{
    if (header_ == NULL)
    {
        cout << "Please create a doubly linked list first.\n\n";
    }
    else
    {
        return header_->value;
    }

}

void DLinkedList::addFront(const Elem& e) //DONE
{
    // If there is no header
    // create a temporary node and set
    // the header to it
    if (header_ == NULL)
    {
        DNode *temp;
        temp = new(struct DNode);
        temp->prev = NULL;
        temp->value = e;
        temp->next = NULL;

        header_ = temp;
        trailer_ = temp;
    }
    else
    {
        //Create current node to point to header
        // and temp node to be the new front node
        DNode *current;
        DNode *temp;
        current = header_;
        temp = new(struct DNode);
        temp->prev = NULL;
        temp->value = e;
        temp->next = current->next;

        header_->prev = temp->next;
        header_ = temp;
    }

    cout << "Element Inserted at the front." << endl;

}

void DLinkedList::removeFront()
{
    // Check to see if there is anything
    // in the list first
    if (header_ == NULL)
    {
        cout << "Create a doubly linked list first.";
    }

    // Check to see if the list has more than one item.
    // If it only has one node erase it.
    DNode *current;
    current = header_;

    if (current->next == NULL)
    {
        header_->next = NULL;
        header_->value = "";
        header_->prev = NULL;
        header_ = NULL;
    }
    else
    {
        current = current->next;
        //header_->next = NULL;
        //header_->value = "";
        //header_->prev = NULL;
        header_ = current;
        header_->prev = NULL;
    }
}

//Main.cpp

#include <iostream>
#include <string>
#include <cassert>
#include "DLinkedList.h"

using namespace std;

int main()
{
    DLinkedList album;
    album.addFront("Word");
    album.addFront("Turn");
    album.addFront("Bird");
    album.addFront("Weird");

    cout << album.front() << endl;

    album.removeFront();

    cout << album.front() << endl;

    system("pause");

    return 0;
}
</code>```

答:
I think your addFront is also wrong, i would do it like that:</p>

```<code>void DLinkedList::addFront(const Elem& content) //DONE
{
    // If there is no header
    // create a temporary node and set
    // the header to it
    if (header_ == NULL)
    {
        header_ = new(struct DNode);
        header_->prev = NULL;
        header_->value = content;
        header_->next = NULL;

        trailer_ = header_;
    }
    else
    {
        //Create current node to point to header
        // and temp node to be the new front node
        DNode *tmp;
        tmp = new(struct DNode);
        tmp->prev = NULL;
        tmp->value = content;
        tmp->next = header_;

        header_->prev = tmp;
        header_ = tmp;
    }

    cout << "Element Inserted at the front." << endl;

}
</code>```

Body:
I'm working on a lab for school and I'm stuck on a function for a doubly linked list. When I try to remove the front node from the list with the removeFront() function it returns NULL and couts for me to create a list even though there already is one. I'll post my cpp file and main below and hopefully someone can help me understand what's going wrong with it.

//DLinkedList.h

#pragma once

#include <string>
using namespace std;

typedef string Elem;

struct DNode
{
    Elem value;
    DNode* next;
    DNode* prev;
};

class DLinkedList
{
public:
    DLinkedList() { header_ = NULL; }
    ~DLinkedList() { };
    bool empty() const;
    const Elem& front() const;
    const Elem& back() const;
    void addFront(const Elem& e);
    void addBack(const Elem& e);
    void removeFront();
    void removeBack();

private:
    DNode* header_;
    DNode* trailer_;

protected:
    void add(DNode* v, const DNode& e);
    void remove(DNode* v);
};

//DLinkedList.cpp

#include <iostream>
#include "DLinkedList.h"

using namespace std;

const Elem& DLinkedList::front() const
{
    if (header_ == NULL)
    {
        cout << "Please create a doubly linked list first.\n\n";
    }
    else
    {
        return header_->value;
    }

}

void DLinkedList::addFront(const Elem& e) //DONE
{
    // If there is no header
    // create a temporary node and set
    // the header to it
    if (header_ == NULL)
    {
        DNode *temp;
        temp = new(struct DNode);
        temp->prev = NULL;
        temp->value = e;
        temp->next = NULL;

        header_ = temp;
        trailer_ = temp;
    }
    else
    {
        //Create current node to point to header
        // and temp node to be the new front node
        DNode *current;
        DNode *temp;
        current = header_;
        temp = new(struct DNode);
        temp->prev = NULL;
        temp->value = e;
        temp->next = current->next;

        header_->prev = temp->next;
        header_ = temp;
    }

    cout << "Element Inserted at the front." << endl;

}

void DLinkedList::removeFront()
{
    // Check to see if there is anything
    // in the list first
    if (header_ == NULL)
    {
        cout << "Create a doubly linked list first.";
    }

    // Check to see if the list has more than one item.
    // If it only has one node erase it.
    DNode *current;
    current = header_;

    if (current->next == NULL)
    {
        header_->next = NULL;
        header_->value = "";
        header_->prev = NULL;
        header_ = NULL;
    }
    else
    {
        current = current->next;
        //header_->next = NULL;
        //header_->value = "";
        //header_->prev = NULL;
        header_ = current;
        header_->prev = NULL;
    }
}

//Main.cpp

#include <iostream>
#include <string>
#include <cassert>
#include "DLinkedList.h"

using namespace std;

int main()
{
    DLinkedList album;
    album.addFront("Word");
    album.addFront("Turn");
    album.addFront("Bird");
    album.addFront("Weird");

    cout << album.front() << endl;

    album.removeFront();

    cout << album.front() << endl;

    system("pause");

    return 0;
}

Body:
I think your addFront is also wrong, i would do it like that:

void DLinkedList::addFront(const Elem& content) //DONE
{
    // If there is no header
    // create a temporary node and set
    // the header to it
    if (header_ == NULL)
    {
        header_ = new(struct DNode);
        header_->prev = NULL;
        header_->value = content;
        header_->next = NULL;

        trailer_ = header_;
    }
    else
    {
        //Create current node to point to header
        // and temp node to be the new front node
        DNode *tmp;
        tmp = new(struct DNode);
        tmp->prev = NULL;
        tmp->value = content;
        tmp->next = header_;

        header_->prev = tmp;
        header_ = tmp;
    }

    cout << "Element Inserted at the front." << endl;

}


来源: stackexchange

问:
R: Selectively display nodes when plotting an igraph
How can I plot a selection of igraph nodes?

I have an existing graph, but it is too complex.  I want to be able to 'zoom in' on a subset of the nodes.

I am able to delete a subset of edges, but I can't figure out how to 'turn off' the isolated nodes.

When using the network package, the  displayisolates=FALSE parameter does this;  it does not display these isolated nodes.

The layout algorithm should also ignore the 'turned off' edges.

For example:

```<code>g1 <- graph( c( 0,1, 1,2, 2,2, 2,3 ) )
g2 <- delete.edges(g1, E(g1, c(0,1)))
plot(g2)
</code>```

When plotting g2, I want to not display node 0.

Thanks

答:
```<code>iso <- V(g1)[degree(g1)==0]
g2 <- delete.vertices(g1, iso)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I plot a selection of igraph nodes?

I have an existing graph, but it is too complex.  I want to be able to 'zoom in' on a subset of the nodes.

I am able to delete a subset of edges, but I can't figure out how to 'turn off' the isolated nodes.

When using the network package, the  displayisolates=FALSE parameter does this;  it does not display these isolated nodes.

The layout algorithm should also ignore the 'turned off' edges.

For example:

g1 <- graph( c( 0,1, 1,2, 2,2, 2,3 ) )
g2 <- delete.edges(g1, E(g1, c(0,1)))
plot(g2)

When plotting g2, I want to not display node 0.

Thanks


问:
MS Access Specify Table Insert Order for Linked Tables? (NULL Foreign Key Error)

Short Version

Is there a way to force (or provide a hint to) Microsoft Access to perform an insert (through an updateable query) in a certain order (between tables), or to tell it that one column in a query depends on (the auto-generated value of) another column in that query?

Longer Version

When I insert values into an updateable query which spans 2 joined tables (both of which are linked tables on an MS SQL Server) through a form, I get the following error:

ODBC--call failed.

[Microsoft][ODBC SQL Server Driver][SQL Server]Cannot insert the value NULL into column <fk column>', table '<tablename>'; column does not allow nulls.  INSERT fails (#515) [Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been terminated. (#3612)

This is because Access does not recognize that the fk column of the second table should have the same value as the pk column of the first table in the query (or doesn't successfully execute the query so this happens).

This behavior is observed on Access 2000, 2003, 2007 connecting to MS SQL Server 2005 (Express or Workgroup) through the Microsoft SQL Server ODBC connector.

Play Along At Home

For those of you who would like to play this game at home, here's how to reproduce the behavior I am describing.  First, create the test tables in SQL Server:

```<code>CREATE TABLE People
(
    PersonID INT IDENTITY NOT NULL
        CONSTRAINT PK_People PRIMARY KEY,
    FullName NVARCHAR(100) NOT NULL
);
CREATE TABLE Gamers
(
    PersonID INT NOT NULL
        CONSTRAINT PK_Gamers PRIMARY KEY
        CONSTRAINT FK_Gamers_People REFERENCES People (PersonID)
            ON DELETE CASCADE
            ON UPDATE CASCADE,
    Alias NVARCHAR(100) NOT NULL
);
</code>```

Then, create a new blank Access database and create new linked tables which reference the tables created above.  Create a relationship between the tables in the Relationships editor (Access will correctly determine that it is a one-to-one relationship).  Then create the following query:

```<code>SELECT People.PersonID AS People_PersonID, People.FullName,
    Gamers.PersonID AS Gamers_PersonID, Gamers.Alias
FROM People
    INNER JOIN Gamers ON People.PersonID = Gamers.PersonID;
</code>```

Note that the above query does work properly for inserting through the Dataset view (as long as FullName is entered, of course).

Then, create a form with the RecordSource set to the query above.  Create text boxes for FullName and Alias.  Then switch to Form View and try to insert data.  With any luck, you will see the error message quoted above.

Possible Workarounds

One way to work-around this problem is to create a sub-form for the data in the child table.  With suitable border and coloring it is almost transparent to the user.  However,  this has a few problems.  First, extra code must be added to prevent entering the subform before the parent form is completed (otherwise Access will provide dense errors to the user about master/child link fields).  Also, users can't sort/filter on any field in the subform, since it would only filter subform records (of which there will always be exactly one).  That being said, it is the solution that I am using for now.

I'm hoping one of you know of a better solution.  Thanks for reading.

答:
Although the solution provided by Remou does work, the solution I am currently using is a bit different.  It is not necessarily better or worse, and the choice between this solution and the one proposed by Remou will depend on the specific situation.

I created an Updatable View on the SQL Server (using INSTEAD OF triggers) which provided the same data as the query in Access.  Next, I created a linked table in Access which referenced the view, then modified the form to use that view instead of the query.  Simple, right?

The tricky part was maintaining the pseudo-index when changing the connection string (which I do often), since I did not want to create an index on the view in SQL Server (since data in the underlying table is updated frequently) and Access can only insert/update tables with indexes.  The solution was to re-create the index after changing the connection string.  (For more on that specific problem, see my writeup)

ContentLicense: CC BY-SA 2.5

Body:
Short Version

Is there a way to force (or provide a hint to) Microsoft Access to perform an insert (through an updateable query) in a certain order (between tables), or to tell it that one column in a query depends on (the auto-generated value of) another column in that query?

Longer Version

When I insert values into an updateable query which spans 2 joined tables (both of which are linked tables on an MS SQL Server) through a form, I get the following error:

ODBC--call failed.

[Microsoft][ODBC SQL Server Driver][SQL Server]Cannot insert the value NULL into column <fk column>', table '<tablename>'; column does not allow nulls.  INSERT fails (#515) [Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been terminated. (#3612)

This is because Access does not recognize that the fk column of the second table should have the same value as the pk column of the first table in the query (or doesn't successfully execute the query so this happens).

This behavior is observed on Access 2000, 2003, 2007 connecting to MS SQL Server 2005 (Express or Workgroup) through the Microsoft SQL Server ODBC connector.

Play Along At Home

For those of you who would like to play this game at home, here's how to reproduce the behavior I am describing.  First, create the test tables in SQL Server:

CREATE TABLE People
(
    PersonID INT IDENTITY NOT NULL
        CONSTRAINT PK_People PRIMARY KEY,
    FullName NVARCHAR(100) NOT NULL
);
CREATE TABLE Gamers
(
    PersonID INT NOT NULL
        CONSTRAINT PK_Gamers PRIMARY KEY
        CONSTRAINT FK_Gamers_People REFERENCES People (PersonID)
            ON DELETE CASCADE
            ON UPDATE CASCADE,
    Alias NVARCHAR(100) NOT NULL
);

Then, create a new blank Access database and create new linked tables which reference the tables created above.  Create a relationship between the tables in the Relationships editor (Access will correctly determine that it is a one-to-one relationship).  Then create the following query:

SELECT People.PersonID AS People_PersonID, People.FullName,
    Gamers.PersonID AS Gamers_PersonID, Gamers.Alias
FROM People
    INNER JOIN Gamers ON People.PersonID = Gamers.PersonID;

Note that the above query does work properly for inserting through the Dataset view (as long as FullName is entered, of course).

Then, create a form with the RecordSource set to the query above.  Create text boxes for FullName and Alias.  Then switch to Form View and try to insert data.  With any luck, you will see the error message quoted above.

Possible Workarounds

One way to work-around this problem is to create a sub-form for the data in the child table.  With suitable border and coloring it is almost transparent to the user.  However,  this has a few problems.  First, extra code must be added to prevent entering the subform before the parent form is completed (otherwise Access will provide dense errors to the user about master/child link fields).  Also, users can't sort/filter on any field in the subform, since it would only filter subform records (of which there will always be exactly one).  That being said, it is the solution that I am using for now.

I'm hoping one of you know of a better solution.  Thanks for reading.


问:
onclick show/hide function and addClass/removeClass on two separate navigations canceling itself out/not working
I have two navigations on the website (not the main navi) with each onclick displaying content underneath. The first content of each is also active, so to be displayed at page load, the button/link changes active class on click for the hover to stick.

I have searched and tried several things but with my very limit knowledge of JS/jQuery did not make any headway. My jQuery below (last try).

P.S. The jQuery works fine with one navigation, and I managed to get it to work with both, but they cancel each others content out (click on one hides all others). Haven't found a semi-workable solution for addClass/removeClass though.

My Fiddle.

jQuery :

```<code>$("#nav1, #nav2 a").click(function(e){
  e.preventDefault();
  $(".toggle").hide(); //also tried $(".toggle,.toggle1") with the seperate navi content having classes toggle and toggle1
  var toShow = $(this).attr('href');
  $(toShow).show();
});

var selector = '.box';

$(selector).on('click', function(){
  $(selector).removeClass('active');
  $(this).addClass('active');
});

// tried this for active class but doesnt work

var selector = '.last-nav';

$(selector).on('click', function(){
  $(selector).removeClass('active');
  $(this).addClass('active');
});
</code>```

EDIT:

If I could bother some more.

The first part worked like a charm, the .closest('section') I found particularly illuminating, aswell as the id^= and id*= - yes im very new to js. :)
But I still have a problem with the second part. As is, when one clicks on one navigation, the active Class (example Button) also hides on the second navigation. I would like the buttons in the first navi to keep the active Class also after clicking a link in the second navi (so both have own active Classes assigned).

I tried with .closest('section') again but didn't work (tried it on all three rows and each row alone, worth a shot I guess).

I again tried like this (assigning diff classes to each)

```<code>var selector = '.nav-active';
$(selector).on('click', function(){
$(selector).removeClass('active');
$(this).addClass('active');
});

var selector = '.nav-active2';
$(selector).on('click', function(){
$(selector).removeClass('active');
$(this).addClass('active');
});
</code>```

For some reason it seems to work on the second navigation, but on the first (with buttons) it doesn't remove the active Class (although it does add it - hover effect sticks).

I hope the above is understandable, it was a long day.

Thankye!

答:
Working fiddle.

You should not use $(".toggle") selector else all the elements with this class will be affected, instead target just those who're inside the section if clicked anchor a using the following selector :

```<code>$(this).closest('section').find(".toggle").hide();
</code>```

NOTE : To target the both nav's you could use class or id selctors like :

```<code>$("[id^='nav'] a").click(function(e){
//Or
$(".row a").click(function(e){
</code>```

Hope this helps.

$("[id^='nav'] a").click(function(e){
  e.preventDefault();

  $(this).closest('section').find(".toggle").hide();

  var toShow = $(this).attr('href');
  $(toShow).show();
});

var selector = '.box';
$(selector).on('click', function(){
  $(this).closest('section').find(selector).removeClass('active');
  $(this).addClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active{
   color: green;
}</code>```

BUTTON 1

BUTTON 2

Content 1

Content 2

Link 1

Link 2

Content 3

Content 4

```

Body:
I have two navigations on the website (not the main navi) with each onclick displaying content underneath. The first content of each is also active, so to be displayed at page load, the button/link changes active class on click for the hover to stick.

I have searched and tried several things but with my very limit knowledge of JS/jQuery did not make any headway. My jQuery below (last try).

P.S. The jQuery works fine with one navigation, and I managed to get it to work with both, but they cancel each others content out (click on one hides all others). Haven't found a semi-workable solution for addClass/removeClass though.

My Fiddle.

jQuery :

$("#nav1, #nav2 a").click(function(e){
  e.preventDefault();
  $(".toggle").hide(); //also tried $(".toggle,.toggle1") with the seperate navi content having classes toggle and toggle1
  var toShow = $(this).attr('href');
  $(toShow).show();
});

var selector = '.box';

$(selector).on('click', function(){
  $(selector).removeClass('active');
  $(this).addClass('active');
});

// tried this for active class but doesnt work

var selector = '.last-nav';

$(selector).on('click', function(){
  $(selector).removeClass('active');
  $(this).addClass('active');
});

EDIT:

If I could bother some more.

The first part worked like a charm, the .closest('section') I found particularly illuminating, aswell as the id^= and id*= - yes im very new to js. :)
But I still have a problem with the second part. As is, when one clicks on one navigation, the active Class (example Button) also hides on the second navigation. I would like the buttons in the first navi to keep the active Class also after clicking a link in the second navi (so both have own active Classes assigned).

I tried with .closest('section') again but didn't work (tried it on all three rows and each row alone, worth a shot I guess).

I again tried like this (assigning diff classes to each)

var selector = '.nav-active';
$(selector).on('click', function(){
$(selector).removeClass('active');
$(this).addClass('active');
});

var selector = '.nav-active2';
$(selector).on('click', function(){
$(selector).removeClass('active');
$(this).addClass('active');
});

For some reason it seems to work on the second navigation, but on the first (with buttons) it doesn't remove the active Class (although it does add it - hover effect sticks).

I hope the above is understandable, it was a long day.

Thankye!

Body:
Working fiddle.

You should not use $(".toggle") selector else all the elements with this class will be affected, instead target just those who're inside the section if clicked anchor a using the following selector :

$(this).closest('section').find(".toggle").hide();

NOTE : To target the both nav's you could use class or id selctors like :

$("[id^='nav'] a").click(function(e){
//Or
$(".row a").click(function(e){

Hope this helps.

$("[id^='nav'] a").click(function(e){
  e.preventDefault();

  $(this).closest('section').find(".toggle").hide();

  var toShow = $(this).attr('href');
  $(toShow).show();
});

var selector = '.box';
$(selector).on('click', function(){
  $(this).closest('section').find(selector).removeClass('active');
  $(this).addClass('active');
});

.active{
   color: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<section>
  <div class="row" id="nav1">
    <ul class="list">
      <li>
        <a href="#link1" class="box active">
          <p>BUTTON 1</p>
        </a>
      </li>
      <li>
        <a href="#link2" class="box">
          <p>BUTTON 2</p>
        </a>
      </li>
    </ul>
  </div>

  <div class="toggle" id="link1" style="display:block">
    <h2>Content 1</h2>
  </div>
  <div class="toggle" id="link2" style="display:none">
    <h2>Content 2</h2>
  </div>
</section>

<section>
  <div class="row" id="nav2">
    <ul class="list">
      <li><a href="#link3" class="last-nav box active">Link 1</a></li>
    </ul>
    <ul class="list">
      <li><a href="#link4" class="last-nav box">Link 2</a></li>
    </ul>

  </div>

  <div class="toggle" id="link3" style="display:block">
    <h2>Content 3</h2>
  </div>
  <div class="toggle" id="link4" style="display:none">
    <h2>Content 4</h2>
  </div>
</section>


问:
iOS - Run async operations in serial manner on non-main thread
```<code>- (void) fetchOperation:(NSString *c){
    async_method(c):^{
      NSLog(@"%@ completed.",c);
    }
  }
// call fetchOperation:@"A"
// call fetchOperation:@"B"
// call fetchOperation:@"C"

//Expecting output: A completed, B completed, C Completed.
</code>```

Please note I want fetch to happen on non-main thread. Their could be 1 to n fetchOperation calls. And each fetchOperation call can happen as a result of some other user action like user tapped.
I tried semaphores, nsoperationQueue but no luck so far.

答:
Give the function a completion handler as part of it's interface...

```<code>- (void)fetchOperation:(NSString *)string completion:(void(^)(void))completion {
    async_method(string):^{
        NSLog(@"%@ completed.",string);
        if (completion) completion();
    }
}
</code>```

Then make the calls nested...

```<code>[self fetchOperation:@"A" completion:^{
    [self fetchOperation:@"B" completion:^{
        [self fetchOperation:@"C" completion:^{
            NSLog(@"all done");
        }];
    }];
}];
</code>```

EDIT To handle an arbitrary set of params, create a function that takes an array and calls itself recursively...

```<code>- (void)manyFetchOperations:(NSArray *)parameters completion:(void(^)(void))completion {
    if (!parameters.count) return completion();
    NSString *nextParam = parameters[0];
    NSArray *remainingParams = [parameters subarrayWithRange:NSMakeRange(1, parameters.count-1)];
    [self fetchOperation:nextParam completion:^{
        [self manyFetchOperations:remainingParams completion:completion];
    }];
}
</code>```

Call it as follows, for the same effect as nesting...

```<code>[self manyFetchOperations:@[@"A", @"B", @"C"] completion:^{}];
</code>```

Body:
- (void) fetchOperation:(NSString *c){
    async_method(c):^{
      NSLog(@"%@ completed.",c);
    }
  }
// call fetchOperation:@"A"
// call fetchOperation:@"B"
// call fetchOperation:@"C"

//Expecting output: A completed, B completed, C Completed.

Please note I want fetch to happen on non-main thread. Their could be 1 to n fetchOperation calls. And each fetchOperation call can happen as a result of some other user action like user tapped.
I tried semaphores, nsoperationQueue but no luck so far.

Body:
Give the function a completion handler as part of it's interface...

- (void)fetchOperation:(NSString *)string completion:(void(^)(void))completion {
    async_method(string):^{
        NSLog(@"%@ completed.",string);
        if (completion) completion();
    }
}

Then make the calls nested...

[self fetchOperation:@"A" completion:^{
    [self fetchOperation:@"B" completion:^{
        [self fetchOperation:@"C" completion:^{
            NSLog(@"all done");
        }];
    }];
}];

EDIT To handle an arbitrary set of params, create a function that takes an array and calls itself recursively...

- (void)manyFetchOperations:(NSArray *)parameters completion:(void(^)(void))completion {
    if (!parameters.count) return completion();
    NSString *nextParam = parameters[0];
    NSArray *remainingParams = [parameters subarrayWithRange:NSMakeRange(1, parameters.count-1)];
    [self fetchOperation:nextParam completion:^{
        [self manyFetchOperations:remainingParams completion:completion];
    }];
}

Call it as follows, for the same effect as nesting...

[self manyFetchOperations:@[@"A", @"B", @"C"] completion:^{}];


问:
Show File Download Progress in MB
I'm downloading a mp3 file from the internet and saving it into the internal storage. The progress of the download is shown in a ProgressDialog. The ProgressDialog displays the progress in percent which is fine. In the right it displays the progress as 1/100 .... I'd like it to display the current size of the file downloaded in MB / the total size of the file being downloaded in MB.

Like in the following picture. The grey text is the current text being displayed. I'd like it to be displayed like the text below it in red.

Here's the current code :

```<code>public class DownloadSKHindi extends AsyncTask<String, Integer, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("Downloading");
        progressDialog.setMax(100);
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        int count = 0;
        try {
            url = new URL(skURL[10]);

            connection = url.openConnection();
            connection.connect();

            int lengthOfFile = connection.getContentLength();

            InputStream input = new BufferedInputStream(url.openStream());

            OutputStream output = getActivity().openFileOutput(file.getPath(), Context.MODE_PRIVATE);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;

                publishProgress((int) (total * 100 / lengthOfFile));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressDialog.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        progressDialog.dismiss();
    }
}
</code>```

答:
Assuming total is how many bytes are downloaded, and lengthOfFile is the size in bytes of how large the file is. You can do this:

```<code>progressDialog.setProgressNumberFormat((bytes2String(total)) + "/" + (bytes2String(lengthOfFile)));
</code>```

Then using the function bytes2String ( Credit to coder )

```<code>private static double SPACE_KB = 1024;
private static double SPACE_MB = 1024 * SPACE_KB;
private static double SPACE_GB = 1024 * SPACE_MB;
private static double SPACE_TB = 1024 * SPACE_GB;

public static String bytes2String(long sizeInBytes) {

    NumberFormat nf = new DecimalFormat();
    nf.setMaximumFractionDigits(2);

    try {
        if ( sizeInBytes < SPACE_KB ) {
            return nf.format(sizeInBytes) + " Byte(s)";
        } else if ( sizeInBytes < SPACE_MB ) {
            return nf.format(sizeInBytes/SPACE_KB) + " KB";
        } else if ( sizeInBytes < SPACE_GB ) {
            return nf.format(sizeInBytes/SPACE_MB) + " MB";
        } else if ( sizeInBytes < SPACE_TB ) {
            return nf.format(sizeInBytes/SPACE_GB) + " GB";
        } else {
            return nf.format(sizeInBytes/SPACE_TB) + " TB";
        }
    } catch (Exception e) {
        return sizeInBytes + " Byte(s)";
    }

}
</code>```

Source

Title: Show File Download Progress in MB

Body:
I'm downloading a mp3 file from the internet and saving it into the internal storage. The progress of the download is shown in a ProgressDialog. The ProgressDialog displays the progress in percent which is fine. In the right it displays the progress as 1/100 .... I'd like it to display the current size of the file downloaded in MB / the total size of the file being downloaded in MB.

Like in the following picture. The grey text is the current text being displayed. I'd like it to be displayed like the text below it in red.

Here's the current code :

public class DownloadSKHindi extends AsyncTask<String, Integer, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("Downloading");
        progressDialog.setMax(100);
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        int count = 0;
        try {
            url = new URL(skURL[10]);

            connection = url.openConnection();
            connection.connect();

            int lengthOfFile = connection.getContentLength();

            InputStream input = new BufferedInputStream(url.openStream());

            OutputStream output = getActivity().openFileOutput(file.getPath(), Context.MODE_PRIVATE);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;

                publishProgress((int) (total * 100 / lengthOfFile));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressDialog.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        progressDialog.dismiss();
    }
}

Body:
Assuming total is how many bytes are downloaded, and lengthOfFile is the size in bytes of how large the file is. You can do this:

progressDialog.setProgressNumberFormat((bytes2String(total)) + "/" + (bytes2String(lengthOfFile)));

Then using the function bytes2String ( Credit to coder )

private static double SPACE_KB = 1024;
private static double SPACE_MB = 1024 * SPACE_KB;
private static double SPACE_GB = 1024 * SPACE_MB;
private static double SPACE_TB = 1024 * SPACE_GB;

public static String bytes2String(long sizeInBytes) {

    NumberFormat nf = new DecimalFormat();
    nf.setMaximumFractionDigits(2);

    try {
        if ( sizeInBytes < SPACE_KB ) {
            return nf.format(sizeInBytes) + " Byte(s)";
        } else if ( sizeInBytes < SPACE_MB ) {
            return nf.format(sizeInBytes/SPACE_KB) + " KB";
        } else if ( sizeInBytes < SPACE_GB ) {
            return nf.format(sizeInBytes/SPACE_MB) + " MB";
        } else if ( sizeInBytes < SPACE_TB ) {
            return nf.format(sizeInBytes/SPACE_GB) + " GB";
        } else {
            return nf.format(sizeInBytes/SPACE_TB) + " TB";
        }
    } catch (Exception e) {
        return sizeInBytes + " Byte(s)";
    }

}

Source


问:
How to check if a nested list contain only empty strings
In pyqt I have a qtableview which a user can edit. If the users makes a change to the table, the table will be copied when the user is done. If no changes are made, the table is skipped. The table is filled with empty strings i.e:

```<code>table = [["","",""],["","",""]]
</code>```

I want to check if the table contains only "", and if it does, ignore it. If it doesnt, i.e. contains a "1", some code runs on the list.
Now I have a working code but its not very pythonic and I wonder how I can improve it. My code is as follows:

```<code>tabell1 = [["","",""],["","",""]]
meh = 0
for item in self.tabell1:
    for item1 in item:
        if item1 == "":
            pass
        else:
            meh = 1
if meh == 1:
    do the thing
</code>```

答:
The primary thing I see that could be more pythonic is using the fact that empty strings are considered false, something like this...</p>

```<code>tabell1 = [["","",""],["","",""]]
meh = 0
for sublist in self.tabell1:
    if any(sublist):  # true if any element of sublist is not empty
        meh = 1
        break         # no need to keep checking, since we found something
if meh == 1:
    do the thing
</code>```

Body:
In pyqt I have a qtableview which a user can edit. If the users makes a change to the table, the table will be copied when the user is done. If no changes are made, the table is skipped. The table is filled with empty strings i.e:

table = [["","",""],["","",""]]

I want to check if the table contains only "", and if it does, ignore it. If it doesnt, i.e. contains a "1", some code runs on the list.
Now I have a working code but its not very pythonic and I wonder how I can improve it. My code is as follows:

tabell1 = [["","",""],["","",""]]
meh = 0
for item in self.tabell1:
    for item1 in item:
        if item1 == "":
            pass
        else:
            meh = 1
if meh == 1:
    do the thing

Body:
The primary thing I see that could be more pythonic is using the fact that empty strings are considered false, something like this...

tabell1 = [["","",""],["","",""]]
meh = 0
for sublist in self.tabell1:
    if any(sublist):  # true if any element of sublist is not empty
        meh = 1
        break         # no need to keep checking, since we found something
if meh == 1:
    do the thing


问:
Use File Watcher in IntelliJ to run Makefile
I would like to run a Makefile in IntelliJ whenever a source file changes. Therefore I installed the File Watcher plugin and added a new File Watcher for Go files. In the Watcher Settings I added make as the Program and test for the Arguments.

When I now change a .go file, I get the following error message:

```<code>make test
make: *** No rule to make target `test'.  Stop.

Process finished with exit code 2
</code>```

so I assume that the file watcher works in general but is somehow runs the make command in the wrong directory.

When I run make test in a terminal from the root of my project, everything works as expected and I get:

```<code>Formatting all packages...
Code analysis with go vet...
Execute test with ginkgo...
[1490735873] Cmd Suite - 1/1 specs • SUCCESS! 120.183µs PASS
[1490735873] Test Helpers Suite - 4/4 specs •••• SUCCESS! 125.046µs PASS
[1490735873] Models Suite - 5/5 specs ••••• SUCCESS! 453.456µs PASS
[1490735873] Services Suite - 16/16 specs •••••••••••••••• SUCCESS! 3.035275ms PASS

Ginkgo ran 4 suites in 855.886243ms
Test Suite Passed
</code>```

What am I doing wrong - or am I missing the point of using file watchers in IntelliJ?

答: Solution was that I had to specify the Working Directory in Other Options. When I set this to $ContentRoot$, everything works as expected.

Body:
I would like to run a Makefile in IntelliJ whenever a source file changes. Therefore I installed the File Watcher plugin and added a new File Watcher for Go files. In the Watcher Settings I added make as the Program and test for the Arguments.

When I now change a .go file, I get the following error message:

make test
make: *** No rule to make target `test'.  Stop.

Process finished with exit code 2

so I assume that the file watcher works in general but is somehow runs the make command in the wrong directory.

When I run make test in a terminal from the root of my project, everything works as expected and I get:

Formatting all packages...
Code analysis with go vet...
Execute test with ginkgo...
[1490735873] Cmd Suite - 1/1 specs • SUCCESS! 120.183µs PASS
[1490735873] Test Helpers Suite - 4/4 specs •••• SUCCESS! 125.046µs PASS
[1490735873] Models Suite - 5/5 specs ••••• SUCCESS! 453.456µs PASS
[1490735873] Services Suite - 16/16 specs •••••••••••••••• SUCCESS! 3.035275ms PASS

Ginkgo ran 4 suites in 855.886243ms
Test Suite Passed

What am I doing wrong - or am I missing the point of using file watchers in IntelliJ?


问:
Supervised machine learning with scikit-learn
This is the first time I'm doing supervised machine learning. This is a pretty advanced topic (at least for me) and I find it hard to specify a question, since I'm not sure what is going wrong.

```<code># Create a training list and test list (looks something like this):
train = [('this hostel was nice',2),('i hate this hostel',1)]
test = [('had a wonderful time',2),('terrible experience',1)]

# Loading modules
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import metrics

# Use a BOW representation of the reviews
vectorizer = CountVectorizer(stop_words='english')
train_features = vectorizer.fit_transform([r[0] for r in train])
test_features = vectorizer.fit([r[0] for r in test])

# Fit a naive bayes model to the training data
nb = MultinomialNB()
nb.fit(train_features, [r[1] for r in train])

# Use the classifier to predict classification of test dataset
predictions = nb.predict(test_features)
actual=[r[1] for r in test]
</code>```

Here I get the error:

```<code>float() argument must be a string or a number, not 'CountVectorizer'
</code>```

This confuses me, since the original ratings that I have zipped up in with the reviews are:

```<code>type(ratings_new[0])
int
</code>```

答:
You should change the line

```<code>test_features = vectorizer.fit([r[0] for r in test])
</code>```

to:

```<code>test_features = vectorizer.transform([r[0] for r in test])
</code>```

The reason is that you already used your training data to fit vectorizer, so you don't need to fit it again on your test data. Instead, you need to transform it.

Body:
This is the first time I'm doing supervised machine learning. This is a pretty advanced topic (at least for me) and I find it hard to specify a question, since I'm not sure what is going wrong.

# Create a training list and test list (looks something like this):
train = [('this hostel was nice',2),('i hate this hostel',1)]
test = [('had a wonderful time',2),('terrible experience',1)]

# Loading modules
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import metrics

# Use a BOW representation of the reviews
vectorizer = CountVectorizer(stop_words='english')
train_features = vectorizer.fit_transform([r[0] for r in train])
test_features = vectorizer.fit([r[0] for r in test])

# Fit a naive bayes model to the training data
nb = MultinomialNB()
nb.fit(train_features, [r[1] for r in train])

# Use the classifier to predict classification of test dataset
predictions = nb.predict(test_features)
actual=[r[1] for r in test]

Here I get the error:

float() argument must be a string or a number, not 'CountVectorizer'

This confuses me, since the original ratings that I have zipped up in with the reviews are:

type(ratings_new[0])
int

Body:
You should change the line

test_features = vectorizer.fit([r[0] for r in test])

to:

test_features = vectorizer.transform([r[0] for r in test])

The reason is that you already used your training data to fit vectorizer, so you don't need to fit it again on your test data. Instead, you need to transform it.


问:
NamedList with Deep Pagination
```<code>QueryRequest req=new QueryRequest(solrQuery);
NoOpResponseParser responseParser = new NoOpResponseParser();
responseParser.setWriterType("csv");
searcherServer.setParser(responseParser);
NamedList<Object> resp=searcherServer.request(req);
QueryResponse res = searcherServer.query(solrQuery);
responseString = (String)resp.get("response");
</code>```

I use the above code to get the output in CSV format. The data I am trying to fetch is huge (In billions). So I want to include deep pagination of SOLR and get chunks of CSV output. Is there a way to do? Also, with the current version of SOLR (I cannot upgrade) I have to use the above code to get CSV output.

I tried the below way to fetch the results.

```<code>searcherServer = new HttpSolrServer(url);
SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery(query);
solrQuery.set("fl","field1");
solrQuery.setParam("wt", "csv");
solrQuery.setStart(0);
solrQuery.setRows(1000);
solrQuery.setSort(SolrQuery.SortClause.asc("field2"));
</code>```

In the output from the above code has wt as javabin. So I cannot get the CSV output.

Any suggestions?

答:
The solution I found was:

```<code>SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery(query); //what you want to fetch
QueryResponse res = searcherServer.query(solrQuery);
int numFound = (int)res.getResults().getNumFound();
int rowsToBeFetched = (numFound > 1000 ? (int)(numFound/6) : numFound);
for(int i=0; i< numFound; i=i+rowsToBeFetched ){
 solrQuery.set("fl","fieldToBeFetched");
 solrQuery.setParam("wt", "csv");
 solrQuery.setStart(i);
 solrQuery.setRows(rowsToBeFetched);
 QueryRequest req=new QueryRequest(solrQuery);
 NoOpResponseParser responseParser = new NoOpResponseParser();
 responseParser.setWriterType("csv");
 searcherServer.setParser(responseParser);
 NamedList<Object> resp=searcherServer.request(req);
 responseString = (String)resp.get("response"); //This is in CSV format
}
</code>```

Pros:

Since I don't get the result at once, it was faster.

The output was csv.

Hitting solr multiple items isn't costly.

Cons:

The result is not unique, meaning there can be repeated data based on what you are fetching.

To get unique results, you can use facets.

Thanks!

Title: NamedList with Deep Pagination

Body:
QueryRequest req=new QueryRequest(solrQuery);
NoOpResponseParser responseParser = new NoOpResponseParser();
responseParser.setWriterType("csv");
searcherServer.setParser(responseParser);
NamedList<Object> resp=searcherServer.request(req);
QueryResponse res = searcherServer.query(solrQuery);
responseString = (String)resp.get("response");

I use the above code to get the output in CSV format. The data I am trying to fetch is huge (In billions). So I want to include deep pagination of SOLR and get chunks of CSV output. Is there a way to do? Also, with the current version of SOLR (I cannot upgrade) I have to use the above code to get CSV output.

I tried the below way to fetch the results.

searcherServer = new HttpSolrServer(url);
SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery(query);
solrQuery.set("fl","field1");
solrQuery.setParam("wt", "csv");
solrQuery.setStart(0);
solrQuery.setRows(1000);
solrQuery.setSort(SolrQuery.SortClause.asc("field2"));

In the output from the above code has wt as javabin. So I cannot get the CSV output.

Any suggestions?

Body:
The solution I found was:

SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery(query); //what you want to fetch
QueryResponse res = searcherServer.query(solrQuery);
int numFound = (int)res.getResults().getNumFound();
int rowsToBeFetched = (numFound > 1000 ? (int)(numFound/6) : numFound);
for(int i=0; i< numFound; i=i+rowsToBeFetched ){
 solrQuery.set("fl","fieldToBeFetched");
 solrQuery.setParam("wt", "csv");
 solrQuery.setStart(i);
 solrQuery.setRows(rowsToBeFetched);
 QueryRequest req=new QueryRequest(solrQuery);
 NoOpResponseParser responseParser = new NoOpResponseParser();
 responseParser.setWriterType("csv");
 searcherServer.setParser(responseParser);
 NamedList<Object> resp=searcherServer.request(req);
 responseString = (String)resp.get("response"); //This is in CSV format
}

Pros:

Since I don't get the result at once, it was faster.

The output was csv.

Hitting solr multiple items isn't costly.

Cons:

The result is not unique, meaning there can be repeated data based on what you are fetching.

To get unique results, you can use facets.

Thanks!


问:
Proper way to return a new string in Rust
I just spent a week reading the Rust Book, and now I'm working on my first program, which returns the filepath to the system wallpaper:

```<code>pub fn get_wallpaper() -> &str {
    let output = Command::new("gsettings");
    // irrelevant code
    if let Ok(message) = String::from_utf8(output.stdout) {
        return message;
    } else {
        return "";
    }
}
</code>```

I'm getting the error expected lifetime parameter on &str and I know Rust wants an input &str which will be returned as the output because any &str I create inside the function will be cleaned up immediately after the function ends.

I know I can sidestep the issue by returning a String instead of a &str, and many answers to similar questions have said as much. But I can also seemingly do this:

```<code>fn main() {
    println!("message: {}", hello_string(""));
}

fn hello_string(x: &str) -> &str {
    return "hello world";
}
</code>```

to get a &str out of my function. Can someone explain to me why this is bad and why I should never do it? Or maybe it's not bad and okay in certain situations?

答:
You cannot return a &str if you've allocated the String in the function. There's further discussion about why, as well as the fact that it's not limited to strings. That makes your choice much easier: return the String.

Strings are heap-allocated and built to be mutable.

Strings are heap-allocated because they have an unknown length. Since that allocation is solely owned by the String, that's what grants the ability to mutate the string.

My function just returns a filepath for reference purposes, and I'd rather leave it up to the caller to decide if they need a heap-stored mutable string.

This isn't possible. Your function has performed an allocation. If you don't return the allocation to the caller, then the value must be deallocated to prevent memory leaks. If it was returned after deallocation, that would be an invalid reference, leading to memory safety violations.

But I can also seemingly do this:

```<code>fn hello_string(x: &str) -> &str {
    return "hello world";
}
</code>```

to get a &str out of my function. Can someone explain to me why this
  is bad and why I should never do it? Or maybe it's not bad and okay in
  certain situations?

It's not bad, it just doesn't really allow you to do what you want in your original case. That "hello world" is a &'static str, a string slice that's been stored inside the code of the program itself. It has a fixed length and is known to live longer than main.

The signature fn hello_string(x: &str) -> &str can be expanded to fn hello_string<'a>(x: &'a str) -> &'a str. This indicates that the resulting string slice must have the same lifetime as the input string. A static string will outlive any lifetime, so that's valid to substitute.

This would be useful for a function where the result is based on the input string only:

```<code>fn long_string(x: &str) -> &str {
    if x.len() > 10 {
        "too long"
    } else {
        x
    }
}
</code>```

However, in your case, the function owns the String. If you attempted to return a reference to a String, completely unrelated to the input string:

```<code>fn hello_string(x: &str) -> &str {
    &String::from("hello world")
}
</code>```

You'll run into the common error message "borrowed value does not live long enough". That's because the borrowed value only lives until the end of method, not as long as the input string slice. You can't "trick" the compiler (or if you can, that's a major bug).

Body:
I just spent a week reading the Rust Book, and now I'm working on my first program, which returns the filepath to the system wallpaper:

pub fn get_wallpaper() -> &str {
    let output = Command::new("gsettings");
    // irrelevant code
    if let Ok(message) = String::from_utf8(output.stdout) {
        return message;
    } else {
        return "";
    }
}

I'm getting the error expected lifetime parameter on &str and I know Rust wants an input &str which will be returned as the output because any &str I create inside the function will be cleaned up immediately after the function ends.

I know I can sidestep the issue by returning a String instead of a &str, and many answers to similar questions have said as much. But I can also seemingly do this:

fn main() {
    println!("message: {}", hello_string(""));
}

fn hello_string(x: &str) -> &str {
    return "hello world";
}

to get a &str out of my function. Can someone explain to me why this is bad and why I should never do it? Or maybe it's not bad and okay in certain situations?

Body:
You cannot return a &str if you've allocated the String in the function. There's further discussion about why, as well as the fact that it's not limited to strings. That makes your choice much easier: return the String.

Strings are heap-allocated and built to be mutable.

Strings are heap-allocated because they have an unknown length. Since that allocation is solely owned by the String, that's what grants the ability to mutate the string.

My function just returns a filepath for reference purposes, and I'd rather leave it up to the caller to decide if they need a heap-stored mutable string.

This isn't possible. Your function has performed an allocation. If you don't return the allocation to the caller, then the value must be deallocated to prevent memory leaks. If it was returned after deallocation, that would be an invalid reference, leading to memory safety violations.

But I can also seemingly do this:

fn hello_string(x: &str) -> &str {
    return "hello world";
}

to get a &str out of my function. Can someone explain to me why this
  is bad and why I should never do it? Or maybe it's not bad and okay in
  certain situations?

It's not bad, it just doesn't really allow you to do what you want in your original case. That "hello world" is a &'static str, a string slice that's been stored inside the code of the program itself. It has a fixed length and is known to live longer than main.

The signature fn hello_string(x: &str) -> &str can be expanded to fn hello_string<'a>(x: &'a str) -> &'a str. This indicates that the resulting string slice must have the same lifetime as the input string. A static string will outlive any lifetime, so that's valid to substitute.

This would be useful for a function where the result is based on the input string only:

fn long_string(x: &str) -> &str {
    if x.len() > 10 {
        "too long"
    } else {
        x
    }
}

However, in your case, the function owns the String. If you attempted to return a reference to a String, completely unrelated to the input string:

fn hello_string(x: &str) -> &str {
    &String::from("hello world")
}

You'll run into the common error message "borrowed value does not live long enough". That's because the borrowed value only lives until the end of method, not as long as the input string slice. You can't "trick" the compiler (or if you can, that's a major bug).

ContentLicense: CC BY-SA 4.0


问:
Counting keys in dictionary of dictionary in python
I have dict sample:

dictsample which have this structure dictsample.update({key: dif_k}), and dif_k have this structure dif_k.update({k:v})

dictsample:

```<code>{Object1 : { size : 14, cell: G, capacity : 35}, Object2 : { size : 14, load : 2}, Object3 : { size : 12, cell : F, load : 3, throughput : 55}, ...}
</code>```

I need output like this:

```<code>{Object1 : 3, Object2 : 2, Object3 : 4, ...}
</code>```

Code I have tried:

```<code>ct = {}
for key, dif_k in dictsample.iteritems():
    for k, v in dif_k.iteritems():
        dictcounter = k.count(k)
        ct.update({key:dictcounter})
</code>```

And all I got is:
    {Object1 : 1, Object2 : 1, Object3 : 1, ...}

答:
Can't you do it a bit simpler. Wouldn't something like this do the trick?</p>

```<code>ct = {}
for key in dictsample:
    ct[key] = len(dictsample[key])
</code>```

Body:
I have dict sample:

dictsample which have this structure dictsample.update({key: dif_k}), and dif_k have this structure dif_k.update({k:v})

dictsample:

{Object1 : { size : 14, cell: G, capacity : 35}, Object2 : { size : 14, load : 2}, Object3 : { size : 12, cell : F, load : 3, throughput : 55}, ...}

I need output like this:

{Object1 : 3, Object2 : 2, Object3 : 4, ...}

Code I have tried:

ct = {}
for key, dif_k in dictsample.iteritems():
    for k, v in dif_k.iteritems():
        dictcounter = k.count(k)
        ct.update({key:dictcounter})

And all I got is:
    {Object1 : 1, Object2 : 1, Object3 : 1, ...}

Body:
Can't you do it a bit simpler. Wouldn't something like this do the trick?

ct = {}
for key in dictsample:
    ct[key] = len(dictsample[key])


问:
How to use addExtraLib in Monaco with an external type definition
I can see how to use addExtraLib in Monaco to add an ambient declaration file. What's not clear is how to use this function with an external declaration file so that Typescript code in the editor can do a:

import * as External from "external"

External.foo();
```
<p>On the Monaco set-up side, this doesn't seem to work:</p>
<pre class="lang-js prettyprint-override"><code> // compiler options
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
    target: monaco.languages.typescript.ScriptTarget.ES2016,
    allowNonTsExtensions: true,
    moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
    module: monaco.languages.typescript.ModuleKind.CommonJS,
    noEmit: true,
    noLib: true,
    typeRoots: ["node_modules/@types"]
});

// extra libraries
monaco.languages.typescript.typescriptDefaults.addExtraLib(
    'export declare function foo():string;', 'node_modules/@types/external/index.d.ts');

monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
    noSemanticValidation: false,
    noSyntaxValidation: false
</code>```

答:
After playing around a little I found a solution. Basically, the file has to be loaded using createModel with an explicit file URL. If you do this then the relative file path for node_module/@types works. Here's my working solution that can be used in the playground:

// compiler options
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
    target: monaco.languages.typescript.ScriptTarget.ES2016,
    allowNonTsExtensions: true,
    moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
    module: monaco.languages.typescript.ModuleKind.CommonJS,
    noEmit: true,
    typeRoots: ["node_modules/@types"]
});

// extra libraries
monaco.languages.typescript.typescriptDefaults.addExtraLib(
    `export declare function next() : string`,
    'node_modules/@types/external/index.d.ts');

monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
    noSemanticValidation: false,
    noSyntaxValidation: false
})

var jsCode = `import * as x from "external"
    const tt : string = x.dnext();`;

monaco.editor.create(document.getElementById("container"), {
    model: monaco.editor.createModel(jsCode,"typescript",new monaco.Uri("file:///main.tsx")),
});
```

Body:
I can see how to use addExtraLib in Monaco to add an ambient declaration file. What's not clear is how to use this function with an external declaration file so that Typescript code in the editor can do a:

import * as External from "external"

External.foo();

On the Monaco set-up side, this doesn't seem to work:

 // compiler options
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
    target: monaco.languages.typescript.ScriptTarget.ES2016,
    allowNonTsExtensions: true,
    moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
    module: monaco.languages.typescript.ModuleKind.CommonJS,
    noEmit: true,
    noLib: true,
    typeRoots: ["node_modules/@types"]
});

// extra libraries
monaco.languages.typescript.typescriptDefaults.addExtraLib(
    'export declare function foo():string;', 'node_modules/@types/external/index.d.ts');

monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
    noSemanticValidation: false,
    noSyntaxValidation: false


答:
Try something like this dict comprehension instead:</p>

```<code>{k: len(v) for k,v in dictsample.iteritems()}
</code>```

Title: Counting keys in dictionary of dictionary in python

Body:
Try something like this dict comprehension instead:

{k: len(v) for k,v in dictsample.iteritems()}


问:
Making a few changes to network script
I work for a company and they want us to create a script to reset all network settings in cases like with the Windows 10 update that "broke" the network where you had to run a netsh winsock reset. We at the shop created a script and it works wonderful.

```<code>    @echo off
goto check_Permissions

:check_Permissions
    echo --------------------------------------------------------------------------------
    echo This script was originally created by Adam, but modified and edited by Steven.
    echo --------------------------------------------------------------------------------

    echo Administrative permissions required. Detecting permissions...

    net session >nul 2>&1
    if %errorLevel% == 0 (
        echo Success: Good job you did it right! Press any key to continue....
    ) else (
        echo Failure: !!!!!!!!!!!DO NOT CONTINUE!!!!!!!!!!!! You are not using Administrative privlages. !!!!!!!!!!!DO NOT CONTINUE!!!!!!!!!!!!
    )

    pause >nul

echo Starting Netsh Dump...
start /wait netsh dump

echo Starting NBTSTAT...
start /wait nbtstat -R

echo Resetting Interface IP.
start /wait netsh int ip reset reset.log

echo Resetting Winsock...
start /wait netsh winsock reset

echo Resetting IPV4 settings...
start /wait netsh int ipv4 reset

echo Resetting IPV6 settings...
start /wait netsh int ipv6 reset

echo Resetting 6to4...
start /wait netsh int 6to4 reset all

echo Resetting HTTP Tunnel...
start /wait netsh int httpstunnel reset all

echo Resetting Port Proxy...
start /wait net int portproxy reset all

echo Releasing IP...
start /wait ipconfig /release

echo Renewing IP...
start /wait ipconfig /renew

echo Flushing DNS...
start /wait ipconfig /flushdns

echo Registering DNS...
start /wait ipconfig /registerdns

pause
</code>```

Goes through and does everything we need it to do. My boss came by the other day and asked us; 'So what do you do if they have a static IP or even Proxy on their computer and you just erased all of that without obtaining that information. As well, where are the logs of what you did? Every time you should run this script there should be logs on what the script did. Not just on the console.'

Good point... So, I've been tweaking with it for a while and I'm unable to make the script output into a log file, I've tried >> Logs.txt, I've tried > Logs.txt, I've tried everything that I can find and nothing. We also rewrote the script to make it a little less clustery... Which is posted below.

```<code> @echo off
goto check_Permissions

:check_Permissions
    echo --------------------------------------------------------------------------------
    echo This script was originally created by Adam, but modified and edited by Steven.
    echo --------------------------------------------------------------------------------

    echo Administrative permissions required. Detecting permissions...

    net session >nul 2>&1
    if %errorLevel% == 0 (
        echo Success: Good job you did it right! Press any key to continue....
    ) else (
        echo Failure: !!!!!!!!!!!DO NOT CONTINUE!!!!!!!!!!!! You are not using Administrative privlages. !!!!!!!!!!!DO NOT CONTINUE!!!!!!!!!!!!
    )

    pause >nul

echo Starting Networking Reset...
netsh dump && nbtstat -R && netsh int ip reset reset.log && netsh winsock reset && nbtstat -R && netsh int ip reset && netsh int 6to4 reset all && netsh int httpstunnel reset all && net int portproxy reset all && ipconfig /flushdns

pause
</code>```

Basically I just want it to output a file saying what all was done and if at all possible a scan that detects if they have a static IP//proxies set up in the network BEFORE running this script...

Cheers,
Mittens.

答:
To keep it a clickable process I'd string 2 bat files together. 2 bats like below, and I would click BatThatTriggersYourScript.bat to make it run

BatThatTriggersYourScript.bat

```<code>CheckPermissions.bat > OurLog.log
</code>```

CheckCheckPermissions.bat

```<code>All that code you already have
</code>```

To do it manually in cmd line, then I would take away the stringing and write it myself every time...yurk!

```<code>CheckCheckPermissions.bat > MyLog.log
</code>```

As a side note, > writes to a new file, while >> appends to a file.

Title: Making a few changes to network script

Body:
I work for a company and they want us to create a script to reset all network settings in cases like with the Windows 10 update that "broke" the network where you had to run a netsh winsock reset. We at the shop created a script and it works wonderful.

    @echo off
goto check_Permissions

:check_Permissions
    echo --------------------------------------------------------------------------------
    echo This script was originally created by Adam, but modified and edited by Steven.
    echo --------------------------------------------------------------------------------

    echo Administrative permissions required. Detecting permissions...

    net session >nul 2>&1
    if %errorLevel% == 0 (
        echo Success: Good job you did it right! Press any key to continue....
    ) else (
        echo Failure: !!!!!!!!!!!DO NOT CONTINUE!!!!!!!!!!!! You are not using Administrative privlages. !!!!!!!!!!!DO NOT CONTINUE!!!!!!!!!!!!
    )

    pause >nul

echo Starting Netsh Dump...
start /wait netsh dump

echo Starting NBTSTAT...
start /wait nbtstat -R

echo Resetting Interface IP.
start /wait netsh int ip reset reset.log

echo Resetting Winsock...
start /wait netsh winsock reset

echo Resetting IPV4 settings...
start /wait netsh int ipv4 reset

echo Resetting IPV6 settings...
start /wait netsh int ipv6 reset

echo Resetting 6to4...
start /wait netsh int 6to4 reset all

echo Resetting HTTP Tunnel...
start /wait netsh int httpstunnel reset all

echo Resetting Port Proxy...
start /wait net int portproxy reset all

echo Releasing IP...
start /wait ipconfig /release

echo Renewing IP...
start /wait ipconfig /renew

echo Flushing DNS...
start /wait ipconfig /flushdns

echo Registering DNS...
start /wait ipconfig /registerdns

pause

Goes through and does everything we need it to do. My boss came by the other day and asked us; 'So what do you do if they have a static IP or even Proxy on their computer and you just erased all of that without obtaining that information. As well, where are the logs of what you did? Every time you should run this script there should be logs on what the script did. Not just on the console.'

Good point... So, I've been tweaking with it for a while and I'm unable to make the script output into a log file, I've tried >> Logs.txt, I've tried > Logs.txt, I've tried everything that I can find and nothing. We also rewrote the script to make it a little less clustery... Which is posted below.

 @echo off
goto check_Permissions

:check_Permissions
    echo --------------------------------------------------------------------------------
    echo This script was originally created by Adam, but modified and edited by Steven.
    echo --------------------------------------------------------------------------------

    echo Administrative permissions required. Detecting permissions...

    net session >nul 2>&1
    if %errorLevel% == 0 (
        echo Success: Good job you did it right! Press any key to continue....
    ) else (
        echo Failure: !!!!!!!!!!!DO NOT CONTINUE!!!!!!!!!!!! You are not using Administrative privlages. !!!!!!!!!!!DO NOT CONTINUE!!!!!!!!!!!!
    )

    pause >nul

echo Starting Networking Reset...
netsh dump && nbtstat -R && netsh int ip reset reset.log && netsh winsock reset && nbtstat -R && netsh int ip reset && netsh int 6to4 reset all && netsh int httpstunnel reset all && net int portproxy reset all && ipconfig /flushdns

pause

Basically I just want it to output a file saying what all was done and if at all possible a scan that detects if they have a static IP//proxies set up in the network BEFORE running this script...

Cheers,
Mittens.

Body:
To keep it a clickable process I'd string 2 bat files together. 2 bats like below, and I would click BatThatTriggersYourScript.bat to make it run

BatThatTriggersYourScript.bat

CheckPermissions.bat > OurLog.log

CheckCheckPermissions.bat

All that code you already have

To do it manually in cmd line, then I would take away the stringing and write it myself every time...yurk!

CheckCheckPermissions.bat > MyLog.log

As a side note, > writes to a new file, while >> appends to a file.


问:
Run-time error only after successful runs - Excel VBA
I have an Excel VBA macro that works successfully the first two times I run it, but the third time it gives this error:

Run-Time Error '1004'

The sort reference is not valid. Make sure that it's within the data you want to sort, and the first Sort By box isn't the same or blank.

If I restart Excel it works the first two times, then gives the error again. Why would this happen? Here's my code:

```<code>Dim rawData As Object
Dim report As Object
Dim areaCodes As Object
Set rawData = Sheets("RawData")
Set report = Sheets("Report")
Set areaCodes = Sheets("AreaCodes")

report.Cells.Clear
report.Cells.ClearFormats

stateCol = rawData.Cells(1, 1).EntireRow.Find(What:="state", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column

Dim MyRange As Range
Set MyRange = rawData.Cells(1, stateCol)

With rawData
    lastRow = .Cells(Rows.Count, MyRange.Column).End(xlUp).Row
    .Range(.Cells(2, stateCol), .Cells(lastRow, stateCol)).Copy
End With

With report
    .Range("A3").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    .Range(.Cells(3, 1), .Cells(lastRow + 1, 1)).RemoveDuplicates Columns:=1, Header:=xlNo
End With

lastRow = report.Cells(Rows.Count, Range("A1").Column).End(xlUp).Row

report.Range("B3").Select
ActiveCell.FormulaR1C1 = "=COUNTIF(rawData!C[" & stateCol - 2 & "],report!RC[-1])"
Range("B3").AutoFill Destination:=Range("B3:B" & lastRow)
Range("B" & lastRow + 1).Select
ActiveCell.FormulaR1C1 = "=SUM(R[-" & lastRow - 2 & "]C:R[-1]C)"

Range("C3").Select
ActiveCell.FormulaR1C1 = "=RC[-1]/R" & lastRow + 1 & "C[-1]"
Range("C3").AutoFill Destination:=Range("C3:C" & lastRow)
Range("C" & lastRow + 1).Select
ActiveCell.FormulaR1C1 = "=SUM(R[-" & lastRow - 2 & "]C:R[-1]C)"
Range("C:C").NumberFormat = "0.0%"

Range("A2:A" & lastRow + 1).Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove

report.Range("A2").Value = "State"
report.Range("A2").Font.Bold = True
report.Range("A:A").HorizontalAlignment = xlCenter

report.Range("A3").FormulaR1C1 = "=INDEX(areaCodes!R2C5:R52C5,MATCH(report!RC[1],AreaCodes!R2C6:R52C6,0))"
Range("A3").Select
ActiveCell.AutoFill Destination:=Range("A3:A" & lastRow)

With report
    newLastRow = .Cells(Rows.Count, Range("C1").Column).End(xlUp).Row - 1
    .Range(.Cells(3, 3), .Cells(newLastRow, 3)).Copy
    .Range("C3").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
End With

With report
    .Sort.SortFields.Add Key:=Range("C2"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    newLastRow = .Cells(Rows.Count, Range("C1").Column).End(xlUp).Row - 1
    With .Sort
        .SetRange Range("A2:D" & newLastRow)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End With
</code>```

答:
you should qualify the range in your sort instruction, this will produce an error if the sheet report is not activated</p>

```<code>With report
    .Sort.SortFields.Add Key:=.Range("C2"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    newLastRow = .Cells(Rows.Count, .Range("C1").Column).End(xlUp).Row - 1
    With .Sort
        .SetRange report.Range("A2:D" & newLastRow)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End With
</code>```

Body:
I have an Excel VBA macro that works successfully the first two times I run it, but the third time it gives this error:

Run-Time Error '1004'

The sort reference is not valid. Make sure that it's within the data you want to sort, and the first Sort By box isn't the same or blank.

If I restart Excel it works the first two times, then gives the error again. Why would this happen? Here's my code:

Dim rawData As Object
Dim report As Object
Dim areaCodes As Object
Set rawData = Sheets("RawData")
Set report = Sheets("Report")
Set areaCodes = Sheets("AreaCodes")

report.Cells.Clear
report.Cells.ClearFormats

stateCol = rawData.Cells(1, 1).EntireRow.Find(What:="state", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column

Dim MyRange As Range
Set MyRange = rawData.Cells(1, stateCol)

With rawData
    lastRow = .Cells(Rows.Count, MyRange.Column).End(xlUp).Row
    .Range(.Cells(2, stateCol), .Cells(lastRow, stateCol)).Copy
End With

With report
    .Range("A3").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    .Range(.Cells(3, 1), .Cells(lastRow + 1, 1)).RemoveDuplicates Columns:=1, Header:=xlNo
End With

lastRow = report.Cells(Rows.Count, Range("A1").Column).End(xlUp).Row

report.Range("B3").Select
ActiveCell.FormulaR1C1 = "=COUNTIF(rawData!C[" & stateCol - 2 & "],report!RC[-1])"
Range("B3").AutoFill Destination:=Range("B3:B" & lastRow)
Range("B" & lastRow + 1).Select
ActiveCell.FormulaR1C1 = "=SUM(R[-" & lastRow - 2 & "]C:R[-1]C)"

Range("C3").Select
ActiveCell.FormulaR1C1 = "=RC[-1]/R" & lastRow + 1 & "C[-1]"
Range("C3").AutoFill Destination:=Range("C3:C" & lastRow)
Range("C" & lastRow + 1).Select
ActiveCell.FormulaR1C1 = "=SUM(R[-" & lastRow - 2 & "]C:R[-1]C)"
Range("C:C").NumberFormat = "0.0%"

Range("A2:A" & lastRow + 1).Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove

report.Range("A2").Value = "State"
report.Range("A2").Font.Bold = True
report.Range("A:A").HorizontalAlignment = xlCenter

report.Range("A3").FormulaR1C1 = "=INDEX(areaCodes!R2C5:R52C5,MATCH(report!RC[1],AreaCodes!R2C6:R52C6,0))"
Range("A3").Select
ActiveCell.AutoFill Destination:=Range("A3:A" & lastRow)

With report
    newLastRow = .Cells(Rows.Count, Range("C1").Column).End(xlUp).Row - 1
    .Range(.Cells(3, 3), .Cells(newLastRow, 3)).Copy
    .Range("C3").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
End With

With report
    .Sort.SortFields.Add Key:=Range("C2"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    newLastRow = .Cells(Rows.Count, Range("C1").Column).End(xlUp).Row - 1
    With .Sort
        .SetRange Range("A2:D" & newLastRow)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End With

Body:
you should qualify the range in your sort instruction, this will produce an error if the sheet report is not activated

With report
    .Sort.SortFields.Add Key:=.Range("C2"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    newLastRow = .Cells(Rows.Count, .Range("C1").Column).End(xlUp).Row - 1
    With .Sort
        .SetRange report.Range("A2:D" & newLastRow)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End With


问:
Python - Using list of strings as class data member. When strings contain variables, variables don't update
Is there a way to change variables within lists within classes after the class instance has been initialized?  (Sorry, sounds more complicated than it is!)

I'm writing a game and storing all of my display text as array elements in instances of a "Text" class. I wrote the following example program to test what I'm trying to do:

```<code>#****************************************#
#INITIALIZE CLASS (to hold text component)
#****************************************#
class Text:
        def __init__(self, array, maxIndex):

            #list of text
            self.list = array

            #number of items in list
            self.max = maxIndex

#set global variable to 7
globalv = 7

#****************************************#
#INITIALIZE VARIABLE-ENHANCED TEXT
#necessary because variables inside class
#data member arrays seem to have a local
#scope, and can't be changed after they
#are initialized
#****************************************#
varLine = Text(["This line contains globalv, which holds: {}".format(globalv)], 0)

print varLine.list[varLine.max]
#prints 7

#CHANGE VALUE OF globalv:
print "Directly accessing globalv: {}".format(globalv)
#prints 7
print "\nUpdate value of globalv to 9"
globalv = 9
print "Directly accessing globalv: {}".format(globalv)
#prints 9

#Try to change and re-print variable
#doesn't work, despite the fact that "global" has changed outside of the class
print "\nfirst try:"

#call print function on globalv directly:
    print "Directly accessing globalv: {}".format(globalv)
    #prints 9

    #print it from the class:
    print "Printing from class:"
    print varLine.list[varLine.max])
    #prints 7

#Change variable by re-initializing class
print "\nsecond try:"
varLine = Text(["This line contains globalv, which holds: {}".format(globalv)], 0)

    #call print function on globalv directly:
    print "Directly accessing globalv: {}".format(globalv)
    #prints 9

    #print it from the class:
    print "Printing from class:"
    print varLine.list[varLine.max])
    #prints 9
</code>```

答:
When you create that string you are concatinating the current value of globalv into a string. Changing globalv after that string been created has no effect on the value of the string. You can make setter and print methods to accomplish this:

```<code>class Text:
    def __init__(self, strList, valueList, maxIndex):

        #list of text/values
        self.strList = strList
        self.valueList = valueList

        #number of items in list
        self.max = maxIndex

    def printStrAtIndex(self, idx):
        print(self.strList[idx] + str(self.valueList[idx]))

    def setValAtIndex(self, val, idx):
        self.valueList[idx] = val
        return self

    # add new str value pair to the the class
    def addStrAndValue(self, newStr, newValue):
        self.strList.append(newStr)
        self.valueList.append(newValue)
        self.max = len(self.valueList)-1
</code>```

Then just call it like this:

```<code>varLine = Text(["This line is tied to the value: "], [7], 0)
varLine.printStrAtIndex(0)
varLine.setValAtIndex(9,0)
varLine.printStrAtIndex(0)
</code>```

Body:
Is there a way to change variables within lists within classes after the class instance has been initialized?  (Sorry, sounds more complicated than it is!)

I'm writing a game and storing all of my display text as array elements in instances of a "Text" class. I wrote the following example program to test what I'm trying to do:

#****************************************#
#INITIALIZE CLASS (to hold text component)
#****************************************#
class Text:
        def __init__(self, array, maxIndex):

            #list of text
            self.list = array

            #number of items in list
            self.max = maxIndex

#set global variable to 7
globalv = 7

#****************************************#
#INITIALIZE VARIABLE-ENHANCED TEXT
#necessary because variables inside class
#data member arrays seem to have a local
#scope, and can't be changed after they
#are initialized
#****************************************#
varLine = Text(["This line contains globalv, which holds: {}".format(globalv)], 0)

print varLine.list[varLine.max]
#prints 7

#CHANGE VALUE OF globalv:
print "Directly accessing globalv: {}".format(globalv)
#prints 7
print "\nUpdate value of globalv to 9"
globalv = 9
print "Directly accessing globalv: {}".format(globalv)
#prints 9

#Try to change and re-print variable
#doesn't work, despite the fact that "global" has changed outside of the class
print "\nfirst try:"

#call print function on globalv directly:
    print "Directly accessing globalv: {}".format(globalv)
    #prints 9

    #print it from the class:
    print "Printing from class:"
    print varLine.list[varLine.max])
    #prints 7

#Change variable by re-initializing class
print "\nsecond try:"
varLine = Text(["This line contains globalv, which holds: {}".format(globalv)], 0)

    #call print function on globalv directly:
    print "Directly accessing globalv: {}".format(globalv)
    #prints 9

    #print it from the class:
    print "Printing from class:"
    print varLine.list[varLine.max])
    #prints 9

Body:
When you create that string you are concatinating the current value of globalv into a string. Changing globalv after that string been created has no effect on the value of the string. You can make setter and print methods to accomplish this:

class Text:
    def __init__(self, strList, valueList, maxIndex):

        #list of text/values
        self.strList = strList
        self.valueList = valueList

        #number of items in list
        self.max = maxIndex

    def printStrAtIndex(self, idx):
        print(self.strList[idx] + str(self.valueList[idx]))

    def setValAtIndex(self, val, idx):
        self.valueList[idx] = val
        return self

    # add new str value pair to the the class
    def addStrAndValue(self, newStr, newValue):
        self.strList.append(newStr)
        self.valueList.append(newValue)
        self.max = len(self.valueList)-1

Then just call it like this:

varLine = Text(["This line is tied to the value: "], [7], 0)
varLine.printStrAtIndex(0)
varLine.setValAtIndex(9,0)
varLine.printStrAtIndex(0)


问:
open source blog like wordpress
I need open source blog, something like Wordpress. I have a limit, whichever is the only solution that runs on IIS and uses SQL Server Express. Any solutions for this problem??</p>

答:
Check out the Microsoft Web Platform. In among the dev tools, there's a bunch of free web applications, including a variety of blogs (notably blogengine.net) and full-fledged CMSes like DotNetNuke.

Update: And as a nod to @birryree's comment, note that the Web Platform includes Wordpress! :)

Title: open source blog like wordpress


问:
AWS Lambda loading libraries each time?
I am looking at AWS Lambda to create a Python function that would process data.
I need to load a heavy model to run my script (trained word2vec model), it takes about 5 min to do it on my computer for example. But once it's loaded, the execution of the function is very fast.
If I use AWS Lambda, will this model load only once or will it load each time I call my function ?

Thanks,

答:
Maybe.

AWS Lambda uses reusable containers. So, for your use case, the Lambda function will execute quickly if it happened in an already initialized container. It'll be slow otherwise. However, there is no way you can predict the behavior.

Relevant documentation:

From here:

The first time a function executes after being created or having its code or resource configuration updated, a new container with the appropriate resources will be created to execute it, and the code for the function will be loaded into the container.

Let’s say your function finishes, and some time passes, then you call it again. Lambda may create a new container all over again, in which case the experience is just as described above. This will be the case for certain if you change your code. However, if you haven’t changed the code and not too much time has gone by, Lambda may reuse the previous container.

Remember, you can’t depend on a container being reused, since it’s Lambda’s prerogative to create a new one instead.

More official documentation here.

Title: AWS Lambda loading libraries each time?


问:
TreeSet ignoring values
I am trying to create a class that is given pairs of strings & told one is 'greater" than the other then keeps a running order of all known strings.

To do this I keep a Map<String, Set<String>> that maps a given String to all the values it's greater than, then I created a TreeSet with a comparator that uses that data to compare two strings.

Here's my class:

```<code>public class StringSorter {

    private Map<String, Set<String>> greaterThan = new HashMap<>();
    private SortedSet<String> order;

    public StringSorter() {
        order = new TreeSet<>((o1, o2) -> {
            if (greaterThan.getOrDefault(o1, Collections.emptySet()).contains(o2))
                return 1;
            else if (greaterThan.getOrDefault(o2, Collections.emptySet()).contains(o1))
                return -1;
            return 0;
        });
    }

    public void addRule(String bigger, String smaller) {

        if (!greaterThan.containsKey(bigger))
            greaterThan.put(bigger, new HashSet<>());
        greaterThan.get(bigger).add(smaller);

        order.add(bigger);
        order.add(smaller);
    }

    public SortedSet<String> getOrder() {
        return order;
    }
}
</code>```

However, for some reason, the TreeSet seems to just ignore many of the values added to it.

Example:

```<code>StringSorter sorter = new StringSorter();
sorter.addRule("one", "two");
sorter.addRule("two", "three");
sorter.addRule("three", "four");
System.out.println(sorter.getOrder());
</code>```

Output:

```<code>[two, one]
</code>```

What happened to the strings three & four?

答:
The problem is that set collections keep unique values.
After debugging your comparator you will see that "three" was evaluated as equal to "one", thus forbidding it to be added to the set.

Consider this modification:

```<code>public StringSorter() {
    order = new TreeSet<>((o1, o2) -> {
        if (greaterThan.getOrDefault(o1, Collections.emptySet()).contains(o2))
            return 1;
        else if (greaterThan.getOrDefault(o2, Collections.emptySet()).contains(o1))
            return -1;
        else if(o1.equals(o2)) return 0;
        else return -1; //or 1, or o1.compareTo(o2)
    });
}
</code>```

Instead of just returning 0 we first check if objects are equal, if not than the comparison itself is irrelevant and result may be arbitrary.

Here is the output when using updated comparator:

```<code>[four, three, two, one]
</code>```

[Edit]

I would consider changing internal representation of rules to custom oriented tree data structure, represented by sparse adjacency matrix.

Title: TreeSet ignoring values

Body:
I am trying to create a class that is given pairs of strings & told one is 'greater" than the other then keeps a running order of all known strings.

To do this I keep a Map<String, Set<String>> that maps a given String to all the values it's greater than, then I created a TreeSet with a comparator that uses that data to compare two strings.

Here's my class:

public class StringSorter {

    private Map<String, Set<String>> greaterThan = new HashMap<>();
    private SortedSet<String> order;

    public StringSorter() {
        order = new TreeSet<>((o1, o2) -> {
            if (greaterThan.getOrDefault(o1, Collections.emptySet()).contains(o2))
                return 1;
            else if (greaterThan.getOrDefault(o2, Collections.emptySet()).contains(o1))
                return -1;
            return 0;
        });
    }

    public void addRule(String bigger, String smaller) {

        if (!greaterThan.containsKey(bigger))
            greaterThan.put(bigger, new HashSet<>());
        greaterThan.get(bigger).add(smaller);

        order.add(bigger);
        order.add(smaller);
    }

    public SortedSet<String> getOrder() {
        return order;
    }
}

However, for some reason, the TreeSet seems to just ignore many of the values added to it.

Example:

StringSorter sorter = new StringSorter();
sorter.addRule("one", "two");
sorter.addRule("two", "three");
sorter.addRule("three", "four");
System.out.println(sorter.getOrder());

Output:

[two, one]

What happened to the strings three & four?

Body:
The problem is that set collections keep unique values.
After debugging your comparator you will see that "three" was evaluated as equal to "one", thus forbidding it to be added to the set.

Consider this modification:

public StringSorter() {
    order = new TreeSet<>((o1, o2) -> {
        if (greaterThan.getOrDefault(o1, Collections.emptySet()).contains(o2))
            return 1;
        else if (greaterThan.getOrDefault(o2, Collections.emptySet()).contains(o1))
            return -1;
        else if(o1.equals(o2)) return 0;
        else return -1; //or 1, or o1.compareTo(o2)
    });
}

Instead of just returning 0 we first check if objects are equal, if not than the comparison itself is irrelevant and result may be arbitrary.

Here is the output when using updated comparator:

[four, three, two, one]

[Edit]

I would consider changing internal representation of rules to custom oriented tree data structure, represented by sparse adjacency matrix.


问:
Outputting JS variable into my PHP file
I'm trying to output a JS variable into my PHP-file. And then let the PHP send the variable value into my database.
But somehow it doesn't work..

Here I have a form that triggers the JS function:   (This file is called index.php)

```<code><form method="post" action="index.php" onsubmit="return phpFunction()" >
      <input type="hidden" name="submitted" value="true">
      <input type="text" id="nameInput" placeholder="your name" maxlength="12" name="name">
      <input type="submit" id="submitted" value="Submit your highscore">
      </form>
</code>```

Here we have the JS function:    ( This file is called main.js)

```<code>function phpFunction () {

var php = duck.highscore ;   // duck.highscore is a number that dynamically changes
window.location.href = "index.php?score=" + php;

};
</code>```

In the end we got the PHP file that sends the value to my localserver:  (This file is inside index.php)

```<code><?php

if (isset($_POST['submitted'])) {

// connect  to the database
include('connect.php');

$name = $_POST['name'] ;
$score = $_GET['score'] ;
$sqlinsert = "INSERT INTO leaderboard (name, score) VALUES ('$name','$score')" ;

if (!mysqli_query($conn, $sqlinsert)) {
    die('error inserting new record') ;
    } // end of my nested if statement

    $newrecord = "record added" ;

}
?>
</code>```

When I press the submit button I get a error message like this:

error 404

答:
Instead of redirecting to index.php through javascript, try to add score value to the form and submit it.

```<code>// HTML Code
<form method="post" action="index.php" onsubmit="return phpFunction()" >
  <input type="hidden" name="submitted" value="true">
  <input type="text" id="nameInput" placeholder="your name" maxlength="12" name="name">
  <input type="submit" id="submitted" value="Submit your highscore">
  // added hidden input for score.
  <input type="hidden" id="score" value="" name="score">
</form>

// javascript code
function phpFunction () {
  var php = duck.highscore ;   // duck.highscore is a number that dynamically changes
  // update the score field value in the HTML form
  document.getElementById('score').value = php;
  return true;
};
</code>```

//PHP code

Replace

```<code>$score = $_GET['score'];
</code>```

with

```<code>$score = $_POST['score'];
</code>```

Title: Outputting JS variable into my PHP file

Body:
I'm trying to output a JS variable into my PHP-file. And then let the PHP send the variable value into my database.
But somehow it doesn't work..

Here I have a form that triggers the JS function:   (This file is called index.php)

<form method="post" action="index.php" onsubmit="return phpFunction()" >
      <input type="hidden" name="submitted" value="true">
      <input type="text" id="nameInput" placeholder="your name" maxlength="12" name="name">
      <input type="submit" id="submitted" value="Submit your highscore">
      </form>

Here we have the JS function:    ( This file is called main.js)

function phpFunction () {

var php = duck.highscore ;   // duck.highscore is a number that dynamically changes
window.location.href = "index.php?score=" + php;

};

In the end we got the PHP file that sends the value to my localserver:  (This file is inside index.php)

<?php

if (isset($_POST['submitted'])) {

// connect  to the database
include('connect.php');

$name = $_POST['name'] ;
$score = $_GET['score'] ;
$sqlinsert = "INSERT INTO leaderboard (name, score) VALUES ('$name','$score')" ;

if (!mysqli_query($conn, $sqlinsert)) {
    die('error inserting new record') ;
    } // end of my nested if statement

    $newrecord = "record added" ;

}
?>

When I press the submit button I get a error message like this:

error 404

Body:
Instead of redirecting to index.php through javascript, try to add score value to the form and submit it.

// HTML Code
<form method="post" action="index.php" onsubmit="return phpFunction()" >
  <input type="hidden" name="submitted" value="true">
  <input type="text" id="nameInput" placeholder="your name" maxlength="12" name="name">
  <input type="submit" id="submitted" value="Submit your highscore">
  // added hidden input for score.
  <input type="hidden" id="score" value="" name="score">
</form>

// javascript code
function phpFunction () {
  var php = duck.highscore ;   // duck.highscore is a number that dynamically changes
  // update the score field value in the HTML form
  document.getElementById('score').value = php;
  return true;
};

//PHP code

Replace

$score = $_GET['score'];

with

$score = $_POST['score'];


问:
Is com.sun.javafx.robot.FXRobot proprietary
I am new to javafx, and I recently came across the FXRobot class. It works fine, but I am concerned about the long term support of the class, because usually when I use a com.sun class, the javac gives this error message:

warning: com.sun.* is an internal proprietary API and may be removed in a future release

Although the FXRobot class does not give me the above error, I just wanted to ask if the FXRobot class is a permanent part of the JDK, and if it is, then why is it not bundled with the javafx package instead of the com.sun.javafx package.

答:
I haven't tried java 9, but I think there is a very good chance that com.sun.javafx.robot.FXRobot would not be usable from Java 9 user code due to the introduction of the Jigsaw module system and the systematic hiding of non-public API which goes along with that.

See: JEP 253: Prepare JavaFX UI Controls & CSS APIs for Modularization, which translates a lot of API which is private in Java 8 to public in Java 9, but which does not include the FXRobot class in the translation.

Also see this mailing list exchange, which mentions removal of the com.sun.javafx.robot package from the Java 9 codebase:

http://openjfx-dev.openjdk.java.narkive.com/ZR9JPyC4/removal-of-com-sun-javafx-robot

So, it would seem not to be a good idea to rely on the FXRobot class.


问:
Using two Keyspan PR-PR03 presentation remotes in same room
If we want to have two Keyspan PR PR03 presentation remotes controlling two different computers in the same room, is there a way to assign a unique ID or frequency to each so one remote doesn't control both computers?</p>

答:
I got this from their tech support (after the event):

Thank you for your recent inquiry. You will need to change the ID on at least one of your remote controls. To do this, please do the following:

Connect your receiver to your USB port.

Press the CONNECT button the receiver. The receiver's light will turn on.

On the remote control, simultaneously press in on the Composite Switch (black 'wheel' on side of remote) AND hold the laser pointer button until the status red light on the remote control blinks slowly. If your USB receiver blinks at the same time, your remote and receiver are paired. Your remote now has a new ID and the receiver is listening to the new ID. Repeat these steps for every remote you have in the same area. You will now be able to use multiple Presentation Remote Pros in the same area without interference.

ADDITIONAL INFO - - - - - - - - - - - Please note that the Remote's ID is lost if your remote's batteries die or if you change a battery.

Thank you for choosing Tripp Lite!

Please send all replies and inquiries to:
TechSupport@TrippLite.com

Tripp Lite
1111 W 35th Street
Chicago, IL  60609

www.TrippLite.com
Phone:  773-869-1233