问:
Formatted Sub string
I am using C# and have a string with document name:

```<code>string docName = "email notification 4926-0538-5751 v.11.docx"
</code>```

Here is how it was formated originally:

```<code>"Doc_Name Doc_Number v.version_Number.doc_extension"
</code>```

Trying to find how should I get sub string from this string like this:

```<code>string formateddocNumber = "4826-0718-5751 v.11"
</code>```

I feel like I have to use some sort of regular expression. But not sure.

In case this helps, the doc_number is always this format:

```<code>1234-1234-1234
</code>```

And always have version in this format:

```<code>v.some_number
</code>```

I can not use docx to match for regex as the extension could be doc or txt or something.

答:
Regex is pretty straightforward:</p>

```<code>string docName = "email notification 4926-0538-5751 v.11.docx";
var regex = new Regex(@"^.+ (\d{4}-\d{4}-\d{4} .+?)\.[^.]+$");
var match = regex.Match(docName);
if (match.Success)
{
    Console.WriteLine(match.Groups[1].Value);
}
</code>```

Title: Formatted Sub string

Body:
I am using C# and have a string with document name:

string docName = "email notification 4926-0538-5751 v.11.docx"

Here is how it was formated originally:

"Doc_Name Doc_Number v.version_Number.doc_extension"

Trying to find how should I get sub string from this string like this:

string formateddocNumber = "4826-0718-5751 v.11"

I feel like I have to use some sort of regular expression. But not sure.

In case this helps, the doc_number is always this format:

1234-1234-1234

And always have version in this format:

v.some_number

I can not use docx to match for regex as the extension could be doc or txt or something.

Body:
Regex is pretty straightforward:

string docName = "email notification 4926-0538-5751 v.11.docx";
var regex = new Regex(@"^.+ (\d{4}-\d{4}-\d{4} .+?)\.[^.]+$");
var match = regex.Match(docName);
if (match.Success)
{
    Console.WriteLine(match.Groups[1].Value);
}


来源: stackexchange

问:
unity fuction don't work in client
I am trying to make a construction system like in survival games that works in multiplayer. Here is the code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class CreationSystem : NetworkBehaviour {

public static GameObject SelectedObeject;

bool Preview;
GameObject X;
Material normal;

[SerializeField]
Material previewMaterial;

void Update(){
    Cmd_Creation ();
}

[Command]
void Cmd_Creation() {

    if(Preview == false && MainMenu.GoPreview && SelectedObeject != null){

        RaycastHit rh;
        if(Physics.Raycast(transform.GetChild(0).position,transform.GetChild(0).forward,out rh,60)){

            X = (GameObject)Instantiate (SelectedObeject, rh.point, SelectedObeject.transform.rotation);
            normal = X.GetComponent<Renderer> ().material;
            X.GetComponent<Renderer> ().material = previewMaterial;
            X.GetComponent<Collider> ().enabled = false;

            if(X.transform.childCount > 0){
                for(int i=0; i<X.transform.childCount;i++){
                    X.transform.GetChild(i).GetComponent<Renderer> ().material = previewMaterial;
                    X.transform.GetChild(i).GetComponent<Collider> ().enabled = false;
                }
            }

            NetworkServer.Spawn (X);
            Preview = true;
        }

    }

    if(Preview){
        RaycastHit rh;

        if(Physics.Raycast(transform.GetChild(0).position,transform.GetChild(0).forward,out rh,60)){
            X.transform.position = rh.point;
        }

        if(Input.GetKeyDown(KeyCode.Mouse0)){
            MainMenu.GoPreview = false;
            X.GetComponent<Renderer> ().material = normal;
            X.GetComponent<Collider> ().enabled = true;

            Preview = false;

            if(X.transform.childCount > 0){
                for(int i=0; i<X.transform.childCount;i++){
                    X.transform.GetChild(i).GetComponent<Renderer> ().material = normal;
                    X.transform.GetChild(i).GetComponent<Collider> ().enabled = true;
                }
            }
        }

    }

}
</code>```

It was to work in this way: the player select an object in the menu, that way the variable "SelectedObeject" is changed to the selected object. After the object be selected the preview will starts and if the player click the left mouse button the preview will end and the object will be "Created".

The host can construct with no problem. But the client isn't calling the function "Cmd_Creation()".

答:
Commands are invoked on client but executed on server. If you need the server to communicate to client whatever happened due to previous command then you could use Remote Procedure Call or RPC.</p>

```<code>// invoked on client but executed on server
[Command]
private void CmdMakeServerSayHelloToClient()
{
    RpcSayHelloToClient(); // invoked on server but executed on client
}

[ClientRpc]
private void RpcSayHelloToClient()
{
    Debug.Log("Hello from server."); // logged on client but not on server
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: unity fuction don't work in client

Body:
I am trying to make a construction system like in survival games that works in multiplayer. Here is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class CreationSystem : NetworkBehaviour {

public static GameObject SelectedObeject;

bool Preview;
GameObject X;
Material normal;

[SerializeField]
Material previewMaterial;

void Update(){
    Cmd_Creation ();
}

[Command]
void Cmd_Creation() {

    if(Preview == false && MainMenu.GoPreview && SelectedObeject != null){

        RaycastHit rh;
        if(Physics.Raycast(transform.GetChild(0).position,transform.GetChild(0).forward,out rh,60)){

            X = (GameObject)Instantiate (SelectedObeject, rh.point, SelectedObeject.transform.rotation);
            normal = X.GetComponent<Renderer> ().material;
            X.GetComponent<Renderer> ().material = previewMaterial;
            X.GetComponent<Collider> ().enabled = false;

            if(X.transform.childCount > 0){
                for(int i=0; i<X.transform.childCount;i++){
                    X.transform.GetChild(i).GetComponent<Renderer> ().material = previewMaterial;
                    X.transform.GetChild(i).GetComponent<Collider> ().enabled = false;
                }
            }

            NetworkServer.Spawn (X);
            Preview = true;
        }

    }

    if(Preview){
        RaycastHit rh;

        if(Physics.Raycast(transform.GetChild(0).position,transform.GetChild(0).forward,out rh,60)){
            X.transform.position = rh.point;
        }

        if(Input.GetKeyDown(KeyCode.Mouse0)){
            MainMenu.GoPreview = false;
            X.GetComponent<Renderer> ().material = normal;
            X.GetComponent<Collider> ().enabled = true;

            Preview = false;

            if(X.transform.childCount > 0){
                for(int i=0; i<X.transform.childCount;i++){
                    X.transform.GetChild(i).GetComponent<Renderer> ().material = normal;
                    X.transform.GetChild(i).GetComponent<Collider> ().enabled = true;
                }
            }
        }

    }

}

It was to work in this way: the player select an object in the menu, that way the variable "SelectedObeject" is changed to the selected object. After the object be selected the preview will starts and if the player click the left mouse button the preview will end and the object will be "Created".

The host can construct with no problem. But the client isn't calling the function "Cmd_Creation()".

Body:
Commands are invoked on client but executed on server. If you need the server to communicate to client whatever happened due to previous command then you could use Remote Procedure Call or RPC.

// invoked on client but executed on server
[Command]
private void CmdMakeServerSayHelloToClient()
{
    RpcSayHelloToClient(); // invoked on server but executed on client
}

[ClientRpc]
private void RpcSayHelloToClient()
{
    Debug.Log("Hello from server."); // logged on client but not on server
}


问:
Tkinter : I need to stop generating this "main" function called "pyrotechnik" when i press any button
Hi guys I'm new to programming and I'm working with python at school.
Currently I'm working with tkinter and I have a little problem with this exercise.
Timer starts at 60, when it hits 0, it "explodes". If i click the right wire, it will tell me i've made it but if i click the wrong one it "explodes". The problem is, when i click any button it keeps generating the main function and I have no idea how to stop it. I hope someone can help me :)</p>

```<code>import tkinter
from random import *
canvas = tkinter.Canvas(bg='White', width=400, height=200)
canvas.pack()

stop = randint(1, 4)
timer = 61

def pyrotechnik():
    global timer, stop
    canvas.delete('all')
    timer -= 1
    canvas.create_text(200, 100, font='Arial 20 bold', text=timer, fill='Red')
    if timer == 0:
        canvas.delete('all')
        canvas.create_text(200, 100, font='Arial 20 bold', text='Bomb has exploded', fill='Red')
    else:
        canvas.after(1000, pyrotechnik)
print(stop)

def blue():
    canvas.delete('all')
    if stop == 1:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')
def red():
    canvas.delete('all')
    if stop == 2:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')

def yellow():
    canvas.delete('all')
    if stop == 3:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')

def green():
    canvas.delete('all')
    if stop == 4:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')

button1 = tkinter.Button(text='Blue wire', command=blue, bg='SkyBlue') button1.pack()

button2 = tkinter.Button(text='Red wire', command=red, bg='Red') button2.pack()

button3 = tkinter.Button(text='Yellow wire', command=yellow, bg='Yellow') button3.pack()

button4 = tkinter.Button(text='Green wire', command=green, bg='Green') button4.pack()

pyrotechnik()
</code>```

答:
Not only do you need to delete everything on the canvas, but you also need to cancel the order to update the screen. The following version of your program should work properly. Please note the changes.</p>

```<code>import tkinter
from random import *

canvas = tkinter.Canvas(bg='White', width=400, height=200)
canvas.pack()

stop = randint(1, 4)
timer = 61
handle = None

def pyrotechnik():
    global timer, stop, handle
    canvas.delete('all')
    timer -= 1
    canvas.create_text(200, 100, font='Arial 20 bold', text=timer, fill='Red')
    if timer == 0:
        canvas.delete('all')
        canvas.create_text(200, 100, font='Arial 20 bold',
                           text='Bomb has exploded', fill='Red')
    else:
        handle = canvas.after(1000, pyrotechnik)

print(stop)

def blue():
    canvas.delete('all')
    canvas.after_cancel(handle)
    if stop == 1:
        canvas.create_text(200, 100, font='Arial 20 bold',
                           text="Thank god you've made it", fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM',
                           fill='Orange')

def red():
    canvas.delete('all')
    canvas.after_cancel(handle)
    if stop == 2:
        canvas.create_text(200, 100, font='Arial 20 bold',
                           text="Thank god you've made it", fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM',
                           fill='Orange')

def yellow():
    canvas.delete('all')
    canvas.after_cancel(handle)
    if stop == 3:
        canvas.create_text(200, 100, font='Arial 20 bold',
                           text="Thank god you've made it", fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM',
                           fill='Orange')

def green():
    canvas.delete('all')
    canvas.after_cancel(handle)
    if stop == 4:
        canvas.create_text(200, 100, font='Arial 20 bold',
                           text="Thank god you've made it", fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM',
                           fill='Orange')

button1 = tkinter.Button(text='Blue wire', command=blue, bg='SkyBlue')
button1.pack()

button2 = tkinter.Button(text='Red wire', command=red, bg='Red')
button2.pack()

button3 = tkinter.Button(text='Yellow wire', command=yellow, bg='Yellow')
button3.pack()

button4 = tkinter.Button(text='Green wire', command=green, bg='Green')
button4.pack()

pyrotechnik()
tkinter.mainloop()
</code>```

Body:
Hi guys I'm new to programming and I'm working with python at school.
Currently I'm working with tkinter and I have a little problem with this exercise.
Timer starts at 60, when it hits 0, it "explodes". If i click the right wire, it will tell me i've made it but if i click the wrong one it "explodes". The problem is, when i click any button it keeps generating the main function and I have no idea how to stop it. I hope someone can help me :)

import tkinter
from random import *
canvas = tkinter.Canvas(bg='White', width=400, height=200)
canvas.pack()

stop = randint(1, 4)
timer = 61

def pyrotechnik():
    global timer, stop
    canvas.delete('all')
    timer -= 1
    canvas.create_text(200, 100, font='Arial 20 bold', text=timer, fill='Red')
    if timer == 0:
        canvas.delete('all')
        canvas.create_text(200, 100, font='Arial 20 bold', text='Bomb has exploded', fill='Red')
    else:
        canvas.after(1000, pyrotechnik)
print(stop)

def blue():
    canvas.delete('all')
    if stop == 1:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')
def red():
    canvas.delete('all')
    if stop == 2:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')

def yellow():
    canvas.delete('all')
    if stop == 3:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')

def green():
    canvas.delete('all')
    if stop == 4:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')

button1 = tkinter.Button(text='Blue wire', command=blue, bg='SkyBlue') button1.pack()

button2 = tkinter.Button(text='Red wire', command=red, bg='Red') button2.pack()

button3 = tkinter.Button(text='Yellow wire', command=yellow, bg='Yellow') button3.pack()

button4 = tkinter.Button(text='Green wire', command=green, bg='Green') button4.pack()

pyrotechnik()

Body:
Not only do you need to delete everything on the canvas, but you also need to cancel the order to update the screen. The following version of your program should work properly. Please note the changes.

import tkinter
from random import *

canvas = tkinter.Canvas(bg='White', width=400, height=200)
canvas.pack()

stop = randint(1, 4)
timer = 61
handle = None

def pyrotechnik():
    global timer, stop, handle
    canvas.delete('all')
    timer -= 1
    canvas.create_text(200, 100, font='Arial 20 bold', text=timer, fill='Red')
    if timer == 0:
        canvas.delete('all')
        canvas.create_text(200, 100, font='Arial 20 bold',
                           text='Bomb has exploded', fill='Red')
    else:
        handle = canvas.after(1000, pyrotechnik)

print(stop)

def blue():
    canvas.delete('all')
    canvas.after_cancel(handle)
    if stop == 1:
        canvas.create_text(200, 100, font='Arial 20 bold',
                           text="Thank god you've made it", fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM',
                           fill='Orange')

def red():
    canvas.delete('all')
    canvas.after_cancel(handle)
    if stop == 2:
        canvas.create_text(200, 100, font='Arial 20 bold',
                           text="Thank god you've made it", fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM',
                           fill='Orange')

def yellow():
    canvas.delete('all')
    canvas.after_cancel(handle)
    if stop == 3:
        canvas.create_text(200, 100, font='Arial 20 bold',
                           text="Thank god you've made it", fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM',
                           fill='Orange')

def green():
    canvas.delete('all')
    canvas.after_cancel(handle)
    if stop == 4:
        canvas.create_text(200, 100, font='Arial 20 bold',
                           text="Thank god you've made it", fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM',
                           fill='Orange')

button1 = tkinter.Button(text='Blue wire', command=blue, bg='SkyBlue')
button1.pack()

button2 = tkinter.Button(text='Red wire', command=red, bg='Red')
button2.pack()

button3 = tkinter.Button(text='Yellow wire', command=yellow, bg='Yellow')
button3.pack()

button4 = tkinter.Button(text='Green wire', command=green, bg='Green')
button4.pack()

pyrotechnik()
tkinter.mainloop()


问:
For loop is only checking last value
I feel like I'm missing something really simple but I can't seem to find much help for it. So I'm designing a login using vaadin and a h2 in mem SQL database. There is a method that returns the values from the database in a list. The trouble is that I'm having problems with the method below. It's meant to iterate through every entry in the list and if it finds a username / password that matches then return true. If not return false.....

```<code>public boolean checkUserInDatabase(String username, String email) {
    boolean result = false;
    List<User> localArray = getUserList();

    System.out.println("List retrieved...Checking user in database"+
localArray);
    for (User u : localArray ) {
        if (u.getUsername().equals(username)) {
            result = true;
        }
        else {

            result = false;
        }
    }
    return result;
}
</code>```

I'm aware that at this point I'm only checking the username however, when I add users to the database it will still only check the last user in that database....thoughts?

答:
You should definitely return the boolean once you found the user.</p>

```<code>if (u.getUsername().equals(username)) {
  return true;
}
</code>```

Title: For loop is only checking last value

Body:
I feel like I'm missing something really simple but I can't seem to find much help for it. So I'm designing a login using vaadin and a h2 in mem SQL database. There is a method that returns the values from the database in a list. The trouble is that I'm having problems with the method below. It's meant to iterate through every entry in the list and if it finds a username / password that matches then return true. If not return false.....

public boolean checkUserInDatabase(String username, String email) {
    boolean result = false;
    List<User> localArray = getUserList();

    System.out.println("List retrieved...Checking user in database"+
localArray);
    for (User u : localArray ) {
        if (u.getUsername().equals(username)) {
            result = true;
        }
        else {

            result = false;
        }
    }
    return result;
}

I'm aware that at this point I'm only checking the username however, when I add users to the database it will still only check the last user in that database....thoughts?

Body:
You should definitely return the boolean once you found the user.

if (u.getUsername().equals(username)) {
  return true;
}


问:
How to correct a SQL Server Syntax Error setting FK contrainsts?
Trying to run this query in SSMS 2012:

```<code>SET FOREIGN_KEY_CHECKS = 0;

TRUNCATE TABLE dbo.mydb;

SET FOREIGN_KEY_CHECKS = 1;
</code>```

Results in this error on the Foreign Key check

Msg 102, Level 15, State 1, Line 3

  Incorrect syntax near '='.

So both SET commands are failing for this reason. How can I fix the syntax error?

答:
Or you can use all

Alter Table dbo.xy CHECK Constraint All

Body:
Trying to run this query in SSMS 2012:

SET FOREIGN_KEY_CHECKS = 0;

TRUNCATE TABLE dbo.mydb;

SET FOREIGN_KEY_CHECKS = 1;

Results in this error on the Foreign Key check

Msg 102, Level 15, State 1, Line 3

  Incorrect syntax near '='.

So both SET commands are failing for this reason. How can I fix the syntax error?


问:
How do i come up with a generic way to store all reference data in my database in SQL?
In my database, a customer can have many accounts and an account can be secured by many securities. A customer can be associated to another customer in the bank. For example property developer may be associated with a Surveyor.

A customer cannot be associated to another customer twice.

I have set up tables for Customers, Accounts Securities and Associations in SQL.

In terms of reference data the business has the following requirement: Accounts, Securities and Associations can be of several types For example, an account can be savings, credit; a security can be a bond, house, and an association can be that Customer 1 is the surveyor of Customer 2 (surveyor being the association).  They do not want many tables to store each of these types. They want a generic way to store all reference (types) data in the database.

I am very new to this and I cannot figure out a generic way to store the reference data. Do i need another table of types which would have Type ID Pk and then the description ( if i do it this way the table would be mixed with unrelated data)?

答:
For what I understand, you will have to come with a design that will require to be in the 4NF in order to be reliable and upgradeable.  You are going to need a bunch of tables to support the information if you want this to be done correctly and avoid any update issues that can turn the information stored in the DB inconsistent.

Let's start with the basic tables:

```<code>user_table
ID (PK, NN)
First Name
Last Name
Any other Field

account_type_table
ID (PK, NN)
Account Type (savings, checking, etc)

account_security_type_table
ID (PK, NN)
type of security (bond, house, etc)

users_account_table
ID (PK, NN)
UserID (Foreign Key from users table)
AccountTypeID (Foreign Key from account_type table)
AccountSecurityID (Foreign key from account_security_type table)
Any other information for the account
</code>```

The previous approach is for just 1 type of security for account, if you need to have multiple securities for a single account we need to modify the user_account_table and create another table that will link the account to the security type like this.

```<code>users_account_table
ID (PK, NN)
UserID (Foreign Key from users table)
AccountTypeID (Foreign Key from account_type table)
Any other information for the account

account_security_table
ID (PK, NN)
AccountID (Foreign key from users_account_table)
SecurityID (Foreign key from account_security_type_table)
Any other field you need.
</code>```

For the surveyor part I don't really understand what it is about, if you explain this even further probably I will be able to help you.

Body:
For what I understand, you will have to come with a design that will require to be in the 4NF in order to be reliable and upgradeable.  You are going to need a bunch of tables to support the information if you want this to be done correctly and avoid any update issues that can turn the information stored in the DB inconsistent.

Let's start with the basic tables:

user_table
ID (PK, NN)
First Name
Last Name
Any other Field

account_type_table
ID (PK, NN)
Account Type (savings, checking, etc)

account_security_type_table
ID (PK, NN)
type of security (bond, house, etc)

users_account_table
ID (PK, NN)
UserID (Foreign Key from users table)
AccountTypeID (Foreign Key from account_type table)
AccountSecurityID (Foreign key from account_security_type table)
Any other information for the account

The previous approach is for just 1 type of security for account, if you need to have multiple securities for a single account we need to modify the user_account_table and create another table that will link the account to the security type like this.

users_account_table
ID (PK, NN)
UserID (Foreign Key from users table)
AccountTypeID (Foreign Key from account_type table)
Any other information for the account

account_security_table
ID (PK, NN)
AccountID (Foreign key from users_account_table)
SecurityID (Foreign key from account_security_type_table)
Any other field you need.

For the surveyor part I don't really understand what it is about, if you explain this even further probably I will be able to help you.


问:
CSS transition hover on parent effect on child
I'm trying to animate inside button but for some reason it won't work. Width of the button should shrink to 0 to the left

HTML

```<code><div class="siteBtnShare">
    <div class="share-text-wrapper">
        <span class="share-text">SHARE</span>
    </div>
</div>
</code>```

SCSS

```<code>.siteBtnShare  {
position: relative;
display: inline-block;
font-family: 'Novecentosanswide-Medium';
width: 40px;
transition: width 1s;
overflow:hidden;

.share-text-wrapper{
    width: 40px;
    display: inline-block;
}

&:hover .share-text-wrapper{
    width: 0;
}

}
</code>```

EDIT: - Inside the button should shrink to 0, but it doesn't do anything. It remains visible

答:
The width does shrink, you just don't see it because the text flows outside of the container:

.siteBtnShare  {
position: relative;
display: inline-block;
font-family: 'Novecentosanswide-Medium';
width: 40px;
transition: width 1s;
overflow:hidden;
}

.share-text-wrapper{
    width: 40px;
    display: inline-block;
    overflow: hidden;
}

.siteBtnShare:hover .share-text-wrapper{
    width: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="siteBtnShare">
    <div class="share-text-wrapper">
        <span class="share-text">SHARE</span>
    </div>
</div></code>```

Working code in SCSS:

```<code>.siteBtnShare  {
position: relative;
display: inline-block;
font-family: 'Novecentosanswide-Medium';
width: 40px;
transition: width 1s;
overflow:hidden;

.share-text-wrapper{
    width: 40px;
    display: inline-block;
    overflow: hidden;
}

&:hover .share-text-wrapper{
    width: 0;
}
</code>```

}

Body:
I'm trying to animate inside button but for some reason it won't work. Width of the button should shrink to 0 to the left

HTML

        SHARE

SCSS

.siteBtnShare  {
position: relative;
display: inline-block;
font-family: 'Novecentosanswide-Medium';
width: 40px;
transition: width 1s;
overflow:hidden;

.share-text-wrapper{
    width: 40px;
    display: inline-block;
}

&:hover .share-text-wrapper{
    width: 0;
}

}

EDIT: - Inside the button should shrink to 0, but it doesn't do anything. It remains visible

Body:
The width does shrink, you just don't see it because the text flows outside of the container:

.siteBtnShare  {
position: relative;
display: inline-block;
font-family: 'Novecentosanswide-Medium';
width: 40px;
transition: width 1s;
overflow:hidden;
}

.share-text-wrapper{
    width: 40px;
    display: inline-block;
    overflow: hidden;
}

.siteBtnShare:hover .share-text-wrapper{
    width: 0;
}

<div class="siteBtnShare">
    <div class="share-text-wrapper">
        <span class="share-text">SHARE</span>
    </div>
</div>

Working code in SCSS:

.siteBtnShare  {
position: relative;
display: inline-block;
font-family: 'Novecentosanswide-Medium';
width: 40px;
transition: width 1s;
overflow:hidden;

.share-text-wrapper{
    width: 40px;
    display: inline-block;
    overflow: hidden;
}

&:hover .share-text-wrapper{
    width: 0;
}

}


问:
MPlayer forward/rewind speed
Is it possible to configure how far MPlayer will skips when I press the arrow keys? </p>

答: In the input.conf file, find the lines for "(UP|DOWN|RIGHT|LEFT) seek" and adjust the values for each one.</p>

Title: MPlayer forward/rewind speed

ContentLicense: CC BY-SA 2.5


问:
How can I create a SQL query that looks at the time interval between two consecutive records
How can I reference the previous and next row in a query, as well as the current?

I have a table to record car journeys from A to B. the structure is similar to this…

```<code>CREATE TABLE journeys (
  journeyID       SERIAL,
  vehicleId       CHAR(15),
  startTime       TIMESTAMP,
  endTime         TIMESTAMP
);
</code>```

Each row represents a single journey, how can I find the turn-around time between one journey ending and the next journey starting?

For each journey I want to be able to refer to the previous row (when sorted chronologically) to establish CURR.startTime – PREV.endTime. Note – journeyId is not sequential and is not in chronological order.

I’ve tried a self-join onto a duplicate of the same table, but because I can’t uniquely identify the subsequent journey I end up with a product-query that returns a massive set of results.

(I'm working with PostGres, but would prefer an ANSI SQL solution if possible)

Addendum for Aaron - I'm trying to get the time interval between two records, If a have one journey for a given vehicleID that ends at 12 noon (endTime) and the subsequent journey (for the same vehicle) starts at 12:45 (startTime), then the time interval between the two would be 45 minutes.

答:
You will want to use LAG() to access the previous row's endTime.  LAG() and similar window functions are available in most DBMS (will be coming to MySQL 8.0).

Your query will look something like this:

```<code>SELECT journeyID, vehicleID, startTime, endTime,
       startTime - LAG(endTime) over (PARTITION BY vehicleID ORDER BY startTime ASC) as timeBetweenJourneys
FROM journeys
</code>```

Body:
How can I reference the previous and next row in a query, as well as the current?

I have a table to record car journeys from A to B. the structure is similar to this…

CREATE TABLE journeys (
  journeyID       SERIAL,
  vehicleId       CHAR(15),
  startTime       TIMESTAMP,
  endTime         TIMESTAMP
);

Each row represents a single journey, how can I find the turn-around time between one journey ending and the next journey starting?

For each journey I want to be able to refer to the previous row (when sorted chronologically) to establish CURR.startTime – PREV.endTime. Note – journeyId is not sequential and is not in chronological order.

I’ve tried a self-join onto a duplicate of the same table, but because I can’t uniquely identify the subsequent journey I end up with a product-query that returns a massive set of results.

(I'm working with PostGres, but would prefer an ANSI SQL solution if possible)

Addendum for Aaron - I'm trying to get the time interval between two records, If a have one journey for a given vehicleID that ends at 12 noon (endTime) and the subsequent journey (for the same vehicle) starts at 12:45 (startTime), then the time interval between the two would be 45 minutes.

Body:
You will want to use LAG() to access the previous row's endTime.  LAG() and similar window functions are available in most DBMS (will be coming to MySQL 8.0).

Your query will look something like this:

SELECT journeyID, vehicleID, startTime, endTime,
       startTime - LAG(endTime) over (PARTITION BY vehicleID ORDER BY startTime ASC) as timeBetweenJourneys
FROM journeys


问:
How do you write JSDoc in Javascript for TypeScript Compiler?
I know that there is ability to check JS code with TS compiler. And I know that TS compiler understand JSDoc comments (https://github.com/Microsoft/TypeScript/wiki/JSDoc-support-in-JavaScript).

I want to use TS compiler with my React project and I don't know how specify props definitions with JSDoc :(

I've tried

```<code>class PropertyDetails extends React.Component {
  static propTypes = {
    breadcrumbChange: PropTypes.func,
    folderId: PropTypes.string.isRequired
  }

  /**
   * @typedef {Object} Props
   * @property {function} breadcrumbChange
   * @property {string} folderId
   */

  /**
   * @constructor
   * @param {Props} props
   */
  constructor(props) {
    super(props);
</code>```

but it doesn't work.

答:
To make IntelliSense and type checking working you have to specify prop types for Component class since in typings it is described like generic object. So if you try something like this

```<code>/**
 * @typedef {Object} Props
 * @prop {Function} breadcrumbChange
 * @prop {string} folderId
 * @extends React.Component<Props>
 */
class PropertyDetails extends React.Component {
}
</code>```

it should work

Body:
I know that there is ability to check JS code with TS compiler. And I know that TS compiler understand JSDoc comments (https://github.com/Microsoft/TypeScript/wiki/JSDoc-support-in-JavaScript).

I want to use TS compiler with my React project and I don't know how specify props definitions with JSDoc :(

I've tried

class PropertyDetails extends React.Component {
  static propTypes = {
    breadcrumbChange: PropTypes.func,
    folderId: PropTypes.string.isRequired
  }

  /**
   * @typedef {Object} Props
   * @property {function} breadcrumbChange
   * @property {string} folderId
   */

  /**
   * @constructor
   * @param {Props} props
   */
  constructor(props) {
    super(props);

but it doesn't work.

Body:
To make IntelliSense and type checking working you have to specify prop types for Component class since in typings it is described like generic object. So if you try something like this

/**
 * @typedef {Object} Props
 * @prop {Function} breadcrumbChange
 * @prop {string} folderId
 * @extends React.Component<Props>
 */
class PropertyDetails extends React.Component {
}

it should work


问:
Azure Batch tasks stuck in Running state
I have several tasks on Azure Batch which are stuck in Running state although the node server does not know anything about it (not running there, no folders found). Any task manipulation in GUI (Terminate, Delete, Show files on node) end with There was an error while terminating task t20171129-0010-03. The server returned '500 Internal Server Error'.. This happened several times on different pools / jobs / tasks.

Now I have checked the debug files on node itself and the issue seems to be caused by failed to extend lease and subsequently deleting the task from node, but aborting attempt to update task table without an active queue lease.

Is this something I can avoid, or is it just a bug in the Azure Batch service? What exactly is the "lease" and how often it needs to be renewed? (My Azure subscription does not contain Technical Support).

Interesting lines from log:

```<code>agent.task.lease■lease.py■_renew_lease_unsafe_async■106■1398■MainThread■139690855581440■extending lease for pd1batch 22F55DC6E98C8653$1a-python 22F4F1C234F19066$job-1$t20171129-0010-06
requests.packages.urllib3.connectionpool■connectionpool.py■_make_request■387■1398■Thread-1■139690661328640■"PUT /pd1batch-a-fa357c64-5c3d-4db8-9366-680943d2c20d/messages/821bf60d-3ba5-43a1-9c3d-c7500758bfea?sv=2015-07-08&se=2017-12-06T00%3A42%3A17Z&sp=up&sig=XXX&visibilitytimeout=360&popreceipt=AwAAAAMAAAAAAAAAFePc%2BR5u0wEBAAAA HTTP/1.1" 404 221
azurestorage.helper.HTTPNotFoundError: 404 Client Error: The specified message does not exist. for url: https://watbl2prod1.queue.core.windows.net/pd1batch-a-fa357c64-5c3d-4db8-9366-680943d2c20d/messages/821bf60d-3ba5-43a1-9c3d-c7500758bfea?sv=2015-07-08&se=2017-12-06T00%3A42%3A17Z&sp=up&sig=mU9501N4HHuDeRWuA7qMNni9M%2Fbb83OWLF8AW0%2B4nQE%3D&visibilitytimeout=360&popreceipt=AwAAAAMAAAAAAAAAFePc%2BR5u0wEBAAAA
agent.task.lease■lease.py■_renew_lease_unsafe_async■119■1398■MainThread■139690855581440■failed to extend lease for pd1batch 22F55DC6E98C8653$1a-python 22F4F1C234F19066$job-1$t20171129-0010-06
agent.task.manager■manager.py■handle_task_lease_extension_error_async■4713■1398■MainThread■139690855581440■deleting task pd1batch 22F55DC6E98C8653$1a-python 22F4F1C234F19066$job-1$t20171129-0010-06$0 because lease was lost
agent.task.manager■manager.py■_postprocess_execute_task_async■2255■1398■MainThread■139690855581440■updating row in task table for: pd1batch 22F55DC6E98C8653$1a-python 22F4F1C234F19066$job-1$t20171129-0010-06$0
agent.task.manager■manager.py■_update_tasktable_entity_async■1624■1398■MainThread■139690855581440■aborting attempt to update task table without an active queue lease for pd1batch 22F55DC6E98C8653$1a-python 22F4F1C234F19066$job-1$t20171129-0010-06$0
</code>```

Entire log: https://pastebin.com/fkqTRuBe

答:
Currently, Azure Batch tasks have a limit of a total lifetime of 7 days, from the time it is submitted to the job as noted here.

When this limit is reached, there are issues in the system that prevent the update of the task state from propagating. However, if you observe the node state where the task ran, it will return to idle (assuming no other tasks are scheduled to it or are currently running).

You have a few options to avoid this situation. If your workload is amenable to scale up or migrating to a more performant VM type such that your task completes in under the time limit. If you can scale out your problem (or scale it out further) by performing distribution computation or chunking the problem into smaller sizes and running it in an embarrassingly parallel fashion this may help resolve your issue.

The current behavior is not very user friendly. There are plans to increase this limit in the future.

Body:
I have several tasks on Azure Batch which are stuck in Running state although the node server does not know anything about it (not running there, no folders found). Any task manipulation in GUI (Terminate, Delete, Show files on node) end with There was an error while terminating task t20171129-0010-03. The server returned '500 Internal Server Error'.. This happened several times on different pools / jobs / tasks.

Now I have checked the debug files on node itself and the issue seems to be caused by failed to extend lease and subsequently deleting the task from node, but aborting attempt to update task table without an active queue lease.

Is this something I can avoid, or is it just a bug in the Azure Batch service? What exactly is the "lease" and how often it needs to be renewed? (My Azure subscription does not contain Technical Support).

Interesting lines from log:

agent.task.lease■lease.py■_renew_lease_unsafe_async■106■1398■MainThread■139690855581440■extending lease for pd1batch 22F55DC6E98C8653$1a-python 22F4F1C234F19066$job-1$t20171129-0010-06
requests.packages.urllib3.connectionpool■connectionpool.py■_make_request■387■1398■Thread-1■139690661328640■"PUT /pd1batch-a-fa357c64-5c3d-4db8-9366-680943d2c20d/messages/821bf60d-3ba5-43a1-9c3d-c7500758bfea?sv=2015-07-08&se=2017-12-06T00%3A42%3A17Z&sp=up&sig=XXX&visibilitytimeout=360&popreceipt=AwAAAAMAAAAAAAAAFePc%2BR5u0wEBAAAA HTTP/1.1" 404 221
azurestorage.helper.HTTPNotFoundError: 404 Client Error: The specified message does not exist. for url: https://watbl2prod1.queue.core.windows.net/pd1batch-a-fa357c64-5c3d-4db8-9366-680943d2c20d/messages/821bf60d-3ba5-43a1-9c3d-c7500758bfea?sv=2015-07-08&se=2017-12-06T00%3A42%3A17Z&sp=up&sig=mU9501N4HHuDeRWuA7qMNni9M%2Fbb83OWLF8AW0%2B4nQE%3D&visibilitytimeout=360&popreceipt=AwAAAAMAAAAAAAAAFePc%2BR5u0wEBAAAA
agent.task.lease■lease.py■_renew_lease_unsafe_async■119■1398■MainThread■139690855581440■failed to extend lease for pd1batch 22F55DC6E98C8653$1a-python 22F4F1C234F19066$job-1$t20171129-0010-06
agent.task.manager■manager.py■handle_task_lease_extension_error_async■4713■1398■MainThread■139690855581440■deleting task pd1batch 22F55DC6E98C8653$1a-python 22F4F1C234F19066$job-1$t20171129-0010-06$0 because lease was lost
agent.task.manager■manager.py■_postprocess_execute_task_async■2255■1398■MainThread■139690855581440■updating row in task table for: pd1batch 22F55DC6E98C8653$1a-python 22F4F1C234F19066$job-1$t20171129-0010-06$0
agent.task.manager■manager.py■_update_tasktable_entity_async■1624■1398■MainThread■139690855581440■aborting attempt to update task table without an active queue lease for pd1batch 22F55DC6E98C8653$1a-python 22F4F1C234F19066$job-1$t20171129-0010-06$0

Entire log: https://pastebin.com/fkqTRuBe


问:
Changing a complex join into a Sequel association
Right now I have a relatively complex piece of code (it's not that complex) that I'd like to simplify through Sequel associations

```<code>MyApp::Model::Node.where { last_heartbeat > Time.now - HEARTBEAT_TIMEOUT.seconds }.join(:system_status, node_id: Sequel.expr(:node__id))
</code>```

Pretty nasty, this statement.

So I'd like to accomplish one thing, pretty much: simplify the above statement by replacing the join with an association in my SystemStatus Model.

Let me explain the above join:

I have two tables Node and SystemStatus. The comparison last_heartbeat > Time.now - HEARTBEAT_TIMEOUT.seconds essentially gives me all the "live nodes" in my application (my application is clustered, meaning the user can spawn multiple instances of it at the same time).

So that mess of a statement gives me "all the statuses of my live nodes" which is joined by system_status.node_id to node.id.

So I started this out by establishing my one to one relation in SystemStatus - this sets the association to the node table

```<code>one_to_one :node
</code>```

Next, I needed to join it by a specific key node.id because it's not a straightforward join

```<code>one_to_one :node, key: :id
</code>```

But my question is:

How do I do the rest of this association

Should I perform the association in Node as opposed to SystemStatus? It seems I could simply do one_to_one :system_status and not have to specify a key.. The above complex join resides in the node Model anyways.

答:
If you have the association in SystemStatus, you need to use many_to_one, as the foreign key is in the that model's table, not the associated model's table.  You can just transfer your where condition to the association using a block:

```<code>SystemStatus.many_to_one :live_node, class: :Node, key: :node_id do |ds|
  ds.where{last_heartbeat > Time.now - HEARTBEAT_TIMEOUT.seconds}
end
</code>```

Body:
Right now I have a relatively complex piece of code (it's not that complex) that I'd like to simplify through Sequel associations

MyApp::Model::Node.where { last_heartbeat > Time.now - HEARTBEAT_TIMEOUT.seconds }.join(:system_status, node_id: Sequel.expr(:node__id))

Pretty nasty, this statement.

So I'd like to accomplish one thing, pretty much: simplify the above statement by replacing the join with an association in my SystemStatus Model.

Let me explain the above join:

I have two tables Node and SystemStatus. The comparison last_heartbeat > Time.now - HEARTBEAT_TIMEOUT.seconds essentially gives me all the "live nodes" in my application (my application is clustered, meaning the user can spawn multiple instances of it at the same time).

So that mess of a statement gives me "all the statuses of my live nodes" which is joined by system_status.node_id to node.id.

So I started this out by establishing my one to one relation in SystemStatus - this sets the association to the node table

one_to_one :node

Next, I needed to join it by a specific key node.id because it's not a straightforward join

one_to_one :node, key: :id

But my question is:

How do I do the rest of this association

Should I perform the association in Node as opposed to SystemStatus? It seems I could simply do one_to_one :system_status and not have to specify a key.. The above complex join resides in the node Model anyways.

Body:
If you have the association in SystemStatus, you need to use many_to_one, as the foreign key is in the that model's table, not the associated model's table.  You can just transfer your where condition to the association using a block:

SystemStatus.many_to_one :live_node, class: :Node, key: :node_id do |ds|
  ds.where{last_heartbeat > Time.now - HEARTBEAT_TIMEOUT.seconds}
end


问:
In Java, How to draw multi-line text with auto-resizing font that must fit into a bounds
Using TextLayout and LineMeasurer (The only way to draw multiline center-aligned text in java), How does one go about this?</p>

答:
So I created a wrapper class around LineBreakMeasurer, which immediately populates an arraylist of TextLayouts upon instantiation of the wrapper class. While generating this array list of layouts, I got the lineheight of each layout and added that incrementally to a total line height. I can then externally query this wrapper for the total lineheight of all it's text and if it is greater than my vertical bounds, I rederive the font with a lesser font size and repopulate the arraylist of layouts....which can then be gotten from the arraylist using some getNextLayout() method.

I also had this wrapper class force '\n' to be respected by lineBreakMeasurer by doing a String [] lines = text.split("\n")
And then running linebreakMeasurer on each of those lines as I populated the arraylist of layouts.


答:
It is purely logical. You are iterating through your list, and only at the end returning the value. So your program is going through the entire list, and provides only the last result. Here is your complete, correct program:

```<code>public boolean checkUserInDatabase(String username, String email) {
    boolean result = false;
    List<User> localArray = getUserList();

    System.out.println("List retrieved...Checking user in database"+ localArray);
    for (User u : localArray ) {
        if (u.getUsername().equals(username)) {
        return true;
        }
    }

return result;
}
</code>```

This way if your program finds a user it directly answers true instead of going through the rest of the list.

Title: For loop is only checking last value

Body:
It is purely logical. You are iterating through your list, and only at the end returning the value. So your program is going through the entire list, and provides only the last result. Here is your complete, correct program:

public boolean checkUserInDatabase(String username, String email) {
    boolean result = false;
    List<User> localArray = getUserList();

    System.out.println("List retrieved...Checking user in database"+ localArray);
    for (User u : localArray ) {
        if (u.getUsername().equals(username)) {
        return true;
        }
    }

return result;
}

This way if your program finds a user it directly answers true instead of going through the rest of the list.


问:
AAPT2 gradle issue in android studio 3.0 beta4
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

We have already added android.enableAapt2=false in gradle.properties file

答:
For me, there was no need to add android.enableAapt2=false to my gradle.properties. The solution for me was to make sure that in my gradle build file my compileSdkVersion is set to 26, buildToolsVersion is set to 26.0.2 and targetSdkVersion is set to 26.

Note: In my build file, I had to do this check for all target and compile sdkVersions including product flavors:

mobile

tv

I am using Android Studio 3.0.1.


问:
Sending out SMS messages from my Android phone in Java, how can I do them one at a time?
Sending out SMS messages from my Android phone in Java, how can I do them one at a time?

I made this application to send out a number of SMS messages from my phone, but how do I change it to send one at a time?

I am trying to make this send a SMS message and wait for the reply code to get back before sending the next one:

```<code>import android.telephony.gsm.SmsManager;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import android.util.Log;
import android.widget.Button;

import java.io.*;
import android.util.LogPrinter;

import java.io.*;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.TextView;
import android.os.*;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;
import java.io.*;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;

public class JSSMS extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button button = (Button) findViewById(R.id.Button01);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(JSSMS.this, "Starting SMS", Toast.LENGTH_LONG)
                        .show();

                String message = "Hello This Is John, Please save my new number";
                String number;
                try {
                    BufferedReader buffreader = new BufferedReader(
                            new FileReader(Environment
                                    .getExternalStorageDirectory().toString()
                                    + "/numbers.txt"));
                    int i = 0;
                    while ((number = buffreader.readLine()) != null) {
                        Toast.makeText(JSSMS.this, "Sending text to:" + number,
                                Toast.LENGTH_SHORT).show();
                        sendSMS(number, message);
                    }

                    buffreader.close();
                } catch (java.io.FileNotFoundException e) {
                    Toast.makeText(JSSMS.this, e.toString(), Toast.LENGTH_SHORT)
                            .show();

                } catch (Exception e) {
                    Toast.makeText(JSSMS.this, e.toString(), Toast.LENGTH_SHORT)
                            .show();
                }

                Toast.makeText(JSSMS.this, "DONE!!", Toast.LENGTH_LONG).show();
            }
        });
    }

    // ---Sends an SMS message to another device.---
    private void sendSMS(String phoneNumber, String message) {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
                SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                new Intent(DELIVERED), 0);

        // ---When the SMS has been sent---
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS sent",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(getBaseContext(), "Generic failure",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(getBaseContext(), "No service",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(getBaseContext(), "Null PDU",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(getBaseContext(), "Radio off",
                            Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }, new IntentFilter(SENT));

        // ---When the SMS has been delivered---
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(getBaseContext(), "SMS not delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }, new IntentFilter(DELIVERED));

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
    }
}
</code>```

答:
Here's a general hint to set you in the right direction. When you have a queue of items you want to process in some asynchronous manner, one approach is use the callback/event handler/call-it-what-you-will to trigger the processing of the next element in the queue.

set up your queue of messages

have a method, e.g. 'sendNextMessage' which pops the top message off the queue and sends it

now, in your onReceive method, you can call your sendNextMessage to trigger sending the next one in the queue

For this approach to work, you need to ensure you are guaranteed to get some kind callback regardless of success or failure.

Body:
Sending out SMS messages from my Android phone in Java, how can I do them one at a time?

I made this application to send out a number of SMS messages from my phone, but how do I change it to send one at a time?

I am trying to make this send a SMS message and wait for the reply code to get back before sending the next one:

import android.telephony.gsm.SmsManager;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import android.util.Log;
import android.widget.Button;

import java.io.*;
import android.util.LogPrinter;

import java.io.*;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.TextView;
import android.os.*;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;
import java.io.*;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;

public class JSSMS extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button button = (Button) findViewById(R.id.Button01);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(JSSMS.this, "Starting SMS", Toast.LENGTH_LONG)
                        .show();

                String message = "Hello This Is John, Please save my new number";
                String number;
                try {
                    BufferedReader buffreader = new BufferedReader(
                            new FileReader(Environment
                                    .getExternalStorageDirectory().toString()
                                    + "/numbers.txt"));
                    int i = 0;
                    while ((number = buffreader.readLine()) != null) {
                        Toast.makeText(JSSMS.this, "Sending text to:" + number,
                                Toast.LENGTH_SHORT).show();
                        sendSMS(number, message);
                    }

                    buffreader.close();
                } catch (java.io.FileNotFoundException e) {
                    Toast.makeText(JSSMS.this, e.toString(), Toast.LENGTH_SHORT)
                            .show();

                } catch (Exception e) {
                    Toast.makeText(JSSMS.this, e.toString(), Toast.LENGTH_SHORT)
                            .show();
                }

                Toast.makeText(JSSMS.this, "DONE!!", Toast.LENGTH_LONG).show();
            }
        });
    }

    // ---Sends an SMS message to another device.---
    private void sendSMS(String phoneNumber, String message) {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
                SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                new Intent(DELIVERED), 0);

        // ---When the SMS has been sent---
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS sent",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(getBaseContext(), "Generic failure",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(getBaseContext(), "No service",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(getBaseContext(), "Null PDU",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(getBaseContext(), "Radio off",
                            Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }, new IntentFilter(SENT));

        // ---When the SMS has been delivered---
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(getBaseContext(), "SMS not delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }, new IntentFilter(DELIVERED));

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
    }
}


问:
eclipse not inserting "diamond" operator in a java 8 project
I have a maven project configured to use Java 8 and all works fine, eclipse compiles code like:

```<code>Map<String,String> map = new HashMap<>();
</code>```

It even complains about old-style code ("redundant specification of type arguments") when I set this on the Error/Warnings tab. The problem is, I can't work out how to make it use this syntax by default on autocompletion - I'm pretty sure I saw it working earlier but now whenever I ctrl-space to insert a constructor, it insists on adding the parameters, which I don't like.

Can anybody hint what setting to check to make content assist insert <> instead of < String,String >? Or perhaps it's related to the fact I'm using Java 8 not Java 7, or that I'm on maven?

答: I observed this error when compiling with maven. To solve it, I had to fix my JAVA_HOME environment variable to the right JDK.</p>

Body:
I have a maven project configured to use Java 8 and all works fine, eclipse compiles code like:

Map<String,String> map = new HashMap<>();

It even complains about old-style code ("redundant specification of type arguments") when I set this on the Error/Warnings tab. The problem is, I can't work out how to make it use this syntax by default on autocompletion - I'm pretty sure I saw it working earlier but now whenever I ctrl-space to insert a constructor, it insists on adding the parameters, which I don't like.

Can anybody hint what setting to check to make content assist insert <> instead of < String,String >? Or perhaps it's related to the fact I'm using Java 8 not Java 7, or that I'm on maven?


问:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)

What is this?

This is a collection of questions that come up every now and then about syntax in PHP. This is also a Community Wiki, so everyone is invited to participate in maintaining this list.

Why is this?

It used to be hard to find questions about operators and other syntax tokens.¹

The main idea is to have links to existing questions on Stack Overflow, so it's easier for us to reference them, not to copy over content from the PHP Manual.

Note: Since January 2013, Stack Overflow does support special characters. Just surround the search terms by quotes, e.g. [php] "==" vs "==="

What should I do here?

If you have been pointed here by someone because you have asked such a question, please find the particular syntax below. The linked pages to the PHP manual along with the linked questions will likely answer your question then. If so, you are encouraged to upvote the answer. This list is not meant as a substitute for the help others provided.

The List

If your particular token is not listed below, you might find it in the List of Parser Tokens.

& Bitwise Operators or References

What does it mean to start a PHP function with an ampersand?

Understanding PHP & (ampersand, bitwise and) operator

PHP "&" operator

Difference between & and && in PHP

What does "&" mean here in PHP?

What does "&" mean in this case?

What does the "&" sign mean in PHP?

What does this signature mean (&) in PHP?

How does the "&" operator work in a PHP function?

What does & in &2 mean in PHP?

When should I use a bitwise operator?

Is there ever a need to use ampersand in front of an object? (&$)

=& References

Reference assignment operator in PHP, =&

What do the "=&" and "&=" operators in PHP mean?

What do the '&=' and '=&' operators do?

What does =& mean in PHP?

&= Bitwise Operators

What do the "=&" and "&=" operators in PHP mean?

What do the '&=' and '=&' operators do?

&& Logical Operators

'AND' vs '&&' as operator

Difference between & and && in PHP

Is there any difference between "and" and "&&" operators in PHP?

PHP - and / or keywords

% Arithmetic Operators

What does the percent sign mean in PHP?

What is the PHP operator % and how do I use it in real-world examples?

!! Logical Operators

Double not (!!) operator in PHP

@ Error Control Operators

What is the use of the @ symbol in PHP?

'At' symbol before variable name in PHP: @$_POST

PHP functions and @functions

Should I use @ in my PHP code?

What does @ mean in PHP?

?: Ternary Operator

What are the PHP operators "?" and ":" called and what do they do?

?: operator (the 'Elvis operator') in PHP

Where can I read about conditionals done with "?" and ":" (colon)?

Using PHP 5.3 ?: operator

Double question mark

?? Null Coalesce Operator (since PHP 7)

C#'s null coalescing operator (??) in PHP

Question mark followed by a type declaration

?string
?int
?array
?bool
?float Nullable type declaration (since PHP 7.1)

How to use a nullable type

Nullable return type declaration

?-> question mark followed by object operator is a NullSafe Operator (since PHP 8.0)

Is there a "nullsafe operator" in PHP?

: Alternative syntax for control structures, Ternary Operator, Return Type Declaration

What is ":" in PHP?

What does ":" mean in PHP?

Colon after method declaration?

:: Scope Resolution Operator

What do two colons mean in PHP?

What's the meaning of the PHP token name T_PAAMAYIM_NEKUDOTAYIM?

What's the difference between :: (double colon) and -> (arrow) in PHP?

What exactly are late static bindings in PHP?

static::staticFunctionName()

Unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting T_NS_Separator

\ Namespaces

Backslash in PHP -- what does it mean?

What does a \ (backslash) do in PHP (5.3+)?

-> Classes And Objects

What is the "->" PHP operator called?

Where do we use the object operator "->" in PHP?

What's the difference between :: (double colon) and -> (arrow) in PHP?

What does the PHP syntax $var1->$var2 mean?

What does "->" mean/refer to in PHP?

=> Arrays

What does "=>" mean in PHP?

Use of => in PHP

What does $k => $v in foreach($ex as $k=>$v) mean?

^ Bitwise Operators

How does the bitwise operator XOR ('^') work?

What does ^ mean in PHP?

>> Bitwise Operators

What does >> mean in PHP?

<< Bitwise Operators

Strange print behaviour in PHP?

<<< Heredoc or Nowdoc

What does <<<END mean in PHP?

PHP expression <<<EOB

In PHP, what does "<<<" represent?

Using <<<CON in PHP

What's this kind of syntax in PHP?

= Assignment Operators

The 3 different equals

== Comparison Operators

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

PHP != and == operators

The 3 different equals

Type-juggling and (strict) greater/lesser-than comparisons in PHP

=== Comparison Operators

What does "===" mean?

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

The 3 different equals

Type-juggling and (strict) greater/lesser-than comparisons in PHP

!== Comparison Operators

What does !== comparison operator in PHP mean?

Is there a difference between !== and != in PHP?

!= Comparison Operators

PHP != and == operators

Is there a difference between !== and != in PHP?

comparing, !== versus !=

What is the difference between <> and !=

<> Comparison Operators

PHP operator <>

https://stackoverflow.com/questions/589391

What is the difference between <> and !=

Type-juggling and (strict) greater/lesser-than comparisons in PHP

<=> Comparison Operators (since PHP 7.0)

Spaceship (three way comparison) operator

| Bitwise Operators

What is the difference between the | and || operators?

What Does Using A Single Pipe '|' In A Function Argument Do?

|| Logical Operators

What is the difference between the | and || operators?

PHP - and / or keywords

What exactly does || mean?

The behaviour of the or operator in PHP

~ Bitwise Operators

What does this ~ operator mean here?

+ Arithmetic Operators, Array Operators

Merging two arrays with the "+" (array union operator) How does it work?

+= and -= Assignment Operators

What is += used for?

What does `$page -= 1` in my PHP document mean?

++ and -- Incrementing/Decrementing Operators

Understanding Incrementing

Answer below

.= Assignment Operators

What is the difference between .= and += in PHP?

What is the .= (dot equals) operator in PHP?

. String Operators

Difference between period and comma when concatenating with echo versus return?

What does a . (dot) do in PHP?

, Function Arguments

Difference between period and comma when concatenating with echo versus return?

, Variable Declarations

What do commas mean in a variable declaration?

$$ Variable Variables

What does $$ (dollar dollar or double dollar) mean in PHP?

what is "$$" in PHP

$function() and $$variable

` Execution Operator

What are the backticks `` called?

<?= Short Open Tags

What does this symbol mean in PHP <?=

What does '<?=' mean in PHP?

What does <?= mean?

[] Arrays (short syntax since PHP 5.4)

PHP arrays... What is/are the meaning(s) of an empty bracket?

What is the meaning of []

Php array_push() vs myArray[]

What does [] mean when reading from a PHP array?

Shorthand for arrays: literal $var = [] empty array

<? Opening and Closing tags

Are PHP short tags acceptable to use?

.. Double-dot character range

Native PHP functions that allow double-dot range syntax

... Argument unpacking (since PHP 5.6)

** Exponentiation (since PHP 5.6)

# One-line shell-style comment

Can I use hashes for comments in PHP?

#[] Attributes (since PHP 8)

答:
Null Coalesce operator "??" (Added in PHP 7)

Not the catchiest name for an operator, but PHP 7 brings in the rather handy null coalesce so I thought I'd share an example.

In PHP 5, we already have a ternary operator, which tests a value, and then returns the second element if that returns true and the third if it doesn't:

```<code>echo $count ? $count : 10; // outputs 10
</code>```

There is also a shorthand for that which allows you to skip the second element if it's the same as the first one: echo $count ?: 10; // also outputs 10

In PHP 7 we additionally get the ?? operator which rather than indicating extreme confusion which is how I would usually use two question marks together instead allows us to chain together a string of values. Reading from left to right, the first value which exists and is not null is the value that will be returned.

```<code>// $a is not set
$b = 16;

echo $a ?? 2; // outputs 2
echo $a ?? $b ?? 7; // outputs 16
</code>```

This construct is useful for giving priority to one or more values coming perhaps from user input or existing configuration, and safely falling back on a given default if that configuration is missing. It's kind of a small feature but it's one that I know I'll be using as soon as my applications upgrade to PHP 7.

OwnerDisplayName: anon

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: anon

Body:
Null Coalesce operator "??" (Added in PHP 7)

Not the catchiest name for an operator, but PHP 7 brings in the rather handy null coalesce so I thought I'd share an example.

In PHP 5, we already have a ternary operator, which tests a value, and then returns the second element if that returns true and the third if it doesn't:

echo $count ? $count : 10; // outputs 10

There is also a shorthand for that which allows you to skip the second element if it's the same as the first one: echo $count ?: 10; // also outputs 10

In PHP 7 we additionally get the ?? operator which rather than indicating extreme confusion which is how I would usually use two question marks together instead allows us to chain together a string of values. Reading from left to right, the first value which exists and is not null is the value that will be returned.

// $a is not set
$b = 16;

echo $a ?? 2; // outputs 2
echo $a ?? $b ?? 7; // outputs 16

This construct is useful for giving priority to one or more values coming perhaps from user input or existing configuration, and safely falling back on a given default if that configuration is missing. It's kind of a small feature but it's one that I know I'll be using as soon as my applications upgrade to PHP 7.


问:
Connect Google App Engine with on-premises local storage
I'm designing a network architecture and I have a doubt about connecting google app engine with on-premises local storage server. Here I'm posting my design and please let me know is this possible or not!

答:
Update: Oh lookey loo! They've added some networking support to AppEngine recently!

I think that you're going to have problems with this sort of setup. When you use App Engine you're losing the networking level of control which you get when using Compute Engine or Container Engine. Where you have Cloud Interconnect & VPN, I think you will find that there's no way forward.

Better would be to use Container Engine or Compute and then you can use the Networking capabilities of the platform.


问:
Curve in D3 shape
I tried creating a funnel chart using D3 and vx. This is what i have achieved so far

https://www.webpackbin.com/bins/-L-TDMSWHUS-ZOi0jb8t

But i tried all curve options from d3-shape. But couldn't create the cure as shown in

Any help would be appreciated.

答: Seems like your best bet would be to make a basic area chart and to reflect it across the x-axis. I believe that would give a similar effect. For more clarification, the x-axis would go through the horizontal center of the chart in the image above</p>

Title: Curve in D3 shape


问:
Receiving "No frames output" when using AndroidSequenceEncoder
I am trying to use AndroidSequenceEncoder to create a video slideshow. In order to do this, I have a method that retrieves an ArrayList of Bitmaps and a String representing the video's filename. The following is my method's code:

```<code>public class ImageToVideo
{
    //used to input frames (images) into the video file
    private AndroidSequenceEncoder ase;
    //Arraylist containing the frames to input
    private ArrayList<Bitmap> bi;
    //temporary variable used for AsyncTask below
    private Bitmap image;
    //This method is called until main code can be written to retrieve the proper length of the audio file
    public AndroidSequenceEncoder videoEncode(final ArrayList<Bitmap> images, String filename) throws  IOException
    {
        ase = AndroidSequenceEncoder.createSequenceEncoder(new File(filename), 3);
        bi = images;
        Log.d("SEQUENCEENCODER", "SequenceEncoder created");
        //outer for-loop; goes through each image individually
        for(int i = 0; i < images.size(); i++)
        {
            Log.d("SEQUENCEENCODER", "Retrieving image " + i + " of " + (images.size() - 1));
        //inner for-loop; adds the given image a number of times determined by how long each image is on-screen
        //since encoder's fps is currently set to 3, this loops once for each second the picture should be on-screen times 3
        for(int j = 0; j < 3; j++)
        {
            Log.d("SEQUENCEENCODER", "Encoding image " + i + ", " + (j+1) + " of " + 3);
            image = bi.get((i));
            //used because of error "Choreographer: Skipped ~90 frames! The application may be doing too much work on its main thread"
            AsyncTask.execute(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        ase.encodeImage(image);
                    }
                    catch(IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    ase.finish();
    return ase;
}
</code>```

The AndroidSequenceEncoder's fps is set to 3 as a temporary value; when I work on the code more, I want this method to take the video's length as well, so that the method determines fps based on the how long each image should be on-screen, given they each have equal time. When running this method with 4 images, I get the following messages

```<code>D/SEQUENCEENCODER: SequenceEncoder created
D/SEQUENCEENCODER: Retrieving image 0 of 3
D/SEQUENCEENCODER: Encoding image 0, 1 of 3
D/SEQUENCEENCODER: Encoding image 0, 2 of 3
D/SEQUENCEENCODER: Encoding image 0, 3 of 3
D/SEQUENCEENCODER: Retrieving image 1 of 3
D/SEQUENCEENCODER: Encoding image 1, 1 of 3
D/SEQUENCEENCODER: Encoding image 1, 2 of 3
D/SEQUENCEENCODER: Encoding image 1, 3 of 3
D/SEQUENCEENCODER: Retrieving image 2 of 3
D/SEQUENCEENCODER: Encoding image 2, 1 of 3
D/SEQUENCEENCODER: Encoding image 2, 2 of 3
D/SEQUENCEENCODER: Encoding image 2, 3 of 3
D/SEQUENCEENCODER: Retrieving image 3 of 3
D/SEQUENCEENCODER: Encoding image 3, 1 of 3
D/SEQUENCEENCODER: Encoding image 3, 2 of 3
D/SEQUENCEENCODER: Encoding image 3, 3 of 3
I/System.out: [WARN]    . (:0): No frames output.
D/EGL_emulation: eglMakeCurrent: 0xa8a05240: ver 2 0 (tinfo 0xa8a03250)
D/EGL_emulation: eglMakeCurrent: 0xa8a05240: ver 2 0 (tinfo 0xa8a03250)
I/chatty: uid=10080(projectname) RenderThread identical 1 line
D/EGL_emulation: eglMakeCurrent: 0xa8a05240: ver 2 0 (tinfo 0xa8a03250)
I/zygote: Do partial code cache collection, code=122KB, data=94KB
I/zygote: After code cache collection, code=117KB, data=92KB
I/zygote: Increasing code cache capacity to 512KB
</code>```

followed by a long list of system errors pointing back to the command

```<code>ase.encodeImage(image);
</code>```

A new video file does get created in the Android Virtual Device, but it ends almost immediately after playing, despite that it says its length is 4 seconds. I am wondering what I am doing wrong in the code to cause this.

答:
One problem that I see with the above code is that the actual encoding of frames takes place in a separate (background) thread. So under some circumstance it is possible that none of the frames are actually encoded by the time 'finish' is called.
What you need to do is make sure 'finish' is called after the encoding of all frames actually took place. There are multiple ways to achieve this:

Move your loops entirely inside the async task followed by finish;

In case there's only one executor thread you can get away with executing 'finish' inside the async task also, that way you'll rely on internal executor queue to execute your 'finish' at the very end;

Use thread synchronization primitives, like 'wait/notify'. So in the main thread you can 'wait' before calling 'finish' and in the async task you'll 'notify'. Though this is a viable option I would strongly discourage you from using it for a variety of other reasons.

Body:
I am trying to use AndroidSequenceEncoder to create a video slideshow. In order to do this, I have a method that retrieves an ArrayList of Bitmaps and a String representing the video's filename. The following is my method's code:

public class ImageToVideo
{
    //used to input frames (images) into the video file
    private AndroidSequenceEncoder ase;
    //Arraylist containing the frames to input
    private ArrayList<Bitmap> bi;
    //temporary variable used for AsyncTask below
    private Bitmap image;
    //This method is called until main code can be written to retrieve the proper length of the audio file
    public AndroidSequenceEncoder videoEncode(final ArrayList<Bitmap> images, String filename) throws  IOException
    {
        ase = AndroidSequenceEncoder.createSequenceEncoder(new File(filename), 3);
        bi = images;
        Log.d("SEQUENCEENCODER", "SequenceEncoder created");
        //outer for-loop; goes through each image individually
        for(int i = 0; i < images.size(); i++)
        {
            Log.d("SEQUENCEENCODER", "Retrieving image " + i + " of " + (images.size() - 1));
        //inner for-loop; adds the given image a number of times determined by how long each image is on-screen
        //since encoder's fps is currently set to 3, this loops once for each second the picture should be on-screen times 3
        for(int j = 0; j < 3; j++)
        {
            Log.d("SEQUENCEENCODER", "Encoding image " + i + ", " + (j+1) + " of " + 3);
            image = bi.get((i));
            //used because of error "Choreographer: Skipped ~90 frames! The application may be doing too much work on its main thread"
            AsyncTask.execute(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        ase.encodeImage(image);
                    }
                    catch(IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    ase.finish();
    return ase;
}

The AndroidSequenceEncoder's fps is set to 3 as a temporary value; when I work on the code more, I want this method to take the video's length as well, so that the method determines fps based on the how long each image should be on-screen, given they each have equal time. When running this method with 4 images, I get the following messages

D/SEQUENCEENCODER: SequenceEncoder created
D/SEQUENCEENCODER: Retrieving image 0 of 3
D/SEQUENCEENCODER: Encoding image 0, 1 of 3
D/SEQUENCEENCODER: Encoding image 0, 2 of 3
D/SEQUENCEENCODER: Encoding image 0, 3 of 3
D/SEQUENCEENCODER: Retrieving image 1 of 3
D/SEQUENCEENCODER: Encoding image 1, 1 of 3
D/SEQUENCEENCODER: Encoding image 1, 2 of 3
D/SEQUENCEENCODER: Encoding image 1, 3 of 3
D/SEQUENCEENCODER: Retrieving image 2 of 3
D/SEQUENCEENCODER: Encoding image 2, 1 of 3
D/SEQUENCEENCODER: Encoding image 2, 2 of 3
D/SEQUENCEENCODER: Encoding image 2, 3 of 3
D/SEQUENCEENCODER: Retrieving image 3 of 3
D/SEQUENCEENCODER: Encoding image 3, 1 of 3
D/SEQUENCEENCODER: Encoding image 3, 2 of 3
D/SEQUENCEENCODER: Encoding image 3, 3 of 3
I/System.out: [WARN]    . (:0): No frames output.
D/EGL_emulation: eglMakeCurrent: 0xa8a05240: ver 2 0 (tinfo 0xa8a03250)
D/EGL_emulation: eglMakeCurrent: 0xa8a05240: ver 2 0 (tinfo 0xa8a03250)
I/chatty: uid=10080(projectname) RenderThread identical 1 line
D/EGL_emulation: eglMakeCurrent: 0xa8a05240: ver 2 0 (tinfo 0xa8a03250)
I/zygote: Do partial code cache collection, code=122KB, data=94KB
I/zygote: After code cache collection, code=117KB, data=92KB
I/zygote: Increasing code cache capacity to 512KB

followed by a long list of system errors pointing back to the command

ase.encodeImage(image);

A new video file does get created in the Android Virtual Device, but it ends almost immediately after playing, despite that it says its length is 4 seconds. I am wondering what I am doing wrong in the code to cause this.


问:
How do I get android preferences to work?
Sorry about this guys. This must be like the third question I've had to ask about this project alone. =(

What i want to be able to do is toggle the visibility of a radio button using a check box in a preferences activity.

There are no errors in my code and both activities run fine, but there is no change in visibility when the check box is checked or unchecked.

Here is my Activity with the radiobuttons

```<code>import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import com.medialets.android.analytics.MMAnalyticsManager;

public class Temperature extends Activity {
MMAnalyticsManager mManager;
private EditText text;

public void onStart(Bundle savedInstanceState){
    super.onStart();
    getPrefs();
}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.temperature);
        text = (EditText)findViewById(R.id.EditText01);

mManager = MMAnalyticsManager.sharedInstance(this);
mManager.start("codeHere", "1.0",
    false);
}

@Override
public void onPause() {
super.onPause();

mManager.pause();
}

@Override
public void onResume() {
super.onResume();

mManager.resume();
}

@Override
public void onDestroy() {
super.onDestroy();
mManager.stop();
}

    public void myClickHandler(View view){
        switch (view.getId()) {
        case R.id.Button01:
            RadioButton celsiustokelvinButton = (RadioButton) findViewById (R.id.RadioButton05);
            RadioButton celsiustofarenheitButton = (RadioButton) findViewById(R.id.RadioButton01);
            RadioButton farenheittocelsiusButton = (RadioButton) findViewById(R.id.RadioButton02);
            RadioButton farenheittokelvinButton = (RadioButton) findViewById(R.id.RadioButton06);
            RadioButton kelvintocelsiusButton = (RadioButton) findViewById (R.id.RadioButton03);
            RadioButton kelvintofarenheitButton=(RadioButton) findViewById (R.id.RadioButton04);
            float inputValue = Float.parseFloat(text.getText().toString());

              if (celsiustofarenheitButton.isChecked())  {
                text.setText(String
                        .valueOf(convertCelsiusToFarenheit(inputValue)));
            } if (farenheittocelsiusButton.isChecked()) {
                text.setText(String
                        .valueOf(convertFarenheitToCelsius(inputValue)));
            } if (celsiustokelvinButton.isChecked()) {
                text.setText(String
                        .valueOf(convertCelsiusToKelvin(inputValue)));
            } if (farenheittokelvinButton.isChecked()) {
                text.setText(String
                        .valueOf(convertFarenheitToKelvin(inputValue)));
            } if (kelvintocelsiusButton.isChecked()) {
                text.setText(String
                        .valueOf(convertKelvinToCelsius(inputValue)));
            } if (kelvintofarenheitButton.isChecked()) {
                text.setText(String
                        .valueOf(convertKelvinToFarenheit(inputValue)));
            }
            break;

        }}

    private float convertFarenheitToCelsius(float fahrenheit){
        return ((fahrenheit - 32) * 5 / 9);
    }
    private float convertCelsiusToFarenheit(float celsius){
        return ((celsius * 9) / 5) + 32;
    }
    private double convertCelsiusToKelvin(float celsius){
        return celsius + 273.15;
    }
    private double convertFarenheitToKelvin(float farenheit){
        return ((farenheit-32)/(1.8));
    }
    private double convertKelvinToCelsius(float kelvin){
        return kelvin-273.1;
    }
    private double convertKelvinToFarenheit(float kelvin){
        return kelvin*1.8-459.67;
    }
    boolean CheckboxPreference;

    private void getPrefs() {
            // Get the xml/preferences.xml preferences
            SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(getBaseContext());
            CheckboxPreference = prefs.getBoolean("checkboxPref", true);
}

}
</code>```

And here is my Preferences Activity

```<code>import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class Preferences extends PreferenceActivity {

private RadioButton btn01;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    btn01 = (RadioButton)findViewById(R.id.RadioButton01);
    Preference customPref = (Preference) findPreference("customPref");

    customPref.setOnPreferenceClickListener(new OnPreferenceClickListener(){

        public boolean onPreferenceClick(Preference preference) {
            Toast.makeText(getBaseContext(),"The Custom Preference Has Been     Clicked",Toast.LENGTH_LONG).show();
            SharedPreferences customSharedPreference =     getSharedPreferences("myCutomSharedPrefs", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = customSharedPreference.edit();
            editor.putString("myCustomPref","The preference has been clicked");
            editor.commit();

            CheckBox();

            return true;

        }
        private void CheckBox() {
            final CheckBox ThisCheckBox = (CheckBox) findViewById (R.id.checkboxPref);
            ThisCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
                @Override
               public void onCheckedChanged(CompoundButton compoundButton,boolean     test) {
                    if (ThisCheckBox.isChecked()){
                        btn01.setVisibility(View.VISIBLE);
                    } else {
                        btn01.setVisibility(View.GONE);
                    }
                }
            });
        };
    });

}}
</code>```

Sorry there is other stuff in there as well such as an analytics plug in

Anyone have any idea as to why this just isn't working

(Just a side note. When looking at the logcat, clicking the checkbox returned no results)

EDIT: OK i've just ammended my code as suggested but i'm afraid that the preferences still do not affect anything. Anybody have any ideas?? =(

答:
It's not working because for visiblity the values you should use are (reference):</p>

```<code> 0 = VISIBLE
 4 = INVISIBLE
 8 = GONE
</code>```

Body:
Sorry about this guys. This must be like the third question I've had to ask about this project alone. =(

What i want to be able to do is toggle the visibility of a radio button using a check box in a preferences activity.

There are no errors in my code and both activities run fine, but there is no change in visibility when the check box is checked or unchecked.

Here is my Activity with the radiobuttons

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import com.medialets.android.analytics.MMAnalyticsManager;

public class Temperature extends Activity {
MMAnalyticsManager mManager;
private EditText text;

public void onStart(Bundle savedInstanceState){
    super.onStart();
    getPrefs();
}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.temperature);
        text = (EditText)findViewById(R.id.EditText01);

mManager = MMAnalyticsManager.sharedInstance(this);
mManager.start("codeHere", "1.0",
    false);
}

@Override
public void onPause() {
super.onPause();

mManager.pause();
}

@Override
public void onResume() {
super.onResume();

mManager.resume();
}

@Override
public void onDestroy() {
super.onDestroy();
mManager.stop();
}

    public void myClickHandler(View view){
        switch (view.getId()) {
        case R.id.Button01:
            RadioButton celsiustokelvinButton = (RadioButton) findViewById (R.id.RadioButton05);
            RadioButton celsiustofarenheitButton = (RadioButton) findViewById(R.id.RadioButton01);
            RadioButton farenheittocelsiusButton = (RadioButton) findViewById(R.id.RadioButton02);
            RadioButton farenheittokelvinButton = (RadioButton) findViewById(R.id.RadioButton06);
            RadioButton kelvintocelsiusButton = (RadioButton) findViewById (R.id.RadioButton03);
            RadioButton kelvintofarenheitButton=(RadioButton) findViewById (R.id.RadioButton04);
            float inputValue = Float.parseFloat(text.getText().toString());

              if (celsiustofarenheitButton.isChecked())  {
                text.setText(String
                        .valueOf(convertCelsiusToFarenheit(inputValue)));
            } if (farenheittocelsiusButton.isChecked()) {
                text.setText(String
                        .valueOf(convertFarenheitToCelsius(inputValue)));
            } if (celsiustokelvinButton.isChecked()) {
                text.setText(String
                        .valueOf(convertCelsiusToKelvin(inputValue)));
            } if (farenheittokelvinButton.isChecked()) {
                text.setText(String
                        .valueOf(convertFarenheitToKelvin(inputValue)));
            } if (kelvintocelsiusButton.isChecked()) {
                text.setText(String
                        .valueOf(convertKelvinToCelsius(inputValue)));
            } if (kelvintofarenheitButton.isChecked()) {
                text.setText(String
                        .valueOf(convertKelvinToFarenheit(inputValue)));
            }
            break;

        }}

    private float convertFarenheitToCelsius(float fahrenheit){
        return ((fahrenheit - 32) * 5 / 9);
    }
    private float convertCelsiusToFarenheit(float celsius){
        return ((celsius * 9) / 5) + 32;
    }
    private double convertCelsiusToKelvin(float celsius){
        return celsius + 273.15;
    }
    private double convertFarenheitToKelvin(float farenheit){
        return ((farenheit-32)/(1.8));
    }
    private double convertKelvinToCelsius(float kelvin){
        return kelvin-273.1;
    }
    private double convertKelvinToFarenheit(float kelvin){
        return kelvin*1.8-459.67;
    }
    boolean CheckboxPreference;

    private void getPrefs() {
            // Get the xml/preferences.xml preferences
            SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(getBaseContext());
            CheckboxPreference = prefs.getBoolean("checkboxPref", true);
}

}

And here is my Preferences Activity

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class Preferences extends PreferenceActivity {

private RadioButton btn01;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    btn01 = (RadioButton)findViewById(R.id.RadioButton01);
    Preference customPref = (Preference) findPreference("customPref");

    customPref.setOnPreferenceClickListener(new OnPreferenceClickListener(){

        public boolean onPreferenceClick(Preference preference) {
            Toast.makeText(getBaseContext(),"The Custom Preference Has Been     Clicked",Toast.LENGTH_LONG).show();
            SharedPreferences customSharedPreference =     getSharedPreferences("myCutomSharedPrefs", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = customSharedPreference.edit();
            editor.putString("myCustomPref","The preference has been clicked");
            editor.commit();

            CheckBox();

            return true;

        }
        private void CheckBox() {
            final CheckBox ThisCheckBox = (CheckBox) findViewById (R.id.checkboxPref);
            ThisCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
                @Override
               public void onCheckedChanged(CompoundButton compoundButton,boolean     test) {
                    if (ThisCheckBox.isChecked()){
                        btn01.setVisibility(View.VISIBLE);
                    } else {
                        btn01.setVisibility(View.GONE);
                    }
                }
            });
        };
    });

}}

Sorry there is other stuff in there as well such as an analytics plug in

Anyone have any idea as to why this just isn't working

(Just a side note. When looking at the logcat, clicking the checkbox returned no results)

EDIT: OK i've just ammended my code as suggested but i'm afraid that the preferences still do not affect anything. Anybody have any ideas?? =(

Body:
It's not working because for visiblity the values you should use are (reference):

 0 = VISIBLE
 4 = INVISIBLE
 8 = GONE