问:
How internal working of memcache and redis is different
How redis performs below functionality internally.

Memory Management:
I know memcache does memory management using fixed size and frame and
fixed sized slab  inside frame.How different redis memory management is?

For eviction memcache uses LRU .For this each memcache node has Map and Doubly linked list.On read write operation both data structure is accesses using global lock. Again how Redis perform this? As Redis in single threaded locking for these data structure would not be required.

答:
First of all I'll suggest you to go through this post.
In that stackoverflow answer, you can see answer of your first point "Memory Management" along with many other detailed information.
Rest for your second point, I would like to tell that you can check default configuration file of redis from where you can manage different available behaviours.

This snippet is mentioned in redis configuration file:

```<code># MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
# is reached. You can select among five behaviors:
#
# volatile-lru -> remove the key with an expire set using an LRU algorithm
# allkeys-lru -> remove any key according to the LRU algorithm
# volatile-random -> remove a random key with an expire set
# allkeys-random -> remove a random key, any key
# volatile-ttl -> remove the key with the nearest expire time (minor TTL)
# noeviction -> don't expire at all, just return an error on write operations
</code>```

Hope that it will help you. Rest if I'm missing something then please update me with that.

Body:
First of all I'll suggest you to go through this post.
In that stackoverflow answer, you can see answer of your first point "Memory Management" along with many other detailed information.
Rest for your second point, I would like to tell that you can check default configuration file of redis from where you can manage different available behaviours.

This snippet is mentioned in redis configuration file:

# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
# is reached. You can select among five behaviors:
#
# volatile-lru -> remove the key with an expire set using an LRU algorithm
# allkeys-lru -> remove any key according to the LRU algorithm
# volatile-random -> remove a random key with an expire set
# allkeys-random -> remove a random key, any key
# volatile-ttl -> remove the key with the nearest expire time (minor TTL)
# noeviction -> don't expire at all, just return an error on write operations

Hope that it will help you. Rest if I'm missing something then please update me with that.


来源: stackexchange

问:
EditText is not showing hint as well as text when typing
EditText is not showing hint as well as text when typing.
Here is code:

```<code><EditText
        android:id="@+id/passwordText"
        android:layout_width="135dp"
        android:layout_height="18dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="46dp"
        android:hint="Enter your password."
        android:text="Enter password"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/emailText"
        tools:text="Enter Password"/>
</code>```

I also tried to set color by code but it didn't worked:

final EditText passwordText = (EditText)
  findViewById(R.id.passwordText);
          passwordText.setTextColor(Color.BLACK);
          passwordText.setHint("Enter your Password.");
          passwordText.setHintTextColor(Color.BLACK);

Note: I'm using android studio 2.3.3;

Any help will be appreciated.

答:
Change height and try</p>

```<code><EditText
        android:id="@+id/passwordText"
        android:layout_width="135dp"
        android:layout_height="40dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="46dp"
        android:hint="Enter your password."
        android:text="Enter password"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/emailText"
        tools:text="Enter Password"/>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
EditText is not showing hint as well as text when typing.
Here is code:

<EditText
        android:id="@+id/passwordText"
        android:layout_width="135dp"
        android:layout_height="18dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="46dp"
        android:hint="Enter your password."
        android:text="Enter password"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/emailText"
        tools:text="Enter Password"/>

I also tried to set color by code but it didn't worked:

final EditText passwordText = (EditText)
  findViewById(R.id.passwordText);
          passwordText.setTextColor(Color.BLACK);
          passwordText.setHint("Enter your Password.");
          passwordText.setHintTextColor(Color.BLACK);

Note: I'm using android studio 2.3.3;

Any help will be appreciated.

Body:
Change height and try

<EditText
        android:id="@+id/passwordText"
        android:layout_width="135dp"
        android:layout_height="40dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="46dp"
        android:hint="Enter your password."
        android:text="Enter password"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/emailText"
        tools:text="Enter Password"/>


答:
because you are using both text and hint, delete the text tag change height to wrap_content too

```<code><EditText
        android:id="@+id/passwordText"
        android:layout_width="135dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="46dp"
        android:hint="Enter your password."
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/emailText"
/>
</code>```

Title: EditText is not showing hint as well as text when typing

Body:
because you are using both text and hint, delete the text tag change height to wrap_content too

<EditText
        android:id="@+id/passwordText"
        android:layout_width="135dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="46dp"
        android:hint="Enter your password."
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/emailText"
/>


问:
Is there a way to get offset for each message consumed in kafka streams?
In order to avoid reading of messages which are processed but missed to get committed when a KAFKA STREAMS is killed , I want to get the offset for each message along with the key and value so that I can store it somewhere and use it to avoid the reprocessing of  already processed messages.</p>

答:
Yes, this is possible.  See the FAQ entry at http://docs.confluent.io/current/streams/faq.html#accessing-record-metadata-such-as-topic-partition-and-offset-information.

I'll copy-paste the key information below:

Accessing record metadata such as topic, partition, and offset information?

Record metadata is accessible through the Processor API.
  It is also accessible indirectly through the DSL thanks to its
  Processor API integration.

With the Processor API, you can access record metadata through a
  ProcessorContext. You can store a reference to the context in an
  instance field of your processor during Processor#init(), and then
  query the processor context within Processor#process(), for example
  (same for Transformer). The context is updated automatically to match
  the record that is currently being processed, which means that methods
  such as ProcessorContext#partition() always return the current
  record’s metadata. Some caveats apply when calling the processor
  context within punctuate(), see the Javadocs for details.

If you use the DSL combined with a custom Transformer, for example,
  you could transform an input record’s value to also include partition
  and offset metadata, and subsequent DSL operations such as map or
  filter could then leverage this information.


问:
bind label to model length in sapui5
I am trying to bind a label to length of model defined in component.js. I can get the length in component, but when I try to map the same inside view it returns undefined. I have binded table to that model and am able to get data inside table.

Here is my code in component.js

```<code>var oModel = new sap.ui.model.json.JSONModel("model/data.json");
var datacount ;
oModel.attachRequestCompleted(function() {
     // console.log(this.getData().length);
     datacount = this.getData().length; //I am able to get length here
    oModel.setData({
        struct : this.getData(),
        number: datacount
    });
});
this.setModel(oModel, "MyJsonData");
</code>```

Inside view:

```<code>oTable.bindRows("MyJsonData>/struct/");
var lbl = new sap.ui.commons.Label({text: "{MyJsonData>/number}"});
</code>```

The label is not returning anything?

答:
Your model MyJsonData is not yet available when you are declaring the Label.

I tried with a similar example and observed this control flow:

Component init() -> view Controller -> setModel() statement -> requestCompleted handler

So if I plot a timeline this is what I'd see:

Your Label gets instantiated when there is no model available with Component.

Your model gets created without the number property.

You add a number property to the existing model MyJsonData.

The solution:

Do everything in your view's controller and inside the requestCompleted handler.

The requestCompleted event works asynchronously i.e. it allows further execution while waiting for data to load. So any statements outside the handler method would get executed before the handler does its magic.

Note:

You can use controller.getOwnerComponent() to retrieve an instance of your Component and set your model on it.

Your event handler wouldn't know what oModel is. You have to call setData on this.

If you are trying to retrieve the text of the Label without first adding it to the UI DOM then make sure you explicitly bind your model to it.

In other words:

```<code>var lbl = new sap.ui.commons.Label({
    text: "{MyJsonData>/number}"
});
console.log(lbl.getText());
</code>```

won't work because you haven't yet added lbl to the view and so it doesn't have access to the models. However, it would certainly print the text in your browser console if you did:

```<code>var lbl = new sap.ui.commons.Label({
    text: "{MyJsonData>/number}"
}).setModel(oModel, "MyJsonData");
</code>```

Lastly, nobody uses sap.ui.commons anymore. I advise you to switch to sap.m.

Cheers!

Title: bind label to model length in sapui5

Body:
I am trying to bind a label to length of model defined in component.js. I can get the length in component, but when I try to map the same inside view it returns undefined. I have binded table to that model and am able to get data inside table.

Here is my code in component.js

var oModel = new sap.ui.model.json.JSONModel("model/data.json");
var datacount ;
oModel.attachRequestCompleted(function() {
     // console.log(this.getData().length);
     datacount = this.getData().length; //I am able to get length here
    oModel.setData({
        struct : this.getData(),
        number: datacount
    });
});
this.setModel(oModel, "MyJsonData");

Inside view:

oTable.bindRows("MyJsonData>/struct/");
var lbl = new sap.ui.commons.Label({text: "{MyJsonData>/number}"});

The label is not returning anything?

Body:
Your model MyJsonData is not yet available when you are declaring the Label.

I tried with a similar example and observed this control flow:

Component init() -> view Controller -> setModel() statement -> requestCompleted handler

So if I plot a timeline this is what I'd see:

Your Label gets instantiated when there is no model available with Component.

Your model gets created without the number property.

You add a number property to the existing model MyJsonData.

The solution:

Do everything in your view's controller and inside the requestCompleted handler.

The requestCompleted event works asynchronously i.e. it allows further execution while waiting for data to load. So any statements outside the handler method would get executed before the handler does its magic.

Note:

You can use controller.getOwnerComponent() to retrieve an instance of your Component and set your model on it.

Your event handler wouldn't know what oModel is. You have to call setData on this.

If you are trying to retrieve the text of the Label without first adding it to the UI DOM then make sure you explicitly bind your model to it.

In other words:

var lbl = new sap.ui.commons.Label({
    text: "{MyJsonData>/number}"
});
console.log(lbl.getText());

won't work because you haven't yet added lbl to the view and so it doesn't have access to the models. However, it would certainly print the text in your browser console if you did:

var lbl = new sap.ui.commons.Label({
    text: "{MyJsonData>/number}"
}).setModel(oModel, "MyJsonData");

Lastly, nobody uses sap.ui.commons anymore. I advise you to switch to sap.m.

Cheers!


问:
How do I make site info appear in the address bar of a browser
I saw this :

Some site info appears. I use https and i only see "secure" on this place. How do they do this?

答:
Certificates with extended verification.
These are the most expensive certificates and get them the hardest. In such certificates there is a so-called "green bar" - that is, at the entrance is not a site where such a certificate is installed in the address bar of the visitor's browser, a green line appears in which the name of the organization that received the certificate will be indicated.</p>


问:
Can someone explain to me the difference between activation and recurrent activation arguments passed in initialising keras lstm layer?
Can someone explain to me the difference between activation and recurrent activation arguments passed in initialising keras lstm layer?

According to my understanding LSTM has 4 layers. Please explain what are th e default activation functions of each layer if I do not pass any activation argument to the LSTM constructor?

答:
So when a LSTM layer is called two kind of operations are performed:

inner recurrent activations compuations which actualizes inner memory cell - for this recurrent_activation is used (default value is a hard_sigmoid).

the final output of layer is computed. Here you are applying an activation function (default value is tanh).

Here you could read the details.


问:
Using DbGeography Tyes with Entity Framework 7 and vNext
I am building an application that will use Spatial Data with vNext and EF7. In the past with the current version of asp.net and EF6 I have used System.Data.Entity.Spatial in order to use the DbGeography however now this namespace is not available.

Currently I have the following nuget packages in my project.json file:

"EntityFramework.Commands": "7.0.0-rc1-final"

"EntityFramework.Core": "7.0.0-rc1-final"

"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final"

Is there a package that I am missing, or is support for Spatial Data Types with SQL Server something that has not been implemented yet? I notice that there is a backlog feature marked ‘Modelling - Complex/value types’ on the EF7 github Roadmap, but I don’t see any specifics.

If there is a package I am missing, what is the package so I can include it.

Many thanks in advance

答:
Spatial data isn't supported yet by Entity Framework Core.

"Spatial is not planned for 2.0 and we haven’t finished planning for the version after. It might be a good idea to post more details about what you would like to have in spatial support at github.com/aspnet/EntityFramework/issues/1100, e.g. do you use specific spatial functions or do you need rich spatial types with all kinds of spatial functionality, would you use this only with a specific database or do you need to write the same code against multiple databases? Etc."

Source:

http://github.com/aspnet/EntityFramework/issues/1100
https://blogs.msdn.microsoft.com/dotnet/2017/06/28/announcing-ef-core-2-0-preview-2/

Altought I have made a temporary workaround to include Geography column and use it in EF Core 1.0.0 and above.
(It's not perfect, but it will do for now)

See the accepted answer on:

Entity Framework Core: Type Udt is not supported on this platform. (Spatial Data - Geography)


问:
Appengine Request Duration for Backend Services
I am in the process of migrating an Appengine Java application from Backends to modules / services.  One thing that we currently use our backend for is uploads of data that take longer than the 60 second request duration limit.  So far, I have been unable to find a way to configure services to accept requests longer than 60 seconds without returning a CancellationException.  Surely Appengine did not drop support for longer requests with the conversion to services?  How can they be configured?</p>

答:
please have a look at the following link

https://cloud.google.com/appengine/docs/standard/java/an-overview-of-app-engine

you need to configure your module as manual or basic scaling


问:
Manage abstract classes in std container
After a lot of research I still don't understand how to deal with an abstract class collection with smart pointers.

Here are the errors I got:

```<code>error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Shape; _Dp = std::default_delete<Shape>]'
   base_ptr s = shapes.front();

error: no matching function for call to 'std::unique_ptr<Shape>::unique_ptr(Shape&)'
   shapes.push(base_ptr(b));
</code>```

By compiling the minimal code to replicate the error (code online avaiable).

```<code>    #include <queue>
    #include <memory>

    class Shape {
    public:
        virtual int getPerimeter() =0;
    };

    typedef std::unique_ptr<Shape> base_ptr;

    class Circle : public Shape {
    public:
        virtual int getPerimeter() { return 1; };
    };

    class Square : public Shape {
    public:
        virtual int getPerimeter() { return 0; };
    };

    class ShapeManager {
    public:
        ShapeManager();
        void useShape() {
            if(shapes.empty())
                throw "Work stack is empty.";

            base_ptr s = shapes.front();
            s->getPerimeter();
            shapes.pop();
        }

        void submitShape(Shape &b) {
            shapes.push(base_ptr(b));
        }
    private:
        std::queue<base_ptr> shapes;
    };

    int main(int argc, char **argv) {
        ShapeManager s();
        Circle c;
        s.submitShape(c);
        s.useShape();
        return 1;
    }
</code>```

It works if I declare the queue as queue<Shape*> but I don't want to deal with pointers -meaning *.

EDIT, this code compiles. Thanks everyone. This article suggested by Guillaume Racicot helps seeing clearer the situation.

```<code>#include <queue>
#include <memory>

class Shape {
public:
    virtual int getPerimeter() =0;
};

typedef std::unique_ptr<Shape> base_ptr;

class Circle : public Shape {
public:
    Circle() {};
    virtual int getPerimeter() { return 1; };
};

class Square : public Shape {
public:
    virtual int getPerimeter() { return 0; };
};

class ShapeManager {
public:
    ShapeManager();
    void useShape() {
        if(shapes.empty())
            throw "Work stack is empty.";

        base_ptr s = std::move(shapes.front());
        s->getPerimeter();
        shapes.pop();
    }

    void submitShape(base_ptr b) {
        shapes.push(std::move(b));
    }
private:
    std::queue<base_ptr> shapes;
};

int main(int argc, char **argv) {
    ShapeManager s;
    base_ptr c = std::make_unique<Circle>();
    s.submitShape(std::move(c));
    s.useShape();
    return 1;
}
</code>```

答:
The container is a distraction. The problem is that unique_ptr is not copyable; if it were, it wouldn't be unique. So you probably need to add a call to std::move:

```<code>base_ptr s = std::move(shapes.front());
</code>```

This means something different from what the original code might have been intended to do; it removes the object from the container. If that's not what you wanted, then std::move isn't the right answer and, probably, unique_ptr is not the right mechanism.

Body:
After a lot of research I still don't understand how to deal with an abstract class collection with smart pointers.

Here are the errors I got:

error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Shape; _Dp = std::default_delete<Shape>]'
   base_ptr s = shapes.front();

error: no matching function for call to 'std::unique_ptr<Shape>::unique_ptr(Shape&)'
   shapes.push(base_ptr(b));

By compiling the minimal code to replicate the error (code online avaiable).

    #include <queue>
    #include <memory>

    class Shape {
    public:
        virtual int getPerimeter() =0;
    };

    typedef std::unique_ptr<Shape> base_ptr;

    class Circle : public Shape {
    public:
        virtual int getPerimeter() { return 1; };
    };

    class Square : public Shape {
    public:
        virtual int getPerimeter() { return 0; };
    };

    class ShapeManager {
    public:
        ShapeManager();
        void useShape() {
            if(shapes.empty())
                throw "Work stack is empty.";

            base_ptr s = shapes.front();
            s->getPerimeter();
            shapes.pop();
        }

        void submitShape(Shape &b) {
            shapes.push(base_ptr(b));
        }
    private:
        std::queue<base_ptr> shapes;
    };

    int main(int argc, char **argv) {
        ShapeManager s();
        Circle c;
        s.submitShape(c);
        s.useShape();
        return 1;
    }

It works if I declare the queue as queue<Shape*> but I don't want to deal with pointers -meaning *.

EDIT, this code compiles. Thanks everyone. This article suggested by Guillaume Racicot helps seeing clearer the situation.

#include <queue>
#include <memory>

class Shape {
public:
    virtual int getPerimeter() =0;
};

typedef std::unique_ptr<Shape> base_ptr;

class Circle : public Shape {
public:
    Circle() {};
    virtual int getPerimeter() { return 1; };
};

class Square : public Shape {
public:
    virtual int getPerimeter() { return 0; };
};

class ShapeManager {
public:
    ShapeManager();
    void useShape() {
        if(shapes.empty())
            throw "Work stack is empty.";

        base_ptr s = std::move(shapes.front());
        s->getPerimeter();
        shapes.pop();
    }

    void submitShape(base_ptr b) {
        shapes.push(std::move(b));
    }
private:
    std::queue<base_ptr> shapes;
};

int main(int argc, char **argv) {
    ShapeManager s;
    base_ptr c = std::make_unique<Circle>();
    s.submitShape(std::move(c));
    s.useShape();
    return 1;
}

Body:
The container is a distraction. The problem is that unique_ptr is not copyable; if it were, it wouldn't be unique. So you probably need to add a call to std::move:

base_ptr s = std::move(shapes.front());

This means something different from what the original code might have been intended to do; it removes the object from the container. If that's not what you wanted, then std::move isn't the right answer and, probably, unique_ptr is not the right mechanism.


问:
Azure: How to create the WADLogsTable for capturing diagnostics code?
I have a worker role that I would like to get diagnoistics feedback on... after adding the appropriate connection string to the ServiceConfiguration.cscfg and the following code:

```<code>//DiagnosticMonitor.Start("DiagnosticsConnectionString");
DiagnosticMonitorConfiguration diagConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();
diagConfig.WindowsEventLog.DataSources.Add("Application!*");
diagConfig.WindowsEventLog.ScheduledTransferPeriod = System.TimeSpan.FromMinutes(5.0);
diagConfig.Logs.ScheduledTransferPeriod = System.TimeSpan.FromMinutes(5.0);

Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitor.Start("DiagnosticsConnectionString", diagConfig);
CrashDumps.EnableCollection(true);
</code>```

When I call "System.Diagnostics.Trace.TraceInformation("test log") I expect to be able to find the record in the WADLogsTable of the target Azure Storage Account.  Howver, the table doesn't exist- how is it created?  None of the documentation I've read covers this.

Thanks in advance,

答:
You'll want to set a log level filter, like:

```<code>diagConfig.Logs.ScheduledTransferLogLevelFilter = LogLevel.Information;
</code>```

I have a more detailed answer here.

Note that occasionally, in the simulation environment, the tables don't get created immediately.

Body:
I have a worker role that I would like to get diagnoistics feedback on... after adding the appropriate connection string to the ServiceConfiguration.cscfg and the following code:

//DiagnosticMonitor.Start("DiagnosticsConnectionString");
DiagnosticMonitorConfiguration diagConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();
diagConfig.WindowsEventLog.DataSources.Add("Application!*");
diagConfig.WindowsEventLog.ScheduledTransferPeriod = System.TimeSpan.FromMinutes(5.0);
diagConfig.Logs.ScheduledTransferPeriod = System.TimeSpan.FromMinutes(5.0);

Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitor.Start("DiagnosticsConnectionString", diagConfig);
CrashDumps.EnableCollection(true);

When I call "System.Diagnostics.Trace.TraceInformation("test log") I expect to be able to find the record in the WADLogsTable of the target Azure Storage Account.  Howver, the table doesn't exist- how is it created?  None of the documentation I've read covers this.

Thanks in advance,

Body:
You'll want to set a log level filter, like:

diagConfig.Logs.ScheduledTransferLogLevelFilter = LogLevel.Information;

I have a more detailed answer here.

Note that occasionally, in the simulation environment, the tables don't get created immediately.

ContentLicense: CC BY-SA 2.5


问:
Python Twisted - How to send the data over the connected socket connections?
I've a server as follow:-

```<code>class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        self.sendMessage(payload, isBinary)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))
</code>```

The above code receives the message and replies back with the same message. However, my use case is different.

I'm processing some data, storing it into the DB and then finally want to send the data to the connected clients, or one type of data to specific set of connected clients and the other type to another.

How can I do it? How can I call sendMessage function outside the class?

答:
You need to subclass WebSocketServerFactory to keep track of your connections.

Take a look at this example, which stores all the open connections in a list and broadcasts to all of them. You could easily adapt it to send specific messages to certain clients.

Body:
I've a server as follow:-

class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        self.sendMessage(payload, isBinary)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))

The above code receives the message and replies back with the same message. However, my use case is different.

I'm processing some data, storing it into the DB and then finally want to send the data to the connected clients, or one type of data to specific set of connected clients and the other type to another.

How can I do it? How can I call sendMessage function outside the class?


答:
You are using text and hint both together so hint is not visible.

Remove 'text' tag into the EditText :'android:text="Enter password"' and  'tools:text="Enter Password"', if text is set then hint will not display.

```<code><EditText
        android:id="@+id/passwordText"
        android:layout_width="135dp"
        android:layout_height="18dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="46dp"
        android:hint="Enter your password."
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/emailText"
/>
</code>```

Hope it will help..

Body:
You are using text and hint both together so hint is not visible.

Remove 'text' tag into the EditText :'android:text="Enter password"' and  'tools:text="Enter Password"', if text is set then hint will not display.

<EditText
        android:id="@+id/passwordText"
        android:layout_width="135dp"
        android:layout_height="18dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="46dp"
        android:hint="Enter your password."
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/emailText"
/>

Hope it will help..

ContentLicense: CC BY-SA 4.0


问:
sending named Mulitpart Data wit HttpClient
I try to Send Multipart Content as a Post to an WebService using c# HttpClient

My Code is the Following

```<code>public string UploadDocument(Stream stream)
{

  MultipartContent multipart = new MultipartContent();
  //multipart.Add(new StreamContent(stream), "importFile");
  StreamContent content = new StreamContent(stream);
  multipart.Add(content);

  Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

  HttpResponseMessage response = Client.PostAsync("URL to webservice", multipart).Result;
  string result = response.Content.ReadAsStringAsync().Result;

  //Wirft eine Exception wenn der StatusCode nicht 200 (OK) ist.
  response.EnsureSuccessStatusCode();

  return result;

}
</code>```

I Need the Stream Content to be named, how can i do it.

I found a Java Way to do it, but in C# I don't find a Parameter "Name"

Here the Java Example (see "importFile")

```<code>httpRequest = new HttpPostwebviewer/?action=import");
    // set headers
    httpRequest.setHeader(HEADER_NAME_ACCEPT, "application/json");
    // prepare upload entity
    MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
    meBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    meBuilder.setCharset(Consts.UTF_8);
    meBuilder.addPart("importFile", contentBody);
    // build upload entity
    HttpEntity uploadEntity = meBuilder.build();
    // set properties to http request
    ((HttpPost) httpRequest).setEntity(uploadEntity);
</code>```

答:
You can use  System.Net.HttpWebRequest to do the same, Below is the code that I am using:</p>

```<code> public static void UploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
    {
        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
        url = handlerLocation + url;
        HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
        wr.ContentType = "multipart/form-data; boundary=" + boundary;
        wr.Method = "POST";
        wr.KeepAlive = true;
        wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

        Stream rs = wr.GetRequestStream();

        string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
        foreach (string key in nvc.Keys)
        {
            rs.Write(boundarybytes, 0, boundarybytes.Length);
            string formitem = string.Format(formdataTemplate, key, nvc[key]);
            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
            rs.Write(formitembytes, 0, formitembytes.Length);
        }
        rs.Write(boundarybytes, 0, boundarybytes.Length);

        string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
        string header = string.Format(headerTemplate, paramName, file, contentType);
        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
        rs.Write(headerbytes, 0, headerbytes.Length);

        FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            rs.Write(buffer, 0, bytesRead);
        }
        fileStream.Close();

        byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
        rs.Write(trailer, 0, trailer.Length);
        rs.Close();

        WebResponse wresp = null;
        try
        {
            wresp = wr.GetResponse();
            Stream stream2 = wresp.GetResponseStream();
            StreamReader reader2 = new StreamReader(stream2);
        }
        catch (Exception ex)
        {
            //WriteTrace(ex.Message);
            if (wresp != null)
            {
                wresp.Close();
                wresp = null;
            }
        }
        finally
        {
            wr = null;
        }
    }
</code>```

Body:
I try to Send Multipart Content as a Post to an WebService using c# HttpClient

My Code is the Following

public string UploadDocument(Stream stream)
{

  MultipartContent multipart = new MultipartContent();
  //multipart.Add(new StreamContent(stream), "importFile");
  StreamContent content = new StreamContent(stream);
  multipart.Add(content);

  Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

  HttpResponseMessage response = Client.PostAsync("URL to webservice", multipart).Result;
  string result = response.Content.ReadAsStringAsync().Result;

  //Wirft eine Exception wenn der StatusCode nicht 200 (OK) ist.
  response.EnsureSuccessStatusCode();

  return result;

}

I Need the Stream Content to be named, how can i do it.

I found a Java Way to do it, but in C# I don't find a Parameter "Name"

Here the Java Example (see "importFile")

httpRequest = new HttpPostwebviewer/?action=import");
    // set headers
    httpRequest.setHeader(HEADER_NAME_ACCEPT, "application/json");
    // prepare upload entity
    MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
    meBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    meBuilder.setCharset(Consts.UTF_8);
    meBuilder.addPart("importFile", contentBody);
    // build upload entity
    HttpEntity uploadEntity = meBuilder.build();
    // set properties to http request
    ((HttpPost) httpRequest).setEntity(uploadEntity);

Body:
You can use  System.Net.HttpWebRequest to do the same, Below is the code that I am using:

 public static void UploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
    {
        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
        url = handlerLocation + url;
        HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
        wr.ContentType = "multipart/form-data; boundary=" + boundary;
        wr.Method = "POST";
        wr.KeepAlive = true;
        wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

        Stream rs = wr.GetRequestStream();

        string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
        foreach (string key in nvc.Keys)
        {
            rs.Write(boundarybytes, 0, boundarybytes.Length);
            string formitem = string.Format(formdataTemplate, key, nvc[key]);
            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
            rs.Write(formitembytes, 0, formitembytes.Length);
        }
        rs.Write(boundarybytes, 0, boundarybytes.Length);

        string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
        string header = string.Format(headerTemplate, paramName, file, contentType);
        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
        rs.Write(headerbytes, 0, headerbytes.Length);

        FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            rs.Write(buffer, 0, bytesRead);
        }
        fileStream.Close();

        byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
        rs.Write(trailer, 0, trailer.Length);
        rs.Close();

        WebResponse wresp = null;
        try
        {
            wresp = wr.GetResponse();
            Stream stream2 = wresp.GetResponseStream();
            StreamReader reader2 = new StreamReader(stream2);
        }
        catch (Exception ex)
        {
            //WriteTrace(ex.Message);
            if (wresp != null)
            {
                wresp.Close();
                wresp = null;
            }
        }
        finally
        {
            wr = null;
        }
    }


问:
getting same value in every hashmap variable.why?
code is:

```<code>HashMap<String, String> map = new HashMap<>();
JSONObject jsonResponse = new JSONObject(response);
HashMap<String, String> question1 = readJsonObject(jsonResponse.getJSONObject("1"), map);
HashMap<String, String> question2 = readJsonObject(jsonResponse.getJSONObject("2"), map);
HashMap<String, String> question3 = readJsonObject(jsonResponse.getJSONObject("3"), map);

q1.setText(question1.get("question"));    //q1,q2,q3 are textviews
q2.setText(question2.get("question"));
q3.setText(question3.get("question"));
</code>```

this is readJsonObject method/function:

```<code>private HashMap<String,String> readJsonObject(JSONObject jsonObject,HashMap<String, String> map ) throws JSONException {
    map.put("question", jsonObject.getString("question"));
    map.put("optiona", jsonObject.getString("optiona"));
    map.put("optionb", jsonObject.getString("optionb"));
    map.put("optionc", jsonObject.getString("optionc"));
    map.put("optiond", jsonObject.getString("optiond"));
    map.put("correct", jsonObject.getString("correct"));
    return map;
}
</code>```

but i am getting same string value in q1 q2 q4 TextViews. please solve this.

response getting from the server:

```<code>{
"0":[],

"success":true,

"1":{ "question":"question3",
      "optiona":"optiona",
      "optionb":"optionb",
      "optionc":"optionc",
      "optiond":"optiond",
      "correct":"optiona"},

"2":{ "question":"question1",
      "optiona":"optiona",
      "optionb":"optionb",
      "optionc":"optionc",
      "optiond":"optiond",
      "correct":"optiond"},

"3":{ "question":"question4",
      "optiona":"optiona",
      "optionb":"optionb",
      "optionc":"optionc",
      "optiond":"optiond",
      "correct":"optionc"}
}
</code>```

getting different value from server in response but q1,q2,q3 showing same values. why? please solve this

if i am adding map.clear() after every readJsonObject() textview becomes blank,,,,, and if i add map.clear in readJsonObject() no change still same value in q1,q2,q3

if i use different hashmap in every time calling readJsonObject getting right answer but i think it is not efficient. right?

答:
Change the method to this</p>

```<code>private HashMap<String,String> readJsonObject(JSONObject jsonObject ) throws JSOException {
HashMap<String, String> tempMap = new HashMap<>();
tempMap.put("question", jsonObject.getString("question"));
tempMap.put("optiona", jsonObject.getString("optiona"));
tempMap.put("optionb", jsonObject.getString("optionb"));
tempMap.put("optionc", jsonObject.getString("optionc"));
tempMap.put("optiond", jsonObject.getString("optiond"));
tempMap.put("correct", jsonObject.getString("correct"));
return tempMap;
}
</code>```

Body:
code is:

HashMap<String, String> map = new HashMap<>();
JSONObject jsonResponse = new JSONObject(response);
HashMap<String, String> question1 = readJsonObject(jsonResponse.getJSONObject("1"), map);
HashMap<String, String> question2 = readJsonObject(jsonResponse.getJSONObject("2"), map);
HashMap<String, String> question3 = readJsonObject(jsonResponse.getJSONObject("3"), map);

q1.setText(question1.get("question"));    //q1,q2,q3 are textviews
q2.setText(question2.get("question"));
q3.setText(question3.get("question"));

this is readJsonObject method/function:

private HashMap<String,String> readJsonObject(JSONObject jsonObject,HashMap<String, String> map ) throws JSONException {
    map.put("question", jsonObject.getString("question"));
    map.put("optiona", jsonObject.getString("optiona"));
    map.put("optionb", jsonObject.getString("optionb"));
    map.put("optionc", jsonObject.getString("optionc"));
    map.put("optiond", jsonObject.getString("optiond"));
    map.put("correct", jsonObject.getString("correct"));
    return map;
}

but i am getting same string value in q1 q2 q4 TextViews. please solve this.

response getting from the server:

{
"0":[],

"success":true,

"1":{ "question":"question3",
      "optiona":"optiona",
      "optionb":"optionb",
      "optionc":"optionc",
      "optiond":"optiond",
      "correct":"optiona"},

"2":{ "question":"question1",
      "optiona":"optiona",
      "optionb":"optionb",
      "optionc":"optionc",
      "optiond":"optiond",
      "correct":"optiond"},

"3":{ "question":"question4",
      "optiona":"optiona",
      "optionb":"optionb",
      "optionc":"optionc",
      "optiond":"optiond",
      "correct":"optionc"}
}

getting different value from server in response but q1,q2,q3 showing same values. why? please solve this

if i am adding map.clear() after every readJsonObject() textview becomes blank,,,,, and if i add map.clear in readJsonObject() no change still same value in q1,q2,q3

if i use different hashmap in every time calling readJsonObject getting right answer but i think it is not efficient. right?

Body:
Change the method to this

private HashMap<String,String> readJsonObject(JSONObject jsonObject ) throws JSOException {
HashMap<String, String> tempMap = new HashMap<>();
tempMap.put("question", jsonObject.getString("question"));
tempMap.put("optiona", jsonObject.getString("optiona"));
tempMap.put("optionb", jsonObject.getString("optionb"));
tempMap.put("optionc", jsonObject.getString("optionc"));
tempMap.put("optiond", jsonObject.getString("optiond"));
tempMap.put("correct", jsonObject.getString("correct"));
return tempMap;
}


问:
Why do statistics get out of date so quickly in SQL Server?
We have a somewhat complex SQL update query which gets run a few times a month.  Most of the time it seems to run really fast, but on some databases, it takes a really long time.  After running an "UPDATE STATISTICS" on the tables involved, the update immediately runs quickly again.  We finally set up a nightly task which calls UPDATE STATISTICS on all the tables in the database.  But that didn't seem to fix the problem.  We're still ending up having to run "UPDATE STATISTICS" manually each time.  Why would statistics go stale so quickly?

Here's approximately what the query looks like:

```<code>UPDATE DataTableA
SET DataTableA.IndexedColumn1 = 123456789, DataTableA.Flag1 = 1
FROM DataTableA WITH (INDEX(IX_DataTableA))
INNER JOIN GroupingTableA ON GroupingTableA.ForeignKey1 = GroupingTableA.PrimaryKey
INNER JOIN LookupTableA ON DataTableA.ForeignKey3 = LookupTableA.PrimaryKey
LEFT OUTER JOIN GroupingTableB ON DataTableA.IndexedColumn2 = GroupingTableB.IndexedColumn2
WHERE GroupingTableB.IndexedColumn1 = 123456789
AND DataTableA.IndexedColumn1 IS NULL
AND DataTableA.IndexedColumn2 IN ( ... 300 entries here ... )
AND DataTableA.Deleted = 0
AND GroupingTableA.Date <= GroupingTableB.EndDate
AND GroupingTableA.Date >= DATEADD(month, -1, GroupingTableB.StartDate)
AND LookupTableA.Column2 = 1
AND DataTableA.Status1 IN (1, 3)
AND DataTableA.Status2 NOT IN (1, 3, 9)
</code>```

DataTableA contains millions of rows.

GroupingTableA and GroupingTableB each contain tens of thousands of rows.

LookupTableA contains dozens of rows.

Index IX_DataTableA is an index on (IndexedColumn1 ASC, IndexedColumn2 ASC)

答:
I don't think your statistics will matter as much if you are forcing it to use a specific index (WITH (INDEX(IX_DataTableA))

Are you sure you know better than the optimizer?

I would start by looking at the execution plan for a fast update and a slow update.  Also, are the number of records being updated comparable for fast/slow queries?

Body:
We have a somewhat complex SQL update query which gets run a few times a month.  Most of the time it seems to run really fast, but on some databases, it takes a really long time.  After running an "UPDATE STATISTICS" on the tables involved, the update immediately runs quickly again.  We finally set up a nightly task which calls UPDATE STATISTICS on all the tables in the database.  But that didn't seem to fix the problem.  We're still ending up having to run "UPDATE STATISTICS" manually each time.  Why would statistics go stale so quickly?

Here's approximately what the query looks like:

UPDATE DataTableA
SET DataTableA.IndexedColumn1 = 123456789, DataTableA.Flag1 = 1
FROM DataTableA WITH (INDEX(IX_DataTableA))
INNER JOIN GroupingTableA ON GroupingTableA.ForeignKey1 = GroupingTableA.PrimaryKey
INNER JOIN LookupTableA ON DataTableA.ForeignKey3 = LookupTableA.PrimaryKey
LEFT OUTER JOIN GroupingTableB ON DataTableA.IndexedColumn2 = GroupingTableB.IndexedColumn2
WHERE GroupingTableB.IndexedColumn1 = 123456789
AND DataTableA.IndexedColumn1 IS NULL
AND DataTableA.IndexedColumn2 IN ( ... 300 entries here ... )
AND DataTableA.Deleted = 0
AND GroupingTableA.Date <= GroupingTableB.EndDate
AND GroupingTableA.Date >= DATEADD(month, -1, GroupingTableB.StartDate)
AND LookupTableA.Column2 = 1
AND DataTableA.Status1 IN (1, 3)
AND DataTableA.Status2 NOT IN (1, 3, 9)

DataTableA contains millions of rows.

GroupingTableA and GroupingTableB each contain tens of thousands of rows.

LookupTableA contains dozens of rows.

Index IX_DataTableA is an index on (IndexedColumn1 ASC, IndexedColumn2 ASC)


问:
Full height div responsiveness on landscape
I'm making a page that has a fixed navigation bar, full-screen background and a text in the middle of it. And I don't know how to make it responsive in landscape modes. On other versions, it behaves properly, but on a landscape, because the height is a lot smaller I assume, the text overlaps with a navigation bar. And it looks really messy.

Is there something I could change in my current code to fix this but to still retain full-screen div? I've looked everywhere, but nothing is really working.

This is my code so far:

.hero {
  height: 100vh;
  width: 100%;
  background: url('http://lorempixel.com/1200/600/') no-repeat;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  position: relative;
}

.headline {
  position: absolute;
  top: 50%;
  left: 0%;
  right: 0;
  transform: translate(0%, -50%);
  -webkit-transform: translate(0%, -50%);
}

.headline h2 {
  font-weight: 100;
  font-size: 48px;
  color: #212121;
  margin-bottom: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

<div class="hero">
  <nav class="navbar navbar-toggleable navbar-light bg-faded fixed-top">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
    Navbar

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item active">
          Home <span class="sr-only">(current)</span>
        </li>
        <li class="nav-item">
          Link
        </li>
        <li class="nav-item">
          Link
        </li>
      </ul>
      <form class="form-inline my-2 my-lg-0">
        <input class="form-control mr-sm-2" type="text" placeholder="Search">
        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
      </form>
    </div>
  </nav>

  <div class="headline text-center">
    <div>
      <h2>Lorem ipsum dolor sit amet, consectetur adipiscing elit. <br>Morbi in volutpat diam, ut laoreet magna. </h2>
      LINK ONE
      LINK TWO
    </div>
  </div>
  <!-- /.headline -->
</div>

<div style="height:900px"></div></code>```

答:
you can set css by using media query

For Exp :

```<code><style  type="text/css">
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px)
and (orientation : landscape) {
/* STYLES GO HERE */
height: 50vh;
}
</style>
</code>```

Body:
I'm making a page that has a fixed navigation bar, full-screen background and a text in the middle of it. And I don't know how to make it responsive in landscape modes. On other versions, it behaves properly, but on a landscape, because the height is a lot smaller I assume, the text overlaps with a navigation bar. And it looks really messy.

Is there something I could change in my current code to fix this but to still retain full-screen div? I've looked everywhere, but nothing is really working.

This is my code so far:

.hero {
  height: 100vh;
  width: 100%;
  background: url('http://lorempixel.com/1200/600/') no-repeat;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  position: relative;
}

.headline {
  position: absolute;
  top: 50%;
  left: 0%;
  right: 0;
  transform: translate(0%, -50%);
  -webkit-transform: translate(0%, -50%);
}

.headline h2 {
  font-weight: 100;
  font-size: 48px;
  color: #212121;
  margin-bottom: 10px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>
    Navbar

          Home (current)

          Link

          Link

      <form class="form-inline my-2 my-lg-0">
        <input class="form-control mr-sm-2" type="text" placeholder="Search">
        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
      </form>

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Morbi in volutpat diam, ut laoreet magna.

      LINK ONE
      LINK TWO

Body:
you can set css by using media query

For Exp :

<style  type="text/css">
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px)
and (orientation : landscape) {
/* STYLES GO HERE */
height: 50vh;
}
</style>


问:
Python: Checking the MX records for a list of domains keeps running, then stopping unless I hit Ctrl+C?
I have an Excel spreadsheet of domains that I need to check for a valid MX record. It runs for the first 10 lines, then pauses, then runs again for the next 10 lines, then pauses, then runs for the next 41 lines, then pauses, so there's not really a pattern that's making sense to me.

Do I need to tell it "Hey, if you don't find an mx record in x seconds, move on", or is there a better way entirely of running this code?

```<code>import pandas as pd
import dns.resolver

def getListOfDomains():

    data_df= pd.read_excel('check.xlsx') #todo: mainRun passes name of file into run
    df = pd.DataFrame(data_df)
    result= df.drop_duplicates(subset=['domain'])
    for index, row in df.iterrows():
        TryString= str(row['domain'])
         try:
            check= dns.resolver.query(TryString, 'MX')
            print check.response
        except:
            print "No MX here"
</code>```

答:
Question; Do I need to tell it "... x seconds, move on", ...

There is no guarantee that dns.resolver.query(... return immediately.

The Pause is normal behavior awaiting a response

Comment: ... how can I ... if no response is received in x seconds, continue?

Read this SO Answer:
Dnspython: Setting query timeout/lifetime

Body:
I have an Excel spreadsheet of domains that I need to check for a valid MX record. It runs for the first 10 lines, then pauses, then runs again for the next 10 lines, then pauses, then runs for the next 41 lines, then pauses, so there's not really a pattern that's making sense to me.

Do I need to tell it "Hey, if you don't find an mx record in x seconds, move on", or is there a better way entirely of running this code?

import pandas as pd
import dns.resolver

def getListOfDomains():

    data_df= pd.read_excel('check.xlsx') #todo: mainRun passes name of file into run
    df = pd.DataFrame(data_df)
    result= df.drop_duplicates(subset=['domain'])
    for index, row in df.iterrows():
        TryString= str(row['domain'])
         try:
            check= dns.resolver.query(TryString, 'MX')
            print check.response
        except:
            print "No MX here"


问:
How to reload in CRON job? (sending GET value on reload)
I am using this command to do CRON Job from Cpanel

```<code>wget http://example.com.com/test.php
</code>```

I have this Javascript code inside the PHP file, which reload the page.

```<code>echo'<script> location.replace("?number='.$requestsDone.'"); </script>';
</code>```

Now you may say, Just do the CRON job every minute. But, i guess, it will not do what I want, in my case.

As you can see, i am sending a GET value, when i reload the page. And that GET value is important part of my code.

So, I tried to run that page with that command (given above), but it do not reload the page (that Javascript code do not work).

So, what's the solution?

Let me know, if you did not understand.

答:
JavaScript will only work in a browser. You can use phantomJs and use it like cron if you would like to run javascript but it will be little complicated.

so you can just use curl in php to achieve your purpose of reloading page like this:

```<code>function curl_download($Url){

    // is cURL installed yet?
    if (!function_exists('curl_init')){
        die('Sorry cURL is not installed!');
    }

    // OK cool - then let's create a new cURL resource handle
    $ch = curl_init();

    // Now set some options (most are optional)

    // Set URL to download
    curl_setopt($ch, CURLOPT_URL, $Url);

    // Set a referer
    curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");

    // User agent
    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");

    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);

    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    // Download the given URL, and return output
    $output = curl_exec($ch);

    // Close the cURL resource, and free system resources
    curl_close($ch);

    return $output;
}

$output = curl_download("http://www.example.com/yourscript.php?number='$requestsDone'");
</code>```

Body:
I am using this command to do CRON Job from Cpanel

wget http://example.com.com/test.php

I have this Javascript code inside the PHP file, which reload the page.

echo'';

Now you may say, Just do the CRON job every minute. But, i guess, it will not do what I want, in my case.

As you can see, i am sending a GET value, when i reload the page. And that GET value is important part of my code.

So, I tried to run that page with that command (given above), but it do not reload the page (that Javascript code do not work).

So, what's the solution?

Let me know, if you did not understand.

Body:
JavaScript will only work in a browser. You can use phantomJs and use it like cron if you would like to run javascript but it will be little complicated.

so you can just use curl in php to achieve your purpose of reloading page like this:

function curl_download($Url){

    // is cURL installed yet?
    if (!function_exists('curl_init')){
        die('Sorry cURL is not installed!');
    }

    // OK cool - then let's create a new cURL resource handle
    $ch = curl_init();

    // Now set some options (most are optional)

    // Set URL to download
    curl_setopt($ch, CURLOPT_URL, $Url);

    // Set a referer
    curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");

    // User agent
    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");

    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);

    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    // Download the given URL, and return output
    $output = curl_exec($ch);

    // Close the cURL resource, and free system resources
    curl_close($ch);

    return $output;
}

$output = curl_download("http://www.example.com/yourscript.php?number='$requestsDone'");


问:
Zend_Session / Zend_Auth randomly throws Error Message ps_files_cleanup_dir: opendir(/var/lib/php5) failed: Permission denied (13)
I'm currently working on a new Application using (among other things) Zend_Auth but, for whatever reason, this Error Message is showing up at any location totally randomly (or so it seams)

Zend_Session::start() - /home/hannes/workspace/develop/library/Zend/Session.php(Line:480): Error #8 session_start() [function.session-start]: ps_files_cleanup_dir: opendir(/var/lib/php5) failed: Permission denied (13) Array

#0 /home/hannes/workspace/develop/library/Zend/Session/Namespace.php(143): Zend_Session::start(true)

#1 /home/hannes/workspace/develop/library/Zend/Auth/Storage/Session.php(87): Zend_Session_Namespace->__construct('Zend_Auth')

#2 /home/hannes/workspace/develop/library/Zend/Auth.php(91): Zend_Auth_Storage_Session->__construct()

#3 /home/hannes/workspace/develop/library/Zend/Auth.php(141): Zend_Auth->getStorage()

#4 /home/hannes/workspace/develop/xxxxxxx/application/controllers/AdminController.php(10): Zend_Auth->hasIdentity()

#5 /home/hannes/workspace/develop/library/Zend/Controller/Action.php(133): AdminController->init()

#6 /home/hannes/workspace/develop/library/Zend/Controller/Dispatcher/Standard.php(262): Zend_Controller_Action->__construct(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http), Array)

#7 /home/hannes/workspace/develop/library/Zend/Controller/Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))

#8 /home/hannes/workspace/develop/library/Zend/Application/Bootstrap/Bootstrap.php(97): Zend_Controller_Front->dispatch()

#9 /home/hannes/workspace/develop/library/Zend/Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()

#10 /home/hannes/workspace/develop/xxxxxxx/public/index.php(26): Zend_Application->run()

#11 {main}

答:
If you are using PHP 7 on Ubuntu, ensure the PHP sessions directory is owned by the web server:</p>
```<code>sudo chown www-data:www-data /var/lib/php/sessions
</code>```

Body:
If you are using PHP 7 on Ubuntu, ensure the PHP sessions directory is owned by the web server:

sudo chown www-data:www-data /var/lib/php/sessions


问:
Best way to import a package located in a sibling directory
My file stucture is :

```<code>top\
   my_package\
      __init__.py
      functions.py
   scripts\
      test.py
   main.py
</code>```

I would like to import the content of functions.py in test.py.

In main.py, I can import functions.py with from my_package.functions import ....
I was expecting to be able to import functions.py in test.py with something like from ..my_package.functions import ... but it raises the following error :

```<code>SystemError: Parent module '' not loaded, cannot perform relative import
</code>```

top directory shoudln't be a package because I want to be able to run main.py without being running a script in a package.

What is the proper/pythonic way import functions.py from test.py ?

I could add my_package to the PYTHONPATH, but my code would be less portable. I'm using Python 3.5

答:
This is happening because as far as python is concerned my_package and scripts directories are not related to each other.
To solve your problem you can add __init__.py to your top directory and try using

```<code>from ..function import *
</code>```

Body:
My file stucture is :

top\
   my_package\
      __init__.py
      functions.py
   scripts\
      test.py
   main.py

I would like to import the content of functions.py in test.py.

In main.py, I can import functions.py with from my_package.functions import ....
I was expecting to be able to import functions.py in test.py with something like from ..my_package.functions import ... but it raises the following error :

SystemError: Parent module '' not loaded, cannot perform relative import

top directory shoudln't be a package because I want to be able to run main.py without being running a script in a package.

What is the proper/pythonic way import functions.py from test.py ?

I could add my_package to the PYTHONPATH, but my code would be less portable. I'm using Python 3.5

Body:
This is happening because as far as python is concerned my_package and scripts directories are not related to each other.
To solve your problem you can add __init__.py to your top directory and try using

from ..function import *


问:
Jmeter run transaction controllers based on if condition
I'm fairly new to Jmeter. Here is my question.

I have 2 transaction controllers. Those will be run based on some if condition.

Example. I have transaction_controller_01 and transaction_controller_02.

I have a variable called 'type'.
When type = "user", transaction_controller_01 should be run.
When type = "admin", transaction_controller_02 should be run.

Can anyone help me with this?

Thanks in advance.

答:
Just put both Transaction Controller under If Controller

First If Condition will be "${type} == "user"

Second If Condition will be  "${type} == "admin"


问:
Handle aggregate promise of EachPromise (each_limit) in Guzzle

The task

Suppose we have an API POST endpoint which returns answer like this:

```<code>{
  "data": [1,2,3],
  "total_rows": 20
}
</code>```

Which means that we received data partially, only the first page of 3 entries. The total entries count is 20, which means we want to call other pages using some offset in request. The total count (and possibly offset) is therefore only known after the first call is completed, while other calls do not depend on each other and can be done simultaneously.

The Toolset

It's PHP and for this task Guzzle 6 is used with Promises/A+. Additionally, Guzzle offers EachPromise class, which receives an iterable of multiple promises and a config hash to setup processing. As per PhpDoc block of that class constructor:

Configuration hash can include the following key value pairs:

fulfilled: (callable) Invoked when a promise fulfills. The function   is invoked with three arguments: the fulfillment value, the index

  position from the iterable list of the promise, and the aggregate

  promise that manages all of the promises. The aggregate promise may

  be resolved from within the callback to short-circuit the promise.

rejected: (callable) Invoked when a promise is rejected. The   function is invoked with three arguments: the rejection reason, the

  index position from the iterable list of the promise, and the

  aggregate promise that manages all of the promises. The aggregate

  promise may be resolved from within the callback to short-circuit

  the promise.

concurrency: (integer) Pass this configuration option to limit the   allowed number of outstanding concurrently executing promises,

  creating a capped pool of promises. There is no limit by default.

The code

$paginatedResult = $this->client->sendAsync($this->createRequest($requestBody))
    ->then(function (ResponseInterface $response) use ($requestBody) {
            return $this->deserializeToPaginatedResult(
                $response,
                $requestBody->paginatedResultClass()
            );
        }
    )->wait();

$pageGenerator = function () use ($paginatedResult, $requestBody) {
    $perPageCount = count($paginatedResult->getItems());
    $totalItems = $paginatedResult->getTotalCount();

    for ($currentOffset = $perPageCount; $currentOffset <= $totalItems; $currentOffset += $perPageCount) {
        $newRequestBody = clone $requestBody;
        $newRequestBody->setOffset($currentOffset);

        yield $this->client->sendAsync($this->createRequest($newRequestBody));
    }
};

$aggregatedResult = (new EachPromise(
    $pageGenerator(), [
        'concurrency' => 4,
        'fulfilled' => function ($promiseResult, $promiseIndex, $promiseAggregate) use ($requestBody) {
            $paginatedResult = $this->deserializeToPaginatedResult(
                $promiseResult,
                $requestBody->paginatedResultClass()
            );

            return $paginatedResult->getItems();
        },
    ]
))->promise()
    ->then(
        function ($promisedAggregatedResult) {
            var_dump($promisedAggregatedResult);
        }
    )
    ->wait();

var_dump($aggregatedResult);
```

The problem

In the config hash the fulfilled callback receives 3 objects, as documentation states. The $promiseResult can be properly handled and $paginatedResult->getItems() actually returns an array of items in requested page, but I cannot aggregate those items. The $aggregatedResult is null, and the $promisedAggregatedResult inside the last thened fulfillment callback is also null.

The question

How should one properly use Guzzle's EachPromise (and it's helper functions each and each_limit) to aggregate results of all the promises passed to it?

答:
You can also use Pool::batch() method for that, it does almost the same inside.

```<code>$pageGenerator = function () use (...) {
    // ...
    yield $this->createRequest($newRequestBody);
    // ...
}

$responses = Pool::batch($this->client, $pageGenerator(), ['concurrency' => 4]);
</code>```

Body:
The task

Suppose we have an API POST endpoint which returns answer like this:

{
  "data": [1,2,3],
  "total_rows": 20
}

Which means that we received data partially, only the first page of 3 entries. The total entries count is 20, which means we want to call other pages using some offset in request. The total count (and possibly offset) is therefore only known after the first call is completed, while other calls do not depend on each other and can be done simultaneously.

The Toolset

It's PHP and for this task Guzzle 6 is used with Promises/A+. Additionally, Guzzle offers EachPromise class, which receives an iterable of multiple promises and a config hash to setup processing. As per PhpDoc block of that class constructor:

Configuration hash can include the following key value pairs:

fulfilled: (callable) Invoked when a promise fulfills. The function   is invoked with three arguments: the fulfillment value, the index

  position from the iterable list of the promise, and the aggregate

  promise that manages all of the promises. The aggregate promise may

  be resolved from within the callback to short-circuit the promise.

rejected: (callable) Invoked when a promise is rejected. The   function is invoked with three arguments: the rejection reason, the

  index position from the iterable list of the promise, and the

  aggregate promise that manages all of the promises. The aggregate

  promise may be resolved from within the callback to short-circuit

  the promise.

concurrency: (integer) Pass this configuration option to limit the   allowed number of outstanding concurrently executing promises,

  creating a capped pool of promises. There is no limit by default.

The code

$paginatedResult = $this->client->sendAsync($this->createRequest($requestBody))
    ->then(function (ResponseInterface $response) use ($requestBody) {
            return $this->deserializeToPaginatedResult(
                $response,
                $requestBody->paginatedResultClass()
            );
        }
    )->wait();

$pageGenerator = function () use ($paginatedResult, $requestBody) {
    $perPageCount = count($paginatedResult->getItems());
    $totalItems = $paginatedResult->getTotalCount();

    for ($currentOffset = $perPageCount; $currentOffset <= $totalItems; $currentOffset += $perPageCount) {
        $newRequestBody = clone $requestBody;
        $newRequestBody->setOffset($currentOffset);

        yield $this->client->sendAsync($this->createRequest($newRequestBody));
    }
};

$aggregatedResult = (new EachPromise(
    $pageGenerator(), [
        'concurrency' => 4,
        'fulfilled' => function ($promiseResult, $promiseIndex, $promiseAggregate) use ($requestBody) {
            $paginatedResult = $this->deserializeToPaginatedResult(
                $promiseResult,
                $requestBody->paginatedResultClass()
            );

            return $paginatedResult->getItems();
        },
    ]
))->promise()
    ->then(
        function ($promisedAggregatedResult) {
            var_dump($promisedAggregatedResult);
        }
    )
    ->wait();

var_dump($aggregatedResult);

The problem

In the config hash the fulfilled callback receives 3 objects, as documentation states. The $promiseResult can be properly handled and $paginatedResult->getItems() actually returns an array of items in requested page, but I cannot aggregate those items. The $aggregatedResult is null, and the $promisedAggregatedResult inside the last thened fulfillment callback is also null.

The question

How should one properly use Guzzle's EachPromise (and it's helper functions each and each_limit) to aggregate results of all the promises passed to it?

Body:
You can also use Pool::batch() method for that, it does almost the same inside.

$pageGenerator = function () use (...) {
    // ...
    yield $this->createRequest($newRequestBody);
    // ...
}

$responses = Pool::batch($this->client, $pageGenerator(), ['concurrency' => 4]);


问:
Node giving strange output on sum of particular float digits
I was playing with Node REPL and came across this strange behavior.

4.32 + 4.78 should be just 9.1

> 4.32 + 4.78
9.100000000000001

Another one is:

> 7.3 + 1.08
8.379999999999999

For other digits it works fine:

>  4.31 + 4.78
9.09

Tested it on Node version 4.8.3 and 7.4 on Ubuntu 16.04 and Linux/amd64 respectively.

Getting the same output.

Can anyone explain why it is like this?

答:
JavaScript uses IEEE 754 double precision floating-point numbers (see ECMA-262) and they cannot accurately represent all decimal fractions.

To get the results that you expect you can either scale the numbers to work on integers (e.g. count cents instead of dollars) or round the numbers to a specific number of decimal digits after you do the calculations.

Examples:

```<code>> 4.32 + 4.78
9.100000000000001

> (432 + 478) / 100
9.1

> +(4.32 + 4.78).toFixed(2)
9.1

> Math.round(100 * (4.32 + 4.78)) / 100
9.1
</code>```

See this for more details:

Avoiding problems with JavaScript's weird decimal calculations

Body:
JavaScript uses IEEE 754 double precision floating-point numbers (see ECMA-262) and they cannot accurately represent all decimal fractions.

To get the results that you expect you can either scale the numbers to work on integers (e.g. count cents instead of dollars) or round the numbers to a specific number of decimal digits after you do the calculations.

Examples:

> 4.32 + 4.78
9.100000000000001

> (432 + 478) / 100
9.1

> +(4.32 + 4.78).toFixed(2)
9.1

> Math.round(100 * (4.32 + 4.78)) / 100
9.1

See this for more details:

Avoiding problems with JavaScript's weird decimal calculations


问:
Split an NSString to access one particular piece
I have a string like this: @"10/04/2011" and I want to save only the "10" in another string. How can I do that?

答:
Swift 3.0 version

```<code>let arr = yourString.components(separatedBy: "/")
let month = arr[0]
</code>```

Body:
Swift 3.0 version

let arr = yourString.components(separatedBy: "/")
let month = arr[0]


问:
Using npm behind corporate proxy .pac
I need to download several packages through npm but our corporate proxy configuration is a .pac file (i'm on windows)

I have already tried

```<code>npm config set proxy http://mydomain\username:password@1.2.3.4:8181/proxy.pac
npm config set https-proxy http://mydomain\username:password@1.2.3.4:8181/proxy.pac
</code>```

or

```<code>npm config set proxy http://1.2.3.4:8181/proxy.pac
npm config set https-proxy http://1.2.3.4:8181/proxy.pac
</code>```

but it doesn't work...

any suggestion? thanks

答:
Try this, it was the only that worked for me:

npm --proxy http://:@proxyhost: --https-proxy http://:@proxyhost: --strict-ssl false install -g package

Pay atention to the option --strict-ssl false

Good luck.

Title: Using npm behind corporate proxy .pac

Body:
I need to download several packages through npm but our corporate proxy configuration is a .pac file (i'm on windows)

I have already tried

npm config set proxy http://mydomain\username:password@1.2.3.4:8181/proxy.pac
npm config set https-proxy http://mydomain\username:password@1.2.3.4:8181/proxy.pac

or

npm config set proxy http://1.2.3.4:8181/proxy.pac
npm config set https-proxy http://1.2.3.4:8181/proxy.pac

but it doesn't work...

any suggestion? thanks


问:
How to fetch all contacts record in ios xamarin
I want to fetch all contact records in iOS Xamarin.
I used code --> https://developer.xamarin.com/recipes/ios/shared_resources/contacts/find_a_contact/

Code:

```<code>    public override void ViewDidLoad()
    {
        base.ViewDidLoad();
        Util.CurrentView = this;
        _View = this;

        var predicate = CNContact.GetPredicateForContacts("Appleseed");
        var fetchKeys = new NSString[] { CNContactKey.GivenName, CNContactKey.FamilyName };
        var store = new CNContactStore();
        NSError error;
        var contacts = store.GetUnifiedContacts(predicate, fetchKeys, out error);
    }
</code>```

Error code:

This Error: Foundation.MonoTouchException: Objective-C exception
  thrown.  Name: NSInvalidArgumentException Reason: +[CNContact
  predicateForContactsMatchingName:]: unrecognized selector sent to
  class 0x1a3e1ec

I already add [Export("predicateForContactsMatchingName:")], but it didn't help.

答:
"Appleseed" is the search term used in the example. Seems like your mismatch is because none of the contacts match with the predicate.

Anyways, during my own implementation I ran into many issues. Below is a full solution to fetch all contacts in iOS Xamarin.

First: Add permission in info.plist

```<code><key>NSContactsUsageDescription</key>
<string>This app requires contacts access to function properly.</string>
</code>```

Second: Create a Model for Contacts info

In the example below I only add 3 fields

```<code>using System.Collections;

/// <summary>
///
/// </summary>
namespace YourNameSpace
{
    /// <summary>
    ///
    /// </summary>
    public class UserContact
    {
        public UserContact()
        {
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="givenName"></param>
        /// <param name="familyName"></param>
        /// <param name="emailId"></param>
        public UserContact(string givenName, string familyName, IList emailId)
        {
            GivenName = givenName;
            FamilyName = familyName;
            EmailId = emailId;
        }

        public bool IsSelected { get; set; }
        public string GivenName { get; set; }
        public string FamilyName { get; set; }
        public IList EmailId { get; set; }
    }
}
</code>```

Third: Read Contacts

```<code>public IEnumerable<UserContact> GetAllContactsAndEmails()
        {
            var keysTOFetch = new[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.EmailAddresses };
            NSError error;
            CNContact[] contactList;
            var ContainerId = new CNContactStore().DefaultContainerIdentifier;
            using (var predicate = CNContact.GetPredicateForContactsInContainer(ContainerId))

            using (var store = new CNContactStore())
            {
                contactList = store.GetUnifiedContacts(predicate, keysTOFetch, out error);
            }
            var contacts = new List<UserContact>();

            foreach (var item in contactList)
            {
                if (null != item && null != item.EmailAddresses)
                {
                    contacts.Add(new UserContact
                    {
                        GivenName = item.GivenName,
                        FamilyName = item.FamilyName,
                        EmailId = item.EmailAddresses.Select(m => m.Value.ToString()).ToList()
                    });
                }
            }
            return contacts;
        }
</code>```

Make sure you include contact attributes you need in KeysToFetch array

Body:
I want to fetch all contact records in iOS Xamarin.
I used code --> https://developer.xamarin.com/recipes/ios/shared_resources/contacts/find_a_contact/

Code:

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();
        Util.CurrentView = this;
        _View = this;

        var predicate = CNContact.GetPredicateForContacts("Appleseed");
        var fetchKeys = new NSString[] { CNContactKey.GivenName, CNContactKey.FamilyName };
        var store = new CNContactStore();
        NSError error;
        var contacts = store.GetUnifiedContacts(predicate, fetchKeys, out error);
    }

Error code:

This Error: Foundation.MonoTouchException: Objective-C exception
  thrown.  Name: NSInvalidArgumentException Reason: +[CNContact
  predicateForContactsMatchingName:]: unrecognized selector sent to
  class 0x1a3e1ec

I already add [Export("predicateForContactsMatchingName:")], but it didn't help.

Body:
"Appleseed" is the search term used in the example. Seems like your mismatch is because none of the contacts match with the predicate.

Anyways, during my own implementation I ran into many issues. Below is a full solution to fetch all contacts in iOS Xamarin.

First: Add permission in info.plist

<key>NSContactsUsageDescription</key>
<string>This app requires contacts access to function properly.</string>

Second: Create a Model for Contacts info

In the example below I only add 3 fields

using System.Collections;

/// <summary>
///
/// </summary>
namespace YourNameSpace
{
    /// <summary>
    ///
    /// </summary>
    public class UserContact
    {
        public UserContact()
        {
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="givenName"></param>
        /// <param name="familyName"></param>
        /// <param name="emailId"></param>
        public UserContact(string givenName, string familyName, IList emailId)
        {
            GivenName = givenName;
            FamilyName = familyName;
            EmailId = emailId;
        }

        public bool IsSelected { get; set; }
        public string GivenName { get; set; }
        public string FamilyName { get; set; }
        public IList EmailId { get; set; }
    }
}

Third: Read Contacts

public IEnumerable<UserContact> GetAllContactsAndEmails()
        {
            var keysTOFetch = new[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.EmailAddresses };
            NSError error;
            CNContact[] contactList;
            var ContainerId = new CNContactStore().DefaultContainerIdentifier;
            using (var predicate = CNContact.GetPredicateForContactsInContainer(ContainerId))

            using (var store = new CNContactStore())
            {
                contactList = store.GetUnifiedContacts(predicate, keysTOFetch, out error);
            }
            var contacts = new List<UserContact>();

            foreach (var item in contactList)
            {
                if (null != item && null != item.EmailAddresses)
                {
                    contacts.Add(new UserContact
                    {
                        GivenName = item.GivenName,
                        FamilyName = item.FamilyName,
                        EmailId = item.EmailAddresses.Select(m => m.Value.ToString()).ToList()
                    });
                }
            }
            return contacts;
        }

Make sure you include contact attributes you need in KeysToFetch array


问:
How to optimize wordpress website and Db properly?
I am using wp-minify and css and scripts file aggregation plugin for website optimization.
Can anybody answer the following

Which plugin is considered good for Database optimization?

How to add expiry headers to javascripts,images and stylesheet?

Which plugin is good for enabling cache for website's better performance?

答:
For expiry headers you can modify the .htaccess file in your website root folder. You can set the expiry time for all files in said root.

Here is a simple guide:
http://softstribe.com/wordpress/how-to-add-expires-headers-in-wordpress/


问:
Is it bad practice to return from within a try catch finally block?
So I came across some code this morning that looked like this:

```<code>try
{
    x = SomeThingDangerous();
    return x;
}
catch (Exception ex)
{
    throw new DangerousException(ex);
}
finally
{
    CleanUpDangerousStuff();
}
</code>```

Now this code compiles fine and works as it should, but it just doesn't feel right to return from within a try block, especially if there's an associated finally.

My main issue is what happens if the finally throws an exception of it's own? You've got a returned variable but also an exception to deal with... so I'm interested to know what others think about returning from within a try block?

答:
Personally, I would avoid this kind of coding as I don't feel like seeing return statements before finally statements.

My mind is simple and it process things rather linearly. Therefore when I walk through the code for dry running, I will have tendency to think that once I can reach the return statement, everything follow doesn't matter which obviously is pretty wrong in this case (not that it would affect the return statement but what the side effects could be).

Thus, I would arrange the code so that the return statement always appear after the finally statements.

OwnerDisplayName: lomaxx

Body:
So I came across some code this morning that looked like this:

try
{
    x = SomeThingDangerous();
    return x;
}
catch (Exception ex)
{
    throw new DangerousException(ex);
}
finally
{
    CleanUpDangerousStuff();
}

Now this code compiles fine and works as it should, but it just doesn't feel right to return from within a try block, especially if there's an associated finally.

My main issue is what happens if the finally throws an exception of it's own? You've got a returned variable but also an exception to deal with... so I'm interested to know what others think about returning from within a try block?

OwnerDisplayName: Conrad


问:
Small OpenMP program sometimes freezes (gcc, c, linux)
Just write a small omp test, and it does not work correctly all the times:

```<code>#include <omp.h>
int main() {
  int i,j=0;
#pragma omp parallel
  for(i=0;i<1000;i++)
  {
#pragma omp barrier
    j+= j^i;
  }
  return j;
}
</code>```

The usage of j for writing from all threads is incorrect in this example, BUT

there must be only nondeterministic value of j

I have a freeze.

Compiled with gcc-4.3.1 -fopenmp a.c -o gcc -static

Run on 4-core x86_Core2 Linux server: $ ./gcc and got freeze (sometimes; like 1 freeze for 4-5 fast runs).

Strace:

```<code>[pid 13118] futex(0x80d3014, FUTEX_WAKE, 1) = 1
[pid 13119] <... futex resumed> )       = 0
[pid 13118] futex(0x80d3020, FUTEX_WAIT, 251, NULL <unfinished ...>
[pid 13119] futex(0x80d3014, FUTEX_WAKE, 1) = 0
[pid 13119] futex(0x80d3020, FUTEX_WAIT, 251, NULL
                        <freeze>
</code>```

Why do I have a freeze (deadlock)?

答:
You're trying to add to the same location from multiple threads. You can't do what you're trying to do in parallel. If you want to do a sum in parallel, you need to divide it into smaller pieces and collect them afterwards.

Update by a5b: right idea but wrong part of code was spotted. The i variable is changed by both threads.

Body:
Just write a small omp test, and it does not work correctly all the times:

#include <omp.h>
int main() {
  int i,j=0;
#pragma omp parallel
  for(i=0;i<1000;i++)
  {
#pragma omp barrier
    j+= j^i;
  }
  return j;
}

The usage of j for writing from all threads is incorrect in this example, BUT

there must be only nondeterministic value of j

I have a freeze.

Compiled with gcc-4.3.1 -fopenmp a.c -o gcc -static

Run on 4-core x86_Core2 Linux server: $ ./gcc and got freeze (sometimes; like 1 freeze for 4-5 fast runs).

Strace:

[pid 13118] futex(0x80d3014, FUTEX_WAKE, 1) = 1
[pid 13119] <... futex resumed> )       = 0
[pid 13118] futex(0x80d3020, FUTEX_WAIT, 251, NULL <unfinished ...>
[pid 13119] futex(0x80d3014, FUTEX_WAKE, 1) = 0
[pid 13119] futex(0x80d3020, FUTEX_WAIT, 251, NULL
                        <freeze>

Why do I have a freeze (deadlock)?


问:
How to test object from factory with mocha with sinon

Background

I have a factory function that creates dogs that bark:

```<code>const dogFactory = () => {
    const bark = name => console.log(`${name} just barked!`);

    return{
        bark
    };
};
</code>```

One would use it like:

```<code>const dog = dogFactory();
dog.bark("boby"); //"boby just barked!"
</code>```

I also have an hotel of dogs. Business is not going good, so to keep appearances I am creating my own dogs ! This hotel thus takes a dogFactory as an argument and looks like the following:

```<code>const dogHotel = deps => {
    const {
        dogFactory
    } = deps;

    let dogsHosted = [];

    const feed = () => {
        dogsHosted.push(dogFactory());
        dogsHosted.forEach( (dog, i) => dog.bark(i));
    }

    return{
        feed
    };
};
</code>```

You would use it like:

```<code>const hotelAwsome = dogHotel({dogFactory: dogFactory});
hotelAwsome.feed();
</code>```

This hotel feeds dogs. Because there is no business it creates a dog and then feeds everyone. Every time a dog is fed, it barks of happiness!

Problem

One would think that creating infinite dogs in a broken hotel would be the problem, but that is not the case!

The problem here is that I want to make sure the dogs are happy barking. That is, that for each dog in the hotel bark is being called.

Code

This is currently my test. I am using mocha as a test suite, I am using sinon to spy on my fake factory objects:

```<code>const sinon = require( "sinon" );
const chai = require( "chai" );
const expect = chai.expect;

describe("dog hotel", () => {

    const fakeFacory = () => {
        const bark = () => sinon.spy()
        return {bark};
    };

    it("should make the dogs bark with happiness when feeding them!", () => {
        const hotelAweomse = dogHotel({dogFactory: fakeFacory});
        hotelAwesome.feed();
        //expect something here
    });
});
</code>```

The issue here is that I am passing a fake dog factory, but I can't check with sinon if the dog are barking or not!

Question

How do I test if the dogs that are created in the hotel, are barking?

答:
You should move the spy creation out of the fake factory. Now you can just use the spy properties (callOnce, calls) in the expect.

Kudos for the entertaining question :)

```<code>describe("dog hotel", () => {
    const spy = sinon.spy(); // create the spy outside

    const fakeFacory = () => {
        return {
          bark: spy // assign it to bark
        };
    };

    it("should make the dogs bark with happiness when feeding them!", () => {
        const hotelAweomse = dogHotel({dogFactory: fakeFacory});
        hotelAwesome.feed();

        // expect only one bark
        expect(spy.calledOnce).to.be.true;

        // expect a number of barks
        expect(spy.calls).to.equal(1);
    });
});
</code>```

Body:
Background

I have a factory function that creates dogs that bark:

const dogFactory = () => {
    const bark = name => console.log(`${name} just barked!`);

    return{
        bark
    };
};

One would use it like:

const dog = dogFactory();
dog.bark("boby"); //"boby just barked!"

I also have an hotel of dogs. Business is not going good, so to keep appearances I am creating my own dogs ! This hotel thus takes a dogFactory as an argument and looks like the following:

const dogHotel = deps => {
    const {
        dogFactory
    } = deps;

    let dogsHosted = [];

    const feed = () => {
        dogsHosted.push(dogFactory());
        dogsHosted.forEach( (dog, i) => dog.bark(i));
    }

    return{
        feed
    };
};

You would use it like:

const hotelAwsome = dogHotel({dogFactory: dogFactory});
hotelAwsome.feed();

This hotel feeds dogs. Because there is no business it creates a dog and then feeds everyone. Every time a dog is fed, it barks of happiness!

Problem

One would think that creating infinite dogs in a broken hotel would be the problem, but that is not the case!

The problem here is that I want to make sure the dogs are happy barking. That is, that for each dog in the hotel bark is being called.

Code

This is currently my test. I am using mocha as a test suite, I am using sinon to spy on my fake factory objects:

const sinon = require( "sinon" );
const chai = require( "chai" );
const expect = chai.expect;

describe("dog hotel", () => {

    const fakeFacory = () => {
        const bark = () => sinon.spy()
        return {bark};
    };

    it("should make the dogs bark with happiness when feeding them!", () => {
        const hotelAweomse = dogHotel({dogFactory: fakeFacory});
        hotelAwesome.feed();
        //expect something here
    });
});

The issue here is that I am passing a fake dog factory, but I can't check with sinon if the dog are barking or not!

Question

How do I test if the dogs that are created in the hotel, are barking?

Body:
You should move the spy creation out of the fake factory. Now you can just use the spy properties (callOnce, calls) in the expect.

Kudos for the entertaining question :)

describe("dog hotel", () => {
    const spy = sinon.spy(); // create the spy outside

    const fakeFacory = () => {
        return {
          bark: spy // assign it to bark
        };
    };

    it("should make the dogs bark with happiness when feeding them!", () => {
        const hotelAweomse = dogHotel({dogFactory: fakeFacory});
        hotelAwesome.feed();

        // expect only one bark
        expect(spy.calledOnce).to.be.true;

        // expect a number of barks
        expect(spy.calls).to.equal(1);
    });
});