答:
Your code is pretty close. See the comments below:

```<code>termz = {
    'does not exceed': 0,
    'shall not exceed': 0,
    'not exceeding': 0,
    'do not exceed': 0,
    'not to exceed': 0,
    'shall at no time exceed': 0,
    'shall not be less than': 0,
    'not less than': 0
}

with open('Q:/hello/place/textfile.txt', 'r') as f:
    sections = f.read().split('**************************************************')

    # Skip the first section. (I assume this is on purpose?)
    for p in sections[1:]:
        for eachKey in termz:
            if eachKey in p:
                # This is simpler than termz[eachKey] = termz.get(eachKey) + 1
                termz[eachKey] += 1

        # Move this outside of the inner loop
        print(termz)

        # After printing the results for that section, reset the counts
        termz = dict.fromkeys(termz, 0)
</code>```

EDIT

Sample input and output:

```<code>input = '''
Section 1:

This section is ignored.
does not exceed
**************************************************
Section 2:

shall not exceed
not to exceed
**************************************************
Section 3:

not less than'''

termz = {
    'does not exceed': 0,
    'shall not exceed': 0,
    'not exceeding': 0,
    'do not exceed': 0,
    'not to exceed': 0,
    'shall at no time exceed': 0,
    'shall not be less than': 0,
    'not less than': 0
}

sections = input.split('**************************************************')

# Skip the first section. (I assume this is on purpose?)
for p in sections[1:]:
    for eachKey in termz:
        if eachKey in p:
            # This is simpler than termz[eachKey] = termz.get(eachKey) + 1
            termz[eachKey] += 1

    # Move this outside of the inner loop
    print(termz)

    # After printing the results for that section, reset the counts
    termz = dict.fromkeys(termz, 0)

# OUTPUT:
# {'not exceeding': 0, 'shall not exceed': 1, 'not less than': 0, 'shall not be less than': 0, 'shall at no time exceed': 0, 'not to exceed': 1, 'do not exceed': 0, 'does not exceed': 0}
# {'not exceeding': 0, 'shall not exceed': 0, 'not less than': 1, 'shall not be less than': 0, 'shall at no time exceed': 0, 'not to exceed': 0, 'do not exceed': 0, 'does not exceed': 0}
</code>```

Title: Splitting up text file into pieces, then searching key phrases in those sections

Body:
Your code is pretty close. See the comments below:

termz = {
    'does not exceed': 0,
    'shall not exceed': 0,
    'not exceeding': 0,
    'do not exceed': 0,
    'not to exceed': 0,
    'shall at no time exceed': 0,
    'shall not be less than': 0,
    'not less than': 0
}

with open('Q:/hello/place/textfile.txt', 'r') as f:
    sections = f.read().split('**************************************************')

    # Skip the first section. (I assume this is on purpose?)
    for p in sections[1:]:
        for eachKey in termz:
            if eachKey in p:
                # This is simpler than termz[eachKey] = termz.get(eachKey) + 1
                termz[eachKey] += 1

        # Move this outside of the inner loop
        print(termz)

        # After printing the results for that section, reset the counts
        termz = dict.fromkeys(termz, 0)

EDIT

Sample input and output:

input = '''
Section 1:

This section is ignored.
does not exceed
**************************************************
Section 2:

shall not exceed
not to exceed
**************************************************
Section 3:

not less than'''

termz = {
    'does not exceed': 0,
    'shall not exceed': 0,
    'not exceeding': 0,
    'do not exceed': 0,
    'not to exceed': 0,
    'shall at no time exceed': 0,
    'shall not be less than': 0,
    'not less than': 0
}

sections = input.split('**************************************************')

# Skip the first section. (I assume this is on purpose?)
for p in sections[1:]:
    for eachKey in termz:
        if eachKey in p:
            # This is simpler than termz[eachKey] = termz.get(eachKey) + 1
            termz[eachKey] += 1

    # Move this outside of the inner loop
    print(termz)

    # After printing the results for that section, reset the counts
    termz = dict.fromkeys(termz, 0)

# OUTPUT:
# {'not exceeding': 0, 'shall not exceed': 1, 'not less than': 0, 'shall not be less than': 0, 'shall at no time exceed': 0, 'not to exceed': 1, 'do not exceed': 0, 'does not exceed': 0}
# {'not exceeding': 0, 'shall not exceed': 0, 'not less than': 1, 'shall not be less than': 0, 'shall at no time exceed': 0, 'not to exceed': 0, 'do not exceed': 0, 'does not exceed': 0}


来源: stackexchange

问:
Twitch Button (HTML/JScript w bootstrap)
Hello everyone I've tried everything I can think of to make this work. I know it does return stream = null or active through use in the browser, but It will not apply my buttons to my page. Not so good with javascript can anyone point me in the right direction.</p>

```<code>  <script type="text/javascript">
    (function() {

          var user_name, api_key;

      user_name = "Undead_Atomsk";
      api_key = "************************";

      twitch_widget.attr("href","https://twitch.tv/" + user_name);

      $.getJSON('https://api.twitch.tv/kraken/streams/' + user_name + '?client_id=' + api_key + '&callback=?', function(data) {
          if (data.stream) {
              document.write(<a href="http://www.twitch.tv/Undead_Atomsk" target="_blank" class="btn btn-success navbar-btn navbar-right">Live!</a>);
          } else {
              document.write(<a href="http://www.twitch.tv/Undead_Atomsk" target="_blank" class="btn btn-danger navbar-btn navbar-right">Offline!</a>);
          }
      });

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

答:
Took your advice and used browser tools "Completely forgot about those".

I added this line to my html.

```<code>    <a href="" id="twitch-btn" class="navbar-right"></a>
</code>```

I then made a .js file and used the following code everything works now the twitch API is just slow!

```<code>    (function() {

     var user_name, api_key, twitch_widget;

     user_name = "Undead_Atomsk";
     api_key = "********************";
     twitch_widget = $("#twitch-widget");

     twitch_widget.attr("href","https://twitch.tv/" + user_name);

     $.getJSON('https://api.twitch.tv/kraken/streams/' + user_name +'?client_id=' + api_key + '&callback=?', function(data) {
    if (data.stream) {
    document.getElementById("twitch-btn").innerHTML = '<a href="http://www.twitch.tv/Undead_Atomsk" target="_blank" class="btn btn-danger navbar-btn navbar-right">Live!</a>';
} else {
  document.getElementById("twitch-btn").innerHTML = '<a href="http://www.twitch.tv/Undead_Atomsk" target="_blank" class="btn btn-default navbar-btn navbar-right">Offline!</a>';
}
 });

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

ContentLicense: CC BY-SA 3.0

Body:
Took your advice and used browser tools "Completely forgot about those".

I added this line to my html.

    <a href="" id="twitch-btn" class="navbar-right"></a>

I then made a .js file and used the following code everything works now the twitch API is just slow!

    (function() {

     var user_name, api_key, twitch_widget;

     user_name = "Undead_Atomsk";
     api_key = "********************";
     twitch_widget = $("#twitch-widget");

     twitch_widget.attr("href","https://twitch.tv/" + user_name);

     $.getJSON('https://api.twitch.tv/kraken/streams/' + user_name +'?client_id=' + api_key + '&callback=?', function(data) {
    if (data.stream) {
    document.getElementById("twitch-btn").innerHTML = '<a href="http://www.twitch.tv/Undead_Atomsk" target="_blank" class="btn btn-danger navbar-btn navbar-right">Live!</a>';
} else {
  document.getElementById("twitch-btn").innerHTML = '<a href="http://www.twitch.tv/Undead_Atomsk" target="_blank" class="btn btn-default navbar-btn navbar-right">Offline!</a>';
}
 });

 })();


问:
Insert Docker parent host ip into container's hosts file
I'm new to Docker and trying to understand what is the best way to insert docker parent host ip into container hosts file.

I'm using the following command in my Dockerfile

RUN /sbin/ip route|awk '/default/ { print  $3,"\tdockerhost" }' >> /etc/hosts

but sometimes hosts ip get change so its non relevant anymore...

The reason to do that, if you ask yourself, is that i need to access another 2 dockers containers (and link not offer this feature).

Thanks,

答:
--add-host option can be used when you create/run your container but since /sbin/ip command isn't available in operating systems like OSX, we can use a more generic solution:

docker run --add-host=dockerhost:`docker network inspect \
   --format='{{range .IPAM.Config}}{{.Gateway}}{{end}}' bridge` [IMAGE]


问:
Background Worker ReportProgress not firing 2
I am working on a Legacy app and this is driving me crazy, every example I have seen addressing this issue appears to do what I am doing but for some reason my reportProgress event refuses to fire:

```<code>Private _worker as BackgroundWorker

Private Sub btnEditCheckSymbol_Click (ByVal sender As Object, ByVal e As EventArgs) Handles btnEditCheckSymbol.Click
    _worker = new BackgroundWorker()
    _worker.WorkerSupportsCancellation = True
    _worker.WorkerReportsProgress = True
    AddHandler _worker.DoWork, AddressOf worker_DoWork
    AddHandler _worker.ProgressChanged, AddressOf worker_ProgressChanged
    AddHandler _worker.RunWorkerCompleted, AddressOf worker_RunWorkerCompleted
    _worker.RunWorkerAsync()

   'Other long running code

   If _worker.IsBusy Then
       _worker.CancelAsync()
   End If
End Sub

Private Sub worker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) _
    For i As Integer = 60 To 0 step -1
        If _worker.CancellationPending Then
            e.Cancel = True
            return
        End If
        _worker.ReportProgress(i)
    Next
End Sub

Private Sub worker_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) _
    lbEditCheckSymbol.Invoke(
    Sub ()
        with lbEditCheckSymbol
            .Items.Clear()
            .Items.Add("Please wait for results: " + e.ProgressPercentage)
        end With
    End Sub)
    Thread.Sleep(100)
End Sub

Private Sub worker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
    with lbEditCheckSymbol
        .Items.Clear()
        If Not e.Cancelled then
            lbEditCheckSymbol.Invoke(
                Sub ()
                    with lbEditCheckSymbol
                        .Items.Add("Results should have arrived by now... um wait some more?")
                    end With
                End Sub)
        End If
    end With
End Sub
</code>```

The DoWork is called and it burns through the loop never invoking the ProgressChanged event, I checked in the debugger and the ProgressChanged is registered.  I mostly work in C# so am I missing some VB voodoo here?

UPDATE

I have abandoned the use of the background worker in favor of the TPL library. Less code, easier to debug and I actually got it to work so win, win, win.

答:
If you had better error handlers around your threaded work, you would catch the access violation when your background thread tries to access objects on the foreground thread.  To reach-across threads like that, you need some delegates and use BeginInvoke instead of Invoke to call over to the right thread.

This code might not be perfect, but it should be pretty close

```<code>Private _worker as BackgroundWorker

Public Delegate Sub ProgressChangedDelegateType(percent As Integer)
Public Delegate Sub RunWorkerCompletedDelegateType(cancelled As Boolean)

Private progressChangedDelegate As ProgressChangedDelegateType
Private runWorkerCompletedDelegate AS RunWorkerCompletedDelegateType

Public Sub Form_Load()
    'bind your delegates in your form load event or in the class constructor
    progressChangedDelegate = AddressOf ProgressChanged
    runWorkerCompletedDelegate = AddressOf RunWorkerCompleted

    'and all of your other stuff in your form_load() event handler...
End Sub

Private Sub btnEditCheckSymbol_Click (ByVal sender As Object, ByVal e As EventArgs) Handles btnEditCheckSymbol.Click
    _worker = new BackgroundWorker()
    _worker.WorkerSupportsCancellation = True
    _worker.WorkerReportsProgress = True
    AddHandler _worker.DoWork, AddressOf worker_DoWork
    AddHandler _worker.ProgressChanged, AddressOf worker_ProgressChanged
    AddHandler _worker.RunWorkerCompleted, AddressOf worker_RunWorkerCompleted
    _worker.RunWorkerAsync()

   'Other long running code

   If _worker.IsBusy Then
       _worker.CancelAsync()
   End If
End Sub

Private Sub worker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) _
    For i As Integer = 60 To 0 step -1
        If _worker.CancellationPending Then
            e.Cancel = True
            return
        End If
        _worker.ReportProgress(i)
    Next
End Sub

Private Sub worker_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
    If lbEditCheckSymbol.InvokeRequired Then
        BeginInvoke(progressChangedDelgate, {e.ProgressPercentage})
    Else
        ProgressChanged(e.ProgressPercentage)
    End If
End Sub

Public Sub ProgressChanged(percent As Integer)
    Try
        with lbEditCheckSymbol
            .Items.Clear()
            .Items.Add("Please wait for results: " + percent.ToString())
        end With
        DoEvents() 'forces a UI update
    Catch Ex As Exception
        Debug.WriteLine(ex.message) 'put a breakpoint here, just in case
    End Try
    Thread.Sleep(100)
End Sub

Private Sub worker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
    If lbEditCheckSymbol.InvokeRequired Then
        BeginInvoke(runWorkerCompletedDelegate, {e.Cancelled})
    Else
        RunWorkerCompleted(e.Cancelled)
    End If
End Sub

Public Sub RunWorkerCompleted(cancelled As Boolean)
    Try
        with lbEditCheckSymbol
            .Items.Clear()
            If Not cancelled then
                .Items.Add("Results should have arrived by now... um wait some more?")
        end With
        DoEvents() 'Forces a UI update
    Catch Ex As Exception
        Debug.WriteLine(ex.message) 'put a breakpoint here, just in case
    End Try
End Sub
</code>```

Body:
I am working on a Legacy app and this is driving me crazy, every example I have seen addressing this issue appears to do what I am doing but for some reason my reportProgress event refuses to fire:

Private _worker as BackgroundWorker

Private Sub btnEditCheckSymbol_Click (ByVal sender As Object, ByVal e As EventArgs) Handles btnEditCheckSymbol.Click
    _worker = new BackgroundWorker()
    _worker.WorkerSupportsCancellation = True
    _worker.WorkerReportsProgress = True
    AddHandler _worker.DoWork, AddressOf worker_DoWork
    AddHandler _worker.ProgressChanged, AddressOf worker_ProgressChanged
    AddHandler _worker.RunWorkerCompleted, AddressOf worker_RunWorkerCompleted
    _worker.RunWorkerAsync()

   'Other long running code

   If _worker.IsBusy Then
       _worker.CancelAsync()
   End If
End Sub

Private Sub worker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) _
    For i As Integer = 60 To 0 step -1
        If _worker.CancellationPending Then
            e.Cancel = True
            return
        End If
        _worker.ReportProgress(i)
    Next
End Sub

Private Sub worker_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) _
    lbEditCheckSymbol.Invoke(
    Sub ()
        with lbEditCheckSymbol
            .Items.Clear()
            .Items.Add("Please wait for results: " + e.ProgressPercentage)
        end With
    End Sub)
    Thread.Sleep(100)
End Sub

Private Sub worker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
    with lbEditCheckSymbol
        .Items.Clear()
        If Not e.Cancelled then
            lbEditCheckSymbol.Invoke(
                Sub ()
                    with lbEditCheckSymbol
                        .Items.Add("Results should have arrived by now... um wait some more?")
                    end With
                End Sub)
        End If
    end With
End Sub

The DoWork is called and it burns through the loop never invoking the ProgressChanged event, I checked in the debugger and the ProgressChanged is registered.  I mostly work in C# so am I missing some VB voodoo here?

UPDATE

I have abandoned the use of the background worker in favor of the TPL library. Less code, easier to debug and I actually got it to work so win, win, win.

Body:
If you had better error handlers around your threaded work, you would catch the access violation when your background thread tries to access objects on the foreground thread.  To reach-across threads like that, you need some delegates and use BeginInvoke instead of Invoke to call over to the right thread.

This code might not be perfect, but it should be pretty close

Private _worker as BackgroundWorker

Public Delegate Sub ProgressChangedDelegateType(percent As Integer)
Public Delegate Sub RunWorkerCompletedDelegateType(cancelled As Boolean)

Private progressChangedDelegate As ProgressChangedDelegateType
Private runWorkerCompletedDelegate AS RunWorkerCompletedDelegateType

Public Sub Form_Load()
    'bind your delegates in your form load event or in the class constructor
    progressChangedDelegate = AddressOf ProgressChanged
    runWorkerCompletedDelegate = AddressOf RunWorkerCompleted

    'and all of your other stuff in your form_load() event handler...
End Sub

Private Sub btnEditCheckSymbol_Click (ByVal sender As Object, ByVal e As EventArgs) Handles btnEditCheckSymbol.Click
    _worker = new BackgroundWorker()
    _worker.WorkerSupportsCancellation = True
    _worker.WorkerReportsProgress = True
    AddHandler _worker.DoWork, AddressOf worker_DoWork
    AddHandler _worker.ProgressChanged, AddressOf worker_ProgressChanged
    AddHandler _worker.RunWorkerCompleted, AddressOf worker_RunWorkerCompleted
    _worker.RunWorkerAsync()

   'Other long running code

   If _worker.IsBusy Then
       _worker.CancelAsync()
   End If
End Sub

Private Sub worker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) _
    For i As Integer = 60 To 0 step -1
        If _worker.CancellationPending Then
            e.Cancel = True
            return
        End If
        _worker.ReportProgress(i)
    Next
End Sub

Private Sub worker_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
    If lbEditCheckSymbol.InvokeRequired Then
        BeginInvoke(progressChangedDelgate, {e.ProgressPercentage})
    Else
        ProgressChanged(e.ProgressPercentage)
    End If
End Sub

Public Sub ProgressChanged(percent As Integer)
    Try
        with lbEditCheckSymbol
            .Items.Clear()
            .Items.Add("Please wait for results: " + percent.ToString())
        end With
        DoEvents() 'forces a UI update
    Catch Ex As Exception
        Debug.WriteLine(ex.message) 'put a breakpoint here, just in case
    End Try
    Thread.Sleep(100)
End Sub

Private Sub worker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
    If lbEditCheckSymbol.InvokeRequired Then
        BeginInvoke(runWorkerCompletedDelegate, {e.Cancelled})
    Else
        RunWorkerCompleted(e.Cancelled)
    End If
End Sub

Public Sub RunWorkerCompleted(cancelled As Boolean)
    Try
        with lbEditCheckSymbol
            .Items.Clear()
            If Not cancelled then
                .Items.Add("Results should have arrived by now... um wait some more?")
        end With
        DoEvents() 'Forces a UI update
    Catch Ex As Exception
        Debug.WriteLine(ex.message) 'put a breakpoint here, just in case
    End Try
End Sub


问:
How do I select from tables with a specifically named column when that column contains a specific value?
I am trying to select all the tables that has the same column, and there is an instance in that column matches a string format that I specify.

For example,

Table1:

FirstName, LastName, ID

Table2:

ID, Value

Table3:

FirstName, Value

I want my result to show the tables that contains ID in which the ID begin with character 'a'

So far what I have is

```<code>    SELECT SYS.TABLES.NAME FROM SYS.TABLES
    INNER JOIN SYS.COLUMNS
    ON SYS.TABLES.OBJECT_ID = SYS.COLUMS.OBJECT_ID
    WHERE SYS.COLUMS.NAME = 'ID'
</code>```

but then I have no clue how to continue. Any help is appreciated :)

答:
You can use "LIKE" to select once beginning with 'a':

```<code>SELECT SYS.TABLES.NAME AS t
FROM SYS.TABLES INNER JOIN SYS.COLUMNS
ON SYS.TABLES.OBJECT_ID = SYS.COLUMS.OBJECT_ID
WHERE SYS.COLUMNS.NAME = 'ID' AND EXISTS (SELECT * FROM t WHERE t.ID LIKE 'a%');
</code>```

The symbol "%" indicates that any combination of characters can be present after the letter "a"

Body:
I am trying to select all the tables that has the same column, and there is an instance in that column matches a string format that I specify.

For example,

Table1:

FirstName, LastName, ID

Table2:

ID, Value

Table3:

FirstName, Value

I want my result to show the tables that contains ID in which the ID begin with character 'a'

So far what I have is

    SELECT SYS.TABLES.NAME FROM SYS.TABLES
    INNER JOIN SYS.COLUMNS
    ON SYS.TABLES.OBJECT_ID = SYS.COLUMS.OBJECT_ID
    WHERE SYS.COLUMS.NAME = 'ID'

but then I have no clue how to continue. Any help is appreciated :)

Body:
You can use "LIKE" to select once beginning with 'a':

SELECT SYS.TABLES.NAME AS t
FROM SYS.TABLES INNER JOIN SYS.COLUMNS
ON SYS.TABLES.OBJECT_ID = SYS.COLUMS.OBJECT_ID
WHERE SYS.COLUMNS.NAME = 'ID' AND EXISTS (SELECT * FROM t WHERE t.ID LIKE 'a%');

The symbol "%" indicates that any combination of characters can be present after the letter "a"


问:
Android Studio Firebase Database return null object reference
Hello Guys i need you I have a problem with Firebase Realtime Database I put the data successful to the Firebase but when I try to retrieve it from Firebase I got a problem there is how I put the data

```<code>private void user_info(String user_id, String user_display_name) {

    mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);

    HashMap<String, String> userMap = new HashMap<>();
    userMap.put("Name",user_display_name);
    userMap.put("Balls","30");
    userMap.put("Level","1");
    mProgressDialog.setMessage("Please Wait...");

    mDatabase.setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {

            if (task.isSuccessful()){

            }
            else
                Toast.makeText(WelcomeActivity.this, ""+task.getException(), Toast.LENGTH_SHORT).show();
                mProgressDialog.dismiss();
        }
    });

}
</code>```

And how I try to retrieve the data

```<code>private FirebaseUser mUser;
private DatabaseReference mDatabase;
private String level,level1;
private int lev,i;

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

    //Image
    mImg_level1 = (ImageView)findViewById(R.id.mImg_lev1);
    mImg_level2 = (ImageView)findViewById(R.id.mImg_lev2);
    mImg_level3 = (ImageView)findViewById(R.id.mImg_lev3);
    mImg_level4 = (ImageView)findViewById(R.id.mImg_lev4);
    mImg_level5 = (ImageView)findViewById(R.id.mImg_lev5);
    mImg_level6 = (ImageView)findViewById(R.id.mImg_lev6);
    mImg_level7 = (ImageView)findViewById(R.id.mImg_lev7);
    mImg_level8 = (ImageView)findViewById(R.id.mImg_lev8);
    mImg_level9 = (ImageView)findViewById(R.id.mImg_lev9);
    mImg_level10 = (ImageView)findViewById(R.id.mImg_lev10);
    mImg_level11 = (ImageView)findViewById(R.id.mImg_lev11);

    //Firebase
    mUser = FirebaseAuth.getInstance().getCurrentUser();
    String user_id = mUser.getUid();

    mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
    mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            level = dataSnapshot.child("Level").getValue().toString();
            if (level.equals("1")){
                level1 = "1";
            }

            }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
</code>```

The toast don't show anything because it null

答:
Change this :-

```<code>mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            level = dataSnapshot.child("Level").getValue().toString();
            if (level.equals("1")){
                level1 = "1";
            }

            }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
</code>```

to this :-

```<code>mDatabase.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        level = dataSnapshot.child("Level").getValue().toString();
        if (level.equals("1")){
            level1 = "1";

        }
         Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
        }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});
</code>```

The reason this works is that Firebase downloads asynchronously and your code lines execute synchronously.

Body:
Hello Guys i need you I have a problem with Firebase Realtime Database I put the data successful to the Firebase but when I try to retrieve it from Firebase I got a problem there is how I put the data

private void user_info(String user_id, String user_display_name) {

    mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);

    HashMap<String, String> userMap = new HashMap<>();
    userMap.put("Name",user_display_name);
    userMap.put("Balls","30");
    userMap.put("Level","1");
    mProgressDialog.setMessage("Please Wait...");

    mDatabase.setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {

            if (task.isSuccessful()){

            }
            else
                Toast.makeText(WelcomeActivity.this, ""+task.getException(), Toast.LENGTH_SHORT).show();
                mProgressDialog.dismiss();
        }
    });

}

And how I try to retrieve the data

private FirebaseUser mUser;
private DatabaseReference mDatabase;
private String level,level1;
private int lev,i;

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

    //Image
    mImg_level1 = (ImageView)findViewById(R.id.mImg_lev1);
    mImg_level2 = (ImageView)findViewById(R.id.mImg_lev2);
    mImg_level3 = (ImageView)findViewById(R.id.mImg_lev3);
    mImg_level4 = (ImageView)findViewById(R.id.mImg_lev4);
    mImg_level5 = (ImageView)findViewById(R.id.mImg_lev5);
    mImg_level6 = (ImageView)findViewById(R.id.mImg_lev6);
    mImg_level7 = (ImageView)findViewById(R.id.mImg_lev7);
    mImg_level8 = (ImageView)findViewById(R.id.mImg_lev8);
    mImg_level9 = (ImageView)findViewById(R.id.mImg_lev9);
    mImg_level10 = (ImageView)findViewById(R.id.mImg_lev10);
    mImg_level11 = (ImageView)findViewById(R.id.mImg_lev11);

    //Firebase
    mUser = FirebaseAuth.getInstance().getCurrentUser();
    String user_id = mUser.getUid();

    mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
    mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            level = dataSnapshot.child("Level").getValue().toString();
            if (level.equals("1")){
                level1 = "1";
            }

            }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();

The toast don't show anything because it null

Body:
Change this :-

mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            level = dataSnapshot.child("Level").getValue().toString();
            if (level.equals("1")){
                level1 = "1";
            }

            }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();

to this :-

mDatabase.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        level = dataSnapshot.child("Level").getValue().toString();
        if (level.equals("1")){
            level1 = "1";

        }
         Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
        }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

The reason this works is that Firebase downloads asynchronously and your code lines execute synchronously.


问:
Oracle APEX Presenting Data Slower When Row Count bigger than 1.000.000
When type query in SQL Developer, it return data less than a second. When do the same in Oracle APEX it take much more time, over 5 seconds. I go in DEBUG section to see what's wrong, and it return this to me:

```<code>-IR binding: "APXWS_MAX_ROW_CNT" value="1000000"
</code>```

I figure it out, that it returns more than 1.000.000 rows, and that's why is slower. But don't know how to fix it, to get approximately the same time as in SQL Developer?

答:
"Leave the Maximum Row Count property null, so classic reports won't fetch all the way to this number and interactive reports won't introduce the analytic function count(*) over ().

Don't use a Pagination Type with a Z, so classic reports won't fetch all rows and interactive reports again won't introduce count(*) over ()."

source: http://rwijk.blogspot.ca/2016/11/performance-aspects-of-apex-reports.html
(I saved it in the wayback machine too if the link goes away: http://web.archive.org/web/20170706183715/http://rwijk.blogspot.ca/2016/11/performance-aspects-of-apex-reports.html

Body:
When type query in SQL Developer, it return data less than a second. When do the same in Oracle APEX it take much more time, over 5 seconds. I go in DEBUG section to see what's wrong, and it return this to me:

-IR binding: "APXWS_MAX_ROW_CNT" value="1000000"

I figure it out, that it returns more than 1.000.000 rows, and that's why is slower. But don't know how to fix it, to get approximately the same time as in SQL Developer?


问:
Reading a file from tar.gz archive in Spark
I have a bunch of tar.gz files which I would like to process with Spark without decompressing them.

A single archive is about ~700MB and contains 10 different files but I'm interested only in one of them (which is ~7GB after decompression).

I know that context.textFile supports tar.gz but I'm not sure is it the right tool when an archive contains more then one file. What happens is that Spark will return content of all files (line by line) in the archive including file names with some binary data.

Is there any way to select which file from tar.gz I would like to map?

答:
AFAIK, I'd suggest sc.binaryFiles method... please see below doc. where file name and file content are present, you can map and pickup the file you want and process that.

```<code>public RDD<scala.Tuple2<String,PortableDataStream>> binaryFiles(String path,
                                                           int minPartitions)
</code>```

Get an RDD for a Hadoop-readable dataset as PortableDataStream for each file (useful for binary data)
For example, if you have the following files:

hdfs://a-hdfs-path/part-00000

    hdfs://a-hdfs-path/part-00001

  ...

   hdfs://a-hdfs-path/part-nnnnn

Do val rdd = sparkContext.binaryFiles("hdfs://a-hdfs-path"),

then rdd contains

(a-hdfs-path/part-00000, its content)

     (a-hdfs-path/part-00001, its content)

     ...

  (a-hdfs-path/part-nnnnn, its content)

Also, check this

Body:
AFAIK, I'd suggest sc.binaryFiles method... please see below doc. where file name and file content are present, you can map and pickup the file you want and process that.

public RDD<scala.Tuple2<String,PortableDataStream>> binaryFiles(String path,
                                                           int minPartitions)

Get an RDD for a Hadoop-readable dataset as PortableDataStream for each file (useful for binary data)
For example, if you have the following files:

hdfs://a-hdfs-path/part-00000

    hdfs://a-hdfs-path/part-00001

  ...

   hdfs://a-hdfs-path/part-nnnnn

Do val rdd = sparkContext.binaryFiles("hdfs://a-hdfs-path"),

then rdd contains

(a-hdfs-path/part-00000, its content)

     (a-hdfs-path/part-00001, its content)

     ...

  (a-hdfs-path/part-nnnnn, its content)

Also, check this


问:
Do I need to create a different awk script if I don't want to perform the same actions on all of the files i pass as parameters?
I'm a noob writing an awk script to combine two differently formatted files and insert specific data from each into another file, and I was wondering how I could specify which actions to perform on which files? In constructing the pattern statement I want to reference a different field number depending on which file I'm dealing with. Would that require a separate script? Ex:

```<code>file 1:
blue 6'0
brown 5'8
green 5'4

file 2:
36 28 20
</code>```

and then I'd like to combine these two into (after a specfic string)

```<code>file 3:
*string*
blue 6'0 36
brown 5'8 20
green 5'4 28
</code>```

I know in bash scripting the $ references parameter number, but in awk that sign references field number. Any insight you could provide would be helpful. Thanks

答:
Given:

```<code>$ cat f1
blue 6'0
brown 5'8
green 5'4

$ cat f2
36 28 20

$ cat f3
line 1
string line 2
line 3
string line 4
line 5
</code>```

You can use this awk with paste:

```<code>$ awk 'FNR==NR{s=s ? s ORS $0 : $0; next}
       1;
       /string/ {print s}' <(paste -d' ' f1 <(tr ' ' '\n' <f2)) f3
</code>```

Prints:

```<code>line 1
string line 2
blue 6'0 36
brown 5'8 28
green 5'4 20
line 3
string line 4
blue 6'0 36
brown 5'8 28
green 5'4 20
line 5
</code>```

Body:
I'm a noob writing an awk script to combine two differently formatted files and insert specific data from each into another file, and I was wondering how I could specify which actions to perform on which files? In constructing the pattern statement I want to reference a different field number depending on which file I'm dealing with. Would that require a separate script? Ex:

file 1:
blue 6'0
brown 5'8
green 5'4

file 2:
36 28 20

and then I'd like to combine these two into (after a specfic string)

file 3:
*string*
blue 6'0 36
brown 5'8 20
green 5'4 28

I know in bash scripting the $ references parameter number, but in awk that sign references field number. Any insight you could provide would be helpful. Thanks

Body:
Given:

$ cat f1
blue 6'0
brown 5'8
green 5'4

$ cat f2
36 28 20

$ cat f3
line 1
string line 2
line 3
string line 4
line 5

You can use this awk with paste:

$ awk 'FNR==NR{s=s ? s ORS $0 : $0; next}
       1;
       /string/ {print s}' <(paste -d' ' f1 <(tr ' ' '\n' <f2)) f3

Prints:

line 1
string line 2
blue 6'0 36
brown 5'8 28
green 5'4 20
line 3
string line 4
blue 6'0 36
brown 5'8 28
green 5'4 20
line 5


问:
SQL query to search for hotel availability
I have tables with following columns:

hotel (id, name, address)

room (id, name, price, hotel_id)

room_calendar (customer_id, room_id, date) we will create a date record for the specific room if it is booked by the specific customer.

How can I query the database directly based on arrival date and departure date to check for hotel availability?

Thanks a lot.

答:
LEFT JOIN on room_calendar table with your searching date.

Keep an eye on: WHERE room_calendar.date IS NULL
If there is no row for this room in room_calendar table, the room is not booked for this day.

```<code>    SELECT hotel.name
          ,room.name
          ,room.price
      FROM hotel
INNER JOIN room
        ON room.hotel_id = hotel.id
 LEFT JOIN room_calendar
        ON room_calendar.room_id = room.id
       AND room_calendar.date = @yourdate
     WHERE room_calendar.date IS NULL
</code>```

Body:
LEFT JOIN on room_calendar table with your searching date.

Keep an eye on: WHERE room_calendar.date IS NULL
If there is no row for this room in room_calendar table, the room is not booked for this day.

    SELECT hotel.name
          ,room.name
          ,room.price
      FROM hotel
INNER JOIN room
        ON room.hotel_id = hotel.id
 LEFT JOIN room_calendar
        ON room_calendar.room_id = room.id
       AND room_calendar.date = @yourdate
     WHERE room_calendar.date IS NULL


问:
Trying to use HtmlAgilityPack
Im having problems trying to install the HtmlAgilityPack.dll ver 1.4. I've copied the files into my windows\system32 folder and tried regsvr32 htmlagilitypack.dll in run.

I got the following error:

```<code>The module was loaded but the entry point DllUnregisterServer was not found.
</code>```

It seems to be a common library used by many people on SO so the dll's cant be corrupted. How do I fix this?

答:
The reason you can't use regsvr32 is because the HTML Agility pack isn't a COM library. It's written in .NET, so you need to reference from a .NET project.

Download the latest zip file and extract somewhere on your local hard disk e.g. c:\SharedLibs\HtmlAgilityPack.

Launch Visual Studio (or one of the VS Express editions)

Create a new project or open an existing one.

In solution explorer right click on References and click Add Reference.

Click the Browse tab and browse to where you extracted the agility pack

Select the HtmlAgilityPack.dll DLL

Click OK

Refer to the CodePlex site:

Html Agility Pack Home

  Html Agility Pack Examples

Here's a couple of links I dug up in everyone's favourite search engine:

A simple web crawler in C# using HtmlAgilityPack

  .NET Html Agility Pack: How to use malformed HTML just like it was well-formed XML...

ContentLicense: CC BY-SA 2.5

Title: Trying to use HtmlAgilityPack

Body:
Im having problems trying to install the HtmlAgilityPack.dll ver 1.4. I've copied the files into my windows\system32 folder and tried regsvr32 htmlagilitypack.dll in run.

I got the following error:

The module was loaded but the entry point DllUnregisterServer was not found.

It seems to be a common library used by many people on SO so the dll's cant be corrupted. How do I fix this?


问:
Reusing output from last command in Bash
Is the output of a Bash command stored in any register? E.g. something similar to $? capturing the output instead of the exit status.

I could assign the output to a variable with:

```<code>output=$(command)
</code>```

but that's more typing...

答:
Like konsolebox said, you'd have to hack into bash itself. Here is a quite good example on how one might achieve this. The stderred repository (actually meant for coloring stdout) gives instructions on how to build it.

I gave it a try: Defining some new file descriptor inside .bashrc like

```<code>exec 41>/tmp/my_console_log
</code>```

(number is arbitrary) and modify stderred.c accordingly so that content also gets written to fd 41. It kind of worked, but contains loads of NUL bytes, weird formattings and is basically binary data, not readable. Maybe someone with good understandings of C could try that out.

If so, everything needed to get the last printed line is tail -n 1 [logfile].

Body:
Is the output of a Bash command stored in any register? E.g. something similar to $? capturing the output instead of the exit status.

I could assign the output to a variable with:

output=$(command)

but that's more typing...

Body:
Like konsolebox said, you'd have to hack into bash itself. Here is a quite good example on how one might achieve this. The stderred repository (actually meant for coloring stdout) gives instructions on how to build it.

I gave it a try: Defining some new file descriptor inside .bashrc like

exec 41>/tmp/my_console_log

(number is arbitrary) and modify stderred.c accordingly so that content also gets written to fd 41. It kind of worked, but contains loads of NUL bytes, weird formattings and is basically binary data, not readable. Maybe someone with good understandings of C could try that out.

If so, everything needed to get the last printed line is tail -n 1 [logfile].


问:
UDP sendto() error: invalid argument
We are trying to apply a UDP based protocol and having some problem with sendto() function.

when we try to response to the write-request with ack we get "invalid argument" from the sendto() function

this is our code:

```<code>int                sock;                  // Socket
sockaddr_in_t      echoServAddr;          // Local address
sockaddr_in_t      echoClntAddr;          // Client address
unsigned int       cliAddrLen;            // Length of incoming message
data_packet_t      echoBuffer;
wrq_packet_t       wrqBuffer;
unsigned short     echoServPort;          // Server port
int                recvMsgSize;           // Size of received message
ack_packet_t      Ack;
struct timeval     timeout;
fd_set             fds;

/* Create socket for sending/receiving datagrams */
if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) perror("TTFTPERROR: socket() failed");

/* Construct local address structure */
memset(&echoServAddr, 0, sizeof(echoServAddr));
echoServAddr.sin_family = AF_INET;
echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY);
echoServAddr.sin_port = htons(echoServPort);

/*Bind to the local address */
if (bind(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) perror("TTFTPERROR: bind() failed");

FD_ZERO(&fds);
FD_SET(sock, &fds);
timeout.tv_sec = WAIT_FOR_PACKET_TIMEOUT;
timeout.tv_usec = 0;

while (1) {
    recvMsgSize = recvfrom(sock, &wrqBuffer, FULL_PACKET_SIZE, 0, (struct sockaddr *) &echoClntAddr, &cliAddrLen);
    if (recvMsgSize > 0) break; // we got something!
}

Ack = CreateAckPacket(0); // send ack 0
if (sendto(sock, &Ack, sizeof(Ack), 0, (struct sockaddr *) &echoClntAddr, sizeof(echoClntAddr)) == -1){
    perror("TTFTPERROR: sendto() failed to send ack 0");
    exit(-1);
}
</code>```

Could you help us understand what is wrong?

答:
Also be very careful to you pass VALID and EXISTING IP address to the bind()'s parameter:
echoServAddr.sin_addr.s_addr

If you don't have network interface exposed with that exactly IP address the bind won't fail on some platforms (ESP32 for example) BUT the sendto() WILL definitely fail. I've spend 2 days debugging that and I'm mad!

Title: UDP sendto() error: invalid argument

Body:
We are trying to apply a UDP based protocol and having some problem with sendto() function.

when we try to response to the write-request with ack we get "invalid argument" from the sendto() function

this is our code:

int                sock;                  // Socket
sockaddr_in_t      echoServAddr;          // Local address
sockaddr_in_t      echoClntAddr;          // Client address
unsigned int       cliAddrLen;            // Length of incoming message
data_packet_t      echoBuffer;
wrq_packet_t       wrqBuffer;
unsigned short     echoServPort;          // Server port
int                recvMsgSize;           // Size of received message
ack_packet_t      Ack;
struct timeval     timeout;
fd_set             fds;

/* Create socket for sending/receiving datagrams */
if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) perror("TTFTPERROR: socket() failed");

/* Construct local address structure */
memset(&echoServAddr, 0, sizeof(echoServAddr));
echoServAddr.sin_family = AF_INET;
echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY);
echoServAddr.sin_port = htons(echoServPort);

/*Bind to the local address */
if (bind(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) perror("TTFTPERROR: bind() failed");

FD_ZERO(&fds);
FD_SET(sock, &fds);
timeout.tv_sec = WAIT_FOR_PACKET_TIMEOUT;
timeout.tv_usec = 0;

while (1) {
    recvMsgSize = recvfrom(sock, &wrqBuffer, FULL_PACKET_SIZE, 0, (struct sockaddr *) &echoClntAddr, &cliAddrLen);
    if (recvMsgSize > 0) break; // we got something!
}

Ack = CreateAckPacket(0); // send ack 0
if (sendto(sock, &Ack, sizeof(Ack), 0, (struct sockaddr *) &echoClntAddr, sizeof(echoClntAddr)) == -1){
    perror("TTFTPERROR: sendto() failed to send ack 0");
    exit(-1);
}

Could you help us understand what is wrong?


问:
Upgrading Spring Security breaks a project
I have a template project I created long time ago. Project can be found on: here

All the libraries have been updated to a new versions expect spring security. If you checkout master branch go to localhost:8080/springdemo/index.htm application will redirect you to login page and once you enter demouser/demopass or userdemo/passdemo you will be logged in and redirected to index.htm.

Problem is when I update to Spring Security 4.2.3.RELEASE application does not work. This code is on spring-security-update branch. I tried a lot of online resources. Messed around with csrf token and disabled it for time being but was unable to get it to work.

Anybody has an idea why is spring security not working?

Thanks in advance

答:
This is because of migration from version 3 to version 4. To make all this works you should do this:

1) in your index.jsp change form action from action='/springdemo/j_spring_security_check' to action='/springdemo/login'

2) in your index.jsp change input name from name='j_username' to name='username', same for name='j_password' -> name='password'

3) in your index.jsp change logout url from href="j_spring_security_logout" to href="logout"

Worked for me. Hope it helps


问:
Time complexity of only accessing rows in a matrix
while accessing all elements of a matrix we can use to for loops and time complexity is O(n^2).
But, when we are only accessing rows from a 2D array, what is the time complexity? Is it O(n) when n = number of rows?
Ex:-

```<code>int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < arr.length; i++)
  for (int j = 0; j < arr[0].length; j++)
</code>```

The time complexity for the above lines is O(n^2).

But if we access the matrix in the following way will the time complexity still be O(n^2) or will it be O(n)

```<code>for (int rows[] : arr) - Time complexity is O(n) or O(n^2)
</code>```

答:
```<code>int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < arr.length; i++)
  for (int j = 0; j < arr[0].length; j++)
</code>```

<p>This is having complexity of O(n) and not O(n^2). That is you are traversing and seeing n items only once and the it linearly increases when n increases. </p>

Body:
while accessing all elements of a matrix we can use to for loops and time complexity is O(n^2).
But, when we are only accessing rows from a 2D array, what is the time complexity? Is it O(n) when n = number of rows?
Ex:-

int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < arr.length; i++)
  for (int j = 0; j < arr[0].length; j++)

The time complexity for the above lines is O(n^2).

But if we access the matrix in the following way will the time complexity still be O(n^2) or will it be O(n)

for (int rows[] : arr) - Time complexity is O(n) or O(n^2)

Body:
int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < arr.length; i++)
  for (int j = 0; j < arr[0].length; j++)

This is having complexity of O(n) and not O(n^2). That is you are traversing and seeing n items only once and the it linearly increases when n increases.


问:
Selenium Python Selector Returning Too Many Values
wondering if anyone can give me some advice for using Selenium with Python for webscraping.

I need to get the number of elements with a certain class on a page, and I have it working well with

```<code>driver=webdriver.PhantomJS()
driver.get('https://www.somerandomsite.com/1')
number_of_elements = len(driver.find_elements_by_class_name('some_class'))
</code>```

this gets the right number of elements every time.

But now I want to define a function so it can scrape multiple webpages - say https://www.somerandomsite.com/1 to https://www.somerandomsite.com/10

So I do

```<code>driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        start += 1
</code>```

Theoretically, this should move onto the next page, and retrieve the number of classes that I want in that page. However, it works fine for the first page, but subsequent pages yield a number of elements that's either equal to the number of elements of the previous page plus that of the current page, or that sum minus 1. If I use an xpath instead of a class name selector I get the exact same results.

Also, if I try to access any elements that are in that longer list, it throws an error since only the values on that page actually exist. So I have no idea how it's getting that longer list if the elements on it don't even exist. (For example, if there are 8 elements on page one and 5 elements on page two, when it gets to page two it'll say there are 12 or 13 elements. If I access elements 1-5 they all return values, but trying to call the sixth element or higher will cause a NoSuchElementException.)

Anyone know why this might be happening?

EDIT: I've narrowed it down a bit more, hopefully this helps. Sorry I was off in the initial question.

```<code>driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        start += 1
</code>```

So the above code actually works. However, when I then navigate to another page that also has elements of 'some_class', and then continue looping, it adds the number of elements from the previous page to the current page.

So my code's like this:

```<code>driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        print(number_of_elements)
        driver.get('https://www.somerandomsite.com/otherpage')
        start += 1

my_func(1,2)
</code>```

So let's say https://www.somerandomsite.com/1 has 8 elements of class 'some_class', https://www.somerandomsite.com/otherpage has 7 elements of class 'some_class', and https://www.somerandomsite.com/2 has 10 elements of class 'some_class'.

When I run the above code, it'll print 8, then 17. If I don't navigate to the other page, and run

```<code>driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        start += 1
</code>```

So the above code actually works. However, when I then navigate to another page that also has elements of 'some_class', and then continue looping, it adds the number of elements from the previous page to the current page.

So my code's like this:

```<code>driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        print(number_of_elements)
        start += 1

my_func(1,2)
</code>```

it'll print 8 then 10, as I want it to. I'm not sure why it's counting elements on two pages at once, and only if I get that other page beforehand.

EDIT2: So I've gotten it working by navigating to a page on a different server and then returning to the page I want. Weird, but I'll use it. If anyone has any ideas on why it doesn't work if I don't though I'd still love to understand the problem better.

答:
Difficult to tell what - if at all - the problem is as you don't provide the necessary details to replicate what you're describing.

IMHO a function is overkill for this simple task. Just toss it and create the loop. In general I'd put the loop outside.

Also you need a function call for this to do anything at all - and a return statement.

In general for similar stuff I'd put the loop outside the function.

Like so:

```<code>def my_func(driver, count):
    driver.get('https://www.somerandomsite.com/%d' % count)
    number_of_elements = len(driver.find_elements_by_class_name('some_class'))
    return number_of_elements

driver=webdriver.PhantomJS()
total_element_count = 0
count = 1
while count < 1000: # or whatever number you need
    number_of_elements = my_func(driver, count)
    total_element_count += number_of_elements
    print("[*] Elements for iteration %d: %d" % (count, number_of_elements))
    print("[*] Total count so far: %d" % total_element_count)
    count +=1
</code>```

Body:
wondering if anyone can give me some advice for using Selenium with Python for webscraping.

I need to get the number of elements with a certain class on a page, and I have it working well with

driver=webdriver.PhantomJS()
driver.get('https://www.somerandomsite.com/1')
number_of_elements = len(driver.find_elements_by_class_name('some_class'))

this gets the right number of elements every time.

But now I want to define a function so it can scrape multiple webpages - say https://www.somerandomsite.com/1 to https://www.somerandomsite.com/10

So I do

driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        start += 1

Theoretically, this should move onto the next page, and retrieve the number of classes that I want in that page. However, it works fine for the first page, but subsequent pages yield a number of elements that's either equal to the number of elements of the previous page plus that of the current page, or that sum minus 1. If I use an xpath instead of a class name selector I get the exact same results.

Also, if I try to access any elements that are in that longer list, it throws an error since only the values on that page actually exist. So I have no idea how it's getting that longer list if the elements on it don't even exist. (For example, if there are 8 elements on page one and 5 elements on page two, when it gets to page two it'll say there are 12 or 13 elements. If I access elements 1-5 they all return values, but trying to call the sixth element or higher will cause a NoSuchElementException.)

Anyone know why this might be happening?

EDIT: I've narrowed it down a bit more, hopefully this helps. Sorry I was off in the initial question.

driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        start += 1

So the above code actually works. However, when I then navigate to another page that also has elements of 'some_class', and then continue looping, it adds the number of elements from the previous page to the current page.

So my code's like this:

driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        print(number_of_elements)
        driver.get('https://www.somerandomsite.com/otherpage')
        start += 1

my_func(1,2)

So let's say https://www.somerandomsite.com/1 has 8 elements of class 'some_class', https://www.somerandomsite.com/otherpage has 7 elements of class 'some_class', and https://www.somerandomsite.com/2 has 10 elements of class 'some_class'.

When I run the above code, it'll print 8, then 17. If I don't navigate to the other page, and run

driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        start += 1

So the above code actually works. However, when I then navigate to another page that also has elements of 'some_class', and then continue looping, it adds the number of elements from the previous page to the current page.

So my code's like this:

driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        print(number_of_elements)
        start += 1

my_func(1,2)

it'll print 8 then 10, as I want it to. I'm not sure why it's counting elements on two pages at once, and only if I get that other page beforehand.

EDIT2: So I've gotten it working by navigating to a page on a different server and then returning to the page I want. Weird, but I'll use it. If anyone has any ideas on why it doesn't work if I don't though I'd still love to understand the problem better.

Body:
Difficult to tell what - if at all - the problem is as you don't provide the necessary details to replicate what you're describing.

IMHO a function is overkill for this simple task. Just toss it and create the loop. In general I'd put the loop outside.

Also you need a function call for this to do anything at all - and a return statement.

In general for similar stuff I'd put the loop outside the function.

Like so:

def my_func(driver, count):
    driver.get('https://www.somerandomsite.com/%d' % count)
    number_of_elements = len(driver.find_elements_by_class_name('some_class'))
    return number_of_elements

driver=webdriver.PhantomJS()
total_element_count = 0
count = 1
while count < 1000: # or whatever number you need
    number_of_elements = my_func(driver, count)
    total_element_count += number_of_elements
    print("[*] Elements for iteration %d: %d" % (count, number_of_elements))
    print("[*] Total count so far: %d" % total_element_count)
    count +=1


问:
Add URL parameters to DoubleClick destination URL

Is there anyway to add URL Parameters to the destination URL of a creative?

Example:

I load a banner on the website that has the destination link in DFP www.mysite.com

The javascript on the page forces DFP to add zone=above_the_fold

When the user clicks the banner the destination link is now www.mysite.com?zone=above_the_fold

If somehow the above is possible, can I mix parameters from DFP with forced parameters from javascript code?

Example:
I load a banner on the website that has the destination link in DFP www.mysite.com?campaign=summer_sale

The javascript on the page forces DFP to add zone=above_the_fold

When the user clicks the banner the destination link is now www.mysite.com?campaign=summer_sale&zone=above_the_fold

Note: Due to a very very specific business case I use DFP to advertise to pages on the same website and I need to measure the impact on sales in Google Analytics. That's what the parameters are for.

Thanks in advance

答:
First you need to pass the URL parameters to DFP. You can try Google DFP: Pass UTM_Source to DFP with javascript

After that, you will build the destination URL:

```<code><script>
    var clickTag = %%CLICK_URL_ESC%%%%DEST_URL%%?=utm_source=%%PATTERN:utm_source%%;
</script>
</code>```

%%PATTERN:utm_source%% it is a DFP Macro

Body:
First you need to pass the URL parameters to DFP. You can try Google DFP: Pass UTM_Source to DFP with javascript

After that, you will build the destination URL:

<script>
    var clickTag = %%CLICK_URL_ESC%%%%DEST_URL%%?=utm_source=%%PATTERN:utm_source%%;
</script>

%%PATTERN:utm_source%% it is a DFP Macro


问:
Where can i find nlp-compromise architecture diagram?
I came across with very interesting project on git hub nlp-compromise/compromise.

I want to know how it works but cant find any documentation about its architecture or how it works on back-end.

答:
yeah, we've been working hard on the docs the past-few months.

Hope this hits the spot:

https://github.com/nlp-compromise/compromise/wiki/How-it-Works


问:
How to custom style angular-bootstrap-toggle?
I am including angular-bootstrap-toggle in my library for toggling. I am also setting the on and off values. But the labels are overflowing, and is overlapped by the toggle button - Image 1, and Image 2. I want to set my own style. According to the documentation online on angular-bootstrap-toggle, we can just add style attribute. I tried that, but am getting an error saying ': expected' as shown here:

```<code> <div>
     <toggle ng-model="selectedTicket" ng-change="toggleTicket()" on="Ticket" off="Image" style="ami"></toggle>
 </div>
</code>```

Style is defined in my index.html file under  after including all the css files as:

```<code><style>
        .toggle.ami {
            width: 80px;
        }
        .toggle.ami .toggle-handle{
            width: 80px;
        }
</style>
</code>```

I would appreciate any suggestions to help me overcome this problem.

答:
It should work if you change "style" to "class" in your HTML:

```<code><div>
  <toggle ng-model="selectedTicket" ng-change="toggleTicket()" on="Ticket" off="Image" class="ami"></toggle>
</div>
</code>```

You will also need to remove the . from your .toggle CSS selector because toggle isn't a class:

```<code><style>
  toggle.ami {
    width: 80px;
  }
  toggle.ami .toggle-handle{
    width: 80px;
  }
</style>
</code>```

Body:
I am including angular-bootstrap-toggle in my library for toggling. I am also setting the on and off values. But the labels are overflowing, and is overlapped by the toggle button - Image 1, and Image 2. I want to set my own style. According to the documentation online on angular-bootstrap-toggle, we can just add style attribute. I tried that, but am getting an error saying ': expected' as shown here:

     <toggle ng-model="selectedTicket" ng-change="toggleTicket()" on="Ticket" off="Image" style="ami"></toggle>

Style is defined in my index.html file under  after including all the css files as:

I would appreciate any suggestions to help me overcome this problem.

Body:
It should work if you change "style" to "class" in your HTML:

<div>
  <toggle ng-model="selectedTicket" ng-change="toggleTicket()" on="Ticket" off="Image" class="ami"></toggle>
</div>

You will also need to remove the . from your .toggle CSS selector because toggle isn't a class:

<style>
  toggle.ami {
    width: 80px;
  }
  toggle.ami .toggle-handle{
    width: 80px;
  }
</style>


问:
PROGMEM variable discarded even if declared as (used)
I'm using ATMEL Studio 6.2 and its toolchain with avr-gcc (avr8-gnu-toolchain). I have a variable that needs to be placed in flash (PROGMEM) and I declare it as a global:

```<code>static const uint16_t gPrgLen PROGMEM __attribute__((used)) = 0;
</code>```

The compiler doesn't complain and the linker doesn't complain, but when I open the .lss file, there is no gPrgLen to be found. In the .map file we can see that it has been listed under "discarded input sections"

```<code>Discarded input sections
.progmem.data.gPrgLen    0x00000000    0x2    Boot.o
</code>```

It is built as a release, but a debug build gives the same result.
How can I force the linker to include this variable in the *(.progmem*) section?

EDIT

Added static but still the same result.

Here is the linker part:

```<code># All Target
all: $(OUTPUT_FILE_PATH) $(ADDITIONAL_DEPENDENCIES)

$(OUTPUT_FILE_PATH): $(OBJS) $(USER_OBJS) $(OUTPUT_FILE_DEP) $(LIB_DEP)
@echo Building target: $@
@echo Invoking: AVR/GNU Linker : 4.8.1
$(QUOTE)C:\Program Files (x86)\Atmel\Atmel Toolchain\AVR8 GCC\Native\3.4.1056\avr8-gnu-toolchain\bin\avr-gcc.exe$(QUOTE) -o$(OUTPUT_FILE_PATH_AS_ARGS) $(OBJS_AS_ARGS) $(USER_OBJS) $(LIBS) -Wl,-Map="Boot.map" -Wl,--start-group -Wl,-lm  -Wl,--end-group -Wl,--gc-sections -Wl,-section-start=.text=0xf800  -mmcu=at90usb647
@echo Finished building target: $@
"C:\Program Files (x86)\Atmel\Atmel Toolchain\AVR8 GCC\Native\3.4.1056\avr8-gnu-toolchain\bin\avr-objcopy.exe" -O ihex -R .eeprom -R .fuse -R .lock -R .signature -R .user_signatures  "Boot.elf" "Boot.hex"
"C:\Program Files (x86)\Atmel\Atmel Toolchain\AVR8 GCC\Native\3.4.1056\avr8-gnu-toolchain\bin\avr-objcopy.exe" -j .eeprom  --set-section-flags=.eeprom=alloc,load --change-section-lma .eeprom=0  --no-change-warnings -O ihex "Boot.elf" "Boot.eep" || exit 0
"C:\Program Files (x86)\Atmel\Atmel Toolchain\AVR8 GCC\Native\3.4.1056\avr8-gnu-toolchain\bin\avr-objdump.exe" -h -S "Boot.elf" > "Boot.lss"
"C:\Program Files (x86)\Atmel\Atmel Toolchain\AVR8 GCC\Native\3.4.1056\avr8-gnu-toolchain\bin\avr-objcopy.exe" -O srec -R .eeprom -R .fuse -R .lock -R .signature -R .user_signatures "Boot.elf" "Boot.srec"
"C:\Program Files (x86)\Atmel\Atmel Toolchain\AVR8 GCC\Native\3.4.1056\avr8-gnu-toolchain\bin\avr-size.exe" "Boot.elf"
</code>```

答:
Odd that __attribute__((used)) isn't working. Two suggestions to try.

First, change the variable from static to volatile (or just add volatile). That may prevent it from being optimized away.

If that doesn't work, instead you can add a line to the linker to make it "[p]retend the symbol symbol is undefined, to force linking of library modules to define it" (GCC Link Options). This is done via -u symbol or --undefined=symbol.

To add it to the Atmel Studio project file, go to Toolchain -> AVR/GNU Linker -> Miscellaneous. Then in Other Linker Flags add --undefined=gPrgLen.

I've used this to embed revision/compile-time information into the Hex file where it wasn't otherwise used. That way I could retrieve the memory from a device and know under what conditions it was built (primarily for tracking changes during prototyping and initial firmware debugging). My main.c file had a global char array that looked something like const char codeCompileDetails[] PROGMEM = "company_name-" __DATE__ "-" __TIME__;. Coupled with --undefined=codeCompileDetails, that data (here including the date and time the code was compiled) always makes it into the executable.

Body:
I'm using ATMEL Studio 6.2 and its toolchain with avr-gcc (avr8-gnu-toolchain). I have a variable that needs to be placed in flash (PROGMEM) and I declare it as a global:

static const uint16_t gPrgLen PROGMEM __attribute__((used)) = 0;

The compiler doesn't complain and the linker doesn't complain, but when I open the .lss file, there is no gPrgLen to be found. In the .map file we can see that it has been listed under "discarded input sections"

Discarded input sections
.progmem.data.gPrgLen    0x00000000    0x2    Boot.o

It is built as a release, but a debug build gives the same result.
How can I force the linker to include this variable in the *(.progmem*) section?

EDIT

Added static but still the same result.

Here is the linker part:

# All Target
all: $(OUTPUT_FILE_PATH) $(ADDITIONAL_DEPENDENCIES)

$(OUTPUT_FILE_PATH): $(OBJS) $(USER_OBJS) $(OUTPUT_FILE_DEP) $(LIB_DEP)
@echo Building target: $@
@echo Invoking: AVR/GNU Linker : 4.8.1
$(QUOTE)C:\Program Files (x86)\Atmel\Atmel Toolchain\AVR8 GCC\Native\3.4.1056\avr8-gnu-toolchain\bin\avr-gcc.exe$(QUOTE) -o$(OUTPUT_FILE_PATH_AS_ARGS) $(OBJS_AS_ARGS) $(USER_OBJS) $(LIBS) -Wl,-Map="Boot.map" -Wl,--start-group -Wl,-lm  -Wl,--end-group -Wl,--gc-sections -Wl,-section-start=.text=0xf800  -mmcu=at90usb647
@echo Finished building target: $@
"C:\Program Files (x86)\Atmel\Atmel Toolchain\AVR8 GCC\Native\3.4.1056\avr8-gnu-toolchain\bin\avr-objcopy.exe" -O ihex -R .eeprom -R .fuse -R .lock -R .signature -R .user_signatures  "Boot.elf" "Boot.hex"
"C:\Program Files (x86)\Atmel\Atmel Toolchain\AVR8 GCC\Native\3.4.1056\avr8-gnu-toolchain\bin\avr-objcopy.exe" -j .eeprom  --set-section-flags=.eeprom=alloc,load --change-section-lma .eeprom=0  --no-change-warnings -O ihex "Boot.elf" "Boot.eep" || exit 0
"C:\Program Files (x86)\Atmel\Atmel Toolchain\AVR8 GCC\Native\3.4.1056\avr8-gnu-toolchain\bin\avr-objdump.exe" -h -S "Boot.elf" > "Boot.lss"
"C:\Program Files (x86)\Atmel\Atmel Toolchain\AVR8 GCC\Native\3.4.1056\avr8-gnu-toolchain\bin\avr-objcopy.exe" -O srec -R .eeprom -R .fuse -R .lock -R .signature -R .user_signatures "Boot.elf" "Boot.srec"
"C:\Program Files (x86)\Atmel\Atmel Toolchain\AVR8 GCC\Native\3.4.1056\avr8-gnu-toolchain\bin\avr-size.exe" "Boot.elf"


问:
How to copy projects in Android Studio?
I tried copying my Android Studio project but every time I do that it gives me errors. I read other questions and answers on this topics but none of this helped me.

When I copy a project and try to run it on the emulator it gives the following error:

"Installation failed with message Invalid File:
  C:...\app\build\intermediates\split-apk\debug\slices\slice_9.apk. It
  is possible that this issue is resolved by uninstalling an existing
  version of the apk if it is present, and then re-installing."

According to answers on similar questions, it should help to perform a 'clean project'. When I do this, the emulator starts but stops starting the app with a runtime error:

"java.lang.RuntimeException: Unable to instantiate activity
  ComponentInfo{nl.assortimens.hardlooptrainingapp/nl.assortimens.hardlooptrainingapp.MainMenuActivity}:
  java.lang.ClassNotFoundException: Didn't find class
  "nl.assortimens.hardlooptrainingapp.MainMenuActivity" on path:
  DexPathList[[zip file
  "/data/app/nl.assortimens.hardlooptrainingapp-1/base.apk"],nativeLibraryDirectories=[/data/app/nl.assortimens.hardlooptrainingapp-1/lib/x86,
  /vendor/lib, /system/lib]]"

How can I copy projects without errors or what should I do to fix those errors?

答: Try to remove the build.gradle file, and settings.gradle file. Then rebuild. Hope this gives your problem.</p>

Title: How to copy projects in Android Studio?


问:
Ruby vs. PHP/plugins social networking
I am in the process of building a site that will contain features comparable to those that social networking sites usually use.  I already built the signup forms, login forms, and forms to add information to the database in PHP/mySQL.  What do people usually use for these types of projects?  Can anyone suggest any good plugins or methods to help me out?  Where is a good place to find these sort of things?  Is it worth it to learn Ruby to do this?  Does Ruby make this much easier?  How can I use jquery in a project such as this?  How should I create the chat rooms / forums / profiles?

Thanks!

答:
i think that if your planning on something with more than 10 pages, well it should be more than necesary to start thinking about a framework. As i said many times, i'm a symfony enthusiast and i've been working with it for quite some time for work. Its based on php (you wont need to learn any other language) and implements the MVC object pattern.

It handles from routing, forms, database abstracions and everything else. Also has a plugin project with tons of code. Check the main project page for more details

Title: Ruby vs. PHP/plugins social networking


问:
Why is my for loop in C working correctly?
So I have this code I created for CS50 pset1 Mario problem. The code is behaving correctly and is doing exactly what it is supposed to do, but I don't understand one of the parts. Why is it behaving this way.

Here's the code I have written in C:

```<code>  #include <cs50.h>
#include <stdio.h>

int main (void){
int height, row, space, hash;

    do {
        printf("Height: ");
        height = get_int();
    } while(height<0 || height>23);

    for (row=0; row<height; row++){

        for (space=height-(row+1); space>0; space--){
            printf("-");
        }

        for (hash=height-row; hash<=height; hash++){
            printf("#");
        }

        printf("#\n");
    }

}
</code>```

So for example when the user enters 3 as the Height, I get

```<code>--##
-###
####
</code>```

What I don't understand why it is not:

```<code>--####
-###
##
</code>```

This part is what is throwing me off:

```<code>for (hash=height-row; hash<=height; hash++){
            printf("#");
        }
</code>```

If hash = height-row then shouldn't it be 3-0=3 and have it print the hash sign 3 times? Then 3-1=2 and print it twice, and so on? Why is it doing it in reverse?

Can someone please explain what's wrong with my logic?

答:
The answer is in the conditional and the increment part of the for loop.

You are correct that the initial value of hash would be 3. The conditional part of the for loop will check to make sure hash (3) is less than or equal to height (3). So, is 3 <= 3 ? Yes.

The increment part of the for loop determines what changes in each iteration. In you case, hash will be incremented by 1, so the next time the loop is executed, hash will have a value of 4. The conditional will check: is hash (4) <= height (3)? This returns false, and the for loop will be terminated.

When the next iteration of the "row" loop happens, the initial value of hash is 2 (since 3 - 1 = 2). This will continue to add 1 to hash until "hash <= height" returns false. As "row" increases, more "#" get printed.

Body:
So I have this code I created for CS50 pset1 Mario problem. The code is behaving correctly and is doing exactly what it is supposed to do, but I don't understand one of the parts. Why is it behaving this way.

Here's the code I have written in C:

  #include <cs50.h>
#include <stdio.h>

int main (void){
int height, row, space, hash;

    do {
        printf("Height: ");
        height = get_int();
    } while(height<0 || height>23);

    for (row=0; row<height; row++){

        for (space=height-(row+1); space>0; space--){
            printf("-");
        }

        for (hash=height-row; hash<=height; hash++){
            printf("#");
        }

        printf("#\n");
    }

}

So for example when the user enters 3 as the Height, I get

--##
-###
####

What I don't understand why it is not:

--####
-###
##

This part is what is throwing me off:

for (hash=height-row; hash<=height; hash++){
            printf("#");
        }

If hash = height-row then shouldn't it be 3-0=3 and have it print the hash sign 3 times? Then 3-1=2 and print it twice, and so on? Why is it doing it in reverse?

Can someone please explain what's wrong with my logic?


问:
SQL Join returns duplicate entries
Just going to start out saying that I am new to SQL and what I've written is based off of tutorials (Also I am using SQL Server 2012). The issue I am having is I am trying to take data from 4 different tables and put them into 1 table to be accessed by Access. However I keep getting duplicate results if a value is different from the rest.
The tables look like

Cell1

```<code>|LotNum|SerialNum|PassFail|
| Lot11|     1234|       1|
| Lot11|     2345|       1|
| Lot11|     3456|       1|
| Lot11|     4567|       1|
</code>```

Cell2

```<code>|LotNum|SerialNum|PassFail|
| Lot11|     1234|       1|
| Lot11|     2345|       1|
| Lot11|     3456|       1|
| Lot11|     4567|       1|
</code>```

Cell3

```<code>|LotNum|SerialNum|PassFail|
| Lot11|     1234|       1|
| Lot11|     2345|       1|
| Lot11|     3456|       1|
| Lot11|     4567|       1|
</code>```

Cell4

```<code>|LotNum|SerialNum|PassFail|
| Lot11|     1234|       1|
| Lot11|     2345|       1|
| Lot11|     3456|       1|
| Lot11|     4567|       0|
</code>```

My code is

```<code>Alter Procedure [dbo].[spSingleData](
@LotNum varchar(50)
)
AS
Truncate Table dbo.SingleSheet
Begin
Insert INTO dbo.SingleSheet (SerialNum, Cell1PF, Cell2Pf, Cell3PF, Cell4PF)
Select Distinct Cell1.SerialNum, Cell1.PF, Cell2.PF, Cell3.PF, Cell4.PF
From dbo.Cell1
Left Join Cell2 On Cell1.LotNum=Cell2.LotNum
Left Join Cell3 On Cell1.LotNum=Cell3.LotNum
Left Join Cell4 On Cell1.LotNum=Cell4.LotNum
Where Cell1.LotNum = @LotNum
Order by SerialNum
End
</code>```

PassFail can be 0, 1, or NULL, however, like in the example above, if one of the PassFails is different from the rest, the resulting table returns

```<code>|1234|   1|   1|   1|    0|
|1234|   1|   1|   1|    1|
|2345|   1|   1|   1|    0|
|2345|   1|   1|   1|    1|
|3456|   1|   1|   1|    0|
|3456|   1|   1|   1|    1|
|4567|   1|   1|   1|    0|
|4567|   1|   1|   1|    1|
</code>```

Am I just using the wrong Join or should I be using something else?

答:
Is this what you are trying to achieve:

If so then you are missing a JOIN predicate on SerialNum and you do not need the DISTINCT

Sample Data:

```<code>IF OBJECT_ID('tempdb..#Cell1') IS NOT NULL
DROP TABLE #Cell1
CREATE TABLE #Cell1 (LotNum varchar(10),SerialNum int,PassFail bit)
INSERT INTO #Cell1
VALUES
('Lot11',1234,1),
('Lot11',2345,1),
('Lot11',3456,1),
('Lot11',4567,1)

IF OBJECT_ID('tempdb..#Cell2') IS NOT NULL
DROP TABLE #Cell2
CREATE TABLE #Cell2 (LotNum varchar(10),SerialNum int,PassFail bit)
INSERT INTO #Cell2
VALUES
('Lot11',1234,1),
('Lot11',2345,1),
('Lot11',3456,1),
('Lot11',4567,1)

IF OBJECT_ID('tempdb..#Cell3') IS NOT NULL
DROP TABLE #Cell3
CREATE TABLE #Cell3 (LotNum varchar(10),SerialNum int,PassFail bit)
INSERT INTO #Cell3
VALUES
('Lot11',1234,1),
('Lot11',2345,1),
('Lot11',3456,1),
('Lot11',4567,1)

IF OBJECT_ID('tempdb..#Cell4') IS NOT NULL
DROP TABLE #Cell4
CREATE TABLE #Cell4 (LotNum varchar(10),SerialNum int,PassFail bit)
INSERT INTO #Cell4
VALUES
('Lot11',1234,1),
('Lot11',2345,1),
('Lot11',3456,1),
('Lot11',4567,0)
</code>```

Query:

```<code>SELECT #Cell1.SerialNum,
       #Cell1.PassFail,
       #Cell2.PassFail,
       #Cell3.PassFail,
       #Cell4.PassFail
FROM #Cell1
     LEFT JOIN #Cell2 ON #Cell1.LotNum = #Cell2.LotNum AND #Cell1.SerialNum = #Cell2.SerialNum
     LEFT JOIN #Cell3 ON #Cell1.LotNum = #Cell3.LotNum AND #Cell1.SerialNum = #Cell3.SerialNum
     LEFT JOIN #Cell4 ON #Cell1.LotNum = #Cell4.LotNum AND #Cell1.SerialNum = #Cell4.SerialNum
ORDER BY SerialNum;
</code>```

Results:

Title: SQL Join returns duplicate entries

Body:
Just going to start out saying that I am new to SQL and what I've written is based off of tutorials (Also I am using SQL Server 2012). The issue I am having is I am trying to take data from 4 different tables and put them into 1 table to be accessed by Access. However I keep getting duplicate results if a value is different from the rest.
The tables look like

Cell1

|LotNum|SerialNum|PassFail|
| Lot11|     1234|       1|
| Lot11|     2345|       1|
| Lot11|     3456|       1|
| Lot11|     4567|       1|

Cell2

|LotNum|SerialNum|PassFail|
| Lot11|     1234|       1|
| Lot11|     2345|       1|
| Lot11|     3456|       1|
| Lot11|     4567|       1|

Cell3

|LotNum|SerialNum|PassFail|
| Lot11|     1234|       1|
| Lot11|     2345|       1|
| Lot11|     3456|       1|
| Lot11|     4567|       1|

Cell4

|LotNum|SerialNum|PassFail|
| Lot11|     1234|       1|
| Lot11|     2345|       1|
| Lot11|     3456|       1|
| Lot11|     4567|       0|

My code is

Alter Procedure [dbo].[spSingleData](
@LotNum varchar(50)
)
AS
Truncate Table dbo.SingleSheet
Begin
Insert INTO dbo.SingleSheet (SerialNum, Cell1PF, Cell2Pf, Cell3PF, Cell4PF)
Select Distinct Cell1.SerialNum, Cell1.PF, Cell2.PF, Cell3.PF, Cell4.PF
From dbo.Cell1
Left Join Cell2 On Cell1.LotNum=Cell2.LotNum
Left Join Cell3 On Cell1.LotNum=Cell3.LotNum
Left Join Cell4 On Cell1.LotNum=Cell4.LotNum
Where Cell1.LotNum = @LotNum
Order by SerialNum
End

PassFail can be 0, 1, or NULL, however, like in the example above, if one of the PassFails is different from the rest, the resulting table returns

|1234|   1|   1|   1|    0|
|1234|   1|   1|   1|    1|
|2345|   1|   1|   1|    0|
|2345|   1|   1|   1|    1|
|3456|   1|   1|   1|    0|
|3456|   1|   1|   1|    1|
|4567|   1|   1|   1|    0|
|4567|   1|   1|   1|    1|

Am I just using the wrong Join or should I be using something else?

Body:
Is this what you are trying to achieve:

If so then you are missing a JOIN predicate on SerialNum and you do not need the DISTINCT

Sample Data:

IF OBJECT_ID('tempdb..#Cell1') IS NOT NULL
DROP TABLE #Cell1
CREATE TABLE #Cell1 (LotNum varchar(10),SerialNum int,PassFail bit)
INSERT INTO #Cell1
VALUES
('Lot11',1234,1),
('Lot11',2345,1),
('Lot11',3456,1),
('Lot11',4567,1)

IF OBJECT_ID('tempdb..#Cell2') IS NOT NULL
DROP TABLE #Cell2
CREATE TABLE #Cell2 (LotNum varchar(10),SerialNum int,PassFail bit)
INSERT INTO #Cell2
VALUES
('Lot11',1234,1),
('Lot11',2345,1),
('Lot11',3456,1),
('Lot11',4567,1)

IF OBJECT_ID('tempdb..#Cell3') IS NOT NULL
DROP TABLE #Cell3
CREATE TABLE #Cell3 (LotNum varchar(10),SerialNum int,PassFail bit)
INSERT INTO #Cell3
VALUES
('Lot11',1234,1),
('Lot11',2345,1),
('Lot11',3456,1),
('Lot11',4567,1)

IF OBJECT_ID('tempdb..#Cell4') IS NOT NULL
DROP TABLE #Cell4
CREATE TABLE #Cell4 (LotNum varchar(10),SerialNum int,PassFail bit)
INSERT INTO #Cell4
VALUES
('Lot11',1234,1),
('Lot11',2345,1),
('Lot11',3456,1),
('Lot11',4567,0)

Query:

SELECT #Cell1.SerialNum,
       #Cell1.PassFail,
       #Cell2.PassFail,
       #Cell3.PassFail,
       #Cell4.PassFail
FROM #Cell1
     LEFT JOIN #Cell2 ON #Cell1.LotNum = #Cell2.LotNum AND #Cell1.SerialNum = #Cell2.SerialNum
     LEFT JOIN #Cell3 ON #Cell1.LotNum = #Cell3.LotNum AND #Cell1.SerialNum = #Cell3.SerialNum
     LEFT JOIN #Cell4 ON #Cell1.LotNum = #Cell4.LotNum AND #Cell1.SerialNum = #Cell4.SerialNum
ORDER BY SerialNum;

Results:


问:
Android - protecting api endpoint auth header
In my Android app, I make requests to my backend API and add a auth header value so that only my app can access my API data. I'm using OKHttp which makes it simple  .addHeader("name", "value")

However, right now I'm simply hardcoding this header name and value in my Java file. It seems that people are able to decompile Android apps and will be able to see my auth header value.

Is there a way I can prevent this from happening?

答:
This is a very discussed topic and it's always a tradeoff.

Some strategies are

Hardcoded in Java

In shared preferences, assets or resources folders

Using the NDK

Public/private API key exchange

Article's conclusion

What option you choose is probably going to be determined by how much control you have over the backend server. If you don’t have any control then you’re probably going to have to hide the API key using the NDK. If you do then we recommend the Public/Private encryption of the API key using nonces to prevent any replay attacks. In the next article we’ll look at the security implications of supporting earlier Android OS versions, as well as how some Android phones are more secure than others.

Subscribe to our Android Developer Newsletter
Join our Android Developers newsletter to get all the top developer news, tips & links once a week in your inbox

Full article

Possible duplicated question/answer


问:
What purpose does the WCF client-specified "userPrincipalName" serve?
I've created a WCF service with a wsHttpBinding and Message security.  Then I added a service reference which resulted in the client's config file being updated with this:

```<code><client>
  <endpoint address="http://localhost:42160/Service1.svc/secure"
    binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1"
    contract="SecureProxy.IService1" name="WSHttpBinding_IService1">
    <identity>
        <userPrincipalName value="baria2@mydomain.com" />
    </identity>
  </endpoint>
</client>
</code>```

I don't understand what the userPrincipalName is for.  No matter what I modify the value to, the client and service communicate successfully.  It doesn't seem to serve any purpose.

This MSDN article attempts to explain the purpose in detail, and somehow manages to explain nothing at all.

What problem was Microsoft trying to solve by adding that into the WCF story?  Again, I can change the value to anything I want and it doesn't affect the client and service.

Also, here is a similar question.

答:
By default, when a service is configured to use Windows credentials, an  and  element is generated in the WSDL document produced the by Service Model Metadata Utility Tool (Svcutil.exe). If the service is running under the LocalSystem. LocalService, or NetworkService account, a Service Principal Name (SPN) will be generated in the form of host/ because those accounts have access to the computer's SPN data. If the service is running under a different account, WCF generates a Principal Name (UPN) in the form of @. This occurs because Kerberos authentication requires a UPN or SPN to be supplied to the client to authenticate the service.

This behavior does not occur if you set the Identity of the service endpoint in either code or configuration. You can also use the SetSpn.exe (http://www.microsoft.com/windows2000/techinfo/reskit/tools/existing/setspn-o.asp) tool register an additional SPN with a service's account in a domain. The SPN can then be used as the Identity of the service.

as mentioned here: https://social.msdn.microsoft.com/Forums/vstudio/en-US/78638457-ca7a-4f88-b8a9-9bc32d4b5c7d/userprincipalname-element-generated-in-client-config?forum=wcf

Body:
I've created a WCF service with a wsHttpBinding and Message security.  Then I added a service reference which resulted in the client's config file being updated with this:

<client>
  <endpoint address="http://localhost:42160/Service1.svc/secure"
    binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1"
    contract="SecureProxy.IService1" name="WSHttpBinding_IService1">
    <identity>
        <userPrincipalName value="baria2@mydomain.com" />
    </identity>
  </endpoint>
</client>

I don't understand what the userPrincipalName is for.  No matter what I modify the value to, the client and service communicate successfully.  It doesn't seem to serve any purpose.

This MSDN article attempts to explain the purpose in detail, and somehow manages to explain nothing at all.

What problem was Microsoft trying to solve by adding that into the WCF story?  Again, I can change the value to anything I want and it doesn't affect the client and service.

Also, here is a similar question.


问:
CSS layout with header and colums top to bottom
Greets,

I'm currently working on a website and have stumbled upon some layout difficulties. What I want is a website with a header (fixed hight) and followed by three columns (left, middle, left). I want the columns to stretch from top to bottom. But when I set them to a 100% height, the page gets overflow from the static header on 140px. I have included an image of the page with lots of colors to show the divs (http://oi51.tinypic.com/974rqd.jpg).

Any help is greatly appreciated!

答:
This should solve your problem:
http://www.cssplay.co.uk/layouts/three-column-layouts.html</p>


问:
404 (Not Found) when trying to route to the index with mongodb and nodejs
I'm working on an app for a portfolio that works as sort of a video game companion but I can't seem to get it to connect to the mongo server.

My code seems to work as it says that the connection is successful when I run the server.js in node as this is what my terminal says.

(node:45137) DeprecationWarning: open() is deprecated in mongoose >= >4.11.0, use openUri() instead, or set the useMongoClient option if >using connect() or createConnection(). See http://mongoosejs.com >/docs/connections.html#use-mongo-client
  App running on port 27017!
  Mongoose connection successful.

However when I try put it on localhost it fails

GET http://localhost:27017/ 404 (Not Found)

This is my server code with the routes inside it.

I've already double checked to make sure all the styles and javascripts needed are linked correctly but still no good.

// Dependencies
var express = require("express");
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var exphbs = require("express-handlebars");
var request = require("request");

// Set mongoose to leverage built in JavaScript ES6 Promises
mongoose.Promise = Promise;

// Initialize Express
var app = express();

// Use morgan and body parser with our app
app.use(bodyParser.urlencoded({
  extended: false
}));

// Make public a static dir
app.use(express.static(__dirname + "/public"));

app.engine("handlebars", exphbs({ defaultLayout: "main" }));
app.set("view engine", "handlebars");

// Database configuration with mongoose
mongoose.connect("mongodb://localhost/usersdb");
var db = mongoose.connection;

// Show any mongoose errors
db.on("error", function(error) {
  console.log("Mongoose Error: ", error);
});

// Once logged in to the db through mongoose, log a success message
db.once("open", function() {
  console.log("Mongoose connection successful.");
});

//routes

app.get('/', function(req, res, next, error){
 // Log any errors
    if (error) {
      console.log(error);
    }
    // Or send the doc to the browser as a json object
    else {
    res.render("index",{ title: 'Express' });
      }
});

// Listen on port 27107
app.listen(process.env.PORT || 27017, function() {
  console.log("App running on port 27017!");
});```

Any ideas?

答: You have set wrong signature for the router handler, instead of app.get('/', function(req, res, next, error){ , you need to use app.get('/', function(req, res, next){, without error param, which if occur should be on first place, and when error param occur this handler will be an error middleware.

Body:
I'm working on an app for a portfolio that works as sort of a video game companion but I can't seem to get it to connect to the mongo server.

My code seems to work as it says that the connection is successful when I run the server.js in node as this is what my terminal says.

(node:45137) DeprecationWarning: open() is deprecated in mongoose >= >4.11.0, use openUri() instead, or set the useMongoClient option if >using connect() or createConnection(). See http://mongoosejs.com >/docs/connections.html#use-mongo-client
  App running on port 27017!
  Mongoose connection successful.

However when I try put it on localhost it fails

GET http://localhost:27017/ 404 (Not Found)

This is my server code with the routes inside it.

I've already double checked to make sure all the styles and javascripts needed are linked correctly but still no good.

// Dependencies
var express = require("express");
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var exphbs = require("express-handlebars");
var request = require("request");

// Set mongoose to leverage built in JavaScript ES6 Promises
mongoose.Promise = Promise;

// Initialize Express
var app = express();

// Use morgan and body parser with our app
app.use(bodyParser.urlencoded({
  extended: false
}));

// Make public a static dir
app.use(express.static(__dirname + "/public"));

app.engine("handlebars", exphbs({ defaultLayout: "main" }));
app.set("view engine", "handlebars");

// Database configuration with mongoose
mongoose.connect("mongodb://localhost/usersdb");
var db = mongoose.connection;

// Show any mongoose errors
db.on("error", function(error) {
  console.log("Mongoose Error: ", error);
});

// Once logged in to the db through mongoose, log a success message
db.once("open", function() {
  console.log("Mongoose connection successful.");
});

//routes

app.get('/', function(req, res, next, error){
 // Log any errors
    if (error) {
      console.log(error);
    }
    // Or send the doc to the browser as a json object
    else {
    res.render("index",{ title: 'Express' });
      }
});

// Listen on port 27107
app.listen(process.env.PORT || 27017, function() {
  console.log("App running on port 27017!");
});

Any ideas?


问:
JavaFX8, SQLite(Embedded) exe, exec jar can't read/update the runtime database
I am creating a simple desktop application using JavaFx8 and SQLite and Eclipse Neon IDE. The Application works fine when launched to test from Eclipse. But If I create an executable jar or a Windows Exe file, it doesn't read/update the database.
Here's the code snippet used for creating and reading database.

```<code> private Connection loadPropertiesFileSQLite() throws SQLException, ClassNotFoundException {
    try {
        inputStream = new FileInputStream("databasesqlite.properties");
        properties.load(inputStream);
        Class.forName("org.sqlite.JDBC");
        // database path, if it's new database, it will be created in the project folder
        conSQLite = DriverManager.getConnection("jdbc:sqlite:Application.db");
        System.out.println("Database Opened Successfully.");
    } catch (Exception e) {
        System.out.println("DDDD");
        e.printStackTrace();
    }
    return conSQLite;
}
</code>```

The connectors and jars I'm using are these:

The database is created in embedded mode when the user runs the application for the first time.
I have searched and tried scores of combinations from changing the location of database in DriverManager.getConnection("jdbc:sqlite:Application.db");
to many other things. Is there anything big that I'm missing here?

答:
The key is to use conSQLite = DriverManager.getConnection("jdbc:sqlite::resource:File:\\{some_path}\\Application.db");

instead of

```<code>conSQLite = DriverManager.getConnection("jdbc:sqlite:Application.db");
</code>```

Now it works all fine.

Body:
I am creating a simple desktop application using JavaFx8 and SQLite and Eclipse Neon IDE. The Application works fine when launched to test from Eclipse. But If I create an executable jar or a Windows Exe file, it doesn't read/update the database.
Here's the code snippet used for creating and reading database.

 private Connection loadPropertiesFileSQLite() throws SQLException, ClassNotFoundException {
    try {
        inputStream = new FileInputStream("databasesqlite.properties");
        properties.load(inputStream);
        Class.forName("org.sqlite.JDBC");
        // database path, if it's new database, it will be created in the project folder
        conSQLite = DriverManager.getConnection("jdbc:sqlite:Application.db");
        System.out.println("Database Opened Successfully.");
    } catch (Exception e) {
        System.out.println("DDDD");
        e.printStackTrace();
    }
    return conSQLite;
}

The connectors and jars I'm using are these:

The database is created in embedded mode when the user runs the application for the first time.
I have searched and tried scores of combinations from changing the location of database in DriverManager.getConnection("jdbc:sqlite:Application.db");
to many other things. Is there anything big that I'm missing here?

Body:
The key is to use conSQLite = DriverManager.getConnection("jdbc:sqlite::resource:File:\\{some_path}\\Application.db");

instead of

conSQLite = DriverManager.getConnection("jdbc:sqlite:Application.db");

Now it works all fine.


问:
Extracting values from function output based on being greater than or less than
I have created multiple functions using this code:

```<code>getT <- function(df, ID, Number){
  df %>%
    group_by(ID, Number) %>%
    mutate( Distance = finish - begin) %>%
    select(-begin,-finish,-symbols) %>%
    nest() %>%
    mutate( data = map( data, ~ filter(.x, Distance == max(Distance)))) %>%
    unnest()
}

getallT <- as.data.frame(getT(df))

getTID <- function(df, ID) {
  df1 <- getallT(df)
  subset(x = getallT, subset = (ID))
}`
</code>```

Which gives me an output like this:

```<code>ID     Number     Time     Distance
33         1      2.00         870
33         2      1.98         859
33         3      0.82         305
33         4      2.02         651
33         5      2.53         502
</code>```

I am wondering if there is a way to extract the Time values based on how low or high the value is? In the case of above, I would like to create a function that could extract the values that were above 2.00 so it would have an output like this instead:

```<code>ID     Number     Time     Distance
33         4      2.02         651
33         5      2.53         502
</code>```

Eventually, I would like to create a different function to extract the values that are below 1.00 and then go further by creating another different function for the combination of the two but I think I can do that once I know how to do the first part! Any response is much appreciated.

答:
Here's your data frame:

```<code>df <- data.frame(ID=rep(33,5),
                 Number=1:5,
                 Time=c(2.00,1.98,0.82,2.02,2.53),
                 Distance=c(870,859,305,651,502))
</code>```

You can keep values <=1 and >=2 with filter, between and !

```<code>df <- df %>% filter(!between(Time,1,2))

  ID Number Time Distance
1 33      3 0.82      305
2 33      4 2.02      651
3 33      5 2.53      502
</code>```

Body:
I have created multiple functions using this code:

getT <- function(df, ID, Number){
  df %>%
    group_by(ID, Number) %>%
    mutate( Distance = finish - begin) %>%
    select(-begin,-finish,-symbols) %>%
    nest() %>%
    mutate( data = map( data, ~ filter(.x, Distance == max(Distance)))) %>%
    unnest()
}

getallT <- as.data.frame(getT(df))

getTID <- function(df, ID) {
  df1 <- getallT(df)
  subset(x = getallT, subset = (ID))
}`

Which gives me an output like this:

ID     Number     Time     Distance
33         1      2.00         870
33         2      1.98         859
33         3      0.82         305
33         4      2.02         651
33         5      2.53         502

I am wondering if there is a way to extract the Time values based on how low or high the value is? In the case of above, I would like to create a function that could extract the values that were above 2.00 so it would have an output like this instead:

ID     Number     Time     Distance
33         4      2.02         651
33         5      2.53         502

Eventually, I would like to create a different function to extract the values that are below 1.00 and then go further by creating another different function for the combination of the two but I think I can do that once I know how to do the first part! Any response is much appreciated.

Body:
Here's your data frame:

df <- data.frame(ID=rep(33,5),
                 Number=1:5,
                 Time=c(2.00,1.98,0.82,2.02,2.53),
                 Distance=c(870,859,305,651,502))

You can keep values <=1 and >=2 with filter, between and !

df <- df %>% filter(!between(Time,1,2))

  ID Number Time Distance
1 33      3 0.82      305
2 33      4 2.02      651
3 33      5 2.53      502