问:
Why can't I initialize a variable to the indices of two other variables working on a string?
The wording of my question was not polite to the search feature on the site, so I apologize should someone feel this is a duplicate question, but I must ask anyway.

Working in Python 3.6.1, my goal is to find a substring of letters in a string that are in alphabetical order and if that substring of letters is the longest substring of letters in alphabetical order (aa would be considered alphabetical order), then print out the string. I have not gotten entirely close to the solution but I'm making progress; however, this came up and I'm confounded by it being completely new to Python. My question is, why is this valid:

```<code>s = 'hijkkpdgijklmnopqqrs'
n = len(s)
i = 0
a = 0
for i in range(n-2):
    if s[i] <= s[i+1]:
       a = s[i+1]
       i = s[i+2]
       a = i + a
print(a)
</code>```

And yet this is not:

```<code>s = 'hijkkpdgijklmnopqqrs'
n = len(s)
i = 0
a = 0
b = ''
for i in range(n-2):
    if s[i] <= s[i+1]:
       b = a + i
       a = s[i+1]
       i = s[i+2]
       a = a + i
print(b)
</code>```

When the latter code is run, I receive the error:

Traceback (most recent call last):
File "C:\Users\spect\Desktop\newjackcity.py", line 14, in <module>
b = a + i
TypeError: must be str, not int
```

<p>What I am ultimately trying to do is to 'index in' to the string <code>s</code>, compare the zeroth element to the zeroth+1 element and if <code>s[I] < s[I+1]</code>, I want to concatenate the two into my variable <code>a</code> for later printing. Because when I do this, <code>a</code> only prints out two letters in the string. I thought, well initialize the variable first so that <code>a</code> and <code>i</code> can be incremented, then added into <code>a</code> for comparison purposes, and <code>b</code> for printing.</p>

<p>I see now that I'm only going through <code>n-2</code> iterations (in order to compare the second to last letter to <code>n-1</code> so the logic is flawed, but I still don't understand the error of why all of a sudden binding <code>a+i</code> to a variable <code>b</code> will produce a str/int error? In my view saying <code>s[i]</code>; etc. is pulling out the elements as a string and this to me is proven in the fact if I run the first set of code, I get the output:</p>

<pre class="lang-none prettyprint-override"><code>sr
>>>
</code>```

答:
In both for loops, you use i as the loop variable, so it starts as an int.

In the first version, you reassign i to a string, then add.

```<code>for i in range(n-2):
  # here i is an int, something between 0 and n-2
  if s[i] <= s[i+1]:
    a = s[i+1]  # a is a string...
    i = s[i+2]  # now you change i to a string
    a = i + a  # string + string: OK!
</code>```

In the second version you try to add i first:

```<code>for i in range(n-2):
  # here i is an int, something between 0 and n-2
  if s[i] <= s[i+1]:
     b = a + i # string + int, can't do it...
     a = s[i+1]
     i = s[i+2]
     a = a + i
</code>```

You will have an easier time debugging your code if you pick more meaningful names.

edit: here is my cleaned up version of your code:

```<code>s = 'hijkkpdgijklmnopqqrs'
# i = 0 isn't needed, range starts at 0
# the first character is always 'alphabetical'
alph_substr = s[0]
# range(1,n) is [1,2, ..., n-1]
for i in range(1, len(s)):
  if s[i-1] <= s[i]:
    alph_substr = alph_substr + s[i]
  else:
    # we have to start over, since we're not alphabetical anymore
    print(alph_substr)
    alph_substr = s[i]
print(alph_substr)
</code>```

Body:
The wording of my question was not polite to the search feature on the site, so I apologize should someone feel this is a duplicate question, but I must ask anyway.

Working in Python 3.6.1, my goal is to find a substring of letters in a string that are in alphabetical order and if that substring of letters is the longest substring of letters in alphabetical order (aa would be considered alphabetical order), then print out the string. I have not gotten entirely close to the solution but I'm making progress; however, this came up and I'm confounded by it being completely new to Python. My question is, why is this valid:

s = 'hijkkpdgijklmnopqqrs'
n = len(s)
i = 0
a = 0
for i in range(n-2):
    if s[i] <= s[i+1]:
       a = s[i+1]
       i = s[i+2]
       a = i + a
print(a)

And yet this is not:

s = 'hijkkpdgijklmnopqqrs'
n = len(s)
i = 0
a = 0
b = ''
for i in range(n-2):
    if s[i] <= s[i+1]:
       b = a + i
       a = s[i+1]
       i = s[i+2]
       a = a + i
print(b)

When the latter code is run, I receive the error:

Traceback (most recent call last):
File "C:\Users\spect\Desktop\newjackcity.py", line 14, in <module>
b = a + i
TypeError: must be str, not int

What I am ultimately trying to do is to 'index in' to the string s, compare the zeroth element to the zeroth+1 element and if s[I] < s[I+1], I want to concatenate the two into my variable a for later printing. Because when I do this, a only prints out two letters in the string. I thought, well initialize the variable first so that a and i can be incremented, then added into a for comparison purposes, and b for printing.

I see now that I'm only going through n-2 iterations (in order to compare the second to last letter to n-1 so the logic is flawed, but I still don't understand the error of why all of a sudden binding a+i to a variable b will produce a str/int error? In my view saying s[i]; etc. is pulling out the elements as a string and this to me is proven in the fact if I run the first set of code, I get the output:

sr
>>>

Body:
In both for loops, you use i as the loop variable, so it starts as an int.

In the first version, you reassign i to a string, then add.

for i in range(n-2):
  # here i is an int, something between 0 and n-2
  if s[i] <= s[i+1]:
    a = s[i+1]  # a is a string...
    i = s[i+2]  # now you change i to a string
    a = i + a  # string + string: OK!

In the second version you try to add i first:

for i in range(n-2):
  # here i is an int, something between 0 and n-2
  if s[i] <= s[i+1]:
     b = a + i # string + int, can't do it...
     a = s[i+1]
     i = s[i+2]
     a = a + i

You will have an easier time debugging your code if you pick more meaningful names.

edit: here is my cleaned up version of your code:

s = 'hijkkpdgijklmnopqqrs'
# i = 0 isn't needed, range starts at 0
# the first character is always 'alphabetical'
alph_substr = s[0]
# range(1,n) is [1,2, ..., n-1]
for i in range(1, len(s)):
  if s[i-1] <= s[i]:
    alph_substr = alph_substr + s[i]
  else:
    # we have to start over, since we're not alphabetical anymore
    print(alph_substr)
    alph_substr = s[i]
print(alph_substr)


来源: stackexchange

问:
TypeError: (intermediate value)(intermediate value).val(...).prop is not a function (ionic)
I've got error message like "TypeError: (intermediate value)(intermediate value).val(...).prop is not a function" on console log after get selected option from $scope. Please check out what's wrong from my script:

HTML Template:

```<code><ion-view view-title="Doll List">
    <ion-content class="has-header">
      <div class="list">
        <label class="item item-input item-select">
          <div class="input-label">
           Product
          </div>
          <select name='options2' ng-model="item.doll" ng-options="DOLLtype as DOLLtype.name for DOLLtype in dolltype track by DOLLType.id">
          </select>
        </label>
        </div>
    </ion-content>
  </ion-view>
</code>```

controller.js

```<code>.controller('DollCtrl', ['$scope', '$stateParams', '$location', '$http', '$window', '$q', '$localStorage', '$rootScope', '$filter', 'DOLLTYPE','$timeout', function($scope, $stateParams, $location, $http, $window, $q, $localStorage, $rootScope,  $filter, DOLLTYPE, $timeout) {

 $scope.item = [];
 $scope.item = {
 id: $stateParams.id
 };

 $scope.dolltype = [];
 DOLLTYPE.get($scope.item.id).then(function(itemtype) {
 $scope.dolltype.push({id:itemtype.id, name:itemtype.name})
 $scope.item.doll =  $scope.dolltype[0];
 console.log($scope.item.doll);
 })
 DOLLTYPE.all().then(function(dolltype){
 $scope.dolltype=dolltype;
 console.log($scope.dolltype);
 })

     }}

 ])
</code>```

How I can fix it?

Note: DOLLTYPE is an example name for services.js for query data with cordova sqlite plugin

答:
Sometimes this can be triggered when you forget a semicolon.
You seem to have forgotten to put semicolons:

$scope.dolltype.push({id:itemtype.id, name:itemtype.name}) ; <---

DOLLTYPE.get(...).then(...) ; <---

and the DOLLTYPE.all().then(...) ; <---

this can sometimes break when you minify

ContentLicense: CC BY-SA 3.0

Body:
I've got error message like "TypeError: (intermediate value)(intermediate value).val(...).prop is not a function" on console log after get selected option from $scope. Please check out what's wrong from my script:

HTML Template:

<ion-view view-title="Doll List">
    <ion-content class="has-header">

           Product

          <select name='options2' ng-model="item.doll" ng-options="DOLLtype as DOLLtype.name for DOLLtype in dolltype track by DOLLType.id">
          </select>

    </ion-content>
  </ion-view>

controller.js

.controller('DollCtrl', ['$scope', '$stateParams', '$location', '$http', '$window', '$q', '$localStorage', '$rootScope', '$filter', 'DOLLTYPE','$timeout', function($scope, $stateParams, $location, $http, $window, $q, $localStorage, $rootScope,  $filter, DOLLTYPE, $timeout) {

 $scope.item = [];
 $scope.item = {
 id: $stateParams.id
 };

 $scope.dolltype = [];
 DOLLTYPE.get($scope.item.id).then(function(itemtype) {
 $scope.dolltype.push({id:itemtype.id, name:itemtype.name})
 $scope.item.doll =  $scope.dolltype[0];
 console.log($scope.item.doll);
 })
 DOLLTYPE.all().then(function(dolltype){
 $scope.dolltype=dolltype;
 console.log($scope.dolltype);
 })

     }}

 ])

How I can fix it?

Note: DOLLTYPE is an example name for services.js for query data with cordova sqlite plugin


问:
Lookahead in Regex
I am trying to extract venue from a file which contains several articles using regex. I know that the venue starts with either For/From and is followed by date which starts with a day of the week or author's name if the date is missing, I wrote the following regex to match the venue, however it always matches everything till the author's name which means the date also comes in the venue if that article has a date.

```<code>"""((?<=\n)(?:(?:\bFrom\b)|(?:\bFor\b)).*?(?=(?:(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)|(?:[A-Z]+))))""".r
</code>```

Why is my code not matching the days if it is encountered but rather goes ahead to match [A-Z] which is the author's name.

Input: "The Consequences of Hostilities Between the States

From the New York Packet.

Tuesday, November 20, 1787.

HAMILTON

To the People of the State of New York:"

The line "Tuesday, November 20, 1787." is optional and may not occur in all articles. I want the output to be "From the New York Packet."
I am getting the correct output for articles that do not have a date, however I am getting the output "From the New York Packet.

Tuesday, November 20, 1787." for articles that contain the date.

答:
You only need to capture the entire line that starts with For or From, so you can simply use this:

```<code>^(For|From).*$
</code>```

The ^ and $ anchor the match to the start and end of the line, and the .* matches everything inbetween.

Here, try it out with whatever examples you like.

If this needs to be more complicated, I'll update my answer.

Title: Lookahead in Regex

Body:
I am trying to extract venue from a file which contains several articles using regex. I know that the venue starts with either For/From and is followed by date which starts with a day of the week or author's name if the date is missing, I wrote the following regex to match the venue, however it always matches everything till the author's name which means the date also comes in the venue if that article has a date.

"""((?<=\n)(?:(?:\bFrom\b)|(?:\bFor\b)).*?(?=(?:(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)|(?:[A-Z]+))))""".r

Why is my code not matching the days if it is encountered but rather goes ahead to match [A-Z] which is the author's name.

Input: "The Consequences of Hostilities Between the States

From the New York Packet.

Tuesday, November 20, 1787.

HAMILTON

To the People of the State of New York:"

The line "Tuesday, November 20, 1787." is optional and may not occur in all articles. I want the output to be "From the New York Packet."
I am getting the correct output for articles that do not have a date, however I am getting the output "From the New York Packet.

Tuesday, November 20, 1787." for articles that contain the date.

Body:
You only need to capture the entire line that starts with For or From, so you can simply use this:

^(For|From).*$

The ^ and $ anchor the match to the start and end of the line, and the .* matches everything inbetween.

Here, try it out with whatever examples you like.

If this needs to be more complicated, I'll update my answer.


问:
Register phantomjs node to Selenium Grid
I am currently running Selenium Grid 3.4.0 and phantomjs 2.1.1 on a windows platform.

When I try to register a phantomjs node onto my hub the following error occurs:

```<code>K:phantomjs-2.1.1-windows/bin/phantomjs.exe --webdriver=8080
--webdriver-selenium-grid-hub=http://IP:5786
[ERROR - 2017-06-05T13:35:55.135Z] GhostDriver - main.fail -
{"line":85,"sourceU
RL":"phantomjs://code/main.js","stack":"global
code@phantomjs://code/main.js:85:56"}
</code>```

phantomjs://platform/console++.js:263 in error

Does anyone know how to get around this error?
Currently my hub is running 5 instances of Firefox, 5 instances of chrome and 1 instance of IE.

```<code>[ERROR - 2017-06-06T14:36:23.920Z] GhostDriver - main.fail -
{"line":97,"sourceURL":"phantomjs://platform/hub_register.js","stack":
"register@phantomjs://platform/hub_register.js:97:79\nglobal
code@phantomjs://code/main.js:78:37"}
</code>```

I ran it again and this time, that is what the error message said.

答: Used Phantomjs 1.9.8 and it worked...</p>

Body:
I am currently running Selenium Grid 3.4.0 and phantomjs 2.1.1 on a windows platform.

When I try to register a phantomjs node onto my hub the following error occurs:

K:phantomjs-2.1.1-windows/bin/phantomjs.exe --webdriver=8080
--webdriver-selenium-grid-hub=http://IP:5786
[ERROR - 2017-06-05T13:35:55.135Z] GhostDriver - main.fail -
{"line":85,"sourceU
RL":"phantomjs://code/main.js","stack":"global
code@phantomjs://code/main.js:85:56"}

phantomjs://platform/console++.js:263 in error

Does anyone know how to get around this error?
Currently my hub is running 5 instances of Firefox, 5 instances of chrome and 1 instance of IE.

[ERROR - 2017-06-06T14:36:23.920Z] GhostDriver - main.fail -
{"line":97,"sourceURL":"phantomjs://platform/hub_register.js","stack":
"register@phantomjs://platform/hub_register.js:97:79\nglobal
code@phantomjs://code/main.js:78:37"}

I ran it again and this time, that is what the error message said.

Body: Used Phantomjs 1.9.8 and it worked...


问:
Why can't SpeechSynthesis.speak() be called more than once in Firefox?
I can call SpeechSynthesis.speak() in Chrome multiple times and get some text read out over and over again. However, if i try the exact same code in Firefox, the first call works fine, but subsequent calls are ignored/silently fail.

It only works again once i refresh the page.

Why is this?

答:
Experimental technology likely not handled correctly by Firefox.

Try a SpeechSynthesis.cancel() before re-iterating your .speak() call.


问:
Create path from javascript object property
Let's say I've got the following javascript object

```<code>var obj = {
            a:{
                b:"value",
                c:{
                    d:"value2"
                }
            }
        }
</code>```

What function would, when input with the "d" object (for example, function getPath(obj, d)), output the "a.c.d" string? I've tried various things including object-path, but it doesn't seem to be designed for that

答:
Here you go. The function you want to use is findLongestPath:

var obj = {
    a:{
        b:"value",
        c:{
            d:"value2"
        }
    }
};

function findAllPaths(obj, property, startString = '') {
  var pathStrings = [];
  Object.keys(obj).forEach(key => {
    if(typeof obj[key] === 'object') {
      pathStrings.push(...findAllPaths(obj[key], property, startString + key + '.'));
      return;
    }

    pathStrings.push(startString + key);
  });

  return pathStrings;
}

function findLongestPath(obj, property) {
  return findAllPaths(obj, property)
    .filter(str => str.split('').reverse().join('').slice(0, property.length) === property.split('').reverse().join(''))
    .reduce((longest, next) => longest.length >= next.length ? longest : next, '');
}

console.log(findLongestPath(obj, 'd'));```

findAllPaths is a recursive function that iterates through the object and generates an array of all possible object paths. findLongestPath filters those strings to make sure the last property matches the property given, and then returns the longest of those.

Body:
Let's say I've got the following javascript object

var obj = {
            a:{
                b:"value",
                c:{
                    d:"value2"
                }
            }
        }

What function would, when input with the "d" object (for example, function getPath(obj, d)), output the "a.c.d" string? I've tried various things including object-path, but it doesn't seem to be designed for that

Body:
Here you go. The function you want to use is findLongestPath:

var obj = {
    a:{
        b:"value",
        c:{
            d:"value2"
        }
    }
};

function findAllPaths(obj, property, startString = '') {
  var pathStrings = [];
  Object.keys(obj).forEach(key => {
    if(typeof obj[key] === 'object') {
      pathStrings.push(...findAllPaths(obj[key], property, startString + key + '.'));
      return;
    }

    pathStrings.push(startString + key);
  });

  return pathStrings;
}

function findLongestPath(obj, property) {
  return findAllPaths(obj, property)
    .filter(str => str.split('').reverse().join('').slice(0, property.length) === property.split('').reverse().join(''))
    .reduce((longest, next) => longest.length >= next.length ? longest : next, '');
}

console.log(findLongestPath(obj, 'd'));

findAllPaths is a recursive function that iterates through the object and generates an array of all possible object paths. findLongestPath filters those strings to make sure the last property matches the property given, and then returns the longest of those.


问:
How to redirect from the main domain to a subdomain in Cloudron?
I have a Cloudron.io app under the www.domain.tld location.

I wan't the main domain domain.tld to redirect to www.domain.tld.

How do I achieve this?

答:
It is possible to redirect from a container to another with a simple Apache redirect.

Use the "LAMP"-app or built your own.


问:
Set remote branch to a commit we don't have locally
Some intern did a force push on master yesterday. After we've done scolding, ;) we looked at the result. Luckily, we had an almost up to date version of the master on one machine, only some pull requests have to be merged again.

But one thing is bugging me: We found the old HEAD commit referenced in the last merged pull requests (on github), but since no branch or tag was pointing to it anymore, we couldn't find any way to either pull that commit (git pull origin <SHA1> didn't work) or to set a remote branch to that commit. Do you see any way to do that?

答:
If you can see the commit on GitHub, e.g. at https://github.com/[org]/[repo]/commit/[sha] but it is orphaned, GitHub won't include it when you clone/fetch the repo.

If you change the URL slightly, though, to https://github.com/[org]/[repo]/tree/[sha], you can use the branch dropdown to create a branch at that commit:


问:
How can i change the text of a textView every time i press a button?
I am just starting learning android and i started making an experimental app.My goal is when i press the button ,the text should change in this way:when it is "OFF" ,pressing the button should make it "ON"  and the opposite.
Here is my code:

```<code>public class MainActivity extends AppCompatActivity {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.TextView);
        Button button = (Button) findViewById(R.id.button);

        button.setOnTouchListener(new View.OnTouchListener(){

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                String text="";
                    if (textView.getText().equals("ON")) {
                       text="OFF";
                    } else if (textView.getText().equals("OFF")) {
                        text="ON";
                    }
                textView.setText(text);
                return false;
            }

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

When i run it and press the button ,the app shows the "OFF" for a fraction of a second and then "ON" again.This happens every time i press the button."ON" is the default value.I just would like to know what am i missing here?

答:
You have to use setOnClickListener, not setOnTouchListener because touch is very more sensible to the touch than the click. Write this code:

```<code>button.setOnClickListener(new View.OnClickListener(){

    @Override
    public void onClick(View v) {
        String text="";
            if (textView.getText().equals("ON")) {
               text="OFF";

            }
            else if (textView.getText().equals("OFF")) {
                text="ON";

            }
        textView.setText(text);
    }

});
</code>```

Body:
I am just starting learning android and i started making an experimental app.My goal is when i press the button ,the text should change in this way:when it is "OFF" ,pressing the button should make it "ON"  and the opposite.
Here is my code:

public class MainActivity extends AppCompatActivity {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.TextView);
        Button button = (Button) findViewById(R.id.button);

        button.setOnTouchListener(new View.OnTouchListener(){

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                String text="";
                    if (textView.getText().equals("ON")) {
                       text="OFF";
                    } else if (textView.getText().equals("OFF")) {
                        text="ON";
                    }
                textView.setText(text);
                return false;
            }

        });
    }
}

When i run it and press the button ,the app shows the "OFF" for a fraction of a second and then "ON" again.This happens every time i press the button."ON" is the default value.I just would like to know what am i missing here?

Body:
You have to use setOnClickListener, not setOnTouchListener because touch is very more sensible to the touch than the click. Write this code:

button.setOnClickListener(new View.OnClickListener(){

    @Override
    public void onClick(View v) {
        String text="";
            if (textView.getText().equals("ON")) {
               text="OFF";

            }
            else if (textView.getText().equals("OFF")) {
                text="ON";

            }
        textView.setText(text);
    }

});


问:
JavaScript count items that have been run in an array
I'm very new to Javascript so i'm looking for a bit of help.
I have a webpage that loads a iframe and loops through loads of URLs. This all works after a bit of help.

However i now need a div showing the count of the completed urls, so everytime it does one it increases the count by one.

Any ideads?

答:
Add an id to your div with class='count1' and set it's value equal to the index.

```<code><script>

    var i = 0;

    $document.getElementByID('count1').innerHTML = "URL Count: "+'index here';

</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Add an id to your div with class='count1' and set it's value equal to the index.

<script>

    var i = 0;

    $document.getElementByID('count1').innerHTML = "URL Count: "+'index here';

</script>


问:
how to parse html contents returned as a response from a webserver and show a specific tag value in a combobox in desktop application in vb.net
i am trying to fetch some data from Url using Httpwebrequest/response, i am getting response which i am showing in a msgbox. It show whole HTML contents.
Now my i want to fetch a specific tag(TD tag) value and show all its value in a combobox in vb.net desktop application.

my code to get response from webserver is :

```<code>enter code here
</code>```

Imports System.IO

Imports System.Net

Imports System.Xml

Imports System.Text.Encoder

Public Class login

```<code>Private Sub login_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    End
End Sub

Private Sub Panel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint

End Sub

Private Sub Ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Ok.Click
    Dim strId As String = txt_uid.Text
    Dim strPwd As String = txt_pwd.Text
    Dim oEncoder As New System.Text.ASCIIEncoding
    Dim postData As String = "UM_username=" + strId
    postData += ("&UM_password=" + strPwd)

    Dim data As Byte() = oEncoder.GetBytes(postData)
    MsgBox(postData)

    Dim webStream As Stream

    Dim webResponse As String = ""

    Dim req As HttpWebRequest

    Dim res As HttpWebResponse
    Dim Output As String
    'Dim Posit1 As Int32
    'Dim Posit2 As Int32

  req = WebRequest.Create("http://localhost/basic_framework/index.php?menu=login&UM_email=" & strId & "&UM_password=" & strPwd)
</code>```

req.ContentType = "application/x-www-form-urlencoded"
        req.KeepAlive = False
        req.Method = "POST"
        res = req.GetResponse()

```<code>    webStream = res.GetResponseStream()

    Dim webStreamReader As New StreamReader(webStream)
    While webStreamReader.Peek >= 0
        Output = webStreamReader.ReadToEnd()
        RichTextBox1.Text = Output
</code>```

Msgbox(Output)

```<code>    End While

End Sub
</code>```

End Class

this code get the response from url and show it in a richtextbox or msgbox
Now i want to get a specific tag value (say, td, option values) and show it in a combobox in my vb.net application form dynamically.It would be needed to parse html content then get that tag value . Please suggest me a way......
If parsing needed , how to parse html contents to get only specific tag value in a combobox in vb.net form

答: For the most complicated cases (e.g., an AJAX web-site, etc.) you could use HTMLUnit library with iKVM.</p>

ContentLicense: CC BY-SA 2.5

Body:
i am trying to fetch some data from Url using Httpwebrequest/response, i am getting response which i am showing in a msgbox. It show whole HTML contents.
Now my i want to fetch a specific tag(TD tag) value and show all its value in a combobox in vb.net desktop application.

my code to get response from webserver is :

enter code here

Imports System.IO

Imports System.Net

Imports System.Xml

Imports System.Text.Encoder

Public Class login

Private Sub login_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    End
End Sub

Private Sub Panel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint

End Sub

Private Sub Ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Ok.Click
    Dim strId As String = txt_uid.Text
    Dim strPwd As String = txt_pwd.Text
    Dim oEncoder As New System.Text.ASCIIEncoding
    Dim postData As String = "UM_username=" + strId
    postData += ("&UM_password=" + strPwd)

    Dim data As Byte() = oEncoder.GetBytes(postData)
    MsgBox(postData)

    Dim webStream As Stream

    Dim webResponse As String = ""

    Dim req As HttpWebRequest

    Dim res As HttpWebResponse
    Dim Output As String
    'Dim Posit1 As Int32
    'Dim Posit2 As Int32

  req = WebRequest.Create("http://localhost/basic_framework/index.php?menu=login&UM_email=" & strId & "&UM_password=" & strPwd)

req.ContentType = "application/x-www-form-urlencoded"
        req.KeepAlive = False
        req.Method = "POST"
        res = req.GetResponse()

    webStream = res.GetResponseStream()

    Dim webStreamReader As New StreamReader(webStream)
    While webStreamReader.Peek >= 0
        Output = webStreamReader.ReadToEnd()
        RichTextBox1.Text = Output

Msgbox(Output)

    End While

End Sub

End Class

this code get the response from url and show it in a richtextbox or msgbox
Now i want to get a specific tag value (say, td, option values) and show it in a combobox in my vb.net application form dynamically.It would be needed to parse html content then get that tag value . Please suggest me a way......
If parsing needed , how to parse html contents to get only specific tag value in a combobox in vb.net form


答:
There are tons of MotionEvent s that get generated on touch. Look for Action
Put your code inside event.getAction()==MotionEvent.ACTION_DOWN

Title: How can i change the text of a textView every time i press a button?


问:
How to do an upsert with SqlAlchemy?
I have a record that I want to exist in the database if it is not there, and if it is there already (primary key exists) I want the fields to be updated to the current state.  This is often called an upsert.

The following incomplete code snippet demonstrates what will work, but it seems excessively clunky (especially if there were a lot more columns).  What is the better/best way?

```<code>Base = declarative_base()
class Template(Base):
    __tablename__ = 'templates'
    id = Column(Integer, primary_key = True)
    name = Column(String(80), unique = True, index = True)
    template = Column(String(80), unique = True)
    description = Column(String(200))
    def __init__(self, Name, Template, Desc):
        self.name = Name
        self.template = Template
        self.description = Desc

def UpsertDefaultTemplate():
    sess = Session()
    desired_default = Template("default", "AABBCC", "This is the default template")
    try:
        q = sess.query(Template).filter_by(name = desiredDefault.name)
        existing_default = q.one()
    except sqlalchemy.orm.exc.NoResultFound:
        #default does not exist yet, so add it...
        sess.add(desired_default)
    else:
        #default already exists.  Make sure the values are what we want...
        assert isinstance(existing_default, Template)
        existing_default.name = desired_default.name
        existing_default.template = desired_default.template
        existing_default.description = desired_default.description
    sess.flush()
</code>```

Is there a better or less verbose way of doing this?  Something like this would be great:

```<code>sess.upsert_this(desired_default, unique_key = "name")
</code>```

although the unique_key kwarg is obviously unnecessary (the ORM should be able to easily figure this out) I added it just because SQLAlchemy tends to only work with the primary key.  eg: I've been looking at whether Session.merge would be applicable, but this works only on primary key, which in this case is an autoincrementing id which is not terribly useful for this purpose.

A sample use case for this is simply when starting up a server application that may have upgraded its default expected data.  ie: no concurrency concerns for this upsert.

答:
SQLAlchemy supports ON CONFLICT with two methods on_conflict_do_update() and on_conflict_do_nothing().

Copying from the documentation:

```<code>from sqlalchemy.dialects.postgresql import insert

stmt = insert(my_table).values(user_email='a@b.com', data='inserted data')
stmt = stmt.on_conflict_do_update(
    index_elements=[my_table.c.user_email],
    index_where=my_table.c.user_email.like('%@gmail.com'),
    set_=dict(data=stmt.excluded.data)
)
conn.execute(stmt)
</code>```

Title: How to do an upsert with SqlAlchemy?

Body:
I have a record that I want to exist in the database if it is not there, and if it is there already (primary key exists) I want the fields to be updated to the current state.  This is often called an upsert.

The following incomplete code snippet demonstrates what will work, but it seems excessively clunky (especially if there were a lot more columns).  What is the better/best way?

Base = declarative_base()
class Template(Base):
    __tablename__ = 'templates'
    id = Column(Integer, primary_key = True)
    name = Column(String(80), unique = True, index = True)
    template = Column(String(80), unique = True)
    description = Column(String(200))
    def __init__(self, Name, Template, Desc):
        self.name = Name
        self.template = Template
        self.description = Desc

def UpsertDefaultTemplate():
    sess = Session()
    desired_default = Template("default", "AABBCC", "This is the default template")
    try:
        q = sess.query(Template).filter_by(name = desiredDefault.name)
        existing_default = q.one()
    except sqlalchemy.orm.exc.NoResultFound:
        #default does not exist yet, so add it...
        sess.add(desired_default)
    else:
        #default already exists.  Make sure the values are what we want...
        assert isinstance(existing_default, Template)
        existing_default.name = desired_default.name
        existing_default.template = desired_default.template
        existing_default.description = desired_default.description
    sess.flush()

Is there a better or less verbose way of doing this?  Something like this would be great:

sess.upsert_this(desired_default, unique_key = "name")

although the unique_key kwarg is obviously unnecessary (the ORM should be able to easily figure this out) I added it just because SQLAlchemy tends to only work with the primary key.  eg: I've been looking at whether Session.merge would be applicable, but this works only on primary key, which in this case is an autoincrementing id which is not terribly useful for this purpose.

A sample use case for this is simply when starting up a server application that may have upgraded its default expected data.  ie: no concurrency concerns for this upsert.

Body:
SQLAlchemy supports ON CONFLICT with two methods on_conflict_do_update() and on_conflict_do_nothing().

Copying from the documentation:

from sqlalchemy.dialects.postgresql import insert

stmt = insert(my_table).values(user_email='a@b.com', data='inserted data')
stmt = stmt.on_conflict_do_update(
    index_elements=[my_table.c.user_email],
    index_where=my_table.c.user_email.like('%@gmail.com'),
    set_=dict(data=stmt.excluded.data)
)
conn.execute(stmt)


问:
How to call Parent Page property in UserControl
I have my parent page as OPC.aspx where Addressdetail.ascx is declared as usercontrol.

Now I have made one property in my parent page(OPC.aspx) as

```<code>public string SelectedOptionUserControl { get; set; }
</code>```

Now I want to set property named SelectedOptionUserControl in usercontrol(Addressdetail.ascx) i.e. I want to set the property of parent page in child page

on Addressdetail.ascx  code below

```<code>protected void Page_Load(object sender, EventArgs e)
    {
     this.Page.Master.SelectedOptionUserControl="abc";
     this.Page.GetType().InvokeMember("SelectedOptionUserControl", System.Reflection.BindingFlags.InvokeMethod, null, this.Page, new object[] { "abc" });
    }
</code>```

I have tried this 2 ways but not working for me.

答:
This

```<code>public string SelectedOptionUserControl { get; set; }
</code>```

declares a property, not a method.

So change

```<code>System.Reflection.BindingFlags.InvokeMethod
</code>```

To

```<code>System.Reflection.BindingFlags.SetProperty
</code>```

Body:
I have my parent page as OPC.aspx where Addressdetail.ascx is declared as usercontrol.

Now I have made one property in my parent page(OPC.aspx) as

public string SelectedOptionUserControl { get; set; }

Now I want to set property named SelectedOptionUserControl in usercontrol(Addressdetail.ascx) i.e. I want to set the property of parent page in child page

on Addressdetail.ascx  code below

protected void Page_Load(object sender, EventArgs e)
    {
     this.Page.Master.SelectedOptionUserControl="abc";
     this.Page.GetType().InvokeMember("SelectedOptionUserControl", System.Reflection.BindingFlags.InvokeMethod, null, this.Page, new object[] { "abc" });
    }

I have tried this 2 ways but not working for me.

Body:
This

public string SelectedOptionUserControl { get; set; }

declares a property, not a method.

So change

System.Reflection.BindingFlags.InvokeMethod

To

System.Reflection.BindingFlags.SetProperty


问:
How to insert sms into sent folder on android
After sending a sms, write the sms into sent folder.
How can i do it on android?</p>

```<code>SmsManager sm = SmsManager.getDefault();
sm.sendTextMessage(to, null, text, null, null);
</code>```

答:
There is no "sent folder" in Android.

Some SMS clients may have a "sent folder". You would have to contact the developers of those applications to find out if there is a documented and supported API for manipulating that folder. For example, there is no documented and supported API for the Messenger application that is part of the Android open source project.

Body:
After sending a sms, write the sms into sent folder.
How can i do it on android?

SmsManager sm = SmsManager.getDefault();
sm.sendTextMessage(to, null, text, null, null);


问:
MVVM Binding between two user controls with separate view models
i have a window which loads a Customer table and another user control of input fields, when i select i wish to populate the user control inputs. I currently have a datagrid that a selected item is set in the CustomerViewModel through binding. When this is selected it updates a textbox with the selected items property such as name, email, etc. I have a CustomerSettingsViewModel which contains multiple input fields. I am trying to bind the selected item to inputs within this model, however as the CustomerViewModel doesn't know about the CustomerSettingsViewModel i cant see the binds within the textbox inputs.

The views are loaded using DataTemplate using the datatype.

MainWindow.xaml

```<code>    <Window.Resources>
            <DataTemplate  DataType="{x:Type VM:CustomerVM}">
                <View:Customers/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type VM:CustomerSettingsVM}">
                <View:CustomerSettings />
            </DataTemplate>
            <DataTemplate DataType="{x:Type VM:SuppliersVM}">
                <View:Suppliers/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type VM:SuppliersSettingsVM}">
                <View:SupplierSettings/>
            </DataTemplate>
        </Window.Resources>

<ContentControl Content="{Binding SelectedMain}"  Margin="0,135,0,10" Grid.ColumnSpan="2"/>
<ContentControl Content="{Binding SelectedSettings}"  Margin="105,53,10,45"/>
</code>```

These are set and get the correct views depending on the datatype that being presented.

MainVM.cs

```<code>Customer = new CustomerVM();
CustomerSettings = new CustomerSettingsVM();
SelectedMain = Customer;
SelectedSettings = CustomerSettings;
</code>```

within the CustomerVM i have a get and selected with binds to anything within the customer view, however how can i get the customer settings view to see the selected customer has changed and populate the inputs?

CustomerVM.cs

```<code> public Customer SelectedCustomer
        {
            get { return _selectedCustomer; }
            set
            {
                _selectedCustomer = value;
                RaisePropertyChangedEvent("SelectedCustomer");
            }
        }
</code>```

i have upload a simple solution of my problem onto GitHub Might give a better understanding of what i am trying to achieve

答:
I think you missed a few concepts about MVVM, maybe you should go back to basics.
Basically, your viewmodels have to be a "testable copy" of your view.
So if your target is to build a Customer View containing Customer Settings, what you need is:

a CustomerViewModel with a CustomerSettingsViewModel property

a CustomerView using CustomerViewModel as datacontext

a CustomerSettingsView declared into your CustomerView binded to the CustomerSettingsViewModel from the CustomerViewModel

Another way to put this: if you want a view to contain another view, you can have a viewModel to contain another viewModel.

This other question could show you how to use a vm as a property of another vm.

Please see my proposed solution using your GitHub example. Basically your problem is that you should not use directly the Customer Model in a View, but create a CustomerVm instead, and just delete the CustomerSettingVm.
You might understand better my implementation by reading how I'm used to deal with MVVM.

Hope it helps.

Body:
i have a window which loads a Customer table and another user control of input fields, when i select i wish to populate the user control inputs. I currently have a datagrid that a selected item is set in the CustomerViewModel through binding. When this is selected it updates a textbox with the selected items property such as name, email, etc. I have a CustomerSettingsViewModel which contains multiple input fields. I am trying to bind the selected item to inputs within this model, however as the CustomerViewModel doesn't know about the CustomerSettingsViewModel i cant see the binds within the textbox inputs.

The views are loaded using DataTemplate using the datatype.

MainWindow.xaml

    <Window.Resources>
            <DataTemplate  DataType="{x:Type VM:CustomerVM}">
                <View:Customers/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type VM:CustomerSettingsVM}">
                <View:CustomerSettings />
            </DataTemplate>
            <DataTemplate DataType="{x:Type VM:SuppliersVM}">
                <View:Suppliers/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type VM:SuppliersSettingsVM}">
                <View:SupplierSettings/>
            </DataTemplate>
        </Window.Resources>

<ContentControl Content="{Binding SelectedMain}"  Margin="0,135,0,10" Grid.ColumnSpan="2"/>
<ContentControl Content="{Binding SelectedSettings}"  Margin="105,53,10,45"/>

These are set and get the correct views depending on the datatype that being presented.

MainVM.cs

Customer = new CustomerVM();
CustomerSettings = new CustomerSettingsVM();
SelectedMain = Customer;
SelectedSettings = CustomerSettings;

within the CustomerVM i have a get and selected with binds to anything within the customer view, however how can i get the customer settings view to see the selected customer has changed and populate the inputs?

CustomerVM.cs

 public Customer SelectedCustomer
        {
            get { return _selectedCustomer; }
            set
            {
                _selectedCustomer = value;
                RaisePropertyChangedEvent("SelectedCustomer");
            }
        }

i have upload a simple solution of my problem onto GitHub Might give a better understanding of what i am trying to achieve


问:
How do I bind a List<string> to an ItemsControl?
In my presenter I have this property:

```<code>public List<string> PropertyNames { get; set; }
</code>```

And I want to list out the names with a ItemsControl/DataTemplate like this:

```<code><ItemsControl ItemsSource="{Binding PropertyNames}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Value}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
</code>```

Since the generic list doesn't have named properties, how do I reference the value in my Binding statement?

答:
An easier way to accomplish the same thing is to simply use:

```<code><ItemsControl ItemsSource="{Binding PropertyNames}"/>
</code>```

By default, this will create a vertical StackPanel and add each element in its own TextBlock. According to MSDN, this works for any of the following:

A string.

A DateTime object.

A UIElement object.

A Panel control that contains an Ellipse and a TextBlock.

Body:
In my presenter I have this property:

public List<string> PropertyNames { get; set; }

And I want to list out the names with a ItemsControl/DataTemplate like this:

<ItemsControl ItemsSource="{Binding PropertyNames}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Value}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Since the generic list doesn't have named properties, how do I reference the value in my Binding statement?

Body:
An easier way to accomplish the same thing is to simply use:

<ItemsControl ItemsSource="{Binding PropertyNames}"/>

By default, this will create a vertical StackPanel and add each element in its own TextBlock. According to MSDN, this works for any of the following:

A string.

A DateTime object.

A UIElement object.

A Panel control that contains an Ellipse and a TextBlock.


问:
Mixing fPIC and non-fPIC object modules
Environment: Ubuntu 16.04

In my experiment, I ran the following commands:

```<code>gcc -c 1.c
gcc -c -fPIC 2.c
gcc -shared 1.o 2.o -o libmyxxx.so
</code>```

The functions that I need to expose are all defined in 2.c via extern "C" declarations. These functions internally call other functions that are defined in 1.c.

Note that I did not apply -fPIC to 1.c. Still everything seems to compile/link fine without any warnings.

Can we conclude that -fPIC must be applied only to those source files that expose external functions?

In the larger picture, I have a bunch of archive (.a) files that may not have been compiled with -fPIC flag. I need to create a custom shared library that would link with these archive files. If my assumption is valid, I am thinking it would be okay to link with these archive files. Appreciate your thoughts. Regards.

答:
Can we conclude that -fPIC must be applied only to those source files
  that expose external functions?

No we can't. The only purpose of -fPIC is ensure that produced machine code can be linked into position-independent binary. Nevertheless it is possible that some code appears to be PIC-ready even if source was compiled without -fPIC. It may be short self-containing functions without external dependencies, whatever that will not require auxiliary data structures in generated object file, like PLT and GOT entries.

Anyway linker will fail with comprehensive error message if your object file cannot be linked into position-independent binary. And you need to recompile it with this magic option.

So you should always put -fPIC to CFLAGS of your shared library just to save your own time and avoid wasteful recompilations.

Title: Mixing fPIC and non-fPIC object modules

Body:
Environment: Ubuntu 16.04

In my experiment, I ran the following commands:

gcc -c 1.c
gcc -c -fPIC 2.c
gcc -shared 1.o 2.o -o libmyxxx.so

The functions that I need to expose are all defined in 2.c via extern "C" declarations. These functions internally call other functions that are defined in 1.c.

Note that I did not apply -fPIC to 1.c. Still everything seems to compile/link fine without any warnings.

Can we conclude that -fPIC must be applied only to those source files that expose external functions?

In the larger picture, I have a bunch of archive (.a) files that may not have been compiled with -fPIC flag. I need to create a custom shared library that would link with these archive files. If my assumption is valid, I am thinking it would be okay to link with these archive files. Appreciate your thoughts. Regards.


问:
Session Variable problems when storing an object in my Session
I have a log in page where I valid my users and based on this validation I store their user info in a session variable so I can access it at any time.  To do this I am trying to store an instance of one of my dbml generated classes "UserInfo".  So I populate the class and then store it in a session variable I call "user"

```<code> UserInfo u = new UserInfo();
    u = dal.RetrieveUser(userID, userPass)
    Session["user"] = u;
</code>```

The issue I am having with this is it seems to mix up these session variables between users.  Or more specifically it always seems to take the information from the first user variable stored for each subsequent user that logs in.  So user 1's info is being pulled in for User 2, User 3, etc...

Is my problem that my class "UserInfo" is somehow static? Or what is causing this to happen?  My UserInfo class looks like this:

```<code>public partial class UserInfo
    {
        ...
</code>```

EDIT:
After further review it seems that my Session variables are in fact working properly but my custom menus are actually the problem.

答: Sounds more like an issue with the DAL than the session object. Can you verify that the userID passed each time is different and the RetrieveUser function is using the passed value and not a static one?</p>

OwnerDisplayName: Collin Estes

Body:
I have a log in page where I valid my users and based on this validation I store their user info in a session variable so I can access it at any time.  To do this I am trying to store an instance of one of my dbml generated classes "UserInfo".  So I populate the class and then store it in a session variable I call "user"

 UserInfo u = new UserInfo();
    u = dal.RetrieveUser(userID, userPass)
    Session["user"] = u;

The issue I am having with this is it seems to mix up these session variables between users.  Or more specifically it always seems to take the information from the first user variable stored for each subsequent user that logs in.  So user 1's info is being pulled in for User 2, User 3, etc...

Is my problem that my class "UserInfo" is somehow static? Or what is causing this to happen?  My UserInfo class looks like this:

public partial class UserInfo
    {
        ...

EDIT:
After further review it seems that my Session variables are in fact working properly but my custom menus are actually the problem.

LastEditorDisplayName: Collin Estes

OwnerDisplayName: Chris Simpson


问:
Reprovision a user in AD using OIM 11 R2
i have a user in oim who i need to provision in AD. The existing AD Instance was stuck in provisioning.  I need to know how to force oim to re provision this AD instance.  i have already revoked the previous instance and went requested another instance but its still in the provisioning state.</p>

答:
You can't revoke the one which stuck in Provisioning. You can try to troubleshoot why your first one has not finished the provisioning process. Check the resource history, if you want to do that.

You can request another one account regardless of the first one, but if the root reason for the failure of the first one is still there, you will end with the same result. So both of your accounts will be in Provisioning.


问:
Create request with POST, which response codes 200 or 201 and content
Suppose I write a REST service whose intent is to add a new data item to a system.

I plan to POST to

```<code>http://myhost/serviceX/someResources
</code>```

Suppose that works, what response code should I use? And what content might I return.

I'm looking at the definitions of HTTP response codes and see these possibilities:

200: Return an entity describing or containing the result of the action;

201: which means CREATED. Meaning *The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field. The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. *

The latter sounds more in line with the Http spec, but I'm not at all clear what

The response SHOULD include an entity
  containing a list of resource
  characteristics and location(s)

means.

Recommendations? Interpretations?

答:
In a few words:

200 when an object is created and returned

201 when an object is created but only its reference is returned (such as an ID or a link)

Body:
Suppose I write a REST service whose intent is to add a new data item to a system.

I plan to POST to

http://myhost/serviceX/someResources

Suppose that works, what response code should I use? And what content might I return.

I'm looking at the definitions of HTTP response codes and see these possibilities:

200: Return an entity describing or containing the result of the action;

201: which means CREATED. Meaning *The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field. The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. *

The latter sounds more in line with the Http spec, but I'm not at all clear what

The response SHOULD include an entity
  containing a list of resource
  characteristics and location(s)

means.

Recommendations? Interpretations?


问:
Asserting that a parent component exists in angular unit test
I have a top level component AppComponent and in it's template property it renders the <child> element on the page. (<child> is another Angular component).

Do I need to tell the unit test to ignore the <child> element or declare it in some way for the test?

I'm not actually trying to test <child> in this test file, I will create a separate unit test file to validate it's functionality.

app.module.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ChildComponent } from './child.component';

@NgModule({
  bootstrap: [AppComponent],
  declarations: [AppComponent, ChildComponent],
  imports: [BrowserModule]
})
export class AppModule { }
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app',
  template: '<child></child>'
})
export class AppComponent { }
</code>```

child.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'child',
  templateUrl: './child.component.html'
})
export class ChildComponent { }
</code>```

app.component.spec.ts

```<code>import { async, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { ChildComponent } from './child.component';

describe('App', (() => {
  beforeEach(async() => {
    TestBed.configureTestingModule({ declarations: [AppComponent, ChildComponent] }).compileComponents();
  }));
  it('should work', () => {
    let fixture = TestBed.createComponent(AppComponent);
    // assert app.component exists
  });
});
</code>```

When I run the unit test, I'm getting this error:

```<code>Error: This test module uses the component ChildComponent which is using a "templateUrl" or "styleUrls", but they were never compiled. Please call "TestBed.compileComponents" before your test. in /tmp/karma-typescript-bundle-3142O76A6m7KjQOD.js (line 3929)
</code>```

答:
The error indicates that other units (ChildComponent) are involved in test. This error is caused by the fact that ChildComponent uses templateUrl, and such components may need to call compileComponents to compile them.

Since AppComponent has template and not templateUrl, this makes a test synchronous and makes async helper unnecessary, also eliminates the need to use compileComponents.

As explained in the guide,

The TestBed.compileComponents method asynchronously compiles all the components configured in the testing module. In this example, the BannerComponent is the only component to compile. When compileComponents completes, the external templates and css files have been "inlined" and TestBed.createComponent can create new instances of BannerComponent synchronously.

Unit test presumes that only one unit is tested, while other units are ignored, stubbed or mocked. This allows to keep a test isolated.

Since undeclared components will result in error, they have to be stubbed:

```<code>  beforeEach(() => {
    @Component({ selector: 'child', template: '' })
    class DummyChildComponent {}

    TestBed.configureTestingModule({ declarations: [AppComponent, DummyChildComponent] });
  });
</code>```

An alternative to dummy component is CUSTOM_ELEMENTS_SCHEMA or NO_ERRORS_SCHEMA, which aren't suitable in tests because any possible error output may be valuable. And custom schema is more heavy-weight solution.

Body:
I have a top level component AppComponent and in it's template property it renders the <child> element on the page. (<child> is another Angular component).

Do I need to tell the unit test to ignore the <child> element or declare it in some way for the test?

I'm not actually trying to test <child> in this test file, I will create a separate unit test file to validate it's functionality.

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ChildComponent } from './child.component';

@NgModule({
  bootstrap: [AppComponent],
  declarations: [AppComponent, ChildComponent],
  imports: [BrowserModule]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app',
  template: '<child></child>'
})
export class AppComponent { }

child.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'child',
  templateUrl: './child.component.html'
})
export class ChildComponent { }

app.component.spec.ts

import { async, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { ChildComponent } from './child.component';

describe('App', (() => {
  beforeEach(async() => {
    TestBed.configureTestingModule({ declarations: [AppComponent, ChildComponent] }).compileComponents();
  }));
  it('should work', () => {
    let fixture = TestBed.createComponent(AppComponent);
    // assert app.component exists
  });
});

When I run the unit test, I'm getting this error:

Error: This test module uses the component ChildComponent which is using a "templateUrl" or "styleUrls", but they were never compiled. Please call "TestBed.compileComponents" before your test. in /tmp/karma-typescript-bundle-3142O76A6m7KjQOD.js (line 3929)

Body:
The error indicates that other units (ChildComponent) are involved in test. This error is caused by the fact that ChildComponent uses templateUrl, and such components may need to call compileComponents to compile them.

Since AppComponent has template and not templateUrl, this makes a test synchronous and makes async helper unnecessary, also eliminates the need to use compileComponents.

As explained in the guide,

The TestBed.compileComponents method asynchronously compiles all the components configured in the testing module. In this example, the BannerComponent is the only component to compile. When compileComponents completes, the external templates and css files have been "inlined" and TestBed.createComponent can create new instances of BannerComponent synchronously.

Unit test presumes that only one unit is tested, while other units are ignored, stubbed or mocked. This allows to keep a test isolated.

Since undeclared components will result in error, they have to be stubbed:

  beforeEach(() => {
    @Component({ selector: 'child', template: '' })
    class DummyChildComponent {}

    TestBed.configureTestingModule({ declarations: [AppComponent, DummyChildComponent] });
  });

An alternative to dummy component is CUSTOM_ELEMENTS_SCHEMA or NO_ERRORS_SCHEMA, which aren't suitable in tests because any possible error output may be valuable. And custom schema is more heavy-weight solution.


问:
Endless scrolling horizontal scrollview with limited visible items
I want an simple endless scrolling horizontal scrollview with limited visible items like in following image :
http://i.stack.imgur.com/uDqkn.jpg

Like in this image 4 views visible at a time, and last item showing on left side of first item, like any carousel works.

Currently I am using simpel HorizontalScrollView :

```<code><HorizontalScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:overScrollMode="never"
    android:requiresFadingEdge="none"
    android:scrollbars="none">

    <LinearLayout
        android:id="@+id/itv_tabs_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

<!--Some Views-->

       </LinearLayout>
</LinearLayout>
</code>```

but I need that to be circular.. like I can move that to both direction without any limitation

Any suggestion or links will be helpful.

Thanks

答:
Follow Creating Lists and Cards with following changes:

In RecyclerView element in xml add android:orientation property with value horizontal

```<code><!-- A RecyclerView with some commonly used attributes -->
<android.support.v7.widget.RecyclerView
    android:id="@+id/my_recycler_view"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" /> // <-- this is changed
</code>```

After setting up RecyclerView scroll to middle position:

```<code> // specify an adapter (see also next example)
 mAdapter = new MyAdapter(myDataset);
 mRecyclerView.setAdapter(mAdapter);
 mRecyclerView.scrollToPosition(Integer.MAX_VALUE / 2);
</code>```

Update onBindViewHolder() to return correct ViewHolder in case value exceeds limit:

```<code>// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    // - get element from your dataset at this position
    // - replace the contents of the view with that element
    holder.mTextView.setText(mDataset[position % mDataset.length]);  // <-- this is changed
}
</code>```

Finally, return Integer.MAX_VALUE from getItemCount()

```<code>// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
    return Integer.MAX_VALUE;
}
</code>```

Limitation:
I am assuming that the user won't scroll the view Integer.MAX_VALUE/2 times otherwise they would reach the end.

Hope this helps.

Body:
I want an simple endless scrolling horizontal scrollview with limited visible items like in following image :
http://i.stack.imgur.com/uDqkn.jpg

Like in this image 4 views visible at a time, and last item showing on left side of first item, like any carousel works.

Currently I am using simpel HorizontalScrollView :

<HorizontalScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:overScrollMode="never"
    android:requiresFadingEdge="none"
    android:scrollbars="none">

    <LinearLayout
        android:id="@+id/itv_tabs_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

       </LinearLayout>
</LinearLayout>

but I need that to be circular.. like I can move that to both direction without any limitation

Any suggestion or links will be helpful.

Thanks

Body:
Follow Creating Lists and Cards with following changes:

In RecyclerView element in xml add android:orientation property with value horizontal

<!-- A RecyclerView with some commonly used attributes -->
<android.support.v7.widget.RecyclerView
    android:id="@+id/my_recycler_view"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" /> // <-- this is changed

After setting up RecyclerView scroll to middle position:

 // specify an adapter (see also next example)
 mAdapter = new MyAdapter(myDataset);
 mRecyclerView.setAdapter(mAdapter);
 mRecyclerView.scrollToPosition(Integer.MAX_VALUE / 2);

Update onBindViewHolder() to return correct ViewHolder in case value exceeds limit:

// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    // - get element from your dataset at this position
    // - replace the contents of the view with that element
    holder.mTextView.setText(mDataset[position % mDataset.length]);  // <-- this is changed
}

Finally, return Integer.MAX_VALUE from getItemCount()

// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
    return Integer.MAX_VALUE;
}

Limitation:
I am assuming that the user won't scroll the view Integer.MAX_VALUE/2 times otherwise they would reach the end.

Hope this helps.


问:
Use amp-img tag in place of img tag for images - Sphinx
I am working on creating a Sphinx theme based on Accelerated Mobile Pages (AMP). While creating it, I came to realize that since AMP uses amp-img tag in place of the img tag. Is there a way to convert all the img tag in the sphinx generated docs to amp-img

答: There is nothing out of the box. The easiest option is to post-process your HTML output from Sphinx.</p>


问:
Keeping Data synchronously From Posts with same UploadKey
I am working on an app where you can post pictures in different categories.
For instance : Animals / Motorcycles.

My user can follow users and see therefor their pictures.

Now I am working on the following: I want to upload a post in a category and at the same time in all posts( a separate screen where users can randomly see all posted pictures)

Every Posts, no matter where posted, will be in the allPosts child

```<code>var REF_POST = Database.database().reference().child("posts")
</code>```

and for each category there is a specific child where just the posts from this category stay in

```<code>var REF_POST = Database.database().reference().child("motorcycles")
</code>```

Now in the feed you can like and comment without a problem.
It uses the data from the child "allPosts"

Now I would like to automatically keep the data in synchrony with the post in motorcycles. They both share the same key but obviously it only get updated in the "allPosts" child.

The goal is to update each category always on the data from "allPosts" and reverse. So if a user liked in the category it will be also updated in "allPosts".

Update Code

```<code>func incrementLikesFeed(postId: String,  onSuccess: @escaping (Post) -> Void, onError: @escaping (_ errorMessage: String?) -> Void){
    let postRef = API.Post.REF_POSTS.child(postId)

    postRef.runTransactionBlock({ (currentData: MutableData) -> TransactionResult in
        if var post = currentData.value as? [String : AnyObject], let uid = API.User.CURRENT_USER?.uid {

            var likes: Dictionary<String, Bool>
            likes = post["likes"] as? [String : Bool] ?? [:]
            var likeCount = post["likeCount"] as? Int ?? 0
            var score = post["score"] as? Int ?? 0

            if let _ = likes[uid] {
                likeCount -= 1
                score -= 100
                likes.removeValue(forKey: uid)
                self.REF_LIKES_POSTS.child(postId).child(uid).removeValue()

            } else {

                likeCount += 1
                score += 100
                likes[uid] = true
                self.REF_LIKES_POSTS.child(postId).child(uid).setValue(true)
            }

            post["score"] = score as AnyObject?
            post["likeCount"] = likeCount as AnyObject?
            post["likes"] = likes as AnyObject?
            currentData.value = post

            return TransactionResult.success(withValue: currentData)
        }
        return TransactionResult.success(withValue: currentData)
    }) { (error, committed, snapshot) in
        if let error = error {
            print(error.localizedDescription)
            onError(error.localizedDescription)
        }
        if let dict = snapshot?.value as? [String: Any] {
            let post = Post.transformPost(dict: dict, key: snapshot!.key)
        onSuccess(post)
        }
    }

}
</code>```

this for example updates the like node in all posts.
As I will have 10+ categories, I would love to update always the fitting post in the specific database path

example:

```<code>database.database().reference.child("Text").child("shortJokes")
database.database().reference.child("allPosts") -> where all posts are
</code>```

how can I achieve that only the specific child gets updated?

because later I will have it like that

```<code>database.database().reference.child("Text").child("Sport")
database.database().reference.child("Text").child("Animals")
database.database().reference.child("Pictures").child("funnyPictures")
database.database().reference.child("Pictures").child("sweetAnimals")
</code>```

I want it to check through the entire database off all posts to look where a child contains the same postId.
I see the problem when I have 10+ categories I have to call 10 functions in one and probably it will always update everything instead of just the one post with same id.

Update

```<code>            let newUserData = ["score": score, "likeCount": likeCount, "likes": likes] as [String : Any]

            let postRefEinzeiler = self.REF_EINZEILER.child(postId)
            postRefEinzeiler.updateChildValues(newUserData)

            let postRefSchwHumor = self.REF_SCHWARZERHUMOR.child(postId)
            postRefSchwHumor.updateChildValues(newUserData)
</code>```

With this code snippet I managed to achieve what I wanted to do.
BUT, it always adds a node with the postId in the other categories with the data I provide.

How I can make it to first look if the postId already exists and only if it exists to update the value?

答:
```<code>var BASE_POST = Database.database().reference()

// Generate a new push ID for the new post
let postkey = ENTER YOUR POST_ID
let postData = YOUR_POST_DETAILS_DICTIONARY

// Create the data we want to update
let updatedPostData = ["posts/\(postkey)": postData,
              "motorcycles/\(postkey)": postData ]

// Do a deep-path update
ref.updateChildValues(updatedPostData, withCompletionBlock: { (error, ref) -> Void in
    if (error) {
        print("Error updating data: \(error.description)")
    }
})
</code>```

Body:
I am working on an app where you can post pictures in different categories.
For instance : Animals / Motorcycles.

My user can follow users and see therefor their pictures.

Now I am working on the following: I want to upload a post in a category and at the same time in all posts( a separate screen where users can randomly see all posted pictures)

Every Posts, no matter where posted, will be in the allPosts child

var REF_POST = Database.database().reference().child("posts")

and for each category there is a specific child where just the posts from this category stay in

var REF_POST = Database.database().reference().child("motorcycles")

Now in the feed you can like and comment without a problem.
It uses the data from the child "allPosts"

Now I would like to automatically keep the data in synchrony with the post in motorcycles. They both share the same key but obviously it only get updated in the "allPosts" child.

The goal is to update each category always on the data from "allPosts" and reverse. So if a user liked in the category it will be also updated in "allPosts".

Update Code

func incrementLikesFeed(postId: String,  onSuccess: @escaping (Post) -> Void, onError: @escaping (_ errorMessage: String?) -> Void){
    let postRef = API.Post.REF_POSTS.child(postId)

    postRef.runTransactionBlock({ (currentData: MutableData) -> TransactionResult in
        if var post = currentData.value as? [String : AnyObject], let uid = API.User.CURRENT_USER?.uid {

            var likes: Dictionary<String, Bool>
            likes = post["likes"] as? [String : Bool] ?? [:]
            var likeCount = post["likeCount"] as? Int ?? 0
            var score = post["score"] as? Int ?? 0

            if let _ = likes[uid] {
                likeCount -= 1
                score -= 100
                likes.removeValue(forKey: uid)
                self.REF_LIKES_POSTS.child(postId).child(uid).removeValue()

            } else {

                likeCount += 1
                score += 100
                likes[uid] = true
                self.REF_LIKES_POSTS.child(postId).child(uid).setValue(true)
            }

            post["score"] = score as AnyObject?
            post["likeCount"] = likeCount as AnyObject?
            post["likes"] = likes as AnyObject?
            currentData.value = post

            return TransactionResult.success(withValue: currentData)
        }
        return TransactionResult.success(withValue: currentData)
    }) { (error, committed, snapshot) in
        if let error = error {
            print(error.localizedDescription)
            onError(error.localizedDescription)
        }
        if let dict = snapshot?.value as? [String: Any] {
            let post = Post.transformPost(dict: dict, key: snapshot!.key)
        onSuccess(post)
        }
    }

}

this for example updates the like node in all posts.
As I will have 10+ categories, I would love to update always the fitting post in the specific database path

example:

database.database().reference.child("Text").child("shortJokes")
database.database().reference.child("allPosts") -> where all posts are

how can I achieve that only the specific child gets updated?

because later I will have it like that

database.database().reference.child("Text").child("Sport")
database.database().reference.child("Text").child("Animals")
database.database().reference.child("Pictures").child("funnyPictures")
database.database().reference.child("Pictures").child("sweetAnimals")

I want it to check through the entire database off all posts to look where a child contains the same postId.
I see the problem when I have 10+ categories I have to call 10 functions in one and probably it will always update everything instead of just the one post with same id.

Update

            let newUserData = ["score": score, "likeCount": likeCount, "likes": likes] as [String : Any]

            let postRefEinzeiler = self.REF_EINZEILER.child(postId)
            postRefEinzeiler.updateChildValues(newUserData)

            let postRefSchwHumor = self.REF_SCHWARZERHUMOR.child(postId)
            postRefSchwHumor.updateChildValues(newUserData)

With this code snippet I managed to achieve what I wanted to do.
BUT, it always adds a node with the postId in the other categories with the data I provide.

How I can make it to first look if the postId already exists and only if it exists to update the value?


问:
Using R with Google Analytics
I found a great project called r-google-analytics that I'd like to use so I can manipulate GA dat in R at this website http://code.google.com/p/r-google-analytics/.

I run this portion of the code:

```<code>library(RCurl)

library(XML)

# 1. Create a new Google Analytics API object
ga <- RGoogleAnalytics()
# 2. Authorize the object with your Google Analytics Account Credentials
ga$SetCredentials("INSERT_USER_NAME", "INSERT_PASSWORD")
</code>```

And I get this error message:

```<code>Error in postForm("https://www.google.com/accounts/ClientLogin", Email = username,  :
  SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
</code>```

Any ideas as to what could be causing the error?

Thanks!

Kim

答:
As a good practice some reference to both the R sessionInfo() and the OS (uname -a in unix-like systems) could be of some use!

Some basic Googling could also guide you in finding a solution, see for example:

http://curl.haxx.se/docs/sslcerts.html

http://www.linuxquestions.org/questions/slackware-14/openssl-ssl-error-code-14090086-verify-the-ca-cert-is-ok-certificate-verify-failed-703523/

HIH!

Title: Using R with Google Analytics

Body:
I found a great project called r-google-analytics that I'd like to use so I can manipulate GA dat in R at this website http://code.google.com/p/r-google-analytics/.

I run this portion of the code:

library(RCurl)

library(XML)

# 1. Create a new Google Analytics API object
ga <- RGoogleAnalytics()
# 2. Authorize the object with your Google Analytics Account Credentials
ga$SetCredentials("INSERT_USER_NAME", "INSERT_PASSWORD")

And I get this error message:

Error in postForm("https://www.google.com/accounts/ClientLogin", Email = username,  :
  SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Any ideas as to what could be causing the error?

Thanks!

Kim


问:
C++ benchmarking, volatile
I'm trying to measure how long it takes to execute a function 'check()' using rdtsc as follows:

```<code>a = rdtsc();
check(pw);
b = rdtsc();

return (b-a);
</code>```

However, I am receiving very small time differences, which I think is due to my compiler (using G++, on windows) optimising the code. As 'check()' does not affect any other part of the program, I think the compiler is ignoring this call altogether.

I have read about using something called asm volatile to tell the compiler not to optimise a certain section of code, but I cannot figure out how to implement it.

Any help on this?

答: Presumably the function calculates and returns some value. Do something with that value, such as add it to a global variable (and eventually print out that variable), so that the compiler cannot easily optimise the function away.</p>

Title: C++ benchmarking, volatile

Body:
I'm trying to measure how long it takes to execute a function 'check()' using rdtsc as follows:

a = rdtsc();
check(pw);
b = rdtsc();

return (b-a);

However, I am receiving very small time differences, which I think is due to my compiler (using G++, on windows) optimising the code. As 'check()' does not affect any other part of the program, I think the compiler is ignoring this call altogether.

I have read about using something called asm volatile to tell the compiler not to optimise a certain section of code, but I cannot figure out how to implement it.

Any help on this?


问:
Separation of concerns for DbContext
Now I use Entity Framework with the following DbContext class:

```<code>public class ItemDbContext : DbContext {
    ...
    public DbSet<Item1> Item1s { get; set; }
    public DbSet<Item2> Item2s { get; set; }
}
</code>```

There are some classes need DbContext with either Item11s or Item2s as dependencies. So my purpose is create a layer of abstraction for DbContext with that DbSet types (logically separate DbContext_Item1 and DbContext_Item2). It can be useful for implementation of abstract factory pattern (create either DbContext_Item1 or DbContext_Item2 instance) also.

My thoughts:

1) Interfaces

```<code>public interface IDbContext_Item1 {
    DbSet<Item1> Item1s { get; set; }
}
public interface IDbContext_Item2 {
    DbSet<Item3> Item2s { get; set; }
}
</code>```

So my abstract factory is able to have API like that:

```<code>public abstract ItemFactory {
    public abstract IDbContext_Item1 GetItem1Context;
    public abstract IDbContext_Item2 GetItem2Context;
}
</code>```

It would be fine for me. However class which get IDbContext_ItemX instance doesn't treat it as DbContext instance (i.e. can not call method like SaveChanges() etc.). Unfortunately any interface can not be inherited from class like DbContext.

2) Extended interfaces with methods of DbContext

```<code>public interface IDbContext_Item1 {
    DbSet<Item1> Item1s { get; set; }
    void SaveChanges;
    // etc
}
</code>```

In my opinion it's extremely not elegant.

3) Abstract classes for IDbContext_ItemX

But my current DbContext implementation, ItemDbContext, can not be inherited from multiple classes.

4) Just devide current ItemDbContext on DbContext_Item1 and DbContext_Item2 concrete classes.

Yes, it is the decision. But is it only way? It would be great if my concrete factories return instances of ItemDbContext under the hood. Can I achieve it?

答:
As I commented, I'd first challenge the reasoning behind wanting to have a single entity for a given context, but if you decide to go forward with that, I'd go with a generic interface, or even a generic context :</p>

```<code>interface IDbContext<T> where T : class
{
    IDbSet<T> Set { get; }
}

// Context implement generic Interface
class DbContextItem1 : IDbContext<Item1>
{
    IDbSet<Item1> Set { get; private set; }

    override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Logic to get relevant mappings,
    }
}

// Technically you could also do that.
class DbContextItem1 : IDbContext<Item1>, IDbContext<Item2>
{
    IDbSet<Item1> IDbContext<Item1>.Set { get; }
    IDbSet<Item2> IDbContext<Item2>.Set { get; }

    override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Logic to get relevant mappings,
    }
}

// Generic context.
class DbContextGeneric<T> : IDbContext<T>
{
    IDbSet<T> Set { get; private set; }

    override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Logic to get relevant mappings based on T.
    }
}
</code>```

Title: Separation of concerns for DbContext

Body:
Now I use Entity Framework with the following DbContext class:

public class ItemDbContext : DbContext {
    ...
    public DbSet<Item1> Item1s { get; set; }
    public DbSet<Item2> Item2s { get; set; }
}

There are some classes need DbContext with either Item11s or Item2s as dependencies. So my purpose is create a layer of abstraction for DbContext with that DbSet types (logically separate DbContext_Item1 and DbContext_Item2). It can be useful for implementation of abstract factory pattern (create either DbContext_Item1 or DbContext_Item2 instance) also.

My thoughts:

1) Interfaces

public interface IDbContext_Item1 {
    DbSet<Item1> Item1s { get; set; }
}
public interface IDbContext_Item2 {
    DbSet<Item3> Item2s { get; set; }
}

So my abstract factory is able to have API like that:

public abstract ItemFactory {
    public abstract IDbContext_Item1 GetItem1Context;
    public abstract IDbContext_Item2 GetItem2Context;
}

It would be fine for me. However class which get IDbContext_ItemX instance doesn't treat it as DbContext instance (i.e. can not call method like SaveChanges() etc.). Unfortunately any interface can not be inherited from class like DbContext.

2) Extended interfaces with methods of DbContext

public interface IDbContext_Item1 {
    DbSet<Item1> Item1s { get; set; }
    void SaveChanges;
    // etc
}

In my opinion it's extremely not elegant.

3) Abstract classes for IDbContext_ItemX

But my current DbContext implementation, ItemDbContext, can not be inherited from multiple classes.

4) Just devide current ItemDbContext on DbContext_Item1 and DbContext_Item2 concrete classes.

Yes, it is the decision. But is it only way? It would be great if my concrete factories return instances of ItemDbContext under the hood. Can I achieve it?

Body:
As I commented, I'd first challenge the reasoning behind wanting to have a single entity for a given context, but if you decide to go forward with that, I'd go with a generic interface, or even a generic context :

interface IDbContext<T> where T : class
{
    IDbSet<T> Set { get; }
}

// Context implement generic Interface
class DbContextItem1 : IDbContext<Item1>
{
    IDbSet<Item1> Set { get; private set; }

    override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Logic to get relevant mappings,
    }
}

// Technically you could also do that.
class DbContextItem1 : IDbContext<Item1>, IDbContext<Item2>
{
    IDbSet<Item1> IDbContext<Item1>.Set { get; }
    IDbSet<Item2> IDbContext<Item2>.Set { get; }

    override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Logic to get relevant mappings,
    }
}

// Generic context.
class DbContextGeneric<T> : IDbContext<T>
{
    IDbSet<T> Set { get; private set; }

    override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Logic to get relevant mappings based on T.
    }
}


问:
Application.Exit() not working
```<code>static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Exit();
            Application.Run(new Form1());
        }
</code>```

Why after calling Application.Exit(), application doesn't exit immediately? After this line, Form1 still shows. How to exit application immediately. Thanks.

*Notes:*this is only an example. I handle some functions before showing form. And in functions, I have a command code to call Application.Exit() but I wonder why application doesn't exit immediately.

I'm using .NET Framework 4.0

答:
The code below should help you.        </p>

```<code>        if (Application.MessageLoop)
            Application.Exit();
        else
            Environment.Exit(1);
</code>```

Title: Application.Exit() not working

Body:
static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Exit();
            Application.Run(new Form1());
        }

Why after calling Application.Exit(), application doesn't exit immediately? After this line, Form1 still shows. How to exit application immediately. Thanks.

*Notes:*this is only an example. I handle some functions before showing form. And in functions, I have a command code to call Application.Exit() but I wonder why application doesn't exit immediately.

I'm using .NET Framework 4.0

Body:
The code below should help you.

        if (Application.MessageLoop)
            Application.Exit();
        else
            Environment.Exit(1);


问:
passing variable from one script to another in shell scripting
I have a script suppose script.sh
it has two scripts to run parallaly inside

```<code>sh script1.sh &
sh script2.sh &
wait;
echo $var1
echo $var2
</code>```

i want to get these two variable(var1,var2) printed while running script.sh

```<code>cat script1.sh

var1=1;
export $var1

cat script2.sh

var1=1;
export $var1
</code>```

答:
Things that come to mind:

If you use bash, you can run a script using dot:

.script1.sh

It will run script in the same environment, so you can modify environment variables of the "invoker" script.

If it is a single output data, you can just print into a standard output of the inner script and intercept in the outer script:

inner_result=`script1.sh`

If it is a numeric value, you can return it as a exit code of the script (but I do not recommend this method as it is a bad practice in script development)

Edit:

Use temporary file to store result and then remove it (but depending on operating system, named queues could be best dedicated solution)

Body:
I have a script suppose script.sh
it has two scripts to run parallaly inside

sh script1.sh &
sh script2.sh &
wait;
echo $var1
echo $var2

i want to get these two variable(var1,var2) printed while running script.sh

cat script1.sh

var1=1;
export $var1

cat script2.sh

var1=1;
export $var1


问:
PyPDF2 not printing any output from the text
I am trying to print text from pdf using PyPDF2. Here is my code:

```<code>import PyPDF2
pdf_file = open('report.pdf', 'rb')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
page = read_pdf.getPage(1)
page_content = page.extractText()
print (page_content.encode('utf-8'))
</code>```

In result I am getting empty line with some warning.

```<code>PdfReadWarning: Xref table not zero-indexed. ID numbers for objects will be corrected. [pdf.py:1736]
b''
</code>```

I have checked that this warning itself does not impact the results but in my case I am getting nothing. Any suggestions. Thanks

答:
Try changing your code like this:</p>

```<code>import PyPDF2
pdf_file = open('report.pdf', 'rb')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
page_content = read_pdf.getPage(1).extractText()
print (page_content.encode('utf-8','strict'))
</code>```

Body:
I am trying to print text from pdf using PyPDF2. Here is my code:

import PyPDF2
pdf_file = open('report.pdf', 'rb')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
page = read_pdf.getPage(1)
page_content = page.extractText()
print (page_content.encode('utf-8'))

In result I am getting empty line with some warning.

PdfReadWarning: Xref table not zero-indexed. ID numbers for objects will be corrected. [pdf.py:1736]
b''

I have checked that this warning itself does not impact the results but in my case I am getting nothing. Any suggestions. Thanks

Body:
Try changing your code like this:

import PyPDF2
pdf_file = open('report.pdf', 'rb')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
page_content = read_pdf.getPage(1).extractText()
print (page_content.encode('utf-8','strict'))


问:
How to analyse WebLogic thread dump?
I notice that there are some stuck threads.

I like to check what could be the cause of the stuck thread just base on the thread dump logs below. Any advise anyone? And also what is the difference between a fat lock and a thin lock?

```<code>        "[STUCK] ExecuteThread: '25' for queue: 'weblogic.kernel.Default (self-tuning)'" id=87495 idx=0x274 tid=15308 prio=1 alive, in native, blocked, daemon

            -- Blocked trying to get lock: com/jnn/testController@0x135a26c0[thin lock]
</code>```

答:
A "thin lock" is a lock with no contention (contention happens when a thread has to wait before acquiring a lock).
Thin locks get promoted to "Fat locks" when there is contention and a list is made with all threads waiting to acquire the lock.

You can read more on the argument here:
http://download.oracle.com/docs/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/thread_basics.html

Title: How to analyse WebLogic thread dump?

Body:
I notice that there are some stuck threads.

I like to check what could be the cause of the stuck thread just base on the thread dump logs below. Any advise anyone? And also what is the difference between a fat lock and a thin lock?

        "[STUCK] ExecuteThread: '25' for queue: 'weblogic.kernel.Default (self-tuning)'" id=87495 idx=0x274 tid=15308 prio=1 alive, in native, blocked, daemon

            -- Blocked trying to get lock: com/jnn/testController@0x135a26c0[thin lock]


问:
Mysql select one record from group having one of three conditions
Using MySQL. I need to extract one record per group of storeID + profitCenter according to the following conditions:

1) If group has a single active record (active=1), select that record

2) If group has no active records select the most recent (max(id))

3) If group has multiple active records, select the most recent active record

Sample table:
(blank lines added for clarity)

```<code> ID  | storeID | profitCenter | active
 --------------------------------------
 1   | X       | 1            |    1
 2   | X       | 1            |    0
 3   | X       | 1            |    0

 4   | X       | 2            |    0
 5   | X       | 2            |    1

 6   | X       | 3            |    0
 7   | X       | 3            |    0
 8   | X       | 3            |    0

 9   | X       | 4            |    1
10   | X       | 4            |    1
11   | X       | 4            |    0

12   | X       | 5            |    1

13   | X       | 6            |    0
</code>```

Desired result:

```<code> ID  | storeID | profitCenter | active
------------------------------------------
 1   | X       | 1            |    1
 5   | X       | 2            |    1
 8   | X       | 3            |    0
10   | X       | 4            |    1
12   | X       | 5            |    1
13   | X       | 6            |    0
</code>```

A single query would be great but I'm thinking I'll need to do this in a stored procedure due to its complexity. I would need to write the records to a new table so I can use that in joins and such. So far all I've really got is...

...A simple query to pull the "single" records like so....

```<code> SELECT * FROM table GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 1
UNION
SELECT * FROM table GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 0
</code>```

...which yields...

```<code> ID  | storeID | profitCenter | active
------------------------------------------
12   | X       | 5            |    1
13   | X       | 6            |    0
</code>```

Then I can do...

```<code> SELECT sum(active),tmult.* FROM
      (SELECT t.* FROM t LEFT JOIN
           (SELECT t.* FROM t GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 1
      UNION
           SELECT t.* FROM t GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 0) tsing
      ON t.id = tsing.id
      WHERE tsing.id IS NULL) tmult
 GROUP BY storeid, profitCenter
 HAVING sum(active)=1;
</code>```

...which gives the active record for each group that has only one active record:

```<code> ID  | storeID | profitCenter | active
 --------------------------------------
 1   | X       | 1            |    1
 5   | X       | 2            |    1
</code>```

It's the groups that have either no active records or multiple active records that I can't even begin to figure out.

Am I taking the right approach? Should I even be attempting this in SQL? I could write a script to do it but I was hoping to not have to go that route.

Any advice would be appreciated.

答:
You can try this with union all.

```<code>SELECT *
FROM TABLE
WHERE (storeID, profitCenter, Id) IN (
SELECT storeID, profitCenter, MAX(case when active=1 then id end) as maxid
FROM table
GROUP BY storeID, profitCenter
HAVING SUM(active) >= 1
UNION ALL
SELECT storeID, profitCenter, MAX(id)
FROM table
GROUP BY storeID, profitCenter
HAVING SUM(active) = 0
)
</code>```

Body:
Using MySQL. I need to extract one record per group of storeID + profitCenter according to the following conditions:

1) If group has a single active record (active=1), select that record

2) If group has no active records select the most recent (max(id))

3) If group has multiple active records, select the most recent active record

Sample table:
(blank lines added for clarity)

 ID  | storeID | profitCenter | active
 --------------------------------------
 1   | X       | 1            |    1
 2   | X       | 1            |    0
 3   | X       | 1            |    0

 4   | X       | 2            |    0
 5   | X       | 2            |    1

 6   | X       | 3            |    0
 7   | X       | 3            |    0
 8   | X       | 3            |    0

 9   | X       | 4            |    1
10   | X       | 4            |    1
11   | X       | 4            |    0

12   | X       | 5            |    1

13   | X       | 6            |    0

Desired result:

 ID  | storeID | profitCenter | active
------------------------------------------
 1   | X       | 1            |    1
 5   | X       | 2            |    1
 8   | X       | 3            |    0
10   | X       | 4            |    1
12   | X       | 5            |    1
13   | X       | 6            |    0

A single query would be great but I'm thinking I'll need to do this in a stored procedure due to its complexity. I would need to write the records to a new table so I can use that in joins and such. So far all I've really got is...

...A simple query to pull the "single" records like so....

 SELECT * FROM table GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 1
UNION
SELECT * FROM table GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 0

...which yields...

 ID  | storeID | profitCenter | active
------------------------------------------
12   | X       | 5            |    1
13   | X       | 6            |    0

Then I can do...

 SELECT sum(active),tmult.* FROM
      (SELECT t.* FROM t LEFT JOIN
           (SELECT t.* FROM t GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 1
      UNION
           SELECT t.* FROM t GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 0) tsing
      ON t.id = tsing.id
      WHERE tsing.id IS NULL) tmult
 GROUP BY storeid, profitCenter
 HAVING sum(active)=1;

...which gives the active record for each group that has only one active record:

 ID  | storeID | profitCenter | active
 --------------------------------------
 1   | X       | 1            |    1
 5   | X       | 2            |    1

It's the groups that have either no active records or multiple active records that I can't even begin to figure out.

Am I taking the right approach? Should I even be attempting this in SQL? I could write a script to do it but I was hoping to not have to go that route.

Any advice would be appreciated.

Body:
You can try this with union all.

SELECT *
FROM TABLE
WHERE (storeID, profitCenter, Id) IN (
SELECT storeID, profitCenter, MAX(case when active=1 then id end) as maxid
FROM table
GROUP BY storeID, profitCenter
HAVING SUM(active) >= 1
UNION ALL
SELECT storeID, profitCenter, MAX(id)
FROM table
GROUP BY storeID, profitCenter
HAVING SUM(active) = 0
)