问:
click the bottom part of an element?
I have a link that I need to click on that is halfway underneath another element.  Something like this:

```<code>______________________
| A  ____________    | <-- on top
|____|B_________|____|
     |__________| < - on bottom (need to click this one)
</code>```

When I try to click on the bottom link, I get

```<code>(B) is not clickable at point (254, 5). Other element would receive the click: (A).
</code>```

Here is an image (I need to click on the PO Box link).  I don't know exactly what to do here.  Thanks!

Here is the HTML in question.  Selenium is sending the click action to the span labelFieldWrapper:

```<code><div class='clr type_address formFieldContainer'>
    <span class="labelFieldWrapper">
        <label class="placeholder" for="address1">
            <span class="labelText">Address 1</span>
        </label>
        <input id="address1" name="address1" type="text" value="" autofillparam="ON" size="20" maxlength="60"/><span class="asterisk">*</span>
    </span>
    <p class="helpLink">
        <a href="javascript: void(0)"
           onclick="window.open('/checkout/canadian_province_support.jsp',
          'pobox',
          'width=450, \
           height=200, \
           directories=no, \
           location=no, \
           menubar=no, \
           resizable=no, \
           scrollbars=1, \
           status=no, \
           toolbar=no');
          return false;">PO Box?</a>  <-- Trying to click on this link
        </p>
    </div><!-- /formFieldContainer -->
</code>```

答:
I would suggest you to look at the problem in a broader way and implement a method to click anywhere on the element. The below is the code snippet. I wrote the below in C# and successfully able to test.
The x and y co-ordinates are assigned with respect to element size which makes it easier to perform the action on the element.

You can implement a method ClickElementAt and call the method like below.

```<code>ClickElementAt(element,Bottom);//Calling the method here

//Implementation
  public void ClickElementAt(Element element, ClickPoint clickPoint)
    {
        int x, y;

        switch (clickPoint)
        {
            case ClickPoint.Center:
                x = element.Size.Width / 2;
                y = element.Size.Height / 2;
                break;
            case ClickPoint.Top:
                x = element.Size.Width / 2;
                y = element.Size.Height / 10;
                break;
            case ClickPoint.Left:
                x = element.Size.Width / 10;
                y = element.Size.Height / 2;
                break;
            case ClickPoint.Right:
                x = element.Size.Width * 90 / 100;
                y = element.Size.Height / 2;
                break;
            case ClickPoint.Bottom:
                x = element.Size.Width / 2;
                y = element.Size.Height * 90 / 100;
                break;
            default:
                throw new ArgumentOutOfRangeException("clickPoint");
        }

        var actions = new Actions(this.driver);
        actions
            .MoveToElement(element, x, y)
            .Click()
            .Perform();
    }
</code>```

Title: click the bottom part of an element?

Body:
I have a link that I need to click on that is halfway underneath another element.  Something like this:

______________________
| A  ____________    | <-- on top
|____|B_________|____|
     |__________| < - on bottom (need to click this one)

When I try to click on the bottom link, I get

(B) is not clickable at point (254, 5). Other element would receive the click: (A).

Here is an image (I need to click on the PO Box link).  I don't know exactly what to do here.  Thanks!

Here is the HTML in question.  Selenium is sending the click action to the span labelFieldWrapper:

            Address 1

        <input id="address1" name="address1" type="text" value="" autofillparam="ON" size="20" maxlength="60"/>*

        PO Box?  <-- Trying to click on this link

Body:
I would suggest you to look at the problem in a broader way and implement a method to click anywhere on the element. The below is the code snippet. I wrote the below in C# and successfully able to test.
The x and y co-ordinates are assigned with respect to element size which makes it easier to perform the action on the element.

You can implement a method ClickElementAt and call the method like below.

ClickElementAt(element,Bottom);//Calling the method here

//Implementation
  public void ClickElementAt(Element element, ClickPoint clickPoint)
    {
        int x, y;

        switch (clickPoint)
        {
            case ClickPoint.Center:
                x = element.Size.Width / 2;
                y = element.Size.Height / 2;
                break;
            case ClickPoint.Top:
                x = element.Size.Width / 2;
                y = element.Size.Height / 10;
                break;
            case ClickPoint.Left:
                x = element.Size.Width / 10;
                y = element.Size.Height / 2;
                break;
            case ClickPoint.Right:
                x = element.Size.Width * 90 / 100;
                y = element.Size.Height / 2;
                break;
            case ClickPoint.Bottom:
                x = element.Size.Width / 2;
                y = element.Size.Height * 90 / 100;
                break;
            default:
                throw new ArgumentOutOfRangeException("clickPoint");
        }

        var actions = new Actions(this.driver);
        actions
            .MoveToElement(element, x, y)
            .Click()
            .Perform();
    }


来源: stackexchange

问:
Angular Js- Is there any way to generate dynamically checkbox which are also preselected?
I have been wandering for two to three hours and I found chunks of relevant questions but my scenario just take a little curve. I have to generate a number of checkboxes which obviously would be generated through ng-repeat. How can I show the preselected values which I am getting from Api. Here is the kind of data I am receiving.

Pre-selected data

```<code>$scope.categoriess = [{"id":1,"name":"Garden Cleaning"},{"id":3,"name":"Home Cleaning"}].
</code>```

and this is the data over which I am using ng-repeat.

ng-repeat data

```<code>$scope.categories = [{"id":1,"name":"Garden Cleaning"},{"id":2,"name":"Gutter Cleaning"},{"id":3,"name":"Home Cleaning"},{"id":4,"name":"Pool Cleaning"}
</code>```

HTML

```<code>  <div ng-repeat="cats in categories">
      <input type="checkbox" ng-model="categoriess.id[cats.id]">
               <label>{{cats.name}}</label>
                  </div>
</code>```

Now how would i tell ng-repeat to check the preselected data, plus if I want to check few more boxes they should also be checked and I want them to store in $scope.categoriess. I have tried a number of solution either with ng-checked or by make a function call in ng-checked I got no expected results.

答:
I saw this but i did not know how it works god it saved my life. see this checklist-model. Its so simple , no need to use ng-checked or something dynamic , preselected and gets updated easily</p>

```<code>[1]: http://jsfiddle.net/iem_usman/v3k6pwrj/1/
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been wandering for two to three hours and I found chunks of relevant questions but my scenario just take a little curve. I have to generate a number of checkboxes which obviously would be generated through ng-repeat. How can I show the preselected values which I am getting from Api. Here is the kind of data I am receiving.

Pre-selected data

$scope.categoriess = [{"id":1,"name":"Garden Cleaning"},{"id":3,"name":"Home Cleaning"}].

and this is the data over which I am using ng-repeat.

ng-repeat data

$scope.categories = [{"id":1,"name":"Garden Cleaning"},{"id":2,"name":"Gutter Cleaning"},{"id":3,"name":"Home Cleaning"},{"id":4,"name":"Pool Cleaning"}

HTML

      <input type="checkbox" ng-model="categoriess.id[cats.id]">
               {{cats.name}}

Now how would i tell ng-repeat to check the preselected data, plus if I want to check few more boxes they should also be checked and I want them to store in $scope.categoriess. I have tried a number of solution either with ng-checked or by make a function call in ng-checked I got no expected results.

Body:
I saw this but i did not know how it works god it saved my life. see this checklist-model. Its so simple , no need to use ng-checked or something dynamic , preselected and gets updated easily

[1]: http://jsfiddle.net/iem_usman/v3k6pwrj/1/


问:
arranging icons in gtk toolbar
I am trying to create a GTK toolbar with a bunch of items. My probelem is that I have not been able to space them out evenly. All icons are bunched together on the left of the bar. How do I get them to spread out? I would like to avoid using additional widgets like hbox, etc for performance reasons. Here's the code I have written:

```<code>GtkWidget* navbar = gtk_toolbar_new();
gtk_toolbar_set_style(GTK_TOOLBAR(navbar), GTK_TOOLBAR_ICONS);
gtk_toolbar_set_icon_size(GTK_TOOLBAR(navbar), GTK_ICON_SIZE_SMALL_TOOLBAR);

GtkToolItem* open = gtk_tool_button_new_from_stock(GTK_STOCK_JUMP_TO);
gtk_toolbar_insert(GTK_TOOLBAR(navbar), open, 0);

GtkToolItem* play = gtk_tool_button_new_from_stock(GTK_STOCK_MEDIA_PLAY);
gtk_toolbar_insert(GTK_TOOLBAR(navbar), play, 1);

GtkToolItem* pause = gtk_tool_button_new_from_stock(GTK_STOCK_MEDIA_PAUSE);
gtk_toolbar_insert(GTK_TOOLBAR(navbar), pause, 2);
</code>```

And here is the arrangement I get:

答:
I do believe that this is by design; toolbars are supposed to be packed tightly, to make them more usable. In my personal opinion, the six buttons in the example image would look way worse if spread out evenly over the full horizontal space.

That said, you can try using gtk_tool_item_set_expand() on your items before adding them to the toolbar.

ContentLicense: CC BY-SA 2.5

Title: arranging icons in gtk toolbar

Body:
I am trying to create a GTK toolbar with a bunch of items. My probelem is that I have not been able to space them out evenly. All icons are bunched together on the left of the bar. How do I get them to spread out? I would like to avoid using additional widgets like hbox, etc for performance reasons. Here's the code I have written:

GtkWidget* navbar = gtk_toolbar_new();
gtk_toolbar_set_style(GTK_TOOLBAR(navbar), GTK_TOOLBAR_ICONS);
gtk_toolbar_set_icon_size(GTK_TOOLBAR(navbar), GTK_ICON_SIZE_SMALL_TOOLBAR);

GtkToolItem* open = gtk_tool_button_new_from_stock(GTK_STOCK_JUMP_TO);
gtk_toolbar_insert(GTK_TOOLBAR(navbar), open, 0);

GtkToolItem* play = gtk_tool_button_new_from_stock(GTK_STOCK_MEDIA_PLAY);
gtk_toolbar_insert(GTK_TOOLBAR(navbar), play, 1);

GtkToolItem* pause = gtk_tool_button_new_from_stock(GTK_STOCK_MEDIA_PAUSE);
gtk_toolbar_insert(GTK_TOOLBAR(navbar), pause, 2);

And here is the arrangement I get:


问:
How do I set a background colour for IWebBrowser2 whilst page is loading?
The title says it all really...

I'm using IWebBrowser2 to display web pages in my application, however, when I call IWebBrowser2::Navigate() a white background is displayed whilst the target page is loading, which conflicts with the colour scheme of my app.

I tried creating a "background.html" and pre-loading that before calling Navigate(), but as soon as I navigate to the new URL, the background changes to white.

答:
This is untested:

Hide the browser window. As I remember calling ShowWindow(SW_HIDE) would not work because the browser control doesn't do anything when its window is hidden. Instead you could MoveWindow() it outside of the client area to effectively hide it while it still thinks it is visible.

Draw your custom background in the parent window of the browser control.

Call IWebBrowser2::Navigate()

Handle the NavigateComplete event where you show the browser window again. It should quickly redraw itself without first showing white background.


问:
TF-IDF Weighting after NLTK pre-processing
I am doing some textual preprocessing prior to machine learning. I have two features (Panda series) - abstract and title - and use the following function to preprocess the data (giving a numpy array, where each row contains the features for one training example):

```<code>def preprocessText(data):
    stemmer = nltk.stem.porter.PorterStemmer()
    preprocessed = []
    for each in data:
        tokens = nltk.word_tokenize(each.lower().translate(xlate))
        filtered = [word for word in tokens if word not in stopwords]
        preprocessed.append([stemmer.stem(item) for item in filtered])
    print(Counter(sum([list(x) for x in preprocessed], [])))
    return np.array(preprocessed)
</code>```

I now need to use TF-IDF to weight the features - how can I do this?

答:
From what I see, you have list of filtered words in preprocessed variable. One way to do TF-IDF transformation is to use scikit-learn, TfidfVectorizer. However, the class tokenizes the space for you i.e. you can provide list of processed documents each contain string. So you have to edit your code to:

```<code>preprocessed.append(' '.join([stemmer.stem(item) for item in filtered]))
</code>```

Then you can transform list of documents as follows

```<code>from sklearn.feature_extraction.text import TfidfVectorizer

tfidf_model = TfidfVectorizer() # specify parameters here
X_tfidf = tfidf_model.fit_transform(preprocessed)
</code>```

The output will be matrix in sparse compressed sparse row (CSR) format where you can transform to numpy array later on.

tfidf_model.vocabulary_ will contain dictionary map of stemming words to id.

Body:
I am doing some textual preprocessing prior to machine learning. I have two features (Panda series) - abstract and title - and use the following function to preprocess the data (giving a numpy array, where each row contains the features for one training example):

def preprocessText(data):
    stemmer = nltk.stem.porter.PorterStemmer()
    preprocessed = []
    for each in data:
        tokens = nltk.word_tokenize(each.lower().translate(xlate))
        filtered = [word for word in tokens if word not in stopwords]
        preprocessed.append([stemmer.stem(item) for item in filtered])
    print(Counter(sum([list(x) for x in preprocessed], [])))
    return np.array(preprocessed)

I now need to use TF-IDF to weight the features - how can I do this?

Body:
From what I see, you have list of filtered words in preprocessed variable. One way to do TF-IDF transformation is to use scikit-learn, TfidfVectorizer. However, the class tokenizes the space for you i.e. you can provide list of processed documents each contain string. So you have to edit your code to:

preprocessed.append(' '.join([stemmer.stem(item) for item in filtered]))

Then you can transform list of documents as follows

from sklearn.feature_extraction.text import TfidfVectorizer

tfidf_model = TfidfVectorizer() # specify parameters here
X_tfidf = tfidf_model.fit_transform(preprocessed)

The output will be matrix in sparse compressed sparse row (CSR) format where you can transform to numpy array later on.

tfidf_model.vocabulary_ will contain dictionary map of stemming words to id.


问:
Unity 5.6 and creating objects with C# classes
I've been trying out Unity, so far I've dedicated a lot of time making up a character class with stats and feats just like in Dungeons and Dragons, so far they all work well, but now it comes to me the desire to create gear for such character.

I've seen you can create objects from the prefab section and then add script snippets to change their behavior or even their appearance, but alas it just feels odd when I'm used to make classes from scratch to alter an already existing class of which I barely have any knowledge on how it works.

Thus, I could just simply go into the script folder and create a new C# script with all the values that will be used in general, for example, all armors have an armor class and weight, thus I could make a general class that has all the properties of an Object called Item then inherits its properties to Armor, Weapons and Consumables, and each of them can be then further specialized into more specific objects, now the real question comes:

Should it be better to create a class that holds specific attributes, for example a class called Iron sword, which inherits from weapons and from items down to gameobject, or should I make only one class called weapon that holds all values and names inside lists or arrays? And then... how do I instantiate my scripts without the need of creating one object in the game that when deleted it also removes the script from the scene?

Sorry for so much info, but I'm just a bit overwhelmed by all the things you can do and can't do with Unity.

答:
Unity is intended to be used with component architecture, not object-oriented design. This means, mostly you will be creating GameObjects in the scene and then attach scripts to them, adding behaviour or data.

Data can also be stored in ScriptableObject instances in the project, or in any other asset like a text file or texture.

Since there is no main function or any specific program start in Unity, you will have to pick a root manager GameObject in your first scene, which has a MonoBehaviour script and one of the Unity callbacks which get triggered at the beginning (e.g. Awake or Start). This script now can work like your main function in a regular app.

If you really want to, you could build your entire game from here with "normal" C# classes. They all start at this once MonoBehaviour, but other than that, you could write everything "top down". For example: Instantiate a Game class, which then loads a text file and instantiates GameObjects, assembles all their components, until the visual representation is complete. However, this way you wouldn't make use of all the features Unity provides.

The Unity way would be to build individual GameObjects from components, which mostly function independently from one another. A human player avatar might consist of PlayerInput, Renderer, WeaponBehaviour, HealthComponent, etc.

Nobody can tell you what design is best for your game, but both directions are possible. For starters, I'd suggest to create an abstract Weapon base class MonoBehaviour and then for each type create a subclass and put it on a GameObject. This can do stuff like access other components, receive collider trigger messages and store data.

Maybe you realize, that all weapons do a similar thing. Then you could have a WeaponBehaviour which works like a hub/controller on your player GameObject. It then has references to a data file which contains stats, as well as references to the model, materials, sound, etc.


问:
Qt-Using signals and slots with different threads
I'm still struggling to get this working as I expect.

I have a Qt project which I would like to update depending on signal states from different threads. My main GUI thread should start a worker thread running on the press of a start button.

The worker thread should then execute a function which continuously polls variables belonging to another class which are being updated by even a different thread (I am using portaudio libraries). It should then fire a signal (sendNewSig) which is connected to a slot (DrawData) in my GUI class.

The problem is the program crashes when I press my start button. I believe that I am missing some vital steps to start executing the worker thread. By calling updater->PollSignal() like this when the start button is clicked, I am expecting it to run in a new thread but perhaps not. I have shown parts of the code below which hopefully is enough to get my idea across.

Many thanks in advance for any help

In GUIApp.cpp

```<code>AudioGuiApplication::AudioGuiApplication(QWidget *parent)
: QMainWindow(parent)
{
    ui.setupUi(this);

    //......  other stuff

    thread = new QThread(this);
    updater = new GUIUpdater(&audio_processor);
    updater->moveToThread(thread);

    connect(updater, SIGNAL(sendNewSig(string)), this, SLOT(DrawData(string)));

    connect(thread, SIGNAL(destroyed()), updater, SLOT(deleteLater()));

    actionText->setPlainText("Press Start to begin ");
}

void AudioGuiApplication::on_startButton_clicked()
{
    updater->PollSignal();
}
</code>```

In GUIUpdater.cpp`

```<code>void GUIUpdater::PollSignal()
{
    string str;

    while (!ap->IsNewDataFound() )
    {
        emit sendNewSig(str);
        ap->SetNewSigFound(false);
    }
}`
</code>```

答:
You are calling the PollSignal function from the main/gui thread directly.

I think the easiest way to execute it in the desired thread is to employ the Signal & Slot mechanism with a single-shot QTimer set at no delay (0 stands for 0 milliseconds):

```<code>void AudioGuiApplication::on_startButton_clicked()
{
    QTimer::singleShot(0, updater, &GUIUpdater::PollSignal);
}
</code>```

By the way: you should consider moving to the "new" connect syntax that doesn't rely on macros and allows compile-time type validation instead.

Body:
I'm still struggling to get this working as I expect.

I have a Qt project which I would like to update depending on signal states from different threads. My main GUI thread should start a worker thread running on the press of a start button.

The worker thread should then execute a function which continuously polls variables belonging to another class which are being updated by even a different thread (I am using portaudio libraries). It should then fire a signal (sendNewSig) which is connected to a slot (DrawData) in my GUI class.

The problem is the program crashes when I press my start button. I believe that I am missing some vital steps to start executing the worker thread. By calling updater->PollSignal() like this when the start button is clicked, I am expecting it to run in a new thread but perhaps not. I have shown parts of the code below which hopefully is enough to get my idea across.

Many thanks in advance for any help

In GUIApp.cpp

AudioGuiApplication::AudioGuiApplication(QWidget *parent)
: QMainWindow(parent)
{
    ui.setupUi(this);

    //......  other stuff

    thread = new QThread(this);
    updater = new GUIUpdater(&audio_processor);
    updater->moveToThread(thread);

    connect(updater, SIGNAL(sendNewSig(string)), this, SLOT(DrawData(string)));

    connect(thread, SIGNAL(destroyed()), updater, SLOT(deleteLater()));

    actionText->setPlainText("Press Start to begin ");
}

void AudioGuiApplication::on_startButton_clicked()
{
    updater->PollSignal();
}

In GUIUpdater.cpp`

void GUIUpdater::PollSignal()
{
    string str;

    while (!ap->IsNewDataFound() )
    {
        emit sendNewSig(str);
        ap->SetNewSigFound(false);
    }
}`

Body:
You are calling the PollSignal function from the main/gui thread directly.

I think the easiest way to execute it in the desired thread is to employ the Signal & Slot mechanism with a single-shot QTimer set at no delay (0 stands for 0 milliseconds):

void AudioGuiApplication::on_startButton_clicked()
{
    QTimer::singleShot(0, updater, &GUIUpdater::PollSignal);
}

By the way: you should consider moving to the "new" connect syntax that doesn't rely on macros and allows compile-time type validation instead.


问:
SSIS package upgrade from 2012 to 2014 issues
I've SSIS packages built in 2012 and now I've migrated those packages into a new Prod system and there Sql Server 2014 installed. The package format version also upgraded from 6 to 8 and executed through SSDT 2014 in VS 2015 and the execution is successful. But when I tried to run through command prompt with batch files, package fails.

I checked the old system the DEXEC.exe was in 110 folder and in the new Prod system the DTEXEC.exe is in folder 120. will it be the cause of failure of jobs.

Please suggest me to get rid of this jobs failure.

答: you need to download the project from the SSIS repository on the Sql 2012 server, upgrade the project and all packages to 2014, and deploy to the 2014 server.  just copying the package will not work.</p>


问:
access variables in nodejs
Im an experienced coder in C# and now I´ve to deal with nodejs .. and I cannot get things to work as I expected them to work :)

I have a "class" declared like this :

```<code>var Gpio;

function Lights()
{
    [.more variables declared the same way..]
    this.o1 = "";
    this.o2 = "";
}

//then I have some methods added like this:
Lights.prototype.Init = function()
{
    var Gpio = require('pigpio').Gpio,
    //init of my variables
    o1 = new Gpio(17, {mode: Gpio.OUTPUT}),
    o2 = new Gpio(18, {mode: Gpio.OUTPUT});
}

//then I have other methods that try to use o1 and o2
//that where already defined and initialiced

Lights.prototype.On = function(id)
{
    if(id == 1)
        o1.digitalWrite(true);
    else if(id == 2)
        o2.digitalWrite(true);
}
</code>```

But when I run it I get :

```<code>o1.digitalWrite(false);
^

ReferenceError: o1 is not defined
</code>```

How can I make those o1 o2 o3 accesibles by the methods ???

答:
Unlike Java, C# and other languages, in JavaScript, the this keyword is not optional when accessing instance variables.

You are getting a ReferenceError because there is no variable named o1 in the current scope.

Try changing it to:

```<code>Lights.prototype.On = function(id)
{
    if(id == 1)
        this.o1.digitalWrite(true);
    else if(id == 2)
        this.o2.digitalWrite(true);
}
</code>```

(Of course, you'll need to change the Init method too)

As a final note, nodeJS supports ES6 which includes class declarations - they make JS code a lot neater (and more like C#) which might help you.

Here's how I would code your class:

```<code>const Gpio = require('pigpio').Gpio;

class Lights {
    constructor() {
        // there's no need to explicitly declare o1 and o2 here - they'll get
        // created whenever they are assigned to. This is just for readability.
        this.o1 = null;
        this.o2 = null;
        // add any more properties here in the constructor - you can't
        // declare them in the class body like C#
        this.another = 5;
    }

    init() {
        // I'm assuming there's a reason you haven't done this in the constructor
        this.o1 = new Gpio(17, {mode: Gpio.OUTPUT}),
        this.o2 = new Gpio(18, {mode: Gpio.OUTPUT});
    }

    on(id) {
        // this assumes that init() has been called
        switch (id) {
          case 1: this.o1.digitalWrite(true); break;
          case 2: this.o2.digitalWrite(true); break;
        }
    }

    // methods can be static too
    static HELLO() {
       // you would call this method with Lights.HELLO()
       console.log('hello');
    }
}

// if you need to access the Lights class from another nodejs source file, you'll
// need to export it (there's a few ways to do this, so read the docs)
exports.Lights = Lights;

// in main.js - import the Lights class and instantiate it
const Lights = require('./lights.js').Lights;
var light = new Lights();
light.init();
light.on(1);
// also note, there's no visibility restrictions in JS - all
//  properties and methods are public.
console.log(light.another);
</code>```

If you know C#, this should be fairly easy to follow.

Title: access variables in nodejs

Body:
Im an experienced coder in C# and now I´ve to deal with nodejs .. and I cannot get things to work as I expected them to work :)

I have a "class" declared like this :

var Gpio;

function Lights()
{
    [.more variables declared the same way..]
    this.o1 = "";
    this.o2 = "";
}

//then I have some methods added like this:
Lights.prototype.Init = function()
{
    var Gpio = require('pigpio').Gpio,
    //init of my variables
    o1 = new Gpio(17, {mode: Gpio.OUTPUT}),
    o2 = new Gpio(18, {mode: Gpio.OUTPUT});
}

//then I have other methods that try to use o1 and o2
//that where already defined and initialiced

Lights.prototype.On = function(id)
{
    if(id == 1)
        o1.digitalWrite(true);
    else if(id == 2)
        o2.digitalWrite(true);
}

But when I run it I get :

o1.digitalWrite(false);
^

ReferenceError: o1 is not defined

How can I make those o1 o2 o3 accesibles by the methods ???

Body:
Unlike Java, C# and other languages, in JavaScript, the this keyword is not optional when accessing instance variables.

You are getting a ReferenceError because there is no variable named o1 in the current scope.

Try changing it to:

Lights.prototype.On = function(id)
{
    if(id == 1)
        this.o1.digitalWrite(true);
    else if(id == 2)
        this.o2.digitalWrite(true);
}

(Of course, you'll need to change the Init method too)

As a final note, nodeJS supports ES6 which includes class declarations - they make JS code a lot neater (and more like C#) which might help you.

Here's how I would code your class:

const Gpio = require('pigpio').Gpio;

class Lights {
    constructor() {
        // there's no need to explicitly declare o1 and o2 here - they'll get
        // created whenever they are assigned to. This is just for readability.
        this.o1 = null;
        this.o2 = null;
        // add any more properties here in the constructor - you can't
        // declare them in the class body like C#
        this.another = 5;
    }

    init() {
        // I'm assuming there's a reason you haven't done this in the constructor
        this.o1 = new Gpio(17, {mode: Gpio.OUTPUT}),
        this.o2 = new Gpio(18, {mode: Gpio.OUTPUT});
    }

    on(id) {
        // this assumes that init() has been called
        switch (id) {
          case 1: this.o1.digitalWrite(true); break;
          case 2: this.o2.digitalWrite(true); break;
        }
    }

    // methods can be static too
    static HELLO() {
       // you would call this method with Lights.HELLO()
       console.log('hello');
    }
}

// if you need to access the Lights class from another nodejs source file, you'll
// need to export it (there's a few ways to do this, so read the docs)
exports.Lights = Lights;

// in main.js - import the Lights class and instantiate it
const Lights = require('./lights.js').Lights;
var light = new Lights();
light.init();
light.on(1);
// also note, there's no visibility restrictions in JS - all
//  properties and methods are public.
console.log(light.another);

If you know C#, this should be fairly easy to follow.


问:
I can't restart my dnsmasq service, so my fog server won't work
I have a fog server set up in work, every now and then our useless internet fails and I have to reset the dnsmasq to get it working again, (don't have a dhcp server set up and can't modify the hubs settings so won't be doing this). Whenever I try sudo dnsmasq restart, I get the message:

junk found in command line.

First of all, can some please explain to me in simple terms what this actually means? As I am no Linux expert and nobody seems to have a simple explanation as to what this is...

Secondly, I have always used the command posted on another the fog forum to correct this error.

sudo /etc/init.d/dnsmasq restart
```

This always worked perfectly however now when I try to run this command I get the message:

command not found`.

答:
Edit your /etc/init.d/dnsmasq

My linux distribution is Debian 9 (stretch)

Change this line :

```<code>ROOT_DS="/usr/share/dns/root.ds"

if [ -f $ROOT_DS ]; then
   DNSMASQ_OPTS="$DNSMASQ_OPTS `sed -e s/". IN DS "/--trust-anchor=.,/ -e s/" "/,/g $ROOT_DS | tr '\n' ' '`"
fi
</code>```

To :

```<code>ROOT_DS="/usr/share/dns/root.ds"

if [ -f $ROOT_DS ]; then
   DNSMASQ_OPTS="$DNSMASQ_OPTS `sed -e s/".*IN[[:space:]]DS[[:space:]]"/--trust-anchor=.,/ -e s/"[[:space:]]"/,/g $ROOT_DS | tr '\n' ' '`"
fi
</code>```

This problem occurs due to updating the dns-root-data package, more precisely in the file /usr/share/dns/root.ds.

The structure of this file was changed, the fields were separated only by spaces, now they were changed by tabs (\t)

ContentLicense: CC BY-SA 4.0

Body:
I have a fog server set up in work, every now and then our useless internet fails and I have to reset the dnsmasq to get it working again, (don't have a dhcp server set up and can't modify the hubs settings so won't be doing this). Whenever I try sudo dnsmasq restart, I get the message:

junk found in command line.

First of all, can some please explain to me in simple terms what this actually means? As I am no Linux expert and nobody seems to have a simple explanation as to what this is...

Secondly, I have always used the command posted on another the fog forum to correct this error.

sudo /etc/init.d/dnsmasq restart

This always worked perfectly however now when I try to run this command I get the message:

command not found`.

Body:
Edit your /etc/init.d/dnsmasq

My linux distribution is Debian 9 (stretch)

Change this line :

ROOT_DS="/usr/share/dns/root.ds"

if [ -f $ROOT_DS ]; then
   DNSMASQ_OPTS="$DNSMASQ_OPTS `sed -e s/". IN DS "/--trust-anchor=.,/ -e s/" "/,/g $ROOT_DS | tr '\n' ' '`"
fi

To :

ROOT_DS="/usr/share/dns/root.ds"

if [ -f $ROOT_DS ]; then
   DNSMASQ_OPTS="$DNSMASQ_OPTS `sed -e s/".*IN[[:space:]]DS[[:space:]]"/--trust-anchor=.,/ -e s/"[[:space:]]"/,/g $ROOT_DS | tr '\n' ' '`"
fi

This problem occurs due to updating the dns-root-data package, more precisely in the file /usr/share/dns/root.ds.

The structure of this file was changed, the fields were separated only by spaces, now they were changed by tabs (\t)


问:
Open an Android app from a web browser
I'm opening an app from a web browser in android and I can't seem to find the way to open this app outside the browser itself. I mean, the app opens inside the browser. I've tried both of these ways:

1) intent://pinnacle.androidApp/#Intent;scheme=launch package=my.androidApp;S.content=WebContent;end

2) my.androidapp://cb

What's the proper way to do this in order to open the app outside the browser?
Thanks in advance.

UPDATE:

My app consists of a native android app with a web view that loads an angular web app. I think that the web browser is opening the web app instead of redirecting back to the android app with the web view.

It goes as follows:
The user opens an android app with a web view that loads an angular web app. Then the user is supposed to log in. Due to some recent changes that google implemented, I can't log in with google from a web view, so I have to open a web browser, log in and go back to the android app. This latter thing is the actual problem. It only works properly if the browser that I use is chrome.
I can't use android to log in because I'm using custom authentication as well to provide access to other web services.

答: Register a URI scheme for your app and launch it by calling the URI somewhere as a link in your web page. This works 100%.</p>

Title: Open an Android app from a web browser


问:
Kafka mirrormaker do not start
Im in the process of upgrading our cluster. However Im having issues trying to make the mirrormakers run.

So this machines have kafka-brokers and kafka-mirrormakers running. They have separate init scripts.

The brokers currently are using version 10.1.1.1 and mirrormakers are using version 0.8.2-beta.

Both of them have their own config files and locations

for example brokers are installed in /server/kafka/
mirrormakers are installed under /opt/kafka_mirrormaker.

Here the config lines for brokers following what the upgrade process explained:

inter.broker.protocol.version=0.10.1
  log.message.format.version=0.8.2

and for mirrormakers:

inter.broker.protocol.version=0.8.2
  log.message.format.version=0.8.2

So I was testing to upgrade this to 10.2.1 I tried the upgrade in one host.
Broker is running fine after I applied the upgrade version 10.2.1 however the mirrormaker dies right away when I tried to start it.

I see this exception on the logs

```<code>    Exception in thread "main" java.lang.NullPointerException
    at kafka.tools.MirrorMaker$.main(MirrorMaker.scala:309)
    at kafka.tools.MirrorMaker.main(MirrorMaker.scala)
Exception in thread "MirrorMakerShutdownHook" java.lang.NullPointerException
    at kafka.tools.MirrorMaker$.cleanShutdown(MirrorMaker.scala:399)
    at kafka.tools.MirrorMaker$$anon$2.run(MirrorMaker.scala:222)
tail: kafka-mirrormaker-repl-sjc2-to-hkg1.out: file truncated
Exception in thread "main" java.lang.NullPointerException
    at kafka.tools.MirrorMaker$.main(MirrorMaker.scala:309)
    at kafka.tools.MirrorMaker.main(MirrorMaker.scala)
Exception in thread "MirrorMakerShutdownHook" java.lang.NullPointerException
    at kafka.tools.MirrorMaker$.cleanShutdown(MirrorMaker.scala:399)
    at kafka.tools.MirrorMaker$$anon$2.run(MirrorMaker.scala:222)
</code>```

and this one

```<code>[2017-05-18 17:02:27,936] ERROR Exception when starting mirror maker. (kafka.tools.MirrorMaker$)
org.apache.kafka.common.config.ConfigException: Missing required configuration "bootstrap.servers" which has no default value.
    at org.apache.kafka.common.config.ConfigDef.parse(ConfigDef.java:436)
    at org.apache.kafka.common.config.AbstractConfig.<init>(AbstractConfig.java:56)
    at org.apache.kafka.common.config.AbstractConfig.<init>(AbstractConfig.java:63)
    at org.apache.kafka.clients.producer.ProducerConfig.<init>(ProducerConfig.java:340)
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:191)
    at kafka.tools.MirrorMaker$MirrorMakerProducer.<init>(MirrorMaker.scala:694)
    at kafka.tools.MirrorMaker$.main(MirrorMaker.scala:236)
    at kafka.tools.MirrorMaker.main(MirrorMaker.scala)
</code>```

This bootstrap error is kind of weird due to this already config. The server.properties has localhost:9292 configured as the bootstrap.server

To upgrade this I did broker and mirrormaker at the same time. Im not sure if I should first upgrade all the brokers first and then the mirrormakers.

Any suggestions. Should I follow the same procedure, upgrade first all brokers and then all mirrormakers. once they are upgrade bump the protocols in server.properties. Even though when it seems that the documentation kind of doesnt imply that: http://kafka.apache.org/documentation.html#upgrade

答:
This has being solved.
The reason why they were not starting was due to the options on the configuration files change or were not properly configure</p>

Title: Kafka mirrormaker do not start

Body:
Im in the process of upgrading our cluster. However Im having issues trying to make the mirrormakers run.

So this machines have kafka-brokers and kafka-mirrormakers running. They have separate init scripts.

The brokers currently are using version 10.1.1.1 and mirrormakers are using version 0.8.2-beta.

Both of them have their own config files and locations

for example brokers are installed in /server/kafka/
mirrormakers are installed under /opt/kafka_mirrormaker.

Here the config lines for brokers following what the upgrade process explained:

inter.broker.protocol.version=0.10.1
  log.message.format.version=0.8.2

and for mirrormakers:

inter.broker.protocol.version=0.8.2
  log.message.format.version=0.8.2

So I was testing to upgrade this to 10.2.1 I tried the upgrade in one host.
Broker is running fine after I applied the upgrade version 10.2.1 however the mirrormaker dies right away when I tried to start it.

I see this exception on the logs

    Exception in thread "main" java.lang.NullPointerException
    at kafka.tools.MirrorMaker$.main(MirrorMaker.scala:309)
    at kafka.tools.MirrorMaker.main(MirrorMaker.scala)
Exception in thread "MirrorMakerShutdownHook" java.lang.NullPointerException
    at kafka.tools.MirrorMaker$.cleanShutdown(MirrorMaker.scala:399)
    at kafka.tools.MirrorMaker$$anon$2.run(MirrorMaker.scala:222)
tail: kafka-mirrormaker-repl-sjc2-to-hkg1.out: file truncated
Exception in thread "main" java.lang.NullPointerException
    at kafka.tools.MirrorMaker$.main(MirrorMaker.scala:309)
    at kafka.tools.MirrorMaker.main(MirrorMaker.scala)
Exception in thread "MirrorMakerShutdownHook" java.lang.NullPointerException
    at kafka.tools.MirrorMaker$.cleanShutdown(MirrorMaker.scala:399)
    at kafka.tools.MirrorMaker$$anon$2.run(MirrorMaker.scala:222)

and this one

[2017-05-18 17:02:27,936] ERROR Exception when starting mirror maker. (kafka.tools.MirrorMaker$)
org.apache.kafka.common.config.ConfigException: Missing required configuration "bootstrap.servers" which has no default value.
    at org.apache.kafka.common.config.ConfigDef.parse(ConfigDef.java:436)
    at org.apache.kafka.common.config.AbstractConfig.<init>(AbstractConfig.java:56)
    at org.apache.kafka.common.config.AbstractConfig.<init>(AbstractConfig.java:63)
    at org.apache.kafka.clients.producer.ProducerConfig.<init>(ProducerConfig.java:340)
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:191)
    at kafka.tools.MirrorMaker$MirrorMakerProducer.<init>(MirrorMaker.scala:694)
    at kafka.tools.MirrorMaker$.main(MirrorMaker.scala:236)
    at kafka.tools.MirrorMaker.main(MirrorMaker.scala)

This bootstrap error is kind of weird due to this already config. The server.properties has localhost:9292 configured as the bootstrap.server

To upgrade this I did broker and mirrormaker at the same time. Im not sure if I should first upgrade all the brokers first and then the mirrormakers.

Any suggestions. Should I follow the same procedure, upgrade first all brokers and then all mirrormakers. once they are upgrade bump the protocols in server.properties. Even though when it seems that the documentation kind of doesnt imply that: http://kafka.apache.org/documentation.html#upgrade


问:
Java app does not start after successful gradle build in eclipse
Simple java libgdx hello world builds sucecssful with gradle(new to gradle) build tool from eclipse, but it does not start.
I.e. I get ton of green buttons in graddle executions tab, and BUILD SUCCESSFUL in console tab. I cant find any errors that something went wrong and application could not start or any runtime errors. Nothing.
All instructions Ive been able to find on internets only tells how to build, none tells how to start the newly built application.</p>

答: If your gradle build is successful and the build script is correct, then the jar or war file which is created as a part of packaging should be under <actualProjectFolder>/build/libs/<yourprojectartifactname>-<version>.jar. I think looking at contents of build folder should give you an idea on what could be wrong.


问:
On 8088/86, does a shift/rotate by CL alter the value in CL?
In the iAP88/86 documentation, the timing information for the shifts and rotates depends on the shift count in CL (p2-64). This seems to imply that it's looping over the count in CL, doing that many single-bit shifts.

So my question is, does CL still have the same value after the rotate/shift completes, or does the operation count it down, similar to how the LOOP instruction behaves?

答:
No. Shift/rotate operations do not alter cl. You can clearly see this from Intel's pseudo code:

```<code>IF 64-Bit Mode and using REX.W
  THEN
    countMASK ← 3FH;
  ELSE
    countMASK ← 1FH;
  FI

  tempCOUNT ← (COUNT AND countMASK);
  tempDEST ← DEST;
  WHILE (tempCOUNT ≠ 0)
  DO
      IF instruction is SAL or SHL
        THEN
          CF ← MSB(DEST);
        ELSE (* Instruction is SAR or SHR *)
          CF ← LSB(DEST);
      FI;
      IF instruction is SAL or SHL
        THEN
          DEST ← DEST ∗ 2;
        ELSE
          IF instruction is SAR
            THEN
              DEST ← DEST / 2; (* Signed divide, rounding toward negative infinity *)
            ELSE (* Instruction is SHR *)
              DEST ← DEST / 2 ; (* Unsigned divide *)
          FI;
      FI;
      tempCOUNT ← tempCOUNT – 1;
  OD;

(* Determine overflow for the various instructions *)
IF (COUNT and countMASK) = 1
  THEN
    IF instruction is SAL or SHL
      THEN
        OF ← MSB(DEST) XOR CF;
      ELSE
        IF instruction is SAR
          THEN
            OF ← 0;
          ELSE (* Instruction is SHR *)
            OF ← MSB(tempDEST);
        FI;
    FI;
  ELSE IF (COUNT AND countMASK) = 0
      THEN
        All flags unchanged;
      ELSE (* COUNT not 1 or 0 *)
        OF ← undefined;
    FI;
FI;
</code>```

As you can clearly see, CL is assigned to tempCOUNT before being looped, so CL stays unchanged.

Note that the original 8086 doesn't mask the shift count which yields slightly different results in case the shift count is a multiple of the register size.

In general, I recommend you to confer the Intel manuals for your emulators. They specify to great detail how every single instruction is supposed to work.

Body:
No. Shift/rotate operations do not alter cl. You can clearly see this from Intel's pseudo code:

IF 64-Bit Mode and using REX.W
  THEN
    countMASK ← 3FH;
  ELSE
    countMASK ← 1FH;
  FI

  tempCOUNT ← (COUNT AND countMASK);
  tempDEST ← DEST;
  WHILE (tempCOUNT ≠ 0)
  DO
      IF instruction is SAL or SHL
        THEN
          CF ← MSB(DEST);
        ELSE (* Instruction is SAR or SHR *)
          CF ← LSB(DEST);
      FI;
      IF instruction is SAL or SHL
        THEN
          DEST ← DEST ∗ 2;
        ELSE
          IF instruction is SAR
            THEN
              DEST ← DEST / 2; (* Signed divide, rounding toward negative infinity *)
            ELSE (* Instruction is SHR *)
              DEST ← DEST / 2 ; (* Unsigned divide *)
          FI;
      FI;
      tempCOUNT ← tempCOUNT – 1;
  OD;

(* Determine overflow for the various instructions *)
IF (COUNT and countMASK) = 1
  THEN
    IF instruction is SAL or SHL
      THEN
        OF ← MSB(DEST) XOR CF;
      ELSE
        IF instruction is SAR
          THEN
            OF ← 0;
          ELSE (* Instruction is SHR *)
            OF ← MSB(tempDEST);
        FI;
    FI;
  ELSE IF (COUNT AND countMASK) = 0
      THEN
        All flags unchanged;
      ELSE (* COUNT not 1 or 0 *)
        OF ← undefined;
    FI;
FI;

As you can clearly see, CL is assigned to tempCOUNT before being looped, so CL stays unchanged.

Note that the original 8086 doesn't mask the shift count which yields slightly different results in case the shift count is a multiple of the register size.

In general, I recommend you to confer the Intel manuals for your emulators. They specify to great detail how every single instruction is supposed to work.


问:
Laravel retrieve status from pivot table
i have tables ,Station & Equipment ,a third pivot table station_equipment with additional field "status" besides the respective table ids, the status can be active or inactive, I just want to get the Active elements, but my query keep on retrieving equipments with both status .

the query:

```<code>   $eqestacion = Station::where('station.id', $id)
                ->whereHas('equipments', function($query) {

                    $query->where('equipment_station.status','=','active');
                    })->with('equipments')
                      ->get();
</code>```

Station Model:

```<code>public function equipments(){

  return $this->belongsToMany('App\Equipment')->withPivot('status')->withTimestamps();
}
</code>```

Equiment Model:

```<code> public function stations()

   return $this->belongsToMany('App\Station')
    ->orderBy('pivot_created_at','desc')->withPivot('status')->withTimestamps();
}
</code>```

thanks in advance

答:
This will give you a Station with id $id:

```<code>$station = Station::findOrFail($id);
</code>```

This will give you all active Equipments associated to the $station.

```<code>$station->equipments()->wherePivot('status', 'active')->get();
</code>```

Body:
i have tables ,Station & Equipment ,a third pivot table station_equipment with additional field "status" besides the respective table ids, the status can be active or inactive, I just want to get the Active elements, but my query keep on retrieving equipments with both status .

the query:

   $eqestacion = Station::where('station.id', $id)
                ->whereHas('equipments', function($query) {

                    $query->where('equipment_station.status','=','active');
                    })->with('equipments')
                      ->get();

Station Model:

public function equipments(){

  return $this->belongsToMany('App\Equipment')->withPivot('status')->withTimestamps();
}

Equiment Model:

 public function stations()

   return $this->belongsToMany('App\Station')
    ->orderBy('pivot_created_at','desc')->withPivot('status')->withTimestamps();
}

thanks in advance

Body:
This will give you a Station with id $id:

$station = Station::findOrFail($id);

This will give you all active Equipments associated to the $station.

$station->equipments()->wherePivot('status', 'active')->get();


问:
Why is the type of tf.Variable([8.0], tf.float64) float 32 rather than float 64 in TensorFlow?
(Updated question)
I think the original question is confusing, and I found a simpler way to ask this question.

```<code>#!/usr/bin/python

import tensorflow as tf
x = tf.Variable([2], tf.float32)
print x.dtype
</code>```

If we try the above code segment, then the output is as follows:

```<code><dtype: 'int32_ref'>
</code>```

Since I explicitly specified the type of x as tf.float32, I had thought that the type should be float32. However, it seems like the type is int32.

Could somebody answer this question?

(original question)

I tried the following code to replace one element of a 2-D tensorflow array.

```<code>#!/usr/bin/python

import tensorflow as tf
import numpy as np

ref = tf.Variable(np.arange(0, 12).reshape((4, 3)).astype(np.float64))
indices = tf.constant([[2, 2]])
updates = tf.Variable([8.0], tf.float64)
ref = tf.scatter_nd_update(ref, indices, updates)

with tf.Session() as sess:
  init = tf.global_variables_initializer()
  sess.run(init)
  print sess.run(ref)
</code>```

Strangely, I encountered the following type error:

TypeError: Input 'updates' of 'ScatterNdUpdate' Op has type float32 that does not match type float64 of argument 'ref'.

After changing tf.Variable([8.0], tf.float64) to the following line, it worked.

```<code>updates = tf.Variable(np.array([8.0]).astype(np.float64), tf.float64)
</code>```

So, it seems like the type of tf.Variable([8.0], tf.float64) is not tf.float64, even though I explicitly specified the type as tf.float64. Could anyone tell me the reason? Thank you!

答:
Update:

Use dtype when using tf.Variable()

Original Question:

making ref type to float32 is working for me.

Do

```<code>ref = tf.Variable(np.arange(0, 12).reshape((4, 3)).astype(np.float32))
</code>```

or

```<code>ref = tf.Variable(np.arange(0, 12).reshape((4, 3)),dtype=tf.float32)
</code>```

I guess, ScatterNdUpdate operation works only for float32 not float64.

Body:
(Updated question)
I think the original question is confusing, and I found a simpler way to ask this question.

#!/usr/bin/python

import tensorflow as tf
x = tf.Variable([2], tf.float32)
print x.dtype

If we try the above code segment, then the output is as follows:

<dtype: 'int32_ref'>

Since I explicitly specified the type of x as tf.float32, I had thought that the type should be float32. However, it seems like the type is int32.

Could somebody answer this question?

(original question)

I tried the following code to replace one element of a 2-D tensorflow array.

#!/usr/bin/python

import tensorflow as tf
import numpy as np

ref = tf.Variable(np.arange(0, 12).reshape((4, 3)).astype(np.float64))
indices = tf.constant([[2, 2]])
updates = tf.Variable([8.0], tf.float64)
ref = tf.scatter_nd_update(ref, indices, updates)

with tf.Session() as sess:
  init = tf.global_variables_initializer()
  sess.run(init)
  print sess.run(ref)

Strangely, I encountered the following type error:

TypeError: Input 'updates' of 'ScatterNdUpdate' Op has type float32 that does not match type float64 of argument 'ref'.

After changing tf.Variable([8.0], tf.float64) to the following line, it worked.

updates = tf.Variable(np.array([8.0]).astype(np.float64), tf.float64)

So, it seems like the type of tf.Variable([8.0], tf.float64) is not tf.float64, even though I explicitly specified the type as tf.float64. Could anyone tell me the reason? Thank you!

Body:
Update:

Use dtype when using tf.Variable()

Original Question:

making ref type to float32 is working for me.

Do

ref = tf.Variable(np.arange(0, 12).reshape((4, 3)).astype(np.float32))

or

ref = tf.Variable(np.arange(0, 12).reshape((4, 3)),dtype=tf.float32)

I guess, ScatterNdUpdate operation works only for float32 not float64.


问:
TypeError: Incompatible broadcastable dimensions. Expected (False,), got (True,)
I am working with theano and lasagne.

I am trying to use BatchNorm and I am getting this error. Can someone please guide me, what could be wrong? Or if I can get name of the variable that has this mismatch?

Thanks!

EDIT1:

I am trying to do something like this:

```<code>inputTarget = lasagne.layers.InputLayer(shape=(1,2,32, 32, 32), input_var=T.concatenate([tX, tY], axis=1))
network = lasagne.layers.SliceLayer(inputTarget, indices=slice(0, 1),axis=1)
tX_new = lasagne.layers.get_output(network)
network = lasagne.layers.batch_norm(network)
tY_predicted = lasagne.layers.get_output(network)
target= lasagne.layers.SliceLayer(inputTarget, indices=slice(1, None), axis=1)

tY_new = lasagne.layers.get_output(target)
loss = lasagne.objectives.squared_error(tY_predicted, tY_new).mean()
updates = lasagne.updates.adam(loss, params, learning_rate=lr)
train_fn = theano.function([tX, tY], [tY_predicted, loss, tY_new, tX_new], updates=updates)
</code>```

LOGS:

```<code>Traceback (most recent call last):
  train_fn = theano.function([tX, tY], [tY_predicted, loss, tY_new, tX_new], updates=updates)
  File "/lib/python2.7/site-packages/theano/compile/function.py", line 326, in function
    output_keys=output_keys)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 449, in pfunc
    no_default_updates=no_default_updates)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 219, in rebuild_collect_shared
    cloned_v = clone_v_get_shared_updates(v, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 219, in rebuild_collect_shared
    cloned_v = clone_v_get_shared_updates(v, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 114, in clone_v_get_shared_updates
    allow_convert=False)
  File "/lib/python2.7/site-packages/theano/sandbox/cuda/type.py", line 185, in filter_variable
    str(self.broadcastable)))
TypeError: Incompatible broadcastable dimensions. Expected (False,), got (True,).
</code>```

After checking the variables, I know that the code breaks for mean. I am not able to figure out why.

答: Theano does not do broadcasting as numpy does(automatically). You must manually set the dimension that you require to be broadcastable. There is an amazing tutorial given about broadcasting here. If your problem still persists after going through this tutorial, please share your code and the full traceback for me to help you further. </p>

Body:
I am working with theano and lasagne.

I am trying to use BatchNorm and I am getting this error. Can someone please guide me, what could be wrong? Or if I can get name of the variable that has this mismatch?

Thanks!

EDIT1:

I am trying to do something like this:

inputTarget = lasagne.layers.InputLayer(shape=(1,2,32, 32, 32), input_var=T.concatenate([tX, tY], axis=1))
network = lasagne.layers.SliceLayer(inputTarget, indices=slice(0, 1),axis=1)
tX_new = lasagne.layers.get_output(network)
network = lasagne.layers.batch_norm(network)
tY_predicted = lasagne.layers.get_output(network)
target= lasagne.layers.SliceLayer(inputTarget, indices=slice(1, None), axis=1)

tY_new = lasagne.layers.get_output(target)
loss = lasagne.objectives.squared_error(tY_predicted, tY_new).mean()
updates = lasagne.updates.adam(loss, params, learning_rate=lr)
train_fn = theano.function([tX, tY], [tY_predicted, loss, tY_new, tX_new], updates=updates)

LOGS:

Traceback (most recent call last):
  train_fn = theano.function([tX, tY], [tY_predicted, loss, tY_new, tX_new], updates=updates)
  File "/lib/python2.7/site-packages/theano/compile/function.py", line 326, in function
    output_keys=output_keys)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 449, in pfunc
    no_default_updates=no_default_updates)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 219, in rebuild_collect_shared
    cloned_v = clone_v_get_shared_updates(v, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 219, in rebuild_collect_shared
    cloned_v = clone_v_get_shared_updates(v, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 93, in clone_v_get_shared_updates
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/lib/python2.7/site-packages/theano/compile/pfunc.py", line 114, in clone_v_get_shared_updates
    allow_convert=False)
  File "/lib/python2.7/site-packages/theano/sandbox/cuda/type.py", line 185, in filter_variable
    str(self.broadcastable)))
TypeError: Incompatible broadcastable dimensions. Expected (False,), got (True,).

After checking the variables, I know that the code breaks for mean. I am not able to figure out why.


问:
UWP StorageFile Efficiency
So reading the Microsoft Documentation it states that there are 3 methods to write to a file in UWP: the FileIO class, a buffer, or a stream. My program is performing lots of live data calculations that are time sensitive for my UI and I would like to implement a file output of this data on top of my visual display. My question is which method would be best for my program? Writing the log file is not time critical at all so which option would impact my programs operations the least?

Thanks in advance!

答:
Using the FileIO class' ReadTextAsync and WriteTextAsync method should be good enough. There is no reason to use buffers unless you really have to for some reason.

Since these methods are async you can call them synchronously without blocking the UI during the time it takes to read or write to the file.

Title: UWP StorageFile Efficiency


问:
Efficient querying for equality of ranges in an integer array
Given an positive integer array of size n, it is expected to find whether two ranges gives as queries are equal or not. Two ranges are considered equal if the all the elements present in range 1 are present in range 2 and in the same count as well.

Example:

```<code>1 2 5 3 5 1 2
</code>```

Queries:

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

Answers:

```<code>Yes
No
</code>```

A naive solution can be suggested in the following way:

1. For every query, make two copies of the array that store each of the ranges O(n).

2. Then sort each of them. O(n*logn)

3. Then compare element by element and return true or false. O(n)

So the complexity of the solution is O(q*n*logn), where q is the number of queries. Is it possible for an efficient solution to this problem?

PS: The constraints of all the variables n, q and the array elements are <=10^5.

答:
Though there may be other approaches as well to solve this one, below approach will work well to solve this in O(N). (for x number of times if queries come then O(xN) which can be optimised by caching the results of queries too, just the query range and its result)

For our ease lets name the starting and ending element in queries as
range1StartIndex , range2StartIndex, range1EndIndex and range2EndIndex.

See if the difference between end and start elements of both the ranges are not equal, of so then return "No" else move to next step.

( If the differences in both the range are equal then we need to process the array elements).

Initialize a HashMap, lets name it countMap. Iterate the array from range1StartIndex till range1EndIndex and put in map as entry of each character encountered and its total number of occurances. Move to next step.

Iterate the array from range2StartIndex till range2EndIndex. As an character is encountered see if it is present in the countMap. If it is not present or if its count is 0 then return "No".  If it is present decrement the count by one and move to next step.

Iterate the keys of the countMap , if any key has a count greater than 1 , return "No", else move to next step.

return "Yes". Exit.

Body:
Given an positive integer array of size n, it is expected to find whether two ranges gives as queries are equal or not. Two ranges are considered equal if the all the elements present in range 1 are present in range 2 and in the same count as well.

Example:

1 2 5 3 5 1 2

Queries:

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

Answers:

Yes
No

A naive solution can be suggested in the following way:

1. For every query, make two copies of the array that store each of the ranges O(n).

2. Then sort each of them. O(n*logn)

3. Then compare element by element and return true or false. O(n)

So the complexity of the solution is O(q*n*logn), where q is the number of queries. Is it possible for an efficient solution to this problem?

PS: The constraints of all the variables n, q and the array elements are <=10^5.


问:
windows phone 7, Button template image source binding
I have got Pivot with ListBoxes in each PevotItem. I've made Button control for animating items in ListBoxes. There is tree of those buttons - each of them has different image in it. However maybe there is some way to make one Button and just bind the image source. I think it will improve loading page time.

I will be thankful for any answer.

Here is my code:

```<code>    <DataTemplate x:Key="pageItemTemplate">
        <Button Content="{Binding name}" Margin="0,0,0,20" Style="{StaticResource PageListItemButton}"/>
    </DataTemplate>

<Style x:Key="PageListItemButton" TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <StackPanel x:Name="stackPanel" Orientation="Horizontal">
                        <StackPanel.Projection>
                            <PlaneProjection CenterOfRotationY="0" CenterOfRotationX="1"/>
                        </StackPanel.Projection>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualStateGroup.Transitions>
                                    <VisualTransition GeneratedDuration="0:0:0.05">
                                        <VisualTransition.GeneratedEasingFunction>
                                            <CircleEase EasingMode="EaseInOut"/>
                                        </VisualTransition.GeneratedEasingFunction>
                                    </VisualTransition>
                                </VisualStateGroup.Transitions>
                                <VisualState x:Name="Normal"/>
                                <VisualState x:Name="MouseOver"/>
                                <VisualState x:Name="Pressed">
                                    <Storyboard>
                                        <DoubleAnimation Duration="0" To="15" Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationY)" Storyboard.TargetName="stackPanel" d:IsOptimized="True"/>
                                        <DoubleAnimation Duration="0" To="0.7" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="stackPanel" d:IsOptimized="True"/>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Disabled"/>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Image Source="Images/MainPage/page.png" Height="40" Stretch="Fill" Width="40"/>
                        <ContentPresenter VerticalAlignment="Bottom"/>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="FontFamily" Value="/BestNote;component/Fonts/Fonts.zip#Diavlo Bold"/>
        <Setter Property="FontWeight" Value="Bold"/>
        <Setter Property="FontSize" Value="24"/>
        <Setter Property="Foreground" Value="#FF292929"/>
    </Style>
</code>```

答:
If you're finding the loading time of one image (sized for a button) is substantial enough to cause a delay opening the page, perhaps the image can be reduced in size to something more suitable for an image of that size.

Alternatively, perhaps do some profiling to identify what is actualy taking the time to load this page .. it may not be the image taking the majority of the time.

You could do simple profiling with debug output and TimeSpans, or try something like the EQATEC profiler.

Body:
I have got Pivot with ListBoxes in each PevotItem. I've made Button control for animating items in ListBoxes. There is tree of those buttons - each of them has different image in it. However maybe there is some way to make one Button and just bind the image source. I think it will improve loading page time.

I will be thankful for any answer.

Here is my code:

    <DataTemplate x:Key="pageItemTemplate">
        <Button Content="{Binding name}" Margin="0,0,0,20" Style="{StaticResource PageListItemButton}"/>
    </DataTemplate>


问:
php query in database doesn't work
Hello guys i tried to add into database some values and it's not working.I tried everything but no.
What should i do? the name of the table is "credit".
Can you help me to rezolv this problem?</p>

```<code><tr>
    <td><input class="form-control" placeholder="nr" name="nr" type="text" autofocus></td>
    <td><input class="form-control" placeholder="suma" name="suma" type="text" autofocus></td>
    <td><input class="form-control" placeholder="rate" name="rate" type="text" autofocus></td>
    <td><input class="form-control" placeholder="dobanda" name="dobanda" type="text" autofocus></td>
    <td><button class="btn btn-success" value="adaugare">Adaugare credit</button></a></td>
</tr>
</table>
</div>
</div>

<?php if(isset($_POST['adaugare']))
    {
        $nr=$_POST['nr'];
        $suma=$_POST['suma'];
        $rate=$_POST['rate'];
        $dobanda=$_POST['dobanda'];

        if($nr=='')
        {

            echo"<script>alert('Introdu numar')</script>";
            exit();
        }

        if($suma=='')
        {

            echo"<script>alert('Introdu suma')</script>";
            exit();
        }
        if($rate=='')
        {
            echo"<script>alert('Introdu rate')</script>";
            exit();
        }
        if($dobanda=='')
        {
            echo"<script>alert('Introdu dobanda')</script>";
            exit();
        }
        $id=$_SESSION['id'];
        $insert_credit="insert into credit VALUE ('$nr','$id','$suma','$rate','$dobanda')";
        mysqli_query($dbcon,$insert_credit);

    }
</code>```

答:
1) I can't see you establishing your    connection to the databse

2) Change your button to a submit button

3) Your SQL query has a syntax error Wich should have been displayed if not for 1.

*4) I would not use mysql
i I find it simple to use PDO and it's allso safer

Title: php query in database doesn't work

Body:
Hello guys i tried to add into database some values and it's not working.I tried everything but no.
What should i do? the name of the table is "credit".
Can you help me to rezolv this problem?

    <input class="form-control" placeholder="nr" name="nr" type="text" autofocus>
    <input class="form-control" placeholder="suma" name="suma" type="text" autofocus>
    <input class="form-control" placeholder="rate" name="rate" type="text" autofocus>
    <input class="form-control" placeholder="dobanda" name="dobanda" type="text" autofocus>
    <button class="btn btn-success" value="adaugare">Adaugare credit</button>

<?php if(isset($_POST['adaugare']))
    {
        $nr=$_POST['nr'];
        $suma=$_POST['suma'];
        $rate=$_POST['rate'];
        $dobanda=$_POST['dobanda'];

        if($nr=='')
        {

            echo"";
            exit();
        }

        if($suma=='')
        {

            echo"";
            exit();
        }
        if($rate=='')
        {
            echo"";
            exit();
        }
        if($dobanda=='')
        {
            echo"";
            exit();
        }
        $id=$_SESSION['id'];
        $insert_credit="insert into credit VALUE ('$nr','$id','$suma','$rate','$dobanda')";
        mysqli_query($dbcon,$insert_credit);

    }


问:
vuejs v-bind:class on a v-for not updating
have this code

```<code><span v-for="tag in ref.tags" @mouseenter="tag.pop=true;tag.adjust($event)" @mouseleave="tag.pop=false" >
    <span  :class="tag.pop? 'ref-tag-pop' : 'tag'">@{{tag.name}}</span>
    <div v-show="tag.pop">@{{tag.info}}</div>
</span>
</code>```

It's basically a popup on hover.
It works fine, but when I add a new "tag", although I see the new tag added to screen, the hover isn't working for it.

When I look in the vue devtools I can see that for the original tags the true and false change dynamically while the new tag doesn't. Although, if I remove the mouseleave event and refresh the devtools I can see the tag.pop does change to true.
If I then hover over one of the old ones both old and new popups show up, so I think it's a change detection problem.

I tried to change the mouseenter to $set(tag,'pop',true), but everything is acting the same way.
I also tried to use the $set for the adding of the new tag, even though the tag was rendered into screen, but still, nothing changed.

I'm not sure what else to do, any suggestions?

Edit:
Code for adding a new tab:

```<code>    submitTab: function(){
            this.form="";
            this.addedObj.name=document.getElementById("fNewTagTitle").value;
            this.addedObj.info=document.getElementById("fNewTagInfo").value;
            if (!this.isEditMode)
                this.isEditMode=true;
            this.editMode.add.tags.push(this.addedObj);
            this.addedObj.pop=false;
            this.addedObj.adjust= function(event) {
                left=event.target.offsetLeft;
                div=event.target.lastChild;
                div.style.left = -left+14+"px";
            };
            ref= this.addedObj.tagRef;
            delete this.addedObj.tagRef;
            this.$set(ref.tags,ref.tags.length, this.addedObj);

            this.addedObj='';
            },
</code>```

Edit 2:

Initial load of refs

```<code>        loadRefs:function(){
            this.$http.get(this.url + "/refs").then(
                function (result) {
                    data = JSON.parse(result.body);
                    var last =0;
                    for  (item of data){
                        if (item.ref_id!= last){
                            if (last!=0)
                                this.refs.push(ref);
                            var ref = new Object();
                            ref.show=false;
                            ref.refId=item.ref_id;
                            ref.type=item.ref_type_id;
                            ref.title=item.title;
                            ref.author=item.author;
                            ref.edition=item.edition;
                            ref.source=item.source;
                            ref.date=item.date;
                            ref.journal=item.journal;
                            ref.year=item.year;
                            ref.page=item.page;
                            ref.publisher=item.publisher;
                            ref.outlet=item.outlet;
                            ref.undersigned=item.undersigned;
                            ref.representing=item.representing;
                            ref.URL=item.URL;
                            ref.created_at=item.created_at;
                            ref.username=item.username;
                            ref.score=item.score;
                            ref.support=item.pivot.support;
                            ref.tags=[];
                        }
                        ref.tags.push({ name:item.tag_name, info: item.tag_info, pop:false, adjust: function(event) {
                            left=event.target.offsetLeft;
                            div=event.target.lastChild;
                            div.style.left = -left+14+"px";
                         }, });
                        last=item.ref_id;
                    }
                    if (data.length>0)
                        this.refs.push(ref);
                },
                function(result) {
                    alert( "error" );//XXX add error function
                }
            )
        },
</code>```

It's also declared in the Data section.

BTW I added the v-for a :key but it didn't change anything.

答:
Thanks to  thanksd

I just copied the way I added the first tags to the add tag function, and now it works fine.

Something about using an already existing object probably stoped it from working in the first place. creating tag as a new object fixed it.

It was probably a better way to code it in the first place.

Body:
have this code

    @{{tag.name}}

@{{tag.info}}

It's basically a popup on hover.
It works fine, but when I add a new "tag", although I see the new tag added to screen, the hover isn't working for it.

When I look in the vue devtools I can see that for the original tags the true and false change dynamically while the new tag doesn't. Although, if I remove the mouseleave event and refresh the devtools I can see the tag.pop does change to true.
If I then hover over one of the old ones both old and new popups show up, so I think it's a change detection problem.

I tried to change the mouseenter to $set(tag,'pop',true), but everything is acting the same way.
I also tried to use the $set for the adding of the new tag, even though the tag was rendered into screen, but still, nothing changed.

I'm not sure what else to do, any suggestions?

Edit:
Code for adding a new tab:

    submitTab: function(){
            this.form="";
            this.addedObj.name=document.getElementById("fNewTagTitle").value;
            this.addedObj.info=document.getElementById("fNewTagInfo").value;
            if (!this.isEditMode)
                this.isEditMode=true;
            this.editMode.add.tags.push(this.addedObj);
            this.addedObj.pop=false;
            this.addedObj.adjust= function(event) {
                left=event.target.offsetLeft;
                div=event.target.lastChild;
                div.style.left = -left+14+"px";
            };
            ref= this.addedObj.tagRef;
            delete this.addedObj.tagRef;
            this.$set(ref.tags,ref.tags.length, this.addedObj);

            this.addedObj='';
            },

Edit 2:

Initial load of refs

        loadRefs:function(){
            this.$http.get(this.url + "/refs").then(
                function (result) {
                    data = JSON.parse(result.body);
                    var last =0;
                    for  (item of data){
                        if (item.ref_id!= last){
                            if (last!=0)
                                this.refs.push(ref);
                            var ref = new Object();
                            ref.show=false;
                            ref.refId=item.ref_id;
                            ref.type=item.ref_type_id;
                            ref.title=item.title;
                            ref.author=item.author;
                            ref.edition=item.edition;
                            ref.source=item.source;
                            ref.date=item.date;
                            ref.journal=item.journal;
                            ref.year=item.year;
                            ref.page=item.page;
                            ref.publisher=item.publisher;
                            ref.outlet=item.outlet;
                            ref.undersigned=item.undersigned;
                            ref.representing=item.representing;
                            ref.URL=item.URL;
                            ref.created_at=item.created_at;
                            ref.username=item.username;
                            ref.score=item.score;
                            ref.support=item.pivot.support;
                            ref.tags=[];
                        }
                        ref.tags.push({ name:item.tag_name, info: item.tag_info, pop:false, adjust: function(event) {
                            left=event.target.offsetLeft;
                            div=event.target.lastChild;
                            div.style.left = -left+14+"px";
                         }, });
                        last=item.ref_id;
                    }
                    if (data.length>0)
                        this.refs.push(ref);
                },
                function(result) {
                    alert( "error" );//XXX add error function
                }
            )
        },

It's also declared in the Data section.

BTW I added the v-for a :key but it didn't change anything.


问:
Move UITextField up when keyboard is overlapped
There is a subView presented on top of ViewA. Please find the screen layout below. When keyboard is shown on selecting UITextField even if its not overlapping with UITextField the view is scrolled up.

```<code>ViewA
  -> UIButton

subView
  -> UIScrollView
        -> UITextField
        -> UITextField

   ViewA
 -----------
|           |
|           |
|  Button   |
|           |
|           |
 -----------

   subView
 --------------
|              |
|              |
|  UITextField |
|  UITextField |
|              |
 --------------
</code>```

I have registered keyboard notification

```<code>    - (void) viewWillAppear:(BOOL)animated {

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardDidShow:)
                                                     name:UIKeyboardDidShowNotification
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillBeHidden:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
    }

- (void) keyboardDidShow:(NSNotification *)notification {

            NSDictionary* info = [notification userInfo];
            CGRect kbRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];

            UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbRect.size.height, 0.0);
            self.scrollViewIb.contentInset = contentInsets;
            self.scrollViewIb.scrollIndicatorInsets = contentInsets;

            CGRect aRect = self.viewSelf.frame;
            aRect.size.height -= kbRect.size.height;
            CGRect frame = [self.viewSelf convertRect:self.activeField.frame toView:self.viewSelf.superview];
            if (!CGRectContainsPoint(aRect, frame.origin) ) {
                [self.scrollViewIb scrollRectToVisible:self.activeField.frame animated:YES];
            }
    }

- (void) keyboardWillBeHidden:(NSNotification *)notification {

        self.scrollViewIb.scrollEnabled = true;

        UIEdgeInsets contentInsets = UIEdgeInsetsZero;
        self.scrollViewIb.scrollIndicatorInsets = contentInsets;
        [self.scrollViewIb setContentOffset:CGPointZero animated:false];

}
</code>```

答:
There's a minor mistake in the coordinate system conversion:  convertRect:toView: converts from the coordinate system of the receiver to the coordinates of the passed view.

If self.activeField.frame is a rectangle in the coordinate system of self.scrollViewIb as the code implies, then the conversion should go like this...

```<code>    CGRect frame = [self.scrollViewIb convertRect:self.activeField.frame toView:self.view];
</code>```

Notice that I also suggest changing self.viewSelf.superview to self.view.  If this code is running in the view controller that contains all of these subviews, then self.view should be sufficient and correct.

Body:
There is a subView presented on top of ViewA. Please find the screen layout below. When keyboard is shown on selecting UITextField even if its not overlapping with UITextField the view is scrolled up.

ViewA
  -> UIButton

subView
  -> UIScrollView
        -> UITextField
        -> UITextField

   ViewA
 -----------
|           |
|           |
|  Button   |
|           |
|           |
 -----------

   subView
 --------------
|              |
|              |
|  UITextField |
|  UITextField |
|              |
 --------------

I have registered keyboard notification

    - (void) viewWillAppear:(BOOL)animated {

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardDidShow:)
                                                     name:UIKeyboardDidShowNotification
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillBeHidden:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
    }

- (void) keyboardDidShow:(NSNotification *)notification {

            NSDictionary* info = [notification userInfo];
            CGRect kbRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];

            UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbRect.size.height, 0.0);
            self.scrollViewIb.contentInset = contentInsets;
            self.scrollViewIb.scrollIndicatorInsets = contentInsets;

            CGRect aRect = self.viewSelf.frame;
            aRect.size.height -= kbRect.size.height;
            CGRect frame = [self.viewSelf convertRect:self.activeField.frame toView:self.viewSelf.superview];
            if (!CGRectContainsPoint(aRect, frame.origin) ) {
                [self.scrollViewIb scrollRectToVisible:self.activeField.frame animated:YES];
            }
    }

- (void) keyboardWillBeHidden:(NSNotification *)notification {

        self.scrollViewIb.scrollEnabled = true;

        UIEdgeInsets contentInsets = UIEdgeInsetsZero;
        self.scrollViewIb.scrollIndicatorInsets = contentInsets;
        [self.scrollViewIb setContentOffset:CGPointZero animated:false];

}

Body:
There's a minor mistake in the coordinate system conversion:  convertRect:toView: converts from the coordinate system of the receiver to the coordinates of the passed view.

If self.activeField.frame is a rectangle in the coordinate system of self.scrollViewIb as the code implies, then the conversion should go like this...

    CGRect frame = [self.scrollViewIb convertRect:self.activeField.frame toView:self.view];

Notice that I also suggest changing self.viewSelf.superview to self.view.  If this code is running in the view controller that contains all of these subviews, then self.view should be sufficient and correct.


问:
using select_related and prefetch_related with many arguments
I am relatively new to django, and I am using select_related() and prefetch_related() in django to decrease my hits to the database.

this is a part of my views.py file:

```<code>topic = Topic.objects.filter(id=topic_id).select_related('followed_by')
questions = Question.objects.filter(topics=topic).prefetch_related('answers','question_comments','answers__created_by__userprofile','answers__answer_comments')
</code>```

without the select_related and prefetch_related the view does 42 queries in 23.36MS, and with those added, it decreases to 10 queries in 7.91MS, looking at this data, I think those functions are really great.

So my question is this: Is there any downside to using these two functions? Should I not join this many tables in one go?

答:
Simple answer

No, there isn't a downside

Real Answer

Prefetch related does the join on the python side. Most of the time this is fine but always profile. You may also find the Prefetch object really helpful when you need to tune your DB access further.

Select related does what you would expect (it creates the join statements and flushes that to the database) and will perform really well most if the time.

In scaling up, the joins may become more of a hinderance - you'll want to maybe alter your data model by denormalizing, implementing a caching layer, separating the calls by resource type, etc..

Side Note

You'll want to start putting these bigger queries into your model manager so the view can just call a method and you can tune away behind the scenes.

e.g. (Note, there are newer ways of doing this with queryset subclasses, etc..)

```<code># models.py

class QuestionManager(models.Manager):
    def by_topic(self, topic):
        return self.filter(topic=topic).prefetch_related('...')

# views

def my_view(request, *args, **kwargs):
    # get the topic however
    topic = get_topic(kwargs.get('topic')
    Question.objects.by_topic(topic)
</code>```

Body:
I am relatively new to django, and I am using select_related() and prefetch_related() in django to decrease my hits to the database.

this is a part of my views.py file:

topic = Topic.objects.filter(id=topic_id).select_related('followed_by')
questions = Question.objects.filter(topics=topic).prefetch_related('answers','question_comments','answers__created_by__userprofile','answers__answer_comments')

without the select_related and prefetch_related the view does 42 queries in 23.36MS, and with those added, it decreases to 10 queries in 7.91MS, looking at this data, I think those functions are really great.

So my question is this: Is there any downside to using these two functions? Should I not join this many tables in one go?

Body:
Simple answer

No, there isn't a downside

Real Answer

Prefetch related does the join on the python side. Most of the time this is fine but always profile. You may also find the Prefetch object really helpful when you need to tune your DB access further.

Select related does what you would expect (it creates the join statements and flushes that to the database) and will perform really well most if the time.

In scaling up, the joins may become more of a hinderance - you'll want to maybe alter your data model by denormalizing, implementing a caching layer, separating the calls by resource type, etc..

Side Note

You'll want to start putting these bigger queries into your model manager so the view can just call a method and you can tune away behind the scenes.

e.g. (Note, there are newer ways of doing this with queryset subclasses, etc..)

# models.py

class QuestionManager(models.Manager):
    def by_topic(self, topic):
        return self.filter(topic=topic).prefetch_related('...')

# views

def my_view(request, *args, **kwargs):
    # get the topic however
    topic = get_topic(kwargs.get('topic')
    Question.objects.by_topic(topic)


问:
How do I stream a file attachment to a response in node.js?
Using node.js/Express.js, I would like to make a call to an API, write the response of that call to a file, then serve that file as an attachment to the client.  The API call returns the correct data and that data is successfully being written to file; the issue is that when I try and stream that file from disk to the client, the file attachment that gets served is empty.  Here is the body of my route handler:

```<code>// Make a request to an API, then pipe the response to a file. (This works)
request({
  url: 'http://localhost:5000/execute_least_squares',
  qs: query
}).pipe(fs.createWriteStream('./tmp/predictions/prediction_1.csv',
  {defaultEncoding: 'utf8'}));

// Add some headers so the client know to serve file as attachment
res.writeHead(200, {
    "Content-Type": "text/csv",
    "Content-Disposition" : "attachment; filename=" +
    "prediction_1.csv"
});

// read from that file and pipe it to the response (doesn't work)
fs.createReadStream('./tmp/predictions/prediction_1.csv').pipe(res);
</code>```

Question:

Why is the response just returning a blank document to the client?

Considerations:

C1. Is this issue happening because by the time the last line tries to read the file the process of writing it hasn't begun?

C1.a) Doesn't the fact that createWriteStream and createReadStream are both async ensure that createWriteStream will precede createReadStream in the event loop?

C2. Could it be that the 'data' event is not being triggered correctly? Doesn't pipe abstract this away for you?

Thanks for your input.

答:
Try this :

```<code>var writableStream = fs.createWriteStream('./tmp/predictions/prediction_1.csv',
{ defaultEncoding: 'utf8' })

request({
    url: 'http://localhost:5000/execute_least_squares',
     qs: query
}).pipe(writableStream);

//event that gets called when the writing is complete
writableStream.on('finish',() => {
    res.writeHead(200, {
    "Content-Type": "text/csv",
    "Content-Disposition" : "attachment; filename=" +
    "prediction_1.csv"
});
    var readbleStream = fs.createReadStream('./tmp/predictions/prediction_1.csv')
   readableStream.pipe(res);
}
</code>```

You should capture the on.('error') for both streams (write and read)   so that you can return an suitable response (400 or else).

For more info :

Read the Node.js Stream documentation

Considerations :

Is this issue happening because by the time the last line tries to read the file the process of writing it hasn't begun?

A: Yes. Or another possibility is that the request has not finished.

Doesn't the fact that createWriteStream and createReadStream are both async ensure that createWriteStream will precede createReadStream in the event loop?

A: From what I have read in the docs createWriteStream and createReadStream are sync and they only return a WriteStream/ReadStream object.

Could it be that the 'data' event is not being triggered correctly? Doesn't pipe abstract this away for you?

A: If you are talking about this code:

```<code>request({
    url: 'http://localhost:5000/execute_least_squares',
    qs: query
}).pipe(fs.createWriteStream('./tmp/predictions/prediction_1.csv',
   {defaultEncoding: 'utf8'}));
</code>```

It works according to the request documentation. If you were talking about something else please explain it in more detail.

Body:
Using node.js/Express.js, I would like to make a call to an API, write the response of that call to a file, then serve that file as an attachment to the client.  The API call returns the correct data and that data is successfully being written to file; the issue is that when I try and stream that file from disk to the client, the file attachment that gets served is empty.  Here is the body of my route handler:

// Make a request to an API, then pipe the response to a file. (This works)
request({
  url: 'http://localhost:5000/execute_least_squares',
  qs: query
}).pipe(fs.createWriteStream('./tmp/predictions/prediction_1.csv',
  {defaultEncoding: 'utf8'}));

// Add some headers so the client know to serve file as attachment
res.writeHead(200, {
    "Content-Type": "text/csv",
    "Content-Disposition" : "attachment; filename=" +
    "prediction_1.csv"
});

// read from that file and pipe it to the response (doesn't work)
fs.createReadStream('./tmp/predictions/prediction_1.csv').pipe(res);

Question:

Why is the response just returning a blank document to the client?

Considerations:

C1. Is this issue happening because by the time the last line tries to read the file the process of writing it hasn't begun?

C1.a) Doesn't the fact that createWriteStream and createReadStream are both async ensure that createWriteStream will precede createReadStream in the event loop?

C2. Could it be that the 'data' event is not being triggered correctly? Doesn't pipe abstract this away for you?

Thanks for your input.

Body:
Try this :

var writableStream = fs.createWriteStream('./tmp/predictions/prediction_1.csv',
{ defaultEncoding: 'utf8' })

request({
    url: 'http://localhost:5000/execute_least_squares',
     qs: query
}).pipe(writableStream);

//event that gets called when the writing is complete
writableStream.on('finish',() => {
    res.writeHead(200, {
    "Content-Type": "text/csv",
    "Content-Disposition" : "attachment; filename=" +
    "prediction_1.csv"
});
    var readbleStream = fs.createReadStream('./tmp/predictions/prediction_1.csv')
   readableStream.pipe(res);
}

You should capture the on.('error') for both streams (write and read)   so that you can return an suitable response (400 or else).

For more info :

Read the Node.js Stream documentation

Considerations :

Is this issue happening because by the time the last line tries to read the file the process of writing it hasn't begun?

A: Yes. Or another possibility is that the request has not finished.

Doesn't the fact that createWriteStream and createReadStream are both async ensure that createWriteStream will precede createReadStream in the event loop?

A: From what I have read in the docs createWriteStream and createReadStream are sync and they only return a WriteStream/ReadStream object.

Could it be that the 'data' event is not being triggered correctly? Doesn't pipe abstract this away for you?

A: If you are talking about this code:

request({
    url: 'http://localhost:5000/execute_least_squares',
    qs: query
}).pipe(fs.createWriteStream('./tmp/predictions/prediction_1.csv',
   {defaultEncoding: 'utf8'}));

It works according to the request documentation. If you were talking about something else please explain it in more detail.