问:
What's the difference between Virtual-8086 Mode and Real-Address Mode in x86 processor
In wikipedia, the explanation of virtual 8086 mode is said that

In the 80386 microprocessor and later, virtual 8086 mode (also called
      virtual real mode, V86-mode or VM86) allows the execution of real mode
      applications that are incapable of running directly in protected mode while
      the processor is running a protected mode operating system

I think this means that virtual 8086 mode can access to system memory and hardware devices.

And the explanation of real-address mode

Real mode, also called real address mode, is an operating mode of all
      x86-compatible CPUs. Real mode is characterized by a 20-bit segmented
      memory address space (giving exactly 1 MiB of addressable memory) and
      unlimited direct software access to all addressable memory, I/O addresses
      and peripheral hardware. Real mode provides no support for memory
      protection, multitasking, or code privilege levels

I think there is no difference between them.
anybody knows it??

答:
I think this means that virtual 8086 mode can access to system memory and hardware devices.

No, not really. In virtual 8086 mode there is also a protected mode operating system (the one that set up the virtual part) running in the background and deciding what memory and devices you have access to. Some of the devices might also be virtual, and simulated by the system. Old graphics cards, for example.

In real mode, the program runs directly on the real hardware - the way it did in the original 8086 (where this was the only mode). Even if there is an operating system, like PC-DOS, the application program still has unlimited access to all hardware and all memory. And can of course easily crash everything.


来源: stackexchange

问:
How to keep iOS native call UI after answering the call with CallKit
I am trying to achieve same results that can be seen on 29:52 second of Enhancing VoIP Apps with CallKit - WWDC 2016.
In that video it shows that after answering call the buttons are moved and changed by animation, and the screen stays in native in-call UI.

I built the Speakerbox and tried the "Simulate Incoming Call" function, but as soon as the call is answered by answer call button (the same action that is shown on video), the native call screen disappears and the application screen is shown with active calls shown in the list (which is different from what is shown in WWDC video):

Though there is a native call UI screen for very short time during transition from Incoming Call native UI to the app, but I can't find how to force it to stay on that screen.
Debugging the Speakerbox app there is no any delegate method called until all native screens are disappeared and the app is already opened.

I have tested receiving incoming call when the screen is locked, in that case the native UI is shown:

I would like to achieve same result on non locked phone.

答: If you lock the phone and then receive an incoming call, you will have similar experience to what you saw on WWDC. There is no a way to change this behavior in iOS 10.</p>

ContentLicense: CC BY-SA 3.0


问:
RestAssured: how to extract field inside JSON array
I know a similar question has been posted, however, the answer didn't work for me.

I am using RestAssured. How do I convert my Response into a JSON object and then extract a field that is within the JSON array (in my case, inside the errors array)?

```<code>Response response =
           given().
                contentType(ContentType.JSON).
                body(jsonAsMap).
           when().
                post("/customers").
           then().
                statusCode(400).extract().response();
   //get "code" field inside "errors".
</code>```

When testing the request in Postman, I get this result:

```<code>{
  "uri": "/customers/",
  "query": null,
  "method": "POST",
  "contentType": "application/json",
  "status": 400,
  "statusMessage": "Bad Request",
  "errors": [
    {
      "field": "firstName",
      "code": "firstName.required", //need to extract this field
      "message": "firstName is required"
    }
  ]
}
</code>```

What is the easiest way to achieve this?

答:
You can use JsonPath to access the value and convert this into a Java type.

Something like this:

```<code>String errorCode = ...then().extract().jsonPath().getString( "errors[0].code" )
</code>```

Body:
I know a similar question has been posted, however, the answer didn't work for me.

I am using RestAssured. How do I convert my Response into a JSON object and then extract a field that is within the JSON array (in my case, inside the errors array)?

Response response =
           given().
                contentType(ContentType.JSON).
                body(jsonAsMap).
           when().
                post("/customers").
           then().
                statusCode(400).extract().response();
   //get "code" field inside "errors".

When testing the request in Postman, I get this result:

{
  "uri": "/customers/",
  "query": null,
  "method": "POST",
  "contentType": "application/json",
  "status": 400,
  "statusMessage": "Bad Request",
  "errors": [
    {
      "field": "firstName",
      "code": "firstName.required", //need to extract this field
      "message": "firstName is required"
    }
  ]
}

What is the easiest way to achieve this?

Body:
You can use JsonPath to access the value and convert this into a Java type.

Something like this:

String errorCode = ...then().extract().jsonPath().getString( "errors[0].code" )


问:
How to fill the variables in html template in django?
I want to pass "name" to html file and get the response instead of rendering the page. I want to send this html page via email after adding the "name".

```<code><!DOCTYPE html>
<html>
<body>
<var>{{name}}</var>
</body>
</html>
</code>```

Here is the django views code:

```<code>def sending(request):
    -- passing request.user --
    return_page = html_page(request.user)
    send_email(--email content--)
</code>```

Can someone suggest me how to do this?

答:
You can use django render_to_string here.

Ex :

```<code>from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', { 'foo': 'bar' })
</code>```

Body:
I want to pass "name" to html file and get the response instead of rendering the page. I want to send this html page via email after adding the "name".

<!DOCTYPE html>

<var>{{name}}</var>

Here is the django views code:

def sending(request):
    -- passing request.user --
    return_page = html_page(request.user)
    send_email(--email content--)

Can someone suggest me how to do this?

Body:
You can use django render_to_string here.

Ex :

from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', { 'foo': 'bar' })


问:
Angular form save not working with dynamic push data
I am new to angular and stuck with dynamic data binding. I have four data
   fields 2 static and 2 dynamically adding after add button. When I click add
   button only two of the fields are shown on the display and remaining data
   is not populated. I might had make some mistake in data passing.
   The first two fields are static and second two are dynamic need to add as
   user clicks. The same happens when using form.
   Will any one please help me resolve this. Thanks in advance.
   Below is my code:</p>

Controller:

```<code>var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.items = [];

  $scope.itemsToAdd = [{
    firstName: '',
    lastName: ''
  }];

  $scope.add = function(itemToAdd) {

    var index = $scope.itemsToAdd.indexOf(itemToAdd);

    $scope.itemsToAdd.splice(index, 1);

    $scope.items.push(angular.copy(itemToAdd))
  }

  $scope.addNew = function() {

    $scope.itemsToAdd.push({
      firstName: '',
      lastName: ''
    })
  }
});
</code>```

View (HTML):

```<code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="plunker" ng-controller="MainCtrl">
  <p>Hello {{name}}!</p>

  <div ng-repeat="item in items">
     {{item.regno}} {{item.section}}
    {{item.firstName}} {{item.lastName}}
  </div>
    <input type="text" ng-model="itemToAdd.regno" />
    <input type="text" ng-model="itemToAdd.section" />
  <div ng-repeat="itemToAdd in itemsToAdd">
    <input type="text" ng-model="itemToAdd.firstName" />
    <input type="text" ng-model="itemToAdd.lastName" />
    <button ng-click="add(itemToAdd)">Add</button>
  </div>
  <div>
    <button ng-click="addNew()">Add new</button>
  </div>
</body>
</code>```

答:
you can try after add: </p>

```<code>$scope.$apply();
</code>```

Body:
I am new to angular and stuck with dynamic data binding. I have four data
   fields 2 static and 2 dynamically adding after add button. When I click add
   button only two of the fields are shown on the display and remaining data
   is not populated. I might had make some mistake in data passing.
   The first two fields are static and second two are dynamic need to add as
   user clicks. The same happens when using form.
   Will any one please help me resolve this. Thanks in advance.
   Below is my code:

Controller:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.items = [];

  $scope.itemsToAdd = [{
    firstName: '',
    lastName: ''
  }];

  $scope.add = function(itemToAdd) {

    var index = $scope.itemsToAdd.indexOf(itemToAdd);

    $scope.itemsToAdd.splice(index, 1);

    $scope.items.push(angular.copy(itemToAdd))
  }

  $scope.addNew = function() {

    $scope.itemsToAdd.push({
      firstName: '',
      lastName: ''
    })
  }
});

View (HTML):

Hello {{name}}!

     {{item.regno}} {{item.section}}
    {{item.firstName}} {{item.lastName}}

    <input type="text" ng-model="itemToAdd.regno" />
    <input type="text" ng-model="itemToAdd.section" />

    <input type="text" ng-model="itemToAdd.firstName" />
    <input type="text" ng-model="itemToAdd.lastName" />
    <button ng-click="add(itemToAdd)">Add</button>

    <button ng-click="addNew()">Add new</button>

Body:
you can try after add:

$scope.$apply();


问:
How to clone button between tabs C# Visual Studio 2015
Example

Hi! How can I clone a button on other tabs? I need the same button in many tabs, the same button with the same proprieties, same code, same events, same name, ect.

"Compress file" button is going to be the same in Tab1, Tab4, Tab6 and Tab8... is going to do the same thing in many tabs, therebefore I don't want to make a new button every time. I don't want to make 10000 buttons which do the same thing.

I need to clone many buttons, not just "compress file", that's why I can't just put "Compress file" outside the TabControl and make it invisible or visible.

I'm working on Visual Studio 2015 with C#.

答:
Create your button in developer code.  Then later on use the reference to add it to the controls for each tab as you switch tabs. e.g.

```<code>public MyForm()
{
    Initialize();
    Button MyOneTrickButton = new Button();
    //Create button with all attributes and actions
    ...
}

void MyTabControl_SelectedIndexChanged(object sender, EventArgs e)
{
    MyTabControl.SelectedTab.Controls.Add(MyOneTrickButton);
}
</code>```

A second option is to create a custom TabControl containing your button and use that instead of the normal TabControl when adding to the tabs to the form.

Body:
Create your button in developer code.  Then later on use the reference to add it to the controls for each tab as you switch tabs. e.g.

public MyForm()
{
    Initialize();
    Button MyOneTrickButton = new Button();
    //Create button with all attributes and actions
    ...
}

void MyTabControl_SelectedIndexChanged(object sender, EventArgs e)
{
    MyTabControl.SelectedTab.Controls.Add(MyOneTrickButton);
}

A second option is to create a custom TabControl containing your button and use that instead of the normal TabControl when adding to the tabs to the form.


问:
Click on disabled Bootstrap radio button group buttons will remove the active from current
I am using Bootstrap 3 and Angular 1.5 to present the radio button group on a page

```<code><div class="btn-group" data-toggle="buttons">
    <label class="btn btn-default" ng-click="changeAvailable(day.item[0],1)" ng-class="{1:'active'}[day.item[0].available]">
        <input type="radio" name="availabe[{{$index}}]" ng-checked="day.item[0].available==1" ng-model="day.item[0].available" ng-value="1">Workday
    </label>
    <label class="btn btn-default disabled" ng-click="changeAvailable(day.item[0],2)" ng-class="{2:'active'}[day.item[0].available]">
        <input type="radio" name="availabe[{{$index}}]" disabled="disabled" ng-checked="day.item[0].available==2" ng-model="day.item[0].available" ng-value="2">Break
    </label>
    <label class="btn btn-default" ng-click="changeAvailable(day.item[0],0)" ng-class="{0:'active'}[day.item[0].available]">
        <input type="radio" name="availabe[{{$index}}]" ng-checked="day.item[0].available==0" ng-model="day.item[0].available" ng-value="0">Dayoff
    </label>
</div>
</code>```

I need to disable some of the buttons. So I add class="disabled" to label and disabled="disabled" to input.

Every thing looks find until I click on the disabled button. The current checked button is no more with active style. So I can't tell which button is active now.

I even checked the bootstrap official site example and also has this problem.

Does anyone know a solution about how to disabled a button entirely?

Any help is appreciated.

答:
you can add to css file :

```<code>.disabled {  pointer-events: none; }
</code>```

or directly in element

```<code><label class="btn btn-default disabled" style="pointer-events:none">
</code>```

Your issue at github
see also
Remove pointer-events:none from .disabled

Body:
I am using Bootstrap 3 and Angular 1.5 to present the radio button group on a page

        <input type="radio" name="availabe[{{$index}}]" ng-checked="day.item[0].available==1" ng-model="day.item[0].available" ng-value="1">Workday

        <input type="radio" name="availabe[{{$index}}]" disabled="disabled" ng-checked="day.item[0].available==2" ng-model="day.item[0].available" ng-value="2">Break

        <input type="radio" name="availabe[{{$index}}]" ng-checked="day.item[0].available==0" ng-model="day.item[0].available" ng-value="0">Dayoff

I need to disable some of the buttons. So I add class="disabled" to label and disabled="disabled" to input.

Every thing looks find until I click on the disabled button. The current checked button is no more with active style. So I can't tell which button is active now.

I even checked the bootstrap official site example and also has this problem.

Does anyone know a solution about how to disabled a button entirely?

Any help is appreciated.

Body:
you can add to css file :

.disabled {  pointer-events: none; }

or directly in element

<label class="btn btn-default disabled" style="pointer-events:none">

Your issue at github
see also
Remove pointer-events:none from .disabled


问:
binding to Array.includes [javascript]
I'm trouble with using this in find if any element in array2 exists in array1:

```<code>array2 = [].includes.bind([1,2,3]);
array2(1);   // returns true
array2(9);   // returns false

[5,6,7,8,9].some(array2);        // returns false  GOOD
[3,6,7,8,9].some(array2);        // returns true   GOOD
[6,7,8,9,3].some(array2);        // returns false  OOPS!

[6,7,8,9,3].some(function(i){return array2(i)});  //returns true
</code>```

Obviously I know one solution to the problem, but I want to know why the [...].some(array2) doesn't work completely.

答:
[6,7,8,9,3].some(array2) doesn't work because Array.prototype.some calls check function with 3 arguments: value, index, entire array while Array.prototype.includes takes 2 arguments. Where the second argument is starting index to search from.

arr.includes(searchElement, fromIndex)

So every next call asks if your first array includes given value starting the given index.

Title: binding to Array.includes [javascript]

Body:
I'm trouble with using this in find if any element in array2 exists in array1:

array2 = [].includes.bind([1,2,3]);
array2(1);   // returns true
array2(9);   // returns false

[5,6,7,8,9].some(array2);        // returns false  GOOD
[3,6,7,8,9].some(array2);        // returns true   GOOD
[6,7,8,9,3].some(array2);        // returns false  OOPS!

[6,7,8,9,3].some(function(i){return array2(i)});  //returns true

Obviously I know one solution to the problem, but I want to know why the [...].some(array2) doesn't work completely.


问:
QT5.8. custom Virtual keyboard including
I'm writing a custom virtual keyboard, which based on QtVirtualKeyboard. For my project I would need to be able to use my version of keyboard.

But the only method, which i found is recompile project and replace original "qtvirtualkeyboardplugin.dll" in "mingw53_32\plugins\platforminputcontexts" on my version of "qtvirtualkeyboardplugin.dll". And use the qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard")); function in main.cpp

After hours of reading the docs and trying various things I'm still cannot find method to use custom keyboard localy, without deleting original "qtvirtualkeyboardplugin.dll".

答:
I'm assuming that you've forked the code, in which case the following modifications seem to be enough to get a differently named plugin to be installed to plugins/platforminputcontexts:

Rename qtvirtualkeyboard/src/virtualkeyboard/qtvirtualkeyboard.json to qtvirtualkeyboard/src/virtualkeyboard/customvirtualkeyboard.json.

In customvirtualkeyboard.json, rename the qtvirtualkeyboard key to customvirtualkeyboard.

In qtvirtualkeyboard/src/virtualkeyboard/plugin.cpp, change the contents of the pluginName string to customvirtualkeyboard.

In qtvirtualkeyboard/src/virtualkeyboard/plugin.h, change the FILE string to customvirtualkeyboard.

In src/virtualkeyboard/virtualkeyboard.pro, change TARGET = qtvirtualkeyboardplugin to TARGET = customvirtualkeyboardplugin. This affects the name of the installed .dll, .lib, etc. that you see in plugins/platforminputcontexts.

Here are the changes as a Git diff:

```<code>diff --git a/src/virtualkeyboard/customvirtualkeyboard.json b/src/virtualkeyboard/customvirtualkeyboard.json
new file mode 100644
index 0000000..9ef7a87
--- /dev/null
+++ b/src/virtualkeyboard/customvirtualkeyboard.json
@@ -0,0 +1,3 @@
+{
+    "Keys": [ "customvirtualkeyboard" ]
+}
diff --git a/src/virtualkeyboard/plugin.cpp b/src/virtualkeyboard/plugin.cpp
index 73ddeab..4abe9a4 100644
--- a/src/virtualkeyboard/plugin.cpp
+++ b/src/virtualkeyboard/plugin.cpp
@@ -76,7 +76,7 @@ using namespace QtVirtualKeyboard;

 Q_LOGGING_CATEGORY(qlcVirtualKeyboard, "qt.virtualkeyboard")

-static const char pluginName[] = "qtvirtualkeyboard";
+static const char pluginName[] = "customvirtualkeyboard";
 static const char inputMethodEnvVarName[] = "QT_IM_MODULE";
 static const char pluginUri[] = "QtQuick.VirtualKeyboard";
 static const char pluginSettingsUri[] = "QtQuick.VirtualKeyboard.Settings";
diff --git a/src/virtualkeyboard/plugin.h b/src/virtualkeyboard/plugin.h
index 08074d1..19593a4 100644
--- a/src/virtualkeyboard/plugin.h
+++ b/src/virtualkeyboard/plugin.h
@@ -38,7 +38,7 @@
 class QVirtualKeyboardPlugin : public QPlatformInputContextPlugin
 {
     Q_OBJECT
-    Q_PLUGIN_METADATA(IID QPlatformInputContextFactoryInterface_iid FILE "qtvirtualkeyboard.json")
+    Q_PLUGIN_METADATA(IID QPlatformInputContextFactoryInterface_iid FILE "customvirtualkeyboard.json")

 public:
     QStringList keys() const;
diff --git a/src/virtualkeyboard/qtvirtualkeyboard.json b/src/virtualkeyboard/qtvirtualkeyboard.json
deleted file mode 100644
index 76d1706..0000000
--- a/src/virtualkeyboard/qtvirtualkeyboard.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
-    "Keys": [ "qtvirtualkeyboard" ]
-}
diff --git a/src/virtualkeyboard/virtualkeyboard.pro b/src/virtualkeyboard/virtualkeyboard.pro
index 4f3ca69..e9b0ff9 100644
--- a/src/virtualkeyboard/virtualkeyboard.pro
+++ b/src/virtualkeyboard/virtualkeyboard.pro
@@ -1,4 +1,4 @@
-TARGET  = qtvirtualkeyboardplugin
+TARGET  = customvirtualkeyboardplugin
 DATAPATH = $$[QT_INSTALL_DATA]/qtvirtualkeyboard

 QMAKE_DOCS = $$PWD/doc/qtvirtualkeyboard.qdocconf
</code>```

Remember that if you're using an open source license, you have to make modifications to Qt code available to users of your application.

Body:
I'm assuming that you've forked the code, in which case the following modifications seem to be enough to get a differently named plugin to be installed to plugins/platforminputcontexts:

Rename qtvirtualkeyboard/src/virtualkeyboard/qtvirtualkeyboard.json to qtvirtualkeyboard/src/virtualkeyboard/customvirtualkeyboard.json.

In customvirtualkeyboard.json, rename the qtvirtualkeyboard key to customvirtualkeyboard.

In qtvirtualkeyboard/src/virtualkeyboard/plugin.cpp, change the contents of the pluginName string to customvirtualkeyboard.

In qtvirtualkeyboard/src/virtualkeyboard/plugin.h, change the FILE string to customvirtualkeyboard.

In src/virtualkeyboard/virtualkeyboard.pro, change TARGET = qtvirtualkeyboardplugin to TARGET = customvirtualkeyboardplugin. This affects the name of the installed .dll, .lib, etc. that you see in plugins/platforminputcontexts.

Here are the changes as a Git diff:

diff --git a/src/virtualkeyboard/customvirtualkeyboard.json b/src/virtualkeyboard/customvirtualkeyboard.json
new file mode 100644
index 0000000..9ef7a87
--- /dev/null
+++ b/src/virtualkeyboard/customvirtualkeyboard.json
@@ -0,0 +1,3 @@
+{
+    "Keys": [ "customvirtualkeyboard" ]
+}
diff --git a/src/virtualkeyboard/plugin.cpp b/src/virtualkeyboard/plugin.cpp
index 73ddeab..4abe9a4 100644
--- a/src/virtualkeyboard/plugin.cpp
+++ b/src/virtualkeyboard/plugin.cpp
@@ -76,7 +76,7 @@ using namespace QtVirtualKeyboard;

 Q_LOGGING_CATEGORY(qlcVirtualKeyboard, "qt.virtualkeyboard")

-static const char pluginName[] = "qtvirtualkeyboard";
+static const char pluginName[] = "customvirtualkeyboard";
 static const char inputMethodEnvVarName[] = "QT_IM_MODULE";
 static const char pluginUri[] = "QtQuick.VirtualKeyboard";
 static const char pluginSettingsUri[] = "QtQuick.VirtualKeyboard.Settings";
diff --git a/src/virtualkeyboard/plugin.h b/src/virtualkeyboard/plugin.h
index 08074d1..19593a4 100644
--- a/src/virtualkeyboard/plugin.h
+++ b/src/virtualkeyboard/plugin.h
@@ -38,7 +38,7 @@
 class QVirtualKeyboardPlugin : public QPlatformInputContextPlugin
 {
     Q_OBJECT
-    Q_PLUGIN_METADATA(IID QPlatformInputContextFactoryInterface_iid FILE "qtvirtualkeyboard.json")
+    Q_PLUGIN_METADATA(IID QPlatformInputContextFactoryInterface_iid FILE "customvirtualkeyboard.json")

 public:
     QStringList keys() const;
diff --git a/src/virtualkeyboard/qtvirtualkeyboard.json b/src/virtualkeyboard/qtvirtualkeyboard.json
deleted file mode 100644
index 76d1706..0000000
--- a/src/virtualkeyboard/qtvirtualkeyboard.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
-    "Keys": [ "qtvirtualkeyboard" ]
-}
diff --git a/src/virtualkeyboard/virtualkeyboard.pro b/src/virtualkeyboard/virtualkeyboard.pro
index 4f3ca69..e9b0ff9 100644
--- a/src/virtualkeyboard/virtualkeyboard.pro
+++ b/src/virtualkeyboard/virtualkeyboard.pro
@@ -1,4 +1,4 @@
-TARGET  = qtvirtualkeyboardplugin
+TARGET  = customvirtualkeyboardplugin
 DATAPATH = $$[QT_INSTALL_DATA]/qtvirtualkeyboard

 QMAKE_DOCS = $$PWD/doc/qtvirtualkeyboard.qdocconf

Remember that if you're using an open source license, you have to make modifications to Qt code available to users of your application.


问:
alertDialog not showing when creating cancel button
I think I know where exactly is the problem but I don't know if I'm right or not and I don't know how to fix it

```<code>AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view1 = getActivity().getLayoutInflater().inflate(R.layout.dialog_reserv_table, null);
builder.setView(view1);
final AlertDialog dialog = builder.create();
Button annulerButton = (Button) view1.findViewById(R.id.annulerReserv);
annulerButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        dialog.cancel();
    }
});
dialog.show();
</code>```

I think creating dialog it should be after all declarations and before show
in this way

```<code>AlertDialog dialog=builder.create();
dialog.show();
</code>```

but in this way I can't call dialog.cancel();

答:
You can create a custom Dialog without AlertDialog.Builder:

Edit:

```<code>Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_reserv_table);
Button annulerButton=(Button)dialog.findViewById(R.id.annulerReserv);
annulerButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        dialog.cancel();
    }
});
dialog.show();
</code>```

Source: http://www.mkyong.com/android/android-custom-dialog-example/

Body:
I think I know where exactly is the problem but I don't know if I'm right or not and I don't know how to fix it

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view1 = getActivity().getLayoutInflater().inflate(R.layout.dialog_reserv_table, null);
builder.setView(view1);
final AlertDialog dialog = builder.create();
Button annulerButton = (Button) view1.findViewById(R.id.annulerReserv);
annulerButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        dialog.cancel();
    }
});
dialog.show();

I think creating dialog it should be after all declarations and before show
in this way

AlertDialog dialog=builder.create();
dialog.show();

but in this way I can't call dialog.cancel();

Body:
You can create a custom Dialog without AlertDialog.Builder:

Edit:

Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_reserv_table);
Button annulerButton=(Button)dialog.findViewById(R.id.annulerReserv);
annulerButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        dialog.cancel();
    }
});
dialog.show();

Source: http://www.mkyong.com/android/android-custom-dialog-example/


问:
Best way to separate read and write concerns using interfaces?
Lately I've been realizing the benefit of (some would argue overuse of) immutable objects to cut down dramatically on read-write dependency issues in my object model and their resulting conditions and side-effects, to ultimately make the code simpler to manage (kind of functional-programming-esque).

This practice has led me to create read-only objects that are provided values at creation/construction time and then to make available only public getters for external callers to access the properties with. Protected, internal and private setters allow internal control to be maintained over writing to the object model.

When creating interfaces while making an API over my object model, I've started considering the same issues about immutability. For example, by providing only public getters on my interfaces, and leaving it up to implementors to decide upon setters and how to handle that aspect.

An example of a "read-only" interface for implementation that I'm talking about is this Valuable Item (just for demonstration):

```<code>public interface IValuableItem {
    decimal Amount {get;}
    string Currency {get;}
}
</code>```

However I got to wondering how I should provide a companion interface that allows for writing (and if I should), and not combine those operations within the same interface as to not "taint" its immutability.

The following ideas have come to mind, just off the top of my head. Without providing what I think are pros and cons to each, what do you think the best approach is? Is there a coding methodology common in the industry for managing this concept?

```<code>// companion writer
public interface IValuableModifier {
    decimal Amount {set;}
    string Currency {set;}
}
</code>```

or

```<code>// explicit methods to enforce importance of or deviance in the programming
public interface IValuableModifier {
    void SetAmount(decimal val);
    void SetCurrency(string cur);
}
</code>```

or

```<code>// companion writer that inherits the original interface
public interface IValuableModifier : IValuableItem { //...
</code>```

or

```<code>// Let a concrete class choose one and/or the other.
class Concrete  : IValuableModifer, IValuableItem { //...
</code>```

or

etc...

What else can help me imbue writing on my otherwise immutable programming model and keep it moderately flexible or at least to separate the concerns for better control over it?

答:
If your objects are to be immutable (and you design your application around the concept of immutable data) then objects really MUST remain immutable.

The canonical method for modifying data in immutable scenarios is to create new objects, so I would suggest something like this:

```<code>public interface IValuableItem<T>
{
    decimal Amount { get; }
    string Currency { get; }
    T CreateCopy(decimal amount, string currency);
}

public class SomeImmutableObject : IValuableItem<SomeImmutableObject>
{
    public decimal Amount { get; private set; }
    public string Currency { get; private set; }

    public SomeImmutableObject(decimal amount, string currency)
    {
        Amount = amount;
        Currency = currency;
    }

    public SomeImmutableObject CreateCopy(decimal amount, string currency)
    {
        return new SomeImmutableObject(amount, currency);
    }
}

SomeImmutableObject obj = new SomeImmutableObject(123.33m, "GBP");
SomeImmutableObject newObj = obj.CreateCopy(120m, obj.Currency);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Lately I've been realizing the benefit of (some would argue overuse of) immutable objects to cut down dramatically on read-write dependency issues in my object model and their resulting conditions and side-effects, to ultimately make the code simpler to manage (kind of functional-programming-esque).

This practice has led me to create read-only objects that are provided values at creation/construction time and then to make available only public getters for external callers to access the properties with. Protected, internal and private setters allow internal control to be maintained over writing to the object model.

When creating interfaces while making an API over my object model, I've started considering the same issues about immutability. For example, by providing only public getters on my interfaces, and leaving it up to implementors to decide upon setters and how to handle that aspect.

An example of a "read-only" interface for implementation that I'm talking about is this Valuable Item (just for demonstration):

public interface IValuableItem {
    decimal Amount {get;}
    string Currency {get;}
}

However I got to wondering how I should provide a companion interface that allows for writing (and if I should), and not combine those operations within the same interface as to not "taint" its immutability.

The following ideas have come to mind, just off the top of my head. Without providing what I think are pros and cons to each, what do you think the best approach is? Is there a coding methodology common in the industry for managing this concept?

// companion writer
public interface IValuableModifier {
    decimal Amount {set;}
    string Currency {set;}
}

or

// explicit methods to enforce importance of or deviance in the programming
public interface IValuableModifier {
    void SetAmount(decimal val);
    void SetCurrency(string cur);
}

or

// companion writer that inherits the original interface
public interface IValuableModifier : IValuableItem { //...

or

// Let a concrete class choose one and/or the other.
class Concrete  : IValuableModifer, IValuableItem { //...

or

etc...

What else can help me imbue writing on my otherwise immutable programming model and keep it moderately flexible or at least to separate the concerns for better control over it?

Body:
If your objects are to be immutable (and you design your application around the concept of immutable data) then objects really MUST remain immutable.

The canonical method for modifying data in immutable scenarios is to create new objects, so I would suggest something like this:

public interface IValuableItem<T>
{
    decimal Amount { get; }
    string Currency { get; }
    T CreateCopy(decimal amount, string currency);
}

public class SomeImmutableObject : IValuableItem<SomeImmutableObject>
{
    public decimal Amount { get; private set; }
    public string Currency { get; private set; }

    public SomeImmutableObject(decimal amount, string currency)
    {
        Amount = amount;
        Currency = currency;
    }

    public SomeImmutableObject CreateCopy(decimal amount, string currency)
    {
        return new SomeImmutableObject(amount, currency);
    }
}

SomeImmutableObject obj = new SomeImmutableObject(123.33m, "GBP");
SomeImmutableObject newObj = obj.CreateCopy(120m, obj.Currency);


问:
Editing specific line in text file in Python
Let's say I have a text file containing:

Dan
Warrior
500
1
0
```

<p>Is there a way I can edit a specific line in that text file? Right now I have this:</p>

```#!/usr/bin/env python
import io

myfile = open('stats.txt', 'r')
dan = myfile.readline()
print dan
print "Your name: " + dan.split('\n')[0]

try:
    myfile = open('stats.txt', 'a')
    myfile.writelines('Mage')[1]
except IOError:
        myfile.close()
finally:
        myfile.close()
```

Yes, I know that myfile.writelines('Mage')[1] is incorrect. But you get my point, right? I'm trying to edit line 2 by replacing Warrior with Mage. But can I even do that?

答:
I have been practising working on files this evening and realised that I can build on Jochen's answer to provide greater functionality for repeated/multiple use. Unfortunately my answer does not address issue of dealing with large files but does make life easier in smaller files.</p>

```<code>with open('filetochange.txt', 'r+') as foo:
    data = foo.readlines()                  #reads file as list
    pos = int(input("Which position in list to edit? "))-1  #list position to edit
    data.insert(pos, "more foo"+"\n")           #inserts before item to edit
    x = data[pos+1]
    data.remove(x)                      #removes item to edit
    foo.seek(0)                     #seeks beginning of file
    for i in data:
        i.strip()                   #strips "\n" from list items
        foo.write(str(i))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Let's say I have a text file containing:

Dan
Warrior
500
1
0

Is there a way I can edit a specific line in that text file? Right now I have this:

#!/usr/bin/env python
import io

myfile = open('stats.txt', 'r')
dan = myfile.readline()
print dan
print "Your name: " + dan.split('\n')[0]

try:
    myfile = open('stats.txt', 'a')
    myfile.writelines('Mage')[1]
except IOError:
        myfile.close()
finally:
        myfile.close()

Yes, I know that myfile.writelines('Mage')[1] is incorrect. But you get my point, right? I'm trying to edit line 2 by replacing Warrior with Mage. But can I even do that?

Body:
I have been practising working on files this evening and realised that I can build on Jochen's answer to provide greater functionality for repeated/multiple use. Unfortunately my answer does not address issue of dealing with large files but does make life easier in smaller files.

with open('filetochange.txt', 'r+') as foo:
    data = foo.readlines()                  #reads file as list
    pos = int(input("Which position in list to edit? "))-1  #list position to edit
    data.insert(pos, "more foo"+"\n")           #inserts before item to edit
    x = data[pos+1]
    data.remove(x)                      #removes item to edit
    foo.seek(0)                     #seeks beginning of file
    for i in data:
        i.strip()                   #strips "\n" from list items
        foo.write(str(i))


问:
Odoo V8 Got error unhashable type : 'list'
ive got error like this :

```<code>    Traceback (most recent call last):
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 544, in _handle_exception
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 581, in dispatch
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 317, in _call_function
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\service\model.py", line 118, in wrapper
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 314, in checked_call
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 810, in __call__
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 410, in response_wrap
  File "C:\Program Files (x86)\Odoo 8.0\server\openerp\addons\web\controllers\main.py", line 944, in call_kw
  File "C:\Program Files (x86)\Odoo 8.0\server\openerp\addons\web\controllers\main.py", line 936, in _call_kw
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\api.py", line 268, in wrapper
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\api.py", line 399, in old_api
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5989, in onchange
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5887, in _onchange_eval
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5395, in _convert_to_cache
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5396, in <dictcomp>
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\fields.py", line 1661, in convert_to_cache
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\tools\misc.py", line 1288, in add
  File "collections.pyc", line 63, in __setitem__
TypeError: unhashable type: 'list'
</code>```

ive checked it using pdb, but i got no error in my code, but got in this part :

```<code>File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5887, in _onchange_eval

    TypeError: unhashable type: 'list'
</code>```

and here is my code, my goal is to override onchange_employee_id function from hr.payslip model, and want to update the one2many field lines values by using (1,ID, {values}) :

```<code>import openerp
from openerp.osv import fields, osv
from openerp import api, fields, models, _, SUPERUSER_ID
from datetime import datetime
import time

class hr_payslip(models.Model):
    _inherit = 'hr.payslip'

    #@api.model
    #@api.multi
    def onchange_employee_id(self, cr, uid, ids, date_from, date_to, employee_id=False, contract_id=False, context=None):
        import pdb;pdb.set_trace()
        res = super(hr_payslip, self).onchange_employee_id(cr, uid, ids, date_from, date_to, employee_id=employee_id, contract_id=contract_id, context=context)
        #res = super(hr_payslip, self).onchange_employee_id(cr, uid, ids, date_from, date_to, employee_id, contract_id, context)
        for pay in self.browse(cr, uid, ids):
            empy = self.pool.get('overtime_details').search(cr, uid, [
                                ('start_date','>=',datetime.strptime(pay.date_from, "%Y-%m-%d").strftime("%Y-%m-%d %H:%M:%S")),
                                ('end_date','<=',datetime.strptime(pay.date_to, "%Y-%m-%d").strftime("%Y-%m-%d %H:%M:%S")),
                                ('employee_id.name','=',pay.employee_id.name),
                                ('overtime_id.state', '=', 'done')], context=context)
            if pay.id:
                #chk_struct = self.pool.get('hr.payroll.structure').search(cr, uid, [('name', '=', pay.struct_id.name)], context=context)
                #chk_contract = self.pool.get('hr.contract').search(cr, uid, [('name', '=', pay.contract_id.name)], context=context)
                if empy:
                    #if chk_struct:
                        #if chk_contract:
                    chk_ovt = self.pool.get('overtime_details').browse(cr, uid, empy, context=context)
                    if chk_ovt:
                        counter = 0
                        hrs = 0
                        vals = []
                        for ovt in chk_ovt:
                            if ovt.id:
                                counter = counter + 1
                                hrs = hrs + ovt.ttalmtp
                    vals.append([1,[pay.worked_days_line_ids],{'number_of_days':counter,
                    'number_of_hours':hrs, 'contract_id':pay.contract_id}])
                    return {'value' : {'worked_days_line_ids' : vals }}
                                #self.create(cr, uid, val2)
                else :
                    val = 0

            return res
</code>```

what should i do to fix the error

thanks before :)

答:
ive got the solution so instead using (1,ID,{values}) iam using (0,0,{values})
and update it later, here is my code solution :</p>

```<code>vals.append([0,0,{'number_of_days':counter,
                'number_of_hours':hrs, 'contract_id':pay.contract_id}])
                ovrtm = {'worked_days_line_ids' : vals }
                res['value'].update(ovrtm)
</code>```

Body:
ive got error like this :

    Traceback (most recent call last):
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 544, in _handle_exception
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 581, in dispatch
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 317, in _call_function
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\service\model.py", line 118, in wrapper
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 314, in checked_call
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 810, in __call__
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 410, in response_wrap
  File "C:\Program Files (x86)\Odoo 8.0\server\openerp\addons\web\controllers\main.py", line 944, in call_kw
  File "C:\Program Files (x86)\Odoo 8.0\server\openerp\addons\web\controllers\main.py", line 936, in _call_kw
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\api.py", line 268, in wrapper
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\api.py", line 399, in old_api
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5989, in onchange
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5887, in _onchange_eval
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5395, in _convert_to_cache
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5396, in <dictcomp>
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\fields.py", line 1661, in convert_to_cache
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\tools\misc.py", line 1288, in add
  File "collections.pyc", line 63, in __setitem__
TypeError: unhashable type: 'list'

ive checked it using pdb, but i got no error in my code, but got in this part :

File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5887, in _onchange_eval

    TypeError: unhashable type: 'list'

and here is my code, my goal is to override onchange_employee_id function from hr.payslip model, and want to update the one2many field lines values by using (1,ID, {values}) :

import openerp
from openerp.osv import fields, osv
from openerp import api, fields, models, _, SUPERUSER_ID
from datetime import datetime
import time

class hr_payslip(models.Model):
    _inherit = 'hr.payslip'

    #@api.model
    #@api.multi
    def onchange_employee_id(self, cr, uid, ids, date_from, date_to, employee_id=False, contract_id=False, context=None):
        import pdb;pdb.set_trace()
        res = super(hr_payslip, self).onchange_employee_id(cr, uid, ids, date_from, date_to, employee_id=employee_id, contract_id=contract_id, context=context)
        #res = super(hr_payslip, self).onchange_employee_id(cr, uid, ids, date_from, date_to, employee_id, contract_id, context)
        for pay in self.browse(cr, uid, ids):
            empy = self.pool.get('overtime_details').search(cr, uid, [
                                ('start_date','>=',datetime.strptime(pay.date_from, "%Y-%m-%d").strftime("%Y-%m-%d %H:%M:%S")),
                                ('end_date','<=',datetime.strptime(pay.date_to, "%Y-%m-%d").strftime("%Y-%m-%d %H:%M:%S")),
                                ('employee_id.name','=',pay.employee_id.name),
                                ('overtime_id.state', '=', 'done')], context=context)
            if pay.id:
                #chk_struct = self.pool.get('hr.payroll.structure').search(cr, uid, [('name', '=', pay.struct_id.name)], context=context)
                #chk_contract = self.pool.get('hr.contract').search(cr, uid, [('name', '=', pay.contract_id.name)], context=context)
                if empy:
                    #if chk_struct:
                        #if chk_contract:
                    chk_ovt = self.pool.get('overtime_details').browse(cr, uid, empy, context=context)
                    if chk_ovt:
                        counter = 0
                        hrs = 0
                        vals = []
                        for ovt in chk_ovt:
                            if ovt.id:
                                counter = counter + 1
                                hrs = hrs + ovt.ttalmtp
                    vals.append([1,[pay.worked_days_line_ids],{'number_of_days':counter,
                    'number_of_hours':hrs, 'contract_id':pay.contract_id}])
                    return {'value' : {'worked_days_line_ids' : vals }}
                                #self.create(cr, uid, val2)
                else :
                    val = 0

            return res

what should i do to fix the error

thanks before :)

Body:
ive got the solution so instead using (1,ID,{values}) iam using (0,0,{values})
and update it later, here is my code solution :

vals.append([0,0,{'number_of_days':counter,
                'number_of_hours':hrs, 'contract_id':pay.contract_id}])
                ovrtm = {'worked_days_line_ids' : vals }
                res['value'].update(ovrtm)


问:
Responsive logo placement
I am trying to figure out how to place the logo in the middle of the two sections of my landing page but only on the mobile view. The text class is for my logo. I cant seem to figure out the best way to do so.

```<code>.text {
 position: absolute;
 right: 70px;
 left: 70px;
 text-align: center;
 z-index: 10;
 margin: auto;
 max-width: 600px;
}
</code>```

Here is the codepen: http://codepen.io/anon/pen/xqQPVN?editors=1100

答:
Just give it position:absolute and set it accordingly for mobile devies..

Added the following css in the case of mobile.

```<code>/* Logo In Center For Mobile Device*/
  .logo-big {
    display: block;
    width: 100%;
    position: absolute;
    top: 500px;
    margin-top: -75px;

  }
</code>```

Codepen link-http://codepen.io/sahildhir_1/pen/wJQxQy?editors=1100

Below is the snippet-

* {
  box-sizing: border-box;
}

html,
body {
  height: 100%
}

img {
  max-width: 100%;
}

.item {
  width: 50%;
  float: left;
  top: 0;
  left: 0;
  height: 100%;
  z-index: 0;
  overflow: hidden;
  background-color: #000000;
  background-position: center center;
  background-size: auto 100%;
  position: relative;
}

.overlay {
  width: 100%;
  height: 100%;
  position: absolute;
  background-color: rgba(0, 0, 0, 0.3);
  transition: .2s linear;
}

.nurseryarea {
  width: 100%;
  position: absolute;
  text-align: center;
  top: 45%;
  color: #fff;
  font-size: 30px;
  font-family: 'times new roman';
  font-weight: bold;
  transition: .2s linear;
}

 ::selection {
  color: #ebebe3;
  background: #222;
}

 ::-moz-selection {
  color: #ebebe3;
  background: #222;
}

.overlay:hover {
  background-color: rgba(0, 0, 0, 0.1);
  transition-property: background-color;
}

.overlay:hover .nurseryarea {
  opacity: 1;
  transition-property: opacity;
}

.logo-big {
  display: block;
  width: 100%;
}

.logo-big .svg {
  display: block;
  width: 100%;
  height: auto;
}

.imgsize {
  width: 40%;
}

.text {
  position: absolute;
  right: 70px;
  left: 70px;
  text-align: center;
  z-index: 10;
  margin: auto;
  max-width: 600px;
}

@media screen and (max-width:600px) {
  .nurseryarea {
    width: 100%;
  }
  .imgsize {
    width: 60%;
  }
  .text {
    position: absolute;
    right: 70px;
    left: 70px;
    text-align: center;
    z-index: 10;
    margin: auto;
    max-width: 600px;
  }
  /* Logo In Center For Mobile Device*/
  .logo-big {
    display: block;
    width: 100%;
    position: absolute;
    top: 500px;
    margin-top: -75px;
  }
  .logo-big .svg {
    display: block;
    width: 100%;
    height: auto;
  }
  .item {
    width: 100%;
    float: left;
    top: 0;
    left: 0;
    height: 500px;
    z-index: 0;
    overflow: hidden;
    background-color: #000000;
    background-position: center center;
    background-size: auto 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="text">

    <img class="svg " src="https://www.lygonstnursery.com/wp-content/uploads/2017/03/NURSERY-landing-page.png" alt="Lygon Street Nursery">

</div>

<div class="item" style="background-image: url(https://www.lygonstnursery.com/wp-content/uploads/2017/02/LygonStNursery_Nursery-29.jpg);background-size:cover;">

  <div class="overlay">
    <div class="nurseryarea">
      <img class='imgsize' src="https://www.lygonstnursery.com/wp-content/uploads/2017/03/nursery.png" ;>
    </div>
  </div>

</div>

<div class="item" style="background-image: url(https://www.lygonstnursery.com/wp-content/uploads/2017/02/LygonStNursery_Brunswick-24.jpg); background-size:cover;">

  <div class="overlay">
    <div class="nurseryarea">
      <img class="imgsize" src="https://www.lygonstnursery.com/wp-content/uploads/2017/03/landscapes.png" ;>
    </div>
  </div>
</div></code>```

Title: Responsive logo placement

Body:
I am trying to figure out how to place the logo in the middle of the two sections of my landing page but only on the mobile view. The text class is for my logo. I cant seem to figure out the best way to do so.

.text {
 position: absolute;
 right: 70px;
 left: 70px;
 text-align: center;
 z-index: 10;
 margin: auto;
 max-width: 600px;
}

Here is the codepen: http://codepen.io/anon/pen/xqQPVN?editors=1100

Body:
Just give it position:absolute and set it accordingly for mobile devies..

Added the following css in the case of mobile.

/* Logo In Center For Mobile Device*/
  .logo-big {
    display: block;
    width: 100%;
    position: absolute;
    top: 500px;
    margin-top: -75px;

  }

Codepen link-http://codepen.io/sahildhir_1/pen/wJQxQy?editors=1100

Below is the snippet-

* {
  box-sizing: border-box;
}

html,
body {
  height: 100%
}

img {
  max-width: 100%;
}

.item {
  width: 50%;
  float: left;
  top: 0;
  left: 0;
  height: 100%;
  z-index: 0;
  overflow: hidden;
  background-color: #000000;
  background-position: center center;
  background-size: auto 100%;
  position: relative;
}

.overlay {
  width: 100%;
  height: 100%;
  position: absolute;
  background-color: rgba(0, 0, 0, 0.3);
  transition: .2s linear;
}

.nurseryarea {
  width: 100%;
  position: absolute;
  text-align: center;
  top: 45%;
  color: #fff;
  font-size: 30px;
  font-family: 'times new roman';
  font-weight: bold;
  transition: .2s linear;
}

 ::selection {
  color: #ebebe3;
  background: #222;
}

 ::-moz-selection {
  color: #ebebe3;
  background: #222;
}

.overlay:hover {
  background-color: rgba(0, 0, 0, 0.1);
  transition-property: background-color;
}

.overlay:hover .nurseryarea {
  opacity: 1;
  transition-property: opacity;
}

.logo-big {
  display: block;
  width: 100%;
}

.logo-big .svg {
  display: block;
  width: 100%;
  height: auto;
}

.imgsize {
  width: 40%;
}

.text {
  position: absolute;
  right: 70px;
  left: 70px;
  text-align: center;
  z-index: 10;
  margin: auto;
  max-width: 600px;
}

@media screen and (max-width:600px) {
  .nurseryarea {
    width: 100%;
  }
  .imgsize {
    width: 60%;
  }
  .text {
    position: absolute;
    right: 70px;
    left: 70px;
    text-align: center;
    z-index: 10;
    margin: auto;
    max-width: 600px;
  }
  /* Logo In Center For Mobile Device*/
  .logo-big {
    display: block;
    width: 100%;
    position: absolute;
    top: 500px;
    margin-top: -75px;
  }
  .logo-big .svg {
    display: block;
    width: 100%;
    height: auto;
  }
  .item {
    width: 100%;
    float: left;
    top: 0;
    left: 0;
    height: 500px;
    z-index: 0;
    overflow: hidden;
    background-color: #000000;
    background-position: center center;
    background-size: auto 100%;
  }
}

<div class="text">
  <a class="logo logo-big" href="http://www.lygonstnursery.com">
    <img class="svg " src="https://www.lygonstnursery.com/wp-content/uploads/2017/03/NURSERY-landing-page.png" alt="Lygon Street Nursery">
  </a>

</div>

<div class="item" style="background-image: url(https://www.lygonstnursery.com/wp-content/uploads/2017/02/LygonStNursery_Nursery-29.jpg);background-size:cover;">

  <div class="overlay">
    <div class="nurseryarea">
      <a href=" https://www.lygonstnursery.com/nursery/"><img class='imgsize' src="https://www.lygonstnursery.com/wp-content/uploads/2017/03/nursery.png" ;></a>
    </div>
  </div>

</div>

<div class="item" style="background-image: url(https://www.lygonstnursery.com/wp-content/uploads/2017/02/LygonStNursery_Brunswick-24.jpg); background-size:cover;">

  <div class="overlay">
    <div class="nurseryarea">
      <a href=" http://www.landscapes.lygonstnursery.com"><img class="imgsize" src="https://www.lygonstnursery.com/wp-content/uploads/2017/03/landscapes.png" ;></a>
    </div>
  </div>
</div>


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
For me, it wasn't a specific syntax - it was finding out I could break out and change ZX Spectrum games - I guess discovering source code is what got me hooked.

Then, when I actually started programming, and was copying code from books, being able to customise what was in the book and have the program still work, but how I wanted.

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

OwnerDisplayName: Peter Boughton


问:
Edit field in all documents in Azure DocumentDb
I have my data in DocumentDb.

I want to edit one field in all documents with Type == 8.

How I can do it?

Create console app for it

Use Azure Functions

I tried the second option and it not working.

```<code>public static void Run(string myQueueItem, dynamic inputDocument)
{
    if(inputDocument.Type == 8) {
        inputDocument.Entity.Discount.Name = inputDocument.Entity.Discount.Name + "smth";
    }
}
</code>```

Do you have any idea?

答:
Below code seems naïve and RU-wasteful but will work.</p>

```<code>DocumentClient _documentDbclient;

// Database configuration
static readonly string DocumentDbKeyConfig = "3dzS7T3a8lgEblkEnzSsdfasdfasf2omI1cp7==";
static readonly string DocumentDbEndPointConfig = "https://your-docdb.documents.azure.com:443/";
static readonly string DocumentDbDatabaseNameConfig = "your-database-name";

void Main()
{

    string collectionName = "TestCollection";

    Uri uri = UriFactory.CreateDocumentCollectionUri(DocumentDbDatabaseNameConfig, collectionName);
    InitializeDocumentDbAsync(DocumentDbDatabaseNameConfig).ConfigureAwait(false);

    createDocumentCollectionIfNotExistAsync(DocumentDbDatabaseNameConfig, collectionName).ConfigureAwait(false);

    DocumentCollection collection = _documentDbclient.ReadDocumentCollectionAsync(uri).Result;
    var query = _documentDbclient.CreateDocumentQuery(uri);
    var queryList = query.ToList();

    int index = 0;
    int count = 50; // number of item to fetch at a time
    while (true)
    {
        var result = queryList.Skip(index * count).Take(count);

        if (!result.Any())
        {
            // end iterating.
            return;
        }

        foreach (Document element in result)
        {
            JObject j = (dynamic)element;
            if(j["Type"] != 8) continue;

            j["YourProperty"] = "Some Value"; // edit value.
            var upsertedResult = _documentDbclient.UpsertDocumentAsync(uri, j, null, true).Result;
        }
        ++index;
    }
}

public async Task InitializeDocumentDbAsync(string databaseName)
{
    // Create a new instance of the DocumentClient
    _documentDbclient = new DocumentClient(
        new Uri(DocumentDbEndPointConfig), DocumentDbKeyConfig);
    // Check if the database FamilyDB does not exist

    try
    {
        await _documentDbclient.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName));
    }
    catch (DocumentClientException de)
    {
        // If the database does not exist, create a new database
        if (de.StatusCode == HttpStatusCode.NotFound)
        {
            await _documentDbclient.CreateDatabaseAsync(new Database { Id = databaseName });
        }
        else
        {
            throw;
        }
    }
    catch (Exception e)
    {
        throw;
    }
}

private async Task createDocumentCollectionIfNotExistAsync(string databaseName, string collectionName)
{
    try
    {
        await
            _documentDbclient.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName));
    }
    catch (DocumentClientException de)
    {
        // not exist
        throw;
    }
    catch (Exception e)
    {
        // do nothing.
    }
}
</code>```

Body:
I have my data in DocumentDb.

I want to edit one field in all documents with Type == 8.

How I can do it?

Create console app for it

Use Azure Functions

I tried the second option and it not working.

public static void Run(string myQueueItem, dynamic inputDocument)
{
    if(inputDocument.Type == 8) {
        inputDocument.Entity.Discount.Name = inputDocument.Entity.Discount.Name + "smth";
    }
}

Do you have any idea?

Body:
Below code seems naïve and RU-wasteful but will work.

DocumentClient _documentDbclient;

// Database configuration
static readonly string DocumentDbKeyConfig = "3dzS7T3a8lgEblkEnzSsdfasdfasf2omI1cp7==";
static readonly string DocumentDbEndPointConfig = "https://your-docdb.documents.azure.com:443/";
static readonly string DocumentDbDatabaseNameConfig = "your-database-name";

void Main()
{

    string collectionName = "TestCollection";

    Uri uri = UriFactory.CreateDocumentCollectionUri(DocumentDbDatabaseNameConfig, collectionName);
    InitializeDocumentDbAsync(DocumentDbDatabaseNameConfig).ConfigureAwait(false);

    createDocumentCollectionIfNotExistAsync(DocumentDbDatabaseNameConfig, collectionName).ConfigureAwait(false);

    DocumentCollection collection = _documentDbclient.ReadDocumentCollectionAsync(uri).Result;
    var query = _documentDbclient.CreateDocumentQuery(uri);
    var queryList = query.ToList();

    int index = 0;
    int count = 50; // number of item to fetch at a time
    while (true)
    {
        var result = queryList.Skip(index * count).Take(count);

        if (!result.Any())
        {
            // end iterating.
            return;
        }

        foreach (Document element in result)
        {
            JObject j = (dynamic)element;
            if(j["Type"] != 8) continue;

            j["YourProperty"] = "Some Value"; // edit value.
            var upsertedResult = _documentDbclient.UpsertDocumentAsync(uri, j, null, true).Result;
        }
        ++index;
    }
}

public async Task InitializeDocumentDbAsync(string databaseName)
{
    // Create a new instance of the DocumentClient
    _documentDbclient = new DocumentClient(
        new Uri(DocumentDbEndPointConfig), DocumentDbKeyConfig);
    // Check if the database FamilyDB does not exist

    try
    {
        await _documentDbclient.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName));
    }
    catch (DocumentClientException de)
    {
        // If the database does not exist, create a new database
        if (de.StatusCode == HttpStatusCode.NotFound)
        {
            await _documentDbclient.CreateDatabaseAsync(new Database { Id = databaseName });
        }
        else
        {
            throw;
        }
    }
    catch (Exception e)
    {
        throw;
    }
}

private async Task createDocumentCollectionIfNotExistAsync(string databaseName, string collectionName)
{
    try
    {
        await
            _documentDbclient.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName));
    }
    catch (DocumentClientException de)
    {
        // not exist
        throw;
    }
    catch (Exception e)
    {
        // do nothing.
    }
}


问:
comparing the content of two cells in VBA
I need to compare the content of two cells in macro

RC1=2.0

RC2=2

I am using if(RC1=RC2,"''","x") for this which prints x for the above input but 2.0 and 2 are same, I need it to be '' in this case, please suggest

答:
Your failing 'code' suggests you're merely using a formula:

```<code>if(RC1=RC2,"''","x")
</code>```

If you are happy using a formula to test them, you could use:

```<code>IF(VALUE(RC1)=VALUE(RC2),"''","x")
</code>```

Be aware though, a blank cell has a VALUE of 0 (zero) so an empty cell would match a cell containing 0.00

Body:
Your failing 'code' suggests you're merely using a formula:

if(RC1=RC2,"''","x")

If you are happy using a formula to test them, you could use:

IF(VALUE(RC1)=VALUE(RC2),"''","x")

Be aware though, a blank cell has a VALUE of 0 (zero) so an empty cell would match a cell containing 0.00


问:
Hide Up & Down Arrow Buttons (Spinner) in Input Number - Firefox 29
On Firefox 28, I'm using <input type="number"> works great because it brings up the numerical keyboard on input fields which should only contain numbers.

In Firefox 29, using number inputs displays spin buttons at the right side of the field, which looks like crap in my design. I really don't need the buttons, because they are useless when you need to write something like a 6~10 digit number anyway.

Is it possible to disable this with CSS or jQuery?

答:
```<code>/* for chrome */
    input[type=number]::-webkit-inner-spin-button,
    input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;}

/* for mozilla */
   input[type=number] {-moz-appearance: textfield;}
</code>```


问:
How to Handle Infinite hits to your public url
I am developing a Web Application using WebApi and AngularJS. My Application is Public Classified Web Site where a lot of URLs are public. My Question : What if someone writes very simple infinite loop and starts hitting my Server like:

```<code><script type="text/javascript">

    $(function () {

        while (true) {
            $.get("https://MyPublicURL", function (data) {
            });
        };
    });

</script>
</code>```

It will make my expensive server serve unnecessary requests for no reason. What are the best practices to avoid such situation?

答:
3Scale also provide API usage limitation feature.
Refer:https://www.3scale.net/api-management/rate-limits/</p>

Body:
I am developing a Web Application using WebApi and AngularJS. My Application is Public Classified Web Site where a lot of URLs are public. My Question : What if someone writes very simple infinite loop and starts hitting my Server like:

It will make my expensive server serve unnecessary requests for no reason. What are the best practices to avoid such situation?


问:
Retrieve IP address from Tomcat session ID?
Based on how is generated the session ID by Tomcat, is there a way to retrieve the IP address of the client from her session ID, using some decoding tool/method?

Using Tomcat 6.

NB: not sure it is relevant / possible at all.

The question could be about "How is generated the Tomcat session ID, does the calculation use the client IP, and is there a way to get it back"

edit

In case it matters, this is for a one time use, the analysis of an old log file via a Tomcat 6 generated session id. We are not looking at an implementation that works over time.

答: As it isn't specified how Tomcat or any other container generates a sessionID the answer is 'no'.</p>


问:
Rewriting URL and hiding Subpage Name
I have a rewrite in my .htaccess file that sends people from example.com to example.com/home

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^$ home [L,R=301]
</code>```

How do I do this but then strip the string "home" from the url bar so that it appears to be example.com? I'm not interested in any subdirectories after home as the rest of the site lives in the root.

Full Context

```<code># Perch Runway
<IfModule mod_rewrite.c>

# Turn on RewriteEngine
RewriteEngine On

# When user goes to the home page send to .com/home and strip /home
RewriteBase /
RewriteRule ^$ home [L,R=301]

# Cache Busting
RewriteRule (assets[/])([^.]*).min.+.(css|js)$ $1$2.min.$3

# Perch Runway
RewriteCond %{REQUEST_URI} !^/login
RewriteCond %{REQUEST_URI} !(/sub-directory-one|/sub-directory-two) [NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . /login/core/runway/start.php [L]
</IfModule>
</code>```

答:
Use below rule,</p>

```<code>RewriteEngine On
RewriteBase /
RewriteRule !home /home%{REQUEST_URI} [L]
</code>```

Title: Rewriting URL and hiding Subpage Name

Body:
I have a rewrite in my .htaccess file that sends people from example.com to example.com/home

RewriteEngine On
RewriteBase /
RewriteRule ^$ home [L,R=301]

How do I do this but then strip the string "home" from the url bar so that it appears to be example.com? I'm not interested in any subdirectories after home as the rest of the site lives in the root.

Full Context

# Perch Runway
<IfModule mod_rewrite.c>

# Turn on RewriteEngine
RewriteEngine On

# When user goes to the home page send to .com/home and strip /home
RewriteBase /
RewriteRule ^$ home [L,R=301]

# Cache Busting
RewriteRule (assets[/])([^.]*).min.+.(css|js)$ $1$2.min.$3

# Perch Runway
RewriteCond %{REQUEST_URI} !^/login
RewriteCond %{REQUEST_URI} !(/sub-directory-one|/sub-directory-two) [NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . /login/core/runway/start.php [L]
</IfModule>

Body:
Use below rule,

RewriteEngine On
RewriteBase /
RewriteRule !home /home%{REQUEST_URI} [L]


问:
Laravel save($request->all()) Error
I have a question, I've been developing laravel application and I encountered this strange error:

QueryException in Connection.php line 770:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`testenv`.`products`, CONSTRAINT `products_tenant_id_foreign` FOREIGN KEY (`tenant_id`) REFERENCES `tenants` (`id`)) (SQL: insert into `products` () values ())
```

<p>and Here's my store function</p>

```public function store(Request $request)
{
    $product = new Product;

    /*
    $product->name = $request->name;
    $product->stockQty = $request->stockQty;
    $product->minimumQty = $request->minimumQty;
    $product->description = $request->description;
    $product->notes = $request->notes;
    $product->tenantMargin = $request->tenantMargin;
    $product->length = $request->length;
    $product->height = $request->height;
    $product->weight = $request->weight;
    $product->showLength = $request->showLength;
    $product->showHeight = $request->showHeight;
    $product->showWeight = $request->showWeight;
    $product->size = $request->size;
    $product->colorName = $request->colorName;
    $product->colorHex = $request->colorHex;
    $product->isActive =$request->isActive;
    $product->tenant_id = $request->tenant_id;
    $product->productviewid = $request->productviewid;
    */

    $product->save($request->all());

    return "product successfully created";
}
```

And the error only occurs if i use

$product->save($request->all());

but if I un-comment the the commented code and use

$product->save()

instead, it works, no error.

Can anyone help me to find the source of this problem?

答:
As Alexey said, $product->save()it's going to use the data sent in the function instead of whatever you've set before, just like what you are trying to do in your example.

That way you are not using the mass assignment feature, because you are specifying every single field that needs to be updated in the database.

$product->save($parameters) actually makes use of the mass assignment feature and those attributes need to fillable, or un-guarded in the laravel properties.

Note that also Model::create() supports mass assignments.

Title: Laravel save($request->all()) Error

Body:
I have a question, I've been developing laravel application and I encountered this strange error:

QueryException in Connection.php line 770:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`testenv`.`products`, CONSTRAINT `products_tenant_id_foreign` FOREIGN KEY (`tenant_id`) REFERENCES `tenants` (`id`)) (SQL: insert into `products` () values ())

and Here's my store function

public function store(Request $request)
{
    $product = new Product;

    /*
    $product->name = $request->name;
    $product->stockQty = $request->stockQty;
    $product->minimumQty = $request->minimumQty;
    $product->description = $request->description;
    $product->notes = $request->notes;
    $product->tenantMargin = $request->tenantMargin;
    $product->length = $request->length;
    $product->height = $request->height;
    $product->weight = $request->weight;
    $product->showLength = $request->showLength;
    $product->showHeight = $request->showHeight;
    $product->showWeight = $request->showWeight;
    $product->size = $request->size;
    $product->colorName = $request->colorName;
    $product->colorHex = $request->colorHex;
    $product->isActive =$request->isActive;
    $product->tenant_id = $request->tenant_id;
    $product->productviewid = $request->productviewid;
    */

    $product->save($request->all());

    return "product successfully created";
}

And the error only occurs if i use

$product->save($request->all());

but if I un-comment the the commented code and use

$product->save()

instead, it works, no error.

Can anyone help me to find the source of this problem?


问:
Read huge .txt file with python
I have a problem in reading a huge txt file with python. I should read all the ~500M lines of a 33 GB .txt file, one by one, but for some obscure reason, my script stops at the 7446633rd line, and gives no error..
The script is the following easy one:

```<code>file = open ("file.txt","r")
i = 0
for line in file:
    i = i + 1
print i
file.close()
</code>```

I tried the script on more than one machine, and with both 32 and 64-bit versions of python, but no luck..

Anyone knows what could be the problem??

答:
Try using the "with" statement.

```<code>with open("file.txt") as input_file:
    for line in input_file:
        process_line(line)
</code>```

Also you could probably think about processing the lines in parallel using celery or something similar.

Later edit: if that doesn't work try to open the files and then use a range to read lines (read in batches).

Title: Read huge .txt file with python

Body:
I have a problem in reading a huge txt file with python. I should read all the ~500M lines of a 33 GB .txt file, one by one, but for some obscure reason, my script stops at the 7446633rd line, and gives no error..
The script is the following easy one:

file = open ("file.txt","r")
i = 0
for line in file:
    i = i + 1
print i
file.close()

I tried the script on more than one machine, and with both 32 and 64-bit versions of python, but no luck..

Anyone knows what could be the problem??

Body:
Try using the "with" statement.

with open("file.txt") as input_file:
    for line in input_file:
        process_line(line)

Also you could probably think about processing the lines in parallel using celery or something similar.

Later edit: if that doesn't work try to open the files and then use a range to read lines (read in batches).


问:
What do I need to take care of when releasing an OSX Electron build?
Apologies if this has been asked elsewhere - I couldn't find it.

Being the developer of a web application (PWA), I'd like to offer an Electron build for Mac users since Safari does not support some advanced features like Service Workers, yet.

I'm not very familiar with Mac peculiarities (I'm rather a Linux & Windows user), so I'm not sure what I need to take care of when releasing a downloadable program. I'm not so interested in the App store (which needs some additional steps)  - I guess it would be enough if my users could simply download an installation package, like the Chrome team seems to do for it's browser.

Do such packages need to be signed in some way or can I simply create an MacOS-Electron-Build and publish the resulting binary on my website, assuming that Mac users will know how to install it?

答:
So to get a user to install an electron application, you have a couple options.

Firstly, due to Apples default security settings, most unsigned applications will require the user to verify and allow the unsigned application to be installed. (So basically an extra step for the user... not entirely great for non savvy users)

To expand from this, to get a developer certificate, you'll need to get one from Apple (as to verify the authenticity of the application to your users)

As a precursor, I don't think it's entirely related to putting the app on the App Store, however you do need to have pay Apple $99 for a Mac developer account. (Not the iOS account).

This mirrors the process if you were to develop on Microsoft systems which require you to have a developer certificate via Visual Studio.


问:
How to get Xpath for the following?
I have a xml file like following

```<code><topic>
    <title>Abstract
    </title>
    <body>
        <p>
            abstract data
        </p>
    </body>
</topic>
<topic>
    <title>Keywords</title>
    <body>
        <p>
            keywords data
        </p>
    </body>
</topic>
</code>```

I have to check if title is "Keywords" than show the
text in
.
can anyone help me to get the exact xpath for this?
Thanks in advance

答:
Try this below xpath

```<code>//title[text()="Keywords"]/following::p
</code>```

Explanation of xpath:- Start your xpath with <title> along with text method and move ahead to the
 tag using the following keyword.

Title: How to get Xpath for the following?

Body:
I have a xml file like following

<topic>
    <title>Abstract
    </title>

            abstract data

</topic>
<topic>
    <title>Keywords</title>

            keywords data

</topic>

I have to check if title is "Keywords" than show the
text in
.
can anyone help me to get the exact xpath for this?
Thanks in advance

Body:
Try this below xpath

//title[text()="Keywords"]/following::p

Explanation of xpath:- Start your xpath with <title> along with text method and move ahead to the <p> tag using the following keyword.


答:
A couple of things:

1) For calculation, take another program based on python (e.g. http://www.sagemath.org/index.html). For now its fine but later on you will face problems with re-calculation etc. Math programms offer a designed UI for that.

2) sometimes it helps sympy by giving the numbers in x/y style because ... beeing very accurate 1/3 =! 0.333333333333333 (16th digit)

3) if 2 is not the solution, you can workaround (layman's-style):
think about a numerical integration within boarders of a and b, than decrease a towords -oo and increase b towords oo in a loop. Plotting the results and extrapolating to infinity ... However, a solution should be possible for this problem. I wonder that sympy has problems...(lkely I oversee the error)

Title: Sympy integrate PolynomialDivisionFailed error

Body:
For my research I want to calculate an integral in Python using Sympy. Eventually I want to change some parameters and see how that affects the result but to test my code I first want to do a basic calculation. Unfortunately using the following function:

sp.integrate(Z, (x, -sp.oo, sp.oo))

With :

Z = -9.274e-12*(x** 2*(y** 2 + 1)*(-20.0*x** 2 + 15.0*y** 2 + 15.0) + (-0.666666666666667*x** 2 + 0.333333333333333*y** 2 + 0.333333333333333)*(35.0*x** 4 - 30.0*x** 2*(x** 2 + y** 2 + 1) + 3.0*(x** 2 + y** 2 + 1)** 2))*tanh(0.672028985507246*sqrt((1.0*x** 2*(y** 2 + 1) + (-0.666666666666667*x** 2 + 0.333333333333333*y** 2 + 0.333333333333333)** 2)/(x** 2 + y** 2 + 1)** 5))/(sqrt((1.0*x** 2*(y** 2 + 1) + (-0.666666666666667*x** 2 + 0.333333333333333*y** 2 + 0.333333333333333)** 2)/(x** 2 + y** 2 + 1)** 5)*(x** 2 + y** 2 + 1)** 7)

I get the following error:

 PolynomialDivisionFailed: couldn't reduce degree in a polynomial
 division algorithm when dividing [0.444444444444444,
 0.555555555555556*y** 2 + 0.555555555555556, 0.111111111111111*y** 4 + 0.222222222222222*y** 2 + 0.111111111111111] by [-5.08052634253563e-5*y** 18 - 0.000457247370828057*y** 16 -
 0.00182898948331216*y** 14 - 0.00426764212772879*y** 12 - 0.00640146319159407*y** 10 - 0.00640146319159407*y** 8 - 0.00426764212772879*y** 6 - 0.00182898948331216*y** 4 - 0.000457247370828057*y** 2 - 5.08052634253563e-5, -5.08052634253074e-5*y** 20 - 0.000508052634253037*y** 18 - 0.00228623685413862*y** 16 - 0.00609663161103645*y** 14 - 0.0106691053193141*y** 12 - 0.0128029263831771*y** 10 - 0.0106691053193141*y** 8 - 0.00609663161103645*y** 6 - 0.00228623685413862*y** 4 - 0.000508052634253037*y** 2 - 5.08052634253074e-5].  This can happen when it's not possible to detect zero in the coefficient domain. The domain of computation is
 RR[y]. Zero detection is guaranteed in this coefficient domain. This
 may indicate a bug in SymPy or the domain is user defined and doesn't
 implement zero detection properly.

By looking into this error I think it is a bug in Sympy but other people sometimes found a work around to let their calculations still compute. Does someone kwow how to get my calculation to compute?


问:
sqoop export from hdfs to mysql failed, need help to escape the characters
I have a file in hdfs and exporting it to sqoop table. please find the log details below:

```<code>Caused by: java.lang.RuntimeException: Can't parse input data: ' characters'
    at tags.__loadFromFields(tags.java:335)
    at tags.parse(tags.java:268)
    at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:89)
    ... 10 more
</code>```

sqoop export command

```<code>sqoop export \
--connect "**************************************" \
--username=**** \
--password=***** \
--table tags \
--export-dir /user/cloudera/movie_lens/tags_no_header.csv \
--batch \
--input-lines-terminated-by '\n' \
--input-fields-terminated-by ',' \
--num-mappers 9 \
</code>```

Table Structure :

```<code>create table tags
    (userId integer
    ,movieId integer
    ,tag varchar(150)
    ,timestamp decimal
    );
</code>```

Record failing :
660,260,"imaginary world, characters, story, philosophical",1436680217

As per my understanding It's failing because of ambiguous parsing caused by comma ',' in middle of string.

Please help me to understand usage of --input-enclosed-by and --input-escaped-by arguments in this case or Is there any other solution.

Body:
I have a file in hdfs and exporting it to sqoop table. please find the log details below:

Caused by: java.lang.RuntimeException: Can't parse input data: ' characters'
    at tags.__loadFromFields(tags.java:335)
    at tags.parse(tags.java:268)
    at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:89)
    ... 10 more

sqoop export command

sqoop export \
--connect "**************************************" \
--username=**** \
--password=***** \
--table tags \
--export-dir /user/cloudera/movie_lens/tags_no_header.csv \
--batch \
--input-lines-terminated-by '\n' \
--input-fields-terminated-by ',' \
--num-mappers 9 \

Table Structure :

create table tags
    (userId integer
    ,movieId integer
    ,tag varchar(150)
    ,timestamp decimal
    );

Record failing :
660,260,"imaginary world, characters, story, philosophical",1436680217

As per my understanding It's failing because of ambiguous parsing caused by comma ',' in middle of string.

Please help me to understand usage of --input-enclosed-by and --input-escaped-by arguments in this case or Is there any other solution.

Body:
I have got it resolved using attribute --input-optionally-enclosed-by.
export command :

sqoop export \
--connect "jdbc:mysql://quickstart.cloudera:3306/movie_lens_db" \
--username=root \
--password=cloudera \
--table tags \
--export-dir /user/cloudera/escape_by_test.txt \
--batch \
--input-lines-terminated-by '\n' \
--input-fields-terminated-by ',' \
--input-optionally-enclosed-by '\"' \
--num-mappers 1 \
--outdir java_files

Table Data :

+--------+---------+---------------------------------------------------+------------+
| userId | movieId | tag                                               | timestamp  |
+--------+---------+---------------------------------------------------+------------+
|    660 |     260 | imaginary world, characters, story, philosophical | 1436680217 |
|    212 |   69712 | genuine characters                                | 1260688086 |
+--------+---------+---------------------------------------------------+------------+


问:
C# get cmd output just as shown in real cmd window
I have a BackgroundWorker thread that runs a cmd process and writes multiple commands to it. Some of the commands may take a while to complete so I want to show the user the cmd output of the progress.
My code for running the cmd commands looks like this:

```<code>private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    var startInfo = new ProcessStartInfo("cmd.exe")
    {
        UseShellExecute = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    };

    cmd = new Process { StartInfo = startInfo };

    cmd.OutputDataReceived += Cmd_OutputDataReceived;
    cmd.Start();
    cmd.BeginOutputReadLine();

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\uboot");

    string[] commands = CmdCommands.GetUbootFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\android");
    commands = CmdCommands.GetKernelFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine("exit");
    cmd.WaitForExit();
}

private void Cmd_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Invoke(new Action(() =>
    {
        txtCmd.Text += e.Data + Environment.NewLine;
    }));
}
</code>```

But the cmd output loos nothing the real output as shown in a regular cmd window.
Here is how my output looks like:

```<code>Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\>cd C:\img files\uboot

C:\img files\uboot>fastboot flash XXX.bin

C:\img files\uboot>fastboot flash XXX.bin

C:\img files\uboot>cd C:\img files\android

C:\img files\android>fastboot flash kernel

C:\img files\android>fastboot flash system XXX.img

C:\img files\android>fastboot flash userdata XXX.img

C:\img files\android>fastboot flash cache XXX.img

C:\img files\android>exit
</code>```

And here is how output looks like when I open a cmd window and type in the commands:

```<code>Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\WINDOWS\system32>cd C:\img files\uboot

C:\img files\uboot>fastboot flash bl2 bl2.bin
target didn't report max-download-size
sending 'bl2' (14 KB)...
OKAY [  0.006s]
writing 'bl2'...
OKAY [  0.042s]
finished. total time: 0.052s

C:\img files\uboot>fastboot flash bootloader u-boot.bin
target didn't report max-download-size
sending 'bootloader' (275 KB)...
OKAY [  0.049s]
writing 'bootloader'...
OKAY [  0.046s]
finished. total time: 0.098s

C:\img files\uboot>cd C:\img files\android

C:\img files\android>fastboot flash kernel zImage-dtb
target didn't report max-download-size
sending 'kernel' (5099 KB)...
OKAY [  0.839s]
writing 'kernel'...
OKAY [  0.145s]
finished. total time: 0.988s

C:\img files\android>fastboot flash system system.img
target didn't report max-download-size
sending 'system' (426874 KB)...
OKAY [ 70.327s]
writing 'system'...
OKAY [ 30.963s]
finished. total time: 101.295s

C:\img files\android>fastboot flash userdata userdata.img
target didn't report max-download-size
sending 'userdata' (35680 KB)...
OKAY [  5.895s]
writing 'userdata'...
OKAY [  2.301s]
finished. total time: 8.200s

C:\img files\android>fastboot flash cache cache.img
target didn't report max-download-size
sending 'cache' (6248 KB)...
OKAY [  1.036s]
writing 'cache'...
OKAY [  0.380s]
finished. total time: 1.422s

C:\img files\android>
</code>```

How do I get this output in my my C# code???

答:
As @Damien_The_Unbeliever and @user2033402 has suggested, it seems that for some reason the output I needed was redirected to the StandardError instead of to the StandardOutput.

So the working solution in my case was this code:

```<code>private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    var startInfo = new ProcessStartInfo("cmd.exe")
    {
        UseShellExecute = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        CreateNoWindow = true
    };

    cmd = new Process { StartInfo = startInfo };

    cmd.OutputDataReceived += Cmd_OutputDataReceived;
    cmd.ErrorDataReceived += Cmd_ErrorDataReceived;
    cmd.Start();
    cmd.BeginOutputReadLine();
    cmd.BeginErrorReadLine();

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\uboot");

    string[] commands = CmdCommands.GetUbootFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\android");
    commands = CmdCommands.GetKernelFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine("exit");
    cmd.WaitForExit();
}

private void Cmd_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Invoke(new Action(() =>
    {
        txtCmd.Text += e.Data + Environment.NewLine;
    }));
}

private void Cmd_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
    Invoke(new Action(() =>
    {
        txtCmd.Text += e.Data + Environment.NewLine;
    }));
}
</code>```

Body:
I have a BackgroundWorker thread that runs a cmd process and writes multiple commands to it. Some of the commands may take a while to complete so I want to show the user the cmd output of the progress.
My code for running the cmd commands looks like this:

private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    var startInfo = new ProcessStartInfo("cmd.exe")
    {
        UseShellExecute = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    };

    cmd = new Process { StartInfo = startInfo };

    cmd.OutputDataReceived += Cmd_OutputDataReceived;
    cmd.Start();
    cmd.BeginOutputReadLine();

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\uboot");

    string[] commands = CmdCommands.GetUbootFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\android");
    commands = CmdCommands.GetKernelFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine("exit");
    cmd.WaitForExit();
}

private void Cmd_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Invoke(new Action(() =>
    {
        txtCmd.Text += e.Data + Environment.NewLine;
    }));
}

But the cmd output loos nothing the real output as shown in a regular cmd window.
Here is how my output looks like:

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\>cd C:\img files\uboot

C:\img files\uboot>fastboot flash XXX.bin

C:\img files\uboot>fastboot flash XXX.bin

C:\img files\uboot>cd C:\img files\android

C:\img files\android>fastboot flash kernel

C:\img files\android>fastboot flash system XXX.img

C:\img files\android>fastboot flash userdata XXX.img

C:\img files\android>fastboot flash cache XXX.img

C:\img files\android>exit

And here is how output looks like when I open a cmd window and type in the commands:

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\WINDOWS\system32>cd C:\img files\uboot

C:\img files\uboot>fastboot flash bl2 bl2.bin
target didn't report max-download-size
sending 'bl2' (14 KB)...
OKAY [  0.006s]
writing 'bl2'...
OKAY [  0.042s]
finished. total time: 0.052s

C:\img files\uboot>fastboot flash bootloader u-boot.bin
target didn't report max-download-size
sending 'bootloader' (275 KB)...
OKAY [  0.049s]
writing 'bootloader'...
OKAY [  0.046s]
finished. total time: 0.098s

C:\img files\uboot>cd C:\img files\android

C:\img files\android>fastboot flash kernel zImage-dtb
target didn't report max-download-size
sending 'kernel' (5099 KB)...
OKAY [  0.839s]
writing 'kernel'...
OKAY [  0.145s]
finished. total time: 0.988s

C:\img files\android>fastboot flash system system.img
target didn't report max-download-size
sending 'system' (426874 KB)...
OKAY [ 70.327s]
writing 'system'...
OKAY [ 30.963s]
finished. total time: 101.295s

C:\img files\android>fastboot flash userdata userdata.img
target didn't report max-download-size
sending 'userdata' (35680 KB)...
OKAY [  5.895s]
writing 'userdata'...
OKAY [  2.301s]
finished. total time: 8.200s

C:\img files\android>fastboot flash cache cache.img
target didn't report max-download-size
sending 'cache' (6248 KB)...
OKAY [  1.036s]
writing 'cache'...
OKAY [  0.380s]
finished. total time: 1.422s

C:\img files\android>

How do I get this output in my my C# code???

Body:
As @Damien_The_Unbeliever and @user2033402 has suggested, it seems that for some reason the output I needed was redirected to the StandardError instead of to the StandardOutput.

So the working solution in my case was this code:

private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    var startInfo = new ProcessStartInfo("cmd.exe")
    {
        UseShellExecute = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        CreateNoWindow = true
    };

    cmd = new Process { StartInfo = startInfo };

    cmd.OutputDataReceived += Cmd_OutputDataReceived;
    cmd.ErrorDataReceived += Cmd_ErrorDataReceived;
    cmd.Start();
    cmd.BeginOutputReadLine();
    cmd.BeginErrorReadLine();

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\uboot");

    string[] commands = CmdCommands.GetUbootFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\android");
    commands = CmdCommands.GetKernelFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine("exit");
    cmd.WaitForExit();
}

private void Cmd_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Invoke(new Action(() =>
    {
        txtCmd.Text += e.Data + Environment.NewLine;
    }));
}

private void Cmd_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
    Invoke(new Action(() =>
    {
        txtCmd.Text += e.Data + Environment.NewLine;
    }));
}


问:
ERROR 1064 iYou have an error in your SQL syntax;
Hi I have an error when I am inserting data into my database:

1064 You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'User,hello,2017-03-30 10:42:43,0)' at line 3 SQL=INSERT INTO
  #__registentrys (name,type_entry,date_regist,published)
  VALUES (Super User,hello,2017-03-30 10:42:43,0)

My code:

```<code>$greating1=$this->item->greeting;
                $datetime = new Jdate('now + 1 hour'); //GTM hour Lisbon
                $this->item->menssage1 = $datetime;
                //session portection
                $user = JFactory::getUser();
                if($user->guest)
                {
                    $this->item->menssage2 = "You are not allowed to enter this site";
                }
                else
                {
                    $username = $user->name;
                    $this->item->menssage2 = $username;
                    $db1 = JFactory::getDbo();
                    $query1 = $db1->getQuery(true);

                    // Insert columns.
                    $columns = array('name', 'type_entry', 'date_regist', 'published');

                    // Insert values.
                    $values = array($username, $greating1, $datetime, 0);

                    // Build the query
                    $query1
                    ->insert($db1->quoteName('#__registentrys'))
                    ->columns($db1->quoteName($columns))
                    ->values(implode(',', $values));

                    $db1->setQuery($query1);
                    $db1->execute();
</code>```

Thanks in advance for your answers.

答:
It's easy to place quotes on values</p>

```<code>->values(implode(',', $db1->quote($values)));
</code>```

Body:
Hi I have an error when I am inserting data into my database:

1064 You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'User,hello,2017-03-30 10:42:43,0)' at line 3 SQL=INSERT INTO
  #__registentrys (name,type_entry,date_regist,published)
  VALUES (Super User,hello,2017-03-30 10:42:43,0)

My code:

$greating1=$this->item->greeting;
                $datetime = new Jdate('now + 1 hour'); //GTM hour Lisbon
                $this->item->menssage1 = $datetime;
                //session portection
                $user = JFactory::getUser();
                if($user->guest)
                {
                    $this->item->menssage2 = "You are not allowed to enter this site";
                }
                else
                {
                    $username = $user->name;
                    $this->item->menssage2 = $username;
                    $db1 = JFactory::getDbo();
                    $query1 = $db1->getQuery(true);

                    // Insert columns.
                    $columns = array('name', 'type_entry', 'date_regist', 'published');

                    // Insert values.
                    $values = array($username, $greating1, $datetime, 0);

                    // Build the query
                    $query1
                    ->insert($db1->quoteName('#__registentrys'))
                    ->columns($db1->quoteName($columns))
                    ->values(implode(',', $values));

                    $db1->setQuery($query1);
                    $db1->execute();

Thanks in advance for your answers.

Body:
It's easy to place quotes on values

->values(implode(',', $db1->quote($values)));