问:
Xpages setvalue bug?

My database allow Anonymous to access the database and submit form to do process
It have 3 roles inside [Applicant],[Admin],[Reviewer]

problem:

I need to update "Email" field by combining 3 different "mail" field to combine it. So i use add element but it seem save wrong data, it give an extra [applicant]. Attached image will display how it display

```<code>var v;
//  Update mail 1 and mail 2 and mail3 into Email field!
if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")!=null && document1.getValue("Mail2")!="")&&
    (document1.getValue("Mail3")!=null && document1.getValue("Mail3")!="")
)   //all not empty
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail2")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail3")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")==null && document1.getValue("Mail2")=="")&&
    (document1.getValue("Mail3")===null && document1.getValue("Mail3")=="")
)   //  only have mail 1
    {
        document1.replaceItemValue("Email", document1.getValue("Mail1")+"@brookedockyard.com.my")
    }
else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")!=null && document1.getValue("Mail2")!="")&&
    (document1.getValue("Mail3")==null && document1.getValue("Mail3")=="")
)   //  only have mail 1 and mail 2
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail2")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")==null && document1.getValue("Mail2")=="")&&
    (document1.getValue("Mail3")!=null && document1.getValue("Mail3")!="")
)       //  only have mail 1 and mail 3
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail3")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

    }
</code>```

i am using serverside javascript to save document. But during save it add extra information inside the system.

答:
I think your code needs some optimization. This code does the same as yours:

```<code>var v = [];
["Mail1", "Mail2", "Mail3"].forEach(function(name) {
    if (document1.getValue(name)) {
        v.push(document1.getValue(name)+"@brookedockyard.com.my");
    }
});
document1.replaceItemValue("Email",v);
</code>```

In addition it initializes the variable vas an empty array. Use arrays instead of Vectors when possible. It's more JavaScript native.

Title: Xpages setvalue bug?

Body:
My database allow Anonymous to access the database and submit form to do process
It have 3 roles inside [Applicant],[Admin],[Reviewer]

problem:

I need to update "Email" field by combining 3 different "mail" field to combine it. So i use add element but it seem save wrong data, it give an extra [applicant]. Attached image will display how it display

var v;
//  Update mail 1 and mail 2 and mail3 into Email field!
if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")!=null && document1.getValue("Mail2")!="")&&
    (document1.getValue("Mail3")!=null && document1.getValue("Mail3")!="")
)   //all not empty
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail2")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail3")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")==null && document1.getValue("Mail2")=="")&&
    (document1.getValue("Mail3")===null && document1.getValue("Mail3")=="")
)   //  only have mail 1
    {
        document1.replaceItemValue("Email", document1.getValue("Mail1")+"@brookedockyard.com.my")
    }
else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")!=null && document1.getValue("Mail2")!="")&&
    (document1.getValue("Mail3")==null && document1.getValue("Mail3")=="")
)   //  only have mail 1 and mail 2
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail2")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")==null && document1.getValue("Mail2")=="")&&
    (document1.getValue("Mail3")!=null && document1.getValue("Mail3")!="")
)       //  only have mail 1 and mail 3
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail3")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

    }

i am using serverside javascript to save document. But during save it add extra information inside the system.

Body:
I think your code needs some optimization. This code does the same as yours:

var v = [];
["Mail1", "Mail2", "Mail3"].forEach(function(name) {
    if (document1.getValue(name)) {
        v.push(document1.getValue(name)+"@brookedockyard.com.my");
    }
});
document1.replaceItemValue("Email",v);

In addition it initializes the variable vas an empty array. Use arrays instead of Vectors when possible. It's more JavaScript native.


来源: stackexchange

问:
How to generate classes.dex.toc files?
Here is the make file i am using to generate and JAVA module which i am importing in another module. While compiling it, the build breaks saying

```<code>error: 'out/target/common/obj/JAVA_LIBRARIES/android.hardware.automotive.vehicle@2.0-java_intermediates/classes.dex.toc', needed by 'out/target/common/obj/JAVA_LIBRARIES/vendor.harman.hardware.automotive.vehicle.fca_r1@1.0-java_intermediates/with-local/classes.dex', missing and no known rule to make it
</code>```

Any suggestion on how to generate a .toc file in general?
Anything specific to be added in the make file?

答:
Usually such toc file will be auto generated during fullbuild, but if it is missing when you build single module you can manually generate the classes.dex.toc with the following command:

```<code>dexdump2 classes.dex >> classes.dex.toc
</code>```

If you want to know the details, please read the sourcecode of android build system: _transform_dex-to-toc
https://android.googlesource.com/platform/build/+/f972a4a980660d2347ace8fdc7c668403c0e9697/core/definitions.mk

ContentLicense: CC BY-SA 3.0

Title: How to generate classes.dex.toc files?

Body:
Here is the make file i am using to generate and JAVA module which i am importing in another module. While compiling it, the build breaks saying

error: 'out/target/common/obj/JAVA_LIBRARIES/android.hardware.automotive.vehicle@2.0-java_intermediates/classes.dex.toc', needed by 'out/target/common/obj/JAVA_LIBRARIES/vendor.harman.hardware.automotive.vehicle.fca_r1@1.0-java_intermediates/with-local/classes.dex', missing and no known rule to make it

Any suggestion on how to generate a .toc file in general?
Anything specific to be added in the make file?

Body:
Usually such toc file will be auto generated during fullbuild, but if it is missing when you build single module you can manually generate the classes.dex.toc with the following command:

dexdump2 classes.dex >> classes.dex.toc

If you want to know the details, please read the sourcecode of android build system: _transform_dex-to-toc
https://android.googlesource.com/platform/build/+/f972a4a980660d2347ace8fdc7c668403c0e9697/core/definitions.mk


问:
Java Processbuilder GitLog pretty-format
I create a java method to make a gitlog from a git repo.

Method:

```<code>String gitLogFormat = "--pretty=format:\"%H %an %ad %s\"";

List<String> cmds = Arrays.asList("git", "log", gitLogFormat, "--numstat",  "--date=short");
ProcessBuilder builder = new ProcessBuilder(cmds);
builder.directory(new File( GitPath.toAbsolutePath().toString() ));

builder.redirectOutput(ProcessBuilder.Redirect.to( path.resolve("gitlog.txt").toFile() ) );

Process process = builder.start();
</code>```

If i run this method without gitLogFormat it works and I get a file with the Gitlog. But with the format I always get the exitcode 128.

Is there a Problem with the \" because the other both options --numstat and --date=short works?

Update

I try it with :

```<code>String gitLogFormat = "--pretty=format:\"%H_%an_%ad_%s\"";
</code>```

and it works.

The Whitespaces are the Problems. Have anyone an idea how i can use the code with withespaces because the Log should have spaces between the informations.

答:
Update 2 and Solution:

The Problem are the Whitespaces so i must add between every whitespace a ,

It works with this code :

```<code>List<String> cmds = Arrays.asList("git", "log", "--pretty=format:\"%H" , "%an" , "%ad" , "%s\"" , "--numstat" , "--date=short");
</code>```

Body:
I create a java method to make a gitlog from a git repo.

Method:

String gitLogFormat = "--pretty=format:\"%H %an %ad %s\"";

List<String> cmds = Arrays.asList("git", "log", gitLogFormat, "--numstat",  "--date=short");
ProcessBuilder builder = new ProcessBuilder(cmds);
builder.directory(new File( GitPath.toAbsolutePath().toString() ));

builder.redirectOutput(ProcessBuilder.Redirect.to( path.resolve("gitlog.txt").toFile() ) );

Process process = builder.start();

If i run this method without gitLogFormat it works and I get a file with the Gitlog. But with the format I always get the exitcode 128.

Is there a Problem with the \" because the other both options --numstat and --date=short works?

Update

I try it with :

String gitLogFormat = "--pretty=format:\"%H_%an_%ad_%s\"";

and it works.

The Whitespaces are the Problems. Have anyone an idea how i can use the code with withespaces because the Log should have spaces between the informations.

Body:
Update 2 and Solution:

The Problem are the Whitespaces so i must add between every whitespace a ,

It works with this code :

List<String> cmds = Arrays.asList("git", "log", "--pretty=format:\"%H" , "%an" , "%ad" , "%s\"" , "--numstat" , "--date=short");


问:
Cannot retrieve stereotypes from UML model generated using Papyrus with Acceleo
I am currently testing out the DSL capabilities of Papyrus in combination with Acceleo and I am currently encountering a problem.

I created a simple relational database metamodel using UML 2 profiles with Papyrus. I then created a gruesome library model using the meta-model defined.

Then I created a very very simple Acceleo template file, in which I try to print some elements' stereotypes :

```<code>[template public generateElement(p : Package)]
[comment @main/]
[file (p.name.concat('_debug.txt'), false, 'UTF-8')]
Creating file for package [p.name/]
Stereotypes: [for (st : Stereotype | p.getAppliedStereotypes()) separator(',')][st.name/][/for]
[/file]
[/template]
</code>```

When I use the OCL console on my model, "getAppliedStereotypes()" works just fine. But when I run my Acceleo, there is nothing behind "Stereotypes", even though the generator terminates without any error code...

Do you have any idea what is going on ?

答:
This is most likely the same issue as I pointed out for this question. Acceleo generations operate in stand-alone mode, so you have to actually tell it where to find the profile you're using.

The Acceleo FAQ has some examples with "standard" profiles, you will have to follow the same process for your own defined profiles.

Body:
I am currently testing out the DSL capabilities of Papyrus in combination with Acceleo and I am currently encountering a problem.

I created a simple relational database metamodel using UML 2 profiles with Papyrus. I then created a gruesome library model using the meta-model defined.

Then I created a very very simple Acceleo template file, in which I try to print some elements' stereotypes :

[template public generateElement(p : Package)]
[comment @main/]
[file (p.name.concat('_debug.txt'), false, 'UTF-8')]
Creating file for package [p.name/]
Stereotypes: [for (st : Stereotype | p.getAppliedStereotypes()) separator(',')][st.name/][/for]
[/file]
[/template]

When I use the OCL console on my model, "getAppliedStereotypes()" works just fine. But when I run my Acceleo, there is nothing behind "Stereotypes", even though the generator terminates without any error code...

Do you have any idea what is going on ?


问:
How to Create a Jar that uses a file to save app information to
I have a Java project that creates a UI with a table, The table is editable and when you add entries, I have it being saved into a json in a data folder outside of src in the project folder. I'm using Intellij, and I know to create a JAR to make it in artefacts, and the data folder is selected as a resource. But when the JAR is created it cannot find the file data/items.json is this because JARS cannot edit files inside them?</p>

答:
Jar files are read only, that means you can't save informations inside the jar. You can save files inside an read them but you can't edit them.

In your case there are more or less two options:

Save the *.json file in e.g the OS Temp path or somewhere else where you can read and write them.

Handle like zip - https://stackoverflow.com/a/4056713/8087490 -

Locate the JAR file and open as a ZIP archive reader.

Create a ZIP archive writer to write a new version of JAR file.

Write the application's files to the writer.

Write all resources from the ZIP reader to the writer, excluding old versions of the applications files.

Close the reader and writer.

Rename the new version of the JAR to replace the old one.


问:
Save List to SharedPreferences in android activity
Im trying to save list data in preferences

```<code>List<AppGrid> mArrayProducts = new ArrayList<AppGrid>();
Gson gson = new Gson();
            String jsonObject = gson.toJson(mArrayProducts);
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("MyObject", jsonObject);
            editor.commit();
            Intent intent = new Intent(InstalledAppActivity.this,MainActivity.class);
            startActivity(intent);
</code>```

AppGrid.java

```<code>private String dataDir;
private Drawable icon;
private String id;
private String name;
private String launcherName;
private String packageName;
private int pageIndex;
private int position;
private boolean sysApp;
public boolean selected;
public AppGrid() {

}

public AppGrid(Drawable icon, String title, String packageName) {
    this.icon = icon;
    this.name = title;
    this.packageName = packageName;
}
protected AppGrid(Parcel in) {
    name = in.readString();
    packageName = in.readString();
    selected = in.readByte() != 0;
}

public String getDataDir() {
    return this.dataDir;
}

public Drawable getIcon() {
    return this.icon;
}

public String getId() {
    return this.id;
}

public String getName() {
    return this.name;
}

public String getPackageName() {
    return this.packageName;
}

public int getPageIndex() {
    return this.pageIndex;
}

public int getPosition() {
    return this.position;
}

public void setDataDir(String paramString) {
    this.dataDir = paramString;
}

public void setIcon(Drawable paramDrawable) {
    this.icon = paramDrawable;
}

public void setId(String paramString) {
    this.id = paramString;
}

public void setName(String paramString) {
    this.name = paramString;
}

public void setPackageName(String paramString) {
    this.packageName = paramString;
}

public void setPageIndex(int paramInt) {
    this.pageIndex = paramInt;
}

public void setPosition(int paramInt) {
    this.position = paramInt;
}

public String toString() {
    return "AppGrid [packageName=" + this.packageName + ", name=" + this.name + ", icon=" + this.icon + ", dataDir=" + this.dataDir + "]";
}

public boolean isSysApp() {
    return sysApp;
}

public void setSysApp(boolean sysApp) {
    this.sysApp = sysApp;
}

public String getLauncherName() {
    return launcherName;
}

public void setLauncherName(String launcherName) {
    this.launcherName = launcherName;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(name);
    parcel.writeString(packageName);
   /* Bitmap bitmap = (Bitmap)((BitmapDrawable) icon ).getBitmap();
    parcel.writeParcelable(bitmap, i);*/
    parcel.writeByte((byte) (selected ? 1 : 0));
}
public boolean isSelected() {
    return selected;
}
public void setSelected(boolean selected) {
    this.selected = selected;
}

public static final Creator<AppGrid> CREATOR = new Creator<AppGrid>() {
    @Override
    public AppGrid createFromParcel(Parcel in) {
        return new AppGrid(in);
    }

    @Override
    public AppGrid[] newArray(int size) {
        return new AppGrid[size];
    }
};
</code>```

}

Data is not saving in shared preferences.Could you please help me

Logcat:

D/Error: ERR: stack=java.lang.OutOfMemoryError: Failed to allocate a
  16 byte allocation with 4194272 free bytes and 4MB until OOM; failed
  due to fragmentation (required continguous free 4096 bytes for a new
  buffer where largest contiguous free 0 bytes)

答:
It seems that you are trying to saving a very large value. SharedPreferences is not used for storing data. it just store simple data. It is designed to store small, key value pairs such as settings , user names , ids , options etc.

Technically, all shared prefs are stored in /data/data/[package name]/shared_prefs/[app name].xml, so i think there's no limit based on architecture.

But some devices might have difficulties and performance issues on this matter. thus, basically there is a limitations of SharedPreference data for few devices

So its better to use SQLite database when you have to deal with huge amount of data.

EDIT

If i not mistaken, you are trying to store drawable icon which might lead large byte stored. best practices is just store the IDs of the drawable only..

```<code>public class AppGrid {

    private String dataDir;
    private int Drawableicon;
    private String id;
    private String name;
    private String launcherName;
    private String packageName;
    private int pageIndex;
    private int position;
    private boolean sysApp;
    public boolean selected;

    public AppGrid(@drawable int icon, String title, String packageName) {
        this.Drawableicon = icon;
        this.name = title;
        this.packageName = packageName;
    }

    //setter and getter
}
</code>```

just create simple model class. no need Parcel..

Body:
Im trying to save list data in preferences

List<AppGrid> mArrayProducts = new ArrayList<AppGrid>();
Gson gson = new Gson();
            String jsonObject = gson.toJson(mArrayProducts);
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("MyObject", jsonObject);
            editor.commit();
            Intent intent = new Intent(InstalledAppActivity.this,MainActivity.class);
            startActivity(intent);

AppGrid.java

private String dataDir;
private Drawable icon;
private String id;
private String name;
private String launcherName;
private String packageName;
private int pageIndex;
private int position;
private boolean sysApp;
public boolean selected;
public AppGrid() {

}

public AppGrid(Drawable icon, String title, String packageName) {
    this.icon = icon;
    this.name = title;
    this.packageName = packageName;
}
protected AppGrid(Parcel in) {
    name = in.readString();
    packageName = in.readString();
    selected = in.readByte() != 0;
}

public String getDataDir() {
    return this.dataDir;
}

public Drawable getIcon() {
    return this.icon;
}

public String getId() {
    return this.id;
}

public String getName() {
    return this.name;
}

public String getPackageName() {
    return this.packageName;
}

public int getPageIndex() {
    return this.pageIndex;
}

public int getPosition() {
    return this.position;
}

public void setDataDir(String paramString) {
    this.dataDir = paramString;
}

public void setIcon(Drawable paramDrawable) {
    this.icon = paramDrawable;
}

public void setId(String paramString) {
    this.id = paramString;
}

public void setName(String paramString) {
    this.name = paramString;
}

public void setPackageName(String paramString) {
    this.packageName = paramString;
}

public void setPageIndex(int paramInt) {
    this.pageIndex = paramInt;
}

public void setPosition(int paramInt) {
    this.position = paramInt;
}

public String toString() {
    return "AppGrid [packageName=" + this.packageName + ", name=" + this.name + ", icon=" + this.icon + ", dataDir=" + this.dataDir + "]";
}

public boolean isSysApp() {
    return sysApp;
}

public void setSysApp(boolean sysApp) {
    this.sysApp = sysApp;
}

public String getLauncherName() {
    return launcherName;
}

public void setLauncherName(String launcherName) {
    this.launcherName = launcherName;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(name);
    parcel.writeString(packageName);
   /* Bitmap bitmap = (Bitmap)((BitmapDrawable) icon ).getBitmap();
    parcel.writeParcelable(bitmap, i);*/
    parcel.writeByte((byte) (selected ? 1 : 0));
}
public boolean isSelected() {
    return selected;
}
public void setSelected(boolean selected) {
    this.selected = selected;
}

public static final Creator<AppGrid> CREATOR = new Creator<AppGrid>() {
    @Override
    public AppGrid createFromParcel(Parcel in) {
        return new AppGrid(in);
    }

    @Override
    public AppGrid[] newArray(int size) {
        return new AppGrid[size];
    }
};

}

Data is not saving in shared preferences.Could you please help me

Logcat:

D/Error: ERR: stack=java.lang.OutOfMemoryError: Failed to allocate a
  16 byte allocation with 4194272 free bytes and 4MB until OOM; failed
  due to fragmentation (required continguous free 4096 bytes for a new
  buffer where largest contiguous free 0 bytes)

Body:
It seems that you are trying to saving a very large value. SharedPreferences is not used for storing data. it just store simple data. It is designed to store small, key value pairs such as settings , user names , ids , options etc.

Technically, all shared prefs are stored in /data/data/[package name]/shared_prefs/[app name].xml, so i think there's no limit based on architecture.

But some devices might have difficulties and performance issues on this matter. thus, basically there is a limitations of SharedPreference data for few devices

So its better to use SQLite database when you have to deal with huge amount of data.

EDIT

If i not mistaken, you are trying to store drawable icon which might lead large byte stored. best practices is just store the IDs of the drawable only..

public class AppGrid {

    private String dataDir;
    private int Drawableicon;
    private String id;
    private String name;
    private String launcherName;
    private String packageName;
    private int pageIndex;
    private int position;
    private boolean sysApp;
    public boolean selected;

    public AppGrid(@drawable int icon, String title, String packageName) {
        this.Drawableicon = icon;
        this.name = title;
        this.packageName = packageName;
    }

    //setter and getter
}

just create simple model class. no need Parcel..


问:
Validation in MEAN stack .....?
I am developing a MEAN stack application but i stuck at validation(user-inputs). I know the client-side validations are done in Angular-JS but i am confused where to validate on server side. Either to use mongooose for validations or don't do any validation on mongooose(just store) do validations only in server(Node/express using some modules) or  validate on both server-level and database-level....????

What should i do pls help me choose which practice is best.....????

Thanks.

答:
As a MEAN stack developer there are various ways to validate the form...
1.) AngularJs form validations
2.) Mongoose Validation
3.) Backend Validation ( Express validator ot nodeValidator )

==> Validation in mongoose

Ex.

```<code>var userSchema = new Schema({
  phone: {
    type: String,
    required: [true, 'User phone number required']
  },
  name: String,
  subDoc: [
    {
      newName:String,
      data:String
    }
  ]
});
</code>```

Above code shows simple integration of mongoose validator.

Validation in mongoose schema can create problems when writing the document
and worse situation can be generated when there are nested field and i am sure there will be. There are chances of modification of schema in such situation you to manage the validation, so much trouble i have faced..

So its a better IDEA to go with node validator or express validator which are super simple to use and provide lots of different type of validation options..

TRY
node-validator,
Express validator

js.com/package/node-validator

I personally suggest Express validator. which is simple and provide most of thing you need.

Title: Validation in MEAN stack .....?

Body:
As a MEAN stack developer there are various ways to validate the form...
1.) AngularJs form validations
2.) Mongoose Validation
3.) Backend Validation ( Express validator ot nodeValidator )

==> Validation in mongoose

Ex.

var userSchema = new Schema({
  phone: {
    type: String,
    required: [true, 'User phone number required']
  },
  name: String,
  subDoc: [
    {
      newName:String,
      data:String
    }
  ]
});

Above code shows simple integration of mongoose validator.

Validation in mongoose schema can create problems when writing the document
and worse situation can be generated when there are nested field and i am sure there will be. There are chances of modification of schema in such situation you to manage the validation, so much trouble i have faced..

So its a better IDEA to go with node validator or express validator which are super simple to use and provide lots of different type of validation options..

TRY
node-validator,
Express validator

js.com/package/node-validator

I personally suggest Express validator. which is simple and provide most of thing you need.


问:
Custom GIF Keyboard in iOS8
I am creating Custom GIF Keyboard in iOS8 using app extension. I was created layout of my custom keyboard. I was implement LongPress Gesture for selecting GIF Image but its not work. so what can i do for this or any suggestion regarding to this?

```<code>- (void)textWillChange:(id<UITextInput>)textInput {
    [self.textDocumentProxy insertText:@"Hi"];
}
</code>```

I also tried with UITextInputDelegate mentioned above.
This method is also deals with only text append. But My concern is to load gif or png image in input area.

答:
You couldn't load a gif directly in the input area. To do that you have to copy the gif to the pasteboard and then paste the gif in the input area.

To copy the gif into the pasteboard you need to convert it into the NSData.

Here is the demo code in Swift 3.0.

```<code>let pb = UIPasteboard.general
let data = NSData(contentsOfURL: url)
 if data != nil
  {
     self.pb.setData(data!, forPasteboardType: kUTTypeGIF as String)
  }
</code>```

Title: Custom GIF Keyboard in iOS8

Body:
I am creating Custom GIF Keyboard in iOS8 using app extension. I was created layout of my custom keyboard. I was implement LongPress Gesture for selecting GIF Image but its not work. so what can i do for this or any suggestion regarding to this?

- (void)textWillChange:(id<UITextInput>)textInput {
    [self.textDocumentProxy insertText:@"Hi"];
}

I also tried with UITextInputDelegate mentioned above.
This method is also deals with only text append. But My concern is to load gif or png image in input area.

Body:
You couldn't load a gif directly in the input area. To do that you have to copy the gif to the pasteboard and then paste the gif in the input area.

To copy the gif into the pasteboard you need to convert it into the NSData.

Here is the demo code in Swift 3.0.

let pb = UIPasteboard.general
let data = NSData(contentsOfURL: url)
 if data != nil
  {
     self.pb.setData(data!, forPasteboardType: kUTTypeGIF as String)
  }


问:
Android - SQlite check if value in row exists
This question is similar to this and this.

I have 4 columns in my database (id, name, surname, image). I only want to check if the name that is being entered already exists in "name" column.

here is my SQLiteOpenHelper:

```<code>public class SQLiteHelper extends SQLiteOpenHelper {

public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
}

public void queryData(String sql){
    SQLiteDatabase database = getWritableDatabase();
    database.execSQL(sql);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

}

public void insertData(String name, String surname, byte[] image){
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO STUDENTS VALUES (NULL, ?, ?, ?)";

    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1, name);
    statement.bindString(2, surname);
    statement.bindBlob(3, image);

    statement.executeInsert();

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}

/*public void removeSingleContact(String name, String price, byte[] image) {

    SQLiteDatabase dbb = getWritableDatabase();
    dbb.delete(name, surname, image);

}*/

public Cursor getData(String sql){
    SQLiteDatabase database = getReadableDatabase();
    return database.rawQuery(sql, null);
}

}
</code>```

and this is how I add to SQlite;

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

    public static SQLiteHelper sqLiteHelper;

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

        sqLiteHelper = new SQLiteHelper(this, "StudentsDB.sqlite", null, 1);

        sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS STUDENTS(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, surname VARCHAR, image BLOB)");

            btnAdd.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {

                        if (edtName.getText().toString().trim().length() == 0) {
                            Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();

                        } else
                            try {

                                    //THIS IS WHERE I WANT TO CHECK---------

                                    sqLiteHelper.insertData(
                                            edtName.getText().toString().trim(),
                                            edtPrice.getText().toString().trim(),
                                            imageViewToByte(imageView)

                                    );

                                        Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();

                                        finish();
                                    }

                                }
                            } catch (Exception e) {
                            e.printStackTrace();
                            }

                    }
                });
</code>```

EDIT----
Thank you for the help so far. I have 2 buttons, one for update and one for insert, the problem I am facing is how will I know what row to update without using an ID. I have a gridview that is being populated by cardviews, in the cardview there is a button to edit info, please see image.

https://i.stack.imgur.com/aFJTl.png

If I click on the exit sign I do;

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

            @Override
            public void onClick(View v) {
                // Do something
                Intent editintent = new Intent(context, AddEditStudent.class);
                editintent.putExtra("studentname", finalHolder.txtName.getText().toString());
                editintent.putExtra("studentsurname", finalHolder.txtPrice.getText().toString());

                context.startActivity(editintent);
            }
        });
</code>```

then in AddEditStudent Class is where the insert and update is.

答:
i think this will help you.</p>

```<code>boolean isAdded(String name) {
    SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
    String query="SELECT * FROM "+TABLE_NAME+" WHERE "+NAME+" = "+name;
    Cursor cursor = sqLiteDatabase.rawQuery(query,null);
    if(cursor.getCount()>0)
        return true;
    else
        return false;
}
</code>```

Body:
This question is similar to this and this.

I have 4 columns in my database (id, name, surname, image). I only want to check if the name that is being entered already exists in "name" column.

here is my SQLiteOpenHelper:

public class SQLiteHelper extends SQLiteOpenHelper {

public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
}

public void queryData(String sql){
    SQLiteDatabase database = getWritableDatabase();
    database.execSQL(sql);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

}

public void insertData(String name, String surname, byte[] image){
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO STUDENTS VALUES (NULL, ?, ?, ?)";

    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1, name);
    statement.bindString(2, surname);
    statement.bindBlob(3, image);

    statement.executeInsert();

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}

/*public void removeSingleContact(String name, String price, byte[] image) {

    SQLiteDatabase dbb = getWritableDatabase();
    dbb.delete(name, surname, image);

}*/

public Cursor getData(String sql){
    SQLiteDatabase database = getReadableDatabase();
    return database.rawQuery(sql, null);
}

}

and this is how I add to SQlite;

public class AddEditStudent extends AppCompatActivity {

    public static SQLiteHelper sqLiteHelper;

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

        sqLiteHelper = new SQLiteHelper(this, "StudentsDB.sqlite", null, 1);

        sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS STUDENTS(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, surname VARCHAR, image BLOB)");

            btnAdd.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {

                        if (edtName.getText().toString().trim().length() == 0) {
                            Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();

                        } else
                            try {

                                    //THIS IS WHERE I WANT TO CHECK---------

                                    sqLiteHelper.insertData(
                                            edtName.getText().toString().trim(),
                                            edtPrice.getText().toString().trim(),
                                            imageViewToByte(imageView)

                                    );

                                        Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();

                                        finish();
                                    }

                                }
                            } catch (Exception e) {
                            e.printStackTrace();
                            }

                    }
                });

EDIT----
Thank you for the help so far. I have 2 buttons, one for update and one for insert, the problem I am facing is how will I know what row to update without using an ID. I have a gridview that is being populated by cardviews, in the cardview there is a button to edit info, please see image.

https://i.stack.imgur.com/aFJTl.png

If I click on the exit sign I do;

holder.dit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Do something
                Intent editintent = new Intent(context, AddEditStudent.class);
                editintent.putExtra("studentname", finalHolder.txtName.getText().toString());
                editintent.putExtra("studentsurname", finalHolder.txtPrice.getText().toString());

                context.startActivity(editintent);
            }
        });

then in AddEditStudent Class is where the insert and update is.

Body:
i think this will help you.

boolean isAdded(String name) {
    SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
    String query="SELECT * FROM "+TABLE_NAME+" WHERE "+NAME+" = "+name;
    Cursor cursor = sqLiteDatabase.rawQuery(query,null);
    if(cursor.getCount()>0)
        return true;
    else
        return false;
}


问:
Getting value of each selected item using a contextual action bar
I am using a contextual action bar and wish to retrieve each value selected to pass to another activity after I click on the 'mail' button. How can I do this?e

Code for the CAB.

```<code>mAdapter = new SelectionAdapter(this, R.layout.activity_result, R.id.name, new String[] {TAG_NAME, TAG_ROOM_PRICE});
    setListAdapter(mAdapter);
    lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    getListView().setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {

        private int nr = 0;
        @Override
        public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
            nr = 0;
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.contextual_menu, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                case R.id.email:

            }
            return false;
        }

        @Override
        public void onDestroyActionMode(android.view.ActionMode mode) {
            mAdapter.clearSelection();
        }

        @Override
        public void onItemCheckedStateChanged(android.view.ActionMode mode, int position, long id, boolean checked) {
            if (checked) {
                nr++;
                mAdapter.setNewSelection(position, checked);
            } else {
                nr--;
                mAdapter.removeSelection(position);
            }
            mode.setTitle("No: of resorts selected: " + nr);
        }
    });
    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            //String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
            getListView().setItemChecked(position, !mAdapter.isPositionChecked(position));
            return true;
        }
    });
</code>```

Selection adapter class which is used to define the object mAdapter

```<code>private class SelectionAdapter extends ArrayAdapter<String> {

    private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();

    public SelectionAdapter(Context context, int resource, int textViewResourceId, String[] objects) {
        super(context, resource, textViewResourceId, objects);
    }

    public void setNewSelection(int position, boolean value) {
        mSelection.put(position, value);
        notifyDataSetChanged();
    }

    public boolean isPositionChecked(int position) {
        Boolean result = mSelection.get(position);
        return result == null ? false : result;
    }

    public Set<Integer> getCurrentCheckedPosition() {
        return mSelection.keySet();
    }

    public void removeSelection(int position) {
        mSelection.remove(position);
        notifyDataSetChanged();
    }

    public void clearSelection() {
        mSelection = new HashMap<Integer, Boolean>();
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = super.getView(position, convertView, parent);//let the adapter handle setting up the row views
        v.setBackgroundColor(getResources().getColor(android.R.color.background_light)); //default color

        if (mSelection.get(position) != null) {
            v.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));// this is a selected position so make it red
        }
        return v;
    }
}
</code>```

I wish to retrieve the String value of every selection that I make

答:
I found the solution.

```<code>mAdapter.setNewSelection(position, checked);
                String get_list = resortsList.get(position).get(TAG_NAME);
                stringList.add(get_list);
</code>```

And to remove the item selected when deselected:`int i;

```<code>for(i = 0 ; i < stringList.size(); i++){
     if(stringList.get(i).equals(resortsList.get(position).get(TAG_NAME))){
          stringList.remove(i);
          Log.d("String List: ", stringList.toString());
          break;
          }
 }`
</code>```

Body:
I am using a contextual action bar and wish to retrieve each value selected to pass to another activity after I click on the 'mail' button. How can I do this?e

Code for the CAB.

mAdapter = new SelectionAdapter(this, R.layout.activity_result, R.id.name, new String[] {TAG_NAME, TAG_ROOM_PRICE});
    setListAdapter(mAdapter);
    lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    getListView().setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {

        private int nr = 0;
        @Override
        public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
            nr = 0;
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.contextual_menu, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                case R.id.email:

            }
            return false;
        }

        @Override
        public void onDestroyActionMode(android.view.ActionMode mode) {
            mAdapter.clearSelection();
        }

        @Override
        public void onItemCheckedStateChanged(android.view.ActionMode mode, int position, long id, boolean checked) {
            if (checked) {
                nr++;
                mAdapter.setNewSelection(position, checked);
            } else {
                nr--;
                mAdapter.removeSelection(position);
            }
            mode.setTitle("No: of resorts selected: " + nr);
        }
    });
    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            //String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
            getListView().setItemChecked(position, !mAdapter.isPositionChecked(position));
            return true;
        }
    });

Selection adapter class which is used to define the object mAdapter

private class SelectionAdapter extends ArrayAdapter<String> {

    private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();

    public SelectionAdapter(Context context, int resource, int textViewResourceId, String[] objects) {
        super(context, resource, textViewResourceId, objects);
    }

    public void setNewSelection(int position, boolean value) {
        mSelection.put(position, value);
        notifyDataSetChanged();
    }

    public boolean isPositionChecked(int position) {
        Boolean result = mSelection.get(position);
        return result == null ? false : result;
    }

    public Set<Integer> getCurrentCheckedPosition() {
        return mSelection.keySet();
    }

    public void removeSelection(int position) {
        mSelection.remove(position);
        notifyDataSetChanged();
    }

    public void clearSelection() {
        mSelection = new HashMap<Integer, Boolean>();
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = super.getView(position, convertView, parent);//let the adapter handle setting up the row views
        v.setBackgroundColor(getResources().getColor(android.R.color.background_light)); //default color

        if (mSelection.get(position) != null) {
            v.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));// this is a selected position so make it red
        }
        return v;
    }
}

I wish to retrieve the String value of every selection that I make

Body:
I found the solution.

mAdapter.setNewSelection(position, checked);
                String get_list = resortsList.get(position).get(TAG_NAME);
                stringList.add(get_list);

And to remove the item selected when deselected:`int i;

for(i = 0 ; i < stringList.size(); i++){
     if(stringList.get(i).equals(resortsList.get(position).get(TAG_NAME))){
          stringList.remove(i);
          Log.d("String List: ", stringList.toString());
          break;
          }
 }`


问:
Space Complexity of an array?
I have an array of size N, and N is <=200.

What would be the space complexity here.

O(1) or (N) - considering the constraint N.

答:
It depends on the case of your problem.if you use only constant amount of memory (or space). So, space complexity is O(1).

However, if you have some data structures like a 1D-array, designed to hold N elements, where N can vary from input-to-input, then the amount of memory required is dependent on N. When N is small, the space required is also small. When N is large, then space required is also large. So, there is a linear dependence on the space required and the input size. That is O(N) space.

Similarly, if you have a 2D-array of size NxN, then generally, the space required is O(N^2).

Consider the following example of finding the minimum space required for the algorithm:

```<code> Scanner in = new Scanner(System.in);
 int n = in.nextInt();
 int[] array = new int[n];
 for(int i = 0; i < n; i++){
     array[i] = in.nextInt();
 }
 int minimum = array[0];
 for(int i = 0; i < n; i++){
     if (array[i] < minimum){
        minimum = array[i];
     }
 }
 System.out.println(minimum);
</code>```

Here, we are having an array, whose size varies with n. Total space requirement = 2 + N, where 2 is for the variables n and minimum and N is for the array. So, the space complexity of this algorithm is O(N).

I hope this was what you were looking for.

Title: Space Complexity of an array?

Body:
It depends on the case of your problem.if you use only constant amount of memory (or space). So, space complexity is O(1).

However, if you have some data structures like a 1D-array, designed to hold N elements, where N can vary from input-to-input, then the amount of memory required is dependent on N. When N is small, the space required is also small. When N is large, then space required is also large. So, there is a linear dependence on the space required and the input size. That is O(N) space.

Similarly, if you have a 2D-array of size NxN, then generally, the space required is O(N^2).

Consider the following example of finding the minimum space required for the algorithm:

 Scanner in = new Scanner(System.in);
 int n = in.nextInt();
 int[] array = new int[n];
 for(int i = 0; i < n; i++){
     array[i] = in.nextInt();
 }
 int minimum = array[0];
 for(int i = 0; i < n; i++){
     if (array[i] < minimum){
        minimum = array[i];
     }
 }
 System.out.println(minimum);

Here, we are having an array, whose size varies with n. Total space requirement = 2 + N, where 2 is for the variables n and minimum and N is for the array. So, the space complexity of this algorithm is O(N).

I hope this was what you were looking for.


问:
Testing something that requires dynamic pageloads using Selenium IDE
I'm trying to create a test for a quiz. The quiz works like this:

Click and wait on the quiz link.

First page has a question and radio buttons. User clicks on a radio button, then clicks and waits on the submit button.

Second page is another question with radio buttons. User clicks on a radio button, then clicks and waits on the submit button, etc.

After N pages, at the results page, I want to verify that some text exists.

The purposes of this test are: (1) that the user can take a quiz all the way to the end, (2) quiz questions are submitting properly (no exceptions between submissions), (3) the user sees the expected results.

I know that I can do this easily with Selenium RC, but I need this is in Selenium IDE so that non-technical people can just press a button when they are doing a smoke test. (I know, QA is supposed to do this, but I don't make the rules.)

My question is: how should I best test a quiz with a dynamic number of questions (quizzes featured on our quiz page vary from day to day and some get disabled or deleted from the system)?

I'm looking to do this in JavaScript (putting the script in runScript), but I can't figure out how to do the equivalent of "clickAndWait" within the script, so I can't do a submit.

I'm new to JavaScript, btw.

答: blog post describing about the same thing...</p>

ContentLicense: CC BY-SA 2.5


问:
Drag/Drop feature in Android studio not working
I'm new to android programming The drag/ and drop feature in android studio is not working. I can't drag anything to my phone. Right now my fragment is  google map view  and i want to add a search bar to the view. It just doesn't drag. When I try to add it in text it says element item not allowed here?

This is my activity_maps.xml file

```<code> <fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/map" tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment">
<item android:id="@+id/search"
    android:title="@string/search_title"
    android:icon="@drawable/ic_search"
    android:showAsAction="collapseActionView|ifRoom"
    android:actionViewClass="android.widget.SearchView" />
</fragment>
</code>```

答:
Drag 'n' Drop may not work properly, when you have a LinearLayout, in that condition, the items you drag will try to settle in a specific manner(Horizontal or Vertical), instead try to change your main layout to Relative Layout

Linear Layout --> Relative Layout

Body:
I'm new to android programming The drag/ and drop feature in android studio is not working. I can't drag anything to my phone. Right now my fragment is  google map view  and i want to add a search bar to the view. It just doesn't drag. When I try to add it in text it says element item not allowed here?

This is my activity_maps.xml file

 <fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/map" tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment">
<item android:id="@+id/search"
    android:title="@string/search_title"
    android:icon="@drawable/ic_search"
    android:showAsAction="collapseActionView|ifRoom"
    android:actionViewClass="android.widget.SearchView" />
</fragment>


问:
How to load chat history on top of recycler view android
Hi I am developing a chat application like whatsapp. I have to load the chat history from the api when user scrolls down like in whatsapp. I get the data and set it to the adapter. But the history is loading at the bottom of recycler view. I need to add it on top for every scroll. This is my code. Please help me. Thanks in advance.</p>

```<code>                              if (Status.equals("1")) {
                                historyList = resp.getHistory();
                                Log.i("history size",String.valueOf(resp.getHistory().size()));
                                String historysize = String.valueOf(resp.getHistory().size());
                                Message message = new Message();
                                for (int i = 0; i < resp.getHistory().size(); i++) {
                                    String fromusertoken = String.valueOf(resp.getHistory().get(i).getFromUserToken());
                                    String txtmsg = resp.getHistory().get(i).getMessage();
                                    String username = String.valueOf(resp.getHistory().get(i).getFromUserName());

                                    if (fromusertoken.equals(user_token)) {
                                        Message messages = new Message();
                                        messages.setUser_token(fromusertoken);
                                        messages.setUsername(username);
                                        messages.setIsMine(true);
                                        messages.setMessage(txtmsg);
                                        messageAdapter.add(messages);

                                    }
                                    else {
                                        Message messages = new Message();
                                        messages.setUser_token(fromusertoken);
                                        messages.setUsername(username);
                                        messages.setIsMine(false);
                                        messages.setMessage(txtmsg);
                                        messageAdapter.add(messages);
                                    }
                                }

                                messageAdapter.notifyDataSetChanged();
                                onItemsLoadComplete();

                                Toast.makeText(Single_chat.this, msg, Toast.LENGTH_SHORT).show();
                            }

                        } else {
                            Toast.makeText(Single_chat.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    Toast.makeText(Single_chat.this, "No Response", Toast.LENGTH_SHORT).show();
                }

            }
</code>```

答:
```<code>chatHistoyList.add(adapter.getCurrentChatList());

adapter.setData(chatHistoryList);

adapter.notifyDataSetChanged();

//This method has to be in adapter
public List<Chat> getCurrentChatList() {
         return currentChatList;
}
</code>```

Body:
Hi I am developing a chat application like whatsapp. I have to load the chat history from the api when user scrolls down like in whatsapp. I get the data and set it to the adapter. But the history is loading at the bottom of recycler view. I need to add it on top for every scroll. This is my code. Please help me. Thanks in advance.

                              if (Status.equals("1")) {
                                historyList = resp.getHistory();
                                Log.i("history size",String.valueOf(resp.getHistory().size()));
                                String historysize = String.valueOf(resp.getHistory().size());
                                Message message = new Message();
                                for (int i = 0; i < resp.getHistory().size(); i++) {
                                    String fromusertoken = String.valueOf(resp.getHistory().get(i).getFromUserToken());
                                    String txtmsg = resp.getHistory().get(i).getMessage();
                                    String username = String.valueOf(resp.getHistory().get(i).getFromUserName());

                                    if (fromusertoken.equals(user_token)) {
                                        Message messages = new Message();
                                        messages.setUser_token(fromusertoken);
                                        messages.setUsername(username);
                                        messages.setIsMine(true);
                                        messages.setMessage(txtmsg);
                                        messageAdapter.add(messages);

                                    }
                                    else {
                                        Message messages = new Message();
                                        messages.setUser_token(fromusertoken);
                                        messages.setUsername(username);
                                        messages.setIsMine(false);
                                        messages.setMessage(txtmsg);
                                        messageAdapter.add(messages);
                                    }
                                }

                                messageAdapter.notifyDataSetChanged();
                                onItemsLoadComplete();

                                Toast.makeText(Single_chat.this, msg, Toast.LENGTH_SHORT).show();
                            }

                        } else {
                            Toast.makeText(Single_chat.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    Toast.makeText(Single_chat.this, "No Response", Toast.LENGTH_SHORT).show();
                }

            }


问:
what are pros and cons to define constant local variables as static ( c++)?
```<code>void Animation::playAnimation() const
{
    static const int index = 0;
    const std::string& animationFileName = m_animationContainer.getAnimationName(index);
    static const int zOrder = -1;
    static bool isLooping = false;

    AnimationBank::play(animationFileName,
                        zOrder,
                        isLooping);
}
</code>```

what are pros and cons to define constant local variables as static?
what is an overhead of defining index, zOrder, isLooping as static. Is there any benefit to do this?

答:
In general case if you declare a static variable inside of a function then it will be initialized during first use. In order to achieve this behavior another global static variable of boolean type will be created by the compiler. It will be initially set to false and then set to true after related static variable is initialized.

In your case there is no point to declare any variables as static.

Body:
void Animation::playAnimation() const
{
    static const int index = 0;
    const std::string& animationFileName = m_animationContainer.getAnimationName(index);
    static const int zOrder = -1;
    static bool isLooping = false;

    AnimationBank::play(animationFileName,
                        zOrder,
                        isLooping);
}

what are pros and cons to define constant local variables as static?
what is an overhead of defining index, zOrder, isLooping as static. Is there any benefit to do this?


问:
Extension methods for multiple types
I have an object of type Product and type Variant.  Variant and Product have the same structure, but are two different types, and so I can't make just one method to encompass both. Is it possible to make an extension method that would accept both of these types?

答:
You can not change the Product and Variant classes, but you can subclass them and apply a interface to the subclass. This interface can be used for the extension method:

```<code>using System;

public class Program
{
    public static void Main()
    {
        var p = new MyProduct();
        p.Name = "test";
        Console.WriteLine(p.GetName());
    }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Foo { get; set; }
}
public class Variant
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Bar { get; set; }
}

public class MyProduct: Product, IType {
}

public class MyVariant: Variant, IType {
}

public static class Extensions {
    public static string GetName(this IType type){
        return type.Name;
    }
}

public interface IType {
    string Name {get; set; }
}
</code>```

See: https://dotnetfiddle.net/u1JJmJ

Title: Extension methods for multiple types

Body:
You can not change the Product and Variant classes, but you can subclass them and apply a interface to the subclass. This interface can be used for the extension method:

using System;

public class Program
{
    public static void Main()
    {
        var p = new MyProduct();
        p.Name = "test";
        Console.WriteLine(p.GetName());
    }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Foo { get; set; }
}
public class Variant
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Bar { get; set; }
}

public class MyProduct: Product, IType {
}

public class MyVariant: Variant, IType {
}

public static class Extensions {
    public static string GetName(this IType type){
        return type.Name;
    }
}

public interface IType {
    string Name {get; set; }
}

See: https://dotnetfiddle.net/u1JJmJ


问:
PHP sprintf('%d', floatval('16.40') * 100) outputs 1639?
The sprinf behaviour below is very strange.

```<code>// The code below outputs 1639
$value = floatval('16.40') * 100;
echo sprintf('%d', $value);
</code>```

But when I use %f it outputs 1640.000000

I dumped the $value, it's definitely float(1640).

Does anyone knows what happened when I use %d? Is this a PHP bug? I've tested in PHP7.

答:
The variable $value contains a floating point number. Floating point numbers are not exact, they are approximations.1

The value of $value is not 1640 but 1639.99999999999977262632. When you use %f to print it, printf() rounds it to 6 decimal places and the rounded value is 1640.000000.

When it is printed with %d, printf() uses only the integer part of $value and it is 1639.

Use round() to get the correct integer value:

```<code>printf('%d', round($value, 0));
</code>```

Or, even better, use number_format() to get the value as string:

```<code>echo(number_format($value, 0, '', ''));
</code>```

Both print 1640.

1 Think of 1/3. It is approximatively 0.3333333333 but one cannot represent it exactly because it has an infinite number of 3 after the decimal dot. In mathematics, 3 * 1/3 = 1 but in real life (and in computers), 3 * 0.333333333 is never 1, no matter how many 3 we put after the decimal dot. The computer programs usually round the value to some number of decimal places and it ends up being displayed as 1 but this doesn't happen always.

When it doesn't happen, another question similar to this one pops up on StackOverflow.

Body:
The sprinf behaviour below is very strange.

// The code below outputs 1639
$value = floatval('16.40') * 100;
echo sprintf('%d', $value);

But when I use %f it outputs 1640.000000

I dumped the $value, it's definitely float(1640).

Does anyone knows what happened when I use %d? Is this a PHP bug? I've tested in PHP7.

Body:
The variable $value contains a floating point number. Floating point numbers are not exact, they are approximations.1

The value of $value is not 1640 but 1639.99999999999977262632. When you use %f to print it, printf() rounds it to 6 decimal places and the rounded value is 1640.000000.

When it is printed with %d, printf() uses only the integer part of $value and it is 1639.

Use round() to get the correct integer value:

printf('%d', round($value, 0));

Or, even better, use number_format() to get the value as string:

echo(number_format($value, 0, '', ''));

Both print 1640.

1 Think of 1/3. It is approximatively 0.3333333333 but one cannot represent it exactly because it has an infinite number of 3 after the decimal dot. In mathematics, 3 * 1/3 = 1 but in real life (and in computers), 3 * 0.333333333 is never 1, no matter how many 3 we put after the decimal dot. The computer programs usually round the value to some number of decimal places and it ends up being displayed as 1 but this doesn't happen always.

When it doesn't happen, another question similar to this one pops up on StackOverflow.


问:
Parameters.ParamByname Doesn't accept string values Delphi
I have the following code

```<code>procedure TFrmMain.ComboBox1KeyPress(Sender: TObject; var Key: Char);
begin

 if Key = #13 then
 begin
  ADOQuery1.close;
  ADOQuery1.sql.Text := 'INSERT INTO palletweighttemp(TickCode,SchedID,BatchNo)values';
  ADOQuery1.SQL.Add(' (:field1,(select SchedID from TicketBatch where TickCode =:field1),');
  ADOQuery1.SQL.Add('(select BatchNo from TicketBatch where TickCode =:field1))');
  ADOQuery1.Parameters.ParamByName('field1').DataType := ftString;
  ADOQuery1.Parameters.ParamByName('field1').Value := ComboBox1.Text;
  ADOQuery1.ExecSQL;
       PopulateDBGrid;
        ComboBox1.SetFocus;
       end;

 end;
</code>```

I Populate my comboBox using

```<code>procedure TFrmMain.PopulateBoxes();
begin
ComboBox1.SetFocus;

ComboBox1.Perform(WM_SYSKEYDOWN, VK_TAB, 0);

ComboBox1.clear;
ADOQuery1.sql.add
('select * from TicketBatch where isProcesed = 0 and TickCode is not null');
ADOQuery1.open;
ComboBox1.Text := '';
while not ADOQuery1.Eof do
begin
ComboBox1.Items.add(ADOQuery1.FieldByName('TickCode').AsString);
ADOQuery1.Next;
end;
 ADOQuery1.close;

 end;
</code>```

If i press enter to run my Combobox1KeyPress procedure an error pops up that

I'm assuming it's because its a needs a integer and currently is a string
Please assist

答:
The  property "DataType" of ParamByName is not to be set by you. As the documentation from Embarcardero clearly states, this is set automatically when a value is assigned. Setting it yourself will only lead to strange errors.

You can use it to check for type and do your own error-handling etc. like:

```<code>IF  (ADOQuery1.Parameters.ParamByName('field1').DataType = ftInteger)
AND (not TRYSTRTOINT(ComboBox1.Text),myInt) then
  ShowMessage('invalid ticket code!');
</code>```

As the other answeres stated, look into your table definitions, you will have a type mismatch there.

Body:
I have the following code

procedure TFrmMain.ComboBox1KeyPress(Sender: TObject; var Key: Char);
begin

 if Key = #13 then
 begin
  ADOQuery1.close;
  ADOQuery1.sql.Text := 'INSERT INTO palletweighttemp(TickCode,SchedID,BatchNo)values';
  ADOQuery1.SQL.Add(' (:field1,(select SchedID from TicketBatch where TickCode =:field1),');
  ADOQuery1.SQL.Add('(select BatchNo from TicketBatch where TickCode =:field1))');
  ADOQuery1.Parameters.ParamByName('field1').DataType := ftString;
  ADOQuery1.Parameters.ParamByName('field1').Value := ComboBox1.Text;
  ADOQuery1.ExecSQL;
       PopulateDBGrid;
        ComboBox1.SetFocus;
       end;

 end;

I Populate my comboBox using

procedure TFrmMain.PopulateBoxes();
begin
ComboBox1.SetFocus;

ComboBox1.Perform(WM_SYSKEYDOWN, VK_TAB, 0);

ComboBox1.clear;
ADOQuery1.sql.add
('select * from TicketBatch where isProcesed = 0 and TickCode is not null');
ADOQuery1.open;
ComboBox1.Text := '';
while not ADOQuery1.Eof do
begin
ComboBox1.Items.add(ADOQuery1.FieldByName('TickCode').AsString);
ADOQuery1.Next;
end;
 ADOQuery1.close;

 end;

If i press enter to run my Combobox1KeyPress procedure an error pops up that

I'm assuming it's because its a needs a integer and currently is a string
Please assist

Body:
The  property "DataType" of ParamByName is not to be set by you. As the documentation from Embarcardero clearly states, this is set automatically when a value is assigned. Setting it yourself will only lead to strange errors.

You can use it to check for type and do your own error-handling etc. like:

IF  (ADOQuery1.Parameters.ParamByName('field1').DataType = ftInteger)
AND (not TRYSTRTOINT(ComboBox1.Text),myInt) then
  ShowMessage('invalid ticket code!');

As the other answeres stated, look into your table definitions, you will have a type mismatch there.


问:
MySQL function returning multiple rows, need 1 row
```<code>SELECT count(*)
from media
where STR_TO_DATE(CONCAT('2014', '-', `datum`), '%Y-%e-%b') = givendate AND medium_cat like p_media AND `positief_negatief` like p_sentiment
into results;
</code>```

This is the main code of the function, it checks if there is a media record in media that has the same date as the given date.
It returns 61 rows with 1 as result (there are 61 rows in media, and the result should be 1), so it needs to be 1 row with 1 as result.

The main problem is that this function runs 10 times on a table with 100000 rows, so it takes about 120 seconds to complete.
Any help is appreciated.

答:
```<code>SELECT count(*) into results
from media
where STR_TO_DATE(CONCAT('2014', '-', `datum`), '%Y-%e-%b') = givendate AND medium_cat like p_media AND `positief_negatief` like p_sentiment
;
</code>```

Just try above code.
Hope this will help.

Body:
SELECT count(*)
from media
where STR_TO_DATE(CONCAT('2014', '-', `datum`), '%Y-%e-%b') = givendate AND medium_cat like p_media AND `positief_negatief` like p_sentiment
into results;

This is the main code of the function, it checks if there is a media record in media that has the same date as the given date.
It returns 61 rows with 1 as result (there are 61 rows in media, and the result should be 1), so it needs to be 1 row with 1 as result.

The main problem is that this function runs 10 times on a table with 100000 rows, so it takes about 120 seconds to complete.
Any help is appreciated.

Body:
SELECT count(*) into results
from media
where STR_TO_DATE(CONCAT('2014', '-', `datum`), '%Y-%e-%b') = givendate AND medium_cat like p_media AND `positief_negatief` like p_sentiment
;

Just try above code.
Hope this will help.


问:
Replacing specific characters in python string
I have a string which is

string = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"

I want to replace specific set of ' to %. It has to look like

```<code>string = "create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})"
</code>```

I'm trying to use replace function. But failed to get the exact result.

答:
```<code>string = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"

w = string.find('{')+ 1
x = w + 10;t = w + 22;y = w + 31;z = w + 43;q = w + 48
w1=string[w].replace("'",'%')
x1=string[x].replace("'",'%')
t1=string[t].replace("'",'%')
y1=string[y].replace("'",'%')
z1=string[z].replace("'",'%')
q1=string[q].replace("'",'%')

print(string[0:23]+w1+string[24:33]+x1+string[34:45]+t1+string[46:54]+y1+string[55:66]+z1+string[67:71]+q1+string[72:])
</code>```

hope that is what you wanted.

Body:
I have a string which is

string = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"

I want to replace specific set of ' to %. It has to look like

string = "create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})"

I'm trying to use replace function. But failed to get the exact result.

Body:
string = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"

w = string.find('{')+ 1
x = w + 10;t = w + 22;y = w + 31;z = w + 43;q = w + 48
w1=string[w].replace("'",'%')
x1=string[x].replace("'",'%')
t1=string[t].replace("'",'%')
y1=string[y].replace("'",'%')
z1=string[z].replace("'",'%')
q1=string[q].replace("'",'%')

print(string[0:23]+w1+string[24:33]+x1+string[34:45]+t1+string[46:54]+y1+string[55:66]+z1+string[67:71]+q1+string[72:])

hope that is what you wanted.


问:
how to force scrapy exit when there is an exception
I wrote a crawler with Scrapy.

There is a function in the pipeline where I write my data to a database. I use the logging module to log runtime logs.

I found that when my string have Chinese logging.error() will throw an exception. But the crawler keeps running!

I know this is a minor error but if there is a critical exception I will miss it if crawler keeps running.

My question is: Is there a setting that I can force Scrapy stop when there is an exception?

答:
You can use CLOSESPIDER_ERRORCOUNT

An integer which specifies the maximum number of errors to receive
  before closing the spider. If the spider generates more than that
  number of errors, it will be closed with the reason
  closespider_errorcount. If zero (or non set), spiders won’t be closed
  by number of errors.

By default it is set to 0
CLOSESPIDER_ERRORCOUNT = 0
you can change it to 1 if you want to exit when you have the first error.

UPDATE

Read the answers of this question,  you can also use:

```<code>crawler.engine.close_spider(self, 'log message')
</code>```

for more information read :

Close spider extension

Body:
You can use CLOSESPIDER_ERRORCOUNT

An integer which specifies the maximum number of errors to receive
  before closing the spider. If the spider generates more than that
  number of errors, it will be closed with the reason
  closespider_errorcount. If zero (or non set), spiders won’t be closed
  by number of errors.

By default it is set to 0
CLOSESPIDER_ERRORCOUNT = 0
you can change it to 1 if you want to exit when you have the first error.

UPDATE

Read the answers of this question,  you can also use:

crawler.engine.close_spider(self, 'log message')

for more information read :

Close spider extension


问:
javascript split
I can use JavaScript's split to put a comma-separated list of items in an array:

```<code>var mystring = "a,b,c,d,e";
var myarray = mystring.split(",");
</code>```

What I have in mind is a little more complicated. I have this comma separated string:

```<code>"mystring_109_all,mystring_110_mine,mystring_125_all"
</code>```

how do i split this string in to an array

答:
```<code><!DOCTYPE html>
<html>
<body>

<p>Question is var str = "a,b,c,d,e,f,g"; </p>

<button onclick="myFunction()">Split Button</button>

<p id="demo"></p>
<p id="demo1"></p>

<script>
var text = "";
function myFunction() {
    var str = "a,b,c,d,e,f";
    var arr = str.split(",");

    for(var i = 0; i<arr.length; ++i){
        text += arr[i] +" ";
        document.getElementById("demo").innerHTML = text;
    }
    document.getElementById("demo1").innerHTML = arr[0];
}

</script>

</body>
</html>

**Answer**
a b c d e f g

Arr[0]=a
</code>```

Title: javascript split

Body:
I can use JavaScript's split to put a comma-separated list of items in an array:

var mystring = "a,b,c,d,e";
var myarray = mystring.split(",");

What I have in mind is a little more complicated. I have this comma separated string:

"mystring_109_all,mystring_110_mine,mystring_125_all"

how do i split this string in to an array


问:
Class with two constructors taking different objects as parents
I want to create a new class, which has to be able to take two different types of objects (with nearly the same functions and variables). I am trying to use two constructors for this. Since both possible argument classes have nearly the same variables in them, I want to refer to them with the same variable named parent.

What I tried:

class Segment{
  float phi;
  float theta;
  float len;
  Base parent;
  Segment parent;

  public Segment(Base parent, float len, float phi, float theta) {
    this.len = len;
    this.phi = phi;
    this.theta = theta;

    this.parent = parent;
  }

  public Segment(Segment parent, float len, float phi, float theta) {
    this.len = len;
    this.phi = phi;
    this.theta = theta;

    this.parent = parent;
  }

  // ... functions calling parent.variableName
}
```

This is not possible because parent is a duplicate, what would be a way to solve this?

Edit

The only thing Segment and Base have in common are some variables telling the start end end points, to connect new Segments to.
Other than that the Base is standing still, and the Segment's are moving

答:
You have some ways to do:

Declare parent is Object: Object parent; then cast it if needed. It's very simple but isn't good.

Use inheritance by define the base class / interface like 2 answers below. I prefer interface if they have same properties and methods. Otherwise, use class.

Use generic like Segment or Segment

Body:
I want to create a new class, which has to be able to take two different types of objects (with nearly the same functions and variables). I am trying to use two constructors for this. Since both possible argument classes have nearly the same variables in them, I want to refer to them with the same variable named parent.

What I tried:

class Segment{
  float phi;
  float theta;
  float len;
  Base parent;
  Segment parent;

  public Segment(Base parent, float len, float phi, float theta) {
    this.len = len;
    this.phi = phi;
    this.theta = theta;

    this.parent = parent;
  }

  public Segment(Segment parent, float len, float phi, float theta) {
    this.len = len;
    this.phi = phi;
    this.theta = theta;

    this.parent = parent;
  }

  // ... functions calling parent.variableName
}

This is not possible because parent is a duplicate, what would be a way to solve this?

Edit

The only thing Segment and Base have in common are some variables telling the start end end points, to connect new Segments to.
Other than that the Base is standing still, and the Segment's are moving


问:
Python code generation with pyside-uic
How can I generate python code from a QtDesigner file ?
I found pyside-uic but I can't find an example for the syntax.
I run win7 and pythonxy with spyder.</p>

答:
Read the documentation. In this particular case, http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#pyuic4:</p>

```<code>The pyuic4 utility is a command line interface to the uic module. The command has the following syntax:

pyuic4 [options] .ui-file

The full set of command line options is:
-h, --help  A help message is written to stdout.
--version   The version number is written to stdout.
-i N, --indent=N
    The Python code is generated using an indentation of N spaces. If N is 0 then a tab is used. The default is 4.
-o FILE, --output=FILE
    The Python code generated is written to the file FILE.
-p, --preview   The GUI is created dynamically and displayed. No Python code is generated.
-w, --pyqt3-wrapper
    The generated Python code includes a small wrapper that allows the GUI to be used in the same way as it is used in PyQt v3.
-x, --execute   The generated Python code includes a small amount of additional code that creates and displays the GUI when it is executes as a standalone application.
--from-imports  Resource modules are imported using from . import rather than a simple import.
</code>```

Title: Python code generation with pyside-uic

Body:
Read the documentation. In this particular case, http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#pyuic4:

The pyuic4 utility is a command line interface to the uic module. The command has the following syntax:

pyuic4 [options] .ui-file

The full set of command line options is:
-h, --help  A help message is written to stdout.
--version   The version number is written to stdout.
-i N, --indent=N
    The Python code is generated using an indentation of N spaces. If N is 0 then a tab is used. The default is 4.
-o FILE, --output=FILE
    The Python code generated is written to the file FILE.
-p, --preview   The GUI is created dynamically and displayed. No Python code is generated.
-w, --pyqt3-wrapper
    The generated Python code includes a small wrapper that allows the GUI to be used in the same way as it is used in PyQt v3.
-x, --execute   The generated Python code includes a small amount of additional code that creates and displays the GUI when it is executes as a standalone application.
--from-imports  Resource modules are imported using from . import rather than a simple import.


问:
access django model fields label and help_text
I have something like this:

```<code>class ContactData(models.Model):
    name  = models.CharField(max_length=300, verbose_name=u"Name", help_text=u"Please enter your name...",null=True, blank=False)
    phone = models.CharField(max_length=300, verbose_name=u"Phone number", null=True, blank=False)
</code>```

I would like to show a field's label and help_text in template (that is - just access it from view).
Can this be done?

答:
I know this is old, but it deserves a full answer that can be used in templates.

If you need to use it in a template, the preferred method is to add model methods that get these values, such as:

```<code>from django.db import models
from six import text_type

class ContactData(models.Model):
    name  = models.CharField(max_length=300, verbose_name=u"Name", help_text=u"Please enter your name...",null=True, blank=False)
    phone = models.CharField(max_length=300, verbose_name=u"Phone number", null=True, blank=False)

    def __get_label(self, field):
        return text_type(self._meta.get_field(field).verbose_name)

    def __get_help_text(self, field)
        return text_type(self._meta.get_field(field).help_text)

    @property
    def name_label(self):
        return self.__get_label('name')

    @property
    def name_help_text(self):
        return self.__get_help_text('name')

    @property
    def phone_label(self):
        return self.__get_label('phone')

    @property
    def phone_help_text(self):
        return self.__get_help_text('phone')
</code>```

Then, let us say instance is your object in a template, this is your label

```<code><label for="id_phone">{{ instance.phone_label }}</label>
<div id="id_phone">{{ instance.phone }}</div>
</code>```

Alternatively, you could create a template tag to do this, but the model method is clearer and keeps the model self contained.

Body:
I have something like this:

class ContactData(models.Model):
    name  = models.CharField(max_length=300, verbose_name=u"Name", help_text=u"Please enter your name...",null=True, blank=False)
    phone = models.CharField(max_length=300, verbose_name=u"Phone number", null=True, blank=False)

I would like to show a field's label and help_text in template (that is - just access it from view).
Can this be done?

Body:
I know this is old, but it deserves a full answer that can be used in templates.

If you need to use it in a template, the preferred method is to add model methods that get these values, such as:

from django.db import models
from six import text_type

class ContactData(models.Model):
    name  = models.CharField(max_length=300, verbose_name=u"Name", help_text=u"Please enter your name...",null=True, blank=False)
    phone = models.CharField(max_length=300, verbose_name=u"Phone number", null=True, blank=False)

    def __get_label(self, field):
        return text_type(self._meta.get_field(field).verbose_name)

    def __get_help_text(self, field)
        return text_type(self._meta.get_field(field).help_text)

    @property
    def name_label(self):
        return self.__get_label('name')

    @property
    def name_help_text(self):
        return self.__get_help_text('name')

    @property
    def phone_label(self):
        return self.__get_label('phone')

    @property
    def phone_help_text(self):
        return self.__get_help_text('phone')

Then, let us say instance is your object in a template, this is your label

<label for="id_phone">{{ instance.phone_label }}</label>
<div id="id_phone">{{ instance.phone }}</div>

Alternatively, you could create a template tag to do this, but the model method is clearer and keeps the model self contained.


问:
Google Chrome extenstion - local storage set and get
I'm developing an extension for Google Chrome, and have run into some trouble.I created an options.html page and added it to the manifest.json file.The page shows properly.

Further I need to save the filled data in local storage there I am not able to proceed ahead

Can you help me to get the code to execute local storage by set and get

enter image description here[entryt form2

Manifest

```<code>{
   "background": {
      "scripts": [ "background.js" ]
   },
   "browser_action": {
      "default_icon": "t19.png"
   },
   "description": "Fill out web forms instantly with junk or custom data",
   "icons": {
      "128": "t128.png",
      "48": "t48.png"
   },

   "manifest_version": 2,
   "name": "Tatkal on budget style",
   "options_page": "entry_form.html",
   "permissions": [ "storage",  "tabs", "http://*/*", "https://*/*" ],
   "version": "1.0"
}`enter code here`

Background

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.create({'url': chrome.extension.getURL('entry_form.html')}, function(tab) {
    // Tab opened.
  });
});
</code>```

Looking forward to have the code for local storage

答:
Chrome extension doesnt support localstorage. You will have to use chrome.storage.sync (syncs data for the user across devices) or chrome.storage.local (local to the current chrome instance).
lets say u want to save a field called name with value as John.
Localstorage:

```<code>localstorage.setItem('name', 'Jogn');
</code>```

Chrome extension

```<code>var obj = {
    name:'Jogn'
}
chrome.storage.sync.set(obj, function () {
    //success callback
});
</code>```

to get the stored name use:

```<code>var keys = ['name'];
chrome.storage.sync.get(key, function (result) {
    // the received result  field will be an object
    console.log(result.name);
});
</code>```

Body:
I'm developing an extension for Google Chrome, and have run into some trouble.I created an options.html page and added it to the manifest.json file.The page shows properly.

Further I need to save the filled data in local storage there I am not able to proceed ahead

Can you help me to get the code to execute local storage by set and get

enter image description here[entryt form2

Manifest

{
   "background": {
      "scripts": [ "background.js" ]
   },
   "browser_action": {
      "default_icon": "t19.png"
   },
   "description": "Fill out web forms instantly with junk or custom data",
   "icons": {
      "128": "t128.png",
      "48": "t48.png"
   },

   "manifest_version": 2,
   "name": "Tatkal on budget style",
   "options_page": "entry_form.html",
   "permissions": [ "storage",  "tabs", "http://*/*", "https://*/*" ],
   "version": "1.0"
}`enter code here`

Background

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.create({'url': chrome.extension.getURL('entry_form.html')}, function(tab) {
    // Tab opened.
  });
});

Looking forward to have the code for local storage

Body:
Chrome extension doesnt support localstorage. You will have to use chrome.storage.sync (syncs data for the user across devices) or chrome.storage.local (local to the current chrome instance).
lets say u want to save a field called name with value as John.
Localstorage:

localstorage.setItem('name', 'Jogn');

Chrome extension

var obj = {
    name:'Jogn'
}
chrome.storage.sync.set(obj, function () {
    //success callback
});

to get the stored name use:

var keys = ['name'];
chrome.storage.sync.get(key, function (result) {
    // the received result  field will be an object
    console.log(result.name);
});


问:
MySQLBackup in c#
How to solve this error ? </p>

```<code>Error   1   Assembly 'MySqlBackup, Version=2.0.9.2, Culture=neutral,
PublicKeyToken=null' uses 'MySql.Data, Version=6.9.9.0, Culture=neutral,
PublicKeyToken=c5687fc88969c44d' which has a higher version than referenced
assembly 'MySql.Data, Version=6.3.6.0, Culture=neutral,
PublicKeyToken=c5687fc88969c44d'    c:\Users\Mohammed Abdullah\Desktop\MySqlBackup.dll  mobile_shop
</code>```

答:
Add reference to

MySql.Data

in you cs project

Title: MySQLBackup in c#

Body:
How to solve this error ?

Error   1   Assembly 'MySqlBackup, Version=2.0.9.2, Culture=neutral,
PublicKeyToken=null' uses 'MySql.Data, Version=6.9.9.0, Culture=neutral,
PublicKeyToken=c5687fc88969c44d' which has a higher version than referenced
assembly 'MySql.Data, Version=6.3.6.0, Culture=neutral,
PublicKeyToken=c5687fc88969c44d'    c:\Users\Mohammed Abdullah\Desktop\MySqlBackup.dll  mobile_shop


问:
AJAX returning 404 not found
I am new to MVC and have been trying to generate a table from a list of objects but the ajax call keeps failing . Am i doing something wrong ?
Below is my controller code

```<code>     @RequestMapping(value="/PopulateTable",method = RequestMethod.GET,headers="Accept=*/*")
     public @ResponseBody ArrayList<ReportMetrics> doGet(HttpServletRequest
      request, HttpServletResponse response) throws ServletException,
      IOException {
      ArrayList<ReportMetrics> metrics=new ArrayList<ReportMetrics>();
     metrics=responseservice.getReportMetrics();;
     return metrics;
     }
</code>```

My Jquery code  is

```<code>        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function(){
        $("#showTable").click(function(){
               $("div").css("border", "3px solid blue");
        $("div").css("border", "3px solid gray");
        $.ajax({
        type: "GET",
        url: "/PopulateTable",
        success: function(data,status)
       {
        createTableByForLoop(data);
        createTableByJqueryEach(data);

       },
       async:   true,
       dataType: 'json'
      });
      });
      });
</code>```

have the below dependency already

```<code>        <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
        </dependency>
</code>```

error screenshot

Also my URI mapping on web.xml

```<code>         <servlet-mapping>
         <servlet-name>SplunkPOC</servlet-name>
         <url-pattern>*.htm</url-pattern>
         <url-pattern>*.*</url-pattern>
         </servlet-mapping>
</code>```

答:
try to change url like:

url: "PopulateTable"

refer this link

Title: AJAX returning 404 not found

Body:
I am new to MVC and have been trying to generate a table from a list of objects but the ajax call keeps failing . Am i doing something wrong ?
Below is my controller code

     @RequestMapping(value="/PopulateTable",method = RequestMethod.GET,headers="Accept=*/*")
     public @ResponseBody ArrayList<ReportMetrics> doGet(HttpServletRequest
      request, HttpServletResponse response) throws ServletException,
      IOException {
      ArrayList<ReportMetrics> metrics=new ArrayList<ReportMetrics>();
     metrics=responseservice.getReportMetrics();;
     return metrics;
     }

My Jquery code  is