问:
Serial port coin acceptor reading
```<code>private void serialPort1_PinChanged(object sender, SerialPinChangedEventArgs e)
{
     time = time + 100;
}
</code>```

I've made a cafe program in C# which reads pulse from SerialPort and adds time to user. Also there is an electronic circuit connected between coin acceptor and serial port. I'm using the code above to read pulse from coin acceptor.

Code works fine and catches pin changes very well. But there is one problem: The pinchanged function works twice. Normally it must add 100 to time variable, but it adds 200 every time. Why this happens?

答: It's very simple, the event is call one time when the pig goes up (Low to High) and one when it goes down (High to Low), so you have +200.</p>

Title: Serial port coin acceptor reading

Body:
private void serialPort1_PinChanged(object sender, SerialPinChangedEventArgs e)
{
     time = time + 100;
}

I've made a cafe program in C# which reads pulse from SerialPort and adds time to user. Also there is an electronic circuit connected between coin acceptor and serial port. I'm using the code above to read pulse from coin acceptor.

Code works fine and catches pin changes very well. But there is one problem: The pinchanged function works twice. Normally it must add 100 to time variable, but it adds 200 every time. Why this happens?


来源: stackexchange

问:
Print vector <string> m[][] in C++
I need to print the strings from this 3d matrix using an iterator.

This is the declaration

vector <string> transicoes[estados.size()][alfabeto.size()];

I tried printing like this

printf("%s", transicoes[i][j][k]);

but I get this error message:

cannot pass objects of non-trivially-copyable type

How can I do this?

EDIT: changed to cout and it works now, thanks

答:
The problem is that C functions are not compatible with C++ structures. Try doing this instead:

```<code>printf("%s", transicoes[i][j][k].c_str());
</code>```

The c_str() call returns a const char* to a null-terminated character array with data equivalent to those stored in the string, which is a C-like string.

But if you are working with C++, you should use the stream operators << and >>. The code would then loop like this:

```<code>std::cout << transicoes[i][j][k] << endl;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Print vector <string> m[][] in C++

Body:
The problem is that C functions are not compatible with C++ structures. Try doing this instead:

printf("%s", transicoes[i][j][k].c_str());

The c_str() call returns a const char* to a null-terminated character array with data equivalent to those stored in the string, which is a C-like string.

But if you are working with C++, you should use the stream operators << and >>. The code would then loop like this:

std::cout << transicoes[i][j][k] << endl;


问:
Get Current Thread Handle
I have problem in Delphi application with determining current application (current Thread) handle. I know that I can get Current Thread ID with Windows API function GetCurrentThreadID, but I need current Thread handle to use as param for another Windows API function that is SuspendThread.

Actually what I am trying to do is to make one of my old dll's made for hooking API functions located in kernel32.dll like OpenProcess or TerminateProcessto also do hook for SuspendProcess. Hook is located in dll file and using SetWindowsHookEx to be injected in running processes then finding base address of target functions.
I had no problem with hooking functions like TerminateProcess because it needs process ID as param that is easy to obtain in main application using GetCurrentProcessID. To make similar hook for SuspendThread function i need to pass thread handle as param.

Only place where I found thread handle is PROCESS_INFORMATION structure that contains

```<code>typedef struct _PROCESS_INFORMATION { // pi
    HANDLE hProcess;
    HANDLE hThread;
    DWORD dwProcessId;
    DWORD dwThreadId;
} PROCESS_INFORMATION;
</code>```

but problem is that this structure is available only after creating process with CreateProcess API function. Main goal is to prevent program users to use different tools available online like ProcessExplorer etc to terminate process. I acheived that with success hooking TerminateProcess API calls and preventing that way closing my app but Suspend option in those process exploring tools can Suspend my process. It is internet kiosk application and it is vital that users can't close that application. Applications is currently running in Windows XP and it has to be run on administrator account because other apps that users are using after logging in my application requires administrator account to operate, so I can't simply run my application under restricted user.

Is there any way that I can get my main application main thread handle in Delphi ?

Thanks in advance

答:
The only safe way to call SuspendThread is with a handle to the current thread. Suspending any other thread is a bad idea. To get a handle to the current thread, just call GetCurrentThread. You can use it pretty much anywhere a thread handle is required. But don't give that handle to another thread — it's a special "pseudo-handle" that always means "current thread," no matter which thread has it.

You can use OpenThread or DuplicateHandle to get a "real" thread handle, but that probably won't get you where you want to go. You won't be able to recognize attempts to suspend your thread or process because the handle another program uses to suspend your thread won't necessarily be the same value that you got when you called OpenThread. Handles are only meaningful within the process that opened them, and it's possible to acquire multiple handles to the same thing, and that may or may not yield the same value each time.

Instead, call GetThreadId to get the ID of the thread being suspended, and then see whether it matches any of your program's thread IDs. Thread IDs uniquely identify threads; handles don't. Likewise for process IDs and handles.

ContentLicense: CC BY-SA 2.5

Title: Get Current Thread Handle

Body:
I have problem in Delphi application with determining current application (current Thread) handle. I know that I can get Current Thread ID with Windows API function GetCurrentThreadID, but I need current Thread handle to use as param for another Windows API function that is SuspendThread.

Actually what I am trying to do is to make one of my old dll's made for hooking API functions located in kernel32.dll like OpenProcess or TerminateProcessto also do hook for SuspendProcess. Hook is located in dll file and using SetWindowsHookEx to be injected in running processes then finding base address of target functions.
I had no problem with hooking functions like TerminateProcess because it needs process ID as param that is easy to obtain in main application using GetCurrentProcessID. To make similar hook for SuspendThread function i need to pass thread handle as param.

Only place where I found thread handle is PROCESS_INFORMATION structure that contains

typedef struct _PROCESS_INFORMATION { // pi
    HANDLE hProcess;
    HANDLE hThread;
    DWORD dwProcessId;
    DWORD dwThreadId;
} PROCESS_INFORMATION;

but problem is that this structure is available only after creating process with CreateProcess API function. Main goal is to prevent program users to use different tools available online like ProcessExplorer etc to terminate process. I acheived that with success hooking TerminateProcess API calls and preventing that way closing my app but Suspend option in those process exploring tools can Suspend my process. It is internet kiosk application and it is vital that users can't close that application. Applications is currently running in Windows XP and it has to be run on administrator account because other apps that users are using after logging in my application requires administrator account to operate, so I can't simply run my application under restricted user.

Is there any way that I can get my main application main thread handle in Delphi ?

Thanks in advance


问:
What is the most efficient way to deep clone an object in JavaScript?
What is the most efficient way to clone a JavaScript object? I've seen obj = eval(uneval(o)); being used, but that's non-standard and only supported by Firefox.

 I've done things like obj = JSON.parse(JSON.stringify(o)); but question the efficiency.

 I've also seen recursive copying functions with various flaws.

I'm surprised no canonical solution exists.

答:
Lodash has a function that handles that for you like so.

```<code>var foo = {a: 'a', b: {c:'d', e: {f: 'g'}}};

var bar = _.cloneDeep(foo);
// bar = {a: 'a', b: {c:'d', e: {f: 'g'}}}
</code>```

Read the docs here.

LastEditorDisplayName: JasonBunting

Body:
Lodash has a function that handles that for you like so.

var foo = {a: 'a', b: {c:'d', e: {f: 'g'}}};

var bar = _.cloneDeep(foo);
// bar = {a: 'a', b: {c:'d', e: {f: 'g'}}}

Read the docs here.


问:
Roles.userIsInRole returns FALSE - Meteor
Im using FlowRouter with FlowTemplate and in both/router/router.js I am checking is it user in role admin:

```<code>....
action: function () {
    if(Roles.userIsInRole(Meteor.userId(), 'admin')){
        FlowLayout.render('layout', {
            sidebar: 'sidebar', main:'admin', cart:'cart'
        })
    } else {
        FlowLayout.render('layout', {
            sidebar: 'sidebar', main:'unauthorised', cart:'cart'
        })
    }

    console.log(Meteor.userId());

}
....
</code>```

and returns FALSE, but when I use it in the WEB console is TRUE . This line console.log(Meteor.userId()); output the correct userID and when I am logged in, if I do this in the WEB console Roles.userIsInRole(Meteor.userId(), 'admin'), it is TRUE. If I do this Meteor.user().roles, the result is ['admin']

If I check in the template is it user in role:

```<code>{{#if isInRole 'admin' }}
    ADMIN
{{/if}}
</code>```

It is TRUE, but in the router.js returns FALSE.

How to fix it ?

答:
It is likely that the roles field is received at a later stage (based on a different subscription).

You should make sure that this subscription is ready - either directly or by using some other mechanism to make sure that you get the field (for example making sure that it is an array), and only then make the routing/rendering decision.

Body:
Im using FlowRouter with FlowTemplate and in both/router/router.js I am checking is it user in role admin:

....
action: function () {
    if(Roles.userIsInRole(Meteor.userId(), 'admin')){
        FlowLayout.render('layout', {
            sidebar: 'sidebar', main:'admin', cart:'cart'
        })
    } else {
        FlowLayout.render('layout', {
            sidebar: 'sidebar', main:'unauthorised', cart:'cart'
        })
    }

    console.log(Meteor.userId());

}
....

and returns FALSE, but when I use it in the WEB console is TRUE . This line console.log(Meteor.userId()); output the correct userID and when I am logged in, if I do this in the WEB console Roles.userIsInRole(Meteor.userId(), 'admin'), it is TRUE. If I do this Meteor.user().roles, the result is ['admin']

If I check in the template is it user in role:

{{#if isInRole 'admin' }}
    ADMIN
{{/if}}

It is TRUE, but in the router.js returns FALSE.

How to fix it ?


问:
urllib.urlretrieve() cannot download the file
Hi there's a button in the web, if you click it, it'll download a file.

Say the corresponding url is like this
http://www.mydata.com/data/filedownload.aspx?e=MyArgu1&k=kfhk22wykq

If i put this url in the address bar in the browser, it can download the file as well properly.

Now i do this in the python,

```<code>urllib.urlretrieve(url, "myData.csv")
</code>```

The csv file is empty. Any suggestions please ?

答: This may not be possible with every website. If a link has a token then python is unlikely to be able to use the link as it is tied to your browser.</p>

Body:
Hi there's a button in the web, if you click it, it'll download a file.

Say the corresponding url is like this
http://www.mydata.com/data/filedownload.aspx?e=MyArgu1&k=kfhk22wykq

If i put this url in the address bar in the browser, it can download the file as well properly.

Now i do this in the python,

urllib.urlretrieve(url, "myData.csv")

The csv file is empty. Any suggestions please ?


问:
powershell REST API issue with Meraki Dashboard API
I'm having a problem with a specific REST api from meraki. I have been able to perform all the get operations with success, however the POST operations I am receiving a "308" error from the server. I'm trying to do the following:

Example request:

```<code>curl -L -H 'X-Cisco-Meraki-API-Key: <key>' -X POST -H 'Content-Type:
application/json' --data-binary '{"name":"Miles Meraki",
"email":"miles@meraki.com", "orgAccess":"none", "tags":[{"tag":"west",
"access":"read-only"}]}'
'https://dashboard.meraki.com/api/v0/organizations/1234/admins'
</code>```

My Request:

```<code>Invoke-RestMethod -Method Post -Uri
https://dashboard.meraki.com/api/v0/organizations/$global:MerakiOrg/admins/ -
Body $jbody -Headers $Global:MerakiHeader -ContentType 'application/json'
</code>```

My $jbody value is the literal copied json from the example. I'm not familiar with this 308 code as a return code. Any guidance would be very helpful.

答:
Ok I figured out the issue, thanks to some of the responses I was able to get back on the trail and figure out. The first part of my problem was understanding what the 308 response error meant. After understanding that it was a redirect error I manually ran the rest command in the web browser to find out the redirect URL. I then used this URL as the URI prefix for my rest string. The second biggest issue I had in figuring out what was going wrong was that I wasn't getting enough information in the server response error. I found another stack overflow topic that showed me how to get the full json response
Here

After doing the streamreader method I got a better description of what my error was:

Email miles@meraki.com is already registered with a Cisco Meraki Dashboard account. For s
ecurity purposes, that user must verify his/her email address before administrator permis
sions can be granted here.

So apparently the issue boiled down to me trying to create a test account on my dashboard with the same name as what was in the api example doc. I simply modified the email suffix with my own custom suffix and that resolved the issue and the rest command worked!

thanks to those who helped me point in the right direction.

Body:
I'm having a problem with a specific REST api from meraki. I have been able to perform all the get operations with success, however the POST operations I am receiving a "308" error from the server. I'm trying to do the following:

Example request:

curl -L -H 'X-Cisco-Meraki-API-Key: <key>' -X POST -H 'Content-Type:
application/json' --data-binary '{"name":"Miles Meraki",
"email":"miles@meraki.com", "orgAccess":"none", "tags":[{"tag":"west",
"access":"read-only"}]}'
'https://dashboard.meraki.com/api/v0/organizations/1234/admins'

My Request:

Invoke-RestMethod -Method Post -Uri
https://dashboard.meraki.com/api/v0/organizations/$global:MerakiOrg/admins/ -
Body $jbody -Headers $Global:MerakiHeader -ContentType 'application/json'

My $jbody value is the literal copied json from the example. I'm not familiar with this 308 code as a return code. Any guidance would be very helpful.

ContentLicense: CC BY-SA 4.0


问:
User registration/authentication flow on a REST API
I know this is not the first time the topic is treated in StackOverflow, however, I have some questions I couldn't find an answer to or other questions have opposed answers.

I am doing a rather simple REST API (Silex-PHP) to be consumed initially by just one SPA (backbone app). I don't want to comment all the several authentication methods in this question as that topic is already fully covered on SO. I'll basically create a token for each user, and this token will be attached in every request that requires authentication by the SPA. All the SPA-Server transactions will run under HTTPS. For now, my decision is that the token doesn't expire. Tokens that expire/tokens per session are not complying with the statelessness of REST, right? I understand there's a lot of room for security improvement but that's my scope for now.

I have a model for Tokens, and thus a table in the database for tokens with a FK to user_id. By this I mean the token is not part of my user model.

REGISTER

I have a POST /users (requires no authentication) that creates a user in the database and returns the new user. This complies with the one request one resource rule. However, this brings me certain doubts:

My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?

If I decided to return the token together with the user, then I believe POST /users would be confusing for the API consumer, and then something like POST /auth/register appears. Once more, I dislike this idea because involves a verb. I really like the simplicity offered in this answer. But then again, I'd need to do two requests together, a POST /users and a POST /tokens. How wrong is it to do two requests together and also, how would I exactly send the relevant information for the token to be attached to a certain user if both requests are sent together?

For now my flow works like follows:

```<code>1. Register form makes a POST /users request
2. Server creates a new user and a new token, returns both in the response (break REST rule)
3. Client now attaches token to every Request that needs Authorization
</code>```

The token never expires, preserving REST statelessness.

EMAIL VALIDATION

Most of the current webapps require email validation without breaking the UX for the users, i.e the users can immediately use the webapp after registering. On the other side, if I return the token with the register request as suggested above, users will immediately have access to every resource without validating emails.

Normally I'd go for the following workflow:

```<code>1. Register form sends POST /users request.
2. Server creates a new user with validated_email set to false and stores an email_validation_token. Additionally, the server sends an email generating an URL that contains the email_validation_token.
3. The user clicks on the URL that makes a request: For example POST /users/email_validation/{email_validation_token}
4. Server validates email, sets validated_email to true, generates a token and returns it in the response, redirecting the user to his home page at the same time.
</code>```

This looks overcomplicated and totally ruins the UX. How'd you go about it?

LOGIN

This is quite simple, for now I am doing it this way so please correct me if wrong:

```<code>1. User fills a log in form which makes a request to POST /login sending Basic Auth credentials.
2. Server checks Basic Auth credentials and returns token for the given user.
3. Web app attached the given token to every future request.
</code>```

login is a verb and thus breaks a REST rule, everyone seems to agree on doing it this way though.

LOGOUT

Why does everyone seem to need a /auth/logout endpoint? From my point of view clicking on "logout" in the web app should basically remove the token from the application and not send it in further requests. The server plays no role in this.

As it is possible that the token is kept in localStorage to prevent losing the token on a possible page refresh, logout would also imply removing the token from the localStorage. But still, this doesn't affect the server. I understand people who need to have a POST /logout are basically working with session tokens, which again break the statelessness of REST.

REMEMBER ME

I understand the remember me basically refers to saving the returned token to the localStorage or not in my case. Is this right?

If you'd recommend any further reading on this topic I'd very much appreciate it. Thanks!

答:
REGISTER

Tokens that expire/tokens per session are not complying with the statelessness of REST, right?

No, there's nothing wrong with that. Many HTTP authentication schemes do have expiring tokens. OAuth2 is super popular for REST services, and many OAuth2 implementations force the client to refresh the access token from time to time.

My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?

Typically, if you create a new resource following REST best practices, you don't return something in response to a POST like this. Doing this would make the call more RPC-like, so I would agree with you here... it's not perfectly RESTful. I'll offer two solutions to this:

Ignore this, break the best practices. Maybe it's for the best in this case, and making exceptions if they make a lot more sense is sometimes the best thing to do (after careful consideration).

If you want be more RESTful, I'll offer an alternative.

Lets assume you want to use OAuth2 (not a bad idea!). The OAuth2 API is not really RESTful for a number of reasons. I'm my mind it is still better to use a well-defined authentication API, over rolling your own for the sake of being RESTful.

That still leaves you with the problem of creating a user on your API, and in response to this (POST) call, returning a secret which can be used as an access/refresh token.

My alternative is as follows:

You don't need to have a user in order to start a session.

What you can do instead is start the session before you create the user. This guarantees that for any future call, you know you are talking to the same client.

If you start your OAuth2 process and receive your access/refresh token, you can simply do an authenticated POST request on /users. What this means is that your system needs to be aware of 2 types of authenticated users:

Users that logged in with a username/password (`grant_type = passsword1).

Users that logged in 'anonymously' and intend to create a user after the fact. (grant_type = client_credentials).

Once the user is created, you can assign your previously anonymous session with the newly created user entity, thus you don't need to do any access/refresh token exchanges after creation.

EMAIL VALIDATION

Both your suggestions to either:

Prevent the user from using the application until email validation is completed.

Allow the user to use the application immediately

Are done by applications. Which one is more appropriate really depends on your application and what's best for you. Is there any risk associated with a user starting to use an account with an email they don't own? If no, then maybe it's fine to allow the user in right away.

Here's an example where you don't want to do this: Say if the email address is used by other members of your system to add a user as a friend, the email address is a type of identity. If you don't force users to validate their emails, it means I can act on behalf of someone with a different email address. This is similar to being able to receive invitations, etc. Is this an attack vector? Then you might want to consider blocking the user from using the application until the email is validated.

You might also consider only blocking certain features in your application for which the email address might be sensitive. In the previous example, you could prevent people from seeing invitations from other users until the email is validated.

There's no right answer here, it just depends on how you intend to use the email address.

LOGIN

Please just use OAuth2. The flow you describe is already fairly close to how OAuth2 works. Take it one step further an actually use OAuth2. It's pretty great and once you get over the initial hurdle of understanding the protocol, you'll find that it's easier than you thought and fairly straightforward to just implement the bits you specifically need for your API.

Most of the PHP OAuth2 server implementations are not great. They do too much and are somewhat hard to integrate with. Rolling your own is not that hard and you're already fairly close to building something similar.

LOGOUT

The two reasons you might want a logout endpoint are:

If you use cookie/session based authentication and want to tell the server to forget the session. It sounds like this is not an issue for you.

If you want to tell the server to expire the access/refresh token earlier. Yes, you can just remove them from localstorage, and that might be good enough. Forcing to expire them server-side might give you that little extra confidence. What if someone was able to MITM your browser and now has access to your tokens? I might want to quickly logout and expire all existing tokens. It's an edge case, and I personally have never done this, but that could be a reason why you would want it.

REMEMBER ME

Yea, implementing "remember me" with local storage sounds like a good idea.

Body:
I know this is not the first time the topic is treated in StackOverflow, however, I have some questions I couldn't find an answer to or other questions have opposed answers.

I am doing a rather simple REST API (Silex-PHP) to be consumed initially by just one SPA (backbone app). I don't want to comment all the several authentication methods in this question as that topic is already fully covered on SO. I'll basically create a token for each user, and this token will be attached in every request that requires authentication by the SPA. All the SPA-Server transactions will run under HTTPS. For now, my decision is that the token doesn't expire. Tokens that expire/tokens per session are not complying with the statelessness of REST, right? I understand there's a lot of room for security improvement but that's my scope for now.

I have a model for Tokens, and thus a table in the database for tokens with a FK to user_id. By this I mean the token is not part of my user model.

REGISTER

I have a POST /users (requires no authentication) that creates a user in the database and returns the new user. This complies with the one request one resource rule. However, this brings me certain doubts:

My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?

If I decided to return the token together with the user, then I believe POST /users would be confusing for the API consumer, and then something like POST /auth/register appears. Once more, I dislike this idea because involves a verb. I really like the simplicity offered in this answer. But then again, I'd need to do two requests together, a POST /users and a POST /tokens. How wrong is it to do two requests together and also, how would I exactly send the relevant information for the token to be attached to a certain user if both requests are sent together?

For now my flow works like follows:

1. Register form makes a POST /users request
2. Server creates a new user and a new token, returns both in the response (break REST rule)
3. Client now attaches token to every Request that needs Authorization

The token never expires, preserving REST statelessness.

EMAIL VALIDATION

Most of the current webapps require email validation without breaking the UX for the users, i.e the users can immediately use the webapp after registering. On the other side, if I return the token with the register request as suggested above, users will immediately have access to every resource without validating emails.

Normally I'd go for the following workflow:

1. Register form sends POST /users request.
2. Server creates a new user with validated_email set to false and stores an email_validation_token. Additionally, the server sends an email generating an URL that contains the email_validation_token.
3. The user clicks on the URL that makes a request: For example POST /users/email_validation/{email_validation_token}
4. Server validates email, sets validated_email to true, generates a token and returns it in the response, redirecting the user to his home page at the same time.

This looks overcomplicated and totally ruins the UX. How'd you go about it?

LOGIN

This is quite simple, for now I am doing it this way so please correct me if wrong:

1. User fills a log in form which makes a request to POST /login sending Basic Auth credentials.
2. Server checks Basic Auth credentials and returns token for the given user.
3. Web app attached the given token to every future request.

login is a verb and thus breaks a REST rule, everyone seems to agree on doing it this way though.

LOGOUT

Why does everyone seem to need a /auth/logout endpoint? From my point of view clicking on "logout" in the web app should basically remove the token from the application and not send it in further requests. The server plays no role in this.

As it is possible that the token is kept in localStorage to prevent losing the token on a possible page refresh, logout would also imply removing the token from the localStorage. But still, this doesn't affect the server. I understand people who need to have a POST /logout are basically working with session tokens, which again break the statelessness of REST.

REMEMBER ME

I understand the remember me basically refers to saving the returned token to the localStorage or not in my case. Is this right?

If you'd recommend any further reading on this topic I'd very much appreciate it. Thanks!


问:
This code can't find first element
```<code>def c(stringenter):
    last = 1
    commandsline = [['a', 'first'], ['b', 'second'], ['c', 'third']]
    for commandblock in commandsline:
        last = last + 1
        if commandblock[0] == stringenter:
            realcommand = str(commandblock[1])
        elif last == len(commandsline):
            realcommand = stringenter
    return realcommand
</code>```

Hello!!! This code can find and return second, third but can't find first how  resolve problem?

答:
indices starts in 0, so you must change like this, another think, you should update the counter at the end!:</p>

```<code>def c(stringenter):
    last = 0
    commandsline = [['a', 'first'], ['b', 'second'], ['c', 'third']]
    for commandblock in commandsline:
        if commandblock[0] == stringenter:
            realcommand = str(commandblock[1])
        elif last == len(commandsline):
            realcommand = stringenter
        last = last + 1
    return realcommand
</code>```

Title: This code can't find first element

Body:
def c(stringenter):
    last = 1
    commandsline = [['a', 'first'], ['b', 'second'], ['c', 'third']]
    for commandblock in commandsline:
        last = last + 1
        if commandblock[0] == stringenter:
            realcommand = str(commandblock[1])
        elif last == len(commandsline):
            realcommand = stringenter
    return realcommand

Hello!!! This code can find and return second, third but can't find first how  resolve problem?

Body:
indices starts in 0, so you must change like this, another think, you should update the counter at the end!:

def c(stringenter):
    last = 0
    commandsline = [['a', 'first'], ['b', 'second'], ['c', 'third']]
    for commandblock in commandsline:
        if commandblock[0] == stringenter:
            realcommand = str(commandblock[1])
        elif last == len(commandsline):
            realcommand = stringenter
        last = last + 1
    return realcommand


问:
How can place a imageButton inside a textfield?
How can i create a text field with a button at the left side like whatsapp's smiley button and i also want my text to start after the button.

答:
Position them one after another in a LinearLayout and you are good to go. You don't need it to be inside. Structure is as follows:</p>

```<code><LinearLayout>
    <Button/>
    <EditText/>
</LinearLayout>
</code>```

Body:
Position them one after another in a LinearLayout and you are good to go. You don't need it to be inside. Structure is as follows:

<LinearLayout>
    <Button/>
    <EditText/>
</LinearLayout>


问:
Why isn't the state of a transition maintained once it ends?
I wanted to slightly expand the basic example for transitions and have an element fading out in one div and at the same time fading in on another:

new Vue({
  el: '#demo',
  data: {
    show: true
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fade-enter-active,
.fade-leave-active {
  transition: opacity 2s
}

.fade-enter,
.fade-leave-to {
  opacity: 0
}</code>```

  <button v-on:click="show = !show">
    Toggle
  </button>
  <transition name="fade">

hello

  </transition>
  <transition name="fade">

hello

  </transition>

```

This does not however work as intended: the upper hello fades out and the lower one fades in (so far OK), but then the lower one dissapears and the upper one appears (immediately, as if the state have changed and there were no transitions).

When clicking the button once again, it looks like the transition is correct (it starts with the lower hello fading out and the upper one fading in).

The CSS is symmetrical, the state changes only when pressing the button - so I do not understand the immediate switch after the first transition?

答:
v-show hides elements by settings the display CSS property as explained by the documentation:

v-show simply toggles the display CSS property of the element.

This has the effect that the element disappears after the transition completes, which is when the display property is set. Elements with display: none are completely hidden without any space occupied for the element.

The effect you see is not symmetrical because when hiding the element, the display property is set when the transition ends, but when showing the element again, it needs to be set when the transition starts (otherwise the transition would be invisible).

If you want to avoid that position change, you will have to keep the element in the calculated layout all the time, so you cannot use display: none to hide it but have to use a different way. This also means that you cannot use v-show for this.

What you could do is simply use CSS transitions and transition between different opacity states:

new Vue({
  el: '#demo',
  data: {
    show: true
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fading-element {
    transition: opacity 2s;
}
.invisible {
    opacity: 0;
}</code>```

  <button v-on:click="show = !show">Toggle</button>

hello

hello

```

Body:
I wanted to slightly expand the basic example for transitions and have an element fading out in one div and at the same time fading in on another:

new Vue({
  el: '#demo',
  data: {
    show: true
  }
})

.fade-enter-active,
.fade-leave-active {
  transition: opacity 2s
}

.fade-enter,
.fade-leave-to {
  opacity: 0
}

  <button v-on:click="show = !show">
    Toggle
  </button>
  <transition name="fade">

hello

  </transition>
  <transition name="fade">

hello

  </transition>

This does not however work as intended: the upper hello fades out and the lower one fades in (so far OK), but then the lower one dissapears and the upper one appears (immediately, as if the state have changed and there were no transitions).

When clicking the button once again, it looks like the transition is correct (it starts with the lower hello fading out and the upper one fading in).

The CSS is symmetrical, the state changes only when pressing the button - so I do not understand the immediate switch after the first transition?

Body:
v-show hides elements by settings the display CSS property as explained by the documentation:

v-show simply toggles the display CSS property of the element.

This has the effect that the element disappears after the transition completes, which is when the display property is set. Elements with display: none are completely hidden without any space occupied for the element.

The effect you see is not symmetrical because when hiding the element, the display property is set when the transition ends, but when showing the element again, it needs to be set when the transition starts (otherwise the transition would be invisible).

If you want to avoid that position change, you will have to keep the element in the calculated layout all the time, so you cannot use display: none to hide it but have to use a different way. This also means that you cannot use v-show for this.

What you could do is simply use CSS transitions and transition between different opacity states:

new Vue({
  el: '#demo',
  data: {
    show: true
  }
})

.fading-element {
    transition: opacity 2s;
}
.invisible {
    opacity: 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<div id="demo">
  <button v-on:click="show = !show">Toggle</button>
  <p :class="['fading-element', { 'invisible': !show }]">hello</p>
  <p :class="['fading-element', { 'invisible': show }]">hello</p>
</div>


问:
Show the table of values under the bar plot
I ask this without find something to try, because I didn't find something same. I apologize for this.

From this bar plot:

```<code>df <- structure(list(year = 2002:2005, work = c(1L, 2L, 3L, 2L), confid = c(8L,
5L, 0L, 6L), jrs = c(0L, 3L, 4L, 5L)), .Names = c("year", "work",
"confid", "jrs"), class = "data.frame", row.names = c(NA, -4L
))

library(ggplot2)
library(reshape)
md <- melt(df, id=(c("year")))
temp.plot <- ggplot(data=md, aes(x=year, y=value, fill=variable) ) +
    geom_bar(stat="identity")+
    theme(axis.text.x=element_text(angle=90))+
    ggtitle("Score Distribtion")

temp.plot
</code>```

I would like to ask if is there any simple way using ggplot2 to have the value under every year as it is in barplot for every variable.
Here a dummy example output:

答:
It might be better to plot the counts within each bar. For example:

```<code>library(ggplot2)
theme_set(theme_classic())

ggplot(data=md, aes(x=year, y=value, fill=variable)) +
  geom_bar(stat="identity") +
  ggtitle("Score Distribution") +
  geom_text(aes(label=value), position=position_stack(vjust=0.5), colour="white") +
  labs(fill="")
</code>```

If you still want a table beneath the plot, I don't know of a simple way, but you can create a separate tableGrob for the table, extract the legend as a separate grob (graphical object), then lay out each part separately. Laying out the various parts requires some tweaking by hand, although someone who understands grid graphics better than I do might be able to automate that. Here's an example:

```<code>library(grid)
library(gridExtra)

# Function to extract legend
# https://stackoverflow.com/a/13650878/496488
g_legend <- function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}

p = ggplot(data=md, aes(x=year, y=value, fill=variable) ) +
  geom_bar(stat="identity")+
  #theme(axis.text.x=element_text(angle=90, vjust=0.5, hjust=0.5))+
  ggtitle("Score Distribution") +
  labs(fill="")

# Extract the legend as a separate grob
leg = g_legend(p)

# Create a table grob
tab = t(df)
tab = tableGrob(tab, rows=NULL)
tab$widths <- unit(rep(1/ncol(tab), ncol(tab)), "npc")

# Lay out plot, legend, and table grob
grid.arrange(arrangeGrob(nullGrob(),
                         p + guides(fill=FALSE) +
                           theme(axis.text.x=element_blank(),
                                 axis.title.x=element_blank(),
                                 axis.ticks.x=element_blank()),
                         widths=c(1,8)),
             arrangeGrob(arrangeGrob(nullGrob(),leg,heights=c(1,10)),
                         tab, nullGrob(), widths=c(6,20,1)),
             heights=c(4,1))
</code>```

Body:
I ask this without find something to try, because I didn't find something same. I apologize for this.

From this bar plot:

df <- structure(list(year = 2002:2005, work = c(1L, 2L, 3L, 2L), confid = c(8L,
5L, 0L, 6L), jrs = c(0L, 3L, 4L, 5L)), .Names = c("year", "work",
"confid", "jrs"), class = "data.frame", row.names = c(NA, -4L
))

library(ggplot2)
library(reshape)
md <- melt(df, id=(c("year")))
temp.plot <- ggplot(data=md, aes(x=year, y=value, fill=variable) ) +
    geom_bar(stat="identity")+
    theme(axis.text.x=element_text(angle=90))+
    ggtitle("Score Distribtion")

temp.plot

I would like to ask if is there any simple way using ggplot2 to have the value under every year as it is in barplot for every variable.
Here a dummy example output:

Body:
It might be better to plot the counts within each bar. For example:

library(ggplot2)
theme_set(theme_classic())

ggplot(data=md, aes(x=year, y=value, fill=variable)) +
  geom_bar(stat="identity") +
  ggtitle("Score Distribution") +
  geom_text(aes(label=value), position=position_stack(vjust=0.5), colour="white") +
  labs(fill="")

If you still want a table beneath the plot, I don't know of a simple way, but you can create a separate tableGrob for the table, extract the legend as a separate grob (graphical object), then lay out each part separately. Laying out the various parts requires some tweaking by hand, although someone who understands grid graphics better than I do might be able to automate that. Here's an example:

library(grid)
library(gridExtra)

# Function to extract legend
# https://stackoverflow.com/a/13650878/496488
g_legend <- function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}

p = ggplot(data=md, aes(x=year, y=value, fill=variable) ) +
  geom_bar(stat="identity")+
  #theme(axis.text.x=element_text(angle=90, vjust=0.5, hjust=0.5))+
  ggtitle("Score Distribution") +
  labs(fill="")

# Extract the legend as a separate grob
leg = g_legend(p)

# Create a table grob
tab = t(df)
tab = tableGrob(tab, rows=NULL)
tab$widths <- unit(rep(1/ncol(tab), ncol(tab)), "npc")

# Lay out plot, legend, and table grob
grid.arrange(arrangeGrob(nullGrob(),
                         p + guides(fill=FALSE) +
                           theme(axis.text.x=element_blank(),
                                 axis.title.x=element_blank(),
                                 axis.ticks.x=element_blank()),
                         widths=c(1,8)),
             arrangeGrob(arrangeGrob(nullGrob(),leg,heights=c(1,10)),
                         tab, nullGrob(), widths=c(6,20,1)),
             heights=c(4,1))


问:
Converting string to valid wordpress url in python 3 to be used by requests library
Given a string  https://websiteurl/path/photo's url.jpeg

How to converted it to legal url https://websiteurl/path/photos-url.jpeg from Wordpress point of view using python3.5. This url is going to be used by sending post request with json where src will be key and value the above legal url.

When the photo was uploaded url https://websiteurl/path/photos-url.jpeg  was given to it. (' removed and space converted to - )

The only way i see is using "https://websiteurl/path/photo's url.jpeg".replace(\',"").replace(" ","-").

Is there any generic pythonic way?

答:
You could use re.sub and str.replace. Example:

```<code>import re

special_chars = ["?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", "%", "+"]
uri = "photo's url.jpeg"

#use str.replace
for i in special_chars:
    uri = uri.replace(i, "")

#or re.sub
#uri = re.sub("\?|\[|\]|/|\\|\=|<|>|:|;|,|'|\"|\&|\$|#|\*|\(|\)|~|`|!|\{|\}|%|\+", "", uri)

uri = re.sub("\s+", "-", uri)
print(uri)
</code>```

This will change photo's url.jpeg into photos-url.jpeg.
Take a look at how wordpress is doing it in php here: https://core.trac.wordpress.org/browser/tags/4.7.3/src/wp-includes/formatting.php#L1761

Body:
You could use re.sub and str.replace. Example:

import re

special_chars = ["?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", "%", "+"]
uri = "photo's url.jpeg"

#use str.replace
for i in special_chars:
    uri = uri.replace(i, "")

#or re.sub
#uri = re.sub("\?|\[|\]|/|\\|\=|<|>|:|;|,|'|\"|\&|\$|#|\*|\(|\)|~|`|!|\{|\}|%|\+", "", uri)

uri = re.sub("\s+", "-", uri)
print(uri)

This will change photo's url.jpeg into photos-url.jpeg.
Take a look at how wordpress is doing it in php here: https://core.trac.wordpress.org/browser/tags/4.7.3/src/wp-includes/formatting.php#L1761


问:
Xcode Build Succeeded but not run on iPhone/Simulator
I am facing a little strange problem with Xcode, that is when I run my app is Xcode shows Succeeded but my app does not run automatically on iPhone or Simulator. I have to manually click on app icon then it runs. I have already tried all the solutions I could find. I have tried the following points:

Adding in armv6

Restarting xcode

Restarting device/simulator

Removing device from the organizer then adding it back.

Restarting Mac Book Pro.

Cleaning project and rebuilding

Check plist

Check target

Check product>edit scheme > select run option (and info tab) ==> all is fine there

Please note I am using these frameworks via pods name are:

```<code>pod 'IQKeyboardManager'
pod 'GooglePlacePicker'
pod 'Firebase/Messaging'
pod 'Google'
pod 'Google/SignIn'
pod 'FBSDKCoreKit'
pod 'FBSDKShareKit'
pod 'FBSDKLoginKit'
</code>```

The app does not run automatically even after Xcode show Build succeeded on simulator/iPhone.

答:
Did you set the initial view controller?
step one.
select the view controller you want to show.
step two.
select the attributes inspector.
step three.
check the is initial view controller.</p>

Body:
I am facing a little strange problem with Xcode, that is when I run my app is Xcode shows Succeeded but my app does not run automatically on iPhone or Simulator. I have to manually click on app icon then it runs. I have already tried all the solutions I could find. I have tried the following points:

Adding in armv6

Restarting xcode

Restarting device/simulator

Removing device from the organizer then adding it back.

Restarting Mac Book Pro.

Cleaning project and rebuilding

Check plist

Check target

Check product>edit scheme > select run option (and info tab) ==> all is fine there

Please note I am using these frameworks via pods name are:

pod 'IQKeyboardManager'
pod 'GooglePlacePicker'
pod 'Firebase/Messaging'
pod 'Google'
pod 'Google/SignIn'
pod 'FBSDKCoreKit'
pod 'FBSDKShareKit'
pod 'FBSDKLoginKit'

The app does not run automatically even after Xcode show Build succeeded on simulator/iPhone.


问:
Using Django authentication system with existing hashed passwords
I have a very old Perl CGI system with a table of users. The passwords are stored as computed hashes using the  crypt function. I am looking to migrate the system to Django, and I would like to keep the user data while using the Django table structure.

One option would be to copy all the user/password data an auth_user table and use a custom authentication function since I have existing password hashes.

Do I have a better option?

If I go with this option then how can it be implemented?

答:
The documentation for writing up a custom authentication backend are in
Customizing authentication in Django

Since Borodin asked and since you might find it handy to have a sample more specific to your request, I went ahead and wrote up an example  that authenticates against a crypt-based file (e.g., htpasswd).

If the backend finds a user with a matching password in the crypt file, it looks for a standard Django user and returns it.  If it can't find one it creates one.  Obviously you would need to decide how you want to handle the actual details of your implementation.

./authbackend/__init__.py

```<code>import crypt
from django.conf import settings
from django.contrib.auth.models import User

class CryptBackend(object):
    def authenticate(self, request, username=None, password=None):
        crypt_file = getattr(settings, "CRYPT_DB", None)
        if crypt_file is None:
            return None

        password_match = False
        with open(crypt_file,"r") as f:
            for line in f:
                (user, crypted_pass) = line.rstrip().split(":")
                if user == username:
                    password_match = crypt.crypt(password, crypted_pass) == crypted_pass
                    break

        if not password_match:
            return None

        # found a match in our crypt database
        try:
            django_user = User.objects.get(username=username)
        except User.DoesNotExist:
            django_user = User.objects.create_user(username=username, email='', password=password)
            django_user.is_staff = True
            django_user.save()

        return django_user

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
</code>```

That new custom backend is loaded based on additions to settings.py.  In my example, I'm keeping the default Django backend and simply adding my new custom one. Django checks them in order, so it will try a standard Django authentication and if that doesn't work moves on to my custom one. The CRYPT_DB parameter is the path to the htpasswd file.

settings.py

```<code>AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'authbackend.CryptBackend',
]

CRYPT_DB = '/path/to/your/passwd.file'
</code>```

And for completeness, an example of the format (htpasswd) that the above is  checking against.

passwd.file

```<code>jill:C.1oP2DOot4MY
jack:qJn7lPS/VNssM
</code>```

Body:
The documentation for writing up a custom authentication backend are in
Customizing authentication in Django

Since Borodin asked and since you might find it handy to have a sample more specific to your request, I went ahead and wrote up an example  that authenticates against a crypt-based file (e.g., htpasswd).

If the backend finds a user with a matching password in the crypt file, it looks for a standard Django user and returns it.  If it can't find one it creates one.  Obviously you would need to decide how you want to handle the actual details of your implementation.

./authbackend/__init__.py

import crypt
from django.conf import settings
from django.contrib.auth.models import User

class CryptBackend(object):
    def authenticate(self, request, username=None, password=None):
        crypt_file = getattr(settings, "CRYPT_DB", None)
        if crypt_file is None:
            return None

        password_match = False
        with open(crypt_file,"r") as f:
            for line in f:
                (user, crypted_pass) = line.rstrip().split(":")
                if user == username:
                    password_match = crypt.crypt(password, crypted_pass) == crypted_pass
                    break

        if not password_match:
            return None

        # found a match in our crypt database
        try:
            django_user = User.objects.get(username=username)
        except User.DoesNotExist:
            django_user = User.objects.create_user(username=username, email='', password=password)
            django_user.is_staff = True
            django_user.save()

        return django_user

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

That new custom backend is loaded based on additions to settings.py.  In my example, I'm keeping the default Django backend and simply adding my new custom one. Django checks them in order, so it will try a standard Django authentication and if that doesn't work moves on to my custom one. The CRYPT_DB parameter is the path to the htpasswd file.

settings.py

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'authbackend.CryptBackend',
]

CRYPT_DB = '/path/to/your/passwd.file'

And for completeness, an example of the format (htpasswd) that the above is  checking against.

passwd.file

jill:C.1oP2DOot4MY
jack:qJn7lPS/VNssM


问:
jQuery value exists in array
I work on a contact form in HTML, PHP and jQuery.

Recently, I try to secure the entire form and, to realise this, I use an array  like this :

```<code>var parameters = [
        {
            'format': 'email',
            'value': 'bernard.dupont@yahoo.fr'
        },
        {
            'format': 'subject',
            'value': 'Hello world'
        },
        {
            'format': 'message',
            'value': 'Good morning !'
        }
    ]`
</code>```

Here is my code :

```<code>function verificationInput(array, format, param, field, length) {
    var test = verificationFormat(format, param, length);

    if (!test) {
        $('#' + field).removeClass('valid').addClass('invalid');
    } else {
        $('#' + field).removeClass('invalid').addClass('valid');
    }

    var added=false;
    $.map(array, function(key, item) {
        if (item.value == param) {
            item.value = param;
            added = true;
        }
    });
    if (!added) {
        array.push({format: format, value: param});
    }
}
</code>```

The idea is to change the value if the format is present and the value if it is present.

答:
Why not use a data structure that is keyed by the format? It would be much easier to work with:

```<code>var parameters = {
    email: 'bernard.dupont@yahoo.fr',
    subject: 'Hello world',
    message: 'Good morning !'
};
</code>```

Then your code could look like this:

```<code>parameters[format] = param;
</code>```

This will add the format if not already present, and otherwise update the value associated with that format.

If you ever need to iterate over the parameters, you can still use $.map.

Title: jQuery value exists in array

Body:
I work on a contact form in HTML, PHP and jQuery.

Recently, I try to secure the entire form and, to realise this, I use an array  like this :

var parameters = [
        {
            'format': 'email',
            'value': 'bernard.dupont@yahoo.fr'
        },
        {
            'format': 'subject',
            'value': 'Hello world'
        },
        {
            'format': 'message',
            'value': 'Good morning !'
        }
    ]`

Here is my code :

function verificationInput(array, format, param, field, length) {
    var test = verificationFormat(format, param, length);

    if (!test) {
        $('#' + field).removeClass('valid').addClass('invalid');
    } else {
        $('#' + field).removeClass('invalid').addClass('valid');
    }

    var added=false;
    $.map(array, function(key, item) {
        if (item.value == param) {
            item.value = param;
            added = true;
        }
    });
    if (!added) {
        array.push({format: format, value: param});
    }
}

The idea is to change the value if the format is present and the value if it is present.

Body:
Why not use a data structure that is keyed by the format? It would be much easier to work with:

var parameters = {
    email: 'bernard.dupont@yahoo.fr',
    subject: 'Hello world',
    message: 'Good morning !'
};

Then your code could look like this:

parameters[format] = param;

This will add the format if not already present, and otherwise update the value associated with that format.

If you ever need to iterate over the parameters, you can still use $.map.


问:
Repeater with HiddenField
I have the following HiddenField within a Repeater labeled "AdminGetAllRPT":

```<code> <asp:Repeater ID="AdminGetAllRPT" runat="server" OnLoad="AdminGetAllRPT_Load">
    <HeaderTemplate>
        <table id="AdminGetAllTBL">
            <tr>
                <td></td>
                <td>Username</td>
                <td>Email Address</td>
                <td>First Name</td>
                <td>Last Name</td>
                <td>Active?</td>
            </tr>
    </HeaderTemplate>
    <ItemTemplate>
       <tr>
           <td>
               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>
           </td>
           <td><%# Eval("userName") %></td>
           <td><%# Eval("emailAddress") %></td>
           <td><%# Eval("firstName") %></td>
           <td><%# Eval("lastName") %></td>
           <td><%# Eval("isActive") %></td>
       </tr>
    </ItemTemplate>
    <AlternatingItemTemplate>
        <tr class="alternateTemplate">
           <td>
               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>
           </td>
           <td><%# Eval("userName") %></td>
           <td><%# Eval("emailAddress") %></td>
           <td><%# Eval("firstName") %></td>
           <td><%# Eval("lastName") %></td>
           <td><%# Eval("isActive") %></td>
       </tr>
    </AlternatingItemTemplate>
    <FooterTemplate>
            <tr>
                <td colspan="2"><a href="#">Add Administrator</a></td>
            </tr>
        </table>
    </FooterTemplate>
</asp:Repeater>
</code>```

I have a linkbutton that fires this code:

```<code>protected void AdminEdit_OnClick(object sender, EventArgs e)
{
    HiddenField hf = (HiddenField)AdminGetAllRPT.FindControl("editAdminEmail");
</code>```

but the hf is coming up null. What am I doing wrong?

答:
As jball has pointed out, you need to search at repeater item level. Where is your link button located? I believe that it should be within repeater it self (otherwise you can have multiple hidden fields (one for each repeater row) and which one is supposed to be picked up by linkbutton?). So if both link button and hidden field are in repeater then you can use code such as</p>

```<code>protected void AdminEdit_OnClick(object sender, EventArgs e)
{
    var repeaterItem = ((Control)sender).NamingContainer;
    HiddenField hf = (HiddenField)repeaterItem.FindControl("editAdminEmail");
</code>```

Title: Repeater with HiddenField

Body:
I have the following HiddenField within a Repeater labeled "AdminGetAllRPT":

 <asp:Repeater ID="AdminGetAllRPT" runat="server" OnLoad="AdminGetAllRPT_Load">
    <HeaderTemplate>

                Username
                Email Address
                First Name
                Last Name
                Active?

    </HeaderTemplate>
    <ItemTemplate>

               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>

           <%# Eval("userName") %>
           <%# Eval("emailAddress") %>
           <%# Eval("firstName") %>
           <%# Eval("lastName") %>
           <%# Eval("isActive") %>

    </ItemTemplate>
    <AlternatingItemTemplate>

               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>

           <%# Eval("userName") %>
           <%# Eval("emailAddress") %>
           <%# Eval("firstName") %>
           <%# Eval("lastName") %>
           <%# Eval("isActive") %>

    </AlternatingItemTemplate>
    <FooterTemplate>

                Add Administrator

    </FooterTemplate>
</asp:Repeater>

I have a linkbutton that fires this code:

protected void AdminEdit_OnClick(object sender, EventArgs e)
{
    HiddenField hf = (HiddenField)AdminGetAllRPT.FindControl("editAdminEmail");

but the hf is coming up null. What am I doing wrong?

Body:
As jball has pointed out, you need to search at repeater item level. Where is your link button located? I believe that it should be within repeater it self (otherwise you can have multiple hidden fields (one for each repeater row) and which one is supposed to be picked up by linkbutton?). So if both link button and hidden field are in repeater then you can use code such as

protected void AdminEdit_OnClick(object sender, EventArgs e)
{
    var repeaterItem = ((Control)sender).NamingContainer;
    HiddenField hf = (HiddenField)repeaterItem.FindControl("editAdminEmail");


问:
Login across two meteor applications with the same database
I have two Meteor applications that share the same database, so they have the same accounts. I want to make it so that when a user login on App1, he will be automatically logged in when he visit App2 as well.

Is this possible? How would you recommend me to do this? Thank you so much!

P.S. The Meteor official guide offers something like this at the "Shared Accounts" of the "Data Structure" section, but when I try it, it does not really work. Is it supposed to work?

答:
Two options (can be used together):

Point both apps to the same MongoDB, via MONGO_URL environment variable

Point clients from both websites to same WebSockets endpoint, via DDP_DEFAULT_CONNECTION_URL environment variable

Example:
Main app:

```<code>ROOT_URL=https://example1.com
DDP_DEFAULT_CONNECTION_URL=https://example1.com
MONGO_URL=mongodb://mongo.example1.com:27000
</code>```

Second app:

```<code>ROOT_URL=https://example2.com
DDP_DEFAULT_CONNECTION_URL=https://example1.com
MONGO_URL=mongodb://mongo.example1.com:27000
</code>```

Body:
Two options (can be used together):

Point both apps to the same MongoDB, via MONGO_URL environment variable

Point clients from both websites to same WebSockets endpoint, via DDP_DEFAULT_CONNECTION_URL environment variable

Example:
Main app:

ROOT_URL=https://example1.com
DDP_DEFAULT_CONNECTION_URL=https://example1.com
MONGO_URL=mongodb://mongo.example1.com:27000

Second app:

ROOT_URL=https://example2.com
DDP_DEFAULT_CONNECTION_URL=https://example1.com
MONGO_URL=mongodb://mongo.example1.com:27000


问:
Why does __mul__() expect integer arguments?
I'm getting TypeError: 'float' object cannot be interpreted as an integer.  It appears __mul__() is expecting an integer only argument.  Did I not define it correctly?

```<code># Running Python 3.6.0
from math import sqrt

class Vector(object):
    def __init__(self, coordinates):
        try:
            self.dimension = len(coordinates)
            if self.dimension < 2 or self.dimension > 3:
                raise ValueError
            self.coordinates = tuple(coordinates)

        except ValueError:
            raise ValueError('Must have at least 2 coordinates and no more than 3. Length = {}'.format(self.dimension))

        except TypeError:
            raise TypeError('The coordinates must be an iterable')

        self.magnitude = sqrt(sum([n ** 2 for n in self.coordinates]))

    # This fails with a type error
    def normalized(self):
        try:
            normalized = self.coordinates.__mul__(1.0 / self.magnitude)
        except ZeroDivisionError:
            raise Exception("Cannot normalize zero vector")
        return normalized

    # This fails with a type error
    # def normalized(self):
    #     try:
    #         normalized = self.coordinates * (1.0 / self.magnitude)
    #     except ZeroDivisionError:
    #         raise Exception("Cannot normalize zero vector")
    #     return normalized

    # This works fine
    # def normalized(self):
    #     try:
    #         normalized = [n / self.magnitude for n in self.coordinates]
    #     except ZeroDivisionError:
    #         raise Exception("Cannot normalize zero vector")
    #     return Vector(normalized)

    def __iter__(self):
        return self.coordinates

    def __mul__(self, scalar):
        # Vector scalar multiplication
        return Vector([e * scalar for e in self.coordinates])

    def __str__(self):
        return 'Vector: {}'.format(self.coordinates)

# Run the test...
if __name__ == "__main__":
    v1 = Vector([1.996, 3.108, -4.554])
    print(v1)
    print(v1.normalized())
</code>```

EDIT:

Now that I understand what happened I'd like to clarify the answer for anyone who might run into this in the future.

The problem was here:

```<code>normalized = self.coordinates.__mul__(1.0 / self.magnitude)
</code>```

Which, for the purpose of this explanation simplifies to:

```<code>a = b.__mul__(c)
</code>```

or

```<code>a = b * c
</code>```

Here b is a tuple and c is a number, a real number.

In Python

```<code>(1, 2) * 3
</code>```

results in

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

In other words the * operator applied to a tuple results in the replication of that tuple N times.

Which also means we can't multiply a tuple by a float, it makes no sense.  Hence the error:

```<code>TypeError: 'float' object cannot be interpreted as an integer
</code>```

Makes sense.

My error was in that I multiplied the tuple by self.magnitude rather than to multiply my Vector object by self.magnitude, like this:

```<code>normalized = self.__mul__(1.0 / self.magnitude)
</code>```

Given my definition of __mul__() this makes sense and works fine.  And this works too:

```<code>normalized = self * (1.0 / self.magnitude)
</code>```

答:
__mul__ applied to a tuple (like your coordinates) duplicates the contents of the tuple to increase its length, and hence only makes sense with an integer.

You're trying to multiply eavh element of an array by a number. If you make coordinates a numpy array then the multiplication operator will do this correctly. If you want to keep coordinates as a tuple then you will need to iterate through it multiplying each element individually (e.g. like in the __mul__ function you define for your vector class).

Personally I recommend using numpy arrays if possible - they'll make a lot of the maths you're doing quicker and easier if used well.

Body:
I'm getting TypeError: 'float' object cannot be interpreted as an integer.  It appears __mul__() is expecting an integer only argument.  Did I not define it correctly?

# Running Python 3.6.0
from math import sqrt

class Vector(object):
    def __init__(self, coordinates):
        try:
            self.dimension = len(coordinates)
            if self.dimension < 2 or self.dimension > 3:
                raise ValueError
            self.coordinates = tuple(coordinates)

        except ValueError:
            raise ValueError('Must have at least 2 coordinates and no more than 3. Length = {}'.format(self.dimension))

        except TypeError:
            raise TypeError('The coordinates must be an iterable')

        self.magnitude = sqrt(sum([n ** 2 for n in self.coordinates]))

    # This fails with a type error
    def normalized(self):
        try:
            normalized = self.coordinates.__mul__(1.0 / self.magnitude)
        except ZeroDivisionError:
            raise Exception("Cannot normalize zero vector")
        return normalized

    # This fails with a type error
    # def normalized(self):
    #     try:
    #         normalized = self.coordinates * (1.0 / self.magnitude)
    #     except ZeroDivisionError:
    #         raise Exception("Cannot normalize zero vector")
    #     return normalized

    # This works fine
    # def normalized(self):
    #     try:
    #         normalized = [n / self.magnitude for n in self.coordinates]
    #     except ZeroDivisionError:
    #         raise Exception("Cannot normalize zero vector")
    #     return Vector(normalized)

    def __iter__(self):
        return self.coordinates

    def __mul__(self, scalar):
        # Vector scalar multiplication
        return Vector([e * scalar for e in self.coordinates])

    def __str__(self):
        return 'Vector: {}'.format(self.coordinates)

# Run the test...
if __name__ == "__main__":
    v1 = Vector([1.996, 3.108, -4.554])
    print(v1)
    print(v1.normalized())

EDIT:

Now that I understand what happened I'd like to clarify the answer for anyone who might run into this in the future.

The problem was here:

normalized = self.coordinates.__mul__(1.0 / self.magnitude)

Which, for the purpose of this explanation simplifies to:

a = b.__mul__(c)

or

a = b * c

Here b is a tuple and c is a number, a real number.

In Python

(1, 2) * 3

results in

(1, 2, 1, 2, 1, 2)

In other words the * operator applied to a tuple results in the replication of that tuple N times.

Which also means we can't multiply a tuple by a float, it makes no sense.  Hence the error:

TypeError: 'float' object cannot be interpreted as an integer

Makes sense.

My error was in that I multiplied the tuple by self.magnitude rather than to multiply my Vector object by self.magnitude, like this:

normalized = self.__mul__(1.0 / self.magnitude)

Given my definition of __mul__() this makes sense and works fine.  And this works too:

normalized = self * (1.0 / self.magnitude)


问:
Animate splitpane divider
I have a horizontal split pane, and i would like to on button click, change divider position, so that i create sort of "slide" animation.

divider would start at 0 (complete left) and on my click it would open till 0.2, when i click again, it would go back to 0;

now i achived this, i just use

```<code>spane.setdividerPositions(0.2);
</code>```

and divider position changes, but i cant manage to do this slowly i would really like that slide feeling when changing divider position.

Could anyone help me ? all examples i found on google, show some DoubleTransition, but that does not exist anymore in java 8, at least i dont have import for that.

答:
You can call getDividers().get(0) to get the first divider. It has a positionProperty() that you can animate using a timeline:

```<code>import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.util.Duration;

public class AnimatedSplitPane extends Application {

    @Override
    public void start(Stage primaryStage) {
        SplitPane splitPane = new SplitPane(new Pane(), new Pane());
        splitPane.setDividerPositions(0);

        BooleanProperty collapsed = new SimpleBooleanProperty();
        collapsed.bind(splitPane.getDividers().get(0).positionProperty().isEqualTo(0, 0.01));

        Button button = new Button();
        button.textProperty().bind(Bindings.when(collapsed).then("Expand").otherwise("Collapse"));

        button.setOnAction(e -> {
            double target = collapsed.get() ? 0.2 : 0.0 ;
            KeyValue keyValue = new KeyValue(splitPane.getDividers().get(0).positionProperty(), target);
            Timeline timeline = new Timeline(new KeyFrame(Duration.millis(500), keyValue));
            timeline.play();
        });

        HBox controls = new HBox(button);
        controls.setAlignment(Pos.CENTER);
        controls.setPadding(new Insets(5));
        BorderPane root = new BorderPane(splitPane);
        root.setBottom(controls);
        Scene scene = new Scene(root, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Title: Animate splitpane divider

Body:
I have a horizontal split pane, and i would like to on button click, change divider position, so that i create sort of "slide" animation.

divider would start at 0 (complete left) and on my click it would open till 0.2, when i click again, it would go back to 0;

now i achived this, i just use

spane.setdividerPositions(0.2);

and divider position changes, but i cant manage to do this slowly i would really like that slide feeling when changing divider position.

Could anyone help me ? all examples i found on google, show some DoubleTransition, but that does not exist anymore in java 8, at least i dont have import for that.

Body:
You can call getDividers().get(0) to get the first divider. It has a positionProperty() that you can animate using a timeline:

import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.util.Duration;

public class AnimatedSplitPane extends Application {

    @Override
    public void start(Stage primaryStage) {
        SplitPane splitPane = new SplitPane(new Pane(), new Pane());
        splitPane.setDividerPositions(0);

        BooleanProperty collapsed = new SimpleBooleanProperty();
        collapsed.bind(splitPane.getDividers().get(0).positionProperty().isEqualTo(0, 0.01));

        Button button = new Button();
        button.textProperty().bind(Bindings.when(collapsed).then("Expand").otherwise("Collapse"));

        button.setOnAction(e -> {
            double target = collapsed.get() ? 0.2 : 0.0 ;
            KeyValue keyValue = new KeyValue(splitPane.getDividers().get(0).positionProperty(), target);
            Timeline timeline = new Timeline(new KeyFrame(Duration.millis(500), keyValue));
            timeline.play();
        });

        HBox controls = new HBox(button);
        controls.setAlignment(Pos.CENTER);
        controls.setPadding(new Insets(5));
        BorderPane root = new BorderPane(splitPane);
        root.setBottom(controls);
        Scene scene = new Scene(root, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
}


问:
Java Multithreading example
I'm a Java student and this is my attempt of implementing a StackExchange (there's a pusher thread and a popper thread, a single stack resource and two controlling Threads for the stack content and time passing).

I was hoping if someone could comment my code for improvements or errors\bad practices, even if the code seems to work.

The main reason of this program was to figure out how to control resource access in a multithreading environment.

I have concerns about the use of the ScheduledThreadPoolExecutor rather than locking(the stack), and my usage of synchronized in the StackExchange class methods(for accessing the stack), I would like to spawn free threads working on a dynamically locked resource. Any advice?

NB:"Format of magic numbers and syso's may be awful for testing porpuses

code here:

```<code>package examples;

import java.util.Random;

import java.util.Stack;

import java.util.concurrent.ScheduledThreadPoolExecutor;

import java.util.concurrent.TimeUnit;

import javax.swing.JOptionPane;

public class StackExchange {

    /*
     * Two Threads playing with a stack, a timer and a controller for the stack that permits to exit
     * */
    public class Popper implements Runnable
    {
        StackExchange sEx;
        public Popper(StackExchange sex)
        {
            this.sEx=sex;

        }
        @Override
        public void run() {
            System.out.println("Popper: popping!\t"+sEx.getPeek());
            sEx.callTheStack(this, null);
        }
    }
    public class Pusher implements Runnable
    {
        StackExchange sEx;
        public Pusher(StackExchange sex)
        {
            sEx=sex;
        }
        @Override
        public void run() {
            System.out.println("Pusher: pushing!\t");
            sEx.callTheStack(this, "Hi!");
        }
    }
    public class StackController implements Runnable
    {
        private Stack<String> theStack;
        public int waiting=5;
        public StackController(Stack<String> theStack, String name) {
            this.theStack =  theStack;
            Thread.currentThread().setName(name);
        }
        @Override
        public void run()
        {
            Random rand = new Random();
            waiting = rand.nextInt(10);
            StringBuilder buffer = new StringBuilder();
            int i=0;
            for(String string: theStack)
            {
                buffer.append(string+"\n");
                i++;
            }
            buffer.append("\nFound "+i+" elements\nIWillWait4:\t"+waiting);

            System.out.println("\t\t\t\t\t\t\t\t"+Thread.currentThread().getName().toString()+" Says:" + buffer.toString());
            if(i>1)
            {
                System.out.println("ERRER");
                System.exit(0);
            }
            if(i==1 && JOptionPane.showConfirmDialog(null,  "found 1 element\nWannaStop?")==0)
                System.exit(0);

        }
    }
    public class Timer implements Runnable{

        @Override
        public void run() {
            StackExchange.time++;
            System.out.println("Time Passed:\t"+StackExchange.time+" seconds");
        }

    }
    /*
     * implementation of the StackExchange class
     * */
    private Popper popper;
    private Pusher pusher;
    private StackController stackController;
    private StackController secondSC;
    private Timer timer;

    static int time=0;

    private Stack<String> stack;

    public StackExchange()
    {
        timer = new Timer();
        stack = new Stack<String>();
        pusher = new Pusher(this);
        popper = new Popper(this);
        stackController = new StackController(this.getStack(), "FirstStackController");
    }
    public static void main(String[] args) {
        StackExchange sex = new StackExchange();
        sex.start();
        System.out.println("Num of Threads:"+Thread.activeCount());
    }
    public void start()
    {
        ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(5);
        exec.scheduleAtFixedRate(timer, 0, 1, TimeUnit.SECONDS);
        exec.scheduleAtFixedRate(pusher, 0, 2, TimeUnit.SECONDS);
        exec.scheduleAtFixedRate(popper, 1, 2, TimeUnit.SECONDS);
        exec.scheduleAtFixedRate(stackController, 0, stackController.waiting, TimeUnit.SECONDS);
    }
    public Stack<String >getStack()
    {
        return this.stack;
    }
    public void callTheStack(Object caller, String pushedString)
    {
        synchronized(this)
        {
            if(caller instanceof Popper)
                stack.pop();

            else if(caller instanceof Pusher)
                stack.push(pushedString);
        }
    }
    public String getPeek()
    {
        synchronized(this)
        {
            return stack.peek();
        }
    }
}
</code>```

答:
Things that might help:

Don't use java.util.Stack.

A more complete and consistent set of LIFO stack operations is
  provided by the Deque interface and its implementations, which should
  be used in preference to this class.
  http://docs.oracle.com/javase/8/docs/api/java/util/Stack.html

Your nested subclasses of StackExchange are all inner classes so
that means they already have a reference to the containing
StackExchange instance

and its member stack instance, which should be final.

So don't pass them as parameters. This simplifies logic, maintenance,
and GC.

caller instanceof Popper this type of reflection is utterly
unnecessary and breaks object orientation.

You know that Object is too broad a type for callTheStack (weak
name). In fact, you know that the object will be a Runnable, but
more importantly, the Runnable should know what to do already.

Synchronization should be kept minimal to just the critical section that shares data and no more, shown below using the synchronized keyword

or to just the memory boundary, shown below using the volatile keyword

and member variables of a containing class are a great way to share data between threads within the class.

Example

```<code>public class StackExchange {

private final Deque<String> stack = new ArrayDeque<>();
private volatile boolean running;

private void consume(String item) {
  // ...
}

private String obtain() {
  // ...
}

private boolean getPermission() {
  // ...
}

// getters, setters, ...

private final Runnable consumer = new Runnable() {
  @Override
  public void run() {
    while (running) {
      final String popped;
      synchronized(stack) {
        popped = stack.pollFirst();
      }
      consume(popped);
    }
  }
};

private final Runnable producer = new Runnable() {
  @Override
  public void run() {
   while (running) {
     final String pushing = obtain();
      synchronized(stack) {
        stack.offerFirst(pushing);
      }
    }
  }
};

public static void main(String ... args) {
  StackExchange exchange = new StackExchange();

  exchange.setRunning(true);
  new Thread(exchange.getConsumer()).start();
  new Thread(exchange.getProducer()).start();

  do  {
  } while (exchange.getPermission());

  exchange.setRunning(false);
}
}
</code>```

It's a good idea to declare member variables prior to member methods.

I put the Runnable code in anonymous classes to leave the code at the very edge of using lambdas.

The idea behind consume, obtain, and getPermission is to hint at how the code would interact with the business logic that doesn't know about threading. These could be implemented as callbacks or abstract methods.

One good thing about Deque is that it can easily be set up for a FIFO queue.

Just for fun, convert those Runnable instances into lambdas, and make the StackExchange class generic.

Hot question: what other subtypes of Deque<E> might suit, and what advantages or disadvantages would they have? What code changes might need to happen to accommodate them?

Title: Java Multithreading example

Body:
I'm a Java student and this is my attempt of implementing a StackExchange (there's a pusher thread and a popper thread, a single stack resource and two controlling Threads for the stack content and time passing).

I was hoping if someone could comment my code for improvements or errors\bad practices, even if the code seems to work.

The main reason of this program was to figure out how to control resource access in a multithreading environment.

I have concerns about the use of the ScheduledThreadPoolExecutor rather than locking(the stack), and my usage of synchronized in the StackExchange class methods(for accessing the stack), I would like to spawn free threads working on a dynamically locked resource. Any advice?

NB:"Format of magic numbers and syso's may be awful for testing porpuses

code here:

package examples;

import java.util.Random;

import java.util.Stack;

import java.util.concurrent.ScheduledThreadPoolExecutor;

import java.util.concurrent.TimeUnit;

import javax.swing.JOptionPane;

public class StackExchange {

    /*
     * Two Threads playing with a stack, a timer and a controller for the stack that permits to exit
     * */
    public class Popper implements Runnable
    {
        StackExchange sEx;
        public Popper(StackExchange sex)
        {
            this.sEx=sex;

        }
        @Override
        public void run() {
            System.out.println("Popper: popping!\t"+sEx.getPeek());
            sEx.callTheStack(this, null);
        }
    }
    public class Pusher implements Runnable
    {
        StackExchange sEx;
        public Pusher(StackExchange sex)
        {
            sEx=sex;
        }
        @Override
        public void run() {
            System.out.println("Pusher: pushing!\t");
            sEx.callTheStack(this, "Hi!");
        }
    }
    public class StackController implements Runnable
    {
        private Stack<String> theStack;
        public int waiting=5;
        public StackController(Stack<String> theStack, String name) {
            this.theStack =  theStack;
            Thread.currentThread().setName(name);
        }
        @Override
        public void run()
        {
            Random rand = new Random();
            waiting = rand.nextInt(10);
            StringBuilder buffer = new StringBuilder();
            int i=0;
            for(String string: theStack)
            {
                buffer.append(string+"\n");
                i++;
            }
            buffer.append("\nFound "+i+" elements\nIWillWait4:\t"+waiting);

            System.out.println("\t\t\t\t\t\t\t\t"+Thread.currentThread().getName().toString()+" Says:" + buffer.toString());
            if(i>1)
            {
                System.out.println("ERRER");
                System.exit(0);
            }
            if(i==1 && JOptionPane.showConfirmDialog(null,  "found 1 element\nWannaStop?")==0)
                System.exit(0);

        }
    }
    public class Timer implements Runnable{

        @Override
        public void run() {
            StackExchange.time++;
            System.out.println("Time Passed:\t"+StackExchange.time+" seconds");
        }

    }
    /*
     * implementation of the StackExchange class
     * */
    private Popper popper;
    private Pusher pusher;
    private StackController stackController;
    private StackController secondSC;
    private Timer timer;

    static int time=0;

    private Stack<String> stack;

    public StackExchange()
    {
        timer = new Timer();
        stack = new Stack<String>();
        pusher = new Pusher(this);
        popper = new Popper(this);
        stackController = new StackController(this.getStack(), "FirstStackController");
    }
    public static void main(String[] args) {
        StackExchange sex = new StackExchange();
        sex.start();
        System.out.println("Num of Threads:"+Thread.activeCount());
    }
    public void start()
    {
        ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(5);
        exec.scheduleAtFixedRate(timer, 0, 1, TimeUnit.SECONDS);
        exec.scheduleAtFixedRate(pusher, 0, 2, TimeUnit.SECONDS);
        exec.scheduleAtFixedRate(popper, 1, 2, TimeUnit.SECONDS);
        exec.scheduleAtFixedRate(stackController, 0, stackController.waiting, TimeUnit.SECONDS);
    }
    public Stack<String >getStack()
    {
        return this.stack;
    }
    public void callTheStack(Object caller, String pushedString)
    {
        synchronized(this)
        {
            if(caller instanceof Popper)
                stack.pop();

            else if(caller instanceof Pusher)
                stack.push(pushedString);
        }
    }
    public String getPeek()
    {
        synchronized(this)
        {
            return stack.peek();
        }
    }
}

Body:
Things that might help:

Don't use java.util.Stack.

A more complete and consistent set of LIFO stack operations is
  provided by the Deque interface and its implementations, which should
  be used in preference to this class.
  http://docs.oracle.com/javase/8/docs/api/java/util/Stack.html

Your nested subclasses of StackExchange are all inner classes so
that means they already have a reference to the containing
StackExchange instance

and its member stack instance, which should be final.

So don't pass them as parameters. This simplifies logic, maintenance,
and GC.

caller instanceof Popper this type of reflection is utterly
unnecessary and breaks object orientation.

You know that Object is too broad a type for callTheStack (weak
name). In fact, you know that the object will be a Runnable, but
more importantly, the Runnable should know what to do already.

Synchronization should be kept minimal to just the critical section that shares data and no more, shown below using the synchronized keyword

or to just the memory boundary, shown below using the volatile keyword

and member variables of a containing class are a great way to share data between threads within the class.

Example

public class StackExchange {

private final Deque<String> stack = new ArrayDeque<>();
private volatile boolean running;

private void consume(String item) {
  // ...
}

private String obtain() {
  // ...
}

private boolean getPermission() {
  // ...
}

// getters, setters, ...

private final Runnable consumer = new Runnable() {
  @Override
  public void run() {
    while (running) {
      final String popped;
      synchronized(stack) {
        popped = stack.pollFirst();
      }
      consume(popped);
    }
  }
};

private final Runnable producer = new Runnable() {
  @Override
  public void run() {
   while (running) {
     final String pushing = obtain();
      synchronized(stack) {
        stack.offerFirst(pushing);
      }
    }
  }
};

public static void main(String ... args) {
  StackExchange exchange = new StackExchange();

  exchange.setRunning(true);
  new Thread(exchange.getConsumer()).start();
  new Thread(exchange.getProducer()).start();

  do  {
  } while (exchange.getPermission());

  exchange.setRunning(false);
}
}

It's a good idea to declare member variables prior to member methods.

I put the Runnable code in anonymous classes to leave the code at the very edge of using lambdas.

The idea behind consume, obtain, and getPermission is to hint at how the code would interact with the business logic that doesn't know about threading. These could be implemented as callbacks or abstract methods.

One good thing about Deque is that it can easily be set up for a FIFO queue.

Just for fun, convert those Runnable instances into lambdas, and make the StackExchange class generic.

Hot question: what other subtypes of Deque<E> might suit, and what advantages or disadvantages would they have? What code changes might need to happen to accommodate them?


问:
How to install Grails plugin from source code?
I got a source code of the plugin from a friend, but still don't know how to install it into my project. Yes, there's install-plugin command, but this plugin isn't allowed to upload to the root grails plugin directory.

How can I install grails plugin from the source code?

UPDATE: the plugin is developed for Grails 1.1, but my current project is Grails 1.3. Can it cause any problem?

答:
You can package the plugin into a zip, and install from that.

Open a command prompt in the root directory containing the plugin source and run grails package-plugin with GRAILS_HOME set to a 1.1 Grails installation and $GRAILS_HOME/bin in your PATH. This will create a zip file, e.g. grails-myplugin-0.1.zip. To install it, run grails install-plugin /path/to/grails-myplugin-0.1.zip in the containing application (using 1.3).

You will probably not have any issues installing a 1.1 plugin in a 1.3 application, but you might want to upgrade if there are issues, or to take advantage of the features of the more recent versions of Groovy and Grails.

My process for upgrading plugins or applications with a large gap in versions like this is to not run grails upgrade - that's best for smaller version deltas, e.g. to upgrade from 1.3.1 to 1.3.5.

Instead what I suggest is to create a new empty plugin in 1.1. Either manually or using a directory-diff tool, find all of the deleted, added, and modified files in the plugin by diffing the current plugin with the empty one. Then create a new empty plugin using Grails 1.3.x. Move over the new files, delete the deleted files, and make the corresponding changes in the edited files.

The edited files will mostly be under grails-app/conf, so you need to be a little careful there since some things have changed. But in general it should be safe to apply most or all of the changes.


问:
jQuery add class to 6 random elements with class
I have 12 elements with class "block" and I need to add class "active" to 6 of 12 elements (randomly).

I think using for loop would to the trick but I am not sure how to do it. Maybe somebody can help me out?

```<code>for (var i = 0; i < 6; i++) {

    var random = Math.floor(Math.random() * 1000);
    block.eq(random % block.length).addClass("active");

}
</code>```

This code adds class, but it's not 6 elements every time.. Need a solution to add "active" class to 6 elements every time. Now sometimes it's 6, sometime less..

答:
you can select all elements first and by random function chose any six of them and add class active to them</p>

```<code>var elements = document.getElementsByName(elementname);

for(var i =0; i<6 ; i++)
 var random = Math.floor((Math.random() * 11) + 1);
 element[random].className += "active";
</code>```

Body:
I have 12 elements with class "block" and I need to add class "active" to 6 of 12 elements (randomly).

I think using for loop would to the trick but I am not sure how to do it. Maybe somebody can help me out?

for (var i = 0; i < 6; i++) {

    var random = Math.floor(Math.random() * 1000);
    block.eq(random % block.length).addClass("active");

}

This code adds class, but it's not 6 elements every time.. Need a solution to add "active" class to 6 elements every time. Now sometimes it's 6, sometime less..

Body:
you can select all elements first and by random function chose any six of them and add class active to them

var elements = document.getElementsByName(elementname);

for(var i =0; i<6 ; i++)
 var random = Math.floor((Math.random() * 11) + 1);
 element[random].className += "active";


问:
Bookshelf.js, query on related table
I have a model similar to the following:

```<code>var ScholarlyPaper = Bookshelf.Model.extend({

  tableName: 'papers',

  paragraphs: function() {
    return this.hasMany(Paragraph).through(Section);
  },

  sections: function() {
    return this.hasMany(Section);
  }

});

var Section = Bookshelf.Model.extend({

  tableName: 'sections',

  paragraphs: function() {
    return this.hasMany(Paragraph);
  }

  scholarlyPaper: function() {
    return this.belongsTo(ScholarlyPaper);
  }

});

var Paragraph = Bookshelf.Model.extend({

  tableName: 'paragraphs',

  section: function() {
    return this.belongsTo(Section);
  },

  scholarlyPaper: function() {
    return this.belongsTo(ScholarlyPaper).through(Section);
  },

  author: function() {
    return this.belongsTo(Author);
  }

});

var Author = Bookshelf.Model.extend({

  tableName: 'authors',

  paragraphs: function() {
    return this.hasMany(Paragraph);
  }

});
</code>```

Using Bookshelf.js, given a scholarlyPaper id and author id, how can I get all of the sections in the paper that the author did not write a single paragraph in?

The particular challenge I am facing is that there is no way that I am aware of to add a where clause on a related table (e.g 'where paragraphs.author_id != author_id).

答:
Check out the bookshelf-eloquent extension. The whereHas() and with() functions are probably what you are looking for. Your function would look something like this:</p>

```<code>async function(authorId, paperId) {
    return await ScholarlyPaper.where('id', paperId)
        .with('sections', (q) {
            // Filter out sections in the paper that the author did not write a single paragraph in.
            q.whereHas('paragraphs', (q) => {
                q.where('author_id', authorId);
            }, '<=', 0);
        }).first();
}
</code>```

Title: Bookshelf.js, query on related table

Body:
I have a model similar to the following:

var ScholarlyPaper = Bookshelf.Model.extend({

  tableName: 'papers',

  paragraphs: function() {
    return this.hasMany(Paragraph).through(Section);
  },

  sections: function() {
    return this.hasMany(Section);
  }

});

var Section = Bookshelf.Model.extend({

  tableName: 'sections',

  paragraphs: function() {
    return this.hasMany(Paragraph);
  }

  scholarlyPaper: function() {
    return this.belongsTo(ScholarlyPaper);
  }

});

var Paragraph = Bookshelf.Model.extend({

  tableName: 'paragraphs',

  section: function() {
    return this.belongsTo(Section);
  },

  scholarlyPaper: function() {
    return this.belongsTo(ScholarlyPaper).through(Section);
  },

  author: function() {
    return this.belongsTo(Author);
  }

});

var Author = Bookshelf.Model.extend({

  tableName: 'authors',

  paragraphs: function() {
    return this.hasMany(Paragraph);
  }

});

Using Bookshelf.js, given a scholarlyPaper id and author id, how can I get all of the sections in the paper that the author did not write a single paragraph in?

The particular challenge I am facing is that there is no way that I am aware of to add a where clause on a related table (e.g 'where paragraphs.author_id != author_id).

Body:
Check out the bookshelf-eloquent extension. The whereHas() and with() functions are probably what you are looking for. Your function would look something like this:

async function(authorId, paperId) {
    return await ScholarlyPaper.where('id', paperId)
        .with('sections', (q) {
            // Filter out sections in the paper that the author did not write a single paragraph in.
            q.whereHas('paragraphs', (q) => {
                q.where('author_id', authorId);
            }, '<=', 0);
        }).first();
}