问:
Cant give roles using python.py
I am trying give people roles. I have made sure my bot can add and remove roles. Here is my code:

```<code>@client.event
async def on_message(message):
    await client.add_roles(message.author, "role id")
</code>```

Error:

```<code>Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Jack Eagles\AppData\Roaming\Python\Python36\site-packages\discord\client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "C:/Users/Jack Eagles/PycharmProjects/Discord Bot/Main.py", line 71, in on_message
    await client.add_roles(message.author, role)
  File "C:\Users\Jack Eagles\AppData\Roaming\Python\Python36\site-packages\discord\client.py", line 2907, in add_roles
    new_roles = utils._unique(role.id for role in itertools.chain(member.roles, roles))
  File "C:\Users\Jack Eagles\AppData\Roaming\Python\Python36\site-packages\discord\utils.py", line 232, in _unique
    return [x for x in iterable if not (x in seen or adder(x))]
  File "C:\Users\Jack Eagles\AppData\Roaming\Python\Python36\site-packages\discord\utils.py", line 232, in <listcomp>
    return [x for x in iterable if not (x in seen or adder(x))]
  File "C:\Users\Jack Eagles\AppData\Roaming\Python\Python36\site-packages\discord\client.py", line 2907, in <genexpr>
    new_roles = utils._unique(role.id for role in itertools.chain(member.roles, roles))
AttributeError: 'str' object has no attribute 'id'
</code>```

答:
client.add_roles requires a Role object. It cannot accept a plain string

To get a Role, you should look through message.server.roles. Keep in mind that message.server might be None (In the case of private messages). You should not try to create your own instance of Role

Title: Cant give roles using python.py

Body:
I am trying give people roles. I have made sure my bot can add and remove roles. Here is my code:

@client.event
async def on_message(message):
    await client.add_roles(message.author, "role id")

Error:

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Jack Eagles\AppData\Roaming\Python\Python36\site-packages\discord\client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "C:/Users/Jack Eagles/PycharmProjects/Discord Bot/Main.py", line 71, in on_message
    await client.add_roles(message.author, role)
  File "C:\Users\Jack Eagles\AppData\Roaming\Python\Python36\site-packages\discord\client.py", line 2907, in add_roles
    new_roles = utils._unique(role.id for role in itertools.chain(member.roles, roles))
  File "C:\Users\Jack Eagles\AppData\Roaming\Python\Python36\site-packages\discord\utils.py", line 232, in _unique
    return [x for x in iterable if not (x in seen or adder(x))]
  File "C:\Users\Jack Eagles\AppData\Roaming\Python\Python36\site-packages\discord\utils.py", line 232, in <listcomp>
    return [x for x in iterable if not (x in seen or adder(x))]
  File "C:\Users\Jack Eagles\AppData\Roaming\Python\Python36\site-packages\discord\client.py", line 2907, in <genexpr>
    new_roles = utils._unique(role.id for role in itertools.chain(member.roles, roles))
AttributeError: 'str' object has no attribute 'id'


来源: stackexchange

问:
Transpose matrix in prolog
I want to transpose a matrix in prolog, so for example
[[1,2,3],[1,2,3],[1,2,3]] should become
[[1,1,1],[2,2,2],[3,3,3]]

Here is what I've done:

```<code>%transpose(M,T)
transpose([],[]).
transpose(M,[H|T]):-row(H,M,M1),transpose(M1,T).

%row(H, M, M1).
row([],[],[]).
row([H|Tt] , [[H|T1]|T] , [T1|Z]) :- row(Tt,T,Z).
</code>```

Where M is to be transposed in T.
Row predicate (not sure for the difference between predicate and function) get the head of each sublist in M, so I can get the entire first row of the new, transposed matrix T.
I tested row separately, and it is giving the proper result. But when I try to transpose, I get only 'false' and nothing happens, no info for the new matrix T is printed.

Can anyone help me? Is the problem in the way I built the program? Or the result I expect is only true/false indeed and if so, how to get the new matrix? Thanks :)

答:
First, a note on terminology: One characteristic of a function is that each input is related to exactly one output. On the other hand, a relation can hold for multiple such combinations. Prolog predicates induce relations between their arguments, and multiple answers can arise on backtracking.

As to your concrete question, @lurker has already given some solid advice.

However, as you already notice, tracing quickly gets very complex in Prolog, and I would therefore like to complement what lurker has written by explaining a few principles of declarative debugging in Prolog.

In essence, we will aim to make our problem simpler instead of harder. We start with the case you mention for the program you posted:

```
?- transpose([[1,2,3],[1,2,3],[1,2,3]], Ls).
<b>false.</b>
```

In logical terms, the relation is too specific: It fails to hold in a case in which it ought to hold.

To find a reason for this problem, we could step through the precise execution details, using a textual or graphical tracer, and try to keep track of all the details. This is extremely hard, so I suggest you first try to find a simpler case that still fails.

I will do this by generalizing the query. There are several ways to do this. For example, instead of concrete integers, I can use fresh variables:

```
?- transpose([[_,_,_],[_,_,_],[_,_,_]], Ls).
<b>false.</b>
```

Aha, so we have found a much more general case that still fails. As long as this case fails, the more specific case will definitely also fails, because we are reasoning over a pure and monotonic logic program.

So, the new question is: Why does this more general query fail? To find a reason, we can simply further generalize the query. For example, instead of reasoning about lists with 3 elements each, we can generalize this to the following case, where two of the lists are generalized to "more than one element":

```
?- transpose([[_|_],[_|_],[_,_,_]], Ls).
<b>false.</b>
```

We see that this much more general query still fails. We can even generalize it further:

```
?- transpose([_,_,[_,_,_]], Ls).
<b>false.</b>
```

This still fails! Note that we can also take it too far. For example:

```
?- transpose([_,_,_], Ls).
<b>nontermination</b>
```

Here, we run into a different issue altogether, related to termination properties of the program. However, in our case, we want to find a reason for the unexpected failure, and so we return to the case above:

```
?- transpose([_,_,[_,_,_]], Ls).
<b>false.</b>
```

At this point, there is not much more to generalize, so we could now invoke the tracer on this simplified query.

However, we can also continue in a different direction: Not every test case needs to be a generalization. We can also come up with an entirely different case, such as a list with only two (instead of three) elements:

```
?- transpose([_,[_,_,_]], Ls).
<b>false</b>
```

Aha, so this also fails, even though it ought to succeed!

What about even simpler cases:

```
?- transpose([[_,_,_]], Ls).
<b>false.</b>
```

And further:

```
?- transpose([[_,_]], Ls).
<b>false.</b>
```

And even further:

```
?- transpose([[_]], Ls).
<b>false.</b>
```

Each of these queries ought to succeed, but fails.

Why?

To find reasons, consider program-slicing of the underlying logic program. For example, let us take one of the simplest queries we found that should succeed, but doesn't: ?- transpose([[_]], _).

I use the following definition to generalize away constraints (= goals) of the original program

```
?- transpose([[_,_,_],[_,_,_],[_,_,_]], Ls).
<b>false.</b>
```0

For example, we can generalize row/3 as follows:

```
?- transpose([[_,_,_],[_,_,_],[_,_,_]], Ls).
<b>false.</b>
```1

Even with this much more general version of row/3, we get:

```
?- transpose([[_,_,_],[_,_,_],[_,_,_]], Ls).
<b>false.</b>
```2

This means: To make this query succeed, you either have to add additional clauses to your code (to make it more general) or change the remaining fragment.

Like lurker, I also leave the rest as an exercise.

ContentLicense: CC BY-SA 3.0

Title: Transpose matrix in prolog

Body:
I want to transpose a matrix in prolog, so for example
[[1,2,3],[1,2,3],[1,2,3]] should become
[[1,1,1],[2,2,2],[3,3,3]]

Here is what I've done:

%transpose(M,T)
transpose([],[]).
transpose(M,[H|T]):-row(H,M,M1),transpose(M1,T).

%row(H, M, M1).
row([],[],[]).
row([H|Tt] , [[H|T1]|T] , [T1|Z]) :- row(Tt,T,Z).

Where M is to be transposed in T.
Row predicate (not sure for the difference between predicate and function) get the head of each sublist in M, so I can get the entire first row of the new, transposed matrix T.
I tested row separately, and it is giving the proper result. But when I try to transpose, I get only 'false' and nothing happens, no info for the new matrix T is printed.

Can anyone help me? Is the problem in the way I built the program? Or the result I expect is only true/false indeed and if so, how to get the new matrix? Thanks :)

Body:
First, a note on terminology: One characteristic of a function is that each input is related to exactly one output. On the other hand, a relation can hold for multiple such combinations. Prolog predicates induce relations between their arguments, and multiple answers can arise on backtracking.

As to your concrete question, @lurker has already given some solid advice.

However, as you already notice, tracing quickly gets very complex in Prolog, and I would therefore like to complement what lurker has written by explaining a few principles of declarative debugging in Prolog.

In essence, we will aim to make our problem simpler instead of harder. We start with the case you mention for the program you posted:

?- transpose([[1,2,3],[1,2,3],[1,2,3]], Ls).
false.

In logical terms, the relation is too specific: It fails to hold in a case in which it ought to hold.

To find a reason for this problem, we could step through the precise execution details, using a textual or graphical tracer, and try to keep track of all the details. This is extremely hard, so I suggest you first try to find a simpler case that still fails.

I will do this by generalizing the query. There are several ways to do this. For example, instead of concrete integers, I can use fresh variables:

?- transpose([[_,_,_],[_,_,_],[_,_,_]], Ls).
false.

Aha, so we have found a much more general case that still fails. As long as this case fails, the more specific case will definitely also fails, because we are reasoning over a pure and monotonic logic program.

So, the new question is: Why does this more general query fail? To find a reason, we can simply further generalize the query. For example, instead of reasoning about lists with 3 elements each, we can generalize this to the following case, where two of the lists are generalized to "more than one element":

?- transpose([[_|_],[_|_],[_,_,_]], Ls).
false.

We see that this much more general query still fails. We can even generalize it further:

?- transpose([_,_,[_,_,_]], Ls).
false.

This still fails! Note that we can also take it too far. For example:

?- transpose([_,_,_], Ls).
nontermination

Here, we run into a different issue altogether, related to termination properties of the program. However, in our case, we want to find a reason for the unexpected failure, and so we return to the case above:

?- transpose([_,_,[_,_,_]], Ls).
false.

At this point, there is not much more to generalize, so we could now invoke the tracer on this simplified query.

However, we can also continue in a different direction: Not every test case needs to be a generalization. We can also come up with an entirely different case, such as a list with only two (instead of three) elements:

?- transpose([_,[_,_,_]], Ls).
false

Aha, so this also fails, even though it ought to succeed!

What about even simpler cases:

?- transpose([[_,_,_]], Ls).
false.

And further:

?- transpose([[_,_]], Ls).
false.

And even further:

?- transpose([[_]], Ls).
false.

Each of these queries ought to succeed, but fails.

Why?

To find reasons, consider program-slicing of the underlying logic program. For example, let us take one of the simplest queries we found that should succeed, but doesn't: ?- transpose([[_]], _).

I use the following definition to generalize away constraints (= goals) of the original program

:- op(950,fy, *).
*_.

For example, we can generalize row/3 as follows:

row([], [], []).
row([H|Tt], [[H|T1]|T], [T1|Z]) :-
        * <s>row(Tt,T,Z).</s>

Even with this much more general version of row/3, we get:

?- transpose([[_]], Ls).
false.

This means: To make this query succeed, you either have to add additional clauses to your code (to make it more general) or change the remaining fragment.

Like lurker, I also leave the rest as an exercise.

ContentLicense: CC BY-SA 4.0


问:
Java Convert AudioFormat
what I'm trying to do is that I am capturing the audio from microphone via TargetDataLine class, send it with socket and play on another side via SourceDataLine. The problem is that microphone I'm capturing with, only supports:

```<code>AudioFormat format = new AudioFormat(48000, 16, 1, true, true);
</code>```

and the speaker I'm playing it to, supports only:

```<code>AudioFormat format = new AudioFormat(32000, 16, 2, true, true);
</code>```

When I directly get 48khz and push it to 32khz audioformat, the sound is pitched, is there any way to convert the 48khz mono sound to 32khz stereo?

答:
If Java has some built in audio file format conversion, you can learn about it from the "Using Files and Format Converters" post on the audio tutorials thread.

If it has to be done manually, check out the first code example on that page, especially noting the point with the comment

```<code>  // Here, do something useful with the audio data that's
  // now in the audioBytes array...
</code>```

If you run the input and output lines in parallel, you can use linear interpolation to take data from the 48000 line and post to the 32000 line. The ratio is 3:2.

Thus, for 3 PCM data points in the input, calculate 2 PCM data points for the output.

For the input, you would send in[0] to out[0] and the sum of in1/2 and in[2]/2 to out1.

Duplicate the value for converting from mono to stereo.

Title: Java Convert AudioFormat

Body:
what I'm trying to do is that I am capturing the audio from microphone via TargetDataLine class, send it with socket and play on another side via SourceDataLine. The problem is that microphone I'm capturing with, only supports:

AudioFormat format = new AudioFormat(48000, 16, 1, true, true);

and the speaker I'm playing it to, supports only:

AudioFormat format = new AudioFormat(32000, 16, 2, true, true);

When I directly get 48khz and push it to 32khz audioformat, the sound is pitched, is there any way to convert the 48khz mono sound to 32khz stereo?

Body:
If Java has some built in audio file format conversion, you can learn about it from the "Using Files and Format Converters" post on the audio tutorials thread.

If it has to be done manually, check out the first code example on that page, especially noting the point with the comment

  // Here, do something useful with the audio data that's
  // now in the audioBytes array...

If you run the input and output lines in parallel, you can use linear interpolation to take data from the 48000 line and post to the 32000 line. The ratio is 3:2.

Thus, for 3 PCM data points in the input, calculate 2 PCM data points for the output.

For the input, you would send in[0] to out[0] and the sum of in1/2 and in[2]/2 to out1.

Duplicate the value for converting from mono to stereo.


问:
Checking if a Screen of the Specified Name Exists
I have made a bash file which launches another bash file in a detached screen with a unique name, I need to ensure that only one instance of that internal bash file is running at any one point in time. To do this, I want to make the parent bash file check to see if the screen by that name exists before attempting to create it. Is there a method to do this?</p>

答:
%100 Work.</p>

```<code>screen -list | grep "SESSİON NAME" && echo "Active Program" || echo "Passive Program"
</code>```

Body:
%100 Work.

screen -list | grep "SESSİON NAME" && echo "Active Program" || echo "Passive Program"


问:
Whats the easiest way to know if a class is an ActiveRecord class?
So I know that I can do

```<code> Class.new.is_a?(ActiveRecord::Base)
</code>```

Is there a way to know what kind of class it is without instantiating it?  Are there any downsides to instantiating it just to find out the type of class it is?

答:
You can get all ancestors of the Class with Class.ancestors. So what you can do to check the type without instantiating the Class is

```<code>Class.ancestors.include?(ActiveRecord::Base)
</code>```

Body:
So I know that I can do

 Class.new.is_a?(ActiveRecord::Base)

Is there a way to know what kind of class it is without instantiating it?  Are there any downsides to instantiating it just to find out the type of class it is?

Body:
You can get all ancestors of the Class with Class.ancestors. So what you can do to check the type without instantiating the Class is

Class.ancestors.include?(ActiveRecord::Base)


问:
Generating sound on the fly with javascript/html5
Is it possible to generate a constant sound stream with javascript/html5? For example, to generate a perpetual sine wave, I would have a callback function, that would be called whenever the output buffer is about to become empty:

```<code>function getSampleAt(timestep)
{
    return Math.sin(timestep);
}
</code>```

(The idea is to use this to make an interactive synth. I don't know in advance how long a key will be pressed, so I can't use a fixed length buffer)

答:
This is what I have looked for like forever and in the end I managed to do it myself like I wanted. Maybe you will like it too.
Simple slider with frequency and push on/off:

buttonClickResult = function () {
 var button = document.getElementById('btn1');

 button.onclick = function buttonClicked()  {

  if(button.className=="off")  {
   button.className="on";
   oscOn ();
  }

  else if(button.className=="on")  {
   button.className="off";
   oscillator.disconnect();
  }
 }
};

buttonClickResult();

var oscOn = function(){

 window.AudioContext = window.AudioContext || window.webkitAudioContext;
 var context = new AudioContext();
 var gainNode = context.createGain ? context.createGain() : context.createGainNode();

 //context = new window.AudioContext();
 oscillator = context.createOscillator(),
   oscillator.type ='sine';

 oscillator.frequency.value = document.getElementById("fIn").value;
 //gainNode = createGainNode();
 oscillator.connect(gainNode);
 gainNode.connect(context.destination);
 gainNode.gain.value = 1;
 oscillator.start(0);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="texts">Frekvence [Hz]</p>
<input type="range" id="fIn" min="20" max="20000" step="100" value="1234" oninput="show()" />
<span id="fOut"></span><br>
<input class="off" type="button" id="btn1" value="Start / Stop" /></code>```

Body:
Is it possible to generate a constant sound stream with javascript/html5? For example, to generate a perpetual sine wave, I would have a callback function, that would be called whenever the output buffer is about to become empty:

function getSampleAt(timestep)
{
    return Math.sin(timestep);
}

(The idea is to use this to make an interactive synth. I don't know in advance how long a key will be pressed, so I can't use a fixed length buffer)

Body:
This is what I have looked for like forever and in the end I managed to do it myself like I wanted. Maybe you will like it too.
Simple slider with frequency and push on/off:

buttonClickResult = function () {
 var button = document.getElementById('btn1');

 button.onclick = function buttonClicked()  {

  if(button.className=="off")  {
   button.className="on";
   oscOn ();
  }

  else if(button.className=="on")  {
   button.className="off";
   oscillator.disconnect();
  }
 }
};

buttonClickResult();

var oscOn = function(){

 window.AudioContext = window.AudioContext || window.webkitAudioContext;
 var context = new AudioContext();
 var gainNode = context.createGain ? context.createGain() : context.createGainNode();

 //context = new window.AudioContext();
 oscillator = context.createOscillator(),
   oscillator.type ='sine';

 oscillator.frequency.value = document.getElementById("fIn").value;
 //gainNode = createGainNode();
 oscillator.connect(gainNode);
 gainNode.connect(context.destination);
 gainNode.gain.value = 1;
 oscillator.start(0);
};

<p class="texts">Frekvence [Hz]</p>
<input type="range" id="fIn" min="20" max="20000" step="100" value="1234" oninput="show()" />
<span id="fOut"></span><br>
<input class="off" type="button" id="btn1" value="Start / Stop" />


问:
Why is SQL Server casting GETDATE() to an other value than CAST('yyyy-mm-dd')?
I'm working with SQL Server for many years and I think I have a really strange thing here.

When I execute these 2 queries:

```<code>SELECT CAST(CAST('2017-03-28' AS DATETIME) AS INT)

SELECT CAST(GETDATE() AS INT), GETDATE()
</code>```

I get these outputs:

```<code>42820
42821   2017-03-28 20:49:10.360
</code>```

So I'm totally clueless about this; how can 28 march 2017 be cast to 42820 and 28 march 2017 20:49 to 42821?

To make it a little more strange, I've figured out that the point for going 1 higher is 12:00 am. I'm really lost...

Can somebody enlighten me?

答:
casting datetime is rounded from 12:00:00</p>

```<code>SELECT CAST(CAST('2017-03-28 12:00:00' AS DATETIME) AS INT)
SELECT CAST(GETDATE() AS INT), GETDATE()

SELECT CAST(CAST('2017-03-28 11:59:59' AS DATETIME) AS INT)
SELECT CAST(GETDATE() AS INT), GETDATE()
</code>```

Body:
I'm working with SQL Server for many years and I think I have a really strange thing here.

When I execute these 2 queries:

SELECT CAST(CAST('2017-03-28' AS DATETIME) AS INT)

SELECT CAST(GETDATE() AS INT), GETDATE()

I get these outputs:

42820
42821   2017-03-28 20:49:10.360

So I'm totally clueless about this; how can 28 march 2017 be cast to 42820 and 28 march 2017 20:49 to 42821?

To make it a little more strange, I've figured out that the point for going 1 higher is 12:00 am. I'm really lost...

Can somebody enlighten me?

Body:
casting datetime is rounded from 12:00:00

SELECT CAST(CAST('2017-03-28 12:00:00' AS DATETIME) AS INT)
SELECT CAST(GETDATE() AS INT), GETDATE()

SELECT CAST(CAST('2017-03-28 11:59:59' AS DATETIME) AS INT)
SELECT CAST(GETDATE() AS INT), GETDATE()


问:
Using Google Admin to view Drive files Domain-wide
I'm trying to list all Google Drive files Domain-wide, both users that still work here, and those that have moved on. With that, we can grep the output for certain terms (former customers) to delete customer-related files.

I believe I have a successful way to list all users using the Admin SDK Quickstart, since we have only about 200 total users (max is 500). I also have a way to list all files for a user using the Drive REST API's files.list() method. What I need to know is how to impersonate each user iteratively, in order to run the file listing script.

I have found the blurb .setServiceAccountUser(someone@domain.com) but I'm not really sure where to implement this, either in the service account authorization step, or in a separate middle-man script.

答:
Have a look at https://github.com/pinoyyid/googleDriveTransferOwnership/blob/master/src/couk/cleverthinking/tof/Main.java

Specifically lines 285-299 which deal with generating a credential for an impersonated user.

```<code>   GoogleCredential.Builder builder = new GoogleCredential.Builder()
                .setTransport(HTTP_TRANSPORT)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(serviceAccountEmailAddress)
                .setServiceAccountPrivateKeyFromP12File(f)
                .setServiceAccountScopes(Collections.singleton(SCOPE));
        // if requested, impresonate a domain user
        if (!"ServiceAccount".equals(impersonatedAccountEmailAddress)) {
            builder.setServiceAccountUser(impersonatedAccountEmailAddress);
        }

        // build the Drive service
        Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, null)
                .setApplicationName("TOF")
                .setHttpRequestInitializer(builder.build()).build();
</code>```

This is Java, but should at least tell you what the steps are.

Body:
Have a look at https://github.com/pinoyyid/googleDriveTransferOwnership/blob/master/src/couk/cleverthinking/tof/Main.java

Specifically lines 285-299 which deal with generating a credential for an impersonated user.

   GoogleCredential.Builder builder = new GoogleCredential.Builder()
                .setTransport(HTTP_TRANSPORT)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(serviceAccountEmailAddress)
                .setServiceAccountPrivateKeyFromP12File(f)
                .setServiceAccountScopes(Collections.singleton(SCOPE));
        // if requested, impresonate a domain user
        if (!"ServiceAccount".equals(impersonatedAccountEmailAddress)) {
            builder.setServiceAccountUser(impersonatedAccountEmailAddress);
        }

        // build the Drive service
        Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, null)
                .setApplicationName("TOF")
                .setHttpRequestInitializer(builder.build()).build();

This is Java, but should at least tell you what the steps are.


问:
Angular 2 Expression has changed after it was checked. Error with Dynamic Image Src
I have a loop that creates a list of events.

```<code><ng-container *ngFor="let event of venueEvents">
    <div class="event-card">
        <div class="event-image">
            <img src={{getRandomImage()}}>
        </div>
        <div class="event-details">
            <p class="event-title">{{event.name}}</p>
            <p class="event-time">{{event.nextOccursOn | date}}</p>
        </div>
    </div>
</ng-container>
</code>```

As you can see the image is a dynamic image that is populated with a function.

```<code>getRandomImage() {
    let baseImageLink = "http://lorempixel.com/640/480/",
        linkKey = {
            '1': 'nature',
            '2': 'sports',
            '3': 'cat',
            '4': 'nightlife',
            '5': 'food'
        },
        randomNumber = Math.floor((Math.random() * 5) + 1);
    return baseImageLink + linkKey[randomNumber];
}
</code>```

This is working as expected, but the console shows an error.

```<code> EXCEPTION: Error in ./VenueDetailComponent class VenueDetailComponent - inline template:64:21 caused by: Expression has changed after it was checked. Previous value: 'http://lorempixel.com/640/480/sports'. Current value: 'http://lorempixel.com/640/480/cat'.
</code>```

This is some temporary function that would never exist in the real application, but I would like to understand the problem and know how it should be solved.

答:
You get that error because you bind a method to a view that returns a different value each time its called

```<code> <img src={{getRandomImage()}}>
</code>```

Every time Angular runs change detection getRandomImage() is called, and every time a different value is returned.

You should generate the values, store them in an array and than bind to the array instead of the method directly.

Body:
I have a loop that creates a list of events.

<ng-container *ngFor="let event of venueEvents">

{{event.name}}

{{event.nextOccursOn | date}}

</ng-container>

As you can see the image is a dynamic image that is populated with a function.

getRandomImage() {
    let baseImageLink = "http://lorempixel.com/640/480/",
        linkKey = {
            '1': 'nature',
            '2': 'sports',
            '3': 'cat',
            '4': 'nightlife',
            '5': 'food'
        },
        randomNumber = Math.floor((Math.random() * 5) + 1);
    return baseImageLink + linkKey[randomNumber];
}

This is working as expected, but the console shows an error.

 EXCEPTION: Error in ./VenueDetailComponent class VenueDetailComponent - inline template:64:21 caused by: Expression has changed after it was checked. Previous value: 'http://lorempixel.com/640/480/sports'. Current value: 'http://lorempixel.com/640/480/cat'.

This is some temporary function that would never exist in the real application, but I would like to understand the problem and know how it should be solved.

Body:
You get that error because you bind a method to a view that returns a different value each time its called

 <img src={{getRandomImage()}}>

Every time Angular runs change detection getRandomImage() is called, and every time a different value is returned.

You should generate the values, store them in an array and than bind to the array instead of the method directly.


答:
That is an interesting feature... You can get around it by casting to float first though.

```<code>select cast(cast('20170328' as datetime) as int)

select convert(int,convert(float,getdate()))
</code>```

rextester demo: http://rextester.com/YVXUJ72002

Both return 42820

Title: Why is SQL Server casting GETDATE() to an other value than CAST('yyyy-mm-dd')?

Body:
That is an interesting feature... You can get around it by casting to float first though.

select cast(cast('20170328' as datetime) as int)

select convert(int,convert(float,getdate()))

rextester demo: http://rextester.com/YVXUJ72002

Both return 42820


问:
Unpivot in Google Sheets - multipe header columns and rows
I have a summary table with about 20 columns and up to a hundred of rows, however I would like to convert it into a flat list so I can import to a database.

This solution is not working properly in my case and my knowledge of JS is far beneath the ability to adjust it properly.

There're three tabs in the Example sheet:

Source Data - dummy data of what I currently have

Desired Result - what I want to convert Source Data to

What I Get - result I get when using the solution mentioned above

Sheet is shared, so you can try and test the script (Menu > Script > Run). It would create a new tab automatically.

答:
I think you can use CONCAT to get a unique row key from location and region and use the method from my answer here which doesn't require extra scripts.

If you do something fancy with the key concatenation (e.g. CONCAT(A3, "~", A4)), you can even extract your original location and region in the unpivot table (e.g. REGEXEXTRACT(A1, "(\w+)~") and REGEXEXTRACT(A1, "~(\w+)")).


问:
Openshift - Execution of post execute step failed
I have node.js app and during the deployment after installing dependencies the following error had occured:

```<code>error: Execution of post execute step failed
warning: Failed to remove container "a167df5e218c392e42ec772d5c22311f88043ff99c71ce1a08e7af535ac3817b": Error response from daemon: {"message":"Driver devicemapper failed to remove root filesystem a167df5e218c392e42ec772d5c22311f88043ff99c71ce1a08e7af535ac3817b: Device is Busy"}
error: build error: building my-pokus/hello-seattle-2:d4b8ecde failed when committing the image due to error: Cannot connect to the Docker daemon. Is the docker daemon running on this host?
</code>```

答:
The problem is that your image is too big, if the commit is longer than 2mins, this error happens.

I found a workaround here : github origin 13515

Shrink your Docker Image :)

Use a more recent S2I-Builder:

In order to temporarily use another version of the docker image, the
  easiest way seems to be to simply pull the new image and tag it as the
  one used by openshift:

```<code>docker pull docker.io/openshift/origin-sti-builder:v1.5.0-rc.0
docker tag docker.io/openshift/origin-sti-builder:v1.5.0-rc.0 docker.io/openshift/origin-sti-builder:v1.4.1
</code>```

Body:
I have node.js app and during the deployment after installing dependencies the following error had occured:

error: Execution of post execute step failed
warning: Failed to remove container "a167df5e218c392e42ec772d5c22311f88043ff99c71ce1a08e7af535ac3817b": Error response from daemon: {"message":"Driver devicemapper failed to remove root filesystem a167df5e218c392e42ec772d5c22311f88043ff99c71ce1a08e7af535ac3817b: Device is Busy"}
error: build error: building my-pokus/hello-seattle-2:d4b8ecde failed when committing the image due to error: Cannot connect to the Docker daemon. Is the docker daemon running on this host?

Body:
The problem is that your image is too big, if the commit is longer than 2mins, this error happens.

I found a workaround here : github origin 13515

Shrink your Docker Image :)

Use a more recent S2I-Builder:

In order to temporarily use another version of the docker image, the
  easiest way seems to be to simply pull the new image and tag it as the
  one used by openshift:

docker pull docker.io/openshift/origin-sti-builder:v1.5.0-rc.0
docker tag docker.io/openshift/origin-sti-builder:v1.5.0-rc.0 docker.io/openshift/origin-sti-builder:v1.4.1


问:
Executing R script within R 3.3.1 installed on windows
Sorry for a basic question. I'm trying run a R script called cuffdiff_gtf_attributes (please find it at enter link description here in R 3.3.1 installed on the Windows 7. The script is started with the below line:

```<code>#!/usr/bin/env Rscript
</code>```

When I type cuffdiff_gtf_attributes in R, it says Error: object 'cuffdiff_gtf_attributes' not found. Also, I tried Rscript cuffdiff_gtf_attributes that returned me: Error: unexpected symbol in "Rscript cuffdiff_gtf_attributes".
Moreover, I tried source('cuffdiff_gtf_attributes.R')that seems to work and returned the usage of the script as bellow

```<code>Error:
 usage: cuffdiff_gtf_attributes --input=<inputGTF> [--output=outputGTF] | --help
</code>```

But, when I add the arguments as source('cuffdiff_gtf_attributes.R') --input=file.gtf, it says that: Error: object 'file.gtf' not found. I also tried this command as source('cuffdiff_gtf_attributes.R') --input file.gtf, it says that Error: unexpected symbol in "source('cuffdiff_gtf_attributes.R') --input file.gtf"

Sorry, I couldn't post a sample GTF file, you can find a short sample of it at enter link description here

Everything is the current path. Could you please help me out to execute the script?

Thanks in advance

答:
This is a script file. You should run using Rscript instead for Rgui.exe. From a command prompt, navigate to the directory where file.gtf is and run:</p>

```<code>"%Programfiles%\R\R-3.3.3\bin\Rscript" cuffdiff_gtf_attributes.R --input=file.gtf
</code>```

Body:
Sorry for a basic question. I'm trying run a R script called cuffdiff_gtf_attributes (please find it at enter link description here in R 3.3.1 installed on the Windows 7. The script is started with the below line:

#!/usr/bin/env Rscript

When I type cuffdiff_gtf_attributes in R, it says Error: object 'cuffdiff_gtf_attributes' not found. Also, I tried Rscript cuffdiff_gtf_attributes that returned me: Error: unexpected symbol in "Rscript cuffdiff_gtf_attributes".
Moreover, I tried source('cuffdiff_gtf_attributes.R')that seems to work and returned the usage of the script as bellow

Error:
 usage: cuffdiff_gtf_attributes --input=<inputGTF> [--output=outputGTF] | --help

But, when I add the arguments as source('cuffdiff_gtf_attributes.R') --input=file.gtf, it says that: Error: object 'file.gtf' not found. I also tried this command as source('cuffdiff_gtf_attributes.R') --input file.gtf, it says that Error: unexpected symbol in "source('cuffdiff_gtf_attributes.R') --input file.gtf"

Sorry, I couldn't post a sample GTF file, you can find a short sample of it at enter link description here

Everything is the current path. Could you please help me out to execute the script?

Thanks in advance

Body:
This is a script file. You should run using Rscript instead for Rgui.exe. From a command prompt, navigate to the directory where file.gtf is and run:

"%Programfiles%\R\R-3.3.3\bin\Rscript" cuffdiff_gtf_attributes.R --input=file.gtf


问:
recipe for working with compressed (any)dbm files in python
I have a big-ol' dbm file, that's being created and used by my python program. It saves a good amount of RAM, but it's getting big,  and I suspect I'll have to gzip it soon to lower the footprint.

I guess usage will involve un-gzipping it to the disk, using it, and erasing the extracted dbm when I'm done.

I was wondering whether there perhaps exists some nice way of compressing the dbm and keep working with it somehow. In my spcific usecase, I only need to read from it.

Thanks.

答: You can gzip the value or use a key/value store that support compression like wiredtiger.</p>


问:
Is it possible to use Java 8 Streams API for asynchronous processing?
I've been playing with CompletionStage/CompletableFuture in Java 8 in order to do asynchronous processing, which works quite well. However, sometimes I want a stage to perform asynchronous processing of an iterator/stream of items, and there doesn't seem to be a way to do this.

Specifically, Stream.forEach() has the semantics that after the call all items have been processed. I would want the same thing, but with a CompletionStage instead, e.g.:

```<code>CompletionStage<Void> done = stream.forEach(...);
done.thenRun(...);
</code>```

If the Stream is backed by an asynchronous streaming result this would be much better than waiting for it to be complete in the above code itself.

Is it possible to construct this with current Java 8 API somehow? Workarounds?

答:
It is possible to produce a stream, map each element to CompletionStage, and collect the results using CompletionStage.thenCombine(), but the resulting code will not be more readable then using simple for like this.

```<code>    CompletionStage<Collection<Result>> collectionStage =
        CompletableFuture.completedFuture(
            new LinkedList<>()
        );

    for (Request request : requests) {
        CompletionStage<Result> resultStage = performRequest(request);
        collectionStage = collectionStage.thenCombine(
            resultStage,
            (collection, result) -> {
                collection.add(result);
                return collection;
            }
        );
    }

    return collectionStage;
</code>```

This example may be easily transformed to functional forEach not loosing readability. But using stream's reduce or collect requires additional not so fine code.

Update: CompletableFuture.allOf and CompletableFuture.join provide another, more readable way of transforming collection of future results to future collection of results.

Body:
I've been playing with CompletionStage/CompletableFuture in Java 8 in order to do asynchronous processing, which works quite well. However, sometimes I want a stage to perform asynchronous processing of an iterator/stream of items, and there doesn't seem to be a way to do this.

Specifically, Stream.forEach() has the semantics that after the call all items have been processed. I would want the same thing, but with a CompletionStage instead, e.g.:

CompletionStage<Void> done = stream.forEach(...);
done.thenRun(...);

If the Stream is backed by an asynchronous streaming result this would be much better than waiting for it to be complete in the above code itself.

Is it possible to construct this with current Java 8 API somehow? Workarounds?

Body:
It is possible to produce a stream, map each element to CompletionStage, and collect the results using CompletionStage.thenCombine(), but the resulting code will not be more readable then using simple for like this.

    CompletionStage<Collection<Result>> collectionStage =
        CompletableFuture.completedFuture(
            new LinkedList<>()
        );

    for (Request request : requests) {
        CompletionStage<Result> resultStage = performRequest(request);
        collectionStage = collectionStage.thenCombine(
            resultStage,
            (collection, result) -> {
                collection.add(result);
                return collection;
            }
        );
    }

    return collectionStage;

This example may be easily transformed to functional forEach not loosing readability. But using stream's reduce or collect requires additional not so fine code.

Update: CompletableFuture.allOf and CompletableFuture.join provide another, more readable way of transforming collection of future results to future collection of results.


问:
Bash count lines and pipe into less info
Im strugling to get the info i want, we are using a spamfilter which can be monitored thru API calls.

We use PRTG as our monitoring, PRTG is calling a Bash script which calls the API using curl.

The info i need to work with is called by this line.

```<code>queue=$(curl -u USER:PASS -X GET -H "Content-Type: application/http" https://mx10.mailfilter.nl/cgi-bin/api?call=api_delivery_queue&sort_field=domain,server)

OUTPUT:(lines below the domain are associated with te domain)
domain1.TLD
mx10.mailfilter.nl,1csiOn-00012P-QL,2017-03-28 21:08:29
mx20.mailfilter.nl,1csLqx-0004fO-EM,2017-03-28 21:08:29
domain2.TLD
mx10.mailfilter.nl,1csvTq-0007a4-MS,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvhh-0000gI-5s,2017-03-28 21:08:29
mx10.mailfilter.nl,1cswCX-0004bQ-Iz,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvk3-00013I-Rx,2017-03-28 21:08:29
domain3.TLD
mx10.mailfilter.nl,1csbxg-0005sG-Px,2017-03-28 21:08:29
</code>```

I need to break this down to: (where the number is the count of lines associated with the domain)
Expected Output :

```<code>domain1.TLD 2
domain2.TLD 4
domain3.TLD 1

totalcount=$(curl -u USER:PASS -X GET -H "Content-Type: application/http" https://mx10.mailfilter.nl/cgi-bin/api?call=api_get_delivery_queue_count&domain=default)
</code>```

Which at the end echos 0:$totalcount:$queue

EDIT:(29-03)

My example might be not as clear as i ment it to be :)

domain1.TLD
domain2.TLD
..
Are just some examples the variantion of domains is enormous. From a to z. The lines that are static start with mx10 or mx20.

The command from Vipin might do the trick i will try that one tomorrow.

答:
Try this -

```<code>$ cat f
domain1.TLD
mx10.mailfilter.nl,1csiOn-00012P-QL,2017-03-28 21:08:29
mx20.mailfilter.nl,1csLqx-0004fO-EM,2017-03-28 21:08:29
domain2.TLD
mx10.mailfilter.nl,1csvTq-0007a4-MS,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvhh-0000gI-5s,2017-03-28 21:08:29
mx10.mailfilter.nl,1cswCX-0004bQ-Iz,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvk3-00013I-Rx,2017-03-28 21:08:29
domain3.TLD
mx10.mailfilter.nl,1csbxg-0005sG-Px,2017-03-28 21:08:29
</code>```

```<code>$ awk -F,  'NF==1 {h=$0} {(NF==1?k=1:t[h]=k++)} END {for (h in t) print h,t[h]}' f
domain2.TLD 4
domain1.TLD 2
domain3.TLD 1
</code>```

In sorted order -

```<code>awk -F,  'NF==1 {h=$0} {(NF==1?k=1:t[h]=k++)} END {
> PROCINFO["sorted_in"] = "@ind_str_asc"
> for (h in t) print h,t[h]}' f
domain1.TLD 2
domain2.TLD 4
domain3.TLD 1
</code>```

Body:
Im strugling to get the info i want, we are using a spamfilter which can be monitored thru API calls.

We use PRTG as our monitoring, PRTG is calling a Bash script which calls the API using curl.

The info i need to work with is called by this line.

queue=$(curl -u USER:PASS -X GET -H "Content-Type: application/http" https://mx10.mailfilter.nl/cgi-bin/api?call=api_delivery_queue&sort_field=domain,server)

OUTPUT:(lines below the domain are associated with te domain)
domain1.TLD
mx10.mailfilter.nl,1csiOn-00012P-QL,2017-03-28 21:08:29
mx20.mailfilter.nl,1csLqx-0004fO-EM,2017-03-28 21:08:29
domain2.TLD
mx10.mailfilter.nl,1csvTq-0007a4-MS,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvhh-0000gI-5s,2017-03-28 21:08:29
mx10.mailfilter.nl,1cswCX-0004bQ-Iz,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvk3-00013I-Rx,2017-03-28 21:08:29
domain3.TLD
mx10.mailfilter.nl,1csbxg-0005sG-Px,2017-03-28 21:08:29

I need to break this down to: (where the number is the count of lines associated with the domain)
Expected Output :

domain1.TLD 2
domain2.TLD 4
domain3.TLD 1

totalcount=$(curl -u USER:PASS -X GET -H "Content-Type: application/http" https://mx10.mailfilter.nl/cgi-bin/api?call=api_get_delivery_queue_count&domain=default)

Which at the end echos 0:$totalcount:$queue

EDIT:(29-03)

My example might be not as clear as i ment it to be :)

domain1.TLD
domain2.TLD
..
Are just some examples the variantion of domains is enormous. From a to z. The lines that are static start with mx10 or mx20.

The command from Vipin might do the trick i will try that one tomorrow.

Body:
Try this -

$ cat f
domain1.TLD
mx10.mailfilter.nl,1csiOn-00012P-QL,2017-03-28 21:08:29
mx20.mailfilter.nl,1csLqx-0004fO-EM,2017-03-28 21:08:29
domain2.TLD
mx10.mailfilter.nl,1csvTq-0007a4-MS,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvhh-0000gI-5s,2017-03-28 21:08:29
mx10.mailfilter.nl,1cswCX-0004bQ-Iz,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvk3-00013I-Rx,2017-03-28 21:08:29
domain3.TLD
mx10.mailfilter.nl,1csbxg-0005sG-Px,2017-03-28 21:08:29

$ awk -F,  'NF==1 {h=$0} {(NF==1?k=1:t[h]=k++)} END {for (h in t) print h,t[h]}' f
domain2.TLD 4
domain1.TLD 2
domain3.TLD 1

In sorted order -

awk -F,  'NF==1 {h=$0} {(NF==1?k=1:t[h]=k++)} END {
> PROCINFO["sorted_in"] = "@ind_str_asc"
> for (h in t) print h,t[h]}' f
domain1.TLD 2
domain2.TLD 4
domain3.TLD 1


问:
Averaging floating value in assembly
I have to get average. In C++ since I don't pass it the length of the array
I don't   know how to divide it by that.

Here's how I'm passing my values in C++

```<code>extern "C" double Average (long [6]);

        _Average proc

        finit
        mov  ecx, 6  ; number of elements
        mov  ebx, [esp + 4] ; address of the array
        fldz

   L1:
        fld REAL4 PTR [ebx]  ; get elements of array
        fadd
        add ebx, 4

        loop L1
        fdiv DWORD PTR [esp + 4]

        fwait

        ret

       _Average endp
</code>```

答: Then pass the length. Or, since it's a fixed-sized array of length 6, just assume it's 6.</p>

ContentLicense: CC BY-SA 2.5

Title: Averaging floating value in assembly

Body:
I have to get average. In C++ since I don't pass it the length of the array
I don't   know how to divide it by that.

Here's how I'm passing my values in C++

extern "C" double Average (long [6]);

        _Average proc

        finit
        mov  ecx, 6  ; number of elements
        mov  ebx, [esp + 4] ; address of the array
        fldz

   L1:
        fld REAL4 PTR [ebx]  ; get elements of array
        fadd
        add ebx, 4

        loop L1
        fdiv DWORD PTR [esp + 4]

        fwait

        ret

       _Average endp


问:
Android Drawable XML Code For Text Select Handle
I am trying to find the XML code to create a TextSelectHandle. I created three xml files in my drawable folder text_select_handle_middle, text_select_handle_left, and text_select_handle_right. I also added those files to my Style.xml file.

I haven't found any code online that shows how to create the new round text select handlers for android 6.0 marshmallow. Changing the color of the text select handle is my primary reason for wanting to do this.

I also saw a post that linked this website Android Holo Colors Generator but it didn't have anything on the new round text select handlers.

Style.xml

```<code><item name="android:textSelectHandle">@drawable/text_select_handle_middle</item>
<item name="android:textSelectHandleLeft">@drawable/text_select_handle_left</item>
<item name="android:textSelectHandleRight">@drawable/text_select_handle_right</item>
</code>```

答:
In values\styles.xml you should change

```<code><item name="colorAccent">@color/md_red_100</item>
</code>```

for the color you want, so you do not have to redraw text select handler

Body:
I am trying to find the XML code to create a TextSelectHandle. I created three xml files in my drawable folder text_select_handle_middle, text_select_handle_left, and text_select_handle_right. I also added those files to my Style.xml file.

I haven't found any code online that shows how to create the new round text select handlers for android 6.0 marshmallow. Changing the color of the text select handle is my primary reason for wanting to do this.

I also saw a post that linked this website Android Holo Colors Generator but it didn't have anything on the new round text select handlers.

Style.xml

<item name="android:textSelectHandle">@drawable/text_select_handle_middle</item>
<item name="android:textSelectHandleLeft">@drawable/text_select_handle_left</item>
<item name="android:textSelectHandleRight">@drawable/text_select_handle_right</item>

Body:
In values\styles.xml you should change

<item name="colorAccent">@color/md_red_100</item>

for the color you want, so you do not have to redraw text select handler


问:
macos nginx configuration file deos not exists
I have install nginx to macOS Sierra with Homebrew

```<code>brew install nginx
</code>```

I would like to change some configuration, but I could not find nginx.conf

I have already check following locations.

/usr/local/etc/nginx/nginx.conf

    /usr/local/Cellar/nginx/1.10.3

Where is nginx.conf located in macOS Sierra?

答:
I have found the answer.

run the following command

```<code>nginx -V
</code>```

it will list all configuration arguments. nginx.conf location is mentioned at --conf-path argument.

```<code>--conf-path:~/brew/etc/nginx/nginx.conf
</code>```

Body:
I have install nginx to macOS Sierra with Homebrew

brew install nginx

I would like to change some configuration, but I could not find nginx.conf

I have already check following locations.

/usr/local/etc/nginx/nginx.conf

    /usr/local/Cellar/nginx/1.10.3

Where is nginx.conf located in macOS Sierra?

Body:
I have found the answer.

run the following command

nginx -V

it will list all configuration arguments. nginx.conf location is mentioned at --conf-path argument.

--conf-path:~/brew/etc/nginx/nginx.conf


问:
How does the data structure for a lexical analysis look?
I know the lexical analyser tokenizes the input and stores it in a stream, or at least that is what I understood. Unfortunately nearly all articles I have read only talk about lexing simple expressions. What I am interested in is how to tokenize something like:

```<code>if (fooBar > 5) {
  for (var i = 0; i < alot.length; i++) {
    fooBar += 2 + i;
  }
}
</code>```

Please note that this is pseudo code.

Question: I would like to know how the data structure looks like for tokens created by the lexer? I really have no idea for the example i gave above where code is nested. Some example would be nice.

答:
First of all, tokens are not necessarily stored. Some compilers do store the tokens in a table or other data structure, but for a simple compiler (if there is such a thing) it's sufficient in most cases that the lexer can return the type of the next token to be parsed and then in some cases the parser might ask the lexer for the actual text that the token is made up of.

If we use your sample code,

```<code>if (fooBar > 5) {
  for (var i = 0; i < alot.length; i++) {
    fooBar += 2 + i;
  }
}
</code>```

The type of the first token in this sample might be defined as TOK_IF corresponding to the "if" keyword. The next token might be TOK_LPAREN, then TOK_IDENT, then TOK_GREATER, then TOK_INT_LITERAL, and so on. What exactly the types should be is defined by you as the author of the lexer (or tokenizer) code. (Note that there are about a million different tools to help you avoid the somewhat tedious task of coming up with these details by hand.)

Except for TOK_IDENT and TOK_INT_LITERAL the tokens we've seen so far are defined entirely by their type. For these two, we would need to be able to ask the lexer for the underlying text so that we can evaluate the value of the token.

So a tiny excerpt of the parser dealing with an IF statement in pseudo-code might look something like:

```<code>...
  switch(lexer.GetNextTokenType())
  case TOK_IF:
    {
      // "if" statement
      if (lexer.GetNextTokenType() != TOK_LPAREN)
        throw SyntaxError('( expected');
      ParseRelationalExpression(lexer);
      if (lexer.GetNextTokenType() != TOK_RPAREN)
        throw SyntaxError(') expected');
      ...
</code>```

and so on.

If the compiler did choose to actually store the tokens for later reference, and some compilers do e.g. to allow for more efficient backtracking, one way would be to use a structure similar to the following

```<code>struct {
  int TokenType;
  char* TokenStart;
  int TokenLength;
}
</code>```

The container for these might be a linked list or std::vector (assuming C++).

Body:
I know the lexical analyser tokenizes the input and stores it in a stream, or at least that is what I understood. Unfortunately nearly all articles I have read only talk about lexing simple expressions. What I am interested in is how to tokenize something like:

if (fooBar > 5) {
  for (var i = 0; i < alot.length; i++) {
    fooBar += 2 + i;
  }
}

Please note that this is pseudo code.

Question: I would like to know how the data structure looks like for tokens created by the lexer? I really have no idea for the example i gave above where code is nested. Some example would be nice.

Body:
First of all, tokens are not necessarily stored. Some compilers do store the tokens in a table or other data structure, but for a simple compiler (if there is such a thing) it's sufficient in most cases that the lexer can return the type of the next token to be parsed and then in some cases the parser might ask the lexer for the actual text that the token is made up of.

If we use your sample code,

if (fooBar > 5) {
  for (var i = 0; i < alot.length; i++) {
    fooBar += 2 + i;
  }
}

The type of the first token in this sample might be defined as TOK_IF corresponding to the "if" keyword. The next token might be TOK_LPAREN, then TOK_IDENT, then TOK_GREATER, then TOK_INT_LITERAL, and so on. What exactly the types should be is defined by you as the author of the lexer (or tokenizer) code. (Note that there are about a million different tools to help you avoid the somewhat tedious task of coming up with these details by hand.)

Except for TOK_IDENT and TOK_INT_LITERAL the tokens we've seen so far are defined entirely by their type. For these two, we would need to be able to ask the lexer for the underlying text so that we can evaluate the value of the token.

So a tiny excerpt of the parser dealing with an IF statement in pseudo-code might look something like:

...
  switch(lexer.GetNextTokenType())
  case TOK_IF:
    {
      // "if" statement
      if (lexer.GetNextTokenType() != TOK_LPAREN)
        throw SyntaxError('( expected');
      ParseRelationalExpression(lexer);
      if (lexer.GetNextTokenType() != TOK_RPAREN)
        throw SyntaxError(') expected');
      ...

and so on.

If the compiler did choose to actually store the tokens for later reference, and some compilers do e.g. to allow for more efficient backtracking, one way would be to use a structure similar to the following

struct {
  int TokenType;
  char* TokenStart;
  int TokenLength;
}

The container for these might be a linked list or std::vector (assuming C++).


问:
How do I extend the margin at the bottom of a figure in Matplotlib?
The following screenshot shows my x-axis.

I added some labels and rotated them by 90 degrees in order to better read them. However, pyplot truncates the bottom such that I'm not able to completely read the labels.
How do I extend the bottom margin in order to see the complete labels?

答:
A quick one-line solution that has worked for me is to use pyplot's auto tight_layout method directly, available in Matplotlib v1.1 onwards:

```<code>plt.tight_layout()
</code>```

This can be invoked immediately before you show the plot (plt.show()), but after your manipulations on the axes (e.g. ticklabel rotations, etc).

This convenience method avoids manipulating individual figures of subplots.

Where plt is the standard pyplot from:
import matplotlib.pyplot as plt

Body:
A quick one-line solution that has worked for me is to use pyplot's auto tight_layout method directly, available in Matplotlib v1.1 onwards:

plt.tight_layout()

This can be invoked immediately before you show the plot (plt.show()), but after your manipulations on the axes (e.g. ticklabel rotations, etc).

This convenience method avoids manipulating individual figures of subplots.

Where plt is the standard pyplot from:
import matplotlib.pyplot as plt


问:
Delete all elements with same value from doubly circular linked list
I have doubly circular linked list

```<code>struct Element {
    int data;
    Element *next;
    Element *previous;
};

struct List {
    Element *head;
};
</code>```

The task is to delete elements/nodes with the same data. For example, if the list has 1,1,3,4,5,1 and after parsing the function value=1 it should be as following 3,4,5.

```<code>bool removeAllValue(List &l, int value) {
    if(!l.head)
        return false;
    else if(l.head->next == l.head && l.head->data == value){
        l.head = NULL;
        return true;
    }
    Element *p = l.head;
    do{
        if(p->data == value)
            removeElement(l, p);
        p = p->next;
    }while(p!=l.head);
    return true;
</code>```

Above is function which itterates through elements, finds element with given value/data and calls the following function to delete element.

```<code>void removeElement(List &l, Element *element){
    Element *previous = element->previous;
    Element *next = element->next;
    Element *head = l.head;
    if(next == head){ //if element is tail of the list
        l.head->previous = element->previous; // relinking head's previous to new tail
        element->previous->next = head;
    }else if(element == head){ // if element is head of the list
        l.head = next; // relinking head to tail
        l.head->previous = previous; // relinking tail to head
    }else{
        previous->next = next;
        next->previous = previous;
    }
    delete element;

}
</code>```

I have tried different ways but it always gave me errors. The problem is in relinking tail and head, as I think but I can't find the way to fix it.

答:
The problem was in few relinking operations

```<code>void removeElement(List &l, Element *element){
    Element *previous = element->previous;
    Element *next = element->next;
    Element *head = l.head;
    if(element->next == element)
        l.head = NULL;
    else if(next == head){ //if element is tail of the list
        Element *newTail = previous;
        newTail->next = l.head;
        l.head->previous = newTail;
    }else if(element == head){ // if element is head of the list
        l.head = next; // relinking head
        l.head->previous = previous; // relinking tail to head
        previous->next = l.head; // relinking head to tail
    }else{
        previous->next = next;
        next->previous = previous;
    }
    delete element;
}
</code>```

And as Marek Fekete noticed I didn't change iterating pointer each time I deleted an element. So I just iterated through all list from the beginning, each time I deleted an element.

```<code>bool removeAllValue(List &l, int value) {
    if(!l.head)
        return false;
    else if(l.head->next == l.head && l.head->data == value){
        l.head = NULL;
        return true;
    }
    Element *p = l.head;
    bool end = false;
    while(!end){
        do{
            if(p->data == value){
                Element *tmp = p;
                p = p->next;
                removeElement(l, tmp);
                break;
            }else
                p = p->next;
            if(p==l.head || l.head == NULL){
                end = true;
                break;
            }
        }while(p);
    }
    return true;
}
</code>```

Body:
I have doubly circular linked list

struct Element {
    int data;
    Element *next;
    Element *previous;
};

struct List {
    Element *head;
};

The task is to delete elements/nodes with the same data. For example, if the list has 1,1,3,4,5,1 and after parsing the function value=1 it should be as following 3,4,5.

bool removeAllValue(List &l, int value) {
    if(!l.head)
        return false;
    else if(l.head->next == l.head && l.head->data == value){
        l.head = NULL;
        return true;
    }
    Element *p = l.head;
    do{
        if(p->data == value)
            removeElement(l, p);
        p = p->next;
    }while(p!=l.head);
    return true;

Above is function which itterates through elements, finds element with given value/data and calls the following function to delete element.

void removeElement(List &l, Element *element){
    Element *previous = element->previous;
    Element *next = element->next;
    Element *head = l.head;
    if(next == head){ //if element is tail of the list
        l.head->previous = element->previous; // relinking head's previous to new tail
        element->previous->next = head;
    }else if(element == head){ // if element is head of the list
        l.head = next; // relinking head to tail
        l.head->previous = previous; // relinking tail to head
    }else{
        previous->next = next;
        next->previous = previous;
    }
    delete element;

}

I have tried different ways but it always gave me errors. The problem is in relinking tail and head, as I think but I can't find the way to fix it.

Body:
The problem was in few relinking operations

void removeElement(List &l, Element *element){
    Element *previous = element->previous;
    Element *next = element->next;
    Element *head = l.head;
    if(element->next == element)
        l.head = NULL;
    else if(next == head){ //if element is tail of the list
        Element *newTail = previous;
        newTail->next = l.head;
        l.head->previous = newTail;
    }else if(element == head){ // if element is head of the list
        l.head = next; // relinking head
        l.head->previous = previous; // relinking tail to head
        previous->next = l.head; // relinking head to tail
    }else{
        previous->next = next;
        next->previous = previous;
    }
    delete element;
}

And as Marek Fekete noticed I didn't change iterating pointer each time I deleted an element. So I just iterated through all list from the beginning, each time I deleted an element.

bool removeAllValue(List &l, int value) {
    if(!l.head)
        return false;
    else if(l.head->next == l.head && l.head->data == value){
        l.head = NULL;
        return true;
    }
    Element *p = l.head;
    bool end = false;
    while(!end){
        do{
            if(p->data == value){
                Element *tmp = p;
                p = p->next;
                removeElement(l, tmp);
                break;
            }else
                p = p->next;
            if(p==l.head || l.head == NULL){
                end = true;
                break;
            }
        }while(p);
    }
    return true;
}


问:
How can I make a Text View change it's position based on what the user puts in the Text View above?
I have a simple layout filled with 4 TextView's, 2 of which are pre-filled with text, as number 1 and 3 from top. The two other are filled in based on witch ListItem the user taps. They are filled with different lengths of text, so the majority of times, the texts overlap.

How can I make number 3 and 4 position themselves further down on the screen, if the texts overlap?

Code is attached below:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/imageView2"
android:layout_centerHorizontal="true">

    <ImageView
        android:id="@+id/bildeAvGjenstand"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:contentDescription="@string/bildeBesk"
        android:layout_marginBottom="133dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="THIS IS PREFILLED"
        android:textSize="35sp"
        android:layout_above="@+id/gjenstand"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:id="@+id/gjenstand"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textSize="30sp"
        android:visibility="visible"
        android:layout_above="@+id/bildeAvGjenstand"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="24dp" />

    <TextView
        android:id="@+id/gjoremaal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text=""   <!-- I want this text view to change position -->
        android:visibility="visible"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView3" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"  <!-- I want this text view to change position -->
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:text="THIS IS PREFILLED"
    android:textSize="35sp" />
</code>```

答:
It seems like the structure is a little weird. I'm not sure what the end goal of what your trying to do is but I think i have an idea. I rewrote the code here for you that will adjust the items below based on the size of the text above.</p>

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/imageView2"
    android:layout_centerHorizontal="true">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:text="THIS IS PREFILLED"
        android:textSize="35sp"
        />

    <TextView
        android:id="@+id/gjoremaal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text="This text changes "
        android:visibility="visible"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView3"
        android:layout_marginBottom="200dp"
        />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="THIS IS PREFILLED"
        android:textSize="35sp"
        android:layout_below="@+id/gjoremaal"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:id="@+id/gjenstand"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This text changes"
        android:textSize="30sp"
        android:visibility="visible"
        android:layout_below="@+id/textView2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="24dp" />

    <ImageView
        android:id="@+id/bildeAvGjenstand"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:contentDescription="sample"
        android:layout_below="@+id/gjenstand"
        android:layout_centerHorizontal="true" />
    </RelativeLayout>
</code>```

Body:
I have a simple layout filled with 4 TextView's, 2 of which are pre-filled with text, as number 1 and 3 from top. The two other are filled in based on witch ListItem the user taps. They are filled with different lengths of text, so the majority of times, the texts overlap.

How can I make number 3 and 4 position themselves further down on the screen, if the texts overlap?

Code is attached below:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/imageView2"
android:layout_centerHorizontal="true">

    <ImageView
        android:id="@+id/bildeAvGjenstand"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:contentDescription="@string/bildeBesk"
        android:layout_marginBottom="133dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="THIS IS PREFILLED"
        android:textSize="35sp"
        android:layout_above="@+id/gjenstand"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:id="@+id/gjenstand"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textSize="30sp"
        android:visibility="visible"
        android:layout_above="@+id/bildeAvGjenstand"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="24dp" />

    <TextView
        android:id="@+id/gjoremaal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text=""
        android:visibility="visible"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView3" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:text="THIS IS PREFILLED"
    android:textSize="35sp" />

Body:
It seems like the structure is a little weird. I'm not sure what the end goal of what your trying to do is but I think i have an idea. I rewrote the code here for you that will adjust the items below based on the size of the text above.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/imageView2"
    android:layout_centerHorizontal="true">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:text="THIS IS PREFILLED"
        android:textSize="35sp"
        />

    <TextView
        android:id="@+id/gjoremaal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text="This text changes "
        android:visibility="visible"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView3"
        android:layout_marginBottom="200dp"
        />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="THIS IS PREFILLED"
        android:textSize="35sp"
        android:layout_below="@+id/gjoremaal"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:id="@+id/gjenstand"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This text changes"
        android:textSize="30sp"
        android:visibility="visible"
        android:layout_below="@+id/textView2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="24dp" />

    <ImageView
        android:id="@+id/bildeAvGjenstand"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:contentDescription="sample"
        android:layout_below="@+id/gjenstand"
        android:layout_centerHorizontal="true" />
    </RelativeLayout>


问:
Hash small strings into numbers only
My primary key 'is' a string - therefore I want to hash it so I can use the hashed number instead of a string..

I have in total 800 fixed strings (meaning very few and really really low security risk on hashing) so its very unlikely I'll encounter collisions with a simple hash function/method. I considered md5 but since its going to be the primary key in my sqlite table I want to avoid any strings in it. Do you have anything in mind?

Cheers

答:
Normally you would use something like an auto-increment field but if you want a hash you could try this:</p>

```<code>const crc32 = require("crc32")
const key = "lskdjfasoif";
const idNum = parseInt(crc32(key),16);
</code>```

Title: Hash small strings into numbers only

Body:
Normally you would use something like an auto-increment field but if you want a hash you could try this:

const crc32 = require("crc32")
const key = "lskdjfasoif";
const idNum = parseInt(crc32(key),16);


问:
Symfony 2.7 Doctrine don't mount query correctly
I'm trying to get the classrooms from a teacher in a many to many relation.

```<code>$classrooms = $this->getDoctrine()->getManager()->getRepository('AppBundle:Classroom')->findBy(array('teachers' => $teacher));
</code>```

But I get the error.
The doctrine is not mounting the join:

An exception occurred while executing 'SELECT t0.id AS id_1, t0.name AS name_2, t0.institution_id AS institution_id_3 FROM classroom t0 WHERE classroom_teacher.teacher_id = ?' with params [4]:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'classroom_teacher.teacher_id' in 'where clause'

But I'm using the many to many

Class Classroom

```<code>/**
 * Classroom
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ClassroomRepository")
 */
class Classroom
{
    /**
     * @ORM\ManyToMany(targetEntity="Teacher", cascade={"persist"}, inversedBy="classrooms")
     */
    private $teachers;
    public function __construct()
    {
        $this->teachers         = new ArrayCollection();
    }
}
</code>```

Class Teacher

```<code>/**
 * Teacher
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Repository\TeacherRepository")
 */
class Teacher implements AdvancedUserInterface, \Serializable
{
    /**
     * @ORM\ManyToMany(targetEntity="Classroom", mappedBy="teachers")
     */
    protected $classrooms;
    public function __construct()
    {
        $this->classrooms           = new ArrayCollection();
    }
}
</code>```

What is wrong?

答:
Add this @ORM\JoinColumn(nullable=false) and do a :
 php app/console doctrine:schema:update  --force to update so that it can take effect.

```<code> /**
   * Classroom
   *
   * @ORM\Table()
   * @ORM\Entity(repositoryClass="AppBundle\Repository\ClassroomRepository")
   */
   class Classroom{

    /**
     * @ORM\ManyToMany(targetEntity="Teacher", cascade={"persist"}, inversedBy="classrooms")
     * @ORM\JoinColumn(nullable=false)// this line was missing
     */
    private $teachers;
    public function __construct()
    {
        $this->teachers         = new ArrayCollection();
    }
    }
</code>```

Good luck

Body:
I'm trying to get the classrooms from a teacher in a many to many relation.

$classrooms = $this->getDoctrine()->getManager()->getRepository('AppBundle:Classroom')->findBy(array('teachers' => $teacher));

But I get the error.
The doctrine is not mounting the join:

An exception occurred while executing 'SELECT t0.id AS id_1, t0.name AS name_2, t0.institution_id AS institution_id_3 FROM classroom t0 WHERE classroom_teacher.teacher_id = ?' with params [4]:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'classroom_teacher.teacher_id' in 'where clause'

But I'm using the many to many

Class Classroom

/**
 * Classroom
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ClassroomRepository")
 */
class Classroom
{
    /**
     * @ORM\ManyToMany(targetEntity="Teacher", cascade={"persist"}, inversedBy="classrooms")
     */
    private $teachers;
    public function __construct()
    {
        $this->teachers         = new ArrayCollection();
    }
}

Class Teacher

/**
 * Teacher
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Repository\TeacherRepository")
 */
class Teacher implements AdvancedUserInterface, \Serializable
{
    /**
     * @ORM\ManyToMany(targetEntity="Classroom", mappedBy="teachers")
     */
    protected $classrooms;
    public function __construct()
    {
        $this->classrooms           = new ArrayCollection();
    }
}

What is wrong?

Body:
Add this @ORM\JoinColumn(nullable=false) and do a :
 php app/console doctrine:schema:update  --force to update so that it can take effect.

 /**
   * Classroom
   *
   * @ORM\Table()
   * @ORM\Entity(repositoryClass="AppBundle\Repository\ClassroomRepository")
   */
   class Classroom{

    /**
     * @ORM\ManyToMany(targetEntity="Teacher", cascade={"persist"}, inversedBy="classrooms")
     * @ORM\JoinColumn(nullable=false)// this line was missing
     */
    private $teachers;
    public function __construct()
    {
        $this->teachers         = new ArrayCollection();
    }
    }

Good luck


问:
How to bind a component with an object in view scoped managed bean?
I am trying to create a dynamic panel (panel with various items) then i want to bind it with panel component in view page, the scope of managed bean which has the panel object is @ViewScoped.
I noticed  that any ajax render this panel in the view page rebuild the managed bean, Why is that ?
Here is my code :

this is the managed bean :

```<code>package test;

import org.icefaces.ace.component.panel.Panel;

@ManagedBean(name = "myBean")
@ViewScoped

public class myBean  {

    private Panel myPanel;

    // Constructor
    public myBean() {
         myPanel = drawPanel(); // this function initiate and add items to the panel
    }

    // Setters and Getters Methods
}
</code>```

and this the view page :

```<code><h:form>
    <ace:panel binding="#{myBean.myPanel}"></ace:panel>
    <ace:pushButton actionListener="#{myBean.something}">
        <ace:ajax render="@form" />
    </ace:pushButton>
</h:form>
</code>```

in every time i pressed the button, the managed bean constructor invoked , Why does that happened ?
Also i noticed that if i remove the binding attribute from the panel component or make the scope of the managed bean session or application scope, the constructor didn't invoked.

Note : I am using icefaces 3 and jsf 2.0 .

Is there any solution for this situation ?

答:
As the ICEFaces documentation says:

The Push Button is a component that allows entry of a complete form or just itself. It has the same functionality of a regular jsf command button but without having to add extra attributes.

Because the PushButton is a command button it do navigation. If you don't use its action attribute it will apply its default value. I can't find what it is (I just suspect that it is an empty string).

The JSF navigation rules depending on the action outcome of UICommands:

null or void : reloads the current view

empty string : recreates the current view (if the view recreated, the view scoped beans do the same)

non empty string : the next view determined by the navigation handler.

If the reason is the empty string default result of the action attribute, then use it in the facet:

```<code><ace:pushButton action="#{myBean.nextPage}" actionListener="#{myBean.something}">
</code>```

And pass back a null value in its linked handler method:

```<code>public class MyBean // You use myBean here in your question improperly
{
  public String nexPage()
  { return null; }
}
</code>```

Body:
I am trying to create a dynamic panel (panel with various items) then i want to bind it with panel component in view page, the scope of managed bean which has the panel object is @ViewScoped.
I noticed  that any ajax render this panel in the view page rebuild the managed bean, Why is that ?
Here is my code :

this is the managed bean :

package test;

import org.icefaces.ace.component.panel.Panel;

@ManagedBean(name = "myBean")
@ViewScoped

public class myBean  {

    private Panel myPanel;

    // Constructor
    public myBean() {
         myPanel = drawPanel(); // this function initiate and add items to the panel
    }

    // Setters and Getters Methods
}

and this the view page :

<h:form>
    <ace:panel binding="#{myBean.myPanel}"></ace:panel>
    <ace:pushButton actionListener="#{myBean.something}">
        <ace:ajax render="@form" />
    </ace:pushButton>
</h:form>

in every time i pressed the button, the managed bean constructor invoked , Why does that happened ?
Also i noticed that if i remove the binding attribute from the panel component or make the scope of the managed bean session or application scope, the constructor didn't invoked.

Note : I am using icefaces 3 and jsf 2.0 .

Is there any solution for this situation ?

Body:
As the ICEFaces documentation says:

The Push Button is a component that allows entry of a complete form or just itself. It has the same functionality of a regular jsf command button but without having to add extra attributes.

Because the PushButton is a command button it do navigation. If you don't use its action attribute it will apply its default value. I can't find what it is (I just suspect that it is an empty string).

The JSF navigation rules depending on the action outcome of UICommands:

null or void : reloads the current view

empty string : recreates the current view (if the view recreated, the view scoped beans do the same)

non empty string : the next view determined by the navigation handler.

If the reason is the empty string default result of the action attribute, then use it in the facet:

<ace:pushButton action="#{myBean.nextPage}" actionListener="#{myBean.something}">

And pass back a null value in its linked handler method:

public class MyBean // You use myBean here in your question improperly
{
  public String nexPage()
  { return null; }
}


问:
Add int to hex ("/x??" form) with python
```<code>hex = "\xc0\x1d\x00\x00"
n = 4

result = chr(int(hex, 16) + n)
</code>```

I'm reading an .avi file and extracting "hex" from it
I need to be able to operate on it before putting it back in the file
but I'm struggling with the conversions, is there any way I could do this ?

ValueError: invalid literal for int() with base 16: '\xc0\x1d\x00\x00'

edit : more details

I heard .avi files have frame indexes that start at "idx1", the 4 bytes following ("\xc0\x1d\x00\x00") describe the length of that said index.
Since I'm duplicating frames I need to fix the size of the index to make the file readable again.

答:
assuming your using python 2.7 ?

```<code>arr = []
for h in hex:
    arr.append(ord(h))
print( arr )

>>> [192, 29, 0, 0]
</code>```

Then you could compress to a 32 int or just add 4 to the LSB ?

```<code>def addToBytearray(arr, n):
    l = len(arr) - 1
    for i,x in enumerate(arr[::-1]):
        x += n
        n = x >> 8
        arr[l-i] =  x & 0xff
        if n == 0 :
            break
    if n != 0 :
        print( "overflow error" )
    return arr

print(addToBytearray(arr,4))
>>> [192, 29, 0, 4]

print(addToBytearray(arr,304))
>>> [192, 29, 1, 52]
</code>```

if you want to only use built-ins ( should be easier with 3.x )

Body:
hex = "\xc0\x1d\x00\x00"
n = 4

result = chr(int(hex, 16) + n)

I'm reading an .avi file and extracting "hex" from it
I need to be able to operate on it before putting it back in the file
but I'm struggling with the conversions, is there any way I could do this ?

ValueError: invalid literal for int() with base 16: '\xc0\x1d\x00\x00'

edit : more details

I heard .avi files have frame indexes that start at "idx1", the 4 bytes following ("\xc0\x1d\x00\x00") describe the length of that said index.
Since I'm duplicating frames I need to fix the size of the index to make the file readable again.

Body:
assuming your using python 2.7 ?

arr = []
for h in hex:
    arr.append(ord(h))
print( arr )

>>> [192, 29, 0, 0]

Then you could compress to a 32 int or just add 4 to the LSB ?

def addToBytearray(arr, n):
    l = len(arr) - 1
    for i,x in enumerate(arr[::-1]):
        x += n
        n = x >> 8
        arr[l-i] =  x & 0xff
        if n == 0 :
            break
    if n != 0 :
        print( "overflow error" )
    return arr

print(addToBytearray(arr,4))
>>> [192, 29, 0, 4]

print(addToBytearray(arr,304))
>>> [192, 29, 1, 52]

if you want to only use built-ins ( should be easier with 3.x )


问:
Updating a table with different values for different conditions
I have a situation like this:

```<code>update lskinproperty
set frn_lskin_stateid = 2
where frn_lskinid IN (61209, 61208)

update lskinproperty
set frn_lskin_stateid = 3
where frn_lskinid IN (72670, 56916)

update lskinproperty
set frn_lskin_stateid = 4
where frn_lskinid IN (55451)
</code>```

If I run this three queries, it will do what exactly what I want however I feel there it should be a better way to do this. Does SQL Server has anything like case or switch or something similar where you can say for case equal to x do this and for case equal to y do something else and so on?

答:
You can filter for all the values of frn_lskinid at once and then use case to identify which value to assign for which frn_lskinid .

```<code>update lskinproperty
set frn_lskin_stateid = case
        when frn_lskinid in (61209, 61208)
            then 2
        when frn_lskinid in (72670, 56916)
            then 3
        else 4
        end
where frn_lskinid in (72670, 56916, 61209, 61208, 55451)
</code>```

The else here covers for the case when frn_lskinid is 55451 which is same as writing explicitly using another when:

```<code>update lskinproperty
set frn_lskin_stateid = case
        when frn_lskinid in (61209, 61208)
            then 2
        when frn_lskinid in (72670, 56916)
            then 3
        when frn_lskinid = 55451
            then 4
        end
where frn_lskinid in (72670, 56916, 61209, 61208, 55451)
</code>```

Body:
I have a situation like this:

update lskinproperty
set frn_lskin_stateid = 2
where frn_lskinid IN (61209, 61208)

update lskinproperty
set frn_lskin_stateid = 3
where frn_lskinid IN (72670, 56916)

update lskinproperty
set frn_lskin_stateid = 4
where frn_lskinid IN (55451)

If I run this three queries, it will do what exactly what I want however I feel there it should be a better way to do this. Does SQL Server has anything like case or switch or something similar where you can say for case equal to x do this and for case equal to y do something else and so on?

Body:
You can filter for all the values of frn_lskinid at once and then use case to identify which value to assign for which frn_lskinid .

update lskinproperty
set frn_lskin_stateid = case
        when frn_lskinid in (61209, 61208)
            then 2
        when frn_lskinid in (72670, 56916)
            then 3
        else 4
        end
where frn_lskinid in (72670, 56916, 61209, 61208, 55451)

The else here covers for the case when frn_lskinid is 55451 which is same as writing explicitly using another when:

update lskinproperty
set frn_lskin_stateid = case
        when frn_lskinid in (61209, 61208)
            then 2
        when frn_lskinid in (72670, 56916)
            then 3
        when frn_lskinid = 55451
            then 4
        end
where frn_lskinid in (72670, 56916, 61209, 61208, 55451)


问:
Can I get attach_file to work without an ID or class name?
The markup looks exactly like this:

<input type="file">

Is there any way to get attach_file to work with this?

In the meantime I've asked a dev to add an id for me, but I try to avoid any special asks altogether.

答:
Capybara's #attach_field basically boils down to find(:file_field, locator, options).set(path) which will find by id, name, or associated label text.  However if you find the element another way you can just call #set on it with the path.  Another thing to note is that (with up to date  versions of Capybara) if you only have one file field on the page or you are scoped to a region of the page that only has one file field you can pass nil as the locator and it will just find any input of type 'file'.

So

```<code>attach_file(nil, 'test.txt')
</code>```

is equivalent to

```<code>find('input[type="file"]').set('text.txt')
</code>```

except that the example with set will skip Capybara's existence test for the file

Body:
Capybara's #attach_field basically boils down to find(:file_field, locator, options).set(path) which will find by id, name, or associated label text.  However if you find the element another way you can just call #set on it with the path.  Another thing to note is that (with up to date  versions of Capybara) if you only have one file field on the page or you are scoped to a region of the page that only has one file field you can pass nil as the locator and it will just find any input of type 'file'.

So

attach_file(nil, 'test.txt')

is equivalent to

find('input[type="file"]').set('text.txt')

except that the example with set will skip Capybara's existence test for the file


问:
Module compiled with swift 3.0 cannot be imported in Swift 3.0.1
I upgraded Xcode to 8.1 GM and am now getting the below error for SwiftyJSON. Other imported frameworks seem to work. Is there a way to force this to work in Swift 3 until SwiftyJSON upgrades their framework? I used Carthage to import/update frameworks. I also tried changing Use Legacy Swift language version On and Off to no avail.

Module compiled with Swift 3.0 cannot be imported in Swift 3.0.1:
  Modules/SwiftyJSON.swiftmodule/arm64.swiftmodule

答:
Just to give the latest updates:

Carthage has released version 0.20 on Feb 27, 2017.

Carthage now only uses the pre-build binary if available pre-build binary is compatible.

That is being said, you no longer have to use: --no-use-binaries to avoid incompatible pre-build framework.

So make sure that you have carthage version greater than 0.20 and simply do:

```<code>carthage update --platform iOS
</code>```

Body:
Just to give the latest updates:

Carthage has released version 0.20 on Feb 27, 2017.

Carthage now only uses the pre-build binary if available pre-build binary is compatible.

That is being said, you no longer have to use: --no-use-binaries to avoid incompatible pre-build framework.

So make sure that you have carthage version greater than 0.20 and simply do:

carthage update --platform iOS


问:
What is the most efficient way to remove all the elements of one array from another array?
I have two arrays, array A contains a long list with some elements I want to remove. Array B is the full list of those elements that I wish to remove from array A.

What is the most efficient way to achieve this?

答:
array_diff is the obvious answer, but since you've asked for the most efficient way, here's a test

```<code>$big = range(1, 90000);
$remove = range(500, 600);

$ts = microtime(true);
$result = array_diff($big, $remove);
printf("%.2f\n", microtime(true) - $ts);

$ts = microtime(true);
$map = array_flip($remove);
$result = array();
foreach($big as $e)
    if(!isset($map[$e]))
        $result[] = $e;
printf("%.2f\n", microtime(true) - $ts);
</code>```

prints on my machine

```<code>0.67
0.03
</code>```

So the simple loop with a hash-based lookup is approximately 20 times faster than array_diff.

Body:
array_diff is the obvious answer, but since you've asked for the most efficient way, here's a test

$big = range(1, 90000);
$remove = range(500, 600);

$ts = microtime(true);
$result = array_diff($big, $remove);
printf("%.2f\n", microtime(true) - $ts);

$ts = microtime(true);
$map = array_flip($remove);
$result = array();
foreach($big as $e)
    if(!isset($map[$e]))
        $result[] = $e;
printf("%.2f\n", microtime(true) - $ts);

prints on my machine

0.67
0.03

So the simple loop with a hash-based lookup is approximately 20 times faster than array_diff.


问:
Read mutliple data from table and create textboxes in form
My table in MySQL is like this:

I have a panel in my Form, and I want to create a TextBox for each data on this table and write sikicerik data to that TextBox's text.
Actually I did it but it creates only one TextBox and selects only the first data on the table.

My code is like this:

```<code>int count = oku.FieldCount;

reader.Read();
{
    for (int i = 0; i < count; i++)
    {
        TextBox txt1 = new TextBox();
        Point txtyer = new Point(x, y);
        txt1.Text = reader["sikicerik"].ToString();
        txt1.Name = i.ToString();
        x = x + 25;
        y = y + 25;
        panel1.Controls.Add(txt1);
    }
}
</code>```

It creates just one TextBox and writes "5" in it.

How can I do that repeatedly?

答:
I suppose that you get the FieldCount from the reader variable.

Now in this context you should loop over the read and inside the loop create the textbox for each field retrieved by the original query.

Finally, if you don't set the Location property of the TextBoxes they will be created each on top of the others and you see only the topmost one with the latest value obtained in the loop

```<code>// Get the number of fields present in the reader....
int count = reader.FieldCount;

// Read one record at time
while(reader.Read())
{
    // Create a textbox for each field in the record
    for (int i = 0; i < count; i++)
    {
        TextBox txt1 = new TextBox();

        // Set its location on screen
        // Probably if you have many fields you need to
        // use a better algorithm to calculate x,y position
        txt1.Location = new Point(x, y);
        txt1.Text = reader[i].ToString();
        txt1.Name = i.ToString();
        x = x + 25;
        y = y + 25;
        panel1.Controls.Add(txt1);
    }
}
</code>```

If you want to create textboxes only for the field sikicerik you have two options. The first one is the recommended because it causes less overhead on your database consist in changing the SELECT query used to build the read to

```<code> SELECT sikicerik FROM yourTableName
</code>```

The other option is a simple change to your code. You don't need to loop over FieldCount because you already know that you are interested in only one field

```<code>// Read one record at time
while(oku.Read())
{
    textBox1.Text = oku["soru"].ToString();
    label1.Text = Form2.sinavno;

    // Create the single textbox required for the only field required
    TextBox txt1 = new TextBox();

    // Set its location on screen
    txt1.Location = new Point(x, y);
    txt1.Text = oku["sikicerik"].ToString();
    txt1.Name = i.ToString();
    x = x + 25;
    y = y + 25;
    panel1.Controls.Add(txt1);

    // Repeat the loop for each record.

}
</code>```

Body:
My table in MySQL is like this:

I have a panel in my Form, and I want to create a TextBox for each data on this table and write sikicerik data to that TextBox's text.
Actually I did it but it creates only one TextBox and selects only the first data on the table.

My code is like this:

int count = oku.FieldCount;

reader.Read();
{
    for (int i = 0; i < count; i++)
    {
        TextBox txt1 = new TextBox();
        Point txtyer = new Point(x, y);
        txt1.Text = reader["sikicerik"].ToString();
        txt1.Name = i.ToString();
        x = x + 25;
        y = y + 25;
        panel1.Controls.Add(txt1);
    }
}

It creates just one TextBox and writes "5" in it.

How can I do that repeatedly?

Body:
I suppose that you get the FieldCount from the reader variable.

Now in this context you should loop over the read and inside the loop create the textbox for each field retrieved by the original query.

Finally, if you don't set the Location property of the TextBoxes they will be created each on top of the others and you see only the topmost one with the latest value obtained in the loop

// Get the number of fields present in the reader....
int count = reader.FieldCount;

// Read one record at time
while(reader.Read())
{
    // Create a textbox for each field in the record
    for (int i = 0; i < count; i++)
    {
        TextBox txt1 = new TextBox();

        // Set its location on screen
        // Probably if you have many fields you need to
        // use a better algorithm to calculate x,y position
        txt1.Location = new Point(x, y);
        txt1.Text = reader[i].ToString();
        txt1.Name = i.ToString();
        x = x + 25;
        y = y + 25;
        panel1.Controls.Add(txt1);
    }
}

If you want to create textboxes only for the field sikicerik you have two options. The first one is the recommended because it causes less overhead on your database consist in changing the SELECT query used to build the read to

 SELECT sikicerik FROM yourTableName

The other option is a simple change to your code. You don't need to loop over FieldCount because you already know that you are interested in only one field

// Read one record at time
while(oku.Read())
{
    textBox1.Text = oku["soru"].ToString();
    label1.Text = Form2.sinavno;

    // Create the single textbox required for the only field required
    TextBox txt1 = new TextBox();

    // Set its location on screen
    txt1.Location = new Point(x, y);
    txt1.Text = oku["sikicerik"].ToString();
    txt1.Name = i.ToString();
    x = x + 25;
    y = y + 25;
    panel1.Controls.Add(txt1);

    // Repeat the loop for each record.

}